Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rack middleware for proofing HTML at runtime #512

Merged
merged 5 commits into from
Jun 16, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions lib/html-proofer/middleware.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@


module HTMLProofer
class Middleware

def self.options
@options ||= {
type: :file,
allow_missing_href: true, # Permitted in html5
allow_hash_href: true,
check_external_hash: true,
check_html: true,
url_ignore: [/.*/], # Don't try to check local files exist
}
end

def initialize(app)
@app = app
end

HTML_SIGNATURE = [
'<!DOCTYPE HTML',
'<HTML',
'<HEAD',
'<SCRIPT',
'<IFRAME',
'<H1',
'<DIV',
'<FONT',
'<TABLE',
'<A',
'<STYLE',
'<TITLE',
'<B',
'<BODY',
'<BR',
'<P',
'<!--'
]
DanielHeath marked this conversation as resolved.
Show resolved Hide resolved

def call(env)
result = @app.call(env)
return result if env['REQUEST_METHOD'] != 'GET'
return result if env['QUERY_STRING'] =~ /SKIP_VALIDATION/
return result if result.first != 200

# [@status, @headers, @response]
body = []
result.last.each { |e| body << e }
html = body.join('').lstrip
if HTML_SIGNATURE.any? { |sig| html.downcase.starts_with? sig.downcase }
parsed = HTMLProofer::Runner.new(
'response',
Middleware.options
).check_parsed(
Nokogiri::HTML(Utils.clean_content(html)), 'response'
)

if parsed[:failures].length > 0
raise "HTML Validation errors (skip by adding ?SKIP_VALIDATION to URL): \n#{parsed[:failures].join("\n")}"
end
end
result
end
end
end
DanielHeath marked this conversation as resolved.
Show resolved Hide resolved
7 changes: 5 additions & 2 deletions lib/html-proofer/runner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,8 @@ def process_files
end
end

def check_path(path)
def check_parsed(html, path)
result = { external_urls: {}, failures: [] }
html = create_nokogiri(path)

@src = [@src] if @type == :file

Expand All @@ -112,6 +111,10 @@ def check_path(path)
result
end

def check_path(path)
check_parsed create_nokogiri(path), path
end

def validate_urls
url_validator = HTMLProofer::UrlValidator.new(@logger, @external_urls, @options)
@failures.concat(url_validator.run)
Expand Down