command_tower 0.22.0 → 0.23.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 (124) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/command_tower/admin/messaging/gallery_controller.rb +35 -0
  3. data/app/controllers/command_tower/admin/messaging/gallery_test_sends_controller.rb +54 -0
  4. data/app/controllers/command_tower/me/inbox_controller.rb +19 -4
  5. data/app/controllers/command_tower/messaging/unsubscribe_controller.rb +43 -0
  6. data/app/controllers/concerns/command_tower/execution/http_boundary.rb +36 -1
  7. data/app/errors/command_tower/errors/messaging/announcement_type_not_supported_error.rb +23 -0
  8. data/app/errors/command_tower/errors/messaging/gallery_test_send_failed_error.rb +26 -0
  9. data/app/errors/command_tower/errors/messaging/gallery_test_send_impersonating_error.rb +23 -0
  10. data/app/errors/command_tower/errors/messaging/gallery_test_send_rate_limit_error.rb +25 -0
  11. data/app/errors/command_tower/errors/messaging/unsubscribe_rate_limit_error.rb +25 -0
  12. data/app/jobs/command_tower/messaging/communications/produce_recipient_job.rb +2 -2
  13. data/app/mailers/command_tower/messaging/channel_mailer.rb +2 -0
  14. data/app/models/command_tower/messaging/communication.rb +10 -0
  15. data/app/serializers/command_tower/serializers/admin/messaging/gallery_serializer.rb +67 -0
  16. data/app/services/command_tower/email_theme/resolver.rb +13 -12
  17. data/app/services/command_tower/messaging/accept/coordinator.rb +57 -4
  18. data/app/services/command_tower/messaging/accept/persister.rb +3 -0
  19. data/app/services/command_tower/messaging/accept/request_normalizer.rb +9 -4
  20. data/app/services/command_tower/messaging/accept/resolve_communication_slots.rb +114 -0
  21. data/app/services/command_tower/messaging/announcement_definition.rb +88 -0
  22. data/app/services/command_tower/messaging/contract/inbox.rb +65 -0
  23. data/app/services/command_tower/messaging/contract/mappers/communication_mapper.rb +9 -0
  24. data/app/services/command_tower/messaging/contract/requests/mark_viewed_for_communication.rb +21 -0
  25. data/app/services/command_tower/messaging/contract/requests/viewed_for_communication.rb +21 -0
  26. data/app/services/command_tower/messaging/contract/results/communication_result.rb +3 -0
  27. data/app/services/command_tower/messaging/contract/results/inbox_view_mark.rb +18 -0
  28. data/app/services/command_tower/messaging/definitions/document_builder.rb +157 -0
  29. data/app/services/command_tower/messaging/definitions/render_context.rb +18 -0
  30. data/app/services/command_tower/messaging/inbox/item_result.rb +5 -1
  31. data/app/services/command_tower/messaging/inbox/mutator.rb +17 -0
  32. data/app/services/command_tower/messaging/inbox/reader.rb +12 -0
  33. data/app/services/command_tower/messaging/inbox/scope.rb +8 -0
  34. data/app/services/command_tower/messaging/inbox.rb +8 -0
  35. data/app/services/command_tower/messaging/message_definition/metadata.rb +35 -0
  36. data/app/services/command_tower/messaging/message_definition.rb +151 -0
  37. data/app/services/command_tower/messaging/notification_types/declaration.rb +12 -1
  38. data/app/services/command_tower/messaging/notification_types/message_definition_checks.rb +143 -0
  39. data/app/services/command_tower/messaging/notification_types/registry.rb +2 -0
  40. data/app/services/command_tower/messaging/rendering/channel_renderer.rb +73 -6
  41. data/app/services/command_tower/messaging/rendering/compliance_footer.rb +80 -0
  42. data/app/services/command_tower/messaging/rendering/defined_email_renderer.rb +141 -0
  43. data/app/services/command_tower/messaging/rendering/inbox_document_renderer.rb +79 -4
  44. data/app/services/command_tower/messaging/rendering/rendered_payload.rb +13 -1
  45. data/app/services/command_tower/messaging/rendering/unsubscribe_headers.rb +51 -0
  46. data/app/services/command_tower/messaging/unsubscribe/token_verifier.rb +26 -0
  47. data/app/services/command_tower/services/messaging/announcements/resolve_produce_arguments.rb +74 -0
  48. data/app/services/command_tower/services/messaging/communications/explicit_copy_rule.rb +50 -0
  49. data/app/services/command_tower/services/messaging/communications/produce.rb +18 -4
  50. data/app/services/command_tower/services/messaging/communications/produce_many.rb +20 -2
  51. data/app/services/command_tower/services/messaging/gallery/channel_failed.rb +31 -0
  52. data/app/services/command_tower/services/messaging/gallery/check_test_send_rate_limit.rb +47 -0
  53. data/app/services/command_tower/services/messaging/gallery/list_gallery_types.rb +44 -0
  54. data/app/services/command_tower/services/messaging/gallery/preview_builder.rb +122 -0
  55. data/app/services/command_tower/services/messaging/gallery/preview_channels.rb +51 -0
  56. data/app/services/command_tower/services/messaging/gallery/preview_checks.rb +85 -0
  57. data/app/services/command_tower/services/messaging/gallery/preview_email.rb +56 -0
  58. data/app/services/command_tower/services/messaging/gallery/render_gallery_preview.rb +85 -0
  59. data/app/services/command_tower/services/messaging/gallery/test_send.rb +55 -0
  60. data/app/services/command_tower/services/messaging/inbox.rb +36 -8
  61. data/app/services/command_tower/services/messaging/unsubscribe/check_rate_limit.rb +57 -0
  62. data/app/services/command_tower/services/messaging/unsubscribe/issue_token.rb +25 -0
  63. data/app/services/command_tower/services/messaging/unsubscribe/opt_out_of_email.rb +65 -0
  64. data/app/services/command_tower/services/messaging/unsubscribe/verify_token.rb +42 -0
  65. data/app/services/command_tower/services/users/record_last_known_time_zone.rb +40 -0
  66. data/app/workflows/command_tower/workflows/admin/messaging/create_announcement_workflow.rb +16 -3
  67. data/app/workflows/command_tower/workflows/admin/messaging/gallery/index_workflow.rb +29 -0
  68. data/app/workflows/command_tower/workflows/admin/messaging/gallery/show_workflow.rb +40 -0
  69. data/app/workflows/command_tower/workflows/admin/messaging/gallery/test_send_workflow.rb +103 -0
  70. data/app/workflows/command_tower/workflows/messaging/communications/produce_recipient_workflow.rb +2 -2
  71. data/app/workflows/command_tower/workflows/messaging/error_mapping.rb +8 -1
  72. data/app/workflows/command_tower/workflows/messaging/inbox.rb +30 -5
  73. data/app/workflows/command_tower/workflows/messaging/unsubscribe/one_click_workflow.rb +56 -0
  74. data/app/workflows/command_tower/workflows/messaging/unsubscribe/preferences_redirect_workflow.rb +24 -0
  75. data/config/routes.rb +9 -0
  76. data/db/migrate/20261124000001_add_message_definition_columns_to_messaging_communications.rb +9 -0
  77. data/docs/admin_workspace.md +2 -1
  78. data/docs/api_reference.md +78 -20
  79. data/docs/audit.md +9 -0
  80. data/docs/authentication_authorization_guide.md +1 -1
  81. data/docs/bootstrap/09-rbac.md +2 -0
  82. data/docs/bootstrap/11-auth-client-path.md +1 -1
  83. data/docs/cookie_authentication_guide.md +2 -0
  84. data/docs/extending.md +4 -0
  85. data/docs/messaging_integration_guide.md +40 -15
  86. data/docs/principal_capabilities.md +2 -0
  87. data/docs/ui.md +64 -2
  88. data/docs/upgrades/0.23.0.md +64 -0
  89. data/docs/upgrades/README.md +1 -0
  90. data/lib/command_tower/authorization/default.yml +8 -0
  91. data/lib/command_tower/configuration/messaging/compliance.rb +47 -0
  92. data/lib/command_tower/configuration/messaging/config.rb +25 -0
  93. data/lib/command_tower/configuration/registry/admin_workspace/config.rb +9 -0
  94. data/lib/command_tower/configuration/registry/admin_workspace/tool_definition.rb +10 -1
  95. data/lib/command_tower/configuration/registry/audit/config.rb +38 -0
  96. data/lib/command_tower/configuration/registry/principal_capabilities/config.rb +2 -0
  97. data/lib/command_tower/current.rb +1 -0
  98. data/lib/command_tower/email_theme/default_ui_tokens.json +18 -0
  99. data/lib/command_tower/email_theme/palette.rb +75 -0
  100. data/lib/command_tower/email_theme/token_file.rb +81 -0
  101. data/lib/command_tower/engine.rb +7 -0
  102. data/lib/command_tower/execution.rb +2 -1
  103. data/lib/command_tower/install/baseline.rb +1 -0
  104. data/lib/command_tower/rspec/message_definition.rb +125 -0
  105. data/lib/command_tower/ui/document.rb +18 -4
  106. data/lib/command_tower/ui/email/renderer/text_nodes.rb +2 -1
  107. data/lib/command_tower/ui/email/renderer.rb +17 -5
  108. data/lib/command_tower/ui/email/text_part.rb +53 -0
  109. data/lib/command_tower/ui/fragments/markdown.rb +121 -0
  110. data/lib/command_tower/ui/markdown_subset/chunker.rb +91 -0
  111. data/lib/command_tower/ui/markdown_subset/inline.rb +86 -0
  112. data/lib/command_tower/ui/markdown_subset/segment.rb +15 -0
  113. data/lib/command_tower/ui/markdown_subset/walker.rb +129 -0
  114. data/lib/command_tower/ui/nodes/instant.rb +3 -0
  115. data/lib/command_tower/ui/redaction.rb +44 -0
  116. data/lib/command_tower/ui/required_facts/matchers/text.rb +22 -0
  117. data/lib/command_tower/ui/required_facts/matchers/time.rb +37 -0
  118. data/lib/command_tower/ui/required_facts/verdict.rb +54 -0
  119. data/lib/command_tower/ui/text_derivation.rb +18 -17
  120. data/lib/command_tower/ui/time_formatter.rb +5 -3
  121. data/lib/command_tower/ui.rb +6 -0
  122. data/lib/command_tower/version.rb +1 -1
  123. data/lib/command_tower.rb +2 -0
  124. metadata +78 -2
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "class_composer"
4
+
5
+ module CommandTower
6
+ module Configuration
7
+ module Messaging
8
+ class Compliance < ::CommandTower::Configuration::Base
9
+ include ClassComposer::Generator
10
+
11
+ add_composer :api_base_url,
12
+ desc: "Public API origin used to build the one-click unsubscribe URL (no trailing slash, " \
13
+ "no /api). Defaults to ENV COMMAND_TOWER_API_BASE_URL when set, else nil " \
14
+ "(unsubscribe headers are omitted).",
15
+ allowed: [String, NilClass],
16
+ default: nil,
17
+ default_shown: 'ENV["COMMAND_TOWER_API_BASE_URL"]'
18
+
19
+ add_composer :preferences_path,
20
+ desc: "Host path of the notification preferences page, appended to " \
21
+ "config.application.composed_url in the email footer. " \
22
+ "Default nil (footer links to composed_url).",
23
+ allowed: [String, NilClass],
24
+ default: nil
25
+
26
+ add_composer :postal_address,
27
+ desc: "Physical postal address printed in the footer of promotional email. Required for any " \
28
+ "promotional MessageDefinition. Default nil.",
29
+ allowed: [String, NilClass],
30
+ default: nil
31
+
32
+ add_composer :unsubscribe_secret,
33
+ desc: "Optional secret overriding the key derived from secret_key_base for unsubscribe " \
34
+ "tokens. Never log. Default nil.",
35
+ allowed: [String, NilClass],
36
+ default: nil
37
+
38
+ # The ENV fallback is read at call time so it is not frozen at load.
39
+ alias configured_api_base_url api_base_url
40
+
41
+ def api_base_url
42
+ configured_api_base_url.presence || ENV["COMMAND_TOWER_API_BASE_URL"].presence
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -4,6 +4,7 @@ require "class_composer"
4
4
  require "command_tower/configuration/messaging/sms"
5
5
  require "command_tower/configuration/messaging/pushover"
6
6
  require "command_tower/configuration/messaging/expo"
7
+ require "command_tower/configuration/messaging/compliance"
7
8
 
8
9
  module CommandTower
9
10
  module Configuration
@@ -70,6 +71,30 @@ module CommandTower
70
71
  desc: "Expo Push delivery configuration (Messaging push channel; optional access_token)",
71
72
  allowed: Expo,
72
73
  default: Expo.new
74
+
75
+ add_composer :compliance,
76
+ desc: "Email compliance configuration for MessageDefinition types (unsubscribe origin, " \
77
+ "preferences path, postal address, token secret)",
78
+ allowed: Compliance,
79
+ default: Compliance.new
80
+
81
+ add_composer :strict_definitions,
82
+ desc: "When true, MessageDefinition violations (metadata schema, explicit copy on a defined " \
83
+ "type) fail the request; when false they are logged and degraded. Default true in " \
84
+ "development and test, false in production.",
85
+ allowed: [TrueClass, FalseClass, NilClass],
86
+ default: nil,
87
+ default_shown: "!Rails.env.production?"
88
+
89
+ # nil means "not set by the host": resolve from the Rails env at call time.
90
+ alias configured_strict_definitions strict_definitions
91
+
92
+ def strict_definitions
93
+ configured = configured_strict_definitions
94
+ return configured unless configured.nil?
95
+
96
+ !(defined?(::Rails) && ::Rails.respond_to?(:env) && ::Rails.env.production?)
97
+ end
73
98
  end
74
99
  end
75
100
  end
@@ -35,6 +35,15 @@ module CommandTower
35
35
  sort_order: 200,
36
36
  required_entity: "admin_messaging_announcements",
37
37
  icon: "megaphone"
38
+ },
39
+ messaging_gallery: {
40
+ label: "Message gallery",
41
+ description: "Preview every channel for each message type.",
42
+ route: "/admin/messaging/gallery",
43
+ group: "messaging",
44
+ sort_order: 210,
45
+ required_entity: "admin_messaging_gallery",
46
+ icon: "layout-template"
38
47
  }
39
48
  }.freeze
40
49
 
@@ -11,6 +11,9 @@ module CommandTower
11
11
 
12
12
  ROUTE = %r{\A/admin(/[a-z][a-z0-9_-]*)+\z}
13
13
 
14
+ # Icon names may be kebab-case (for example `layout-template`).
15
+ ICON = /\A[a-z][a-z0-9_-]*\z/
16
+
14
17
  DESCRIPTION_MAX_LENGTH = 160
15
18
 
16
19
  add_composer :label,
@@ -130,7 +133,13 @@ module CommandTower
130
133
  def normalize_icon!(name:)
131
134
  return if icon.nil? || icon.to_s.strip.empty?
132
135
 
133
- require_segment!(icon, field: "icon", name:)
136
+ token = icon.to_s.strip
137
+ unless token.match?(ICON)
138
+ raise CommandTower::AdminWorkspace::InvalidToolDefinitionError,
139
+ "admin workspace tool #{name} has invalid icon #{icon.inspect}"
140
+ end
141
+
142
+ token
134
143
  end
135
144
 
136
145
  def normalize_scope!(name:)
@@ -202,6 +202,32 @@ module CommandTower
202
202
  subject_required: false,
203
203
  affected_user_required: false
204
204
  },
205
+ messaging_unsubscribed: {
206
+ label: "Unsubscribed from email",
207
+ tags: %w[messaging preferences unsubscribe],
208
+ enabled: true,
209
+ enablement_configurable: false,
210
+ user_history: true,
211
+ sensitive_fields: [],
212
+ allowed_changes: %i[email_enabled],
213
+ retention: :permanent,
214
+ subject_required: true,
215
+ subject_type: "User",
216
+ affected_user_required: true,
217
+ global_visible_in_host_scope: true
218
+ },
219
+ messaging_gallery_test_sent: {
220
+ label: "Gallery test message sent",
221
+ tags: %w[messaging gallery admin],
222
+ enabled: true,
223
+ enablement_configurable: false,
224
+ user_history: false,
225
+ sensitive_fields: [],
226
+ allowed_changes: [],
227
+ retention: :one_year,
228
+ subject_required: false,
229
+ affected_user_required: true
230
+ },
205
231
  session_created: {
206
232
  label: "Session created",
207
233
  tags: %w[authentication session security],
@@ -266,6 +292,18 @@ module CommandTower
266
292
  affected_user_required: true,
267
293
  global_visible_in_host_scope: true
268
294
  },
295
+ messaging_inbox_item_viewed: {
296
+ label: "Inbox item viewed",
297
+ tags: %w[messaging inbox],
298
+ enabled: true,
299
+ enablement_configurable: true,
300
+ user_history: false,
301
+ sensitive_fields: [],
302
+ allowed_changes: [],
303
+ retention: :ninety_days,
304
+ subject_required: false,
305
+ affected_user_required: true
306
+ },
269
307
  experience_state_completed: {
270
308
  label: "Experience state completed",
271
309
  tags: %w[experience account],
@@ -14,6 +14,8 @@ module CommandTower
14
14
  admin_workspace
15
15
  admin_audit_events
16
16
  admin_messaging_announcements
17
+ admin_messaging_gallery
18
+ admin_messaging_gallery_test_send
17
19
  admin_users
18
20
  admin_users_update
19
21
  admin_rbac_assignments
@@ -17,5 +17,6 @@ module CommandTower
17
17
  attribute :user_agent
18
18
  attribute :client_compatibility_recommendation
19
19
  attribute :ui_catalog, default: 1
20
+ attribute :client_time_zone
20
21
  end
21
22
  end
@@ -0,0 +1,18 @@
1
+ {
2
+ "version": 1,
3
+ "palette": {
4
+ "background": "#f4f5f7",
5
+ "card": "#ffffff",
6
+ "border": "#e2e8f0",
7
+ "primary": "#2b6cb0",
8
+ "primaryForeground": "#ffffff",
9
+ "foreground": "#4a5568",
10
+ "textPrimary": "#1a202c",
11
+ "textSecondary": "#718096",
12
+ "muted": "#f4f5f7",
13
+ "mutedForeground": "#718096",
14
+ "success": "#358d64",
15
+ "warning": "#f59f0a",
16
+ "danger": "#dc2828"
17
+ }
18
+ }
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module EmailTheme
5
+ # Resolves the 13-key palette the email renderer takes (design D19).
6
+ #
7
+ # Precedence:
8
+ # 1. host `config/ui_tokens.json` (when present)
9
+ # 2. host-customised 9-key `config.email_theme` (legacy adapter; muted,
10
+ # success, warning and danger come from the CT default)
11
+ # 3. CT default file (`default_ui_tokens.json`)
12
+ module Palette
13
+ KEYS = UI::Email::Styles::PALETTE_KEYS
14
+
15
+ # config.email_theme key -> palette key(s) it feeds in the legacy adapter,
16
+ # and the palette key each legacy key is derived from (Resolver).
17
+ LEGACY_TO_PALETTE = {
18
+ canvas_background: "background",
19
+ surface_background: "card",
20
+ surface_border: "border",
21
+ primary_text: "textPrimary",
22
+ body_text: "foreground",
23
+ muted_text: "mutedForeground",
24
+ accent: "primary",
25
+ text_on_accent: "primaryForeground",
26
+ primary_action: "primary"
27
+ }.freeze
28
+
29
+ class << self
30
+ # Returns a frozen Hash with exactly the 13 PALETTE_KEYS.
31
+ def resolve(host_path: TokenFile.host_path)
32
+ return pick(TokenFile.load_palette(host_path)) if TokenFile.host_file?(host_path)
33
+ return legacy_palette if legacy_customised?
34
+
35
+ default_palette
36
+ end
37
+
38
+ def default_palette
39
+ pick(TokenFile.load_palette(TokenFile::DEFAULT_PATH))
40
+ end
41
+
42
+ # The 9 legacy keys derived from a palette (Resolver, when a host file exists).
43
+ def legacy_keys_from(palette)
44
+ LEGACY_TO_PALETTE.transform_values { |key| palette.fetch(key) }
45
+ end
46
+
47
+ def legacy_customised?
48
+ legacy_keys_from(default_palette) != legacy_theme_values
49
+ end
50
+
51
+ private
52
+
53
+ def legacy_theme_values
54
+ theme = CommandTower.config.email_theme
55
+ LEGACY_TO_PALETTE.keys.index_with { |key| theme.public_send(key) }
56
+ end
57
+
58
+ def legacy_palette
59
+ # `muted_text` feeds both muted-text keys so the secondary text role stays consistent.
60
+ # `accent` and `primary_action` both feed `primary`; only a customised value overrides
61
+ # the default, and `accent` wins when both are customised.
62
+ defaults = legacy_keys_from(default_palette)
63
+ customised = legacy_theme_values.reject { |key, value| value == defaults.fetch(key) }
64
+ overrides = customised.reverse_each.to_h { |key, value| [LEGACY_TO_PALETTE.fetch(key), value] }
65
+ overrides["textSecondary"] = overrides["mutedForeground"] if overrides.key?("mutedForeground")
66
+ pick(default_palette.merge(overrides))
67
+ end
68
+
69
+ def pick(palette)
70
+ KEYS.index_with { |key| palette.fetch(key) }.freeze
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module CommandTower
6
+ module EmailTheme
7
+ # Reads and validates the shared email token file (design D19). The host
8
+ # file lives at a fixed path (`config/ui_tokens.json` under Rails.root) and
9
+ # is written by the frontend export bin; CT ships a default file of its own.
10
+ #
11
+ # Format: { "version": 1, "palette": { "<token>": "#rrggbb", ... } }. The
12
+ # palette carries every semantic token the app uses; CT only requires the
13
+ # keys the email renderer reads (Palette::KEYS) and ignores the rest.
14
+ # Parsed with JSON.parse only. Error messages name keys, never values.
15
+ module TokenFile
16
+ class InvalidError < CommandTower::Error; end
17
+
18
+ SUPPORTED_VERSION = 1
19
+ HEX_COLOR = /\A#\h{6}\z/
20
+ DEFAULT_PATH = File.expand_path("default_ui_tokens.json", __dir__)
21
+ HOST_RELATIVE_PATH = "config/ui_tokens.json"
22
+ MISSING_FILE_WARNING = "[CommandTower] #{HOST_RELATIVE_PATH} not found; email uses config.email_theme " \
23
+ "or CommandTower's default palette. Export it with ct-export-email-tokens.".freeze
24
+
25
+ class << self
26
+ def host_path
27
+ Rails.root.join(HOST_RELATIVE_PATH).to_s
28
+ end
29
+
30
+ def host_file?(path = host_path)
31
+ File.file?(path)
32
+ end
33
+
34
+ # Returns the validated, frozen palette Hash (string keys, all tokens in the file).
35
+ # Raises InvalidError when the file is unreadable, not JSON, or malformed.
36
+ def load_palette(path)
37
+ document = parse(path)
38
+ raise InvalidError, "token file must be a JSON object" unless document.is_a?(Hash)
39
+ unless document["version"] == SUPPORTED_VERSION
40
+ raise InvalidError, "token file version must be #{SUPPORTED_VERSION}"
41
+ end
42
+
43
+ palette = document["palette"]
44
+ raise InvalidError, "token file palette must be an object" unless palette.is_a?(Hash)
45
+
46
+ validate_palette!(palette)
47
+ palette.freeze
48
+ end
49
+
50
+ # Boot check. An invalid host file raises (boot error); a missing one
51
+ # logs a single warning (0.23.0 keeps the file optional).
52
+ def validate_host_file!(logger: Rails.logger)
53
+ path = host_path
54
+ if host_file?(path)
55
+ load_palette(path)
56
+ else
57
+ logger&.warn(MISSING_FILE_WARNING)
58
+ end
59
+ end
60
+
61
+ private
62
+
63
+ def parse(path)
64
+ JSON.parse(File.read(path))
65
+ rescue JSON::ParserError
66
+ raise InvalidError, "token file is not valid JSON"
67
+ rescue SystemCallError
68
+ raise InvalidError, "token file could not be read"
69
+ end
70
+
71
+ def validate_palette!(palette)
72
+ missing = Palette::KEYS - palette.keys
73
+ raise InvalidError, "token file palette missing keys: #{missing.join(', ')}" if missing.any?
74
+
75
+ bad = palette.reject { |_key, value| value.is_a?(String) && HEX_COLOR.match?(value) }.keys
76
+ raise InvalidError, "token file palette values must be #RRGGBB: #{bad.join(', ')}" if bad.any?
77
+ end
78
+ end
79
+ end
80
+ end
81
+ end
@@ -9,6 +9,12 @@ module CommandTower
9
9
 
10
10
  paths.add "app/shared_sequences", eager_load: true
11
11
 
12
+ # The one-click unsubscribe token is a bearer credential in the query string. Hosts that do not
13
+ # already filter `token` must not log it.
14
+ initializer "command_tower.filter_token_parameter" do |app|
15
+ app.config.filter_parameters |= [:token]
16
+ end
17
+
12
18
  # Run after Rails loads the initializes and environment files
13
19
  # Ensures User has already set their desired config before we lock this down
14
20
  config.after_initialize do
@@ -23,6 +29,7 @@ module CommandTower
23
29
  CommandTower.config.class_composer_assign_defaults!(children: true)
24
30
  CommandTower::CredentialResolution::SmtpActionMailerBridge.apply!
25
31
  CommandTower.config.registry.client_compatibility.apply_env_overlay!
32
+ CommandTower::EmailTheme::TokenFile.validate_host_file!
26
33
 
27
34
  unless Rails.env.test?
28
35
  CommandTower.config.impersonation.validate!
@@ -92,7 +92,8 @@ module CommandTower
92
92
  impersonation_activity_recorded: attrs.key?(:impersonation_activity_recorded) ? attrs[:impersonation_activity_recorded] : false,
93
93
  remote_ip: attrs[:remote_ip],
94
94
  user_agent: attrs[:user_agent],
95
- ui_catalog: attrs.fetch(:ui_catalog, 1)
95
+ ui_catalog: attrs.fetch(:ui_catalog, 1),
96
+ client_time_zone: attrs[:client_time_zone]
96
97
  }
97
98
 
98
99
  run = -> { Current.set(assigned, &block) }
@@ -20,6 +20,7 @@ module CommandTower
20
20
  20261010000002_add_conversation_identity_to_messaging_communications.rb
21
21
  20261012000001_add_provider_metadata_to_messaging_delivery_attempts.rb
22
22
  20261012000002_add_finished_at_index_to_messaging_delivery_attempts.rb
23
+ 20261124000001_add_message_definition_columns_to_messaging_communications.rb
23
24
  ].freeze
24
25
 
25
26
  module_function
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rspec/expectations"
4
+
5
+ # RSpec matchers shipped with CommandTower for host MessageDefinition specs.
6
+ #
7
+ # require "command_tower/rspec/message_definition"
8
+ #
9
+ # expect(ClassCanceled).to express_required_facts(fixture: :default)
10
+ # expect(ClassCanceled).to have_fact_block_once
11
+ # expect(CheckInReady).to exclude_code_from_email(fixture: :default)
12
+ #
13
+ # Each matcher renders the definition from one of its declared fixtures with the same pure code
14
+ # path the sender and the gallery use (`Definitions::DocumentBuilder`). `fixture:` defaults to the
15
+ # first declared fixture. Failure messages name channels, fact keys and node types, never values.
16
+ module CommandTower
17
+ module Testing
18
+ # Rendering helpers behind the matchers.
19
+ module MessageDefinitionRendering
20
+ # Slots that must not carry facts: the inbox headline and the Pushover title are labels.
21
+ FACT_FREE_SLOTS = %i[headline pushover_title].freeze
22
+
23
+ module_function
24
+
25
+ def context_for(definition, fixture)
26
+ metadata = metadata_for(definition, fixture)
27
+ base = Messaging::Definitions::RenderContext.new(
28
+ notification_type_key: "message_definition_spec",
29
+ metadata:,
30
+ metadata_version: definition.metadata_version,
31
+ slots: nil,
32
+ render_zone: definition.default_zone
33
+ )
34
+ base.with(slots: Messaging::Definitions::DocumentBuilder.slots(definition: definition.new, context: base))
35
+ end
36
+
37
+ def metadata_for(definition, fixture)
38
+ name = (fixture || definition.fixtures.keys.first).to_s
39
+ definition.fixtures.fetch(name) do
40
+ raise ArgumentError, "#{definition.name} has no fixture #{name.inspect}"
41
+ end
42
+ end
43
+
44
+ # @return [Hash{Symbol => String}] the channel slots that must express the required facts
45
+ def fact_texts(definition, context)
46
+ slots = Messaging::Definitions::DocumentBuilder.slots(definition: definition.new, context:)
47
+ slots.except(*FACT_FREE_SLOTS).transform_values(&:to_s)
48
+ end
49
+
50
+ def document(definition, channel, context)
51
+ Messaging::Definitions::DocumentBuilder.public_send(channel, definition: definition.new, context:)
52
+ end
53
+
54
+ # Every node `type` in the wire tree.
55
+ def node_types(wire, found = [])
56
+ case wire
57
+ when Hash
58
+ found << wire["type"] if wire["type"]
59
+ wire.each_value { |value| node_types(value, found) }
60
+ when Array
61
+ wire.each { |value| node_types(value, found) }
62
+ end
63
+ found
64
+ end
65
+ end
66
+ end
67
+ end
68
+
69
+ # Passes when every required fact is expressed in every fact-carrying channel text (subject, push,
70
+ # SMS, Pushover message). Fails naming the channel and fact key.
71
+ RSpec::Matchers.define :express_required_facts do |fixture: nil|
72
+ match do |definition|
73
+ helpers = CommandTower::Testing::MessageDefinitionRendering
74
+ context = helpers.context_for(definition, fixture)
75
+ verdicts = CommandTower::UI::RequiredFacts::Verdict.call(
76
+ texts: helpers.fact_texts(definition, context),
77
+ metadata: context.metadata,
78
+ required_facts: definition.required_facts.map(&:to_h),
79
+ render_zone: context.render_zone
80
+ )
81
+ @failures = verdicts.reject { |row| row[:passed] }
82
+ @failures.empty?
83
+ end
84
+
85
+ failure_message do |definition|
86
+ rows = @failures.map { |row| "#{row[:channel]} is missing #{row[:fact_key]}" }
87
+ "expected #{definition.name} to express its required facts, but: #{rows.join('; ')}"
88
+ end
89
+ end
90
+
91
+ # Passes when the inbox and email documents each contain exactly one `facts` node. Accepts a
92
+ # definition class (rendered from `fixture:`) or a built document.
93
+ RSpec::Matchers.define :have_fact_block_once do |fixture: nil|
94
+ match do |subject|
95
+ helpers = CommandTower::Testing::MessageDefinitionRendering
96
+ @counts =
97
+ if subject.is_a?(CommandTower::UI::Document)
98
+ { document: helpers.node_types(subject.as_json["root"]).count("facts") }
99
+ else
100
+ context = helpers.context_for(subject, fixture)
101
+ %i[inbox email].index_with do |channel|
102
+ helpers.node_types(helpers.document(subject, channel, context).as_json["root"]).count("facts")
103
+ end
104
+ end
105
+ @counts.values.all?(1)
106
+ end
107
+
108
+ failure_message do
109
+ "expected exactly one facts node, found #{@counts.map { |name, count| "#{name}: #{count}" }.join(', ')}"
110
+ end
111
+ end
112
+
113
+ # Passes when the email document carries no `code` node (check-in codes never go by email).
114
+ RSpec::Matchers.define :exclude_code_from_email do |fixture: nil|
115
+ match do |definition|
116
+ helpers = CommandTower::Testing::MessageDefinitionRendering
117
+ context = helpers.context_for(definition, fixture)
118
+ wire = helpers.document(definition, :email, context).as_json["root"]
119
+ helpers.node_types(wire).exclude?("code")
120
+ end
121
+
122
+ failure_message do |definition|
123
+ "expected the #{definition.name} email document to exclude a code node, but it contains one"
124
+ end
125
+ end
@@ -8,10 +8,11 @@ module CommandTower
8
8
  # validation. Errors carry node paths and codes only, never values
9
9
  # (a `code` value, spans and times must not reach logs or exceptions).
10
10
  #
11
- # `validate!(profile:)` is the seam for later rule sets (the blocking-notice
12
- # profile in Set 3 adds external-links-only). Only :default exists.
11
+ # `validate!(profile:)` is the seam for rule sets. :default is the base rule
12
+ # set. :message adds "exactly one `facts` node" (message definitions). The
13
+ # blocking-notice profile in Set 3 will add external-links-only.
13
14
  class Document
14
- PROFILES = %i[default].freeze
15
+ PROFILES = %i[default message].freeze
15
16
  MESSAGE_ERROR_LIMIT = 10
16
17
 
17
18
  attr_reader :root, :text_fallback
@@ -41,6 +42,7 @@ module CommandTower
41
42
  walker = Walker.new
42
43
  walker.check_envelope(self)
43
44
  walker.walk(root, "root", 1) if root.is_a?(Nodes::Node)
45
+ walker.check_facts_block if profile == :message
44
46
  walker.check_size(self)
45
47
  walker.details
46
48
  end
@@ -77,6 +79,15 @@ module CommandTower
77
79
  @primary_buttons = 0
78
80
  @open_facts = []
79
81
  @structure_overflow = false
82
+ @facts_nodes = 0
83
+ end
84
+
85
+ # :message profile. Skipped when the walk stopped early (counts would be partial).
86
+ def check_facts_block
87
+ return if @structure_overflow
88
+
89
+ add("document", :missing_facts_node) if @facts_nodes.zero?
90
+ add("document", :multiple_facts_nodes) if @facts_nodes > 1
80
91
  end
81
92
 
82
93
  def check_envelope(document)
@@ -128,7 +139,10 @@ module CommandTower
128
139
 
129
140
  def track(node, path)
130
141
  @open_facts.each { |entry| entry[:count] += 1 }
131
- @open_facts.push({ path:, count: 0 }) if node.is_a?(Nodes::Facts)
142
+ if node.is_a?(Nodes::Facts)
143
+ @facts_nodes += 1
144
+ @open_facts.push({ path:, count: 0 })
145
+ end
132
146
  count_singletons(node, path)
133
147
  end
134
148
 
@@ -64,7 +64,8 @@ module CommandTower
64
64
  end
65
65
 
66
66
  def time_text(node)
67
- TimeFormatter.call(at: node.at, zone: node.zone, format: node.format, label: node.label)
67
+ TimeFormatter.call(at: node.at, zone: node.zone, format: node.format, label: node.label,
68
+ user_zone: @user_zone)
68
69
  end
69
70
 
70
71
  def spacer_row(columns)
@@ -24,6 +24,7 @@ module CommandTower
24
24
  #
25
25
  # Optional chrome keywords: `footer_html:` (trusted, escaped HTML),
26
26
  # `app_name:` and `preheader:` (plain text), passed to {Layout}.
27
+ # `user_zone:` (default `config.ui.default_zone`) is the zone `zone: "user"` times render in.
27
28
  class Renderer
28
29
  Output = Data.define(:html, :text)
29
30
 
@@ -49,11 +50,12 @@ module CommandTower
49
50
  include TextNodes
50
51
  include InlineNodes
51
52
 
52
- def self.call(document, palette:, origin:, **chrome)
53
- new(palette:, origin:).render_document(document, **chrome.assert_valid_keys(*CHROME_KEYS))
53
+ def self.call(document, palette:, origin:, user_zone: CommandTower.config.ui.default_zone, **chrome)
54
+ new(palette:, origin:, user_zone:).render_document(document, **chrome.assert_valid_keys(*CHROME_KEYS))
54
55
  end
55
56
 
56
- def initialize(palette:, origin:)
57
+ def initialize(palette:, origin:, user_zone: CommandTower.config.ui.default_zone)
58
+ @user_zone = user_zone
57
59
  @palette = Styles.validate_palette!(palette)
58
60
  valid_origin = origin.is_a?(String) && ORIGIN_FORMAT.match?(origin)
59
61
  raise InvalidTokenError, "origin must be an http(s) origin" unless valid_origin
@@ -64,12 +66,22 @@ module CommandTower
64
66
  def render_document(document, preheader: nil, **chrome)
65
67
  reject_code!(document.root, "root")
66
68
  document.validate!
67
- text = TextDerivation.call(document.root)
68
- preheader ||= text.gsub(/\s+/, " ").strip.truncate(PREHEADER_LIMIT)
69
+ derived = TextDerivation.call(document.root, user_zone: @user_zone)
70
+ preheader ||= derived.gsub(/\s+/, " ").strip.truncate(PREHEADER_LIMIT)
69
71
  html = Layout.call(body_html: render(document.root).to_str, palette: @palette, preheader:, **chrome)
72
+ text = TextPart.call(document.root, origin: @origin, user_zone: @user_zone)
70
73
  Output.new(html:, text:)
71
74
  end
72
75
 
76
+ # The document's body tables alone (no layout chrome), for previews that show a fragment.
77
+ # Same code rejection and validation as {#render_document}.
78
+ # @return [String]
79
+ def render_body(document)
80
+ reject_code!(document.root, "root")
81
+ document.validate!
82
+ render(document.root).to_str
83
+ end
84
+
73
85
  private
74
86
 
75
87
  def reject_code!(object, path)