本篇是 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(())
}
}
三种情况:
- 配置校验失败 → 只 tap
validate_error报错; - 非 web 目标(Require/AsyncNode)→ 只 tap
warn_non_web警告; - 正常 web → tap 完整链路(process_assets 算 hash、this_compilation 挂协作 Hook、runtime 写加载)。
runtime:create_script / create_link
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 保证并发安全。
这一篇应该带走什么
- SRI 寄生在三个插件上:RealContentHash(算 hash)、Runtime(写 runtime)、Html(注入标签);
get_compilation_hooks_mut+ 全局 map 是插件间协作的标准模式;stage = -10000让 SRI 先挂好 Hook;apply按 validate_error / 非 web / 正常 三种情况分流;- crossOriginLoading 未配置时 SRI 对异步 chunk 无效。
写在最后
跨插件协作讲完了。下一篇转向一类「防御性」插件------rspack_plugin_case_sensitive 和 rspack_plugin_circular_dependencies,看 Rspack 如何在 seal / emit 阶段检测大小写冲突和循环依赖,给出诊断警告。