How to connect VPN using nodejs in ubuntu - javascript

I have the code in my nodejs file which gives me the following information
host:"147.0.40.145"
method:"aes-256-cfb"
password:"9c359ad1ebeec200"
port:38473
I need to use above information and want to connect VPN through it. I have used below code to extract the above information.
const connectServer = (serverId) => {
const token = store('access_token')
httpOptions.Authorization = token.token_type+' '+token.access_token
return new Promise((resolve, reject) => {
const response = await axios.post(`${baseUrl}/servers/${serverId}/connect`, {'serverId':serverId},{headers: httpOptions})
console.log(response.data)
resolve(response.data)
})
}
So I need to know whether it is possible using nodejs to connect or create VPN?
Thank you in advance!!!

Install this npm
npm i node-openvpn --save
const openvpnmanager = require('node-openvpn');
const opts = {
host: '147.0.40.145',
port: 38473,
timeout: 1500, //timeout for connection - optional, will default to 1500ms if undefined
logpath: 'log.txt' //optional write openvpn console output to file, can be relative path or absolute
};
const auth = {
user: '{{add user name}}',
pass: '9c359ad1ebeec200',
};
const openvpn = openvpnmanager.connect(opts)
openvpn.on('connected', () => {
console.log("Connected to VPN successfully...");
});
For more info , please read this link
Another option
Link

Related

How to connect any server using ssh in Cypress.io to run a command?

I know that this probably is not the best way to do this. I read the question with the same title here, but it not solve my problem.
The question is: I have a server that only will achieve a result that I wanna if I run a command line in the server. So I wanna write a test to check the state of one page before and after I run that command. How I do that?
I tried to use the simple-ssh package, but I keep getting this error while trying to read the ssh key file:
fs.readFileSync is not a function
Actually my code looks like this:
import * as fs from 'fs';
let sshConfig = Cypress.config('ssh')
sshConfig.key = fs.readFileSync('path/to/key/file')
let SSH = require('simple-ssh');
Cypress.Commands.add('teste', () => {
let ssh = new SSH(sshConfig)
ssh.exec('echo', {
args: ['$PATH'],
out: function(stdout) {
console.log(stdout);
}
}).start();
})
Other possibility's are welcome.
As Fody mentioned, there are node.js functions present inside simple-ssh so a task is needed.
This is the basic configuration.
It's a direct translation of what you have, but you would want to return something from the task. As it is, the console.log() goes to the terminal console not the browser console.
cypress.config.js
const { defineConfig } = require('cypress')
const fs = require('fs')
const SSH = require('simple-ssh');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
ssh() {
const sshConfig = config.ssh
sshConfig.key = fs.readFileSync('path/to/key/file')
const ssh = new SSH(sshConfig)
ssh.exec('echo', {
args: ['$PATH'],
out: function(stdout) {
console.log(stdout);
}
}).start();
return null
},
})
}
}
})
test
Cypress.Commands.add('ssh', () => {
cy.task('ssh')
})
cy.ssh()
Try it with cy.readFile().
const SSH = require('simple-ssh');
Cypress.Commands.add('testSSH', () => {
cy.readFile('path/to/key/file').then(key
const sshConfig = Cypress.config('ssh')
sshConfig.key = key
const ssh = new SSH(sshConfig)
ssh.exec('echo', {
args: ['$PATH'],
out: function(stdout) {
console.log(stdout);
}
}).start()
})
})
The problem is fs is a node.js library, and it cannot be used in the browser.
But you may find the same thing applies to simple-ssh, If so, you will have to shift the code into a task where you can use any node.js functions.

node-telegram-bot-api deprecated Automatic enabling of cancellation of promises is deprecated

I'm trying to create a Telegram bot but when I run the code I get these errors:
"node-telegram-bot-api deprecated Automatic enabling of cancellation of promises is deprecated
In the future, you will have to enable it yourself.
See https://github.com/yagop/node-telegram-bot-api/issues/319. internal\modules\cjs\loader.js:1063:30"
"error: [polling_error] {"code":"ETELEGRAM","message":"ETELEGRAM: 409 Conflict: terminated by
other getUpdates request; make sure that only one bot instance is running"}"
I have no idea what that means. I've followed the link but I still don't know how to solve the problem, please help me, I don't know what to do.
Here is my bot.js code if that helps:
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');
const parser = require('./parser.js');
require('dotenv').config();
const token = process.env.TELEGRAM_TOKEN;
let bot;
if (process.env.NODE_ENV === 'production') {
bot = new TelegramBot(token);
bot.setWebHook(process.env.HEROKU_URL + bot.token);
} else {
bot = new TelegramBot(token, { polling: true });
}
// Matches "/word whatever"
bot.onText(/\/word (.+)/, (msg, match) => {
const chatId = msg.chat.id;
const word = match[1];
axios
.get(`${process.env.OXFORD_API_URL}/entries/en-gb/${word}`, {
params: {
fields: 'definitions',
strictMatch: 'false'
},
headers: {
app_id: process.env.OXFORD_APP_ID,
app_key: process.env.OXFORD_APP_KEY
}
})
.then(response => {
const parsedHtml = parser(response.data);
bot.sendMessage(chatId, parsedHtml, { parse_mode: 'HTML' });
})
.catch(error => {
const errorText = error.response.status === 404 ? `No definition found for the word: <b>${word}</b>` : `<b>An error occured, please try again later</b>`;
bot.sendMessage(chatId, errorText, { parse_mode:'HTML'})
});
});
Install this package npm I dotenv
Create a file called .env at the root of your project.
Add to that file this NTBA_FIX_319=1
Add to the top of your index.js file (or whatever file that contains your bot instance): require('dotenv').config()
Restart your bot.
So your code will look like
require('dotenv').config();
const TelegramBot = require('node-telegram-bot-api');
// replace the value below with the Telegram token you receive from #BotFather
const token = 'YOUR_TELEGRAM_BOT_TOKEN';
// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true});
bot.on('message', (msg) => {
const chatId = msg.chat.id;
// send a message to the chat acknowledging receipt of their message
bot.sendMessage(chatId, 'Received your message');
});
1) Get rid of the promise cancellation warning
The simplest, is to add that line at the top of your bot file:
process.env.NTBA_FIX_319 = 1 // this line SHOULD be above all imports
const TelegramBot = require('node-telegram-bot-api')
// ...rest of your telegram bot code
2) The 409 conflict error
In short, there are two version of your telegram bot running at the same time, so:
check if there is not multiple instance of your server running your bot, which can be the case when using workers, pm2...
check that your bot script is not started twice
Other causes and explanations can be found here and here

Error in Apollo Server deploy with AWS Lambda

People, how are you? I have a query, I just implemented my API made with apollo server in an AWS Lambda. I used the official documentation as a guide, but I'm noticing that the context handling varies a bit. I have a doubt with the latter, since I made certain changes and everything works fine locally using "serverless offline", but once I deploy it doesn't. Apparently the authentication context that I generate does not finish reaching my query. If someone can guide me a bit with this, I will be very grateful.
This is my API index:
const { ApolloServer, gql } = require('apollo-server-lambda');
const typeDefs = require('./db/schema');
const resolvers = require('./db/resolvers');
const db = require('./config/db');
const jwt = require('jsonwebtoken');
require('dotenv').config({ path: 'variables.env' });
db.conectDB();
// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({
typeDefs,
resolvers,
playground: {
endpoint: "/graphql"
},
context: ({ event, context }) => {
try {
const token = event.headers['authorization'] || '';
if(token){
context.user = jwt.verify(token.replace('Bearer ',''), process.env.KEY_TOKEN);
}
return {
headers: event.headers,
functionName: context.functionName,
event,
context,
}
} catch (error) {
console.error(error);
}
}
});
exports.graphqlHandler = server.createHandler({
cors: {
origin: '*',
credentials: true,
},
});
This is my query:
getUserByToken: async (_, {}, { context }) => {
if(context)
throw new Error((context ? 'context' : '') + ' ' + (context.user ? 'user' : ''));
let user = await db.findOne('users',{ _id: ObjectId(context.user._id) });
if(user.birthdate)
user.birthdate = user.birthdate.toString();
if(user.password)
user.password = true;
else
user.password = false;
return user;
}
My API response:
API response
From what I can see, you're not calling getUserByToken in your context. Is that correct? So, I'm not sure how you're encountering this error.
Can I give you some pointers?
Connecting to your DB is probably (or it should be) asynchronous. For that, I'd run your code like this:
db.connect()
.then(() => {
... handle your request in here
})
.catch(console.error);
I think you meant to call your getUserByToken in this line:
context.user = jwt.verify(token.replace('Bearer ',''), process.env.KEY_TOKEN);

Is there a way that I can get git origin branch code by nodejs

I added a git hook in my project when push event is triggered.
When hook is triggered and the ref value is refs/heads/master, the prod index.html file will be updated.
I want to read the new index.html content
router.post('/gitHook', async (ctx, next) => {
const body = ctx.request.body;
const matches = body.ref.match(/^refs\/heads\/(.*)/);
const branchName = matches[1];
console.log(branchName);
if(branchName === 'master'){
console.log('should get new code from git origin master')
}
await next();
});
I got the index.html content using gitlab package.
const { Gitlab } = require('gitlab');
const api = new Gitlab({
host: 'myhost',
token: 'myToken',
});
api.RepositoryFiles.show(body.project_id, '/build/index.html', body.ref).then(res => {
const content = res.content;
const stringContent = new Buffer(content, 'base64').toString();
console.log(stringContent);
});

Paho MQTT: Possible importing error?

I recently downloaded paho-mqttvia yarn. The problem is I am not sure if I am importing it correctly, because I am getting an error:
Cannot read property 'Client' of undefined
The way I am importing and using it is like this:
import Paho from 'paho-mqtt';
var client = new Paho.MQTT.Client(location.host, location.port, location.clientID)
const MQTTConnectAndMessage = (message) => {
client.connect({onSuccess: sendMQTTMessage})
}
const sendMQTTMessage = (msg) => {
let message = new Paho.MQTT.Message(msg);
message.destinationName = location.messageDestination;
client.send(message);
}
location.host = a string for the IP
location.port = a number for the port
location.clientID = a string for the clientID
If it is relevant, I am attempting to use it within a React Native app.
Maybe this module is not meant to be downloaded via NPM or Yarn? Or maybe I am not supposed to be importing "Paho"?
EDIT: when using react-native-paho-mqtt--this is the code I am using:
const client = new Client({ uri: 'ws://myiphere/ws', port: 1883, clientId: 'clientId', storage: myStorage});
const sendMQTTMessage = (msg) => {
client.on('connectionLost', (responseObject) => {
if (responseObject.errorCode !== 0) {
console.log("connection lost!");
}
});
client.on('messageReceived', (message) => {
console.log(message.payloadString);
});
client.connect()
.then(() => {
const message = new Message(msg);
message.destinationName = 'F2/BOX2/LED3';
client.send(message);
})
.catch((responseObject) => {
if (responseObject.errorCode !== 0) {
console.log('onConnectionLost:' + responseObject.errorMessage);
}
});
}
export {
sendMQTTMessage
}
I notice that whenever I enter anything that isn't prefaced with ws:// (web sockets) I would get a URI error.
The paho-mqtt library has changed, and the example code is incorrect
var client = new Paho.MQTT.Client(location.host, location.port, location.clientID)
Should be changed to (remove MQTT from Object path):
var client = new Paho.Client(location.host, location.port, location.clientID)
See the "breaking changes" in the GitHub README page:
paho.mqtt.javascript
Try this react-native compatible library: https://www.npmjs.com/package/react-native-paho-mqtt
yarn add react-native-paho-mqtt

Categories