Setting up an StartSSL certificate on an Express app - node.js

I'm learning how to use HTTPS on Express, using as example, a certificate that I generated at StartSSL. I tried taking a look at other solutions over there, but nothing seems to work for me.
Ok, so I generated a .pem file in StartSSL, with a key I saved here. I've put the .pem file in the Express app folder, and I'm trying to set up a working server with this code:
const app = require('express')();
const fs = require('fs');
const https = require('https');
// Setup HTTPS
const httpsPort = 3443;
const options = {
key: "my key in plain text",
cert: fs.readFileSync("./cert.pem")
};
var secureServer = https.createServer(options, app).listen(httpsPort, () => {
console.log(">> App listening at port "+httpsPort);
});
I also tried with .crt certificate and so, but nothing seems to work. It throws the following error:
C:\some\path\test>node index.js
_tls_common.js:85
c.context.setKey(options.key, options.passphrase);
^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Error (native)
at Object.createSecureContext (_tls_common.js:85:17)
at Server (_tls_wrap.js:776:25)
at new Server (https.js:26:14)
at Object.exports.createServer (https.js:47:10)
at Object.<anonymous> (C:\some\path\test\index.js:18:26)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
What am I doing wrong, guys? Thank you!
EDIT:
Also tried putting the password in a .pem file with the following content:
-----BEGIN PRIVATE KEY-----
(my key)
-----END PRIVATE KEY-----
Which throws another error, maybe more fs-related:
Error: error:0906D064:PEM routines:PEM_read_bio:bad base64 decode

Related

Client Missing Intents

I have decided I wanted to make my own Discord bot so I started watching a tutorial on Youtube by #CodeLyon. I have followed the procedures exactly and this is my code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Vibre is online!');
});
Of course, I have not included the Client Login code but when I try to "run" this program in command prompt with "node .", this is what happens:
C:\Users\Isaac\Desktop\DiscordBot>node .
C:\Users\Isaac\Desktop\DiscordBot\node_modules\discord.js\src\client\Client.js:544
throw new TypeError('CLIENT_MISSING_INTENTS');
^
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
at Client._validateOptions
(C:\Users\Isaac\Desktop\DiscordBot\node_modules\←[4mdiscord.js←[24m\src\client\Client.js:544:13)
at new Client
(C:\Users\Isaac\Desktop\DiscordBot\node_modules\←[4mdiscord.js←[24m\src\client\Client.js:73:10)
at Object.<anonymous> (C:\Users\Isaac\Desktop\DiscordBot\main.js:3:16)
←[90m at Module._compile (internal/modules/cjs/loader.js:1072:14)←[39m
←[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)←[39m
←[90m at Module.load (internal/modules/cjs/loader.js:937:32)←[39m
←[90m at Function.Module._load (internal/modules/cjs/loader.js:778:12)←[39m
←[90m at Function.executeUserEntryPoint [as runMain]
(internal/modules/run_main.js:76:12)←[39m
←[90m at internal/main/run_main_module.js:17:47←[39m {
[←[32mSymbol(code)←[39m]: ←[32m'CLIENT_MISSING_INTENTS'←[39m
}
Can somebody please help?
In CodeLyon's video he used discord.js#12.2.0 but now discord.js updated to 13.1.0 and with this updated you must send ClientOptions as a parameter while creating new client. So now you need to specify the events which you want your bot to receive using gateway intents.
Instead of
const client = new Discord.Client();
Use
const client = new Discord.Client({intents: [Enter intents you need here]});
Example
const client = new Discord.Client({intents: ["GUILD", "GUILD_MESSAGES"]})

How do I make an API call inside a Firebase Cloud Function?

I'm trying to create a Firebase Cloud Function where I make an API call to NewsAPI and retrieve a set of articles. The code below is an example, and it aims to retrieve articles from BBCNews.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
var url = 'http://newsapi.org/v2/top-headlines?' +
'sources=bbc-news&' +
'apiKey={myKey}';
const GetArticles = () => (
fetch(new Request(url))
.then(function (response) {
console.log(response.json());
})
);
When I run this code I get the following error message:
ReferenceError: Request is not defined
at Object.<anonymous> (C:\Kesav\Coding stuff\project-academy\functions\index.js:9:11)
at Module._compile (internal/modules/cjs/loader.js:1185:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1205:10)
at Module.load (internal/modules/cjs/loader.js:1034:32)
at Function.Module._load (internal/modules/cjs/loader.js:923:14)
at Module.require (internal/modules/cjs/loader.js:1074:19)
at require (internal/modules/cjs/helpers.js:72:18)
at C:\Users\kkosa\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:661:33
at Generator.next (<anonymous>)
at fulfilled (C:\Users\kkosa\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:5:58)
How would I fix this?
You apparen't don't have any code that imports Request. That's not a "free object" in nodejs. You're going to have to find an HTTP client library for node (you have many options), import it, and use that in your code.

HAPI SSL error:0906D06C:PEM routines:PEM_read_bio:no start line

I have a Hapi server which works fine on HTTP. I need to make this work over HTTPS. I have a certificate which we bought from COMODO.
My Key
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGyXFDz/pSzMxO
...
g7N2PgtU9nhM7eYhQmhjB+4=
-----END PRIVATE KEY-----
My Certificate
-----BEGIN CERTIFICATE-----
MIIFbDCCBFSgAwIBAgIRAK3oQPHzO66FR3iLafOh2JkwDQYJKoZIhvcNAQELBQAw
...
pvWiUJabAat2O+hexjv55O4RkfQ13aIKo1Z7VeWyNQdEPaSCOFtteC4a3WelWcZ7
-----END CERTIFICATE-----
(have also tried this with a combined root certificate bundle with the same problem)
Edit: Both the certificates and the key are in the PEM format and not the DER format. There are also no problems with line endings.
My Server Code
var tls = {
key: fs.readFileSync('privkey.pem'),
cert: fs.readFileSync('certificate.pem')
};
var server = new Hapi.Server();
server.connection({
address: '0.0.0.0',
port: 443,
tls: tls,
routes: { cors: { origin: ['*'] }, validate: { options: { abortEarly: false } } }
});
I end up with the following error when trying to start the server
node server.js
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Error (native)
at Object.createSecureContext (_tls_common.js:87:19)
at Server (_tls_wrap.js:754:25)
at new Server (https.js:24:14)
at Object.exports.createServer (https.js:44:10)
at new module.exports.internals.Connection.options (W:\project\node_modules\hapi\lib\connection.js:89:74)
at internals.Server.connection (W:\project\node_modules\hapi\lib\server.js:121:24)
at Object.<anonymous> (W:\project\server.js:98:8)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
What is going on? how do I fix this?
Any help would be appreciated.
Thanks
I was running into a similar issue, my configuration is different as I'm supplying the cert and key as a string (this is dev only). I was getting this same error because I linearized my key from a text editor which stripped out the new line (\n) characters. As soon as I added those \n characters back into my string, it worked just fine. Which got me thinking about your issue....
I tested your fs.readFileSync('server.key') (yes my server.key is in PEM format) code using my certificate and key and I noticed that without specifying an encoding, the file data was coming back as a byte array.
<Buffer 2d 2d 2d 2d ....
However, specifying an encoding fs.readFileSync('server.key', 'utf-8') did give me back the certificate data as a human readable string.
I'd try updating your readFileSync calls to include an encoding like 'utf-8' - it could be why hapi can't understand your certificate data.
Hope this helps!

googleapis throwing 'undefined' error in apirequest.js

I have a problem with the NodeJs googleapis module.
My Simple Test:
var google = require('googleapis');
var analytics = new google.analytics('v3');
var OAuth2 = google.auth.OAuth2;
var config = require('./config.js')
var oauth2Client = new OAuth2(config.clientId, config.clientSecret);
// Retrieve tokens via token exchange explained above or set them:
oauth2Client.setCredentials({
access_token: config.accessToken,
refresh_token: config.refreshToken
});
// get management list
analytics.management.accounts.list({ auth: oauth2Client }, function(err, response) {
console.log(err)
console.log(response)
});
My Result:
Type Error: Cannot read property 'params' of undefined
at createAPIRequest (/Users/gkburdett/Documents/Applications/maestro-and-scout/node_modules/googleapis/lib/apirequest.js:76:39)
at Object.Analytics.management.accounts.list (/Users/gkburdett/Documents/Applications/maestro-and-scout/node_modules/googleapis/apis/analytics/v3.js:342:16)
at Object.<anonymous> (/Users/gkburdett/Documents/Applications/maestro-and-scout/server/google/test/simpleTest.js:13:31)
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:906:3
parameters.context.google is a blank object.
It works if I change apirequest.js line 76 to a blank object. I submitted an issue on GitHub, but I have a hard time believing I'm the only one having this problem if it's a problem with the library.
Change line 2 from:
var analytics = new google.analytics('v3');
to:
var analytics = google.analytics('v3');
When calling analytics.management.accounts.list the context options being passed to createAPIRequest are out of scope to the initial google object.
There was a method in my api with a name that started with "google" and it was overriding some internal config object of the library. I am not a guru to judge anyone but it seems like a poor design to mix internal and user-defined methods in one object

throw new Error('Missing PFX or certificate + private key')

I have previously developed a module in node.js and after complete testing put it in git hub. Now i downloaded the zipped version of same module from githup and tried to run the module, installed all the dependencies, But now i am getting the following error
Error:Missing PFX + certificate + private key
The complete Error Log is as follows:
Error: Missing PFX or certificate + private key.
at HTTPSServer.Server (tls.js:1029:11)
at HTTPSServer.Server (https.js:35:14)
at HTTPSServer (C:/Social/node_modules/express/node_modules/connect/lib/https.js:34:16)
at new HTTPSServer (C:/Social/node_modules/express/lib/https.js:38:23)
at Object.exports.createServer (C:/Social/node_modules/express/lib/express.js:43:12)
at Object.<anonymous> (C:/Social/app.js:46:36)
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)
I tried to find the solution but could not find any. Can anyone help me to with the same. Thanks in advance.
For some reason, Express thinks you want to start an HTTPS server. My guess would be this is because of this line in your code:
var app = module.exports = express.createServer(form({ keepExtensions: true }));
(link)
However, Express uses this code to see if it should start an HTTPS server:
exports.createServer = function(options){
if ('object' == typeof options) {
return new HTTPSServer(options, Array.prototype.slice.call(arguments, 1));
} else {
return new HTTPServer(Array.prototype.slice.call(arguments));
}
};
Which is a bit strange, since form() returns a function and not an object. But to be sure, try rewriting your code to this:
var app = module.exports = express.createServer();
app.use(form({ keepExtensions: true }));

Resources