Cannot setup service worker with self-signed cert and webpack dev server - ssl

I'm new to Progressive Web Apps, and I'm adding a Service Worker to my app for the very first time. It's a simple Service Worker, with my goal being purely to test that it is being registered properly. The file is serviceWorker.js:
console.log('Hello Service Worker');
I'm adding this to an application that I'm running with the Webpack Dev Server. I'm using a self-signed certificate locally with it. I setup the Service Worker in my index.tsx (React Typescript) like this:
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/service-worker.js')
.then(() => console.log('Worker registered'))
.catch((ex) => console.error('Worker registration error', ex));
}
However, when I start the dev server and go to the app, I get an error:
Failed to register a ServiceWorker for scope ('https://localhost:3000/') with script ('https://localhost:3000/service-worker.js'): An SSL certificate error occurred when fetching the script.
The URL, https://localhost:3000/service-worker.js, does indeed work, the browser is just blocking it because of the self-signed piece of the cert.
I'm using Chrome Browser on on M1 Pro MacBook running MacOS Monterey, with Webpack 5.
For the record, I'm aware of plugins like Workbox, I would prefer not to use them at this time because I'm still very new to Service Workers. I believe in working with the low-level constructs when starting with a new tech to understand them better before embracing easier abstractions.

I'm not aware of any features—including service workers—that require HTTPS on localhost.
localhost, and equivalent IP address ranges, are specifically excluded from HTTPS requirements by Chromium-based browsers, and both Firefox and Safari follow that, at least when it comes to service workers.
So I would suggest that you just access your web site via http://localhost:3000 instead.
There are more details in this older answer.

Related

How to fix network error in react-native when access localhost api

We're trying to connect to an API (.net core 2.2) from react-native (version 0.59), via localhost, both apparently running on the same ip, different ports, react-native on port 8080, and the api on the 44344, the issue happens the moment we fetch the url from react-native
We’ve also tested running the url from Postman and everything seems ok, also from any of the web browser installed (safari/chrome), even we tested the browser INSIDE react-native iOS, and it works.
Any api running outside localhost works perfectly, is the localhost were we failed.
Network request failed.
onerror
whatwg-fetch.js:504:29
dispatchEvent
event-target.js:172:43
setReadyState
XMLHttpRequest.js:580:29
__didCompleteResponse
XMLHttpRequest.js:394:25
emit
EventEmitter.js:190:12
__callFunction
MessageQueue.js:366:47
<unknown>
MessageQueue.js:106:26
__guard
MessageQueue.js:314:10
callFunctionReturnFlushedQueue
MessageQueue.js:105:17
callFunctionReturnFlushedQueue
[native code]:0
Part of the code (function) that fetch the api, very simple (for now)
async Submit(){
//GET METHOD
try {
let response = await fetch('https://192.168.1.56:44344/api/values');
let responseJson = await response.json();
return Alert.alert(JSON.stringify(responseJson));
} catch (error) {
console.error(error);
}
}
Ok first of all, we've tried EVERY possible solution,to connect my react native app to my .net core api rest, both running in localhost, this is the list so far, of the things that we've tried so far, and still no result.
Localhost
127.0.0.1
Computer ip (network ip not mac address)
React Native blank project (from the ground up)
API .net core blank project (from the ground up)
Running snack expo + api .net core
ip forwarding (We can't do that do to our job policies/Not the solution we're looking for)
http/https
Different ports
Android and ios permissions from react-native
Same network different ip (this sorta worked, but we don't know exactly why it doesn't work running both react-native and the api in the same ip (localhost))
10.0.2.2 (for android)
Enable cors on api .net core (but apparently this doesn't work on native apps, only for web)
Expose the ip through ngrok/serveo (We can't do that do to our job policies/Not the solution we're looking for)
Frisbee
Axios
Websocket (We can't do that do to our job policies/Not the solution we're looking for)
XMLHttpRequest (status code error 0)
Firewall/proxy (our network is free from firewalls and proxies)
Web browser plugins (deactivated and/or uninstalled)
Cache/cookies
Docker (We can't do that do to our job policies/Not the solution we're looking for)
Reboot my macbook pro
we expect react native to fetch the api, so we can continue with the office 365 login authentication.
EDIT: I just discovered that fetching the machine ip (this time running windows), with my ip being 192.168.0.9 both on the api and the react native, the fetch result showed me the 10.0.2.2:80 in the header of the json response. I suppose it is the "localhost" ip from react native. How am I supposed to fetch an ip from localhost if react native is not letting me to do so?
EDIT: We had to go for plan B this time around, we've made it work with a docker on the api, but I need a solution for this problem. I'm 99% sure the issue is react-native and nothing else.
EDIT: After all these weeks one of my colleges managed to solve it. First of all, we couldn't make the firewall in my macbook pro work properly. Second, we solved that and found out our api was having issues. He found out the redirection was on https, and the certifications weren't working properly, so he changed this
"applicationUrl": "http://192.168.0.114:5001;https:192.168.0.114:5001"
to
"applicationUrl": "http://192.168.0.114:5001"
I got the same issue while fetching localhost API from react-native. Here is what I did to solve this issue.
In the startups class, I removed //app.UseHttpsRedirection(); from Configure method.(Not sure if it is needed)
After that in the launchsetting.js file under the properties folder, I changed from
"applicationUrl": "https://localhost:5001;http://localhost:5000"
to
"applicationUrl": "http://localhost:5000"
and in the React native part, I simply changed my localhost with my IP:
fetch('http://localhost:5000/values/') to fetch('http://127.0.0.1:5000/values/')
This completely worked for me
Take command prompt and type ipconfig, so we will be getting many addresses. From that take IPV4 and copy it to the clipboard. Then paste this address to both the back ends port address and front end port address.
eg say IPV4 address is 192.168.1.3 then make you your back end route API similar to this http://192.168.1.3:8080/patients, where 8080 is the port number (never mind). And use the same for the front end to grab the API result.
You have to do two things.
1 - Use http://192.168.1.x:8080 (your local ip ) rather than http:// localhost:8080 in your client.
2 - Add following code snippets to your .net core web api project in Startup.cs.
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://192.168.1.x:8080")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
.
.
.
app.UseCors(MyAllowSpecificOrigins);
Something that worked for me was run adb reverse tcp:<YOUR PORT> tcp:<YOUR PORT> in terminal
I'm not sure of how it works exactely, but I guess it makes some sort of mapping from the virtual device port to your machine's.
Example:
adb reverse tcp:8080 tcp:8080
Using the local IP address worked for me, with no additional configuration.
Example:
fetch("http://192.168.0.103:4000/books", {
method: "GET"
})
Thanks for all the insight, but none of the above solutions worked for me.
What did work:
https://ngrok.com/ - Download ngrok, signup, and connect your account. ngrok creates a private https localhost tunnel.
Setup - https://dashboard.ngrok.com/get-started/setup
Unzip to install:
unzip /path/to/ngrok.zip
Connect your ngrok account (Non functioning example auth token):
ngrok config add-authtoken 2ySPR5UeS3Fjf5YAblNRe7ZcV1o_9sdf2SDFGHjEQaOCE6xEi
Use the command (with your desired port number):
ngrok http 8080
Once ngrok is online, replace your localhost address:
http://localhost:8080
http://127.0.0.1:8080
http://192.168.0.100:8080
with the forwarding web address (Non functioning example address):
https://ebda-61-137-45-130.ngrok.io
I've used ngrok countless times for testing on a variety of networks without issue. So far its the only foolproof method I've found for testing localhost APIs.

SSL error when using https FCM

I have implemented FCM for web using fcm documentation.
Everything'll be fine if I set url like : 'http://xxx' I have no error.
But when I set url : 'https://xxx..', I get error:
"Failed to register a ServiceWorker: An SSL certificate error occurred when fetching the script."
code: "messaging/failed-serviceworker-registration"
"Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: An SSL certificate error occurred when fetching the script. (messaging/failed-serviceworker-registration)."
Can anyone show me how to fix this error?
This is a general problem when wanting to test service workers in a local development environment without proper SSL certificates. It is not specific to Firebase Messaging but pertains to Service Workers in general.
Here is the solution I found when using Google Chrome: Testing Service workers locally with self-signed certificates
Unfortunately, I don't know yet how to circument the issue with other browsers, but probably there must be similar ways.
For Chrome, you need to start a new instance of Chrome, with some flags telling it to ignore SSL certificate errors for your local origin:
In Linux (and maybe Mac):
google-chrome --ignore-certificate-errors --unsafely-treat-insecure-origin-as-secure=https://127.0.0.1 --user-data-dir=/tmp/foo
The https://127.0.0.1 here is the location where your app (and service worker) is hosted locally. You might need to adjust this to use the appropriate port, if serving on a different port than the standard HTTPS port 443, e.g. https://127.0.0.1:3000, when serving your app over HTTPS on port 3000.
The --user-data-dir=/tmp/foo is necessary to start a new instance, with a new user profile, if another instance of Chrome is already running.
In Windows (might vary, depending on where your chrome.exe is):
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --ignore-certificate-errors --unsafely-treat-insecure-origin-as-secure=https://localhost:1123
Again, you might have to adjust the port.
Easier method that worked for me:
Just paste chrome://flags/#allow-insecure-localhost in your chrome browser, and Enable the setting that says something like "Allow invalid certificates for resources loaded from localhost."

How can I replace the server in Web Component Tester

I have a project set up based around the Polymer Starter Kit, which includes Web-Component-Tester
This project includes php server code which I would also like to test by writing tests to run in the browser which will utilise the PHP server code through Ajax Calls.
This implies replacing the server that Web Component Tester is using ONLY when testing server side code. I hope to make a separate gulp task for this.
Unfortunately, I don't understand the relationship between WCT, Selenium and what ever server is run currently. I can see that WCT command starts Selenium, but I can't find out what the web server is and how that is started. I suspect it is WCT, because there is configuration of the mapping of directories to urls, but other than that I haven't a clue, despite trying to read the code.
Can someone explain how I go about making it run its own server when testing the client, but relying on an already set up web server (nginx) when running the server. I can set nginx to run from local host, or an other domain if that is a way to choose a different configuration.
EDIT: I have now found that runner/webserver.js starts an express server, and that urls get mapped so the base directory for the test runner and the bower_components directory both get mapped to the /components url.
What is currently confusing me is in what circumstances this gets run. It appears that loading plugins somehow does it, but my understanding from reading the code for this is tenuous.
The answer is that web component tester itself has a comment in the runner/config.js file.
In wct-conf.js, you can use registerHooks key into the Object that gets returned to add a function that does
registerHooks: function(wct) {
wct.hook('prepare:webserver', function(app, done) {
var proxy = require('express-http-proxy');
app.use('/api',
proxy('pas.dev', {
forwardPath: function(req, res) {
return require('url').parse(req.url).path;
}
})
);
done();
});
This register hook function allows you to provide a route (/api in my case) which this proxies to a server which can run the php scripts.

How do I set up an SSL connection using catalyst web framework?

According to this site: http://search.cpan.org/~mramberg/Catalyst-Plugin-RequireSSL-0.07/lib/Catalyst/Plugin/RequireSSL.pm
It's as easy as this:
# in MyApp.pm
use Catalyst qw/
RequireSSL
/;
__PACKAGE__->config(
require_ssl => {
remain_in_ssl => 0,
no_cache => 0,
detach_on_redirect => 1,
},
);
__PACKAGE__->setup;
# in any controller methods that should be secured
$c->require_ssl;
However, I am running the app using the built in MyApp_server.pl . And when I follow those instructions I get an SSL connection error Error code: ERR_SSL_PROTOCOL_ERROR
I'm guessing that the MyApp_server.pl doesn't support SSL, or there is more that I need to do to configure it.
Can I set up an SSL connection using nginx? I can find now instructions on how to do this. Can this be done with Apache?
Frankly, I was really hoping to be able to deploy this app with the built in server, but SSL encryption is required for all of my pages.
Thanks for any help that you can provide!
PS This app is running on my personal computer (OSX) behind a firewall, but the intention is to deploy it on a linux server behind a firewall.

Node.js + SSL support

Recent commits reference TLS progress. Any idea when it will be ready?
If not, what are the options for using SSL with a node app at the present time? Reverse proxy nginx? Is there a good tutorial available for using SSL with node?
Most professional apps need to support SSL these days and it would be great to be able to use node for these now.
Node.js 0.3.4 has been released.
Primordal mingw build (Bert Belder)
HTTPS server
Built in debugger 'node debug script.js'
realpath files during module load (Mihai Călin Bazon)
Rename net.Stream to net.Socket
Fix process.platform
Example
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
Node 3.x is not supposed to be used in production, it's unstable, bleeding edge development. 2.6 still has the old SSL implementation, which works.
If you want to know when all the stuff gets finished, your best bet is to either ask on the Google Group, or Ryan on Twitter.
Just for reference ... here's a JavaScript implementation of SSL/TLS:
https://github.com/digitalbazaar/forge
At the moment, it is only a client-side implementation. It would need to be expanded to cover server-side. For someone with a little knowledge about how TLS works, however, it shouldn't be too difficult to add to the existing framework.
From my experience node 0.2 SSL support is very flacky and unreliable.
We use nginx as a proxy.