Rspack 源码解析(三十八):SubresourceIntegrityPlugin 如何跨四个插件协作生成 integrity

本篇是 Rspack 源码解析系列第三十八篇。Subresource Integrity(SRI)是浏览器安全特性:给 <script>/<link> 标签加 integrity 属性,浏览器校验资源哈希是否匹配。本文进入 crates/rspack_plugin_sri,重点看它如何同时 tap 三个其他插件(RealContentHashPlugin、RuntimePlugin、HtmlRspackPlugin)的 Hook,完成「算 hash → 写 runtime → 注入 html」的跨插件协作。

前言:SRI 需要多个插件配合

SRI 的 integrity 值依赖最终产物内容,但产物内容又是在多个阶段逐步生成的:

text 复制代码
1. 算 hash:需要 RealContentHashPlugin 的 update_hash 时机
2. 写 runtime:需要 RuntimePlugin 的 create_script / create_link
3. 注入 html:需要 HtmlRspackPlugin 的 before_asset_tag_generation

所以 SRI 插件不是一个独立流程,而是「寄生」在三个已有插件上的协作层。这是理解本文的关键。

源码入口:模块划分

crates/rspack_plugin_sri/src/lib.rs 拆了五个模块:

rust 复制代码
mod asset;      // process_assets 阶段算 hash、更新 integrity
mod config;     // 选项与编译上下文
mod html;       // 注入 html 标签
mod integrity;  // hash 函数定义
mod runtime;    // 写 runtime 的 create_script/create_link
mod util;

每个模块对应一个协作点。

全局状态:两个 LazyLock map

和 RealContentHashPlugin 一样,SRI 用全局 map 按编译 ID 存状态:

rust 复制代码
static COMPILATION_INTEGRITY_MAP: CompilationIntegrityMap = LazyLock::new(Default::default);
static COMPILATION_CONTEXT_MAP: LazyLock<FxDashMap<CompilationId, Arc<SRICompilationContext>>> =
  LazyLock::new(Default::default);

COMPILATION_INTEGRITY_MAP 存「asset 名 → integrity 值」,COMPILATION_CONTEXT_MAP 存编译上下文(fs、output_path、cross_origin_loading、runtime 模板)。

handle_compilation:三个插件的 Hook 都 tap 上

handle_compilation 是协作的核心,在 this_compilation 阶段执行:

rust 复制代码
#[plugin_hook(CompilerThisCompilation for SubresourceIntegrityPlugin, stage = -10000)]
async fn handle_compilation(&self, compilation: &mut Compilation, _params: &mut CompilationParams) -> Result<()> {
  let ctx = SRICompilationContext {
    fs: compilation.output_filesystem.clone(),
    output_path: compilation.options.output.path.clone(),
    cross_origin_loading: compilation.options.output.cross_origin_loading.clone(),
    runtime_template: compilation.runtime_template.create_module_code_template(),
  };
  SubresourceIntegrityPlugin::set_compilation_sri_context(compilation.id(), ctx);

  // 1. tap RealContentHashPlugin 的 update_hash
  {
    let real_content_hash_plugin_hooks = RealContentHashPlugin::get_compilation_hooks_mut(compilation.id());
    let mut real_content_hash_plugin_hooks = real_content_hash_plugin_hooks.borrow_mut();
    real_content_hash_plugin_hooks.update_hash.tap(update_hash::new(self));
  }

  // 2. tap RuntimePlugin 的 create_script / create_link / link_preload
  {
    let runtime_plugin_hooks = RuntimePlugin::get_compilation_hooks_mut(compilation.id());
    let mut runtime_plugin_hooks = runtime_plugin_hooks.borrow_mut();
    runtime_plugin_hooks.create_script.tap(create_script::new(self));
    runtime_plugin_hooks.create_link.tap(create_link::new(self));
    runtime_plugin_hooks.link_preload.tap(link_preload::new(self));
  }

  // 3. tap HtmlRspackPlugin 的 before_asset_tag_generation / alter_asset_tag_groups
  if matches!(self.options.html_plugin, IntegrityHtmlPlugin::NativePlugin) {
    let html_plugin_hooks = HtmlRspackPlugin::get_compilation_hooks_mut(compilation.id());
    let mut html_plugin_hooks = html_plugin_hooks.borrow_mut();
    html_plugin_hooks.before_asset_tag_generation.tap(before_asset_tag_generation::new(self));
    html_plugin_hooks.alter_asset_tag_groups.tap(alter_asset_tag_groups::new(self));
  }

  Ok(())
}

stage = -10000 保证 SRI 的 this_compilation 先于其他插件执行,这样它能先把自己的 tap 挂到别的 Hook 上。

update_hash:复用 RealContentHash 的时机

第 37 篇讲过 update_hash Hook。SRI 的 update_hash 在它之上算 integrity:

rust 复制代码
// asset.rs
pub async fn update_hash(...) -> Result<Option<String>> {
  // 对 asset 内容用指定的 hash 函数(如 sha256/sha384/sha512)做 digest
  // 返回 integrity 字符串,如 "sha256-xxx"
}

这样 integrity 的计算就复用了 RealContentHashPlugin 已经算好的「最终内容」时机,保证 hash 基于真实产物。

cross_origin_loading 校验

handle_compilation 里有一处诊断:

rust 复制代码
if matches!(compilation.options.output.cross_origin_loading, CrossOriginLoading::Disable) {
  compilation.push_diagnostic(Diagnostic::error(
    "SubresourceIntegrity".to_string(),
    "Subresource integrity is not applied to async chunks because the \"output.crossOriginLoading\" option is not set.".to_string(),
  ));
}

SRI 需要 crossOriginLoading 才能对异步 chunk 生效,没配置就报错。

apply:多条件分流

apply 展示了插件如何按编译配置分流:

rust 复制代码
impl Plugin for SubresourceIntegrityPlugin {
  fn apply(&self, ctx: &mut rspack_core::ApplyContext<'_>) -> Result<()> {
    if self.validate_error.is_some() {
      ctx.compiler_hooks.this_compilation.tap(validate_error::new(self));
      return Ok(());
    }
    if let ChunkLoading::Enable(chunk_loading) = &ctx.compiler_options.output.chunk_loading
      && matches!(chunk_loading, ChunkLoadingType::Require | ChunkLoadingType::AsyncNode) {
      ctx.compiler_hooks.this_compilation.tap(warn_non_web::new(self));
      return Ok(());
    }
    ctx.compilation_hooks.process_assets.tap(handle_assets::new(self));
    ctx.compilation_hooks.after_process_assets.tap(detect_unresolved_integrity::new(self));
    ctx.compiler_hooks.this_compilation.tap(handle_compilation::new(self));
    ctx.compilation_hooks.additional_tree_runtime_requirements.tap(handle_runtime::new(self));
    Ok(())
  }
}

三种情况:

  1. 配置校验失败 → 只 tap validate_error 报错;
  2. 非 web 目标(Require/AsyncNode)→ 只 tap warn_non_web 警告;
  3. 正常 web → tap 完整链路(process_assets 算 hash、this_compilation 挂协作 Hook、runtime 写加载)。

runtime.rs 的 create_script 和 create_link 把 integrity 写进 runtime 模板。create_link 对应 CSS 的 <link>,create_script 对应 JS 的 <script>。它们从 COMPILATION_INTEGRITY_MAP 取 integrity 值,拼进标签。

html:注入标签

html.rs 的 before_asset_tag_generation 和 alter_asset_tag_groups 在 HtmlRspackPlugin 生成标签时,把 integrity 属性附加到对应的 <script>/<link> 上。这是 SRI 对静态 HTML 产物的最后一步。

Rust 角度:插件间的 Hook 依赖图

SRI 是理解 Rspack 插件协作最好的例子:

text 复制代码
SubresourceIntegrityPlugin
  ├─ tap RealContentHashPlugin.update_hash   (算 integrity 的时机)
  ├─ tap RuntimePlugin.create_script/link    (动态 runtime 注入)
  └─ tap HtmlRspackPlugin.before/alter       (静态 html 注入)

插件不是孤立的,而是通过「别人暴露的编译级 Hook」互相织入。get_compilation_hooks_mut(id) 这种全局 map 模式让插件能安全地拿到别的插件的 Hook,AtomicRefCell / RwLock 保证并发安全。

这一篇应该带走什么

  1. SRI 寄生在三个插件上:RealContentHash(算 hash)、Runtime(写 runtime)、Html(注入标签);
  2. get_compilation_hooks_mut + 全局 map 是插件间协作的标准模式;
  3. stage = -10000 让 SRI 先挂好 Hook;
  4. apply 按 validate_error / 非 web / 正常 三种情况分流;
  5. crossOriginLoading 未配置时 SRI 对异步 chunk 无效。

写在最后

跨插件协作讲完了。下一篇转向一类「防御性」插件------rspack_plugin_case_sensitive 和 rspack_plugin_circular_dependencies,看 Rspack 如何在 seal / emit 阶段检测大小写冲突和循环依赖,给出诊断警告。

相关推荐
Amos_Web31 分钟前
通过 Rspack 源码学 Rust(八):struct 保存数据,impl 定义怎样使用数据
前端
anyup1 小时前
2027 年初,uni-app App 端停更倒计时,老项目该何去何从?
前端·vue.js·uni-app
JudithHuang2 小时前
Vue3 Vitest 单元测试进阶
前端·单元测试·log4j·vue
费曼学习法3 小时前
把 Agent 可观测性做进 Harness:从日志里只有 task finished 到全链路回放
前端
GuWenyue3 小时前
z-index 写到 9999 还是被盖住:把层叠上下文的 6 个反例全复现了一遍
前端·css·浏览器
htzyl2063 小时前
TypeScript:tsconfig配置误区及详情介绍,让你清清楚楚
前端·typescript
不服老的小黑哥3 小时前
0b · M2:服务化 + SSE 流式
前端
梦曦i3 小时前
0.9.0 新增页面级 style 支持
前端·uni-app x
不服老的小黑哥3 小时前
10a · M1:命令行 Agent
前端