服务工作者提供服务时,JS文件中缺少CSP标头而CSS没有

如何解决服务工作者提供服务时,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阻止了:

enter image description here

当我进一步检查时,服务工作者提供的CSS文件仍然具有CSP标头(并且内部的nonce也已更改为新值,create-react-app对我们有用吗?),它们加载得很好。

enter image description here

但是,缺少JS文件上的CSP标头,该标头被阻止了。

enter image description here

任何指南都会有所帮助。谢谢!


更新

我在Chrome中注意到一件事,它显示了

注意:显示的是临时标题

我在以下位置找到了更多信息

"CAUTION: provisional headers are shown" in Chrome debugger

我发现的另一件事是,在注册服务工作者(内部使用create {react-app使用Workbox)后,在Chrome和Safari上的第二次调用不会加载该页面。

对于Firefox,尽管从缓存中读取时JS和CSS文件中均未显示CSP标头,但Firefox仍可以显示该页面。

enter image description here

解决方法

第一次加载该页面时,可能会导致CSP中的随机数与脚本标记同步。在第二次加载时,它们不再存在或未在脚本标记中同步。检查CSP标头和内联脚本标签中的nonce值的差异。

CSP适用于在浏览器中呈现的页面(内容类型:“文本/ html”),对加载的其他资源进行设置时,它没有任何作用。 js文件上缺少CSP标头没有任何影响。之所以包含您的CSS文件,是因为您包括了“ style-src'self'”,因此也应将其添加到script-src中。如果还不够,可以在开发中添加localhost:5000。

,
  1. 正如上面的Halvor Sakshaug所指出的,您不需要为带有CSP标头的JS / CSS提供服务,CSP仅适用于具有 document 属性的页面/代码。

  2. 从您的Chrome控制台警告中可以看出,至少有两个问题:

  • 内联脚本被阻止(您确实在某处使用 )。因此,您必须将'unsafe-inline'添加到 script-src (或将nonce ='server_genic_value'属性添加到

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-