Best JavaScript code snippet using mountebank
wireguard.js
Source:wireguard.js
1export function generateDeviceConfig(2 { ip, keys, routed, additionalDNSServers, MTU, port },3 server4) {5 const subnetv4 =6 server.subnet.v4 && server.subnet.v4[server.subnet.v4.length - 1] === "."7 ? `${server.subnet.v4}`.slice(0, -1)8 : server.subnet.v4;9 const subnetv6 =10 server.subnet.v6 &&11 server.subnet.v6[server.subnet.v6.length - 1] === ":" &&12 server.subnet.v6[server.subnet.v6.length - 2] === ":"13 ? `${server.subnet.v6}`.slice(0, -1)14 : server.subnet.v6;15 let allowedIps = "";16 if (routed) {17 allowedIps = "0.0.0.0/0,::/0";18 } else {19 if (ip.v4) {20 allowedIps = `${subnetv4}.0/24`;21 }22 if (ip.v6) {23 if (ip.v4) {24 allowedIps = `${allowedIps},`;25 }26 allowedIps = `${allowedIps}${subnetv6}:/64`;27 }28 }29 if (30 !server.keys ||31 ((!server.ip || (!server.ip.v4 && !server.ip.v6)) && !server.hostname) ||32 !server.port ||33 (!subnetv4 && !subnetv6)34 ) {35 throw new Error("No Server");36 }37 let endpoint;38 if (server.hostname) {39 endpoint = `${server.hostname}:${server.port}`;40 } else {41 if (server.ip.v6 || (server.ip.v6 && server.ip.v4)) {42 endpoint = `[${server.ip.v6}]:${server.port}`;43 } else {44 endpoint = `${server.ip.v4}:${server.port}`;45 }46 }47 if (ip.v4 && !ip.v6) {48 return (49 `[Interface]\n` +50 `Address = ${subnetv4}.${ip.v4}\n` +51 `PrivateKey = ${keys.private}\n` +52 `DNS = ${subnetv4}.1${53 additionalDNSServers ? `,${additionalDNSServers.join(",")}` : ``54 }\n` +55 `${port ? `ListenPort = ${port}\n` : ``}` +56 `${MTU ? `MTU = ${MTU}\n` : ``}` +57 `58[Peer]59Endpoint = ${endpoint}60AllowedIPs = ${allowedIps}61PublicKey = ${server.keys.public}62## keep connection alive behind NAT63PersistentKeepalive = 25`64 );65 }66 if (!ip.v4 && ip.v6) {67 return (68 `[Interface]\n` +69 `Address = ${subnetv6}:${ip.v6}\n` +70 `PrivateKey = ${keys.private}\n` +71 `DNS = ${subnetv6}:0001${72 additionalDNSServers ? `,${additionalDNSServers.join(",")}` : ``73 }\n` +74 `${port ? `ListenPort = ${port}\n` : ``}` +75 `${MTU ? `MTU = ${MTU}\n` : ``}` +76 `77[Peer]78Endpoint = ${endpoint}79AllowedIPs = ${allowedIps}80PublicKey = ${server.keys.public}81## keep connection alive behind NAT82PersistentKeepalive = 25`83 );84 }85 if (ip.v4 && ip.v6) {86 return (87 `[Interface]\n` +88 `Address = ${subnetv4}.${ip.v4},${subnetv6}:${ip.v6}\n` +89 `PrivateKey = ${keys.private}\n` +90 `DNS = ${subnetv4}.1${91 additionalDNSServers ? `,${additionalDNSServers.join(",")}` : ``92 }\n` +93 `${port ? `ListenPort = ${port}\n` : ``}` +94 `${MTU ? `MTU = ${MTU}\n` : ""}` +95 `96[Peer]97Endpoint = ${endpoint}98AllowedIPs = ${allowedIps}99PublicKey = ${server.keys.public}100## keep connection alive behind NAT101PersistentKeepalive = 25`102 );103 }104}105export function generateServerConfig({ port, keys, subnet }, devices) {106 let configs = "";107 let devicesNeedV4 = false;108 let devicesNeedV6 = false;109 const subnetv4 =110 subnet.v4 && subnet.v4[subnet.v4.length - 1] === "."111 ? `${subnet.v4}`.slice(0, -1)112 : subnet.v4;113 const subnetv6 =114 subnet.v6 &&115 subnet.v6[subnet.v6.length - 1] === ":" &&116 subnet.v6[subnet.v6.length - 2] === ":"117 ? `${subnet.v6}`.slice(0, -1)118 : subnet.v6;119 for (let device of devices) {120 if (!devicesNeedV6 && device.ip.v6) {121 devicesNeedV6 = true;122 }123 if (!devicesNeedV4 && device.ip.v4) {124 devicesNeedV4 = true;125 }126 if (device.ip.v4 && !device.ip.v6) {127 configs = `${configs}128[Peer]129# friendly_name = ${device.name}130AllowedIPs = ${subnetv4}.${device.ip.v4}/32131PublicKey = ${device.keys.public}`;132 }133 if (!device.ip.v4 && device.ip.v6) {134 configs = `${configs}135[Peer]136# friendly_name = ${device.name}137AllowedIPs = ${subnetv6}:${device.ip.v6}/128138PublicKey = ${device.keys.public}`;139 }140 if (device.ip.v4 && device.ip.v6) {141 configs = `${configs}142[Peer]143# friendly_name = ${device.name}144AllowedIPs = ${subnetv4}.${device.ip.v4}/32,${subnetv6}:${device.ip.v6}/128145PublicKey = ${device.keys.public}`;146 }147 }148 if (!devicesNeedV6 && !devicesNeedV4) {149 return `[Interface]150Address = ${subnetv4}.1151ListenPort = ${port}152PrivateKey = ${keys.private}`;153 }154 if (!devicesNeedV6 && devicesNeedV4) {155 return `[Interface]156Address = ${subnetv4}.1157ListenPort = ${port}158PrivateKey = ${keys.private}159${configs}`;160 }161 if (devicesNeedV6 && !devicesNeedV4) {162 return `[Interface]163Address = ${subnetv6}:0001164ListenPort = ${port}165PrivateKey = ${keys.private}166${configs}`;167 }168 if (devicesNeedV6 && devicesNeedV4) {169 return `[Interface]170Address = ${subnetv4}.1,${subnetv6}:0001171ListenPort = ${port}172PrivateKey = ${keys.private}173${configs}`;174 }...
parser.ts
Source:parser.ts
1export default (command: string, stdout: string) => {2 switch (command) {3 case 'systemctl status wg-quick@wg0.service':4 const [key, value] = stdout5 .split('\n')6 .find((line) => line.includes('ActiveState'))7 ?.split('ActiveState=') || ['ActiveState=', '']8 return { status: value === 'active' }9 case 'wg show':10 const peers = stdout11 .replaceAll(' ', '')12 .split('\n\n')13 .map((i) => i.split('\n'))14 .filter((i) => i[0].includes('peer'))15 .map((i) => {16 const [publicKey, psk, endpoint, allowedIps, lastTlsHandshake, transfer] = i17 return {18 publicKey: !!publicKey ? publicKey.split('peer:')[1] : null,19 endpoint: !!endpoint ? endpoint.split('endpoint:')[1] : null,20 allowedIps: !!allowedIps ? allowedIps.split('allowedips:')[1] : null,21 lastTlsHandshake: !!lastTlsHandshake22 ? String(lastTlsHandshake.split('latesthandshake:')[1]).replace('ago', '')23 : null,24 transfer: !!transfer25 ? transfer26 .split('transfer:')[1]27 .split(',')28 .reduce(29 (acc, curr, i) => ({30 ...acc,31 [i === 0 ? 'recieved' : 'sent']: String(curr)32 .replace('received', '')33 .replace('sent', ''),34 }),35 { recieved: null, sent: null }36 )37 : { recieved: null, sent: null },38 }39 })40 return { peers }41 case 'cat /etc/wireguard/wg0.conf':42 const [_, ...rest] = stdout.split('\n\n').map((i) => i.split('\n'))43 const entriers = rest.map(([client, _, publicKey, psk, allowedIps]) => ({44 client: !!client ? client.split('### Client ')[1] : null,45 publicKey: !!publicKey ? publicKey.split('PublicKey = ')[1] : null,46 allowedIps: !!allowedIps ? allowedIps.split('AllowedIPs = ')[1] : null,47 }))48 return { entriers }49 case 'top -b -n 1':50 const [topStr, tasksStr, cpuStr, memStr, swapStr] = stdout.split('\n').map((i) => i.replaceAll(' ', ''))51 const total = memStr.split(':')[1].split(',')[0].split('total')[0]52 const used = memStr.split(':')[1].split(',')[2].split('used')[0]53 return {54 status: [55 {56 name: 'RAM',57 message: [used, '/', total].join(''),58 percent: ((parseInt(used)) / parseInt(total)) * 10059 },60 {61 name: 'CPU',62 message: cpuStr.split(',')[1].split('sy')[0],63 precent: parseInt(cpuStr.split(',')[1].split('sy')[0]),64 }65 ]66 }67 case 'wg genkey':68 return {69 key: stdout.trim()70 };71 case 'wg pubkey':72 return {73 key: stdout.trim()74 };75 case 'wg genpsk':76 return {77 key: stdout.trim()78 };79 default:80 return {}81 }...
utils.ts
Source:utils.ts
1import http from 'http';2import url from 'url';3import { Address4 } from 'ip-address';4import { AllowedIPs, Message } from '../lib/interfaces';5const badRequest = (res: http.ServerResponse): void => {6 res.statusCode = 400;7 res.end('Bad request');8};9const checker = 10(allowedIps: AllowedIPs | false, req: http.IncomingMessage, res: http.ServerResponse):11Partial<Message> | false => {12 const toSave: Partial<Message> = {};13 if (allowedIps) {14 if (allowedIps[req.connection.remoteAddress!]) {15 toSave.ip = (new Address4(req.connection.remoteAddress!)).address;16 } else {17 res.statusCode = 403;18 res.end('Forbidden');19 return false;20 }21 } else {22 toSave.ip = (new Address4(req.connection.remoteAddress!)).address;23 }24 if (!(req.method === 'GET' || req.method === 'POST')){25 res.statusCode = 405;26 res.end('Method not allowed');27 return false;28 }29 if (req.method === 'POST') {30 const { "content-type": contentType } = req.headers;31 if (!contentType || contentType !== 'application/json') {32 badRequest(res);33 return false;34 }35 }36 const reqUrl = url.parse(req.url!, true);37 const { pathname } = reqUrl;38 if (pathname !== '/collect') {39 res.statusCode = 404;40 res.end('Method not found :(');41 return false;42 }43 // in case of a lot of bots, keep connection alive can lead to 44 // many open connections at once, so on each request we say that connection have to be closed;45 res.setHeader('Connection', 'close');46 return toSave;47};48const checkOptions = (allowedIps: AllowedIPs | false, req: http.IncomingMessage, res: http.ServerResponse): boolean => {49 if (req.method === 'OPTIONS') {50 if (allowedIps && !allowedIps[req.connection.remoteAddress!]) {51 res.statusCode = 403;52 res.end('Forbidden');53 return true;54 }55 res.setHeader('Accept', 'application/json');56 res.statusCode = 200;57 res.end('Ok');58 return true;59 }60 return false;61};62export {63 checker,64 checkOptions,65 badRequest,...
Using AI Code Generation
1var mb = require('mountebank');2var imposter = {3 {4 {5 is: {6 }7 }8 }9};10var options = {11};12mb.create(options).then(mbServer => {13 mbServer.createImposter(imposter);14});15var mb = require('mountebank');16var imposter = {17 {18 {19 is: {20 }21 }22 }23};24var options = {25};26mb.create(options).then(mbServer => {27 mbServer.createImposter(imposter);28});29var mb = require('mountebank');30var imposter = {31 {32 {33 is: {34 }35 }36 }37};38var options = {39};40mb.create(options).then(mbServer => {41 mbServer.createImposter(imposter);42});43var mb = require('mountebank');44var imposter = {45 {46 {47 is: {48 }49 }50 }51};52var options = {53};54mb.create(options).then(mbServer => {55 mbServer.createImposter(imposter);56});57var mb = require('mountebank');58var imposter = {
Using AI Code Generation
1var mb = require('mountebank');2var options = {3};4mb.create(options, function (error, server) {5 if (error) {6 console.log(error);7 } else {8 console.log("mountebank started on port " + server.port);9 }10});11var mb = require('mountebank');12var options = {13};14mb.create(options, function (error, server) {15 if (error) {16 console.log(error);17 } else {18 console.log("mountebank started on port " + server.port);19 }20});21var mb = require('mountebank');22var options = {23};24mb.create(options, function (error, server) {25 if (error) {26 console.log(error);27 } else {28 console.log("mountebank started on port " + server.port);29 }30});31var mb = require('mountebank');32var options = {33};34mb.create(options, function (error, server) {35 if (error) {36 console.log(error);37 } else {38 console.log("mountebank started on port " + server.port);39 }40});41var mb = require('mountebank');42var options = {43};44mb.create(options, function (error, server) {45 if (error) {46 console.log(error);47 } else {
Using AI Code Generation
1var mb = require('mountebank');2var allowedIPs = mb.allowedIPs();3console.log(allowedIPs);4var mb = require('mountebank');5var allowedIPs = mb.allowedIPs();6console.log(allowedIPs);7var mb = require('mountebank');8var allowedIPs = mb.allowedIPs();9console.log(allowedIPs);10var mb = require('mountebank');11var allowedIPs = mb.allowedIPs();12console.log(allowedIPs);13var mb = require('mountebank');14var allowedIPs = mb.allowedIPs();15console.log(allowedIPs);16var mb = require('mountebank');17var allowedIPs = mb.allowedIPs();18console.log(allowedIPs);19var mb = require('mountebank');20var allowedIPs = mb.allowedIPs();21console.log(allowedIPs);22var mb = require('mountebank');23var allowedIPs = mb.allowedIPs();24console.log(allowedIPs);25var mb = require('mountebank');26var allowedIPs = mb.allowedIPs();27console.log(allowedIPs);28var mb = require('mountebank');29var allowedIPs = mb.allowedIPs();30console.log(allowedIPs);31var mb = require('mountebank');32var allowedIPs = mb.allowedIPs();33console.log(allowedIPs);
Using AI Code Generation
1var request = require('request');2var mb = require('mountebank');3var mbHelper = require('./mbHelper');4var logger = require('./logger');5var mbPort = 2525;6var mbHost = 'localhost';7var mbImposter = {8 {9 {10 is: {11 }12 }13 }14};15var mbImposterUrl = mbUrl + '/imposters/' + mbImposter.port;16var mbImposterUrl = mbUrl + '/imposters/' + mbImposter.port;
Using AI Code Generation
1var mb = require('mountebank'),2 assert = require('assert');3var mbHelper = require('mb-helper'),4var port = 2525;5var imposters = [{6 stubs: [{7 predicates: [{8 equals: {9 }10 }],11 responses: [{12 is: {13 }14 }]15 }]16}];17mb.create({18}, function () {19 mbHelper.post('/imposters', imposters, function (error, response) {20 assert.equal(response.statusCode, 201, 'Expected imposters to be created');21 mbHelper.get('/imposters', function (error, response) {22 assert.equal(response.statusCode, 200, 'Expected imposters to be created');23 mbHelper.post('/imposters/80/allowedIPs', {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!