electron - loading page when certificate is imported - electron

I am using https and in case of a self-signed certificate, I want to prompt the user if he wants to import the required certificate. (Practically the same thing browser does when loading page without trusted certificate)
I have found out that there is a function dialog.showCertificateTrustDialog([browserWindow, ]options, callback) in electron which works just fine. I wanted to use it in a case when a certificate-errorappears.
Something like this:
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
dialog.showCertificateTrustDialog({certificate:certificate, message: "some msg"},
() => {
if (was certificate ok) {
event.preventDefault();
callback(true);
}
else {
callback(false);
}
}
);
});
But I have no idea how to do the was certificate ok part
Is it possible? Or do I have to for example load the page again to show it? If I run the app when the certificate is already imported, it works just fine. Otherwise, I get only a blank window.
Any help is appreciated, thank you

Currently, I have decided to use the following solution but it seems to me more like a hack. I try to load the page again after calling the showCertificateTrustDialog function again but if the certificate-error is thrown again I ignore it. I am still open to other solutions since I don't like this one
let certificateErrorRetry = false;
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
certificateErrorRetry = !certificateErrorRetry;
if (certificateErrorRetry) {
const {dialog} = require('electron');
dialog.showCertificateTrustDialog({certificate: certificate, message: "some msg" }, () => {
myapp.win.loadURL(url);
});
}
else { show some error }
});

Related

Supabase Auth - redirectTo not working for OAuth

I am switching from Flutter to Supabase and am running into an issue with Authentication. Although I can successfully launch the URL with the correct redirect value, I keep getting redirected to the site URL which should only be used for web, not iOS or Android. Below is the function I am using for Apple but this is happening with all other providers as well.
const isWeb = Platform.OS === "web";
const redirectTo = isWeb
? "https://web.example.com/login-callback/"
: "com.example.react://login-callback/";
export const signInWithApple = async () => {
const { data, error } = await supabase.auth.signInWithOAuth({
provider: "apple",
options: {
redirectTo: redirectTo,
},
});
if (error !== null) {
console.log(error?.message);
return "error";
} else {
console.log(data);
Linking.openURL(data.url);
return "success";
}
};
The URL that gets logged before launching is correct, for example, LOG {"provider": "apple", "url": "https://api.example.com/auth/v1/authorize?provider=apple&redirect_to=com.example.react%3A%2F%2Flogin-callback%2F"}, but I always get redirected to something like https://web.example.com/#access_token=*****. I had a similar issue with Flutter, and that was because I had not added the additional redirect in Supabase but I already did that. I also confirmed that I have CFBundleURLSchemes set in the info.plist for iOS but that did not fix it.
IF SELF-HOSTING:
Check that you do not have spaces after commas in ADDITIONAL_REDIRECT_URLS.
Correct ✅ :
ADDITIONAL_REDIRECT_URLS="URL,URL,URL"
Incorrect ❌ :
ADDITIONAL_REDIRECT_URLS="URL, URL, URL"

How can I detect a "certificate-error" message in an electron app?

I have an Electron app. Running fine.
I add the following function in to main.ts:
function MakeHTTPCall(url:string, id:string)
{
var request = require('request');
var options = {
'method': 'GET',
'url': url,
'headers': {
'Cookie': ''
}
};
options.headers["Cookie"] = 'ID=' + id;
request(options, function (error:any, response:any) {
if (error){
throw new Error(error);
}
var s = response;
})
}
This code currently lands on the "throw new Error" line. When I look at the error text it is:
code:'SELF_SIGNED_CERT_IN_CHAIN'
message:'self signed certificate in certificate chain'
stack:'Error: self signed certificate in certificate chain\n at TLS
After doing a web search I added this to my main.ts code:
app.on ("certificate-error", (event, webContents, url, error, cert, callback) => {
// Do some verification based on the URL to not allow potentially malicious certs:
if (url.startsWith ("https://yourdomain.tld")) {
// Hint: For more security, you may actually perform some checks against
// the passed certificate (parameter "cert") right here
event.preventDefault (); // Stop Chromium from rejecting the certificate
callback (true); // Trust this certificate
} else callback (false); // Let Chromium do its thing
});
But this code is never called.
How can I get it to fire? I just want to see if I can ignore the error and make the HTML call.
Thanks

Oidc-client-js trigger login when app start.What is the correct way?

i am using identity server 4 and oidc-client-js for auth, with angular frame work. I faced it this issue,
I am trying to trigger login redirect when application start. First i tried this code;
this.authService.userManager.getUser().then((user) => {
if (!(user)) {
this.authService.userManager.signinRedirect();
}
});
and user always returning null. Then i tried the same code with timeout, like this;
this.authService.userManager.getUser().then((user) => {
setTimeout(() => {
if (!(user)) {
this.authService.userManager.signinRedirect();
}
}, 2000);
});
after that, everything works good. But i'm not comfortable about using timeout. I tried using subject in callback component signinRedirectCallback, i tried userLoaded event but i can't succeeded. And finally i wrote this code;
In app component ngOnInit;
if (!this.authService.currentUser) {
this.authService.userManager.signinRedirectCallback().then((user) => {
// this.authService.userLoadedSub.next(user);
this.authService.currentUser = user;
console.log("01");
//navigate related route
this.initData();
}).catch((err) => {
console.log("signinRedirectCallback Error", err);
this.authService.userManager.signinRedirect();
});
}
Is this a good way to what i need? Is there any other way?
Many thanks for yor helps.

How to get HTTP status code of a page opened in a webview in Electron

I want to open a remote web app in electron's webview, but this app is sometimes down and return 503 response. The problem is that I can't detect any HTTP errors from electron, so that I can do something about it from my side.
Here is a sample of my code :
webviewObj = document.createElement('webview');
webviewObj.addEventListener('did-fail-load', (e) => {
// Is not fired for HTTP errors
});
webviewObj.addEventListener('did-finish-load', (e) => {
// No info about HTTP status code
});
webviewObj.src = "https://web-app.com";
In an old version of electron, the webview had an event did-get-response-details that gives httpResponseCode, but it got deprecated, and I could not find an alternative.
Thanks for your help.
you can use this API https://www.electronjs.org/docs/api/web-contents#event-did-navigate
win.webContents.on('did-navigate', (_event: any, _url: string, httpResponseCode: number) => {
if (httpResponseCode >= 400) {
// what you want to do
}
});

Google Sign-In JavaScript client not working on PWA App

Since yesterday when I use the gapi.auth2 to do a Google Sign-in on an installed PWA app on Android, the App opens the browser window to select the user, but it remains blank.
The same page on the Chrome browser on Android open the user selection as usual. The code is the same, from the same server. The code was not modified in more than 15 days. I presume the problem is some change in the gapi JS client code from Google servers.
Inspecting the PWA Google Sign-in tab on chrome shows the following error:
Uncaught Failed to get parent origin from URL hash!
The origins on Google Developer Console are ok.
Anyone has any clue how to solve this?
Edit1: Code chunk
initGoogle() {
this.ngRedux.dispatch({ type: SN_INIT_GOOGLE });
Observable.create((observer: Observer<any>) => {
let head = document.getElementsByTagName('head');
(<any>window).__ongload = () => {
gapi.load('auth2', () => {
gapi.auth2.init({
client_id: `${AppConfig.google.clientID}`
}).then(() => {
this.auth2 = gapi.auth2.getAuthInstance();
this.googleInitiated();
observer.complete();
}, (err) => {
this.log.error(err);
observer.error(err);
});
});
};
let script: HTMLScriptElement = document.createElement('script');
script.src = 'https://apis.google.com/js/platform.js?onload=__ongload';
script.type = 'text/javascript';
head[ 0 ].appendChild(script);
}).pipe(
timeout(AppConfig.google.timeout),
retry(AppConfig.google.retries),
catchError(error => {
this.googleInitError();
return observableEmpty();
}),
take(1)
).subscribe();
}
async googleLogin(scope: string = 'profile email', rerequest: boolean = false, type: string = SN_GOOGLE_LOGIN): Promise<GoogleUser> {
let goopts = {
scope: this.ngRedux.getState().socialNetworks.getIn([ 'google', 'grantedScopes' ]),
prompt: rerequest ? 'consent' : undefined
};
try {
const user: GoogleUser = await this.auth2.signIn(<any>goopts);
...
return user;
} catch (error) {
...
return error;
}
}
Edit 2: Error screenshot
Screenshot
I had the similar issue as mentioned here. I had not registered my domain under Credential -> My OAuth Client ID -> Authorized JavaScript origins. By adding, it started working. Check the similar case for your app. It may help.
This bug should be fixed. Cannot reproduce it any more.

Resources