allinoneaccessibility 0.0.3 → 1.0.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.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +30 -0
  3. data/LICENSE +21 -0
  4. data/README.md +481 -0
  5. data/app/assets/javascripts/allinoneaccessibility.js +6 -0
  6. data/app/controllers/all_in_one_accessibility/settings_controller.rb +119 -0
  7. data/config/routes.rb +7 -0
  8. data/lib/all_in_one_accessibility/configuration.rb +154 -0
  9. data/lib/all_in_one_accessibility/engine.rb +23 -0
  10. data/lib/all_in_one_accessibility/helper.rb +69 -0
  11. data/lib/all_in_one_accessibility/loader.js +122 -0
  12. data/lib/all_in_one_accessibility/site_config.rb +88 -0
  13. data/lib/all_in_one_accessibility/version.rb +5 -0
  14. data/lib/all_in_one_accessibility/widget.rb +63 -0
  15. data/lib/all_in_one_accessibility.rb +66 -0
  16. data/lib/allinoneaccessibility.rb +6 -8
  17. data/lib/generators/all_in_one_accessibility/install/install_generator.rb +85 -0
  18. data/lib/generators/all_in_one_accessibility/install/templates/initializer.rb.tt +52 -0
  19. data/settings/assets/aioa-icon-type-13-BYUd2bq8.svg +1 -0
  20. data/settings/assets/index-BU8JE2ja.js +44 -0
  21. data/settings/assets/index-DGh_DzL5.css +1 -0
  22. data/settings/icon.svg +1 -0
  23. data/settings/index.html +23 -0
  24. metadata +83 -101
  25. data/MIT-LICENSE +0 -20
  26. data/Rakefile +0 -32
  27. data/lib/allinoneaccessibility/version.rb +0 -3
  28. data/lib/assets/javascripts/allinoneaccessibility.js +0 -1426
  29. data/lib/tasks/allinoneaccessibility_tasks.rake +0 -4
  30. data/test/chartjs_test.rb +0 -7
  31. data/test/dummy/Gemfile +0 -1
  32. data/test/dummy/Gemfile.lock +0 -85
  33. data/test/dummy/README.rdoc +0 -28
  34. data/test/dummy/Rakefile +0 -6
  35. data/test/dummy/app/assets/javascripts/application.js +0 -14
  36. data/test/dummy/app/assets/stylesheets/application.css +0 -13
  37. data/test/dummy/app/controllers/application_controller.rb +0 -5
  38. data/test/dummy/app/helpers/application_helper.rb +0 -2
  39. data/test/dummy/app/views/layouts/application.html.erb +0 -14
  40. data/test/dummy/bin/bundle +0 -3
  41. data/test/dummy/bin/rails +0 -4
  42. data/test/dummy/bin/rake +0 -4
  43. data/test/dummy/config/application.rb +0 -23
  44. data/test/dummy/config/boot.rb +0 -5
  45. data/test/dummy/config/database.yml +0 -25
  46. data/test/dummy/config/environment.rb +0 -5
  47. data/test/dummy/config/environments/development.rb +0 -29
  48. data/test/dummy/config/environments/production.rb +0 -80
  49. data/test/dummy/config/environments/test.rb +0 -36
  50. data/test/dummy/config/initializers/backtrace_silencers.rb +0 -7
  51. data/test/dummy/config/initializers/filter_parameter_logging.rb +0 -4
  52. data/test/dummy/config/initializers/inflections.rb +0 -16
  53. data/test/dummy/config/initializers/mime_types.rb +0 -5
  54. data/test/dummy/config/initializers/secret_token.rb +0 -12
  55. data/test/dummy/config/initializers/session_store.rb +0 -3
  56. data/test/dummy/config/initializers/wrap_parameters.rb +0 -14
  57. data/test/dummy/config/locales/en.yml +0 -23
  58. data/test/dummy/config/routes.rb +0 -56
  59. data/test/dummy/config.ru +0 -4
  60. data/test/dummy/public/404.html +0 -58
  61. data/test/dummy/public/422.html +0 -58
  62. data/test/dummy/public/500.html +0 -57
  63. data/test/dummy/public/favicon.ico +0 -0
  64. data/test/test_helper.rb +0 -15
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AllInOneAccessibility
4
+ # Serves the settings page: a prebuilt static app (settings/, built from
5
+ # settings-app/) and its config.json. The page talks to Skynet Technologies straight
6
+ # from the browser; this controller sends nothing anywhere and stores nothing.
7
+ #
8
+ # GET <mount>/ index.html (redirects <mount> to <mount>/ for relative asset URLs)
9
+ # GET <mount>/config.json the live site's domain and the gem's options (SiteConfig)
10
+ # GET <mount>/*file the page's assets
11
+ #
12
+ # Access: config.settings_page (default: development and test only), and outside
13
+ # development and test, config.authorize_settings_page.
14
+ class SettingsController < AllInOneAccessibility.config.parent_controller.to_s.constantize
15
+ SETTINGS_DIR = File.expand_path("../../../settings", __dir__).freeze
16
+ INDEX = File.join(SETTINGS_DIR, "index.html").freeze
17
+
18
+ # Hosts the settings page calls from the browser (see settings-app/src/settings/config.ts)
19
+ API_HOSTS = %w[
20
+ https://ada.skynettechnologies.us
21
+ https://freeada.skynettechnologies.com
22
+ https://skynetaccessibilityscan.com
23
+ ].freeze
24
+
25
+ if respond_to?(:content_security_policy)
26
+ content_security_policy do |policy|
27
+ policy.default_src :self
28
+ policy.script_src :self
29
+ policy.style_src :self, :unsafe_inline
30
+ policy.img_src :self, :data, :https
31
+ policy.font_src :self, :data
32
+ policy.connect_src :self, *API_HOSTS
33
+ policy.object_src :none
34
+ policy.base_uri :self
35
+ policy.form_action :self
36
+ policy.frame_ancestors :self
37
+ end
38
+ end
39
+
40
+ # Every action is a read-only GET. Forgery protection would also refuse the page's
41
+ # own JavaScript bundle (a non-XHR GET answered with JavaScript).
42
+ skip_forgery_protection if respond_to?(:skip_forgery_protection)
43
+
44
+ before_action :aioa_check_access
45
+ before_action :aioa_no_csp_nonce
46
+
47
+ def show
48
+ # Inside the engine both /aioa and /aioa/ arrive as "/", so look at the path the
49
+ # app received. The page's asset URLs are relative and need the trailing slash.
50
+ path, query = request.original_fullpath.to_s.split("?", 2)
51
+ unless path.to_s.end_with?("/")
52
+ return redirect_to("#{path}/#{query.to_s.empty? ? '' : "?#{query}"}", status: :found)
53
+ end
54
+
55
+ unless File.file?(INDEX)
56
+ return render plain: "The settings page is missing from this install (settings/index.html). " \
57
+ "Reinstall the allinoneaccessibility gem.", status: :not_found
58
+ end
59
+
60
+ aioa_no_store
61
+ send_data File.binread(INDEX), type: "text/html; charset=utf-8", disposition: "inline"
62
+ end
63
+
64
+ def site_config
65
+ aioa_no_store
66
+ render json: AllInOneAccessibility::SiteConfig.new(AllInOneAccessibility.config, request: request).to_h
67
+ end
68
+
69
+ def asset
70
+ file = params[:file].to_s
71
+ path = File.expand_path(file, SETTINGS_DIR)
72
+ unless path.start_with?("#{SETTINGS_DIR}/") && path != INDEX && File.file?(path)
73
+ return head(:not_found)
74
+ end
75
+
76
+ # Built file names carry a content hash
77
+ expires_in(1.year, public: true) if file.start_with?("assets/")
78
+ type = Rack::Mime.mime_type(File.extname(path), "application/octet-stream")
79
+ send_data File.binread(path), type: type, disposition: "inline"
80
+ rescue ArgumentError # a path with a null byte
81
+ head(:not_found)
82
+ end
83
+
84
+ private
85
+
86
+ def aioa_check_access
87
+ config = AllInOneAccessibility.config
88
+ return head(:not_found) unless config.settings_page_enabled?
89
+
90
+ hook = config.authorize_settings_page
91
+ if hook
92
+ allowed = hook.arity.zero? ? instance_exec(&hook) : instance_exec(self, &hook)
93
+ aioa_forbidden("You are not allowed to open the All in One Accessibility settings.") unless performed? || allowed
94
+ elsif !AllInOneAccessibility.local_environment?
95
+ aioa_forbidden(
96
+ "The All in One Accessibility settings page is turned on in the #{AllInOneAccessibility.environment} " \
97
+ "environment, but config.authorize_settings_page is not set. Set it in " \
98
+ "config/initializers/all_in_one_accessibility.rb to say who may open this page."
99
+ )
100
+ end
101
+ end
102
+
103
+ def aioa_forbidden(message)
104
+ render plain: message, status: :forbidden
105
+ end
106
+
107
+ def aioa_no_store
108
+ response.headers["Cache-Control"] = "no-store"
109
+ end
110
+
111
+ # The page has no inline scripts. A nonce in style-src would make browsers ignore
112
+ # 'unsafe-inline', which the page's inline <style> needs.
113
+ def aioa_no_csp_nonce
114
+ return unless request.respond_to?(:content_security_policy_nonce_directives=)
115
+
116
+ request.content_security_policy_nonce_directives = []
117
+ end
118
+ end
119
+ end
data/config/routes.rb ADDED
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ AllInOneAccessibility::Engine.routes.draw do
4
+ root to: "settings#show"
5
+ get "config", to: "settings#site_config", as: :settings_config, defaults: { format: "json" }
6
+ get "*file", to: "settings#asset", as: :settings_asset, format: false
7
+ end
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AllInOneAccessibility
4
+ # Options set in config/initializers/all_in_one_accessibility.rb.
5
+ #
6
+ # A region, load strategy or delay that can't be used raises an ArgumentError when
7
+ # the app boots. A website_url or license_key that can't be used is ignored (the
8
+ # default applies), logged as a warning and listed on the settings page, so a
9
+ # value read from ENV never stops the app from booting.
10
+ class Configuration
11
+ REGIONS = %i[global eu].freeze
12
+ LOAD_STRATEGIES = %i[idle delay head].freeze
13
+ DEFAULT_DELAY = 5000
14
+ MAX_DELAY = 60_000
15
+
16
+ # Live site's domain ("www.example.com"), nil when not set
17
+ attr_reader :website_url
18
+ # :global or :eu
19
+ attr_reader :region
20
+ # :idle, :delay or :head
21
+ attr_reader :load_strategy
22
+ # Milliseconds to wait with load_strategy :delay
23
+ attr_reader :delay
24
+ # Sent as the widget script's token, "" when not set
25
+ attr_reader :license_key
26
+ # Options that could not be used: [{ name:, value:, reason: }]
27
+ attr_reader :ignored
28
+
29
+ # Add the widget in this environment (true, false, or a callable)
30
+ attr_accessor :enabled
31
+ # Keep the widget on the page across Turbo Drive visits
32
+ attr_accessor :turbo
33
+ # Serve the settings page: true, false, or nil for development and test only
34
+ attr_accessor :settings_page
35
+ # Class the settings controller inherits from
36
+ attr_accessor :parent_controller
37
+ attr_writer :authorize_settings_page
38
+
39
+ def initialize
40
+ @website_url = nil
41
+ @region = :global
42
+ @load_strategy = :idle
43
+ @delay = DEFAULT_DELAY
44
+ @license_key = ""
45
+ @ignored = []
46
+ @enabled = true
47
+ @turbo = true
48
+ @settings_page = nil
49
+ @parent_controller = "ActionController::Base"
50
+ @authorize_settings_page = nil
51
+ end
52
+
53
+ def website_url=(value)
54
+ forget(:website_url)
55
+ @website_url = nil
56
+ return if blank?(value)
57
+
58
+ domain = Widget.normalize_domain(value)
59
+ if Widget.valid_domain?(domain)
60
+ @website_url = domain
61
+ else
62
+ ignore(:website_url, value, "expected your live site's domain, for example www.example.com " \
63
+ "(localhost and IP addresses can't be used)")
64
+ end
65
+ end
66
+
67
+ def region=(value)
68
+ region = symbol(value)
69
+ unless REGIONS.include?(region)
70
+ raise ArgumentError, "AllInOneAccessibility: config.region must be :global or :eu, got #{value.inspect}"
71
+ end
72
+
73
+ @region = region
74
+ end
75
+
76
+ def load_strategy=(value)
77
+ strategy = symbol(value)
78
+ unless LOAD_STRATEGIES.include?(strategy)
79
+ raise ArgumentError,
80
+ "AllInOneAccessibility: config.load_strategy must be :idle, :delay or :head, got #{value.inspect}"
81
+ end
82
+
83
+ @load_strategy = strategy
84
+ end
85
+
86
+ def delay=(value)
87
+ number = value.is_a?(Numeric) ? value : Float(value.to_s, exception: false)
88
+ if number.nil? || !number.finite? || number.negative?
89
+ raise ArgumentError,
90
+ "AllInOneAccessibility: config.delay must be a number of milliseconds (0 to #{MAX_DELAY}), " \
91
+ "got #{value.inspect}"
92
+ end
93
+
94
+ @delay = [number.round, MAX_DELAY].min
95
+ end
96
+
97
+ def license_key=(value)
98
+ forget(:license_key)
99
+ @license_key = ""
100
+ return if blank?(value)
101
+
102
+ key = value.to_s.strip
103
+ if Widget::LICENSE_KEY_RE.match?(key)
104
+ @license_key = key
105
+ else
106
+ ignore(:license_key, value, "expected letters, digits, '.', '_', '~' or '-'")
107
+ end
108
+ end
109
+
110
+ # Who may open the settings page outside development and test. Runs in the settings
111
+ # controller (so current_user, request, authenticate_or_request_with_http_basic, ...
112
+ # work); a truthy result allows the request.
113
+ #
114
+ # config.authorize_settings_page { current_user&.admin? }
115
+ # config.authorize_settings_page = ->(controller) { controller.request.remote_ip == "10.0.0.1" }
116
+ def authorize_settings_page(&block)
117
+ @authorize_settings_page = block if block
118
+ @authorize_settings_page
119
+ end
120
+
121
+ def enabled?
122
+ value = enabled.respond_to?(:call) ? enabled.call : enabled
123
+ value ? true : false
124
+ end
125
+
126
+ def settings_page_enabled?
127
+ return AllInOneAccessibility.local_environment? if settings_page.nil?
128
+
129
+ settings_page ? true : false
130
+ end
131
+
132
+ def script_src
133
+ Widget.script_src(region: region, license_key: license_key)
134
+ end
135
+
136
+ private
137
+
138
+ def symbol(value)
139
+ value.to_s.strip.downcase.to_sym
140
+ end
141
+
142
+ def blank?(value)
143
+ value.nil? || value.to_s.strip.empty?
144
+ end
145
+
146
+ def ignore(name, value, reason)
147
+ @ignored << { name: name.to_s, value: value.to_s, reason: reason }
148
+ end
149
+
150
+ def forget(name)
151
+ @ignored.reject! { |option| option[:name] == name.to_s }
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails"
4
+
5
+ module AllInOneAccessibility
6
+ # Mount it to serve the settings page (the install generator adds this line):
7
+ #
8
+ # # config/routes.rb
9
+ # mount AllInOneAccessibility::Engine, at: "/aioa"
10
+ #
11
+ # The view helper (all_in_one_accessibility_tag) works with or without the mount.
12
+ class Engine < ::Rails::Engine
13
+ isolate_namespace AllInOneAccessibility
14
+
15
+ initializer "all_in_one_accessibility.helper" do
16
+ ActiveSupport.on_load(:action_view) { include AllInOneAccessibility::Helper }
17
+ end
18
+
19
+ config.after_initialize do
20
+ AllInOneAccessibility.warn_ignored_options(Rails.logger)
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "active_support/core_ext/string/output_safety"
5
+
6
+ module AllInOneAccessibility
7
+ # View helper that adds the widget. Put it in your layout's <head>:
8
+ #
9
+ # <%= all_in_one_accessibility_tag %>
10
+ #
11
+ # Depending on config.load_strategy it renders
12
+ # :idle / :delay a small inline script that adds the widget script after the page
13
+ # has loaded (when the browser is idle, or after config.delay ms)
14
+ # :head <script id="aioa-adawidget" src="..." defer>, the earliest load
15
+ #
16
+ # The widget script is found by its id, so it is never added twice. With
17
+ # config.turbo (default) the inline script also keeps the widget on the page across
18
+ # Turbo Drive visits, which replace <body> (where the widget lives), and while a
19
+ # visitor has an adjustment on (font size, ...) it loads pages in full so the widget
20
+ # applies it to the new content.
21
+ #
22
+ # Both tags carry the request's Content Security Policy nonce when the app has a
23
+ # nonce generator (nonce: true, the default). Pass nonce: false to leave it out.
24
+ module Helper
25
+ # The inline loader (lib/all_in_one_accessibility/loader.js), a function expression
26
+ # called with the widget options. Indentation and blank lines are dropped, since it is
27
+ # inlined into every page; line breaks stay.
28
+ LOADER = File.read(File.expand_path("loader.js", __dir__)).gsub(/^[ \t]+/, "").squeeze("\n").strip.freeze
29
+
30
+ def all_in_one_accessibility_tag(nonce: true)
31
+ config = AllInOneAccessibility.config
32
+ return "".html_safe unless config.enabled?
33
+
34
+ nonce_value = aioa_csp_nonce(nonce)
35
+ src = config.script_src
36
+ head = config.load_strategy == :head
37
+
38
+ tags = []
39
+ tags << content_tag(:script, "", id: Widget::SCRIPT_ID, src: src, defer: true, nonce: nonce_value) if head
40
+ # With :head the tag is already there; the loader is only needed for Turbo
41
+ tags << aioa_loader_tag(config, src, nonce_value) unless head && !config.turbo
42
+ safe_join(tags, "\n")
43
+ end
44
+ alias aioa_widget_tag all_in_one_accessibility_tag
45
+
46
+ private
47
+
48
+ def aioa_loader_tag(config, src, nonce_value)
49
+ options = {
50
+ id: Widget::SCRIPT_ID,
51
+ src: src,
52
+ strategy: config.load_strategy.to_s,
53
+ delay: config.delay,
54
+ turbo: config.turbo ? true : false
55
+ }
56
+ # json_escape: no "</script>", "<!--" or U+2028 can end or break the script
57
+ code = "#{LOADER}(#{ERB::Util.json_escape(JSON.generate(options))});"
58
+ content_tag(:script, code.html_safe, nonce: nonce_value)
59
+ end
60
+
61
+ def aioa_csp_nonce(nonce)
62
+ return nonce if nonce.is_a?(String) && !nonce.empty?
63
+ return nil unless nonce == true
64
+ return nil unless respond_to?(:content_security_policy_nonce)
65
+
66
+ content_security_policy_nonce
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,122 @@
1
+ (function (o) {
2
+ var d = document, w = window;
3
+
4
+ function add() {
5
+ if (d.getElementById(o.id)) return;
6
+ var s = d.createElement("script");
7
+ s.id = o.id;
8
+ s.src = o.src;
9
+ s.async = true;
10
+ d.head.appendChild(s);
11
+ }
12
+
13
+ function schedule() {
14
+ if (o.strategy === "head") add();
15
+ else if (o.strategy === "delay") w.setTimeout(add, o.delay);
16
+ else if (w.requestIdleCallback) w.requestIdleCallback(add, { timeout: 3000 });
17
+ else w.setTimeout(add, 200);
18
+ }
19
+
20
+ if (d.readyState === "complete") schedule();
21
+ else w.addEventListener("load", schedule);
22
+
23
+ if (!o.turbo || w.__aioaTurbo || !w.WeakSet) return;
24
+ w.__aioaTurbo = true;
25
+
26
+ var MARK = "data-aioa-turbo";
27
+ var WIDGET = "[id^='aioa'],[class^='aioa'],[class*=' aioa'],[id^='accessibility'],[class^='accessibility']," +
28
+ "[class*=' accessibility'],#focus-navigation-panel,#focus-navigation-reopen";
29
+ var page = new WeakSet();
30
+
31
+ function each(list, fn) {
32
+ Array.prototype.forEach.call(list, fn);
33
+ }
34
+
35
+ function markPage(body) {
36
+ if (body) each(body.children, function (el) { if (!el.hasAttribute(MARK)) page.add(el); });
37
+ }
38
+
39
+ function isWidget(el) {
40
+ return el.hasAttribute(MARK) || (!page.has(el) && el.matches(WIDGET));
41
+ }
42
+
43
+ if (d.readyState === "loading") d.addEventListener("DOMContentLoaded", function () { markPage(d.body); });
44
+ else markPage(d.body);
45
+ d.addEventListener("turbo:load", function () { markPage(d.body); });
46
+
47
+ d.addEventListener("turbo:before-cache", function () {
48
+ each(d.body.children, function (el) { if (isWidget(el)) el.setAttribute(MARK, ""); });
49
+ });
50
+
51
+ d.addEventListener("turbo:before-render", function (e) {
52
+ var next = e.detail && e.detail.newBody, body = d.body;
53
+ if (!next || !body || e.detail.renderMethod === "morph" || !d.getElementById(o.id)) return;
54
+ var i, el, kids, anchor, lead = true;
55
+ for (i = next.children.length - 1; i >= 0; i--) {
56
+ if (next.children[i].hasAttribute(MARK)) next.removeChild(next.children[i]);
57
+ }
58
+ markPage(next);
59
+ anchor = next.firstChild;
60
+ kids = Array.prototype.slice.call(body.children);
61
+ for (i = 0; i < kids.length; i++) {
62
+ el = kids[i];
63
+ if (!isWidget(el)) { lead = false; continue; }
64
+ el.setAttribute(MARK, "");
65
+ if (lead) next.insertBefore(el, anchor); else next.appendChild(el);
66
+ }
67
+ each(body.classList, function (c) {
68
+ if (/^(aioa|accessibility)[-_]/.test(c)) next.classList.add(c);
69
+ });
70
+ });
71
+
72
+ d.addEventListener("turbo:before-morph-element", function (e) {
73
+ var el = e.target;
74
+ if (el.parentNode === d.body && isWidget(el)) e.preventDefault();
75
+ });
76
+
77
+ function adjusted() {
78
+ return !!d.querySelector(".aioa-widget-wrapper.aioafo");
79
+ }
80
+
81
+ function framed(link) {
82
+ var target = link.getAttribute("data-turbo-frame"), frame;
83
+ if (target) return target !== "_top";
84
+ frame = link.closest("turbo-frame");
85
+ return !!frame && frame.getAttribute("target") !== "_top";
86
+ }
87
+
88
+ d.addEventListener("turbo:click", function (e) {
89
+ var link = e.target;
90
+ if (!adjusted() || !link || !link.closest) return;
91
+ if (framed(link) || link.hasAttribute("data-turbo-stream")) return;
92
+ e.preventDefault();
93
+ });
94
+
95
+ d.addEventListener("turbo:visit", function (e) {
96
+ if (e.detail && e.detail.action === "restore" && adjusted()) w.location.reload();
97
+ });
98
+
99
+ var rendered = false, watched = false, on = false, found;
100
+ d.addEventListener("turbo:render", function () { rendered = true; });
101
+
102
+ function watch() {
103
+ var el = d.querySelector(".aioa-widget-wrapper");
104
+ if (watched || !el) return watched;
105
+ watched = true;
106
+ on = el.classList.contains("aioafo");
107
+ new MutationObserver(function () {
108
+ var now = el.classList.contains("aioafo");
109
+ if (now && !on && rendered) w.setTimeout(function () { w.location.reload(); }, 400);
110
+ on = now;
111
+ }).observe(el, { attributes: true, attributeFilter: ["class"] });
112
+ return true;
113
+ }
114
+
115
+ found = new MutationObserver(function () { if (watch()) found.disconnect(); });
116
+ function lookForWidget() {
117
+ if (!watch() && d.body) found.observe(d.body, { childList: true });
118
+ }
119
+ if (d.readyState === "loading") d.addEventListener("DOMContentLoaded", lookForWidget);
120
+ else lookForWidget();
121
+ d.addEventListener("turbo:load", lookForWidget);
122
+ })
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AllInOneAccessibility
4
+ # What the settings page needs to know, served as <mount path>/config.json:
5
+ # the live site's domain (and where it came from) and the gem's options.
6
+ #
7
+ # The domain is the first public hostname of
8
+ # 1. config.website_url
9
+ # 2. Rails.application.routes.default_url_options[:host]
10
+ # 3. config.action_mailer.default_url_options[:host]
11
+ # 4. the host the settings page was opened on (on the live site itself)
12
+ class SiteConfig
13
+ def initialize(config = AllInOneAccessibility.config, request: nil, application: default_application)
14
+ @config = config
15
+ @request = request
16
+ @application = application
17
+ end
18
+
19
+ def to_h
20
+ site = website
21
+ {
22
+ platform: Widget::PLATFORM,
23
+ pluginVersion: VERSION,
24
+ website: site[:website],
25
+ websiteSource: site[:source],
26
+ websiteProblem: site[:problem],
27
+ siteUrl: site[:site_url].to_s,
28
+ region: @config.region.to_s,
29
+ loadStrategy: @config.load_strategy.to_s,
30
+ delay: @config.delay,
31
+ scriptSrc: @config.script_src,
32
+ widgetEnabled: @config.enabled?,
33
+ environment: AllInOneAccessibility.environment,
34
+ ignoredOptions: @config.ignored
35
+ }
36
+ end
37
+
38
+ # { website:, source:, problem:, site_url: }
39
+ def website
40
+ if @config.website_url
41
+ return { website: @config.website_url, source: "website_url", problem: "", site_url: "" }
42
+ end
43
+
44
+ not_public = nil
45
+ configured_hosts.each do |source, value|
46
+ next if value.to_s.strip.empty?
47
+
48
+ domain = Widget.normalize_domain(value)
49
+ return { website: domain, source: source, problem: "", site_url: "" } if Widget.valid_domain?(domain)
50
+
51
+ not_public ||= { website: "", source: source, problem: "not-public", site_url: value.to_s }
52
+ end
53
+
54
+ # The request's host counts only when it is a public domain (the page was opened
55
+ # on the live site); "localhost" on a development server is not a problem to report
56
+ request_host = @request.respond_to?(:host) ? Widget.normalize_domain(@request.host) : ""
57
+ if Widget.valid_domain?(request_host)
58
+ return { website: request_host, source: "request", problem: "", site_url: "" }
59
+ end
60
+
61
+ not_public || { website: "", source: "", problem: "missing", site_url: "" }
62
+ end
63
+
64
+ private
65
+
66
+ def default_application
67
+ defined?(::Rails) && ::Rails.respond_to?(:application) ? ::Rails.application : nil
68
+ end
69
+
70
+ def configured_hosts
71
+ return [] unless @application
72
+
73
+ hosts = [["default_url_options", host_of(@application.routes.default_url_options)]]
74
+ if @application.config.respond_to?(:action_mailer)
75
+ hosts << ["action_mailer", host_of(@application.config.action_mailer.default_url_options)]
76
+ end
77
+ hosts
78
+ end
79
+
80
+ def host_of(options)
81
+ return nil unless options.respond_to?(:[])
82
+
83
+ options[:host] || options["host"]
84
+ rescue StandardError
85
+ nil
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AllInOneAccessibility
4
+ VERSION = "1.0.0"
5
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AllInOneAccessibility
4
+ # ---------------------------------------------------------------------------
5
+ # The widget script and the live site's domain.
6
+ # ---------------------------------------------------------------------------
7
+ # Same values and rules as lib/widget.js of the Gatsby plugin.
8
+ #
9
+ # The widget loader reads its own <script> tag (found by the id "aioa-adawidget")
10
+ # and splits its src by hand, so the query string must stay exactly
11
+ # ?colorcode=#<hex>&token=<license key>&position=<position>
12
+ # in that order, with a literal "#" before the color.
13
+ module Widget
14
+ # Id the widget loader finds its own tag by. Never change it.
15
+ SCRIPT_ID = "aioa-adawidget"
16
+
17
+ # Platform sent to Skynet Technologies when a free widget account is created
18
+ PLATFORM = "Ruby on Rails"
19
+
20
+ # Widget script host per data region
21
+ REGION_HOSTS = {
22
+ global: "https://www.skynettechnologies.com",
23
+ eu: "https://eu.skynettechnologies.com"
24
+ }.freeze
25
+
26
+ SCRIPT_PATH = "/accessibility/js/all-in-one-accessibility-js-widget-minify.js"
27
+
28
+ # Values the script URL starts from (same as the other platforms). The widget
29
+ # replaces them with the settings saved on the settings page.
30
+ DEFAULT_COLOR = "420083"
31
+ DEFAULT_POSITION = "bottom_right"
32
+
33
+ # Bare public hostname: "www.example.com", "shop.example.co.uk".
34
+ # "localhost" and IP addresses never match: a free widget account is created per
35
+ # domain, with no-reply@<domain> as its contact address.
36
+ DOMAIN_RE = /\A(?=.{3,253}\z)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\z/.freeze
37
+
38
+ # License key sent as the script's token (paid plans that use one)
39
+ LICENSE_KEY_RE = /\A[A-Za-z0-9._~-]{1,200}\z/.freeze
40
+
41
+ module_function
42
+
43
+ # Reduce a URL to its hostname: "https://www.Example.com/shop" -> "www.example.com"
44
+ def normalize_domain(value)
45
+ value.to_s.strip.downcase
46
+ .sub(%r{\A[a-z][a-z0-9+.-]*://}, "") # scheme
47
+ .sub(%r{[/?#].*\z}m, "") # path, query, hash
48
+ .sub(/\A[^@]*@/, "") # user info
49
+ .sub(/:\d+\z/, "") # port
50
+ .gsub(/\A\.+|\.+\z/, "")
51
+ end
52
+
53
+ def valid_domain?(domain)
54
+ DOMAIN_RE.match?(domain.to_s)
55
+ end
56
+
57
+ # The widget script URL, the same URL the Gatsby, Framer and Strapi plugins use
58
+ def script_src(region: :global, license_key: "")
59
+ host = REGION_HOSTS.fetch(region.to_s.to_sym, REGION_HOSTS[:global])
60
+ "#{host}#{SCRIPT_PATH}?colorcode=##{DEFAULT_COLOR}&token=#{license_key}&position=#{DEFAULT_POSITION}"
61
+ end
62
+ end
63
+ end