WeChat - Feature policy violation: accelerometer is not allowed in this document - angular6

From Angular application we're using on WeChat the last Tencent Captcha API and this error appear in DevTools console (on desktop - windows - Chrome webkit):
[Violation] Feature policy violation: accelerometer is not allowed in this
document.
Unfortunately, there isn't more stacktraces.
It seems Tencent Captcha try to use through iframe the accelerometer browser API which is not allowed from our website. We need to add an HTTP header like 'Feature-Policy : accelerometer ...'
https://developer.mozilla.org/en-US/docs/Web/API/Accelerometer
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy
I don't know where we should add this http header
thks

In your application server you should add a response header called Feature-Policy with a value of one of the following:
"accelerometer *"
"accelerometer 'self'"
"accelerometer 'src'"
The exact allowList argument you provide following accelerometer will depend on your specific circumstances and requirements (re. MDN docs - Feature-Policy: Syntax).
In an application using an Express server, the response header can be set by adding this line in a piece of middleware:
response.set('Feature-Policy', "accelerometer 'self'"
e.g.
// app.js
import express from 'express';
import applyFeaturePolicyHeaderMiddleware from './apply-feature-policy-header-middleware';
const app = express();
app.use(
applyFeaturePolicyHeaderMiddleware
);
// apply-feature-policy-header-middleware.js
export default (request, response, next) => {
response.header('Feature-Policy', "accelerometer 'self'");
next();
}
You can then ensure the Feature Policy is present by checking in the DevTools Network tab that the request for the page document includes the feature-policy header under the Response Headers.

Related

CORS problem requesting a file (ONLY on Google Chrome)

I have a .Net Core API and a React application using BabylonJs to render some 3D models. On my server side I am storing the 3D models that will be requested by the client to render into the scene. In order to do so I have allowed UseFileServer and UseStaticFiles on my .Net Core server. I have also created a Policy to apply for requests that require the CORS policy. The policy that I implemented is the following:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", policyBuilder => policyBuilder
.AllowAnyHeader()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true)
.AllowCredentials());
});
And I am applying it to the requests that target the Static files the following way:
app.UseFileServer(enableDirectoryBrowsing: true);
app.UseStaticFiles(fileOptions);
On the client side the request is being done by the Babylon library the following way:
SceneLoader.ImportMeshAsync(
"",
"http://localhost:9001/resources/objects/",
"sphere.glb",
scene
)
.then((result) => {
result.renderingGroupId = 1;
scene.createDefaultCamera(true, true, true);
scene.activeCamera.alpha += Math.PI;
})
.catch((error) => {
return null;
});
What happens is that I am receiving the following error only on google chrome and not on Firefox neither on Opera.
Also the responses to Firefox and Opera contain the missing header while the response to chrome does not.
Chrome:
Firefox:
Opera:
After some research time I found the solution for my problem. What was causing the issue was not CORS. It looks like Google has made a security upgrade to Chrome that has changed the Referrer-Policy to:
wgile both other browsers remain on:
As so, google only support CORS on https->https sites. After creating a self-signed certificate and open a port for https problem was resolved.

Unable to access cookie in nodeJS after redirected from HTML page

I'm trying to make a post call via an html page. On 2nd application, i'm trying to access a cookie named cookie_test (can be set manually or via code in browser).
Under Application tab(Storage --> cookies), i'm able to see the cookie, but somehow i'm getting undefined in console log when trying to access it from 2nd application (refer 2nd code).
browser cookie screenshot
Application One (test.html is the only file in it & i'm trying to make a post call)
<form action="http://localhost:3000/page-two" method="POST">
<input type="submit" value="Go to P2">
</form>
Application Two (NodeJS/Express:
index.js)
var express = require('express');
var router = express.Router();
router.post('/', function (req, res, next) {
console.log("COOKIE-TEST::::::", req.cookies.cookie_test)
res.render("page_two", { cookie_data: req.cookies.cookie_test });
});
module.exports = router;
Note: Within node application, cookies are accessible & works as expected. Issues seems to happen during redirection.
I was able to solve the issue by setting the cookie parameters as secure(true) & sameSite(none). Make sure to use latest version of express for sameSite property. This setting allowed my 2nd application to access it's cookies, irrespective of getting redirected from any source (in my case Application one).
A couple of things to check.
First, your nodejs app needs the cookie-parser middleware if it is to receive any cookies from users' browsers. It looks like this.
var cookieParser = require('cookie-parser')
...
var express = require('express')
express.use(cookieParser())
...
You didn't mention how you set the cookie from your post route. You would do that like this with a call to res.cookie():
router.post('/', function (req, res, next) {
console.log("COOKIE-TEST::::::", req.cookies.cookie_test)
const testCookieVal = req.cookies.cookie_test || 'some default value'
res.cookie('cookie_test', testCookieVal)
res.render("page_two", { cookie_data: someCookieVal })
});
It's not clear how you set the cookie you're trying to retrieve in your post route. You should understand that your Application One html file is served from the file:// origin, and Application Two is served from the https://localhost:3000 origin. Browsers never send cookies associated with web pages served from one origin in requests to other origins.

Forge Viewer Error

When I open the viewer I get these errors:
Failed to load https://ase.autodesk.com/adp/v1/analytics/upload: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://ontargetapp.local' is therefore not allowed access. The response had HTTP status code 503.
2adp-web-analytics-sdk.min.js:4 OPTIONS https://ase.autodesk.com/adp/v1/analytics/upload 503 (Service Unavailable: Back-end server is at capacity)
How do I solve this?
You do not need to solve this - this is an OPTIONS HTTP request which does not need to be honored - It has no impact on the viewer - This is Autodesk an analytics call.
Yes, just add 'useADP:false' to your load options, like this...
var options = {
env: "Local",
useADP: false,
}
Autodesk.Viewing.Initializer( options, function() {
viewer.start(myURN, options, onSuccess);
});
etc
Reference:
https://github.com/wallabyway/markupExt/blob/6c55e73226a70a61f33bc7f8f021b44a979c32e2/docs/app.js#L14
This will turn off analytics and remove the error you are seeing. Hope that helps!
UPDATED

Cannot run xmlhttprequest in Chrome App : provisional headers & No 'Access-Control-Allow-Origin'

I am building a chrome app sending a Get HTTPRequest to an external API:
I get the answer:
XMLHttpRequest cannot load
http://developer.echonest.com/api/v4/artist/profile?api_key=FILDTEOIK2HBORODV&name=weezer.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'chrome-extension://ihdfphmemcdeadpnjkhpihmcoeiklphe'
is therefore not allowed access.
I did allow the external domain in permissions in my manifest (to prevent blocking in cross domain requests)
When I type the URL in the Address Bar it works perfectly
It seems Chrome is blocking my request, I even tried to load directly the script in an HTML page and it does not work (same message but with origin "null") (oh and it did not allow me to cheat by changing the Origin in the Header).
I also get the famous "Caution : Provisional Headers are shown" in the console, which makes me think Chrome is blocking my request, I looked up on other Stack Overflow Questions but apart running chrome://net-internals and looking for stuff I haven't the first clue about I cannot find any good answers (I did run chrome://net-internals but really can't make any sense out of it).
Here is the request :
function update_stations() {
var xhr = new XMLHttpRequest();
xhr.open("Get","http://developer.echonest.com/api/v4/artist/profile?api_key=FILDTEOIK2HBORODV&name=weezer", true);
xhr.responseType = "json";
xhr.onreadystatechange = function() {
console.log("Essai");
console.log(xhr.readyState);
console.log(xhr);
document.getElementById("resp").innerText = xhr;
}
xhr.send()
}
Any thoughts (would be highly appreciated)?
Cross-Origin XMLHttpRequest chrome developer documentation explains that the host must be listed in the permissions of the manifest file.
I've taken the XHR code from above and included it in the hello world sample. It works after adding the following to the manifest.json.
"permissions": [
"http://*.echonest.com/"
]

Custom 404 error without server

Is possible to intercept 404 error without using web server (browsing html file in the filesystem) ?
I tried with some javascript, using an hidden iframe that preload the destination page and check for the result and then trigger a custom error or redirect to the correct page.
This work fine but is not good on perfomance.
A 404 error is an HTTP status response. So unless you are trying to retrieve this file using an HTTP request/response, you can't have a genuine 404 error. You can only mimic one in something like the way you suggest. Any "standard" way of handling a 404 error is dependent on your flavour of web server anyway...
404 is a HTTP response code, and as such only delivered through the HTTP protocol by servers that speak it. The file:// extension isn't a real protocol response as such, it's a hack built into clients (like browsers) that enable local file support, however it's up to browsers / clients themselves whether they expose any response codes from their file:// implementation. In theory they could report them in the DOM, for example, but they would be response codes exposed to themselves, and as such rarely implemented. Most don't, and there isn't a standard way for it. You may look into browser extensions, like Firefox, and see if they support it, but then, this is highly unstandard and will likely break if you pop it on the web.
Why don't you want to use the server?
I don't believe that it's possible to handle a 404 error client-side, because a 404 error is server-side.
Whenever you load a webpage, you make a request to the server. Thus, when you ask for a file that's not there, it's the server that handles the error. Regular HTML/CSS/JavaScript only come into the picture when the server sends back a response to tell you that it can't find the file.
Steve
Because I was looking for this today. You can now do this without a server by using a Service Worker to cache the custom 404 page, and then serve it when a fetch request status is 404. Following the instructions on the google cache lab, the worker files looks as follows:
const filesToCache = [
'/',
'404.html'
];
const staticCacheName = 'pages-cache-v1';
self.addEventListener('install', event => {
console.log('Attempting to install service worker and cache static assets');
event.waitUntil(
caches.open(staticCacheName).then(cache => {
return cache.addAll(filesToCache);
});
);
});
self.addEventListener('fetch', event => {
console.log('Fetch event for ', event.request.url);
event.respondWith(
caches.match(event.request).then(response => {
if (response) {
console.log('Found ', event.request.url, ' in cache');
return response;
}
console.log('Network request for ', event.request.url);
return fetch(event.request).then(response => {
console.log('response.status:', response.status);
// fetch request returned 404, serve custom 404 page
if (response.status === 404) {
return caches.match('404.html');
}
});
});
);
});