electron-quick-start, ipcMain, CSP blocks 'eval' in Javascript - electron

I clone electron-quick-start demo, and test ipcMain function.
Follow the document add this in main.js
const { ipcMain } = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg) // print "ping"
event.reply('asynchronous-reply', 'pong')
})
ipcMain.on('synchronous-message', (event, arg) => {
console.log(arg) // print "ping"
event.returnValue = 'pong'
})
in preload.js
const { ipcRenderer } = require('electron')
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // print "pong"
ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg) // print "pong"
})
ipcRenderer.send('asynchronous-message', 'ping')
I can't add in renderer.js because it said
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.
and it can't find require(in renderer.js)
The problem is the development tool can't get value in preload.js at this one
ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg) // print "pong"
})
ipcRenderer.send('asynchronous-message', 'ping')
my node.js terminal can get the 'ping' string, and this is development tool's issues==>
screenshot

The index.html file of electron-quick-start demo contains the CSP rules:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
change it to:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-eval'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-eval'">
because eval-expressions are used somewhere. Yes, it is "not secure", but this is just demo. Later you can sort out what of "eval" construct is used and fix those.
Also you can remove both above meta tags to avoid troubles with Content Security Policy at first steps.

Related

Bootstrap doesn't work while using Helmet

app.use(helmet());
const scriptSrcUrls = [
"https://stackpath.bootstrapcdn.com/",
"https://api.tiles.mapbox.com/",
"https://api.mapbox.com/",
"https://kit.fontawesome.com/",
"https://cdnjs.cloudflare.com/",
"https://cdn.jsdelivr.net",
];
const styleSrcUrls = [
"https://kit-free.fontawesome.com/",
"https://stackpath.bootstrapcdn.com/",
"https://api.mapbox.com/",
"https://api.tiles.mapbox.com/",
"https://fonts.googleapis.com/",
"https://use.fontawesome.com/",
];
const connectSrcUrls = [
"https://api.mapbox.com/",
"https://a.tiles.mapbox.com/",
"https://b.tiles.mapbox.com/",
"https://events.mapbox.com/",
];
const fontSrcUrls = [];
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: [],
connectSrc: ["'self'", ...connectSrcUrls],
scriptSrc: ["'unsafe-inline'", "'self'", ...scriptSrcUrls],
styleSrc: ["'self'", "'unsafe-inline'", ...styleSrcUrls],
workerSrc: ["'self'", "blob:"],
objectSrc: [],
imgSrc: [
"'self'",
"blob:",
"data:",
"https://res.cloudinary.com/sdfgsfgsssss/"
"https://images.unsplash.com/",
],
fontSrc: ["'self'", ...fontSrcUrls],
},
})
);
I am getting these errors in the console
Refused to load the stylesheet 'https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css' because it violates the following Content Security Policy directive: "style-src 'self' 'unsafe-inline' https://kit-free.fontawesome.com/ https://stackpath.bootstrapcdn.com/ https://api.mapbox.com/ https://api.tiles.mapbox.com/ https://fonts.googleapis.com/ https://use.fontawesome.com/". Note that 'style-src-elem' was not explicitly set, so 'style-src' is used as a fallback.
clusterMap.js:13 Map Loaded
campgrounds:1 Refused to load the stylesheet 'https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css' because it violates the following Content Security Policy directive: "style-src 'self' 'unsafe-inline' https://kit-free.fontawesome.com/ https://stackpath.bootstrapcdn.com/ https://api.mapbox.com/ https://api.tiles.mapbox.com/ https://fonts.googleapis.com/ https://use.fontawesome.com/". Note that 'style-src-elem' was not explicitly set, so 'style-src' is used as a fallback.
Does anyone know why I am getting these errors in the console
The whole website works but all the bootstrap styling has been disabled!
When I remove the npm helmet all the bootstrap loads again.
has anyone got any ideas?
https://cdn.jsdelivr.net is not in your list of style-src directives.
const styleSrcUrls = [
"https://cdn.jsdelivr.net",
// ...

How to automatically change agent status on Amazon Connect?

I need step by step directions on how to load the CCP into a webpage and use the streams API. I would need the javascript to turn the agent from "missed" to "available" after 25 seconds.
Currently we have to manually update staus which doesn't make sense for our use case.
I saw on the Amazon Connect forum someone made mention of a way to automatically change the status of from Missed to Available.
If you're embedding the CCP and using the Streams API, you can check
the agent status on refresh, and if it's in Missed Call, set it to
Available. I have this set to happen after 10 seconds.
For an embedded CCP you can do this using Stream API. You can subscribe to the agent refresh status, and do it there.
connect.agent(function (agent) {
logInfoMsg("Subscribing to events for agent " + agent.getName());
logInfoMsg("Agent is currently in status of " + agent.getStatus().name);
agent.onRefresh(handleAgentRefresh);
}
function handleAgentRefresh(agent) {
var status = agent.getStatus().name;
logInfoEvent("[agent.onRefresh] Agent data refreshed. Agent status is " + status);
//if status == Missed Call,
// set it to Available after 25 seconds."
//For example -but maybe this is not the best approach
if (status == "Missed") { //PLEASE review if "Missed" and "Availble" are proper codes
setTimeout(function () {
agent.setState("Available", {
success: function () {
logInfoEvent(" Agent is now Available");
},
failure: function (err) {
logInfoEvent("Couldn't change Agent status to Available. Maybe already in another call?");
}
});
;
}, 25000);
}
}
If you also need to know how to embed the CCP in a website, you can just do something like this
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script type="text/javascript" src="amazon-connect-1.4.js"></script>
</head>
<!-- Add the call to init() as an onload so it will only run once the page is loaded -->
<body onload="init()">
<div id=containerDiv style="width: 400px;height: 800px;"></div>
<script type="text/javascript">
var instanceURL = "https://my-instance-domain.awsapps.com/connect/ccp-v2/";
// initialise the streams api
function init() {
// initialize the ccp
connect.core.initCCP(containerDiv, {
ccpUrl: instanceURL, // REQUIRED
loginPopup: true, // optional, defaults to `true`
region: "eu-central-1", // REQUIRED for `CHAT`, optional otherwise
softphone: { // optional
allowFramedSoftphone: true, // optional
disableRingtone: false, // optional
ringtoneUrl: "./ringtone.mp3" // optional
}
});
}
</script>
</body>
</html>
You can see the documentation for StreamsAPI here https://github.com/amazon-connect/amazon-connect-streams/blob/master/Documentation.md

Cordova file-transfer plugin not working in simulator

I'm trying to get the example code for the file-transfer plugin working, it's taken straight from the Cordova docs:
function downloadFile2() {
window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
console.log('file system open: ' + fs.name);
// Make sure you add the domain name to the Content-Security-Policy <meta> element.
var url = 'http://cordova.apache.org/static/img/cordova_bot.png';
// Parameters passed to getFile create a new file or return the file if it already exists.
fs.root.getFile('downloaded-image.png', { create: true, exclusive: false }, function (fileEntry) {
download2(fileEntry, url, true);
}, function () { logError('Error creating file'); });
}, function () { logError('Error creating fs'); });
}
function download2(fileEntry, uri, readBinaryData) {
var fileTransfer = new FileTransfer();
var fileURL = fileEntry.toURL();
console.log('Downloading ' + uri + ' to ' + fileURL);
fileTransfer.download(
uri,
fileURL,
function (entry) {
console.log("Successful download...");
console.log("download complete: " + entry.toURL());
if (false && readBinaryData) {
// Read the file...
readBinaryFile(entry);
}
else {
// Or just display it.
displayImageByFileURL(entry);
}
},
function (error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
null, // or, pass false
{
//headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
//}
}
);
}
function displayImageByFileURL(fileEntry) {
var elem = document.getElementById('imageElement');
elem.src = fileEntry.toURL();
}
I'm using the latest versions of the file-transfer and file plugins (1.7.1/6.0.1). I have added the domain to the Content-Security-Policy element as mentioned in the example:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: http://cordova.apache.org https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
When I run it up in the simulator (Android/iOS) from VS2017 the download fails silently. Neither the success or error callbacks are called, and it doesn't appear to generate a network request. The console log is as follows:
file system open: http_localhost_4400:Temporary
Downloading http://cordova.apache.org/static/img/cordova_bot.png to filesystem:http://localhost:4400/temporary/downloaded-image.png
That filesystem URL looked a bit odd to me, so I have tried other variants such as the full file path, using persistent storage instead of temporary, using 'cdvfile://localhost/persistent/downloaded-image.png', all with the same result. I'm at a loss as to how I can debug this further and wondering if I've missed something really obvious, so any advice appreciated...
Edit
I tried running it again today, and a dialog pooped up in Visual Studio with the message:
There is no handler for the following exec call:
FileTransfer.download("http://cordova.apache.org/static/img/cordova_bot.png", "cdvfile://localhost/persistent/downloaded-image.png", true, 1, null)
I did some more experimenting, including running it up in the VS simulator for Android. For some reason it had trouble connecting to cordova.apache.org (I was also unable to access this site in the browser on the emulator), but downloading a file from github worked correctly....

How to read/intercept JavaScript on the page before it is executed?

I would like to intercept location.reload(); via a Firefox API or by reading the JS on the page (remote & embedded) before it is loaded/executed or by any other means possible.
Example:
<head>
<script>
window.setTimeout(function() { location.reload(); }, 10000);
</script>
</head>
I have tried beforescriptexecute event listener (via GreaseMonkey & // #run-at document-start) but it is fired AFTER above is executed.
Update:
beforescriptexecute works nicely on REMOTE scripts since the event beforescriptexecute is fired before making the request (but then on the script src and not script content). It is different if the script is within normal script tag (and not remote), as per the example given. The beforescriptexecute fires and the script content can be rewritten but by then the window.setTimeout() has already fired and it is executing.
The beforescriptexecute should work. Its a non-greasemonkey event:
https://developer.mozilla.org/en-US/docs/Web/Events/beforescriptexecute
You can do stuff like this:
document.addEventListener("beforescriptexecute", function(e) {
src = e.target.src;
content = e.target.text;
if (src.search("i18n.js") > -1) {
// Stop original script
e.preventDefault();
e.stopPropagation();
window.jQuery(e.target).remove();
var script = document.createElement('script');
script.textContent = 'script you want';
(document.head || document.documentElement).appendChild(script);
script.onload = function() {
this.parentNode.removeChild(this);
}
}

Phonegap and jquery mobile : a href -> Origin null is not allowed by Access-Control-Allow-Origin

Im trying to use jquery mobile with phonegap, in a multi-page document.
Tring to use basic href links within the document, gives the Origin null is not allowed by Access-Control-Allow-Origin error which is quite annoying.
This is because the index page is refered to via file:// rather than http:// which webkit interprets as origin null. Has anyone got jquery mobile and phonegap to work in a multi page environment? if so how can you do it? If you add rel=external to the href tags the links work, but of course all the transitions are lost.
Cant find any info on this specific problem on stack overflow or teh internetz.
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script>
$(document).bind( "mobileinit", function(){
//alert("mobileinit fired");
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
});
</script>
<script src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
<script type="text/javascript">
function onDeviceReady() {
navigator.network.isReachable("google.com", reachableCallback, {});
}
// Check network status
function reachableCallback(reachability) {
// There is no consistency on the format of reachability
var networkState = reachability.code || reachability;
var states = {};
states[NetworkStatus.NOT_REACHABLE] = 'No network connection';
states[NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK] = 'Carrier data connection';
states[NetworkStatus.REACHABLE_VIA_WIFI_NETWORK] = 'WiFi connection';
if (networkState != 0) online = true;
}
var online = navigator.onLine || false;
$(document).ready(function() {
$(document).bind('deviceready', function(){
onDeviceReady()
})
// Your main code
})
//Now if you about to make an AJAX call to load up some dynamic data, you can easily check to see if you're online
if(online) {
} else {
}
</script>
</head>
<body>
<h1>Welcome to PhoneGap</h1>
Edit html
</body>
</html>
Here's the official documentation on how to do just what you are looking for...
Hope this helps!
Leon's comment is the correct answer - you need to add rel="external" to static links.
To Test
Download mongoose http server
copy mongoose_xxxxxxx.exe file to your assets/www
Now you can design your html pages for jquery mobile without Access-Control-Allow-Origin
I think you can find the solution here: http://view.jquerymobile.com/master/demos/faq/how-configure-phonegap-cordova.php
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
$.mobile.phonegapNavigationEnabled = true
Although I have not gotten it to work, I think that here are the solution.
if you are targeting app above JELLY_BEAN(API Level 16), here is what you can add to MainActivity class.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
super.appView.getSettings().setAllowUniversalAccessFromFileURLs(true);
}
Which will allow null origin XHR requests.

Resources