SRI

使用 SRI 从外部 CDN 加载安全的资源。

配置参数

algorithm sha256 sha384 sha512

The algorithm used to calculate the cryptographic hash of the file

Default:
"sha384"
crossorigin anonymous use-credentials

The CORS setting for the file being loaded

Default:
"anonymous"
selector string

The selector to find the elements to add the integrity attribute

Default:
"script[src], link[rel=stylesheet][href]"

Description

SRI (Subresource Integrity) 是一项浏览器特性,用于保护您的网站和用户免受从外部 CDN 加载的被篡改代码的侵害。 它验证浏览器加载的代码与您在构建过程中获得的代码完全相同,没有意外的篡改。 您可以在 MDN 文章 中了解更多关于 SRI 的信息。

该插件会在您的页面中搜索从其他域加载资源的 <script><link rel="stylesheet"> 元素,并自动添加 integritycrossorigin 属性。 例如,如果您有以下代码:

<script src="https://code.jquery.com/jquery-3.7.0.slim.min.js"></script>

该插件会输出以下内容:

<script
  src="https://code.jquery.com/jquery-3.7.0.slim.min.js"
  integrity="sha256-tG5mcZUtJsZvyKAxYLVXrmjKBVLd6VpVccqz/r4ypFE="
  crossorigin="anonymous"
></script>

Installation

在您的 _config.ts 文件中导入此插件以使用它:

import lume from "lume/mod.ts";
import sri from "lume/plugins/sri.ts";

const site = lume();

site.use(sri(/* Options */));

export default site;

Note

请注意,SRI 仅适用于始终返回相同代码的 URL,因此您必须使用保证永远不会更改的 URL。 了解 如何将 SRI 与 jsDelivr 一起使用