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,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module Messaging
6
+ module Gallery
7
+ # Lists the notification types the admin gallery can preview: registered types whose
8
+ # declaration names a `MessageDefinition`. Reads the registry and the definition classes
9
+ # only. It touches no `Communication` and no user data.
10
+ #
11
+ # Output: `types`, an Array of Hashes with `notification_type_key`, `label`, `definition`
12
+ # (class name), `allowed_channels`, `promotional` and `fixtures` (`name`, `metadata_version`).
13
+ class ListGalleryTypes < CommandTower::Services::ApplicationService
14
+ def call
15
+ context.types = CommandTower::Messaging::NotificationTypes.enumerate.filter_map do |declaration|
16
+ definition = definition_for(declaration)
17
+ project(declaration, definition) if definition
18
+ end
19
+ end
20
+
21
+ private
22
+
23
+ def definition_for(declaration)
24
+ klass = declaration.message&.safe_constantize
25
+ klass if klass.is_a?(Class) && klass < CommandTower::Messaging::MessageDefinition
26
+ end
27
+
28
+ def project(declaration, definition)
29
+ {
30
+ notification_type_key: declaration.key,
31
+ label: declaration.label,
32
+ definition: definition.name,
33
+ allowed_channels: declaration.allowed_channels.to_a,
34
+ promotional: definition.promotional?,
35
+ fixtures: definition.fixtures.keys.map do |name|
36
+ { name:, metadata_version: definition.metadata_version }
37
+ end
38
+ }
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module Messaging
6
+ module Gallery
7
+ # Builds the preview Hash for one declared fixture of one defined type, using the same pure
8
+ # code the sender and the inbox read use. Reads no `Communication`. A composer that raises
9
+ # raises {ChannelFailed}.
10
+ class PreviewBuilder
11
+ def self.call(**)
12
+ new(**).call
13
+ end
14
+
15
+ def initialize(declaration:, definition:, fixture:, render_zone:, footer_notice: nil)
16
+ @declaration = declaration
17
+ @definition = definition
18
+ @fixture = fixture
19
+ @render_zone = render_zone
20
+ @footer_notice = footer_notice
21
+ end
22
+
23
+ def call
24
+ {
25
+ notification_type_key: declaration.key, fixture:, metadata_version: definition.metadata_version,
26
+ render_zone:, slots: PreviewChannels.slot_payload(context.slots), channels:,
27
+ facts: facts_payload, checks:
28
+ }
29
+ end
30
+
31
+ private
32
+
33
+ attr_reader :declaration, :definition, :fixture, :render_zone, :footer_notice
34
+
35
+ def instance
36
+ @instance ||= definition.new
37
+ end
38
+
39
+ def builder
40
+ CommandTower::Messaging::Definitions::DocumentBuilder
41
+ end
42
+
43
+ def context
44
+ @context ||= begin
45
+ base = CommandTower::Messaging::Definitions::RenderContext.new(
46
+ notification_type_key: declaration.key, metadata: definition.fixtures.fetch(fixture),
47
+ metadata_version: definition.metadata_version, slots: nil, render_zone:
48
+ )
49
+ base.with(slots: ChannelFailed.guard("slots") { builder.slots(definition: instance, context: base) })
50
+ end
51
+ end
52
+
53
+ def inbox_wire
54
+ return unless declaration.inbox_available
55
+
56
+ ChannelFailed.guard("inbox") { builder.inbox(definition: instance, context:).as_json }
57
+ end
58
+
59
+ # nil when the composer fails; the email then shows the fallback.
60
+ def email_wire
61
+ return unless email_allowed?
62
+
63
+ builder.email(definition: instance, context:).as_json
64
+ rescue StandardError
65
+ nil
66
+ end
67
+
68
+ def email_allowed?
69
+ PreviewChannels.allowed?(declaration, "email")
70
+ end
71
+
72
+ def email
73
+ PreviewEmail.call(definition:, context:, footer_notice:) if email_allowed?
74
+ end
75
+
76
+ def channels
77
+ @channels ||= PreviewChannels.call(
78
+ declaration:, slots: context.slots, link: context.metadata["deep_link"].to_s.presence,
79
+ inbox: inbox_wire, email:
80
+ )
81
+ end
82
+
83
+ def facts_document
84
+ @facts_document ||= ChannelFailed.guard("facts") { builder.facts(definition: instance, context:) }
85
+ end
86
+
87
+ def facts_payload
88
+ return { app: nil, email_html: nil } unless facts_document
89
+
90
+ html = ChannelFailed.guard("facts") do
91
+ CommandTower::UI::Email::Renderer.new(
92
+ palette: CommandTower::EmailTheme::Palette.resolve,
93
+ origin: CommandTower.config.application.composed_url, user_zone: render_zone
94
+ ).render_body(facts_document)
95
+ end
96
+ { app: facts_document.as_json, email_html: html }
97
+ end
98
+
99
+ def checks
100
+ PreviewChecks.call(
101
+ definition:, context:,
102
+ documents: { inbox: channels.dig(:inbox, :content), email: email_wire, facts: facts_document&.as_json },
103
+ texts: rendered_texts, fact_text: fact_text
104
+ )
105
+ end
106
+
107
+ def fact_text
108
+ return "" unless facts_document
109
+
110
+ CommandTower::UI::TextDerivation.call(facts_document.root, user_zone: render_zone)
111
+ end
112
+
113
+ def rendered_texts
114
+ email = channels[:email]
115
+ (context.slots.values + [email&.dig(:html), email&.dig(:text), channels.dig(:push, :body),
116
+ channels.dig(:sms, :text), channels.dig(:pushover, :message)]).compact.map(&:to_s)
117
+ end
118
+ end
119
+ end
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module Messaging
6
+ module Gallery
7
+ # The per-channel payloads of a gallery preview. A channel the type does not allow is nil
8
+ # (the inbox included, G16): the inbox is nil when no inbox document was composed.
9
+ module PreviewChannels
10
+ SLOT_NAMES = %i[headline subject push_body sms_body pushover_title pushover_message].freeze
11
+
12
+ module_function
13
+
14
+ def allowed?(declaration, channel)
15
+ declaration.allowed_channels.to_a.include?(channel)
16
+ end
17
+
18
+ def slot_payload(slots)
19
+ SLOT_NAMES.index_with { |name| slots[name] }
20
+ end
21
+
22
+ # @param inbox [Hash, nil] the inbox document wire hash
23
+ # @param email [Hash, nil] the email preview
24
+ def call(declaration:, slots:, link:, inbox:, email:)
25
+ {
26
+ push: (push(slots) if allowed?(declaration, "push")),
27
+ sms: (sms(slots, link) if allowed?(declaration, "sms")),
28
+ pushover: (pushover(slots, link) if allowed?(declaration, "pushover")),
29
+ inbox: (inbox ? { content: inbox } : nil),
30
+ email:
31
+ }
32
+ end
33
+
34
+ def push(slots)
35
+ title = slots[:headline].to_s
36
+ { title:, body: (slots[:push_body] || title).to_s }
37
+ end
38
+
39
+ def sms(slots, link)
40
+ { text: [slots[:sms_body], link].compact_blank.join(" ") }
41
+ end
42
+
43
+ def pushover(slots, link)
44
+ { title: (slots[:pushover_title] || slots[:headline]).to_s,
45
+ message: [slots[:pushover_message], link].compact_blank.join(" "), url: link }
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module Messaging
6
+ module Gallery
7
+ # The gallery's pass/fail checks for one rendered preview. Rows name checks, channels and
8
+ # fact keys only, never metadata values, slot text or code values.
9
+ #
10
+ # - `required_fact`: every required fact appears in each fact-carrying slot and in the fact
11
+ # block's derived text (`UI::RequiredFacts::Verdict`).
12
+ # - `fact_block_once`: each rendered document has exactly one `facts` node.
13
+ # - `no_code_in_slots_or_body`: no `code` node in the email document, and no code value in
14
+ # any slot, push, SMS, Pushover or email text.
15
+ # - `no_time_in_headline`: the headline carries none of the required `:time` facts.
16
+ module PreviewChecks
17
+ FACT_FREE_SLOTS = %i[headline pushover_title].freeze
18
+
19
+ module_function
20
+
21
+ # @param definition [Class] the MessageDefinition subclass
22
+ # @param context [Messaging::Definitions::RenderContext] with slots resolved
23
+ # @param documents [Hash] wire hashes keyed `:inbox`, `:email`, `:facts` (nil when absent)
24
+ # @param texts [Array<String>] every rendered text the code values must stay out of
25
+ # @param fact_text [String] derived text of the fact block ("" when there is none)
26
+ # @return [Array<Hash>]
27
+ def call(definition:, context:, documents:, texts:, fact_text:)
28
+ required_fact_rows(definition, context, fact_text) +
29
+ fact_block_rows(documents) +
30
+ [no_code_row(documents, texts), no_time_in_headline_row(definition, context)]
31
+ end
32
+
33
+ def required_fact_rows(definition, context, fact_text)
34
+ candidates = context.slots.except(*FACT_FREE_SLOTS).transform_values(&:to_s)
35
+ candidates = candidates.merge(fact_block: fact_text) if fact_text.present?
36
+ verdicts(definition, context, candidates).map do |row|
37
+ { check: "required_fact", channel: row[:channel].to_s, fact_key: row[:fact_key].to_s,
38
+ passed: row[:passed] }
39
+ end
40
+ end
41
+
42
+ def fact_block_rows(documents)
43
+ documents.slice(:inbox, :email).filter_map do |channel, wire|
44
+ next if wire.nil?
45
+
46
+ { check: "fact_block_once", channel: channel.to_s, passed: node_values(wire, "facts").size == 1 }
47
+ end
48
+ end
49
+
50
+ def no_code_row(documents, texts)
51
+ email = documents[:email]
52
+ code_values = documents.values.compact.flat_map { |wire| node_values(wire, "code", "value") }
53
+ leaked = code_values.any? { |value| texts.any? { |text| text.include?(value.to_s) } }
54
+ email_has_code = email ? node_values(email, "code").any? : false
55
+ { check: "no_code_in_slots_or_body", passed: !leaked && !email_has_code }
56
+ end
57
+
58
+ def no_time_in_headline_row(definition, context)
59
+ time_facts = definition.required_facts.select { |fact| fact.matcher == :time }.map(&:to_h)
60
+ rows = verdicts(definition, context, { headline: context.slots[:headline].to_s }, time_facts)
61
+ { check: "no_time_in_headline", passed: rows.none? { |row| row[:passed] } }
62
+ end
63
+
64
+ def verdicts(definition, context, texts, facts = definition.required_facts.map(&:to_h))
65
+ CommandTower::UI::RequiredFacts::Verdict.call(
66
+ texts:, metadata: context.metadata, required_facts: facts, render_zone: context.render_zone
67
+ )
68
+ end
69
+
70
+ # Values of nodes of `type` in a wire tree: the node's `field`, or the node itself.
71
+ def node_values(wire, type, field = nil, found = [])
72
+ case wire
73
+ when Hash
74
+ found << (field ? wire[field] : wire) if wire["type"] == type
75
+ wire.each_value { |value| node_values(value, type, field, found) }
76
+ when Array
77
+ wire.each { |value| node_values(value, type, field, found) }
78
+ end
79
+ found
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module Messaging
6
+ module Gallery
7
+ # The email channel of a gallery preview: the HTML and text `DefinedEmailRenderer` produces
8
+ # from the fixture, plus whether it fell back from the composed document.
9
+ module PreviewEmail
10
+ # Stand-in for the row `DefinedEmailRenderer` expects. Built from the fixture, never read.
11
+ Subject = Data.define(
12
+ :id, :notification_type_key, :metadata, :metadata_version, :slots, :render_zone, :title, :body
13
+ )
14
+
15
+ module_function
16
+
17
+ # @param context [Messaging::Definitions::RenderContext] with slots resolved
18
+ # @param footer_notice [String, nil] a line above the compliance footer (test send)
19
+ # @return [Hash] `subject`, `html`, `text`, `used_fallback`
20
+ def call(definition:, context:, footer_notice: nil)
21
+ output = ChannelFailed.guard("email") do
22
+ CommandTower::Messaging::Rendering::DefinedEmailRenderer.render(
23
+ communication: subject_for(context), definition:, footer_notice:
24
+ )
25
+ end
26
+ { subject: (context.slots[:subject] || context.slots[:headline]).to_s, html: output.html,
27
+ text: output.text, used_fallback: fallback?(definition, context) }
28
+ end
29
+
30
+ def subject_for(context)
31
+ Subject.new(
32
+ id: nil, notification_type_key: context.notification_type_key, metadata: context.metadata,
33
+ metadata_version: context.metadata_version, slots: context.slots,
34
+ render_zone: context.render_zone, title: context.slots[:headline].to_s, body: ""
35
+ )
36
+ end
37
+
38
+ # True when the composed email document cannot be built or rendered (a composer error, a
39
+ # missing fact block or a `code` node), which is when `DefinedEmailRenderer` falls back.
40
+ def fallback?(definition, context)
41
+ document = CommandTower::Messaging::Definitions::DocumentBuilder.email(
42
+ definition: definition.new, context:
43
+ )
44
+ CommandTower::UI::Email::Renderer.call(
45
+ document, palette: CommandTower::EmailTheme::Palette.resolve,
46
+ origin: CommandTower.config.application.composed_url, user_zone: context.render_zone
47
+ )
48
+ false
49
+ rescue StandardError
50
+ true
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module Messaging
6
+ module Gallery
7
+ # Renders one declared fixture of one defined notification type through every channel the
8
+ # type allows, with the same pure code the sender and the inbox read use (design 3.5).
9
+ #
10
+ # - Data comes only from the definition's declared fixtures. It takes no communication id and
11
+ # reads no `Communication`.
12
+ # - `fixture` is a declared fixture name (default: the first). An unknown name is NotFound.
13
+ # - `zone` is any valid TZInfo identifier (default: the definition's `default_zone`) and acts as
14
+ # the render zone. An invalid identifier is a ValidationError.
15
+ # - A channel the type does not allow is nil (`inbox` included, G16).
16
+ # - A composer that raises fails the preview with the channel and error class only; metadata
17
+ # values never reach errors.
18
+ #
19
+ # `footer_notice` (optional) is a line above the email's compliance footer; only the test send sets it.
20
+ #
21
+ # Output: `preview` (snake_case Hash; the serializer shapes the wire form).
22
+ class RenderGalleryPreview < CommandTower::Services::ApplicationService
23
+ validate :notification_type_key, is_a: String, required: true
24
+ validate :fixture, is_a: String, required: false
25
+ validate :zone, is_a: String, required: false
26
+ validate :footer_notice, is_a: String, required: false
27
+
28
+ def call
29
+ target = resolve_target
30
+ return not_found unless target
31
+
32
+ render_zone = render_zone_for(target[:definition])
33
+ return invalid_zone unless TZInfo::Timezone.all_identifiers.include?(render_zone)
34
+
35
+ context.preview = PreviewBuilder.call(**target, render_zone:, footer_notice:)
36
+ rescue ChannelFailed => e
37
+ fail_channel(e)
38
+ end
39
+
40
+ private
41
+
42
+ # @return [Hash, nil] `declaration`, `definition`, `fixture`; nil when any is not found
43
+ def resolve_target
44
+ return unless CommandTower::Messaging::NotificationTypes.registered?(notification_type_key)
45
+
46
+ declaration = CommandTower::Messaging::NotificationTypes.lookup(notification_type_key)
47
+ definition = definition_for(declaration)
48
+ name = definition && fixture_name(definition)
49
+ { declaration:, definition:, fixture: name } if name
50
+ end
51
+
52
+ def definition_for(declaration)
53
+ klass = declaration.message&.safe_constantize
54
+ klass if klass.is_a?(Class) && klass < CommandTower::Messaging::MessageDefinition
55
+ end
56
+
57
+ def fixture_name(definition)
58
+ name = fixture.presence || definition.fixtures.keys.first
59
+ name if definition.fixtures.key?(name)
60
+ end
61
+
62
+ def render_zone_for(definition)
63
+ zone.presence || definition.default_zone.presence || CommandTower.config.ui.default_zone
64
+ end
65
+
66
+ def not_found
67
+ context.fail!(application_error: CommandTower::Errors::NotFoundError.new)
68
+ end
69
+
70
+ def invalid_zone
71
+ context.fail!(application_error: CommandTower::Errors::ValidationError.new(
72
+ details: { zone: "is not a valid time zone" }
73
+ ))
74
+ end
75
+
76
+ def fail_channel(error)
77
+ context.fail!(application_error: CommandTower::Errors::ValidationError.new(
78
+ details: { gallery: "preview failed (channel: #{error.channel}, error: #{error.error_class})" }
79
+ ))
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module Messaging
6
+ module Gallery
7
+ # Builds the email of a gallery test send: one declared fixture of one defined type, rendered
8
+ # like the gallery email preview, addressed to the real actor's own address.
9
+ #
10
+ # - Email only. A type that does not allow email is a ValidationError.
11
+ # - Reads no `Communication` and writes none. It does not send; the workflow hands the content
12
+ # to the adapter boundary.
13
+ # - The subject is the preview subject, unchanged. A "Test message" line sits above the
14
+ # compliance footer. No `List-Unsubscribe*` headers are produced (the content has none).
15
+ #
16
+ # Output: `recipient` (the actor's address, from the user record) and `content`
17
+ # (`subject`, `html`, `text`).
18
+ class TestSend < CommandTower::Services::ApplicationService
19
+ NOTICE = "Test message"
20
+
21
+ validate :notification_type_key, is_a: String, required: true
22
+ validate :fixture, is_a: String, required: false
23
+ validate :zone, is_a: String, required: false
24
+ validate :actor, is_a: User, required: true
25
+
26
+ def call
27
+ address = actor.email.to_s.strip
28
+ return fail_with(recipient: "has no email address") if address.empty?
29
+
30
+ email = email_preview
31
+ return fail_with(channel: "email is not allowed for this notification type") unless email
32
+
33
+ context.recipient = address
34
+ context.content = email.slice(:subject, :html, :text)
35
+ end
36
+
37
+ private
38
+
39
+ def email_preview
40
+ rendered = CommandTower::Services::Messaging::Gallery::RenderGalleryPreview.call(
41
+ notification_type_key:, fixture:, zone:, footer_notice: NOTICE
42
+ )
43
+ context.fail!(application_error: rendered.errors.first) unless rendered.success?
44
+
45
+ rendered.data[:preview].dig(:channels, :email)
46
+ end
47
+
48
+ def fail_with(details)
49
+ context.fail!(application_error: CommandTower::Errors::ValidationError.new(details:))
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
@@ -44,18 +44,27 @@ module CommandTower
44
44
  include FailureMapping
45
45
  validate :user, is_a: User, required: true
46
46
  validate :inbox_item_id, is_a: Integer, required: true
47
+ validate :ui_catalog, is_a: Integer, required: false, default: 1
48
+ # Anything but exactly false redacts `code` nodes of defined types; nil means unknown.
49
+ validate :impersonating, is_a: [TrueClass, FalseClass], required: false
47
50
 
48
51
  def call
49
- with_recipient { |recipient_id| context.item = Inbox.detail(recipient_id:, inbox_item_id:) }
52
+ with_recipient { |recipient_id| context.item = Inbox.detail(recipient_id:, inbox_item_id:, ui_catalog:, impersonating:) }
50
53
  end
51
54
  end
52
55
 
56
+ # Marks the item viewed (unless mark_viewed is false, used for impersonated
57
+ # opens) and renders the detail once. Exposes newly_viewed and
58
+ # communication_id so the calling workflow can own the first-view audit.
53
59
  class Open < Show
60
+ validate :mark_viewed, is_a: [TrueClass, FalseClass], required: false, default: true
61
+
54
62
  def call
55
63
  with_recipient do |recipient_id|
56
- Inbox.detail(recipient_id:, inbox_item_id:)
57
- CommandTower::Messaging::Inbox.mark_viewed(recipient_id:, inbox_item_id:)
58
- context.item = Inbox.detail(recipient_id:, inbox_item_id:)
64
+ marked = CommandTower::Messaging::Inbox.mark_viewed(recipient_id:, inbox_item_id:) if mark_viewed
65
+ context.newly_viewed = marked&.newly_viewed == true
66
+ context.communication_id = marked&.communication_id
67
+ context.item = Inbox.detail(recipient_id:, inbox_item_id:, ui_catalog:, impersonating:)
59
68
  end
60
69
  end
61
70
  end
@@ -89,6 +98,8 @@ module CommandTower
89
98
  validate :before_id, is_a: Integer, required: false
90
99
  validate :after_id, is_a: Integer, required: false
91
100
  validate :limit, is_a: Integer, required: false
101
+ validate :ui_catalog, is_a: Integer, required: false, default: 1
102
+ validate :impersonating, is_a: [TrueClass, FalseClass], required: false
92
103
 
93
104
  def call
94
105
  with_recipient do |recipient_id|
@@ -96,7 +107,7 @@ module CommandTower
96
107
  recipient_id:, key:, scope:, around:, before_id:, after_id:, limit:,
97
108
  )
98
109
  messages = found.message_ids.map do |inbox_item_id|
99
- Inbox.detail(recipient_id:, inbox_item_id:)
110
+ Inbox.detail(recipient_id:, inbox_item_id:, ui_catalog:, impersonating:)
100
111
  end
101
112
  context.conversation = {
102
113
  scope: found.scope,
@@ -165,16 +176,33 @@ module CommandTower
165
176
  }
166
177
  end
167
178
 
168
- def detail(recipient_id:, inbox_item_id:)
179
+ # Raw metadata of a definition-backed row can hold the `code` value, which the document
180
+ # redacts when impersonating (or unknown). The raw hash must not undo that, so it is
181
+ # withheld for those reads. Decided from the stored row only (no registry lookup), and
182
+ # fails closed: any error withholds the metadata.
183
+ def detail_metadata(communication, impersonating:)
184
+ return communication.metadata if impersonating == false
185
+
186
+ communication.message_definition_backed? ? nil : communication.metadata
187
+ rescue StandardError
188
+ nil
189
+ end
190
+
191
+ def detail(recipient_id:, inbox_item_id:, ui_catalog: 1, impersonating: nil)
169
192
  item = CommandTower::Messaging::Inbox.show(recipient_id:, inbox_item_id:)
170
193
  communication = CommandTower::Messaging::Contract::Communications.find(
171
194
  CommandTower::Messaging::Contract::Requests::FindCommunication.build(communication_id: item.communication_id, recipient_id:)
172
195
  )
173
- content = CommandTower::Messaging::Rendering::InboxDocumentRenderer.render(communication:, recipient_id:).to_h
196
+ document = CommandTower::Messaging::Rendering::InboxDocumentRenderer.render(
197
+ communication:, recipient_id:, ui_catalog:, impersonating:
198
+ )
199
+ # A catalog 2 defined type is a `UI::Document` (string-keyed `ui_document`); everything
200
+ # else is an `InboxDocument` (`inbox_document_v1`).
201
+ content = document.is_a?(CommandTower::UI::Document) ? document.as_json : document.to_h
174
202
 
175
203
  item(item).merge(
176
204
  body: communication.body,
177
- metadata: communication.metadata,
205
+ metadata: detail_metadata(communication, impersonating:),
178
206
  notification_type_key: communication.notification_type_key,
179
207
  content:,
180
208
  )
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ module CommandTower
6
+ module Services
7
+ module Messaging
8
+ module Unsubscribe
9
+ # Rate limits the unauthenticated one-click unsubscribe endpoint.
10
+ #
11
+ # - Per token: TOKEN_LIMIT requests per TOKEN_WINDOW_SECONDS. The key is the SHA-256 digest of
12
+ # the token, so the token itself never reaches Redis. This is the main limit: a mail client
13
+ # or scanner replays one token, an attacker guesses many.
14
+ # - Per client IP: IP_LIMIT requests per IP_WINDOW_SECONDS. Deliberately high, because many
15
+ # recipients share a mail gateway or NAT. The IP is `request.remote_ip`, which honours
16
+ # `X-Forwarded-For` only behind the host's configured `trusted_proxies` (Services::Auth::ClientIpResolver).
17
+ # - Redis failure: fail open. Unsubscribe is a compliance action and the token is a signed,
18
+ # unforgeable value, so an outage must not block a recipient from opting out.
19
+ class CheckRateLimit < CommandTower::Services::ApplicationService
20
+ TOKEN_LIMIT = 10
21
+ TOKEN_WINDOW_SECONDS = 60
22
+ IP_LIMIT = 120
23
+ IP_WINDOW_SECONDS = 60
24
+
25
+ validate :token, is_a: String, required: true
26
+ validate :client_ip, is_a: String, required: true
27
+
28
+ def call
29
+ enforce!(key: "messaging-unsubscribe:rate:token:#{Digest::SHA256.hexdigest(token)}:#{bucket(TOKEN_WINDOW_SECONDS)}",
30
+ ttl_seconds: TOKEN_WINDOW_SECONDS, limit: TOKEN_LIMIT)
31
+ enforce!(key: "messaging-unsubscribe:rate:ip:#{client_ip}:#{bucket(IP_WINDOW_SECONDS)}",
32
+ ttl_seconds: IP_WINDOW_SECONDS, limit: IP_LIMIT)
33
+ end
34
+
35
+ private
36
+
37
+ def enforce!(key:, ttl_seconds:, limit:)
38
+ result = CommandTower::Services::RateLimits::Check.call(key:, ttl_seconds:)
39
+ return if result.failure?
40
+ return if result.data[:count] <= limit
41
+
42
+ ttl = result.data[:ttl]
43
+ context.fail!(
44
+ application_error: CommandTower::Errors::Messaging::UnsubscribeRateLimitError.new(
45
+ retry_after_seconds: ttl.positive? ? ttl : nil
46
+ )
47
+ )
48
+ end
49
+
50
+ def bucket(window_seconds)
51
+ Time.now.to_i / window_seconds
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module Messaging
6
+ module Unsubscribe
7
+ # Signs a one-click unsubscribe token for one user and one notification type. The payload is
8
+ # `{ u: user_id, t: notification_type_key }`; it expires after 90 days.
9
+ class IssueToken < CommandTower::Services::ApplicationService
10
+ validate :user_id, is_a: Integer, required: true
11
+ validate :notification_type_key, is_a: String, required: true
12
+
13
+ def call
14
+ signer = CommandTower::Messaging::Unsubscribe::TokenVerifier
15
+ context.token = signer.verifier.generate(
16
+ { u: user_id, t: notification_type_key },
17
+ purpose: signer::PURPOSE,
18
+ expires_in: signer::EXPIRES_IN
19
+ )
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end