about summary refs log tree commit diff
path: root/lib
diff options
context:
space:
mode:
authorEugen Rochko <eugen@zeonfederated.com>2020-11-06 11:56:31 +0100
committerGitHub <noreply@github.com>2020-11-06 11:56:31 +0100
commit9b1f2a4b61660f9a8be62f6296d97a856e376059 (patch)
treedd60029f03394a924d7168277582f0e6c835a9a1 /lib
parent68d4b2b83e124719f8473489ee8c1743ca848dc4 (diff)
Add subresource integrity for JS and CSS assets (#15096)
Fix #2744
Diffstat (limited to 'lib')
-rw-r--r--lib/webpacker/helper_extensions.rb20
-rw-r--r--lib/webpacker/manifest_extensions.rb17
2 files changed, 37 insertions, 0 deletions
diff --git a/lib/webpacker/helper_extensions.rb b/lib/webpacker/helper_extensions.rb
new file mode 100644
index 000000000..8f46d7631
--- /dev/null
+++ b/lib/webpacker/helper_extensions.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module Webpacker::HelperExtensions
+  def javascript_pack_tag(name, **options)
+    src, integrity = current_webpacker_instance.manifest.lookup!(name, type: :javascript, with_integrity: true)
+    javascript_include_tag(src, options.merge(integrity: integrity))
+  end
+
+  def stylesheet_pack_tag(name, **options)
+    src, integrity = current_webpacker_instance.manifest.lookup!(name, type: :stylesheet, with_integrity: true)
+    stylesheet_link_tag(src, options.merge(integrity: integrity))
+  end
+
+  def preload_pack_asset(name, **options)
+    src, integrity = current_webpacker_instance.manifest.lookup!(name, with_integrity: true)
+    preload_link_tag(src, options.merge(integrity: integrity))
+  end
+end
+
+Webpacker::Helper.prepend(Webpacker::HelperExtensions)
diff --git a/lib/webpacker/manifest_extensions.rb b/lib/webpacker/manifest_extensions.rb
new file mode 100644
index 000000000..789eb81cc
--- /dev/null
+++ b/lib/webpacker/manifest_extensions.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module Webpacker::ManifestExtensions
+  def lookup(name, pack_type = {})
+    asset = super
+
+    if pack_type[:with_integrity] && asset.respond_to?(:dig)
+      [asset.dig('src'), asset.dig('integrity')]
+    elsif asset.respond_to?(:dig)
+      asset.dig('src')
+    else
+      asset
+    end
+  end
+end
+
+Webpacker::Manifest.prepend(Webpacker::ManifestExtensions)