Using Polymer in a Dart Chrome App - dart

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

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

Referencing in style.css to sdk definition e.g. color.dart

Having a polymer project using the material color definitions in import 'package:polymer_elements/color.dart'; The references to css styling e.g. var(--paper-green-300); works ok, when they are placed in the <style></style> section for the element, but when I move this to the style.css, they aren't found. I have tried with different combinations of include in index.html and index.dart. E.g. in index.html at <head> section <link rel="import" href="packages/polymer_elements/color.html"> but doesn't seems to do the trick. Anyone who have experience with similar issues?
Of course not a high prio project killer, simple to use the hard coded values or leave the definitions in the <style> section for every element. But this way things will be more tidy.
Environment
Dart version 1.14.0
WebStorm 11.0.3
From pubspec.yaml:
environment:
sdk: '>=1.9.0 <2.0.0'
dependencies:
polymer: ^1.0.0-rc.15
web_components: ^0.12.0
polymer_elements: 1.0.0-rc.8
browser: ^0.10.0
reflectable: ^0.5.0
polymer_interop: ^1.0.0-rc.5
CSS variables in Polymer only work in <style is="custom-style"> and therefore not in .css files.
is="custom-style" is implicit for style tags within Polymer elements and can and should be omitted.

Polymer, Dart, Chrome App, CSP and debugging

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

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...

I'm getting `GET http://localhost:4567/my_app.dart.js 404 (Not Found) ` in Chrome, but works fine in Dartium

I'm trying to get my dummy Dart webapp running in browsers. Here's the code of my html page:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<!-- Always force latest IE rendering engine or request Chrome Frame -->
<meta content='IE=edge,chrome=1' http-equiv='X-UA-Compatible'>
</head>
<body>
<div id='button'>hello world</div>
</body>
<script src='my_app.dart' type='application/dart'></script>
<script src='packages/browser/dart.js'></script>
</html>
and this is what I'm getting in js console when trying to open it:
GET http://localhost:4567/my_app.dart.js 404 (Not Found)
(I'm running it on a local server, thus the url - got the same error if simply opening an html file though).
If I open the same url in Dartium, the webapp works. So the problem, I suppose, is that dart.js doesn't work as expected. What could be the problem?
packages/browser/dart.js is a bootstrap script that checks if a Dart VM is available on your browser. If a Dart VM is available, your dart script is executed directly, otherwise packages/browser/dart.js appends to the document a new js script with a url that points to a file with the same name as your dart file but with a appended .js. Depending on how you work you may have to generate this JS file manually with dart2js :
dart2js --out=my_app.dart.js my_app.dart
Try to "Run as Java Script" it should generate additional files like "my_app.dart.js"

Resources