data_style_sanitizer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3817b2ce8055b36be47116321a6e62265ae6fdcfbc7c12aa1882f084276bdc6e
4
+ data.tar.gz: b57bf6ca274a8e139379ff502b0958ac465183be180655fc3ef8edd0d1ffe0e7
5
+ SHA512:
6
+ metadata.gz: c0a0239a32f913f42e12604f34646e06c337daf2ea74d58189fb729dcb3346ccc823fdfcc8fafa87f2bbdc19069346fef48f68d17c85fe2169ad11e18d09c8ef
7
+ data.tar.gz: 2584f0c30cd3f3b0d7a63a6d10b73e2c38c5e103d0202d48d3f3ebdacff7c39dd3577344a060ad8b89693d1ae6604b81f588ab12ce149ad4c148ff4ac5e1ef6e
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-04-07
4
+
5
+ - Initial release
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 tedaford
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # DataStyleSanitizer
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/data_style_sanitizer`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ ```bash
14
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
15
+ ```
16
+
17
+ If bundler is not being used to manage dependencies, install the gem by executing:
18
+
19
+ ```bash
20
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/data_style_sanitizer.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,50 @@
1
+ # lib/data_style_sanitizer/middleware.rb
2
+ require "nokogiri"
3
+ require "digest"
4
+
5
+ class DataStyleSanitizer
6
+ def initialize(app)
7
+ @app = app
8
+ end
9
+
10
+ def call(env)
11
+ status, headers, response = @app.call(env)
12
+
13
+ if html_response?(headers)
14
+ body = response.body.join
15
+ doc = Nokogiri::HTML(body)
16
+ style_map = {}
17
+
18
+ doc.css("[data-style]").each do |el|
19
+ style = el["data-style"].strip
20
+ class_name = "ds-#{Digest::MD5.hexdigest(style)[0..6]}"
21
+ el.remove_attribute("data-style")
22
+ el["class"] = [el["class"], class_name].compact.join(" ")
23
+ style_map[class_name] ||= style
24
+ end
25
+
26
+ if style_map.any?
27
+ nonce = extract_nonce(doc)
28
+ style_tag = Nokogiri::XML::Node.new("style", doc)
29
+ style_tag["nonce"] = nonce if nonce
30
+ style_tag.content = style_map.map { |klass, style| ".#{klass} { #{style} }" }.join("\n")
31
+ doc.at("head") << style_tag
32
+ end
33
+
34
+ response = [doc.to_html]
35
+ end
36
+
37
+ [status, headers, response]
38
+ end
39
+
40
+ private
41
+
42
+ def html_response?(headers)
43
+ headers["Content-Type"]&.include?("text/html")
44
+ end
45
+
46
+ def extract_nonce(doc)
47
+ meta = doc.at('meta[name="csp-nonce"]')
48
+ meta["content"] if meta
49
+ end
50
+ end
@@ -0,0 +1,65 @@
1
+ require "nokogiri"
2
+ require "securerandom"
3
+ require "digest"
4
+
5
+ module DataStyleSanitizer
6
+ class Processor
7
+ def initialize(html, nonce:)
8
+ @doc = Nokogiri::HTML::DocumentFragment.parse(html)
9
+ @nonce = nonce
10
+ @styles = {}
11
+ end
12
+
13
+ def process
14
+ extract_styles
15
+ inject_style_block
16
+ @doc.to_html
17
+ end
18
+
19
+ private
20
+
21
+ def extract_styles
22
+ @doc.css("[data-style]").each_with_index do |node, i|
23
+ style_string = node.get_attribute("data-style")
24
+ class_name = generate_class_name(style_string)
25
+
26
+ # Apply class and remove attribute
27
+ node.remove_attribute("data-style")
28
+ node.set_attribute("class", [node.get_attribute("class"), class_name].compact.join(" "))
29
+
30
+ # Store unique styles
31
+ @styles[class_name] ||= style_string
32
+ end
33
+ end
34
+
35
+ def generate_class_name(style_string)
36
+ hash = Digest::SHA256.hexdigest(style_string)[0..7]
37
+ "ds-#{hash}"
38
+ end
39
+
40
+ def inject_style_block
41
+ return if @styles.empty?
42
+
43
+ # Create the <style> tag
44
+ style_tag = Nokogiri::XML::Node.new("style", @doc)
45
+ style_tag["nonce"] = @nonce
46
+
47
+ # Generate CSS rules
48
+ css_rules = @styles.map do |class_name, rule|
49
+ rule_lines = rule.split(";").map(&:strip).reject(&:empty?)
50
+ rule_lines.map! { |line| "#{line.strip} !important;" } # Ensure override
51
+ ".#{class_name} { #{rule_lines.join(" ")} }"
52
+ end.join("\n")
53
+
54
+ style_tag.content = css_rules
55
+
56
+ # Add the <style> tag to the <head> if it exists, otherwise to the root
57
+ head = @doc.at_css("head")
58
+ if head
59
+ head.add_child(style_tag)
60
+ else
61
+ @doc.add_child(style_tag)
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DataStyleSanitizer
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "data_style_sanitizer/processor"
4
+ require "data_style_sanitizer/railtie" if defined?(Rails)
5
+ require_relative "data_style_sanitizer/version"
6
+
7
+ module DataStyleSanitizer
8
+ class Error < StandardError; end
9
+
10
+ class << self
11
+ def process(html, nonce:)
12
+ Processor.new(html, nonce: nonce).process
13
+ end
14
+ end
15
+ end
data/lib/railtie.rb ADDED
@@ -0,0 +1,42 @@
1
+ module DataStyleSanitizer
2
+ class Railtie < Rails::Railtie
3
+ initializer "data_style_sanitizer.middleware" do |app|
4
+ app.middleware.insert_after ActionDispatch::ContentSecurityPolicy::Middleware, Middleware
5
+ end
6
+ end
7
+
8
+ class Middleware
9
+ def initialize(app)
10
+ @app = app
11
+ end
12
+
13
+ def call(env)
14
+ status, headers, response = @app.call(env)
15
+
16
+ if headers["Content-Type"]&.include?("text/html")
17
+ body = ""
18
+ response.each { |part| body << part }
19
+
20
+ nonce = env["secure_headers_nonce"] || extract_nonce(env)
21
+
22
+ new_body = DataStyleSanitizer.sanitize_html(body, nonce: nonce)
23
+ headers["Content-Length"] = new_body.bytesize.to_s
24
+
25
+ [status, headers, [new_body]]
26
+ else
27
+ [status, headers, response]
28
+ end
29
+ end
30
+
31
+ private
32
+
33
+ def extract_nonce(env)
34
+ # Customize based on how you expose CSP nonce
35
+ if env["action_dispatch.content_security_policy_nonce"]
36
+ env["action_dispatch.content_security_policy_nonce"].call
37
+ else
38
+ SecureRandom.base64(16) # fallback
39
+ end
40
+ end
41
+ end
42
+ end
metadata ADDED
@@ -0,0 +1,85 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: data_style_sanitizer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - tedaford
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-04-07 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: nokogiri
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: securerandom
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: This is a gem that converts data-style attributes into CSP-compliant
42
+ nonced style blocks. It is designed to work with Rails applications and provides
43
+ a simple interface for sanitizing HTML content.
44
+ email:
45
+ - daturafarms@gmail.com
46
+ executables: []
47
+ extensions: []
48
+ extra_rdoc_files: []
49
+ files:
50
+ - CHANGELOG.md
51
+ - LICENSE.txt
52
+ - README.md
53
+ - lib/data_style_sanitizer.rb
54
+ - lib/data_style_sanitizer/middleware.rb
55
+ - lib/data_style_sanitizer/processor.rb
56
+ - lib/data_style_sanitizer/version.rb
57
+ - lib/railtie.rb
58
+ homepage: https://github.com/tedaford/data_style_sanitizer
59
+ licenses:
60
+ - MIT
61
+ metadata:
62
+ allowed_push_host: https://rubygems.org
63
+ homepage_uri: https://github.com/tedaford/data_style_sanitizer
64
+ source_code_uri: https://github.com/tedaford/data_style_sanitizer
65
+ changelog_uri: https://github.com/tedaford/data_style_sanitizer/blob/master/CHANGELOG.md
66
+ post_install_message:
67
+ rdoc_options: []
68
+ require_paths:
69
+ - lib
70
+ required_ruby_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: 3.1.0
75
+ required_rubygems_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ requirements: []
81
+ rubygems_version: 3.4.19
82
+ signing_key:
83
+ specification_version: 4
84
+ summary: Converts data-style attributes into CSP-compliant nonced style blocks
85
+ test_files: []