如何解决服务工作者提供服务时,JS文件中缺少CSP标头而CSS没有
我正在使用由create-react-app 3.4.1生成的全新应用程序。它使用默认的服务工作者文件:
// This lets the app load faster on subsequent visits in production,and gives
// it offline capabilities. However,it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page,after all the
// existing tabs open on the page have been closed,since previously cached
// resources are updated in the background.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};
export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(
process.env.PUBLIC_URL,window.location.href
);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load',() => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl,config);
// Add some additional logging to localhost,pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker.'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl,config);
}
});
}
}
function registerValidSW(swUrl: string,config?: Config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point,the updated precached content has been fetched,// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point,everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:',error);
});
}
function checkValidServiceWorker(swUrl: string,config?: Config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl,{
headers: { 'Service-Worker': 'script' }
})
.then(response => {
// Ensure service worker exists,and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl,config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}
我通过将 index.ts 中的代码更改为
来打开服务人员serviceWorker.register();
我托管了yarn build
通过 https 由Express.js服务器生成的静态文件,并通过helmet启用了严格的内容安全策略(CSP)。
helmet({
contentSecurityPolicy: {
directives: {
scriptSrc: [
/* Content Security Policy Level 3 */
"'strict-dynamic'",`'nonce-${cspNonce}'`,/* Content Security Policy Level 2 (backward compatible) */
"'self'",// Workbox
'https://storage.googleapis.com',// ...
],styleSrc: [
"'self'",],// ...
},},})
当我第一次打开页面时,浏览器从服务器获取文件。 JS和CSS都有CSP标头。页面显示良好。
当我第二次打开页面时,文件是从Service Worker加载的。正如我的控制台显示的那样,许多计算机被CSP阻止了:
当我进一步检查时,服务工作者提供的CSS文件仍然具有CSP标头(并且内部的nonce也已更改为新值,create-react-app对我们有用吗?),它们加载得很好。
但是,缺少JS文件上的CSP标头,该标头被阻止了。
任何指南都会有所帮助。谢谢!
更新
我在Chrome中注意到一件事,它显示了
注意:显示的是临时标题
我在以下位置找到了更多信息
"CAUTION: provisional headers are shown" in Chrome debugger
我发现的另一件事是,在注册服务工作者(内部使用create {react-app使用Workbox)后,在Chrome和Safari上的第二次调用不会加载该页面。
对于Firefox,尽管从缓存中读取时JS和CSS文件中均未显示CSP标头,但Firefox仍可以显示该页面。
解决方法
第一次加载该页面时,可能会导致CSP中的随机数与脚本标记同步。在第二次加载时,它们不再存在或未在脚本标记中同步。检查CSP标头和内联脚本标签中的nonce值的差异。
CSP适用于在浏览器中呈现的页面(内容类型:“文本/ html”),对加载的其他资源进行设置时,它没有任何作用。 js文件上缺少CSP标头没有任何影响。之所以包含您的CSS文件,是因为您包括了“ style-src'self'”,因此也应将其添加到script-src中。如果还不够,可以在开发中添加localhost:5000。
,-
正如上面的Halvor Sakshaug所指出的,您不需要为带有CSP标头的JS / CSS提供服务,CSP仅适用于具有 document 属性的页面/代码。
-
从您的Chrome控制台警告中可以看出,至少有两个问题:
- 内联脚本被阻止(您确实在某处使用 或 )。因此,您必须将'unsafe-inline'添加到 script-src (或将nonce ='server_genic_value'属性添加到
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。