Redirect http to https with Node.js - node.js

I have a Node.js server, with an active SSL certificate on the domain.
I have read some replies on this website about this, yet even when I relate to such already-solved questions, I get an error.
var express = require('express');
var https = require('https');
var http = require('http');
var path = require('path');
var fs = require('fs');
var mysql = require('mysql');
var queue = {};
var qc = {};
var app = express();
var options = {
key: fs.readFileSync('sslcert/domain-name.key', 'utf8'),
cert: fs.readFileSync('sslcert/domain-name.csr', 'utf8')
};
var httpServer = http.createServer(app);
var httpsServer = https.createServer(options, app);
/* various stuff to display my website */
httpServer.listen(process.env.PORT);
httpsServer.listen(process.env.PORT);
I get the following error in my console.
_tls_common.js:67
c.context.setCert(options.cert);
^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Error (native)
at Object.createSecureContext (_tls_common.js:67:17)
at Server (_tls_wrap.js:754:25)
at new Server (https.js:17:14)
at Object.exports.createServer (https.js:37:10)
at Object.<anonymous> (/srv/data/web/vhosts/default/server.js:35:25)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
Thank you in advance for your answer!
Noël.

cert should be your domain's PEM formatted certificate, followed by the PEM formatted intermediate certificates; not the CSR.
cert: fs.readFileSync('sslcert/domain-name.pem', 'utf8')

In addition to the answer by Anand Bhat note that you shouldn't bind both of those servers to the same port like you're trying to do:
httpServer.listen(process.env.PORT);
httpsServer.listen(process.env.PORT);
It might work but it might work not how you expect it. If you do:
httpServer.listen(process.env.PORT_HTTP);
httpsServer.listen(process.env.PORT_HTTPS);
where PORT_HTTP is e.g. 80 and PORT_HTTPS is e.g. 443, you will always know which server will process which request.

Related

Getting a error in my node js https server

I have built a https server and got my certs all there and it seems to find them with no issues. My my issue is that any time I run the code I am getting
var proxy = new http_proxy.HttpProxy({
^
TypeError: http_proxy.HttpProxy is not a constructor
at Object.<anonymous> (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\server.js:11:13)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
I tried to find the issue on the web but can't seem to get it to work.
Here is my code:
var http_proxy = require ('http-proxy'),
https = require('https'),
fs = require('fs');
var privateKey = fs.readFileSync("privatekey.pem").toString();
var cert = fs.readFileSync("newcert.pem").toString();
var options = {key: privateKey, cert: cert };
var proxy = new http_proxy.HttpProxy({
target:{
host: "localhost",
port: 8080
}
});
var s =https.createServer(options, function (req, res) {
console.log("Proxying!");
proxy.proxyRequest(req, res);
});
s.listen(8443);
The docs don't specify your syntax nor the library exports the module you're trying to initialize.
RTFM https://www.npmjs.com/package/http-proxy
EDIT
Even though the docs are VERY good, here's an example w/ Proxy over HTTPS node server:
var http_proxy = require ('http-proxy'),
https = require('https'),
fs = require('fs');
var privateKey = fs.readFileSync("privatekey.pem").toString();
var cert = fs.readFileSync("newcert.pem").toString();
var options = {key: privateKey, cert: cert };
var proxy = httpProxy.createServer({
ssl: {
key: privateKey,
cert
},
target: 'https://localhost:9010', // Send it anywhere
secure: true // Depends on your needs, could be false.
}).listen(443);
var s = https.createServer(options, function (req, res) {
console.log("Proxying!");
proxy.web(req, res);
});
s.listen(8443);

Node running HTTPS Server?

I am writing a program that will serve a particular file. However, I get an exception. I am not sure on the error since I am a bit new to node based programming.
I have got the certificates correct.
var tls = require('tls');
var fs = require('fs');
var options = {
key: fs.readFileSync('/home/test/key.pem'),
cert: fs.readFileSync('/home/test/server.crt')
};
tls.createServer(options, function (s) {
content = fs.readFileSync('/home/test/abc.conf','utf8');
s.write(content);
s.setEncoding('utf8');
s.pipe(s);
}).listen(8000);
node app.js
events.js:160
throw er; // Unhandled 'error' event
^
Error: write ECONNRESET
at exports._errnoException (util.js:1020:11)
at WriteWrap.afterWrite (net.js:800:14)
Realized, it is quite easy using just https.createServer and provide options of ciphers there.
var ciphers = [
'AES128-SHA',
'AES256-SHA'
].join(':');
var options = {
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem'),
ciphers: ciphers
};
https.createServer(options, function(req, res) {
console.log("Running node now");
}).listen(443);
Since, I am using 443 https standard port, I need to start this node app with admin permission i.e. sudo.

Running NodeJS with TLS protocol

Generated a self-signed certificate with OpenSSL and copied the certificate & the private key to the required destination folder.
To create an HTTPS server, we require two things: an SSL certificate, and Node's built-in https module.
With Node.js installed, I tried the following JavaScript to run from the command Line
TLSServer.js
var tls = require('tls');
var fs = require('fs');
var port = 8081; //3000;
var host = '127.0.0.1'; //192.168.1.135
var options = {
key: fs.readFileSync('private-key.pem'), // /path/to/private-key.pem
cert: fs.readFileSync('certificate.pem') // /path/to/certificate.pem
};
TLSClient.js
var client = tls.connect(port, host, options, function() {
console.log('connected');
if (client.authorized) {
console.log('authorized: ' + client.authorized);
client.on('data', function(data) {
client.write(data); // Just send data back to server
});
} else {
console.log('connection not authorized: ' + client.authorizationError);
}
});
Actual Output:
cmd>node TLSServer.js
openssl config failed: error:02001005:system library:fopen:Input/output error
cmd>node TLSClient.js
openssl config failed: error:02001005:system library:fopen:Input/output error
events.js:193
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT 127.0.0.1:8081
at Object._errnoException (util.js:1031:13)
at _exceptionWithHostPort (util.js:1052:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1195:14)
What might be the reason for getting this issue:
openssl config failed: error:02001005:system library:fopen:Input/output error
httpserver.js
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('certificate.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.write("You are connected to https server");
res.end("\n hello world \n");
}).listen(8080)
https://localhost:8080
From browser I used to get the following output:
You are connected to https server
hello world
But not with TLS Client/Server. But what might be there to modify in OpenSSL config file?
Solved openssl config failed: error:02001005:system library:fopen:Input/output error by adding the path of openssl.cnf in Environment Variables -> System Variables
OPENSSL_CONF=C:\OpenSSL-Win64\bin\openssl.cnf
To validate it you can type in the shell:
echo %OPENSSL_CONF%
But still I'm getting error with TLSServer.js
cmd>node TLSServer.js
module.js:544
throw err;
^
Error: Cannot find module 'C:\Users\user\Desktop\TLSServer.js'
at Function.Module._resolveFilename (module.js:542:15)
at Function.Module._load (module.js:472:25)
at Function.Module.runMain (module.js:682:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:613:3

SSL certificate on NodeJS and express not working

I have a NodeJs Application running with express. I have been trying to integrate an SSL certificate but I keep having the same error: Error: error:0906D06C:PEM routines:PEM_read_bio:no start line.
I have tried some solutions I found on stackOverflow like
var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );
https.createServer({
key: privateKey,
cert: certificate
}, app).listen(port);
or
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey = fs.readFileSync('privatekey.pem');
var certificate = fs.readFileSync('certificate.pem');
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
httpServer.listen(8081);
httpsServer.listen(8443);
But none seem to work. My main problem is that I donwloaded my certificate file from GoDaddy but I only get two .cert files. I have read in some websites how to obtain the .pem files but I keep getting the same error.
As you can see I am new at using https protocol in NodeJs.
Could you help me solve this problem?
Best regards

NodeJS - HTTPS/HTTP Proxy Server Setup

I'm currently trying to setup an HTTP/HTTPS proxy server using NodeJS. Using the example of this gist, this is what I have.
var fs = require('fs'),
http = require('http'),
https = require('https'),
httpProxy = require('http-proxy');
var isHttps = true; // do you want a https proxy?
var options = {
https: {
key: fs.readFileSync('/home/ubuntu/key.key'),
cert: fs.readFileSync('/home/ubuntu/crt.crt')
}
};
// this is the target server
var proxy = new httpProxy.HttpProxy({
target: {
host: '127.0.0.1',
port: 11612
}
});
if (isHttps)
https.createServer(options.https, function(req, res) {
console.log('Proxying https request at %s', new Date());
proxy.proxyRequest(req, res);
}).listen(443, function(err) {
if (err)
console.log('Error serving https proxy request: %s', req);
console.log('Created https proxy. Forwarding requests from %s to %s:%s', '443', proxy.target.host, proxy.target.port);
});
else
http.createServer(options.https, function(req, res) {
console.log('Proxying http request at %s', new Date());
console.log(req);
proxy.proxyRequest(req, res);
}).listen(80, function(err) {
if (err)
console.log('Error serving http proxy request: %s', req);
console.log('Created http proxy. Forwarding requests from %s to %s:%s', '80', proxy.target.host, proxy.target.port);
});
Issue is, when I run it on my Ubuntu server, this is the error I'm getting. Kinda lost.
/home/ubuntu/prox.js:16
var proxy = new httpProxy.HttpProxy({
^
TypeError: undefined is not a function
at Object.<anonymous> (/home/ubuntu/prox.js:16:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
17 Jan 23:18:34 - [nodemon] app crashed - waiting for file changes before starting...
Have you tried the following, might help, this is from their git hub page.
var proxy = httpProxy.createProxyServer(options);

Resources