Rate my idea: NodeJS as root behind Apache as a proxy with password

I’m the admin of a small Linux server owned by a relative of mine. He’s fairly tech savvy, but more at a level of a power user than an expert. I want to make a handy visual tool for him that would allow to do some simple server tasks: add/remove users and change their passwords; set up/remove websites; set up/remove mailboxes (I’ve decoupled those from system users so it’s a separate task if needed); and perhaps something else as needed.

Most of these things can be done from command line and some require the editing of some config files, but lengthy incantations with a lot of changing parts is just asking for trouble. I’d rather have a handy script.

The trouble is: most of these tasks require superuser permissions. He already has that, so I could make a textmode tool (which requires to be run as root), but a website would be so much nicer.

There’s already an apache webserver in place on port 80, bit running that as root would obviously be a lousy idea. Similarly, I don’t want to store root password anywhere.

So I had the idea of making the website in NodeJS and running the Node process as root, listening only on a specific port which only accepts incoming connections from localhost. Then Apache would be a non-elevated proxy in front of the NodeJS app. In addition, both Apache and NodeJS would ask for a password (taken from the same .htpasswd file).

If you can’t enter the password to Apache, you can’t even get to Node. If you hack Apache (or have access to some local account) you still need the password to get the Node app to cooperate.

Would this be safe enough? Ok, that’s kinda subjective, but considering that I’m more worried about opportunistic hackers from outside than malicious local users, would this be ok? There’s really nothing of much value stored on the server; I don’t expect anyone to do targeted hacking because there’s not much to gain (Wanna see pictures of my kids? You’re welcome…) I consider automated scanners and hackers trying to add to their botnets/db leaks the main threat. Any other suggestions on how to achieve this maybe?

Why does the NodeJS Crypto docs use CBC instead of GCM for RSA key-pair?

I have read that GCM is almost always more secure than CBC when implemented correctly.

However, in the documentation of NodeJS, CBC is being used as an example instead. The key-pair will be stored in the node environment.

Since the private key is being stored locally and CBC is an acceptable encryption for local files according to this answer, is it a secure enough implementation, or should GCM be used such as in this sample code?

funciones en nodejs con callbacks

Estuve siguiendo un tutorial y encontre un ejemplo con promesas lo cual es el siguiente:

function requestName(userName){ 	 	const url = `https://api.github.com/users/$  {userName}`; 	fetch(url) 		.then( function(res){ 			return res.json();  		}) 		.then( function(json){ 			console.log(json.name); 		}) 		.catch( function(e){ 			console.log(`El error es: $  {e}`); 		}); 		 }

Aun estoy aprendiendo sobre funciones pero estaba tratando de hacer la misma función con Callback pero el resultado no me imprime nada en la consola o quiza este haciendo algo mal, el codigo es el siguiente:

function requestName(userName){ 	const url = `https://api.github.com/users/$  {userName}`; 	fetch(url, function(err,res){ 		if(err){ 			console.log(`El error es: $  {err}`); 		}else{ 			const json = res.json(); 			console.log(json); 		} 	}) }

Chat entre dos personas con NodeJS y Socket.io

soy algo nuevo con socket.io y quiero hacer un un tipo de ayuda o asistencia en mi plataforma entre un usuario y el administrador a través de un chat, esto para resolver dudas o cualquier otro tipo de inconveniente.

El problema es que no logro hacer la comunicación entre los dos. Acá parte del código.

Cliente o Usuario

enviar.addEventListener('click', function() {     //Enviando Datos al Servidor     socket.emit('asistenciaCliente', {         usuario: usuario.value,         mensaje: mensaje.value     });      mensaje.value = ""; //Borrando campo al mandar el mensaje     mensajeChange();     mensaje.focus(); });   socket.on('asistenciaServidor', function(datos) {     // console.log(datos);     salida.innerHTML +=         `<p>         <strong>$  {datos.usuario}:</strong> $  {datos.mensaje}     </p>`;     salida.scrollIntoView(false); //Mostrar Ultimos Mensajes en Pantalla de forma automatica }); 


socket.on('asistenciaServidor', function(datos) {     // console.log(datos);     salida.innerHTML +=         `<p>         <strong>$  {datos.usuario}:</strong> $  {datos.mensaje}     </p>`;     salida.scrollIntoView(false); //Mostrar Ultimos Mensajes en Pantalla de forma automatica }); 


socket.on('asistenciaCliente', (datos) => {   console.log(datos);    socket.join(datos.usuario);   io.sockets.to(datos.usuario).emit('asistenciaServidor', datos); }); 

cabe mencionar que ya hace los chats privados para cada usuario, pero no muestra los mensajes al Administrador 🙁

Espero me puedan ayudar.

¿Cómo enviar un dato por un emitter desde nodejs?

Resulta que mi código lee los datos de un txt linea a linea, y después de eso los envió por un emitter a otro archivo, sucede que el ha leído muchos datos del txt por lo que esta recibiendo bastantes y esta emitiendo bastantes cada segundo, lo que quiero hacer es el código reciba todo esos valores del txt, pero que envié un solo valor por cada segundo. pero que el valor que envié no sea el primero que recibió y después el segundo, sino mas bien que sea el valor que se recibió justo cuando se ejecuto la linea de código después del segundo. si me explico?

acá esta el código:

const fs = require('fs'); const readline = require('readline');  readFile.on('line', function (line) {     element = line.split('\t');     var counter = 0;         for(let property of element){             counter++;             console.log("1",counter, property)             if(counter === 7){                 convertNumber = parseFloat(property);                 console.log("2", counter, convertNumber, property)                 myEmitter.emit('event', convertNumber)                 counter = 0;             }          } }) 

Nodejs pnp-auth (adfs) behind corporate proxy

We have a node/express app that connect to SharePoint onprem using pnp-auth and node-sp-auth-config. (IE connection settings : automatic) Works like a charm

Moving this app to another server On that server IE connection needs to be on manual proxy config to make be able to connect to SharePoint via the browser

For the node app the result is : nodejs app cannot connect to SharePoint “FetchError: request to ….. failed, reason: connect ETIMEDOUT …..:443 at ClientRequest. (d:\NODE\QOMV-CRExport\node_modules\pnp-auth\node_modules\node-fetch\lib\index.js:1444:11) at ClientRequest.emit (events.js:182:13) at TLSSocket.socketErrorListener (_http_client.js:392:9) at TLSSocket.emit (events.js:182:13) at emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT (internal/streams/destroy.js:50:3) at process._tickCallback (internal/process/next_tick.js:63:19)”

Anybody any pointers how to solve this ?


problema al enviar objeto por socket nodejs

estoy trabajando con nodejs y express como framework, hago una consulta a mi base de datos mysql, envío esa consulta al cliente para poder separarlo y mostrar por fechas en un fullcalendar.

codigo del servidor

var links; io.sockets.on('connection', function (socket) { socket.emit('news', {links}); socket.conn.close ();    },2000);     router.get('/grafica/:id',async (req,res,next)=>{    const {id} = req.params;   links= await pool.query('SELECT * FROM historial WHERE id_paciente=?', [id]);  res.render('date_real/grafica');    }   );  

codigo del cliente

var socket = io.connect(''); console.log('conectado');  socket.on('news', function (data) {    Object.keys(data).forEach(function(key) {      row = data[key];   });  console.log(row.length); 

la consulta lo recibe correctamente el cliente hasta cierto tamaño del objeto ya que muestra las fechas en el fullcalendar, me doy cuenta con el console.log(row.length); que solo lo soporta cuando su tamaño es de 87, si se pasa, el fullcalendar se queda en blanco, no se si la forma en que mando los datos sea la correcta, estaría muy agradecido si pudieran ayudarme.

How to install NodeJS and NPM on Ubuntu 18.04?

How to install NodeJS and NPM on Ubuntu 18.04?

1) I’m wrong, I add the referenciel 11 while I want the version 10 LTS. How can I change that ?

2) Can not install NodeJS and NPM. THERE are errors ?

ubuntu@www-example-com ~ $   curl -sL https://deb.nodesource.com/setup_11.x | sudo -E bash -  ## Installing the NodeSource Node.js 11.x repo...   ## Populating apt-get cache...  + apt-get update Hit:1 http://ppa.launchpad.net/certbot/certbot/ubuntu bionic InRelease Hit:2 http://nova.clouds.archive.ubuntu.com/ubuntu bionic InRelease                                                                         Hit:3 http://security.ubuntu.com/ubuntu bionic-security InRelease                                                                           Hit:4 http://repo.mysql.com/apt/ubuntu bionic InRelease                                                                                     Hit:5 http://ppa.launchpad.net/hda-me/nginx-stable/ubuntu bionic InRelease                                                                  Hit:6 http://nova.clouds.archive.ubuntu.com/ubuntu bionic-updates InRelease                                                                 Hit:7 https://deb.nodesource.com/node_8.x bionic InRelease                                                                                  Hit:8 http://nova.clouds.archive.ubuntu.com/ubuntu bionic-backports InRelease                                                               Hit:9 http://ppa.launchpad.net/ondrej/php/ubuntu bionic InRelease                                                                           Hit:10 http://ppa.launchpad.net/webupd8team/java/ubuntu bionic InRelease                                   Hit:11 https://artifacts.elastic.co/packages/7.x/apt stable InRelease                Hit:12 https://deb.goaccess.io bionic InRelease                                      Reading package lists... Done                        ## Confirming "bionic" is supported...  + curl -sLf -o /dev/null 'https://deb.nodesource.com/node_11.x/dists/bionic/Release'  ## Adding the NodeSource signing key to your keyring...  + curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add - OK  ## Creating apt sources list file for the NodeSource Node.js 11.x repo...  + echo 'deb https://deb.nodesource.com/node_11.x bionic main' > /etc/apt/sources.list.d/nodesource.list + echo 'deb-src https://deb.nodesource.com/node_11.x bionic main' >> /etc/apt/sources.list.d/nodesource.list  ## Running `apt-get update` for you...  + apt-get update Hit:1 http://repo.mysql.com/apt/ubuntu bionic InRelease Hit:2 http://security.ubuntu.com/ubuntu bionic-security InRelease                                                                           Hit:3 http://ppa.launchpad.net/certbot/certbot/ubuntu bionic InRelease                                                                      Hit:4 http://ppa.launchpad.net/hda-me/nginx-stable/ubuntu bionic InRelease                                                                  Get:5 https://deb.nodesource.com/node_11.x bionic InRelease [4,584 B]                                                                       Hit:6 http://ppa.launchpad.net/ondrej/php/ubuntu bionic InRelease                                                                           Hit:7 https://artifacts.elastic.co/packages/7.x/apt stable InRelease                                                                        Hit:8 http://ppa.launchpad.net/webupd8team/java/ubuntu bionic InRelease                                                                     Hit:9 http://nova.clouds.archive.ubuntu.com/ubuntu bionic InRelease                                                                         Hit:10 http://nova.clouds.archive.ubuntu.com/ubuntu bionic-updates InRelease                       Hit:11 http://nova.clouds.archive.ubuntu.com/ubuntu bionic-backports InRelease                                                             Hit:12 https://deb.goaccess.io bionic InRelease                                                                                            Get:13 https://deb.nodesource.com/node_11.x bionic/main amd64 Packages [768 B] Fetched 5,352 B in 3s (1,967 B/s)                            Reading package lists... Done  ## Run `sudo apt-get install -y nodejs` to install Node.js 11.x and npm ## You may also need development tools to build native addons:      sudo apt-get install gcc g++ make ## To install the Yarn package manager, run:      curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -      echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list      sudo apt-get update && sudo apt-get install yarn   ubuntu@www-example-com ~ $   nano /etc/apt/sources.list ubuntu@www-example-com ~ $   sudo apt install nodejs npm Reading package lists... Done Building dependency tree        Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation:  The following packages have unmet dependencies:  nodejs : Conflicts: npm E: Unable to correct problems, you have held broken packages. 

Run nodejs installed as snap package

I am running Ubuntu 18.04 and want to install a specific version of node using snap. I have installed this version successfully but when I run

node --version 

I get the version I have installed using apt. How can I get it to use the node executables installed with snap and not the ones in ‘/usr/local/bin’? I’ve tried adding the path to the snap install to the PATH variable but it keeps picking the one installed by apt. I tried purging the the apt install but that didn’t work because of reasons, and I kind of feel I shouldn’t have to. Any suggestions?

Swift HMAC doesn’t match NodeJS HMAC, but only sometimes!

I have discovered a HUGE issue in my code, and I have literally no idea what is causing this.

SO, when I send requests to my server I hash a string thats in the request. This is sometimes user input.

My app is multi language so I have to support all “ä” chars etc.

So with the normal english letters/chars numbers etc, this hashing method works like a dream. BUT when the string being hashed and compared contains a “ä” or a “ö” (Not specifically those, it literally might be that any char not in the Base64 set will cause this) the hash doesn’t match!

This is an absolute and complete disaster, and I have not noticed it this far. I have tried basically everything I know to try to fix this, and googling, and I am out of luck so far.

I generate the hash in Swift inputting the string and secretToken into this function and saving the output as a HTTP header:

func hmac(string: String, key: String) -> String {      var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))      CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key, key.count, string, string.count, &digest)      let data = Data(digest)      return data.map { String(format: "%02hhx", $  0) }.joined()  } 

How I compare the hash in NodeJS:

if (hashInTheRequest === crypto.createHmac('sha256', secretToken).update(stringToHash).digest('hex')) {     //Good to go } 

Thanks in advance!