Webpack Dev Server running on HTTPS/Web Sockets Secure - ssl

Normally in developer mode Webpack runs using HTTP. There is usually a web server serving content through HTTP and webpack using http/websockets on a separate port.
Is it possible to run the web server on https and webpack on https/websocket secure ?

See the webpack docs
There is a flag you can add to the webpack-dev-server command
webpack-dev-server --https

While the above answer is correct for cli, if you are not in the CLI, you could do something like this (in a gulp task):
var WebpackDevServer = require('webpack-dev-server');
new WebpackDevServer(webpack(WebpackDevConfig), {
https: true,
hot: true,
watch: true,
contentBase: path.join(__dirname, 'src'),
historyApiFallback: true
}).listen(1337, 'localhost', function(err, result) {
if (err) {
console.log(err);
}
console.log('Dev server running at https://localhost:1337');
});

this for TEST environment only:
you need to configure your webpack-dev-server as follows:
webpack-dev-server --https --cert ./cert.pem --key ./key.pem
The easiest work around is to generate a key with no passphrase (I don't know the security consequences of this! but this is for test only) .
To take the passphrase out of your key use this command:
$ openssl rsa -in key.pem -out newKey.pem
and use the new key in the previews configuration line

With webpack-dev-server --https you create a self-signed certificate. But it works not for all use cases.
Browsers will ask you for a security exception and show in the url bar that connection is not secure.
Therefore it is recommended to create a locally trusted development certificate for localhost with mkcert
Then use it via CLI:
webpack-dev-server --https --key C:/Users/User/localhost-key.pem --cert C:/Users/User/localhost.pem --cacert C:/Users/User/AppData/Local/mkcert/rootCA.pem
or configure devServer.https option in webpack.config.js:
devServer: {
https: {
key: fs.readFileSync('C:/Users/User/localhost-key.pem'),
cert: fs.readFileSync('C:/Users/User/localhost.pem'),
ca: fs.readFileSync('C:/Users/User/AppData/Local/mkcert/rootCA.pem')
}
}
mkcert creates .pem files in Unix format by default. So if you're on Windows you'll probably need convert them to Windows format using e.g. Notepad++

Tested on Windows (04/22/2021). Easy (no installations required).
1. Project configuration
In your project root run in Powershell (or CMD):
npx mkcert create-ca
npx mkcert create-cert
Your webpack.config.js:
devServer: {
// ...
https: {
key: fs.readFileSync("cert.key"),
cert: fs.readFileSync("cert.crt"),
ca: fs.readFileSync("ca.crt"),
},
// ....
},
2. Install certificate
Double-click on ca.crt > Install Certificate > ...
... > Current User > Place all certificates in the following store > Trusted Root Certification Authorities > ...
... > Finish > Yes
3. Check correct installation
Start > Type: "cert" > Manage User Certificates > ...
... > Trusted Root Certification Authorities > Certificates > Test CA
4. Reload & Test
Reload your browser, Start yout webpack dev server and check the SSL Certificate validity:
Additional steps
If you get this error:
You can add this configuration to your webpack.config.js:
devServer: {
// ...
// https: { ... }
disableHostCheck: true,
// ....
},
For more info:
https://webpack.js.org/configuration/dev-server/#devserverhttps
https://www.npmjs.com/package/mkcert

In my case I had to run all these commands to get the certificate:
openssl genrsa -out private.key 4096
openssl req -new -sha256 -out private.csr -key private.key
openssl x509 -req -days 3650 -in private.csr -signkey private.key -out private.crt -extensions req_ext
openssl x509 -in private.crt -out private.pem -outform PEM
And then finally:
npm run dev -- --open --https --cert private.pem --key private.key

I'm working on react project, Now wanted to add SSL certificate on this project and run my website with https so have followed below step:
In add https in webpack.config.js
devServer: {
https: true,
host: '0.0.0.0', // you can change this ip with your ip
port: 443, // ssl defult port number
inline: true,
historyApiFallback: true,
publicPath: '/',
contentBase: './dist',
disableHostCheck: true
}
Add SSL public certificate on package.json file If you didn't want to add a certificate on your package.json file then you have to add it on your webpack.config.js it is mandatory to add your certificate in your project either you can it on package.json file or webpack.config.js
For Package.json
scripts: {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode production",
"start": "webpack-dev-server --open --https --cert /path/to/private.crt --key /path/to/private.key"
}
OR webpack.config.js
devServer: {
https: true,
host: '0.0.0.0', // you can change this ip with your ip
port: 443, // ssl defult port number
inline: true,
https: {
key: fs.readFileSync('/path/to/private.pem'),
cert: fs.readFileSync('/path/to/private.pem'),
ca: fs.readFileSync('/path/to/private.pem')
}
historyApiFallback: true,
publicPath: '/',
contentBase: './dist',
disableHostCheck: true
}
Run npm start command on a terminal or you can also use pm2 start npm -- start

Had similar case when webapp was served from docker container which internally uses http, but traefik is serving app though https (multiple ports: 4000, 3000), so socket client was trying to connect to http://my.app.url:3000.
After spending a few hours to figure out a solution, came up with this in webpack 5:
devServer: {
client: {
port: ' ', //<--must be empty to eliminate the 3000 port for connecting to socket client
},
devMiddleware: {
writeToDisk: true,
},
transportMode: 'sockjs',
port: 3000, // port which is dev server opening for the sockets
...(process.env.DOCKER_DEV && {
host: '0.0.0.0',
firewall: false,
public: 'https://my.app.url', <-- HTTPS here
}),
},

Related

Self-Signed SSL certificate for local IP

Development certificate created by command dotnet dev-certs https --trust is works. I want to create a self-signed certificate for local IP in my LAN.
I've created a self-signed certificate by command:
New-SelfSignedCertificate -NotBefore (Get-Date) -NotAfter (Get-Date).AddYears(2) -Subject "192.168.1.100" -KeyAlgorithm "RSA" -KeyLength 2048 -HashAlgorithm "SHA256" -CertStoreLocation "Cert:\LocalMachine\My" -KeyUsage KeyEncipherment -FriendlyName "HTTPS development certificate" -TextExtension #("2.5.29.19={critical}{text}","2.5.29.37={critical}{text}1.3.6.1.5.5.7.3.1","2.5.29.17={critical}{text}DNS=192.168.1.100")
Then I copied certificate in trusted folder in certificates store:
After this I edited appsettings.Development.json:
"Kestrel": {
"Endpoints": {
"localhostHttp": {
"Url": "http://192.168.1.100:5000"
},
"localhostHttps": {
"Url": "https://192.168.1.100:5001",
"Certificate": {
"Subject": "192.168.1.100",
"Store": "Root",
"Location": "CurrentUser",
"AllowInvalid": true
}
}
}
But no result:
Is possible to create certificate like this?

How to run NUXT (npm run dev) with HTTPS in localhost?

EDIT: Updated the text in general to keep it shorter and more concise.
I am trying to configure HTTPS when I run npm run dev so I can test MediaStream and alike locally (for which browsers require me to provide HTTPS).
I am trying to configure it through nuxt.config.js but without any success.
Here is my nuxt.config.js file:
import fs from "fs";
import pkg from "./package";
export default {
mode: "spa",
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: "utf-8" },
{ name: "viewport", content: "width=device-width, initial-scale=1" },
{ hid: "description", name: "description", content: pkg.description },
],
link: [
{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" },
],
},
/*
** Customize the progress-bar color
*/
loading: { color: "#fff" },
/*
** Global CSS
*/
css: [
"element-ui/lib/theme-chalk/index.css",
"#makay/flexbox/flexbox.min.css",
],
/*
** Plugins to load before mounting the App
*/
plugins: [
"#/plugins/element-ui",
"#/plugins/vue-upload",
"#/plugins/axios-error-event-emitter",
"#/plugins/eventemitter2",
"#/plugins/vue-awesome",
"#/plugins/webrtc-adapter",
"#/plugins/vue-browser-detect-plugin",
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://axios.nuxtjs.org/usage
"#nuxtjs/axios",
"#nuxtjs/pwa",
],
/*
** Axios module configuration
*/
axios: {
// See https://github.com/nuxt-community/axios-module#options
baseURL: process.env.NODE_ENV === "production" ? "https://startupsportugal.com/api/v1" : "http://localhost:8080/v1",
},
/*
** Build configuration
*/
build: {
transpile: [/^element-ui/, /^vue-awesome/],
filenames: {
app: ({ isDev }) => (isDev ? "[name].[hash].js" : "[chunkhash].js"),
chunk: ({ isDev }) => (isDev ? "[name].[hash].js" : "[chunkhash].js"),
},
/*
** You can extend webpack config here
*/
extend(config, ctx) {
// Run ESLint on save
if (ctx.isClient) config.devtool = "#source-map";
if (ctx.isDev) {
config.devServer = {
https: {
key: fs.readFileSync("server.key"),
cert: fs.readFileSync("server.crt"),
ca: fs.readFileSync("ca.pem"),
},
};
}
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: "pre",
test: /\.(js|vue)$/,
loader: "eslint-loader",
exclude: /(node_modules)/,
});
}
},
},
};
Also, here you can see my dependencies in package.json:
"dependencies": {
"#makay/flexbox": "^3.0.0",
"#nuxtjs/axios": "^5.3.6",
"#nuxtjs/pwa": "^2.6.0",
"cross-env": "^5.2.0",
"element-ui": "^2.4.11",
"eventemitter2": "^5.0.1",
"lodash": "^4.17.11",
"nuxt": "^2.8.0",
"pug": "^2.0.3",
"pug-plain-loader": "^1.0.0",
"quagga": "^0.12.1",
"stylus": "^0.54.5",
"stylus-loader": "^3.0.2",
"vue-awesome": "^3.5.3",
"vue-browser-detect-plugin": "^0.1.2",
"vue-upload-component": "^2.8.20",
"webrtc-adapter": "^7.2.4"
},
"devDependencies": {
"#nuxtjs/eslint-config": "^0.0.1",
"babel-eslint": "^10.0.1",
"eslint": "^5.15.1",
"eslint-config-airbnb-base": "^13.1.0",
"eslint-config-standard": ">=12.0.0",
"eslint-import-resolver-webpack": "^0.11.1",
"eslint-loader": "^2.1.2",
"eslint-plugin-import": ">=2.16.0",
"eslint-plugin-jest": ">=22.3.0",
"eslint-plugin-node": ">=8.0.1",
"eslint-plugin-nuxt": ">=0.4.2",
"eslint-plugin-promise": ">=4.0.1",
"eslint-plugin-standard": ">=4.0.0",
"eslint-plugin-vue": "^5.2.2",
"nodemon": "^1.18.9"
}
However when I run npm run dev it still does not provide HTTPS, but does not provide any error output as well...
The output is exactly the same as if I didn't have the HTTPS configurations in nuxt.config.js:
$ npm run dev
> clothing-demo#1.0.0 dev /mnt/d/tralha/clothing-demo-app/frontend
> nuxt --hostname 0.0.0.0 --port 3000
╭────────────────────────────────────────────────╮
│ │
│ Nuxt.js v2.8.1 │
│ Running in development mode (spa) │
│ │
│ Listening on: http://192.168.126.241:3000/ │
│ │
╰────────────────────────────────────────────────╯
ℹ Preparing project for development 14:30:34
ℹ Initial build may take a while 14:30:35
✔ Builder initialized 14:30:35
✔ Nuxt files generated
HTTPS on local dev - NUXT style
Solution is described in NUXT documentation:
https://nuxtjs.org/api/configuration-server/#example-using-https-configuration
This may be achieved with:
Go to project main dir;
Create private and public key;
openssl genrsa 2048 > server.key
chmod 400 server.key
openssl req -new -x509 -nodes -sha256 -days 365 -key server.key -out server.crt
Add requirements to the top of the nuxt.config.js;
import path from 'path'
import fs from 'fs'
Extend or add configuration of server in nuxt.config.js;
server: {
https: {
key: fs.readFileSync(path.resolve(__dirname, 'server.key')),
cert: fs.readFileSync(path.resolve(__dirname, 'server.crt'))
}
}
You must follow the doc spec here https://nuxtjs.org/api/configuration-server/#example-using-https-configuration, BUT you must add code in the server/index.js file, otherwise it won’t work at all.
So in the server/index.js add const https = require('https') at the top and replace :
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
With
https.createServer(nuxt.options.server.https, app).listen(port, host);
And now it’s working!
You can use mkcert
Install mkcert:
brew install mkcert
brew install nss # if you use Firefox
Add mkcert to your local root CAs:
mkcert -install
In your terminal, navigate to your site's root directory or whichever directory you'd like the certificates to be located at. And run:
mkcert localhost
Add the following to your nuxt.config.js:
server: {
https: {
key: fs.readFileSync(path.resolve(__dirname, 'localhost-key.pem')),
cert: fs.readFileSync(path.resolve(__dirname, 'localhost.pem'))
}
}
https://web.dev/how-to-use-local-https/
If for some reason you enable https just like Jan Doleczek said and you also make use of axios module, make sure to disable https like this in nuxt.config.js:
axios: {
baseURL: 'http://yourapi:8000',
https:false,
},
If you don't do that all your axios request will use https instead of https.
Nuxt 3:
options.server from nuxt.config is not supported. You can use --port, --host, --https, --ssl-cert and --ssl-key instead.
official docs
Something like this:
{
"scripts": {
"dev": "nuxi dev --host website.test --https --ssl-key key.pem --ssl-cert cert.pem --port 3000",
}
I hope I didn't lose -- in example :-)
In the scenario to run local on https and share a domain or subdomain to share secured cookies for Single Sign On etc follow the below
Prerequisites
openssl
if you're on Windows you can find openssl.exe in C:\Program Files\Git\usr\bin
your .pfx certificate
including password if required
1. Create .crt and .key files using openssl.exe
1.1 Create key
pkcs12 -in '[full-path-and-name-of-your].pfx' -nocerts -out '[full-path-and-name-to-create-the].key'
if prompted enter the password to open your .pfx
1.2 Create crt
pkcs12 -in '[full-path-and-name-of-your].pfx' -clcerts -nokeys -out '[full-path-and-name-to-create-the].crt'
Move the .key and .crt to the root of your source folder
See more details here
2. Update server config likely in nuxt.config.js
As other answers suggested follow the changes to set up https from Nuxt documentation
Enter the password used to at step 1 as the passphase value
server: {
https: {
key: fs.readFileSync(path.resolve(__dirname, '[key-file-name].key')),
cert: fs.readFileSync(path.resolve(__dirname, '[crt-file-name].crt')),
passphrase: '[your password]'
}
}
3. Create / Modify local build script to specify hostname
"dev": "nuxt --hostname subdmain.domain.com --port 8000"
Your local will now serve on https on that domain/subdomain and port e.g. https://subdmain.domain.com:8000

Configuring SSL in JHipster

I am currently trying to implement a ssl into my current Jhipster application.
So far i have generated a certificate using keytool -genkey -alias iroApp -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650 .
In application-dev.yml i changed the server options from:
server:
port: 8080
to:
server:
port: 8443
ssl:
key-store: keystore.p12
key-store-password: myPassword
keyStoreType: PKCS12
keyAlias: myApplicationName
In proxy.conf.json:
From
{
"*": {
"target": "http://localhost:8080",
"secure": false,
"loglevel": "debug"
}
}
To
{
"*": {
"target": "http://localhost:8443",
"secure": true,
"loglevel": "debug"
}
}
In webpack.dev.js i have changed the target ip ports(from 8080 to 8443) and the secure from false to true.
When i enter on the page i get the "This site can’t be reached.localhost unexpectedly closed the connection.ERR_CONNECTION_CLOSED"
Is there something i forgot to do?
Thank you
Your key-alias needs to be all lowercase. It fails silently if you have a capital letter in the alias. You also are missing an indentation in your config, and you shouldn't mix snake-case and camelCase config variables.
Your final config should look like:
server:
port: 8443
ssl:
key-store: keystore.p12
key-store-password: myPassword
key-store-type: PKCS12
key-alias: myapplicationname
This was reported and fixed recently in the generator code (issue link)

Chaincode container can't connect to the local peer due to certificate signed by unknown authority

First of all I'd like to mention, that my setup works like a charm when there's no TLS enabled. It works even in Docker Swarm on AWS.
The problem starts when I enable TLS. When I deploy my .bna file via Composer, my newly created chaincode container produces the following logs:
2017-08-23 13:14:16.389 UTC [Composer] Info -> INFO 001 Setting the Composer pool size to 8
2017-08-23 13:14:16.402 UTC [shim] userChaincodeStreamGetter -> ERRO 002 Error trying to connect to local peer: x509: certificate signed by unknown authority
Error starting chaincode: Error trying to connect to local peer: x509: certificate signed by unknown authority
Funny thing is, that this works when deploying .bna via the composer playground (when the TLS is still enabled in my fabric)...
Below is my connection profile:
{
"name": "test",
"description": "test",
"type": "hlfv1",
"orderers": [
{
"url": "grpcs://orderer.company.com:7050",
"cert": "-----BEGIN CERTIFICATE-----blabla1\n-----END CERTIFICATE-----\n"
}
],
"channel": "channelname",
"mspID": "CompanyMSP",
"ca": {
"url": "https://ca.company.com:7054",
"name": "ca-company",
"trustedRoots": [
"-----BEGIN CERTIFICATE-----\nblabla2\n-----END CERTIFICATE-----\n"
],
"verify": true
},
"peers": [
{
"requestURL": "grpcs://peer0.company.com:7051",
"eventURL": "grpcs://peer0.company.com:7053",
"cert": "-----BEGIN CERTIFICATE-----\nbalbla3\n-----END CERTIFICATE-----\n"
}
],
"keyValStore": "/home/composer/.composer-credentials",
"timeout": 300
}
My certs have been generated by cryptogen tool, hence:
orderers.0.cert contains value of crypto-config/ordererOrganizations/company.com/orderers/orderer.company.com/msp/tlscacerts/tlsca.company.com-cert.pem
peers.0.cert contains value of crypto-config/peerOrganizations/company.com/peers/peer0.company.com/msp/tlscacerts/tlsca.company.com-cert.pem
ca.trustedRoots.0 contains crypto-config/peerOrganizations/company.com/peers/peer0.company.com/tls/ca.crt
I've got the feeling, that my trustedRoots certificate is wrong...
UPDATE
When I do docker inspect chaincode_container I can see that it misses ENV variable: CORE_PEER_TLS_ROOTCERT_FILE=/etc/hyperledger/fabric/peer.crt, while the chaincode container deployed via playground does have it...
When the chaincode image is built, the TLS certificate that it uses to build the trusted roots is the rootcert from:
# TLS Settings
# Note that peer-chaincode connections through chaincodeListenAddress is
# not mutual TLS auth. See comments on chaincodeListenAddress for more info
tls:
enabled: false
cert:
file: tls/server.crt
key:
file: tls/server.key
rootcert:
file: tls/ca.crt
The TLS certificate that the peer uses to run the gRPC service is the cert one.
By the way - You're using the release branch code, not the one in master - is that correct?

logstash http_poller ssl certification issue

I am trying to use logstash http_poller to query a server RESTAPI. I download the server pem through explore, and generate jks file with keytool. but we still get error "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". Don't know what wrong.
The config like below:
http_poller {
urls => {
restapi => {
method => get
url => "https://path_to_resources
headers => {
Accept => "application/json"
}
truststore => "/path/generated.truststore.jks"
truststore_password => "xxx"
ssl_certificate_validation => false
auth => {
user => "xxx"
password => "xxx"
}
}
}
request_timeout => 60
interval => 60000
codec => "json"
metadata_target => "http_poller_metadata"
}
}
By the way, what impact if ssl_certificate_validation is set as false?
I interpret OPs intention as to hopefully being able to disable TLS verification, which we still cant (logstash-7.11.1) and I plow on with how to get a trust store for these cases. This Q was one of my hits in pursuit of the same.
Some appliances will be running self signed certificates (another discussion ppl...) - so a small script to setup such a trust store could be helpful, especially if you are about to set up some automation internally.
Another caveat is that the self signed certificate still has to have a matching host name.
Based on the example from https://www.elastic.co/guide/en/logstash/current/plugins-inputs-http_poller.html
NB! Further error checking, etc. is left at your discretion.
#!/bin/bash
# Fetch an http server's TLS certificate and
# create or update a JAVA keystore / truststore
usage () {
echo "usage: get-cert.sh <hostname>:<port>"
exit 1
}
TRUSTSTORE=cacert/trust.jks
PARAM=$1
HOSTNAME=$(echo "$PARAM" | cut -d: -f 1)
PORT=$(echo "$PARAM" | cut -d: -f 2)
REST=$(echo "$PARAM" | cut -d: -f 3-)
[ -z "$HOSTNAME" ] && usage
[ -z "$PORT" ] && usage
[ -n "$REST" ] && usage
OUTPUT=$(
openssl \
s_client \
-showcerts \
-connect "${HOSTNAME}":"${PORT}" </dev/null 2>/dev/null | \
openssl \
x509 \
-outform PEM)
EC=$?
[ $EC -ne 0 ] && { echo "ERROR EC=$EC - $OUTPUT" ; exit $EC ; }
keytool \
-import \
-storepass changeit \
-alias ${HOSTNAME} \
-noprompt \
-file <(echo "$OUTPUT") \
-keystore ${TRUSTSTORE}
Using some bash specific possibilities here. The alternative is to go through temporary files, as pr the official example (see link above).
Apparently your certificate is invalid .
Regarding
ssl_certificate_validation
it doesn't have real impact , http-puller is based on manticore, a ruby libary which relay on Apache HC
which does not support this hook see