服务工作者提供服务时,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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)