Polymer, Dart, Chrome App, CSP and debugging - dart

Similar questions have been around for a while, maybe someone knows the answer for today's stack. Ideally preserving debuggability...
I have a Dart app which implements the GUI in Polymer/Dart and the back end in Chrome/Dart. Both parts work well (many thanks) now I am trying to tie them together and debug any problems. The unified app hits a wave of CSP errors so I have put together a tiny test case. There's a spread of Dart/Polymer/CSP advice on the net but it changes as things evolve and it's very difficult to see the current best practice. Here is the test case:
manifest.json
{
"manifest_version": 2,
"name": "Test Case",
"version": "0.3",
"icons": {"128": "dart_icon.png"},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"app": {
"background": {
"scripts": ["background.js"]
}
},
"permissions": [ "usb"
, { "usbDevices": [ {"vendorId": 1027, "productId": 24597} ] }
, { "fileSystem": [ "write", "retainEntries", "directory" ] }
]
}
background.js
chrome.app.runtime.onLaunched.addListener(function(launchData) {
chrome.app.window.create('testwrap.html', {
'id': '_myMainWindow',
'bounds': {'width': 800, 'height': 500 }
});
});
testwrap.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PolyChrome</title>
<link rel="import" href="packages/polymer/polymer.html">
<link rel="import" href="clickcounter.html">
</head>
<body>
<h1>Testing...</h1>
<p>in the test directory...</p>
<div id='container_id'>
<p id='text_id'>The log is here.</p>
</div>
<div id='div2'>
<click-counter></click-counter>
</div>
<script type='application/dart' src='testwrap.dart'></script>
</body>
</html>
testwrap.dart
import 'dart:html';
import 'package:polymer/polymer.dart';
export 'package:polymer/init.dart';
//----------------------------------------
#whenPolymerReady
void mainStartup() {
querySelector("#text_id").text = 'Running';
}
The click-counter element is the standard code from the Dart/Polymer page.
The yaml includes a $dart2js that maybe isn't used (?) or maybe having two csp:true lines is incorrect?
pubspec.yaml
name: polyChrome
description: Chrome App with Polymer
dependencies:
chrome: ^0.7.0-dev1
code_transformers: any
core_elements: any
paper_elements: any
polymer: any
transformers:
- polymer:
entry_points:
- web/testwrap.html
csp: 'true'
- $dart2js:
csp: 'true'
checked: 'true'
The CSP error messages (all the same):
Refused to execute inline script because it violates the following Content Security Policy
directive: "default-src 'self' chrome-extension-resource:".
Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...')
is required to enable inline execution. Note also that 'script-src'
was not explicitly set, so 'default-src' is used as a fallback.
Confusingly the test app seems to work OK despite the error messages, but a larger test freezes while booting - can't ignore the messages.
The larger test gives an error message from
Zone zone = await initPolymer();
The message is the somewhat opaque (my_clock is a test polymer component that works 100% as a web app):
Breaking on exception: Unsupported operation: Unsupported uri scheme chrome-extension for library LibraryMirror on 'my_clock'.

This isn't even a partial answer, but it may be helpful to others...
The csp lines have a common typo. Don't write:
csp: 'true'
This is correct (the same fix applies to checked: true) :
csp: true
And remove this line from the manifest:
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
The search continues :)

here is a basic example with polymer dart
https://github.com/dart-gde/dart-chrome-app-samples/tree/master/chrome-app-with-polymer-dart
EDIT: you need in your pubspec.yaml to have these
transformers:
- polymer:
entry_points: web/index.html
csp: true
- chrome
- $dart2js:
csp: true
and remove content_security_policy from your manifest.json
this should works

Related

I added a Content-Security-Policy but still the security warning appears

I added a Content-Security-Policy as suggested here: https://www.electronjs.org/docs/tutorial/security#6-define-a-content-security-policy and here: https://content-security-policy.com/examples/electron/
<html lang="en">
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Electron App</title>
</head>
<body>
<span>Our new Electron app</span>
<div id="root"></div>
</body>
</html>
But still I get this message:
“Electron Security Warning (Insecure Content-Security-Policy). This renderer process has either no Content Security Policy set or a policy with “unsafe-eval” enabled. This exposes users of this app to unnecessary security risks. This warning will not show up once the app is packaged.”
How to solve this security warning?
This is intended behaviour, as it says it will trigger on unset or set policy allowing unsafe-evals. They simply want you to make sure to not add any evals without being 100% sure.
For why this is only displayed when building it's only the case if you build your application and your binary is still called "electron".
Add script-src 'self' to the CSP:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self';">
It should fix the issue. It's a feature of Electron security parser - it does not know abt fallback so thinks that script-src is absent, nitty-gritty is here
You can simply add this environment variable to your package.json.
{
"scripts": {
"electron": "ELECTRON_DISABLE_SECURITY_WARNINGS=true electron ."
}
}
Least two ways to disable CSP : no package.json
Disable through CLI
Consider running Electron's app source file main.js within CLI as so: ELECTRON_DISABLE_SECURITY_WARNINGS=true npx electron main.js
Hereby using npx I did consider you was clever and installed Electron locally beforehand .
Disable through the process
Define anywhere (top-level would be at best) the following process.env['ELECTRON_DISABLE_SECURITY_WARNINGS']=true
info taken from
After a lot of days searching for the solution I found at VScode sources a function when app is ready
w.protocol.registerHttpProtocol(I.Schemas.vscodeRemoteResource, (Pe, Le) => {
Le({ url: Pe.url.replace(/^vscode-remote-resource:/, 'http:'), method: Pe.method })
})
So you need a Protocol to replace to http and you have to register as privileged for example
protocol.registerSchemesAsPrivileged([{ scheme: 'server', privileges: { bypassCSP: true } }])
/*----*/
app.whenReady().then(() => {
protocol.registerHttpProtocol('server', (request, response: any) => {
const redirect: any = {
method: request.method,
url: request.url.replace(/^remote:/, 'http:')
}
if (request.method === 'POST' || request.method === 'PUT') {
redirect.uploadData = {
contentType: 'application/json',
data: request.uploadData ? request.uploadData[0].bytes.toString() : ''
}
}
response(redirect)
})
})
And then, when you make a resquest server://localhost:3000/api you don't will get the error CSP - Content-Security-Policy

Why do none of my plugins work for Apache Cordova?

I am using cordova to load plugins into my app. Here is the simplified reproduceable issue:
cordova create foo
cordova plugin add pluginname --save
cordova platform add android --save
cordova build android --verbose
I can run this app using phonegap and see it on my phone. The app reports deviceready as the basic starter app is supposed to. All looks great so far.
If I look in the plugin folder I can see my plugin there. In this case my plugin is called bluetoothle.
I edit the index.js file at a location that fires after the deviceready occurs and add "alert ( typeof (bluetoothle));"
I expect that when the alert fires it should report "object". It does not do this. It reports "undefined".
I have tried this with several other plugins and I always get the same result. So it would seem that no matter what plugin I install I cannot access any of the functions within the plugin.
I do have the same Problem. But I'm using the Phonegap CLI. And the following plugin: https://github.com/randdusing/cordova-plugin-bluetoothle
I add the plugin using the command:
$ phonegap plugin add cordova-plugin-bluetoothle
I've added platform android and ios.
So in the plugins folder there is the cordova-plugin-bluetoothle folder most probably being a valid plugin packet.
Also in the plugins folder there is the android.json and ios.json file containing the section:
"cordova-plugin-bluetoothle": {
"PACKAGE_NAME": "com.phonegap.helloworld"
},
in plaforms/android there is the android.json file containing:
{
"xml": "<feature name=\"BluetoothLePlugin\"><param name=\"android-package\" value=\"com.randdusing.bluetoothle.BluetoothLePlugin\" /></feature>",
"count": 1
},
in platforms/ios there is the ios.json file containing:
{
"xml": "<feature name=\"BluetoothLePlugin\"><param name=\"ios-package\" value=\"BluetoothLePlugin\" /></feature>",
"count": 1
},
I've targeted Android SDK API 23. As the readme tells...
As I have just modified the hello-world example to call bluetoothle initialize on after the deviceready event has fired.
So where could the problem be so that the bluetoothle variable is not defined in the index.js code, when the device is ready?
So here the complete code of index.js:
var bluetoothle;
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
console.log("platform: " + device.platform);
if(bluetoothle) {
console.log("bluetooth is not defined!");
} else {
console.log("bluetooth is not defined!");
}
console.log("yhea managed to initialize Bluetooth LE!");
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
And the complete code of index.html:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
<!-- Good default declaration:
* gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
* https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
* Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
* Enable inline JS: add 'unsafe-inline' to default-src
* Enable eval(): add 'unsafe-eval' to default-src
* Create your own at http://cspisawesome.com
-->
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: 'unsafe-inline' https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *" /> -->
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
</head>
<body>
<div class="app">
<h1>PhoneGap</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
Sooo,
The Issue I had before I just "worked around" by using a different Plugin for my Bluetooth Low Energy stuff.
Later I ran into the same Problem again with another Plugin.
And then I finally got the picture where it all makes sense:
I was mainly using the Phonegap Developer App to test on-the-fly.
The Phonegap Developer App comes bundled with all the Core Plugins and some others.
!! Those plugins which are not bundled already, will never be accessible for your Phonegap Developer App for testing !!
phonegap plugin add cordova-plugin-new-unbundled
Will not make it available to the App. Only download and prebuild the files for a potential real build.
To make this work in the Phonegap Developer App you would need to build your own Phonegap Developer App adding the Plugins you need.
Otherwise your Plugins are only available in a real build.

Polymer elements not working after pub build - Did I forget something?

so my Polymer.Dart project is running fine in Chromium (running on Dart code) but when I pub upgrade and pub build the sampler-scaffold keeps working but paper-button, paper-dialog, paper-progress... elements are just not showing up!
My HTML file looks like this
<link href='http://fonts.googleapis.com/css?family=Droid+Serif|Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="import" href="packages/paper_elements/paper_button.html">
<link rel="import" href="packages/paper_elements/paper_dialog_transition.html">
<link rel="import" href="packages/paper_elements/paper_dialog.html">
<link rel="stylesheet" href="css/reset.css"> <!-- CSS reset -->
<link rel="stylesheet" href="css/style.css"> <!-- Resource style -->
...
<paper-button id="infoUPC" class="cd-read-more" raised>Read more</paper-button>
...
<script src="education.dart" type="application/dart"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/main.js"></script> <!-- Resource jQuery -->
<script src="js/modernizr.js"></script> <!-- Modernizr -->
education.dart
import 'package:polymer/polymer.dart';
import 'dart:html';
import 'package:paper_elements/paper_dialog.dart';
main() {
initPolymer().run(() {
Polymer.onReady.then((_) {
querySelector('#infoFHV').onClick.listen(
(_) => toggleDialog('fhv'));
querySelector('#infoUPC').onClick.listen(
(_) => toggleDialog('upc'));
querySelector('#infoTU').onClick.listen(
(_) => toggleDialog('tu'));
});
});
}
toggleDialog(language) =>
(querySelector('paper-dialog[edu=$language]') as PaperDialog)
.toggle();
pubspec.yaml
name: polydart_resume
version: 0.0.1
author: Shady
description: Test app
dependencies:
core_elements: '>=0.3.2 <0.5.0'
custom_element_apigen: ">= 0.1.1 <0.2.0"
polymer: ">=0.14.0 <0.16.0"
web_components: ">=0.9.0 <0.10.0"
paper_elements: ">=0.5.0 <0.6.0"
transformers:
- polymer:
entry_points:
- web/index.html
pub build does not give me any warnings or errors on these files, but I'm surely missing something right?
You have two entry pages index.html and languages.html. Only languages.html calls your custom main() but only index.html is in your pubspec.yaml transformer configuration.
index.html will invoke the default main() method provided by Polymer but not your custom main() because of this script tag
<script type="application/dart">export 'package:polymer/init.dart';</script>
languages.html has the correct script tag
<script type="application/dart" src="languages.dart"></script>
but this doesn't work as expected because languages.html is not listed in your Polymer transformer entry_points configuration
transformers:
- polymer:
entry_points:
# - web/index.html
- web/languages.html
From the comments:
Q: Do you load languages.html from a link in drawer.html (<core-item label="Languages" url="chapters/languages.html"></core-item>)? – Günter Zöchbauer 25 mins ago
A: Yessir thats exactly what I'm doing.
This isn't how one usually develops applications in Dart. You can, but Dart is for SPA (http://en.wikipedia.org/wiki/Single-page_application).
If you load another page from a Dart application this is like launching an entirly different application. Each page (app) loaded this way needs all parts of a Polymer application to work.
Usually in Dart you have only one entry page (entry_point) and when you want to change what is shown to the user (a new view) you replace the content in the current page instead of loading another one (this is for example where Polymer elements are handy for, you just remove one element (view) and add another one).
Dart also has a rather large boilerplate code size which has to be loaded each time you load another page which is rather inefficient.
Because my problem was not really code related but more fundamental, I found a sample project on www.polymer-project.org where one can see a recommended routing method. I find the introduction docs on polymer don't cover this topic good enough...

Unittest polymer.dart with karma

The problem is polymer is not loading. Karma has filters for the files it loads, I'm trying load and initialize polymer to be able to test polymer elements with no success (outside the test environment the code works fine).
Debugging the code in the browser I don't see the polymer.html loaded, and besides the custom element is in the page, they do not have the properties and behavior, and don't have the shadow dom.
What I try to do:
karma.conf.js
/**
* Compile HTML into JS so that they can be used as templates
*/
preprocessors: {
'packages/**/*.html': 'html2js'
},
basePath: '.',
frameworks: ['dart-unittest'],
// list of files / patterns to load in the browser
// all tests must be 'included', but all other libraries must be 'served' and
// optionally 'watched' only.
files: [
'test/*.dart',
{pattern: '**/*.dart', watched: true, included: false, served: true},
'packages/browser/dart.js',
{pattern: 'scripts/**/*.js', included: false},
{pattern: '**/*.html', included: false, served: true},
'packages/polymer/polymer.html'
],
autoWatch: true,
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 5000,
plugins: [
'karma-dart'
]
test_index.html
<!DOCTYPE html>
<html>
<head>
<title>Run Unit Tests</title>
<link rel="import" href="packages/polymer/polymer.html" />
<link rel="import" href="packages/vader/components/window.html" />
</head>
<body>
<script type="text/javascript" src="packages/unittest/test_controller.js"></script>
<script type="application/dart;component=1" src="test_vader_browser.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
test_vader_browser.dart
import 'package:scheduled_test/scheduled_test.dart';
import 'vader/_vader.dart' as vader;
import 'package:polymer/polymer.dart';
#initMethod
main() {
setUp((){
schedule(() => Polymer.onReady);
});
groupSep = ' - ';
vader.runAllTests();
}

Using Polymer in a Dart Chrome App

I am trying to build an app with Dart and Polymer. But polymer scripts seem to be using eval() in web_components/platform.js:32. Has anyone managed to do this? I tried to change CSP but that helped in first place.
Does anyone have a working example?
Regards and Thanks
Robert
EDIT
manifest.json:
{
"name": "Animatr app",
"version": "1",
"author": "Robert Hartung",
"manifest_version": 2,
"icons": {"128": "animatr_icon.png"},
"app": {
"background": {
"scripts": ["background.js"]
}
},
"content_security_policy": "script-src 'self' unsafe-inline;"
}
main.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Animatr app</title>
<link rel="stylesheet" href="animatr_chrome_app.css">
<link rel="import" href="packages/polymer/polymer.html">
</head>
<body>
<script src="packages/chrome/bootstrap.js" defer></script>
<script src="my_chrome_app.dart" type="application/dart;component=1"></script>
</body>
</html>
ERROR:
Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src 'self' chrome-extension-resource:". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback. (chrome-extension://ofkfcbfhgkoglbgldcdokficikimdjji/packages/web_components/platform.js:32)
Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
pubspec.yaml:
name: animatr_app
description: A sample Chrome packaged application
dependencies:
chrome: any
polymer: any
transformers:
- chrome
- polymer:
entry_points:
- app/animatr_chrome_app.html
csp: 'true'
The app does not recognize polymer elements correctly.
I have been struggling with the same issue, trying to run the simple wizard generated polymer app (the one with the counter) as a chrome packaged app.
I have finally managed to at least run the javascript built version of it, trying to understand the csp issues.
For many reason, it sounds like it cannot run native as the packaged app is loaded from the file system and not through pub serve. Loading the unpackaged extension from web/build was not working neither as is. The solution was to load xxx.html_bootstrap.dart.precompiled.js instead of xxx.html_bootstrap.js from the generated html file
What i did was:
remove the chrome transformer as the polymer transformer already replace the dart script reference by a javascript script reference
add csp: true in the polymer transformer option (although it did work without it)
to avoid having to change manually the generated html to load the precompiled.js version, I wrote a simple transformer.
I can then load in Chrome (does not have to be Dartium as it is javascript) the unpacked extension from web/build once I run pub build (release mode needed)
I now simply have this warning:
Deprecation: Automatic generation of output for Content Security
Policy is deprecated and will be removed with the next development
release. Use the --csp option to generate CSP restricted output.
which means likely I would have to find a new hack soon...
You can take a look at https://github.com/dart-lang/spark/tree/master/ide for an example Dart Chrome-Packaged-App. They also make heavily use of Polymer.
Maybe this is related https://github.com/Polymer/polymer/issues/252
It seems this is the related Dart bug https://code.google.com/p/dart/issues/detail?id=17409

Resources