command_tower 0.21.1 → 0.22.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 (65) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/concerns/command_tower/execution/http_boundary.rb +2 -1
  3. data/docs/api_reference.md +7 -3
  4. data/docs/bootstrap/11-auth-client-path.md +2 -0
  5. data/docs/extending.md +1 -1
  6. data/docs/messaging_integration_guide.md +2 -0
  7. data/docs/ui.md +138 -0
  8. data/docs/upgrades/0.22.0.md +29 -0
  9. data/docs/upgrades/README.md +1 -0
  10. data/lib/command_tower/configuration/config.rb +6 -0
  11. data/lib/command_tower/configuration/ui/config.rb +47 -0
  12. data/lib/command_tower/current.rb +1 -0
  13. data/lib/command_tower/execution.rb +2 -1
  14. data/lib/command_tower/ui/builder/frame.rb +19 -0
  15. data/lib/command_tower/ui/builder/item_builder.rb +27 -0
  16. data/lib/command_tower/ui/builder/token_resolver.rb +54 -0
  17. data/lib/command_tower/ui/builder.rb +157 -0
  18. data/lib/command_tower/ui/catalog.rb +18 -0
  19. data/lib/command_tower/ui/composer.rb +45 -0
  20. data/lib/command_tower/ui/document.rb +167 -0
  21. data/lib/command_tower/ui/email/layout.rb +95 -0
  22. data/lib/command_tower/ui/email/renderer/containers.rb +72 -0
  23. data/lib/command_tower/ui/email/renderer/inline_nodes.rb +70 -0
  24. data/lib/command_tower/ui/email/renderer/styling.rb +91 -0
  25. data/lib/command_tower/ui/email/renderer/text_nodes.rb +78 -0
  26. data/lib/command_tower/ui/email/renderer.rb +89 -0
  27. data/lib/command_tower/ui/email/styles.rb +77 -0
  28. data/lib/command_tower/ui/fragment.rb +54 -0
  29. data/lib/command_tower/ui/fragments/cta_group.rb +60 -0
  30. data/lib/command_tower/ui/fragments/fact_row.rb +20 -0
  31. data/lib/command_tower/ui/fragments/facts.rb +35 -0
  32. data/lib/command_tower/ui/fragments/header.rb +51 -0
  33. data/lib/command_tower/ui/fragments/notice_frame.rb +36 -0
  34. data/lib/command_tower/ui/hardening.rb +73 -0
  35. data/lib/command_tower/ui/hostname.rb +124 -0
  36. data/lib/command_tower/ui/legacy_mapping.rb +66 -0
  37. data/lib/command_tower/ui/limits.rb +19 -0
  38. data/lib/command_tower/ui/nodes/action.rb +53 -0
  39. data/lib/command_tower/ui/nodes/avatar.rb +35 -0
  40. data/lib/command_tower/ui/nodes/badge.rb +17 -0
  41. data/lib/command_tower/ui/nodes/banner.rb +17 -0
  42. data/lib/command_tower/ui/nodes/base.rb +125 -0
  43. data/lib/command_tower/ui/nodes/button.rb +34 -0
  44. data/lib/command_tower/ui/nodes/card.rb +19 -0
  45. data/lib/command_tower/ui/nodes/code.rb +28 -0
  46. data/lib/command_tower/ui/nodes/component.rb +39 -0
  47. data/lib/command_tower/ui/nodes/divider.rb +11 -0
  48. data/lib/command_tower/ui/nodes/facts.rb +14 -0
  49. data/lib/command_tower/ui/nodes/image.rb +41 -0
  50. data/lib/command_tower/ui/nodes/instant.rb +59 -0
  51. data/lib/command_tower/ui/nodes/key_value.rb +63 -0
  52. data/lib/command_tower/ui/nodes/span.rb +76 -0
  53. data/lib/command_tower/ui/nodes/stack.rb +24 -0
  54. data/lib/command_tower/ui/nodes/stat_tile.rb +20 -0
  55. data/lib/command_tower/ui/nodes/text.rb +24 -0
  56. data/lib/command_tower/ui/text_derivation.rb +89 -0
  57. data/lib/command_tower/ui/time_formatter.rb +59 -0
  58. data/lib/command_tower/ui/tokens/ui_token_mapping.json +277 -0
  59. data/lib/command_tower/ui/tokens.rb +56 -0
  60. data/lib/command_tower/ui/zone_abbreviation.rb +130 -0
  61. data/lib/command_tower/ui.rb +80 -0
  62. data/lib/command_tower/version.rb +1 -1
  63. data/lib/command_tower.rb +1 -0
  64. data/lib/tasks/ui.rake +16 -0
  65. metadata +67 -1
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "action_view"
4
+ require "command_tower/ui/email/renderer/styling"
5
+ require "command_tower/ui/email/renderer/containers"
6
+ require "command_tower/ui/email/renderer/text_nodes"
7
+ require "command_tower/ui/email/renderer/inline_nodes"
8
+
9
+ module CommandTower
10
+ module UI
11
+ module Email
12
+ # Renders a validated UI document to table-based, inline-styled email HTML
13
+ # plus a plain-text part. Spec: design ux/states.md sections 5 and 8.
14
+ #
15
+ # - Escaping is done by ActionView's TagHelper; document values are never
16
+ # interpolated into markup.
17
+ # - `code` nodes are rejected (InvalidDocumentError, path and code only):
18
+ # a check-in code never reaches an email.
19
+ # - Conversions: component -> fallback tree; internal navigate ->
20
+ # `origin + path`; countdown -> short; icons dropped; ghost button ->
21
+ # underlined link; image width/height derived from `aspect`.
22
+ # - Text colour comes from `textTone` (the node default is "primary", so a
23
+ # variant's own default tone, for example subtitle, is not applied).
24
+ #
25
+ # Optional chrome keywords: `footer_html:` (trusted, escaped HTML),
26
+ # `app_name:` and `preheader:` (plain text), passed to {Layout}.
27
+ class Renderer
28
+ Output = Data.define(:html, :text)
29
+
30
+ ORIGIN_FORMAT = %r{\Ahttps?://[^\s/?#@\\]+\z}
31
+ PREHEADER_LIMIT = 110
32
+ CHROME_KEYS = %i[footer_html app_name preheader].freeze
33
+ TABLE = { role: "presentation", cellpadding: 0, cellspacing: 0, border: 0 }.freeze
34
+ # Full-width body tables use a fixed layout so they shrink with the container;
35
+ # in auto layout a wide image's width attribute keeps the table from shrinking.
36
+ FILL_TABLE = TABLE.merge(width: "100%", style: "table-layout:fixed;").freeze
37
+ HANDLERS = {
38
+ Nodes::Stack => :stack, Nodes::Facts => :facts, Nodes::Card => :card, Nodes::Divider => :divider,
39
+ Nodes::Text => :text, Nodes::Instant => :instant, Nodes::KeyValue => :key_value,
40
+ Nodes::Badge => :badge, Nodes::Button => :button, Nodes::Image => :image,
41
+ Nodes::Banner => :banner, Nodes::Avatar => :avatar, Nodes::StatTile => :stat_tile,
42
+ Nodes::Component => :component
43
+ }.freeze
44
+
45
+ include ActionView::Helpers::TagHelper
46
+ include ActionView::Helpers::OutputSafetyHelper
47
+ include Styling
48
+ include Containers
49
+ include TextNodes
50
+ include InlineNodes
51
+
52
+ def self.call(document, palette:, origin:, **chrome)
53
+ new(palette:, origin:).render_document(document, **chrome.assert_valid_keys(*CHROME_KEYS))
54
+ end
55
+
56
+ def initialize(palette:, origin:)
57
+ @palette = Styles.validate_palette!(palette)
58
+ valid_origin = origin.is_a?(String) && ORIGIN_FORMAT.match?(origin)
59
+ raise InvalidTokenError, "origin must be an http(s) origin" unless valid_origin
60
+
61
+ @origin = origin
62
+ end
63
+
64
+ def render_document(document, preheader: nil, **chrome)
65
+ reject_code!(document.root, "root")
66
+ document.validate!
67
+ text = TextDerivation.call(document.root)
68
+ preheader ||= text.gsub(/\s+/, " ").strip.truncate(PREHEADER_LIMIT)
69
+ html = Layout.call(body_html: render(document.root).to_str, palette: @palette, preheader:, **chrome)
70
+ Output.new(html:, text:)
71
+ end
72
+
73
+ private
74
+
75
+ def reject_code!(object, path)
76
+ reject!(path, :code_not_allowed) if object.is_a?(Nodes::Code)
77
+ object.each_child { |relative, child| reject_code!(child, "#{path}.#{relative}") }
78
+ end
79
+
80
+ def render(node)
81
+ handler = HANDLERS[node.class]
82
+ reject!("root", :invalid_node) unless handler
83
+
84
+ send(handler, node)
85
+ end
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module Email
6
+ # Email palette contract and tint maths. Spec: design ux/states.md
7
+ # sections 5.C and 8 (E1, E2).
8
+ module Styles
9
+ PALETTE_KEYS = %w[
10
+ background card border primary primaryForeground foreground textPrimary
11
+ textSecondary muted mutedForeground success warning danger
12
+ ].freeze
13
+ HEX_COLOR = /\A#\h{6}\z/
14
+
15
+ class << self
16
+ # Returns a frozen copy with string keys. Rejects missing or extra
17
+ # keys and any value that is not `#RRGGBB`. Messages name keys, never values.
18
+ def validate_palette!(palette)
19
+ raise InvalidTokenError, "palette must be a Hash" unless palette.is_a?(Hash)
20
+
21
+ normalized = palette.transform_keys(&:to_s)
22
+ reject_keys!(normalized)
23
+ bad = normalized.reject { |_key, value| value.is_a?(String) && HEX_COLOR.match?(value) }.keys
24
+ raise InvalidTokenError, "palette values must be #RRGGBB: #{bad.join(', ')}" if bad.any?
25
+
26
+ normalized.freeze
27
+ end
28
+
29
+ # Pre-blended tint for a tone on `palette.card`: { background:, border: }.
30
+ # Neutral uses `muted` at the neutral alpha and the `border` colour at 1.0.
31
+ def tint(tone, palette)
32
+ palette = validate_palette!(palette)
33
+ mapping = Tokens.mapping
34
+ color = palette.fetch(Tokens.tone_palette_key(tone))
35
+ card = palette.fetch("card")
36
+ return neutral_tint(color, card, palette, mapping) if tone.to_s == "neutral"
37
+
38
+ {
39
+ background: blend(color, card, mapping.fetch("tintBackgroundAlpha")),
40
+ border: blend(color, card, mapping.fetch("tintBorderAlpha"))
41
+ }
42
+ end
43
+
44
+ # Blends `foreground` over `base` at `alpha`, per 8-bit channel, half-up
45
+ # rounding with exact Rational arithmetic (Float misrounds exact halves).
46
+ def blend(foreground, base, alpha)
47
+ exact_alpha = alpha.to_s.to_r # "0.1".to_r is 1/10; Float#to_r is not
48
+ hex = channels(foreground).zip(channels(base)).map do |fg, bg|
49
+ format("%02X", (bg + ((fg - bg) * exact_alpha) + Rational(1, 2)).floor)
50
+ end
51
+ "##{hex.join}"
52
+ end
53
+
54
+ private
55
+
56
+ def neutral_tint(color, card, palette, mapping)
57
+ {
58
+ background: blend(color, card, mapping.fetch("neutralTintBackgroundAlpha")),
59
+ border: palette.fetch(mapping.fetch("neutralTintBorder"))
60
+ }
61
+ end
62
+
63
+ def reject_keys!(normalized)
64
+ missing = PALETTE_KEYS - normalized.keys
65
+ extra = normalized.keys - PALETTE_KEYS
66
+ raise InvalidTokenError, "palette missing keys: #{missing.join(', ')}" if missing.any?
67
+ raise InvalidTokenError, "palette has unknown keys: #{extra.join(', ')}" if extra.any?
68
+ end
69
+
70
+ def channels(hex)
71
+ hex.delete_prefix("#").scan(/../).map { |pair| pair.to_i(16) }
72
+ end
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_model"
4
+
5
+ module CommandTower
6
+ module UI
7
+ # Base class for reusable, parameterized pieces of a document. A fragment
8
+ # declares inputs with `attribute` and `validates`, and `compose(b)` emits
9
+ # primitives only, through the Builder. Fragments are referenced by constant
10
+ # (`d.fragment(MyFragment, **inputs)`); there is no registry (design D3).
11
+ #
12
+ # class FactRow < CommandTower::UI::Fragment
13
+ # attribute :label, :string
14
+ # attribute :value, :string
15
+ # validates :label, :value, presence: true
16
+ #
17
+ # def compose(b)
18
+ # b.key_value { |kv| kv.item label, value }
19
+ # end
20
+ # end
21
+ #
22
+ # Invalid inputs raise InvalidFragmentError at construction. The error
23
+ # carries attribute names and error codes only, never input values.
24
+ class Fragment
25
+ include ActiveModel::Model
26
+ include ActiveModel::Attributes
27
+ include ActiveModel::Validations
28
+
29
+ def initialize(**inputs)
30
+ super
31
+ raise InvalidFragmentError, invalid_message unless valid?
32
+ rescue ActiveModel::UnknownAttributeError => e
33
+ raise InvalidFragmentError, "#{self.class.name}: unknown input #{e.attribute}"
34
+ end
35
+
36
+ # Emits primitives into the builder. Subclasses implement this.
37
+ def compose(_builder)
38
+ raise NotImplementedError, "#{self.class.name} must implement compose(builder)"
39
+ end
40
+
41
+ def inspect
42
+ "#<#{self.class.name}>"
43
+ end
44
+ alias to_s inspect
45
+
46
+ private
47
+
48
+ def invalid_message
49
+ codes = errors.map { |error| "#{error.attribute}:#{error.type}" }
50
+ "#{self.class.name}: invalid inputs (#{codes.join(', ')})"
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module Fragments
6
+ # Stacked buttons: the primary first, then up to two secondaries.
7
+ # `buttons` is a list of `{ label:, action:, variant: }` symbol-key hashes; `variant`
8
+ # defaults to `secondary`, and `ghost` is used only when a caller asks.
9
+ #
10
+ # d.fragment(CtaGroup, buttons: [
11
+ # { label: "View classes", action: d.navigate(path: "/classes"), variant: :primary },
12
+ # { label: "Details", action: d.navigate(path: "/details") }
13
+ # ])
14
+ class CtaGroup < Fragment
15
+ MAX_SECONDARIES = 2
16
+
17
+ attribute :buttons, default: -> { [] }
18
+
19
+ validate :buttons_are_valid
20
+
21
+ def compose(builder)
22
+ builder.stack(gap: :sm) do |s|
23
+ primaries.each { |button| emit(s, button) }
24
+ secondaries.each { |button| emit(s, button) }
25
+ end
26
+ end
27
+
28
+ private
29
+
30
+ def variant_of(button)
31
+ (button[:variant] || :secondary).to_s
32
+ end
33
+
34
+ def primaries
35
+ buttons.select { |button| variant_of(button) == "primary" }
36
+ end
37
+
38
+ def secondaries
39
+ buttons.reject { |button| variant_of(button) == "primary" }
40
+ end
41
+
42
+ def emit(builder, button)
43
+ builder.button(button.fetch(:label), action: button.fetch(:action), variant: variant_of(button))
44
+ end
45
+
46
+ def buttons_are_valid
47
+ return errors.add(:buttons, :invalid) unless well_formed?
48
+
49
+ errors.add(:buttons, :too_many_primaries) if primaries.length > 1
50
+ errors.add(:buttons, :too_many_secondaries) if secondaries.length > MAX_SECONDARIES
51
+ end
52
+
53
+ def well_formed?
54
+ buttons.is_a?(Array) && buttons.any? &&
55
+ buttons.all? { |button| button.is_a?(Hash) && button.key?(:label) && button.key?(:action) }
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module Fragments
6
+ # One labelled fact: a `key_value` with a single item. `value` is a String.
7
+ class FactRow < Fragment
8
+ attribute :value, :string
9
+ attribute :label, :string
10
+ attribute :icon, :string
11
+
12
+ validates :value, presence: true
13
+
14
+ def compose(builder)
15
+ builder.key_value { |kv| kv.item(label.presence, value, icon: icon.presence) }
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module Fragments
6
+ # Base class for a host's shared fact block. The pinned entry point is
7
+ # `Facts.call(f, metadata:)`: `f` is the Builder, `metadata` is the host's
8
+ # data. It emits exactly one `facts` node; the subclass fills it by
9
+ # implementing `compose(b, metadata:)` with primitives (or other fragments).
10
+ #
11
+ # class ClassFacts < CommandTower::UI::Fragments::Facts
12
+ # def compose(b, metadata:)
13
+ # b.text(metadata.fetch(:title), variant: :title)
14
+ # b.key_value { |kv| kv.item "Where", metadata.fetch(:where) }
15
+ # end
16
+ # end
17
+ #
18
+ # ClassFacts.call(d, metadata: { title: "Yoga", where: "Studio B" })
19
+ class Facts
20
+ def self.call(builder, metadata:)
21
+ new.call(builder, metadata:)
22
+ end
23
+
24
+ def call(builder, metadata:)
25
+ builder.facts { |inner| compose(inner, metadata:) }
26
+ end
27
+
28
+ # Subclasses implement this.
29
+ def compose(_builder, metadata:)
30
+ raise NotImplementedError, "#{self.class.name} must implement compose(builder, metadata:)"
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module Fragments
6
+ # Vertical header (UX gap G1: the catalog has no horizontal layout):
7
+ # avatar?, badge?, then title and subtitle.
8
+ #
9
+ # d.fragment(Header, title: "Class canceled", subtitle: "Studio B",
10
+ # badge_label: "Canceled", badge_tone: :danger,
11
+ # avatar: { initials: "SB" })
12
+ class Header < Fragment
13
+ attribute :title, :string
14
+ attribute :subtitle, :string
15
+ attribute :badge_label, :string
16
+ attribute :badge_tone, :string
17
+ # Hash with symbol keys of Builder#avatar arguments (`src:`/`initials:`/`alt:`); size is fixed to md.
18
+ attribute :avatar
19
+
20
+ validates :title, presence: true
21
+ validates :badge_tone, presence: true, if: -> { badge_label.present? }
22
+ validate :avatar_is_hash_or_nil
23
+
24
+ def compose(builder)
25
+ builder.stack(gap: :sm, align: :start) do |s|
26
+ compose_identity(s)
27
+ compose_titles(s)
28
+ end
29
+ end
30
+
31
+ private
32
+
33
+ def compose_identity(builder)
34
+ builder.avatar(**avatar, size: :md) if avatar
35
+ builder.badge(badge_label, tone: badge_tone) if badge_label.present?
36
+ end
37
+
38
+ def compose_titles(builder)
39
+ builder.stack(gap: :xs) do |s|
40
+ s.text(title, variant: :heading_m)
41
+ s.text(subtitle, variant: :subtitle, text_tone: :secondary) if subtitle.present?
42
+ end
43
+ end
44
+
45
+ def avatar_is_hash_or_nil
46
+ errors.add(:avatar, :invalid) unless avatar.nil? || avatar.is_a?(Hash)
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module Fragments
6
+ # A tinted card with a title and body paragraphs. Informational only: no
7
+ # acknowledge or dismiss control.
8
+ class NoticeFrame < Fragment
9
+ attribute :title, :string
10
+ attribute :tone, :string, default: "neutral"
11
+ attribute :body, default: -> { [] }
12
+
13
+ validates :title, presence: true
14
+ validates :tone, inclusion: { in: Tokens::TONE }
15
+ validate :body_is_list_of_strings
16
+
17
+ def compose(builder)
18
+ builder.card(surface: :tinted, tone:, padding: :lg) do |c|
19
+ c.stack(gap: :sm) do |s|
20
+ s.text(title, variant: :heading_m)
21
+ Array(body).each { |paragraph| s.text(paragraph, variant: :body) }
22
+ end
23
+ end
24
+ end
25
+
26
+ private
27
+
28
+ def body_is_list_of_strings
29
+ return if body.is_a?(Array) && body.all?(String)
30
+
31
+ errors.add(:body, :invalid)
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module CommandTower
6
+ module UI
7
+ # Wire hardening for paths and links (design section 8.1). Every check
8
+ # returns a code symbol or nil/true; none echoes the value it rejected.
9
+ # Cases are shared with the frontend through spec/fixtures/ui/wire_hardening.json.
10
+ module Hardening
11
+ INTERNAL_PATH = %r{\A/(?![/\\])[^\s\\]*\z}
12
+ CONTROL_OR_SPACE = /[[:cntrl:][:space:]]/
13
+ # Encoded protocol-relative (%2f%2f, or a leading %2f), encoded backslash, encoded control characters.
14
+ ENCODED_UNSAFE = %r{%2f%2f|%5c|\A/%2f|%[01][0-9a-f]|%7f}i
15
+ UNSAFE_LINK_CHARS = /[[:cntrl:][:space:]\\]/
16
+ MAILTO = /\Amailto:[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}(?:\?[^\s#]*)?\z/
17
+ TEL = /\Atel:\+?[0-9][0-9.\-()]{2,19}\z/
18
+
19
+ class << self
20
+ def internal_path?(value)
21
+ value.is_a?(String) &&
22
+ INTERNAL_PATH.match?(value) &&
23
+ !CONTROL_OR_SPACE.match?(value) &&
24
+ !ENCODED_UNSAFE.match?(value)
25
+ end
26
+
27
+ # nil when the href is allowed; otherwise :invalid_href, :unsafe_scheme or :userinfo.
28
+ def external_href_code(value)
29
+ return :invalid_href unless plain_link_string?(value)
30
+
31
+ case value
32
+ when /\Ahttps:/ then https_code(value)
33
+ when /\Amailto:/ then pattern_code(value, MAILTO)
34
+ when /\Atel:/ then pattern_code(value, TEL)
35
+ else :unsafe_scheme
36
+ end
37
+ end
38
+
39
+ # Images: https only and the host must be an exact member of hosts
40
+ # (already lowercased and IDN-normalized by config.ui).
41
+ def image_src_code(value, hosts:)
42
+ return :unsafe_scheme unless value.is_a?(String) && value.start_with?("https:")
43
+
44
+ code = external_href_code(value)
45
+ return code if code
46
+
47
+ host = Hostname.normalize(URI.parse(value).host)
48
+ hosts.include?(host) ? nil : :host_not_allowed
49
+ end
50
+
51
+ private
52
+
53
+ def plain_link_string?(value)
54
+ value.is_a?(String) && !value.empty? && !UNSAFE_LINK_CHARS.match?(value)
55
+ end
56
+
57
+ def pattern_code(value, pattern)
58
+ pattern.match?(value) ? nil : :invalid_href
59
+ end
60
+
61
+ def https_code(value)
62
+ uri = URI.parse(value)
63
+ return :invalid_href unless uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty?
64
+ return :userinfo if uri.userinfo
65
+
66
+ nil
67
+ rescue URI::InvalidURIError
68
+ :invalid_href
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ # Normalizes a bare host for exact-match allowlists: NFC, lowercase,
6
+ # non-ASCII labels converted to punycode (RFC 3492). Returns nil when the
7
+ # input is not a bare host (scheme, port, path, userinfo, wildcard, spaces).
8
+ module Hostname
9
+ LABEL = /\A[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\z/
10
+ FORBIDDEN = %r{[\s/\\:@*?#%\u0000-\u001f]}
11
+ MAX_LENGTH = 253
12
+
13
+ def self.normalize(value)
14
+ return nil unless value.is_a?(String)
15
+
16
+ host = value.strip.unicode_normalize(:nfc).downcase.chomp(".")
17
+ return nil unless bare_host?(host)
18
+
19
+ labels = host.split(".", -1).map { |label| ascii_label(label) }
20
+ labels.any?(&:nil?) ? nil : labels.join(".")
21
+ rescue ArgumentError, Encoding::UndefinedConversionError
22
+ nil
23
+ end
24
+
25
+ def self.bare_host?(host)
26
+ !host.empty? && host.length <= MAX_LENGTH && !host.match?(FORBIDDEN)
27
+ end
28
+ private_class_method :bare_host?
29
+
30
+ def self.ascii_label(label)
31
+ ascii = label.ascii_only? ? label : "xn--#{Punycode.encode(label)}"
32
+ ascii.match?(LABEL) ? ascii : nil
33
+ end
34
+ private_class_method :ascii_label
35
+
36
+ # RFC 3492 encoder for one label.
37
+ class Punycode
38
+ BASE = 36
39
+ T_MIN = 1
40
+ T_MAX = 26
41
+ SKEW = 38
42
+ DAMP = 700
43
+ INITIAL_BIAS = 72
44
+ INITIAL_N = 128
45
+
46
+ def self.encode(input)
47
+ new(input).encode
48
+ end
49
+
50
+ def initialize(input)
51
+ @codepoints = input.codepoints
52
+ @output = @codepoints.select { |cp| cp < INITIAL_N }.map(&:chr)
53
+ @basic = @handled = @output.length
54
+ @next_cp = INITIAL_N
55
+ @delta = 0
56
+ @bias = INITIAL_BIAS
57
+ end
58
+
59
+ def encode
60
+ @output << "-" if @basic.positive?
61
+ encode_next_codepoint while @handled < @codepoints.length
62
+ @output.join
63
+ end
64
+
65
+ private
66
+
67
+ def encode_next_codepoint
68
+ smallest = @codepoints.select { |cp| cp >= @next_cp }.min
69
+ @delta += (smallest - @next_cp) * (@handled + 1)
70
+ @next_cp = smallest
71
+ @codepoints.each { |cp| handle(cp) }
72
+ @delta += 1
73
+ @next_cp += 1
74
+ end
75
+
76
+ def handle(codepoint)
77
+ @delta += 1 if codepoint < @next_cp
78
+ return unless codepoint == @next_cp
79
+
80
+ emit_delta
81
+ @bias = adapt(@handled + 1, @handled == @basic)
82
+ @delta = 0
83
+ @handled += 1
84
+ end
85
+
86
+ def emit_delta
87
+ quotient = @delta
88
+ step = BASE
89
+ loop do
90
+ limit = threshold(step)
91
+ break if quotient < limit
92
+
93
+ @output << digit(limit + ((quotient - limit) % (BASE - limit)))
94
+ quotient = (quotient - limit) / (BASE - limit)
95
+ step += BASE
96
+ end
97
+ @output << digit(quotient)
98
+ end
99
+
100
+ def threshold(step)
101
+ return T_MIN if step <= @bias
102
+ return T_MAX if step >= @bias + T_MAX
103
+
104
+ step - @bias
105
+ end
106
+
107
+ def digit(value)
108
+ (value < 26 ? value + 97 : value + 22).chr
109
+ end
110
+
111
+ def adapt(num_points, first_time)
112
+ delta = first_time ? @delta / DAMP : @delta / 2
113
+ delta += delta / num_points
114
+ step = 0
115
+ while delta > ((BASE - T_MIN) * T_MAX) / 2
116
+ delta /= BASE - T_MIN
117
+ step += BASE
118
+ end
119
+ step + (((BASE - T_MIN + 1) * delta) / (delta + SKEW))
120
+ end
121
+ end
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ # Maps a catalog-2 UI document to `inbox_document_v1` blocks for catalog-1
6
+ # clients. Not wired into any caller yet.
7
+ #
8
+ # Output is emitted through the real `InboxDocument.compose` Builder
9
+ # (resolved at call time, so lib/ui keeps no load-time dependency on
10
+ # Messaging). The Builder owns the block rules; this mapping adds the
11
+ # narrower external-link allowlist (https, mailto, tel) the Builder lacks.
12
+ #
13
+ # - text: paragraph (spans flattened, links lose their action)
14
+ # - button: cta with a typed destination; dropped when the destination
15
+ # fails the allowlist
16
+ # - time: instant
17
+ # - component whose key is in `legacy_presentation_keys`: presentation;
18
+ # any other component maps its fallback tree
19
+ # - stack, card, facts: children mapped in order
20
+ # - banner, key_value, stat_tile, badge, image: derived-text paragraph
21
+ # - divider, avatar and code: dropped (a code value never reaches output)
22
+ module LegacyMapping
23
+ DERIVED_TEXT_NODES = [Nodes::Banner, Nodes::KeyValue, Nodes::StatTile, Nodes::Badge, Nodes::Image].freeze
24
+
25
+ class << self
26
+ def call(document, legacy_presentation_keys: [])
27
+ keys = Array(legacy_presentation_keys).map(&:to_s)
28
+ Messaging::Rendering::InboxDocument.compose do |builder|
29
+ map_node(document.root, builder, keys)
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ def map_node(node, builder, keys)
36
+ case node
37
+ when Nodes::Container then node.children.each { |child| map_node(child, builder, keys) }
38
+ when Nodes::Text, *DERIVED_TEXT_NODES then builder.paragraph(TextDerivation.call(node))
39
+ when Nodes::Button then map_button(node, builder)
40
+ when Nodes::Instant then builder.instant(node.at)
41
+ when Nodes::Component then map_component(node, builder, keys)
42
+ end
43
+ end
44
+
45
+ def map_button(node, builder)
46
+ action = node.action
47
+ return unless action.is_a?(Nodes::Action::Navigate)
48
+
49
+ if action.path
50
+ builder.cta(node.label, path: action.path) if Hardening.internal_path?(action.path)
51
+ elsif action.href && Hardening.external_href_code(action.href).nil?
52
+ builder.cta(node.label, href: action.href)
53
+ end
54
+ end
55
+
56
+ def map_component(node, builder, keys)
57
+ if keys.include?(node.key)
58
+ builder.presentation(node.key, variant: node.variant)
59
+ else
60
+ map_node(node.fallback, builder, keys)
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end