trek 2.3.2 → 2.5.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 (221) hide show
  1. checksums.yaml +4 -4
  2. data/.node-version +1 -1
  3. data/.yarn/releases/yarn-4.18.1.cjs +1000 -0
  4. data/.yarnrc.yml +3 -5
  5. data/AGENTS.md +12 -8
  6. data/CHANGELOG.md +73 -0
  7. data/Gemfile.lock +226 -171
  8. data/Makefile +38 -1
  9. data/README.md +2 -2
  10. data/app/assets/icons/trek/passkey.svg +5 -0
  11. data/app/assets/stylesheets/trek/base.css +6 -0
  12. data/app/components/trek/entries/item_component/item_component.css +6 -0
  13. data/app/components/trek/form/image_field_component/image_field_component.html.slim +9 -0
  14. data/app/components/trek/form/image_field_component.rb +1 -5
  15. data/app/components/trek/form/password_strength_component/password_strength_component.css +56 -0
  16. data/app/components/trek/form/password_strength_component/password_strength_component.html.slim +8 -0
  17. data/app/components/trek/form/password_strength_component/password_strength_component.js +74 -0
  18. data/app/components/trek/form/password_strength_component.rb +29 -0
  19. data/app/components/trek/gate_component/gate_component.css +7 -0
  20. data/app/components/trek/icon/sprite_component.rb +3 -2
  21. data/app/components/trek/list/item_component.rb +1 -1
  22. data/app/components/trek/list/tree/item_component.rb +2 -2
  23. data/app/components/trek/search_component/search_component.html.slim +2 -1
  24. data/app/components/trek/search_component.rb +9 -1
  25. data/app/components/trek/section_component/section_component.css +22 -0
  26. data/app/components/trek/section_component/section_component.html.slim +5 -0
  27. data/app/components/trek/section_component/section_component.js +1 -0
  28. data/app/components/trek/section_component.rb +14 -0
  29. data/app/content/trek/content/bullet_list.rb +10 -0
  30. data/app/content/trek/content/document.rb +33 -0
  31. data/app/content/trek/content/image_block.rb +52 -0
  32. data/app/content/trek/content/link_resolver.rb +33 -0
  33. data/app/content/trek/content/list_item.rb +19 -0
  34. data/app/content/trek/content/ordered_list.rb +10 -0
  35. data/app/content/trek/content/paragraph.rb +10 -0
  36. data/app/content/trek/content/prompts_block.rb +22 -0
  37. data/app/content/trek/content.rb +32 -0
  38. data/app/controllers/concerns/trek/auditable.rb +103 -0
  39. data/app/controllers/concerns/trek/filters.rb +2 -0
  40. data/app/controllers/concerns/trek/passkeys.rb +37 -0
  41. data/app/controllers/concerns/trek/reorderable.rb +14 -3
  42. data/app/controllers/trek/csp_reports_controller.rb +59 -0
  43. data/app/controllers/trek/panels/base_controller.rb +3 -0
  44. data/app/controllers/trek/panels/links_controller.rb +1 -1
  45. data/app/controllers/trek/panels/prompts_controller.rb +1 -1
  46. data/app/controllers/trek/resource_controller.rb +7 -1
  47. data/app/helpers/trek/audit_logs_helper.rb +21 -0
  48. data/app/helpers/trek/thumbnail_helper.rb +11 -0
  49. data/app/helpers/trek/user_agents_helper.rb +36 -0
  50. data/app/javascript/controllers/index.js +3 -0
  51. data/app/javascript/controllers/passkey_controller.js +118 -0
  52. data/app/javascript/trek.js +4 -0
  53. data/app/jobs/trek/audit_log/purge_job.rb +18 -0
  54. data/app/jobs/trek/purge_expired_sessions_job.rb +14 -0
  55. data/app/jobs/trek/resolve_session_hostname_job.rb +17 -0
  56. data/app/models/concerns/trek/audit_log.rb +30 -0
  57. data/app/models/concerns/trek/contentable.rb +9 -14
  58. data/app/models/concerns/trek/pageable.rb +10 -1
  59. data/app/models/concerns/trek/users/passkeys.rb +75 -0
  60. data/app/models/concerns/trek/users/password_history.rb +51 -0
  61. data/app/models/concerns/trek/users/password_policy.rb +85 -0
  62. data/app/models/concerns/trek/users/password_renewal.rb +51 -0
  63. data/app/models/concerns/trek/users/session_lifetime.rb +39 -0
  64. data/app/models/concerns/trek/users/sign_in_lockout.rb +67 -0
  65. data/app/models/concerns/trek/users/sign_ins.rb +31 -0
  66. data/app/models/concerns/trek/users/validations.rb +3 -2
  67. data/app/models/trek/feature.rb +6 -0
  68. data/app/models/trek/pwned_passwords.rb +40 -0
  69. data/app/models/trek/user_session.rb +10 -0
  70. data/app/policies/trek/audit_log_policy.rb +34 -0
  71. data/app/policies/trek/user_policy.rb +5 -0
  72. data/app/validators/not_disposable_validator.rb +18 -0
  73. data/app/views/trek/panels/images/_form.html.slim +1 -1
  74. data/app/views/trek/panels/images/create.turbo_stream.slim +1 -1
  75. data/app/views/trek/panels/links/_form.html.slim +1 -1
  76. data/app/views/trek/panels/prompts/_form.html.slim +1 -1
  77. data/config/brakeman.ignore +22 -0
  78. data/config/i18n-tasks.yml +7 -0
  79. data/config/locales/trek.en.yml +167 -39
  80. data/config/locales/trek.fr.yml +168 -40
  81. data/docs/.vitepress/config.mjs +8 -3
  82. data/docs/deploy.md +2 -0
  83. data/docs/getting-started.md +3 -3
  84. data/docs/proxies.md +53 -0
  85. data/docs/reference/components.md +1 -0
  86. data/docs/reference/concerns/contentable.md +2 -1
  87. data/docs/reference/controllers.md +1 -1
  88. data/docs/reference/environment-variables.md +2 -0
  89. data/docs/reference/formatters.md +31 -8
  90. data/docs/reference/generators/admin-user.md +1 -1
  91. data/docs/reference/generators/audit-log.md +113 -0
  92. data/docs/reference/generators/install.md +12 -3
  93. data/docs/reference/generators/security-headers.md +109 -0
  94. data/docs/reference/index.md +3 -0
  95. data/docs/reference/models/fragment.md +1 -0
  96. data/docs/reference/models/tag.md +4 -2
  97. data/docs/reference/models/user.md +123 -3
  98. data/docs/reference/validators.md +94 -0
  99. data/docs/security.md +90 -0
  100. data/docs/what-is-trek.md +4 -4
  101. data/lefthook.yml +8 -0
  102. data/lib/generators/trek/helpers.rb +13 -5
  103. data/lib/generators/trek/install/admin/user_password_resets_generator.rb +5 -0
  104. data/lib/generators/trek/install/admin/user_sessions_generator.rb +5 -0
  105. data/lib/generators/trek/install/admin/users_generator.rb +23 -0
  106. data/lib/generators/trek/install/admin_generator.rb +8 -0
  107. data/lib/generators/trek/install/appsignal_generator.rb +1 -1
  108. data/lib/generators/trek/install/audit_log_generator.rb +56 -0
  109. data/lib/generators/trek/install/authentication_generator.rb +78 -4
  110. data/lib/generators/trek/install/authorization_generator.rb +1 -1
  111. data/lib/generators/trek/install/esbuild_generator.rb +1 -2
  112. data/lib/generators/trek/install/mailer_generator.rb +18 -0
  113. data/lib/generators/trek/install/model_specs_generator.rb +6 -4
  114. data/lib/generators/trek/install/postcss_generator.rb +1 -4
  115. data/lib/generators/trek/install/postmark_generator.rb +2 -2
  116. data/lib/generators/trek/install/security_headers_generator.rb +49 -0
  117. data/lib/generators/trek/install/specs_generator.rb +11 -0
  118. data/lib/generators/trek/install/user_generator.rb +1 -1
  119. data/lib/generators/trek/install/yarn_generator.rb +1 -1
  120. data/lib/generators/trek/install_generator.rb +62 -54
  121. data/lib/generators/trek/scaffold_generator.rb +13 -5
  122. data/lib/generators/trek/taxonomies_generator.rb +5 -0
  123. data/lib/generators/trek/templates/.gitlab-ci.yml +18 -2
  124. data/lib/generators/trek/templates/Makefile +1 -1
  125. data/lib/generators/trek/templates/controllers/admin/active_sessions_controller.rb +21 -0
  126. data/lib/generators/trek/templates/controllers/admin/audit_logs_controller.rb +30 -0
  127. data/lib/generators/trek/templates/controllers/admin/fragments_controller.rb +7 -0
  128. data/lib/generators/trek/templates/controllers/admin/panels/images_controller.rb +8 -0
  129. data/lib/generators/trek/templates/controllers/admin/panels/links_controller.rb +8 -0
  130. data/lib/generators/trek/templates/controllers/admin/panels/prompts_controller.rb +8 -0
  131. data/lib/generators/trek/templates/controllers/admin/passkey_sessions_controller.rb +41 -0
  132. data/lib/generators/trek/templates/controllers/admin/passkeys_controller.rb +37 -0
  133. data/lib/generators/trek/templates/controllers/admin/user_password_resets_controller.rb +4 -4
  134. data/lib/generators/trek/templates/controllers/admin/user_sessions_controller.rb +53 -4
  135. data/lib/generators/trek/templates/controllers/admin/users_controller.rb +20 -0
  136. data/lib/generators/trek/templates/controllers/concerns/trek/authentication.rb +58 -7
  137. data/lib/generators/trek/templates/helpers/application_helper.rb +0 -4
  138. data/lib/generators/trek/templates/initializers/audit_log.rb +11 -0
  139. data/lib/generators/trek/templates/initializers/content_security_policy.rb +49 -0
  140. data/lib/generators/trek/templates/initializers/permissions_policy.rb +19 -0
  141. data/lib/generators/trek/templates/jobs/admin/password_reset_job.rb +9 -0
  142. data/lib/generators/trek/templates/layouts/admin/auth.html.slim +0 -5
  143. data/lib/generators/trek/templates/layouts/admin.html.slim +0 -3
  144. data/lib/generators/trek/templates/mailers/admin/passwords_mailer.rb +1 -1
  145. data/lib/generators/trek/templates/mailers/admin_mailer.rb +28 -1
  146. data/lib/generators/trek/templates/migrations/audit_logs.rb.erb +27 -0
  147. data/lib/generators/trek/templates/migrations/tags.rb.erb +6 -1
  148. data/lib/generators/trek/templates/migrations/user_passkeys.rb.erb +24 -0
  149. data/lib/generators/trek/templates/migrations/user_password_renewal.rb.erb +8 -0
  150. data/lib/generators/trek/templates/migrations/user_previous_passwords.rb.erb +10 -0
  151. data/lib/generators/trek/templates/migrations/user_session_tracking.rb.erb +11 -0
  152. data/lib/generators/trek/templates/migrations/user_sign_in_lockout.rb.erb +7 -0
  153. data/lib/generators/trek/templates/migrations/user_sign_ins.rb.erb +13 -0
  154. data/lib/generators/trek/templates/models/audit_log.rb +3 -0
  155. data/lib/generators/trek/templates/models/fragment.rb +14 -0
  156. data/lib/generators/trek/templates/models/tag_category.rb +2 -1
  157. data/lib/generators/trek/templates/models/user/passkey.rb +17 -0
  158. data/lib/generators/trek/templates/models/user/previous_password.rb +4 -0
  159. data/lib/generators/trek/templates/models/user/session.rb +8 -0
  160. data/lib/generators/trek/templates/policies/audit_log.rb +4 -0
  161. data/lib/generators/trek/templates/spec/mailers/admin/passwords_mailer_spec.rb +16 -0
  162. data/lib/generators/trek/templates/spec/mailers/admin_mailer_spec.rb +51 -0
  163. data/lib/generators/trek/templates/spec/models/audit_log_spec.rb +43 -0
  164. data/lib/generators/trek/templates/spec/models/tag_spec.rb +52 -0
  165. data/lib/generators/trek/templates/spec/models/user/session_spec.rb +68 -0
  166. data/lib/generators/trek/templates/spec/models/user_spec.rb +142 -4
  167. data/lib/generators/trek/templates/spec/requests/admin/active_sessions_spec.rb +120 -0
  168. data/lib/generators/trek/templates/spec/requests/admin/audit_logs_spec.rb +149 -0
  169. data/lib/generators/trek/templates/spec/requests/admin/fragments_spec.rb +26 -2
  170. data/lib/generators/trek/templates/spec/requests/admin/pages_spec.rb +8 -0
  171. data/lib/generators/trek/templates/spec/requests/admin/panels_spec.rb +54 -0
  172. data/lib/generators/trek/templates/spec/requests/admin/passkey_sessions_spec.rb +103 -0
  173. data/lib/generators/trek/templates/spec/requests/admin/passkeys_spec.rb +104 -0
  174. data/lib/generators/trek/templates/spec/requests/admin/password_renewal_spec.rb +83 -0
  175. data/lib/generators/trek/templates/spec/requests/admin/sign_in_lockout_spec.rb +95 -0
  176. data/lib/generators/trek/templates/spec/requests/admin/sign_in_notices_spec.rb +95 -0
  177. data/lib/generators/trek/templates/spec/requests/admin/user_password_resets_spec.rb +43 -6
  178. data/lib/generators/trek/templates/spec/requests/admin/user_sessions_spec.rb +25 -2
  179. data/lib/generators/trek/templates/views/admin/audit_logs/index.html.slim +35 -0
  180. data/lib/generators/trek/templates/views/admin/audit_logs/show.html.slim +50 -0
  181. data/lib/generators/trek/templates/views/admin/fragments/index.html.slim +14 -3
  182. data/lib/generators/trek/templates/views/admin/user_password_resets/edit.html.slim +16 -6
  183. data/lib/generators/trek/templates/views/admin/user_password_resets/new.html.slim +2 -1
  184. data/lib/generators/trek/templates/views/admin/user_sessions/new.html.slim +27 -1
  185. data/lib/generators/trek/templates/views/admin/users/_passkeys.html.slim +67 -0
  186. data/lib/generators/trek/templates/views/admin/users/_properties.html.slim +21 -0
  187. data/lib/generators/trek/templates/views/admin/users/_sessions.html.slim +70 -0
  188. data/lib/generators/trek/templates/views/admin/users/index.html.slim +13 -0
  189. data/lib/generators/trek/templates/views/admin/users/show.html.slim +10 -21
  190. data/lib/generators/trek/templates/views/admin_mailer/new_sign_in.en.html.slim +22 -0
  191. data/lib/generators/trek/templates/views/admin_mailer/new_sign_in.en.text.erb +16 -0
  192. data/lib/generators/trek/templates/views/admin_mailer/new_sign_in.fr.html.slim +22 -0
  193. data/lib/generators/trek/templates/views/admin_mailer/new_sign_in.fr.text.erb +16 -0
  194. data/lib/generators/trek/templates/views/admin_mailer/sign_in_locked.en.html.slim +17 -0
  195. data/lib/generators/trek/templates/views/admin_mailer/sign_in_locked.en.text.erb +10 -0
  196. data/lib/generators/trek/templates/views/admin_mailer/sign_in_locked.fr.html.slim +18 -0
  197. data/lib/generators/trek/templates/views/admin_mailer/sign_in_locked.fr.text.erb +10 -0
  198. data/lib/trek/admin_ip_allowlist.rb +52 -0
  199. data/lib/trek/csp_reports.rb +99 -0
  200. data/lib/trek/data/common_passwords.txt +857 -0
  201. data/lib/trek/data/passkey_providers.json +404 -0
  202. data/lib/trek/disposable_email_domains.rb +53 -0
  203. data/lib/trek/engine.rb +18 -1
  204. data/lib/trek/passkey_providers.rb +19 -0
  205. data/lib/trek/reverse_dns.rb +27 -0
  206. data/lib/trek/saved_attachments_reload.rb +2 -1
  207. data/lib/trek/version.rb +1 -1
  208. data/lib/trek.rb +14 -1
  209. data/package.json +3 -5
  210. data/renovate.json +12 -1
  211. data/trek.gemspec +6 -3
  212. data/yarn.lock +2273 -2573
  213. metadata +160 -17
  214. data/.yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs +0 -541
  215. data/.yarn/releases/yarn-3.8.0.cjs +0 -875
  216. data/app/formatters/prosemirror_to_html/global_id_to_links_formatter.rb +0 -19
  217. data/app/formatters/prosemirror_to_html/nodes/image_block.rb +0 -44
  218. data/app/formatters/prosemirror_to_html/nodes/prompts_block.rb +0 -28
  219. data/app/formatters/prosemirror_to_html/remove_empty_paragraphs_formatter.rb +0 -11
  220. data/app/models/prosemirror.rb +0 -23
  221. data/lib/generators/trek/templates/models/user_session.rb +0 -3
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Trek
4
+ # Records an AuditLog row for each request: who (`audit_actor`), what (`controller#action`, the
5
+ # HTTP method, path and parameter names), on which record (`audit_target`), and how it ended (the
6
+ # status, or the class of the error raised).
7
+ #
8
+ # Only mutations are recorded: GET and HEAD are skipped, unless a controller sets
9
+ # `self.audit_reads = true`. A read on sensitive data can be logged explicitly with `audit!`.
10
+ #
11
+ # Auditing never breaks the request: a failed write is reported through `Rails.error`.
12
+ # FEATURE_AUDIT_LOG=false switches it off, read on each request.
13
+ module Auditable
14
+ extend ActiveSupport::Concern
15
+
16
+ included do
17
+ class_attribute :audit_reads, default: false
18
+ # The parameters whose values are recorded, at any depth; the others are recorded by name only,
19
+ # so the log doesn't copy the data the forms send. `config.filter_parameters` still applies.
20
+ class_attribute :audit_param_values, default: %w[id role]
21
+
22
+ # Prepended so it wraps authentication too: requests refused or redirected by
23
+ # `require_authentication`, and failed sign-ins, are recorded as well.
24
+ prepend_around_action :record_audit_log
25
+ end
26
+
27
+ private
28
+
29
+ # Records `name` on `target` now, whatever the HTTP method, e.g. `audit!(:show_answers, @object)`
30
+ # in a GET action showing sensitive data.
31
+ def audit!(name, target = audit_target)
32
+ write_audit_log(action: name, target:) if Trek::Feature.audit_log?
33
+ end
34
+
35
+ def record_audit_log
36
+ return yield unless Trek::Feature.audit_log?
37
+ return yield if read_only_request? && !audit_reads
38
+
39
+ error = nil
40
+ begin
41
+ yield
42
+ rescue StandardError => e
43
+ error = e
44
+ raise
45
+ ensure
46
+ write_audit_log(status: (response.status unless error), error:)
47
+ end
48
+ end
49
+
50
+ # Rails answers `get?` with false for a HEAD, which uptime monitors use.
51
+ def read_only_request?
52
+ request.get? || request.head?
53
+ end
54
+
55
+ def write_audit_log(action: action_name, target: audit_target, status: nil, error: nil)
56
+ ::AuditLog.create!(
57
+ actor: audit_actor,
58
+ auditable: target,
59
+ action: "#{controller_path}##{action}",
60
+ http_method: request.request_method,
61
+ path: request.path,
62
+ http_status: status,
63
+ params: audit_params,
64
+ ip_address: request.remote_ip,
65
+ user_agent: request.user_agent,
66
+ request_id: request.request_id,
67
+ error_class: error&.class&.name,
68
+ **audit_attributes
69
+ )
70
+ rescue StandardError => e
71
+ Rails.error.report(e, handled: true, context: { action: "#{controller_path}##{action}" })
72
+ end
73
+
74
+ # Who made the request; nil when nobody is signed in.
75
+ def audit_actor
76
+ Current.user
77
+ end
78
+
79
+ # The record the action worked on: `@object`, as Trek::ResourceController sets it, once saved
80
+ # (not after a failed create) or destroyed. Override for other controllers.
81
+ def audit_target
82
+ @object if @object.is_a?(ActiveRecord::Base) && (@object.persisted? || @object.destroyed?)
83
+ end
84
+
85
+ # The request's parameter names, with the values of `audit_param_values` only.
86
+ def audit_params
87
+ redact_audit_values(request.filtered_parameters.except("controller", "action"))
88
+ end
89
+
90
+ def redact_audit_values(value, key = nil)
91
+ case value
92
+ when Hash then value.to_h { |k, v| [k, redact_audit_values(v, k)] }
93
+ when Array then value.map { |v| redact_audit_values(v, key) }
94
+ else audit_param_values.map(&:to_s).include?(key.to_s) ? value : "[FILTERED]"
95
+ end
96
+ end
97
+
98
+ # Values for the app's own columns, e.g. `{ event: audit_target.try(:event) }`.
99
+ def audit_attributes
100
+ {}
101
+ end
102
+ end
103
+ end
@@ -20,6 +20,8 @@ module Trek
20
20
  # rubocop:disable Rails/LexicallyScopedActionFilter
21
21
  after_action :ensure_filters_applied, only: :index
22
22
  # rubocop:enable Rails/LexicallyScopedActionFilter
23
+
24
+ helper_method :filter_params
23
25
  end
24
26
 
25
27
  def apply_filters(scope, filters)
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Trek
4
+ # The WebAuthn relying party and challenges, for controllers adding passkeys or signing in with one
5
+ # (Trek::Users::Passkeys).
6
+ module Passkeys
7
+ extend ActiveSupport::Concern
8
+
9
+ # How long the browser has to answer, and the user to touch their authenticator
10
+ CHALLENGE_LIFETIME = 5.minutes
11
+
12
+ private
13
+
14
+ # Passkeys belong to a domain: the request's, so they work on any environment without
15
+ # configuration, each with its own passkeys. Behind a proxy, it must pass the original host and
16
+ # scheme on (see the docs on proxies).
17
+ def passkey_relying_party
18
+ @passkey_relying_party ||= WebAuthn::RelyingParty.new(
19
+ id: request.host,
20
+ allowed_origins: [request.base_url],
21
+ name: t("application_name")
22
+ )
23
+ end
24
+
25
+ # Renders the options as JSON for the browser, keeping their challenge for the answer
26
+ def render_passkey_options(options)
27
+ session[:passkey_challenge] = { "value" => options.challenge, "at" => Time.current.to_i }
28
+ render json: options
29
+ end
30
+
31
+ # The challenge the browser was given, once only, and while it's fresh
32
+ def take_passkey_challenge
33
+ challenge = session.delete(:passkey_challenge) || {}
34
+ challenge["value"] if challenge["at"].to_i > CHALLENGE_LIFETIME.ago.to_i
35
+ end
36
+ end
37
+ end
@@ -7,13 +7,20 @@ module Trek
7
7
  before_action :set_mode, only: [:index]
8
8
  # rubocop:enable Rails/LexicallyScopedActionFilter
9
9
 
10
+ # The index's reorder form posts there
11
+ helper_method :reorder_path
12
+
10
13
  def reorder
11
14
  authorize!
12
15
  objects = reorderable_objects.index_by(&:id)
13
16
 
14
- reorder_params.each do |id, position|
15
- object = objects[id.to_i]
16
- object.update(position:) unless object.position == position
17
+ # Saving the positions one record at a time repeats acts_as_list's queries: Prosopite, in
18
+ # development and test, would take them for an N+1
19
+ without_n_plus_one_detection do
20
+ reorder_params.each do |id, position|
21
+ object = objects[id.to_i]
22
+ object.update(position:) unless object.position == position
23
+ end
17
24
  end
18
25
 
19
26
  redirect_to reorder_success_redirect, notice: reorder_notice
@@ -42,6 +49,10 @@ module Trek
42
49
  [:admin, *model_collection_route]
43
50
  end
44
51
 
52
+ def without_n_plus_one_detection(&)
53
+ defined?(Prosopite) ? Prosopite.pause(&) : yield
54
+ end
55
+
45
56
  def reorder_notice
46
57
  t("admin.#{model_collection}.reorder.success")
47
58
  end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Trek
4
+ # Receives the reports browsers send about Content Security Policy violations, at the policy's
5
+ # report-uri (`post "csp-reports"`, from `trek:install:security_headers`). Each violation is logged,
6
+ # and reported to AppSignal when the app uses it: in a "csp" namespace, as one incident per
7
+ # directive and blocked origin, so a new violation is notified once.
8
+ #
9
+ # Anyone can send reports, so a flood mustn't bury the real violations in AppSignal: it gets each
10
+ # violation once an hour at most, and NEW_VIOLATIONS_PER_HOUR different ones at most, the others
11
+ # being logged only. Requests are rate-limited per IP address, and for all of them together. The
12
+ # counters are in Rails.cache: a cache per process or server counts on its own.
13
+ #
14
+ # Browsers send no CSRF token nor session: the endpoint needs neither, sets no cookie, and answers
15
+ # 204 (429 past the rate limits).
16
+ class CspReportsController < ActionController::Base # rubocop:disable Rails/ApplicationController
17
+ # A report is a few hundred bytes; the Reporting API may group a few
18
+ MAX_BODY = 64.kilobytes
19
+ NEW_VIOLATIONS_PER_HOUR = 20
20
+
21
+ # Browsers send no CSRF token; the endpoint only logs and reports, with no session nor user
22
+ skip_forgery_protection
23
+ rate_limit to: 60, within: 1.minute, with: -> { head :too_many_requests }
24
+ # Against a flood from many addresses
25
+ rate_limit to: 600, within: 1.minute, by: -> { "all" }, with: -> { head :too_many_requests }
26
+
27
+ def create
28
+ body = request.body.read(MAX_BODY + 1).to_s
29
+ CspReports.parse(body, host: request.host).each { |violation| report(violation) } if body.bytesize <= MAX_BODY
30
+
31
+ head :no_content
32
+ end
33
+
34
+ private
35
+
36
+ def report(violation)
37
+ logger.warn("[CSP] #{violation}")
38
+ return unless defined?(::Appsignal) && ::Appsignal.respond_to?(:report_error) && first_this_hour?(violation)
39
+
40
+ ::Appsignal.report_error(CspViolation.new(violation.to_s)) do
41
+ ::Appsignal.set_namespace("csp")
42
+ ::Appsignal.set_action(incident(violation))
43
+ ::Appsignal.add_tags(page: violation.page, disposition: violation.disposition)
44
+ end
45
+ end
46
+
47
+ # AppSignal groups the violations by action: the directive and the blocked origin
48
+ def incident(violation)
49
+ "#{violation.directive} #{violation.blocked}"
50
+ end
51
+
52
+ # Not reported yet this hour, and among the hour's first new violations
53
+ def first_this_hour?(violation)
54
+ return false unless Rails.cache.write("trek/csp_reports/#{incident(violation)}", true, expires_in: 1.hour, unless_exist: true)
55
+
56
+ Rails.cache.increment("trek/csp_reports/new", 1, expires_in: 1.hour).to_i <= NEW_VIOLATIONS_PER_HOUR
57
+ end
58
+ end
59
+ end
@@ -1,6 +1,9 @@
1
1
  module Trek
2
2
  module Panels
3
3
  class BaseController < Trek::BaseController
4
+ # Stands in for a page in the link and prompt panels' choices when the current
5
+ # href isn't a page's global id (another site, a path, a mailto:…), so the select keeps it
6
+ HrefPlaceholder = Data.define(:to_global_id, :title)
4
7
  end
5
8
  end
6
9
  end
@@ -29,7 +29,7 @@ module Trek
29
29
 
30
30
  def set_pages
31
31
  @pages = []
32
- @pages << OpenStruct.new(to_global_id: object_params[:href], title: object_params[:href]) if object_params[:href] && !object_params[:href].start_with?("gid")
32
+ @pages << HrefPlaceholder.new(to_global_id: object_params[:href], title: object_params[:href]) if object_params[:href] && !object_params[:href].start_with?("gid")
33
33
  @pages += Page.alpha_ordered if defined?(Page)
34
34
  end
35
35
 
@@ -29,7 +29,7 @@ module Trek
29
29
 
30
30
  def set_pages
31
31
  @pages = []
32
- @pages << OpenStruct.new(to_global_id: object_params[:href], title: object_params[:href]) if object_params[:href] && !object_params[:href].start_with?("gid")
32
+ @pages << HrefPlaceholder.new(to_global_id: object_params[:href], title: object_params[:href]) if object_params[:href] && !object_params[:href].start_with?("gid")
33
33
  @pages += Page.alpha_ordered if defined?(Page)
34
34
  end
35
35
 
@@ -62,7 +62,13 @@ module Trek
62
62
  end
63
63
 
64
64
  def destroy
65
- @object.destroy
65
+ # Refused by the model, e.g. with `dependent: :restrict_with_error`: says why
66
+ unless @object.destroy
67
+ return respond_to do |format|
68
+ format.html { redirect_back_or_to [:admin, @object], alert: @object.errors.full_messages.to_sentence }
69
+ format.json { render json: @object.errors, status: :unprocessable_entity }
70
+ end
71
+ end
66
72
 
67
73
  destroy_hook
68
74
 
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Trek
4
+ module AuditLogsHelper
5
+ # A record's name, linked to its admin page when the viewer may open it. Records without an
6
+ # admin page, or deleted since, show their name only.
7
+ def audit_log_record_link(record)
8
+ return if record.nil?
9
+ return record.to_s unless allowed_to?(:show?, record)
10
+
11
+ link_to record.to_s, [:admin, record]
12
+ rescue ActionPolicy::NotFound, NoMethodError, ActionController::UrlGenerationError
13
+ record.to_s
14
+ end
15
+
16
+ # The audit log of a record, for a button on its admin page.
17
+ def audit_log_path_for(record)
18
+ admin_audit_logs_path(filters: { auditable_type: record.class.polymorphic_name, auditable_id: record.id })
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,11 @@
1
+ module Trek
2
+ # The URL of an uploaded image's thumbnail: through Shrine's derivation endpoint when the uploader loads
3
+ # it (the generated ImageUploader comments it out), or the image itself otherwise
4
+ module ThumbnailHelper
5
+ module_function
6
+
7
+ def thumbnail_url(file, width, height)
8
+ file.respond_to?(:derivation_url) ? file.derivation_url(:thumbnail, width, height) : file.url
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Trek
4
+ module UserAgentsHelper
5
+ # Checked in order: Edge and Opera also name Chrome, Chrome also names Safari.
6
+ BROWSERS = {
7
+ "Edge" => %r{Edg/},
8
+ "Opera" => %r{OPR/},
9
+ "Firefox" => %r{Firefox/},
10
+ "Chrome" => %r{Chrome/},
11
+ "Safari" => %r{Safari/}
12
+ }.freeze
13
+
14
+ # Checked in order: an iPad also names Mac OS X, Android also names Linux.
15
+ SYSTEMS = {
16
+ "iOS" => /iPhone|iPad/,
17
+ "Android" => /Android/,
18
+ "macOS" => /Mac OS X/,
19
+ "Windows" => /Windows/,
20
+ "Linux" => /Linux/
21
+ }.freeze
22
+
23
+ # The browser and system a User-Agent header names, e.g. "Firefox on Windows"
24
+ def user_agent_summary(user_agent)
25
+ user_agent = user_agent.to_s
26
+ browser = BROWSERS.find { |_name, pattern| user_agent.match?(pattern) }&.first
27
+ system = SYSTEMS.find { |_name, pattern| user_agent.match?(pattern) }&.first
28
+
29
+ if browser && system
30
+ t("trek.user_agents.browser_on_system", browser:, system:)
31
+ else
32
+ browser || system || t("trek.user_agents.unknown")
33
+ end
34
+ end
35
+ end
36
+ end
@@ -7,6 +7,9 @@ import { application } from "./application";
7
7
  import ElementController from "./element_controller";
8
8
  application.register("element", ElementController);
9
9
 
10
+ import PasskeyController from "./passkey_controller";
11
+ application.register("passkey", PasskeyController);
12
+
10
13
  import RemovableElementController from "./removable_element_controller";
11
14
  application.register("removable-element", RemovableElementController);
12
15
 
@@ -0,0 +1,118 @@
1
+ import { Controller } from "@hotwired/stimulus";
2
+
3
+ // Undefined in browsers without WebAuthn, and unknown to ESLint's browser globals
4
+ const { PublicKeyCredential } = window;
5
+
6
+ // Adds a passkey, or signs in with one, from a form posting the credential: fetches the options
7
+ // from the server, lets the browser create or get the credential, then submits the form with it.
8
+ //
9
+ // Its element stays hidden in browsers without WebAuthn's JSON methods (Safari before 18.4…), so
10
+ // it also hides a link leading to passkeys, without any action. With `conditional`, the site's
11
+ // passkeys are also offered in the autofill of the email field (`autocomplete="username webauthn"`).
12
+ export default class extends Controller {
13
+ static targets = ["credential", "error", "alreadyAdded"];
14
+ static values = { optionsUrl: String, conditional: Boolean };
15
+
16
+ connect() {
17
+ if (!supported()) return;
18
+
19
+ this.element.hidden = false;
20
+ if (this.conditionalValue) this.offerInAutofill();
21
+ }
22
+
23
+ disconnect() {
24
+ this.autofill?.abort();
25
+ }
26
+
27
+ // Submitting the form (its button, or Enter in a field) creates the passkey first
28
+ submit(event) {
29
+ if (this.credentialTarget.value) return;
30
+
31
+ event.preventDefault();
32
+ this.create();
33
+ }
34
+
35
+ create() {
36
+ this.run((options) =>
37
+ navigator.credentials.create({
38
+ publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(options),
39
+ })
40
+ );
41
+ }
42
+
43
+ get() {
44
+ // The button replaces the pending autofill request: the browser runs one at a time
45
+ this.autofill?.abort();
46
+ this.run((options) =>
47
+ navigator.credentials.get({
48
+ publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options),
49
+ })
50
+ );
51
+ }
52
+
53
+ async offerInAutofill() {
54
+ if (!(await PublicKeyCredential.isConditionalMediationAvailable?.())) {
55
+ return;
56
+ }
57
+
58
+ this.autofill = new AbortController();
59
+ const { signal } = this.autofill;
60
+ // The user asked for nothing yet: a failure here stays silent
61
+ this.run(
62
+ (options) =>
63
+ navigator.credentials.get({
64
+ publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options),
65
+ mediation: "conditional",
66
+ signal,
67
+ }),
68
+ { silent: true }
69
+ );
70
+ }
71
+
72
+ async run(ceremony, { silent = false } = {}) {
73
+ if (!silent) this.hideError();
74
+
75
+ try {
76
+ const credential = await ceremony(await this.fetchOptions());
77
+ this.credentialTarget.value = JSON.stringify(credential.toJSON());
78
+ this.element.requestSubmit();
79
+ } catch (error) {
80
+ if (!silent) this.showError(error);
81
+ }
82
+ }
83
+
84
+ async fetchOptions() {
85
+ const response = await fetch(this.optionsUrlValue, {
86
+ headers: { Accept: "application/json" },
87
+ });
88
+ if (!response.ok) throw new Error(`Passkey options: ${response.status}`);
89
+
90
+ return response.json();
91
+ }
92
+
93
+ showError(error) {
94
+ // Cancelled by the user, timed out, or replaced by another request: nothing to say
95
+ if (["NotAllowedError", "AbortError"].includes(error.name)) return;
96
+ // The authenticator already holds one of the user's passkeys
97
+ if (error.name === "InvalidStateError" && this.hasAlreadyAddedTarget) {
98
+ this.alreadyAddedTarget.hidden = false;
99
+ } else if (this.hasErrorTarget) {
100
+ this.errorTarget.hidden = false;
101
+ } else {
102
+ throw error;
103
+ }
104
+ }
105
+
106
+ hideError() {
107
+ [...this.errorTargets, ...this.alreadyAddedTargets].forEach((target) => {
108
+ target.hidden = true;
109
+ });
110
+ }
111
+ }
112
+
113
+ function supported() {
114
+ return (
115
+ PublicKeyCredential !== undefined &&
116
+ "parseCreationOptionsFromJSON" in PublicKeyCredential
117
+ );
118
+ }
@@ -1,5 +1,9 @@
1
1
  import "@hotwired/turbo-rails";
2
2
  import "./controllers";
3
3
  import "normalize.css";
4
+ // The admin's font, served by the app rather than Google Fonts
5
+ import "@fontsource/inter/400.css";
6
+ import "@fontsource/inter/500.css";
7
+ import "@fontsource/inter/600.css";
4
8
  import "../assets/stylesheets/trek/base.css";
5
9
  import "../components";
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Trek
4
+ module AuditLog
5
+ # Deletes the audit log rows older than the retention window: 6 months by default, the low end of
6
+ # the CNIL's recommendation for logs (6 months to 1 year). Schedule it daily with the app's Active
7
+ # Job backend, e.g. a GoodJob cron entry.
8
+ # rubocop:disable Rails/ApplicationJob -- the gem can't rely on the host app's ApplicationJob
9
+ class PurgeJob < ActiveJob::Base
10
+ class_attribute :retention, default: 6.months
11
+
12
+ def perform(retention: self.class.retention)
13
+ ::AuditLog.older_than(retention.ago).in_batches(of: 1000).delete_all
14
+ end
15
+ end
16
+ # rubocop:enable Rails/ApplicationJob
17
+ end
18
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Trek
4
+ # Deletes the signed-in browsers past their idle timeout or lifetime (Trek::Users::SessionLifetime):
5
+ # they can't sign anyone in anymore. Schedule it daily with the app's Active Job backend, e.g. a
6
+ # GoodJob cron entry.
7
+ # rubocop:disable Rails/ApplicationJob -- the gem can't rely on the host app's ApplicationJob
8
+ class PurgeExpiredSessionsJob < ActiveJob::Base
9
+ def perform
10
+ ::User::Session.expired.in_batches(of: 1000).delete_all
11
+ end
12
+ end
13
+ # rubocop:enable Rails/ApplicationJob
14
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Trek
4
+ # Records the host name of the IP address a session signed in from (Trek::ReverseDns), after the
5
+ # sign-in rather than during it: the lookup can take up to a second.
6
+ # rubocop:disable Rails/ApplicationJob -- the gem can't rely on the host app's ApplicationJob
7
+ class ResolveSessionHostnameJob < ActiveJob::Base
8
+ # The session may be gone by then: signed out, or purged
9
+ discard_on ActiveJob::DeserializationError
10
+
11
+ def perform(session)
12
+ hostname = ReverseDns.hostname(session.ip_address)
13
+ session.update_column(:ip_hostname, hostname) if hostname # rubocop:disable Rails/SkipsModelValidations
14
+ end
15
+ end
16
+ # rubocop:enable Rails/ApplicationJob
17
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Trek
4
+ # One row per audited request, written by Trek::Auditable. Append-only: rows are never updated,
5
+ # only purged after the retention window by Trek::AuditLog::PurgeJob.
6
+ module AuditLog
7
+ extend ActiveSupport::Concern
8
+
9
+ included do
10
+ belongs_to :actor, polymorphic: true, optional: true
11
+ belongs_to :auditable, polymorphic: true, optional: true
12
+
13
+ scope :for_actor, ->(actor) { where(actor:) }
14
+ scope :for_auditable, ->(auditable) { where(auditable:) }
15
+ scope :failures, -> { where(http_status: 400..).or(where.not(error_class: nil)) }
16
+ scope :recent, -> { order(created_at: :desc) }
17
+ scope :ordered, -> { recent }
18
+ scope :older_than, ->(time) { where(created_at: ...time) }
19
+ end
20
+
21
+ # Rows can't be changed once written; the purge uses delete_all, which skips this.
22
+ def readonly?
23
+ persisted? || super
24
+ end
25
+
26
+ def to_s
27
+ [created_at&.iso8601, action, http_status].compact.join(" – ")
28
+ end
29
+ end
30
+ end
@@ -8,16 +8,20 @@ module Trek
8
8
  content.is_a?(Hash) ? content : JSON.parse(content)
9
9
  end
10
10
 
11
- def formatted_content
11
+ # The content as a Prosemirror::Document, built with Trek::Content.schema. Problems found while parsing
12
+ # or rendering it are reported with the record in their context (see Trek::Content::Document).
13
+ def content_document
12
14
  return if content.blank?
13
15
 
14
- Prosemirror.new.format_content(parsed_content)
16
+ Trek::Content::Document.parse(self, parsed_content)
15
17
  end
16
18
 
17
- def content_text
18
- return if content.blank?
19
+ def formatted_content
20
+ content_document&.to_html
21
+ end
19
22
 
20
- extract_text(parsed_content)
23
+ def content_text
24
+ content_document&.text_content
21
25
  end
22
26
 
23
27
  def prosemirror_content?
@@ -27,14 +31,5 @@ module Trek
27
31
  else false
28
32
  end
29
33
  end
30
-
31
- private
32
-
33
- def extract_text(node)
34
- return node["text"].to_s if node["type"] == "text"
35
- return "" unless node["content"]
36
-
37
- node["content"].map { |child| extract_text(child) }.join
38
- end
39
34
  end
40
35
  end
@@ -21,9 +21,10 @@ module Trek
21
21
  super || build_page(parent: default_parent_page)
22
22
  end
23
23
 
24
+ # The admin links to records by id, the site by slug.
24
25
  def to_param
25
26
  # TODO: find a better way?
26
- if caller.to_s.include?("admin")
27
+ if called_from_admin?
27
28
  id || super
28
29
  else
29
30
  page&.slug || super
@@ -96,5 +97,13 @@ module Trek
96
97
  def apply_default_parent_page
97
98
  page.parent = default_parent_page
98
99
  end
100
+
101
+ # Whether an admin file (controller, view, layout, mailer…) is in the call stack. Trek::AdminIpAllowlist
102
+ # doesn't count: a middleware, it sits in the stack of every request, the site's included.
103
+ def called_from_admin?
104
+ caller_locations.any? do |location|
105
+ location.path.include?("admin") && !location.path.end_with?("/lib/trek/admin_ip_allowlist.rb")
106
+ end
107
+ end
99
108
  end
100
109
  end