command_tower 0.25.0 → 0.26.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 (25) hide show
  1. checksums.yaml +4 -4
  2. data/app/errors/command_tower/errors/account/experience_state_impersonation_forbidden.rb +17 -0
  3. data/app/errors/command_tower/errors/account/experience_state_limit_reached.rb +21 -0
  4. data/app/errors/command_tower/errors/account/experience_state_rate_limited.rb +25 -0
  5. data/app/errors/command_tower/errors/account/experience_state_unregistered.rb +21 -0
  6. data/app/services/command_tower/services/account/experience_states/check_complete_rate_limit.rb +52 -0
  7. data/app/services/command_tower/services/account/experience_states/complete.rb +13 -0
  8. data/app/services/command_tower/services/account/experience_states/completed.rb +36 -0
  9. data/app/workflows/command_tower/workflows/me/error_mapping.rb +4 -1
  10. data/app/workflows/command_tower/workflows/me/experience_states/complete_workflow.rb +35 -7
  11. data/docs/api_reference.md +14 -1
  12. data/docs/audit.md +3 -0
  13. data/docs/bootstrap/08-initializer.md +12 -0
  14. data/docs/controllers.md +1 -1
  15. data/docs/extending.md +2 -1
  16. data/docs/upgrades/0.26.0.md +55 -0
  17. data/docs/upgrades/README.md +1 -0
  18. data/lib/command_tower/configuration/registry/audit/config.rb +1 -1
  19. data/lib/command_tower/configuration/registry/config.rb +7 -0
  20. data/lib/command_tower/configuration/registry/experience_states/config.rb +134 -0
  21. data/lib/command_tower/configuration/registry/experience_states/key_definition.rb +16 -0
  22. data/lib/command_tower/engine.rb +4 -0
  23. data/lib/command_tower/experience_states.rb +17 -0
  24. data/lib/command_tower/version.rb +1 -1
  25. metadata +12 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0fc112898abc411d7eb1f87f2aa7abbc30da084ac1a0a03e840cd25c0a4d216a
4
- data.tar.gz: 9c78de0cf5095e358f8187afaad3b30e1e08eb4fe1fc600589aa664d27ac3ecd
3
+ metadata.gz: 05b8ce1d039ec91d2228dad03542637f26f09a8ef2b8005978492eec134f2144
4
+ data.tar.gz: acf8ff86207ceab5feaacc3f8b32121667fc3ea42d774a2d86f93c4e5bd9f4f8
5
5
  SHA512:
6
- metadata.gz: 8f50b3501443d20d4ad35b7ed76f10c4b19d145243dc8991b9063f28ca1e43c4bac1838d13820ac94eefe06e8f712e6da02863eceecdca15339c83af94c42427
7
- data.tar.gz: a6c0ddcd88ebbef3b47832e15102bfc7852010489d362042ee23de90a5ab4ce9396e0abb6aa3a75f1b912a0c3a1fbb122079d224d394492e2692bfd2df192dfb
6
+ metadata.gz: 940629f890e6242659570a75f4f6ededeee48235d41c15ccf083f1fc487d06bac662bc4a3bff97fa782d559884c4e576b96b1546eb26b2e70a1ed46e142b44ca
7
+ data.tar.gz: c3d64495e56cf198f82acb1cd52db41b90568317239a2bbfc904b374673ec7823a1d0a47c58ba87d94abce145102e911bb259b241960efa0fb75d22140d8e31c
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module Account
6
+ class ExperienceStateImpersonationForbidden < CommandTower::Errors::ForbiddenError
7
+ def code
8
+ "experience_state_impersonation_forbidden"
9
+ end
10
+
11
+ def message
12
+ "Experience states cannot be changed while impersonating"
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module Account
6
+ class ExperienceStateLimitReached < CommandTower::Errors::ApplicationError
7
+ def code
8
+ "experience_state_limit_reached"
9
+ end
10
+
11
+ def message
12
+ "Experience state limit reached"
13
+ end
14
+
15
+ def log_level
16
+ :warn
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module Account
6
+ class ExperienceStateRateLimited < CommandTower::Errors::ApplicationError
7
+ def initialize(retry_after_seconds: nil)
8
+ super(details: retry_after_seconds ? { retry_after_seconds: retry_after_seconds } : nil)
9
+ end
10
+
11
+ def code
12
+ "experience_state_rate_limited"
13
+ end
14
+
15
+ def message
16
+ "Too many requests. Please try again later."
17
+ end
18
+
19
+ def log_level
20
+ :warn
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module Account
6
+ class ExperienceStateUnregistered < CommandTower::Errors::ApplicationError
7
+ def code
8
+ "experience_state_unregistered"
9
+ end
10
+
11
+ def message
12
+ "Experience state is not registered"
13
+ end
14
+
15
+ def log_level
16
+ :warn
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module Account
6
+ module ExperienceStates
7
+ # Rate limits experience-state completion per user, in fixed buckets sized by
8
+ # `config.registry.experience_states.complete_rate` (`limit` requests per `window` seconds).
9
+ #
10
+ # Fails open when Redis is unavailable: a limiter outage must not block completions. The
11
+ # failure publishes `command_tower.experience_states.rate_limiter_unavailable` (user id only).
12
+ # Over the limit, the result fails with `Errors::Account::ExperienceStateRateLimited`
13
+ # carrying the seconds until the bucket resets.
14
+ class CheckCompleteRateLimit < CommandTower::Services::ApplicationService
15
+ validate :user, is_a: User, required: true
16
+
17
+ def call
18
+ result = CommandTower::Services::RateLimits::Check.call(key:, ttl_seconds: window)
19
+ return report_unavailable(result) if result.failure?
20
+ return if result.data[:count] <= rate[:limit]
21
+
22
+ ttl = result.data[:ttl]
23
+ context.fail!(application_error: CommandTower::Errors::Account::ExperienceStateRateLimited.new(
24
+ retry_after_seconds: ttl.positive? ? ttl : nil
25
+ ))
26
+ end
27
+
28
+ private
29
+
30
+ def rate
31
+ CommandTower.config.registry.experience_states.complete_rate
32
+ end
33
+
34
+ def window
35
+ rate[:window]
36
+ end
37
+
38
+ def key
39
+ "experience-states:complete:#{user.id}:#{Time.now.to_i / window}"
40
+ end
41
+
42
+ def report_unavailable(result)
43
+ error = result.errors.first
44
+ CommandTower::Events.publish(category: :experience_states, name: "rate_limiter_unavailable",
45
+ payload: { user_id: user.id, error_class: (error&.cause || error).class.name,
46
+ log_level: :error })
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -36,6 +36,11 @@ module CommandTower
36
36
  return
37
37
  end
38
38
 
39
+ if cap_reached?(host_key)
40
+ context.fail!(application_error: CommandTower::Errors::Account::ExperienceStateLimitReached.new)
41
+ return
42
+ end
43
+
39
44
  begin
40
45
  created = CommandTower::UserExperienceState.create!(
41
46
  identity.merge(completed_at: Time.current),
@@ -48,6 +53,14 @@ module CommandTower
48
53
  context.created = false
49
54
  end
50
55
  end
56
+
57
+ private
58
+
59
+ # Soft cap, checked only when no row exists so a replay of an existing fact always succeeds.
60
+ def cap_reached?(host_key)
61
+ cap = CommandTower.config.registry.experience_states.max_rows_per_user
62
+ CommandTower::UserExperienceState.where(user_id: user.id, host_key:).count >= cap
63
+ end
51
64
  end
52
65
  end
53
66
  end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module Account
6
+ module ExperienceStates
7
+ # Read-only check for whether one completion fact exists for the user. The host_key is
8
+ # server-bound; callers never supply it.
9
+ class Completed < CommandTower::Services::ApplicationService
10
+ validate :user, is_a: User, required: true
11
+ validate :experience_key, is_a: String, required: true
12
+ validate :scope_type, is_a: String, required: true
13
+ validate :scope_identifier, is_a: String, required: true
14
+ validate :version, is_a: String, required: true
15
+
16
+ def call
17
+ host_key = CommandTower.config.application.host_key.to_s
18
+ return fail_unconfigured if host_key.blank?
19
+
20
+ context.completed = CommandTower::UserExperienceState.exists?(identity(host_key))
21
+ end
22
+
23
+ private
24
+
25
+ def identity(host_key)
26
+ { user:, host_key:, experience_key:, scope_type:, scope_identifier:, version: }
27
+ end
28
+
29
+ def fail_unconfigured
30
+ context.fail!(application_error: CommandTower::Errors::Account::ExperienceStatesHostUnconfiguredError.new)
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -27,10 +27,13 @@ module CommandTower
27
27
  CommandTower::Errors::Account::PushEndpointNotFoundError,
28
28
  CommandTower::Errors::Account::PushTestNoEndpointError,
29
29
  CommandTower::Errors::Account::PushTestDestinationError,
30
+ CommandTower::Errors::Account::ExperienceStateUnregistered,
31
+ CommandTower::Errors::Account::ExperienceStateLimitReached,
30
32
  CommandTower::Errors::ValidationError
31
33
  :unprocessable_entity
32
34
  when CommandTower::Errors::Account::PhoneVerificationThrottledError,
33
- CommandTower::Errors::Account::PushTestRateLimitError
35
+ CommandTower::Errors::Account::PushTestRateLimitError,
36
+ CommandTower::Errors::Account::ExperienceStateRateLimited
34
37
  :too_many_requests
35
38
  when CommandTower::Errors::Account::SmsCapabilityUnavailableError,
36
39
  CommandTower::Errors::Account::PushoverCapabilityUnavailableError,
@@ -8,6 +8,11 @@ module CommandTower
8
8
  retry_strategy :none
9
9
 
10
10
  def call(current_user:, experience_key:, scope_type:, scope_identifier:, version:, auth_context: nil)
11
+ # Check order matters: impersonation, then the rate limit (so unregistered traffic is
12
+ # throttled), then the registry, then the cap (inside Complete, only when no row exists).
13
+ errors = precondition_errors(current_user, experience_key, scope_type)
14
+ return rejected(*errors) if errors
15
+
11
16
  result = CommandTower::Services::Account::ExperienceStates::Complete.call(
12
17
  user: current_user,
13
18
  experience_key:,
@@ -15,19 +20,14 @@ module CommandTower
15
20
  scope_identifier:,
16
21
  version:,
17
22
  )
18
- unless result.success?
19
- error = result.errors.first
20
- return failure(
21
- errors: result.errors,
22
- http_status: CommandTower::Workflows::Me::ErrorMapping.http_status_for(error),
23
- )
24
- end
23
+ return rejected(*result.errors) unless result.success?
25
24
 
26
25
  if result.data[:created]
27
26
  audit(
28
27
  :experience_state_completed,
29
28
  affected_user: current_user,
30
29
  changes: {},
30
+ metadata: { experience_key:, version: },
31
31
  scope_class: :host,
32
32
  host_context: {
33
33
  type: scope_type,
@@ -42,6 +42,34 @@ module CommandTower
42
42
  response_effects: WorkflowSupport.expire_header_effects(auth_context),
43
43
  )
44
44
  end
45
+
46
+ private
47
+
48
+ # Returns the errors of the first failing precondition, or nil when all pass.
49
+ def precondition_errors(user, experience_key, scope_type)
50
+ if CommandTower::Current.impersonation_active
51
+ return [CommandTower::Errors::Account::ExperienceStateImpersonationForbidden.new]
52
+ end
53
+
54
+ limited = CommandTower::Services::Account::ExperienceStates::CheckCompleteRateLimit.call(user:)
55
+ return limited.errors unless limited.success?
56
+
57
+ return if registered?(experience_key, scope_type)
58
+
59
+ [CommandTower::Errors::Account::ExperienceStateUnregistered.new]
60
+ end
61
+
62
+ def registered?(experience_key, scope_type)
63
+ registry = CommandTower.config.registry.experience_states
64
+ registry.registered?(experience_key) && registry.fetch(experience_key).scope_type?(scope_type)
65
+ end
66
+
67
+ def rejected(*errors)
68
+ failure(
69
+ errors:,
70
+ http_status: CommandTower::Workflows::Me::ErrorMapping.http_status_for(errors.first),
71
+ )
72
+ end
45
73
  end
46
74
  end
47
75
  end
@@ -561,7 +561,20 @@ Durable completion facts for host-composed experiences. CommandTower stores opaq
561
561
 
562
562
  **RBAC:** `me_experience_states` (`index`, `complete`). Grant explicitly on host roles (dummy host `member` includes it).
563
563
 
564
- **Audit:** first durable creation emits `experience_state_completed` (opaque `host_context` type/identifier). Idempotent replay does not emit again.
564
+ **Registration:** a host registers every key it completes with `config.registry.experience_states.register "key", scope_types: %w[...]` (key: non-blank string of at most 128 characters; at least one scope type). CommandTower seeds none. `POST complete` for a key or scope type that is not registered fails with `422` `experience_state_unregistered`. The registry freezes after boot. A host with `host_key` set and an empty registry raises at boot in the test environment and logs an error elsewhere. See [Bootstrap 08](bootstrap/08-initializer.md#experience-state-keys).
565
+
566
+ **`POST complete` checks, in order:**
567
+
568
+ | Order | Check | Failure |
569
+ |------:|-------|---------|
570
+ | 1 | Impersonation active (`Current.impersonation_active`) | `403` `experience_state_impersonation_forbidden` |
571
+ | 2 | Per-user rate limit (`registry.experience_states.complete_rate`, default 30 per 60 s) | `429` `experience_state_rate_limited`, `errors[].details.retry_after_seconds` |
572
+ | 3 | Key and scope type registered | `422` `experience_state_unregistered` |
573
+ | 4 | Soft cap (`registry.experience_states.max_rows_per_user`, default 250 rows per user and `host_key`), checked only when no row exists yet | `422` `experience_state_limit_reached` |
574
+
575
+ The rate limit runs before the registry check so unregistered traffic is throttled too. Replay of an existing fact returns `200` and skips the cap. The rate limit fails open: if the limiter itself fails, the request proceeds (the failure is logged with the user id only). Error messages never echo the submitted key or identifier. `GET` is unchanged by all of the above.
576
+
577
+ **Audit:** first durable creation emits `experience_state_completed` (opaque `host_context` type/identifier; metadata `experience_key` and `version`; retention `one_year`). Idempotent replay does not emit again. See [Audit](audit.md).
565
578
 
566
579
  **Spec:** `spec/requests/command_tower/me/experience_states_spec.rb`.
567
580
 
data/docs/audit.md CHANGED
@@ -91,6 +91,7 @@ CommandTower.config.registry.audit.set_enabled!(:login_failed, true)
91
91
  | `home_notice_acknowledged` | yes | no |
92
92
  | `home_notice_dismissed` | yes | no |
93
93
  | `home_notice_control_changed` | yes | no |
94
+ | `experience_state_completed` | yes | yes |
94
95
 
95
96
  `messaging_inbox_item_viewed` is emitted by `Workflows::Messaging::Inbox::OpenWorkflow` once per first view of an inbox item, for every notification type (metadata: `inbox_item_id`, `communication_id`; retention `ninety_days`, not in account history). A repeat open, bulk read/unread, `Show`, and `Contract::Inbox` emit nothing. An impersonated open returns the detail but neither marks the item viewed nor audits.
96
97
 
@@ -100,6 +101,8 @@ CommandTower.config.registry.audit.set_enabled!(:login_failed, true)
100
101
 
101
102
  `home_notice_dismissed` is emitted by `Services::HomeNotices::Dismiss` (via `POST /me/home-notices/:id/dismiss`) when the request itself changes the row (affected user: the user; metadata `notice_id`, `key`, `kind`, `severity`; no changes; retention `ninety_days`; not in account history). Only dismissible notices can be dismissed. A repeat dismiss while already dismissed, a blocking dismiss (422) and an impersonated request (403) emit nothing.
102
103
 
104
+ `experience_state_completed` is emitted by `Workflows::Me::ExperienceStates::CompleteWorkflow` on the first durable creation of a fact (affected user: the user; metadata `experience_key` and `version`; no changes; retention `one_year`; not in account history). The host context carries the opaque scope type and identifier. An idempotent replay and every rejected request (impersonating, rate limited, unregistered, over the cap) emit nothing. See [API reference](api_reference.md#experience-states).
105
+
103
106
  `home_notice_control_changed` is emitted by `Workflows::Admin::HomeNotices::UpdateControlWorkflow` (via `PATCH /admin/home-notices/:key`) in the same transaction as the write, only when the request changes the effective state (admin attribution `admin_direct`; no affected user; metadata `key`; change `enabled` from/to; retention `permanent`; not in account history). A no-op, an unknown key (404) and an impersonated request (403) emit nothing. See [home_notices.md](home_notices.md#kill-switch-runbook).
104
107
 
105
108
  `messaging_unsubscribed` is emitted by the one-click unsubscribe workflow when a token turns email off for a type (affected user: the token's user; change key `email_enabled`; `user_history`; retention `permanent`). See [messaging_integration_guide.md](messaging_integration_guide.md#email-compliance-defined-types).
@@ -31,6 +31,18 @@ Blank `host_key` → Me experience-state routes return **503**.
31
31
 
32
32
  The dummy sets `config.application.host_key = "command_tower"`. A product host uses its **own** key.
33
33
 
34
+ ### Experience-state keys
35
+
36
+ Register every experience-state key the product completes, **before** the first deploy (or gem bump) that serves `POST /me/experience-states/complete`. An unregistered key is refused with `422`. CommandTower seeds none.
37
+
38
+ ```ruby
39
+ CommandTower.configure do |config|
40
+ config.registry.experience_states.register "welcome", scope_types: %w[account]
41
+ end
42
+ ```
43
+
44
+ A key is a non-blank string of at most 128 characters; a duplicate raises. With `host_key` set and nothing registered, boot raises in the test environment and logs an error in development and production. Optional composers: `config.registry.experience_states.max_rows_per_user` (default 250) and `complete_rate` (default `{ limit: 30, window: 60 }`). Contract: [API reference](../api_reference.md#experience-states).
45
+
34
46
  ### Secrets
35
47
 
36
48
  Prefer ENV already injected by Compose:
data/docs/controllers.md CHANGED
@@ -21,7 +21,7 @@ This page is an **index** of route areas. Detailed request/response contracts li
21
21
  | Phone | `/me/phone*` | Phone endpoint + verification |
22
22
  | Pushover | `/me/pushover*` | Pushover endpoint lifecycle + verification |
23
23
  | Push | `/me/push*` | Expo push endpoint collection (register / replace / revoke) |
24
- | Experience states | `/me/experience-states*` | Durable completed experience-state facts (list / complete) |
24
+ | Experience states | `/me/experience-states*` | Durable completed experience-state facts (list / complete). Complete is limited to host-registered keys, rate limited, capped, and refused while impersonating: [API reference](api_reference.md#experience-states) |
25
25
  | Admin messaging | `/admin/messaging/announcements` | Cohort announcements |
26
26
 
27
27
  Exact paths depend on where the host mounts the engine.
data/docs/extending.md CHANGED
@@ -17,7 +17,8 @@ Layer map: [architecture.md](architecture.md). Install/configure/migrate/doctor:
17
17
  | `Communications::Produce` / `ProduceMany` | Sending messaging |
18
18
  | `FactoryBot.modify` | Extend shared factories |
19
19
  | Model reopen | Product associations / behavior |
20
- | Initializers | Configuration, including `config.registry.audit.event`, `config.registry.admin_workspace.tool`, and `config.registry.principal_capabilities.capability` |
20
+ | Initializers | Configuration, including `config.registry.audit.event`, `config.registry.admin_workspace.tool`, `config.registry.principal_capabilities.capability`, and `config.registry.experience_states.register` (required before a key can be completed; see [API reference](api_reference.md#experience-states)) |
21
+ | `Services::Account::ExperienceStates::Completed` | Read-only check that one completion fact exists: `call(user:, experience_key:, scope_type:, scope_identifier:, version:)` returns `data[:completed]`. The `host_key` is server-bound |
21
22
  | Notification catalogs / channel policy | Host-owned messaging customization |
22
23
  | `app/views/command_tower/messaging/rendering/**` | Host override of generic and/or per-`notification_type_key` rendered Email/SMS/Pushover/Push templates — see [messaging_integration_guide.md](messaging_integration_guide.md#rendering-template-overrides) |
23
24
 
@@ -0,0 +1,55 @@
1
+ # Upgrade: CommandTower 0.26.0
2
+
3
+ **From:** `0.25.0`
4
+ **To:** `0.26.0`
5
+
6
+ Minor release: experience-states hardening. `POST /me/experience-states/complete` now only accepts keys the host registered, and it is rate limited, capped and refused while impersonating. Contract: [API reference](../api_reference.md#experience-states). No migration.
7
+
8
+ ## Host-visible additions
9
+
10
+ | Change | Host impact |
11
+ |--------|-------------|
12
+ | `config.registry.experience_states.register "key", scope_types: [...]` | **Required.** Any key or scope type not registered is refused with `422` `experience_state_unregistered`. CommandTower seeds no keys. |
13
+ | `max_rows_per_user` (250), `complete_rate` (`{ limit: 30, window: 60 }`) | Composers on the same registry. Over the cap: `422` `experience_state_limit_reached`. Over the rate: `429` `experience_state_rate_limited` with `errors[].details.retry_after_seconds`. |
14
+ | Impersonation | `POST complete` while impersonating returns `403` `experience_state_impersonation_forbidden`. |
15
+ | Boot check | `host_key` set and the registry empty raises at boot in the test environment and logs an error in development and production. |
16
+ | Audit | `experience_state_completed` now has retention `one_year` (was `permanent`) and carries metadata `experience_key` and `version`. See [Audit](../audit.md). |
17
+ | `Services::Account::ExperienceStates::Completed` | Read-only completion check. See [Extending](../extending.md). |
18
+
19
+ `GET /me/experience-states` and the stored rows are unchanged.
20
+
21
+ ## Host actions
22
+
23
+ 1. **Register every key before bumping.** Add `config.registry.experience_states.register` for each key the product (or its client) completes, in the same deploy as the bump or earlier. A client that completes a key the host has not registered gets `422` from the first request after the bump. See [Bootstrap 08](../bootstrap/08-initializer.md#experience-state-keys).
24
+ 2. **Pick'em** must register `welcome` and `competitive_league` before, or in the same deploy as, its gem bump. The enforcing check is pickem-api `spec/requests/api/me/experience_states_spec.rb`.
25
+ 3. Bump gem to `0.26.0` (or `>= 0.26.0`) and run `bundle install`. No `db:migrate` is needed for this release (the `0.25.0` device-sessions migration is separate).
26
+
27
+ ## Local stacks
28
+
29
+ A local stack that path-mounts the gem runs the new code immediately. Until the host initializer registers its keys, its test environment fails at boot (empty registry) and other environments log an error and refuse every complete with `422`. Register the keys first.
30
+
31
+ ## Known residual
32
+
33
+ An impersonating admin is refused on `POST complete`, but `GET /me/experience-states` still returns the impersonated user's facts (read only, as for other `/me` reads).
34
+
35
+ ## Operator recipe: read a user's completed facts
36
+
37
+ Read-only, per user. There is no delete path; a completed fact is undone only by the host choosing a new `version` for the key.
38
+
39
+ ```ruby
40
+ CommandTower::UserExperienceState
41
+ .where(user_id: user.id, host_key: CommandTower.config.application.host_key)
42
+ .order(:completed_at)
43
+ .pluck(:experience_key, :scope_type, :scope_identifier, :version, :completed_at)
44
+ ```
45
+
46
+ Run it from a console or a reporting query. Do not write to the table. First creations are also in the audit ledger as `experience_state_completed` for one year.
47
+
48
+ ## Rolling deploy
49
+
50
+ No schema change, so order only matters for registration: old nodes accept any key, new nodes accept registered keys only. Register keys in the release that bumps the gem.
51
+
52
+ ## Not in this release
53
+
54
+ - No delete or reset endpoint for experience-state facts.
55
+ - No change to authentication, sessions or CSRF.
@@ -4,6 +4,7 @@ Host-facing upgrade / change summaries for CommandTower releases.
4
4
 
5
5
  | Version | Summary |
6
6
  |---------|---------|
7
+ | [0.26.0](0.26.0.md) | Experience-states hardening: host key registry (register before bumping), complete rate limit and per-user cap, refused while impersonating, audit metadata and one-year retention; no migration |
7
8
  | [0.25.0](0.25.0.md) (draft) | Device sessions: `command_tower_device_sessions` migration, `config.session.*`, `sid` token claim, `session_expired` / `session_revoked` 401 codes |
8
9
  | [0.24.0](0.24.0.md) | Home Notices: `Campaign` / `Delivery` notices (blocking or dismissible), `command_tower_home_notices` and `command_tower_home_notice_controls` migrations, `config.home_notices`, `me_home_notices` / `admin_home_notices_kill` RBAC |
9
10
  | [0.23.0](0.23.0.md) | Message definitions: `MessageDefinition` / `AnnouncementDefinition`, composer-built email with compliance footer and one-click unsubscribe, shared email token file, first-view inbox audit, `X-Time-Zone` writer, admin message gallery and test send; `no-store` on inbox reads; one additive migration |
@@ -326,7 +326,7 @@ module CommandTower
326
326
  user_history: false,
327
327
  sensitive_fields: [],
328
328
  allowed_changes: [],
329
- retention: :permanent,
329
+ retention: :one_year,
330
330
  subject_required: false,
331
331
  affected_user_required: true
332
332
  },
@@ -6,6 +6,7 @@ require "command_tower/configuration/registry/admin_workspace/config"
6
6
  require "command_tower/configuration/registry/principal_capabilities/config"
7
7
  require "command_tower/configuration/registry/client_compatibility/config"
8
8
  require "command_tower/configuration/registry/inbox_presentations/config"
9
+ require "command_tower/configuration/registry/experience_states/config"
9
10
 
10
11
  module CommandTower
11
12
  module Configuration
@@ -42,6 +43,12 @@ module CommandTower
42
43
  allowed: InboxPresentations::Config,
43
44
  dynamic_default: ->(_) { InboxPresentations::Config.new },
44
45
  default_shown: "InboxPresentations::Config.new"
46
+
47
+ add_composer :experience_states,
48
+ desc: "Registered experience keys users may complete (host-owned), plus the complete cap and rate limit",
49
+ allowed: ExperienceStates::Config,
50
+ dynamic_default: ->(_) { ExperienceStates::Config.new },
51
+ default_shown: "ExperienceStates::Config.new"
45
52
  end
46
53
  end
47
54
  end
@@ -0,0 +1,134 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "class_composer"
4
+ require "command_tower/experience_states"
5
+ require "command_tower/configuration/registry/experience_states/key_definition"
6
+
7
+ module CommandTower
8
+ module Configuration
9
+ module Registry
10
+ module ExperienceStates
11
+ # No CommandTower-owned keys are seeded. Every registered key is host-owned.
12
+ class Config
13
+ include ClassComposer::Generator
14
+
15
+ MAX_KEY_LENGTH = 128
16
+
17
+ add_composer :max_rows_per_user,
18
+ desc: "Soft cap on completed experience-state rows per user and host_key",
19
+ allowed: Integer,
20
+ default: 250
21
+
22
+ add_composer :complete_rate,
23
+ desc: "Per-user rate limit for the complete endpoint: `limit` requests per `window` seconds",
24
+ allowed: Hash,
25
+ default: { limit: 30, window: 60 }
26
+
27
+ def initialize(*)
28
+ super
29
+ @definitions = {}
30
+ @finalized = false
31
+ end
32
+
33
+ def register(key, scope_types:, owner: :host)
34
+ normalized = normalize_key!(key)
35
+ ensure_registrable!(normalized)
36
+
37
+ @definitions[normalized] = KeyDefinition.new(
38
+ key: normalized,
39
+ scope_types: normalize_scope_types!(scope_types, key: normalized),
40
+ owner: owner.to_sym
41
+ )
42
+ end
43
+
44
+ def fetch(key)
45
+ definition = @definitions[key.to_s]
46
+ if definition.nil?
47
+ raise CommandTower::ExperienceStates::UnregisteredKeyError,
48
+ "experience state is not registered"
49
+ end
50
+
51
+ definition
52
+ end
53
+
54
+ def registered?(key)
55
+ @definitions.key?(key.to_s)
56
+ end
57
+
58
+ def definitions
59
+ @definitions.dup.freeze
60
+ end
61
+
62
+ delegate :empty?, to: :@definitions
63
+
64
+ # Boot check: a host with a `host_key` and no registered keys would reject every
65
+ # completion. Raises in the test environment; logs elsewhere so a boot is never blocked.
66
+ def validate_registered!(host_key:, env: Rails.env)
67
+ return if host_key.to_s.strip.empty? || !empty?
68
+
69
+ message = "experience states registry is empty while application.host_key is set; " \
70
+ "register keys with config.registry.experience_states.register"
71
+ raise CommandTower::ExperienceStates::EmptyRegistryError, message if env.to_s == "test"
72
+
73
+ Rails.logger.error(message)
74
+ end
75
+
76
+ def finalize!
77
+ @definitions.freeze
78
+ @finalized = true
79
+ self
80
+ end
81
+
82
+ def finalized?
83
+ @finalized
84
+ end
85
+
86
+ def reset_host_definitions!
87
+ thaw_for_test!
88
+ @definitions.delete_if { |_key, definition| definition.owner == :host }
89
+ self
90
+ end
91
+
92
+ private
93
+
94
+ def ensure_registrable!(normalized)
95
+ if @finalized
96
+ raise CommandTower::ExperienceStates::FrozenRegistryError,
97
+ "experience states registry is frozen"
98
+ end
99
+ return unless @definitions.key?(normalized)
100
+
101
+ raise CommandTower::ExperienceStates::DuplicateKeyError,
102
+ "experience state #{normalized} is already registered"
103
+ end
104
+
105
+ def thaw_for_test!
106
+ return unless @finalized || @definitions.frozen?
107
+
108
+ @definitions = @definitions.dup
109
+ @finalized = false
110
+ end
111
+
112
+ def normalize_key!(key)
113
+ unless key.is_a?(String) && !key.strip.empty? && key.length <= MAX_KEY_LENGTH
114
+ raise CommandTower::ExperienceStates::InvalidKeyError,
115
+ "experience state key must be a non-blank string of at most #{MAX_KEY_LENGTH} characters"
116
+ end
117
+
118
+ key
119
+ end
120
+
121
+ def normalize_scope_types!(scope_types, key:)
122
+ types = Array(scope_types).map { |type| type.to_s.strip }
123
+ if types.empty? || types.any? { |type| type.empty? || type.length > MAX_KEY_LENGTH }
124
+ raise CommandTower::ExperienceStates::InvalidDefinitionError,
125
+ "experience state #{key} requires at least one valid scope type"
126
+ end
127
+
128
+ types.uniq.freeze
129
+ end
130
+ end
131
+ end
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Configuration
5
+ module Registry
6
+ module ExperienceStates
7
+ # One registered experience key and the scope types it may be completed under.
8
+ KeyDefinition = Struct.new(:key, :scope_types, :owner, keyword_init: true) do
9
+ def scope_type?(scope_type)
10
+ scope_types.include?(scope_type.to_s)
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
@@ -30,6 +30,9 @@ module CommandTower
30
30
  CommandTower::CredentialResolution::SmtpActionMailerBridge.apply!
31
31
  CommandTower.config.registry.client_compatibility.apply_env_overlay!
32
32
  CommandTower::EmailTheme::TokenFile.validate_host_file!
33
+ CommandTower.config.registry.experience_states.validate_registered!(
34
+ host_key: CommandTower.config.application.host_key
35
+ )
33
36
  CommandTower.config.jwt.validate_secret!
34
37
 
35
38
  unless Rails.env.test?
@@ -39,6 +42,7 @@ module CommandTower
39
42
  CommandTower.config.registry.principal_capabilities.finalize!
40
43
  CommandTower.config.registry.client_compatibility.finalize!
41
44
  CommandTower.config.registry.inbox_presentations.finalize!
45
+ CommandTower.config.registry.experience_states.finalize!
42
46
  CommandTower.config.admin_scope.finalize!
43
47
  # Now that we can confirm all variables are defined, freeze all objects an their children
44
48
  CommandTower.config.class_composer_freeze_objects!(behavior: :raise, children: true)
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ # Host-owned registry of the experience keys a host allows users to complete
5
+ # (`POST /me/experience-states/complete`). A key is only accepted when the host
6
+ # registered it, together with the scope types it may be completed under.
7
+ module ExperienceStates
8
+ class Error < CommandTower::Error; end
9
+
10
+ class DuplicateKeyError < Error; end
11
+ class InvalidKeyError < Error; end
12
+ class InvalidDefinitionError < Error; end
13
+ class UnregisteredKeyError < Error; end
14
+ class FrozenRegistryError < Error; end
15
+ class EmptyRegistryError < Error; end
16
+ end
17
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module CommandTower
4
- VERSION = "0.25.0"
4
+ VERSION = "0.26.0"
5
5
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: command_tower
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.25.0
4
+ version: 0.26.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - matt-taylor
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-25 00:00:00.000000000 Z
11
+ date: 2026-11-26 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: phonelib
@@ -306,6 +306,10 @@ files:
306
306
  - app/deserializers/command_tower/deserializers/messaging/inbox.rb
307
307
  - app/deserializers/command_tower/deserializers/messaging/preferences/show_deserializer.rb
308
308
  - app/deserializers/command_tower/deserializers/messaging/preferences/update_deserializer.rb
309
+ - app/errors/command_tower/errors/account/experience_state_impersonation_forbidden.rb
310
+ - app/errors/command_tower/errors/account/experience_state_limit_reached.rb
311
+ - app/errors/command_tower/errors/account/experience_state_rate_limited.rb
312
+ - app/errors/command_tower/errors/account/experience_state_unregistered.rb
309
313
  - app/errors/command_tower/errors/account/experience_states_host_unconfigured_error.rb
310
314
  - app/errors/command_tower/errors/account/phone_already_verified_error.rb
311
315
  - app/errors/command_tower/errors/account/phone_missing_error.rb
@@ -723,7 +727,9 @@ files:
723
727
  - app/services/command_tower/service_base.rb
724
728
  - app/services/command_tower/service_logging.rb
725
729
  - app/services/command_tower/services/account/clear_phone.rb
730
+ - app/services/command_tower/services/account/experience_states/check_complete_rate_limit.rb
726
731
  - app/services/command_tower/services/account/experience_states/complete.rb
732
+ - app/services/command_tower/services/account/experience_states/completed.rb
727
733
  - app/services/command_tower/services/account/experience_states/list.rb
728
734
  - app/services/command_tower/services/account/phone_verification/send.rb
729
735
  - app/services/command_tower/services/account/phone_verification/verify.rb
@@ -1042,6 +1048,7 @@ files:
1042
1048
  - docs/upgrades/0.23.0.md
1043
1049
  - docs/upgrades/0.24.0.md
1044
1050
  - docs/upgrades/0.25.0.md
1051
+ - docs/upgrades/0.26.0.md
1045
1052
  - docs/upgrades/README.md
1046
1053
  - lib/command_tower.rb
1047
1054
  - lib/command_tower/admin_scope.rb
@@ -1112,6 +1119,8 @@ files:
1112
1119
  - lib/command_tower/configuration/registry/client_compatibility/minimum_overrides.rb
1113
1120
  - lib/command_tower/configuration/registry/client_compatibility/platform_definition.rb
1114
1121
  - lib/command_tower/configuration/registry/config.rb
1122
+ - lib/command_tower/configuration/registry/experience_states/config.rb
1123
+ - lib/command_tower/configuration/registry/experience_states/key_definition.rb
1115
1124
  - lib/command_tower/configuration/registry/inbox_presentations/config.rb
1116
1125
  - lib/command_tower/configuration/registry/inbox_presentations/presentation_definition.rb
1117
1126
  - lib/command_tower/configuration/registry/principal_capabilities/capability_definition.rb
@@ -1139,6 +1148,7 @@ files:
1139
1148
  - lib/command_tower/error.rb
1140
1149
  - lib/command_tower/events.rb
1141
1150
  - lib/command_tower/execution.rb
1151
+ - lib/command_tower/experience_states.rb
1142
1152
  - lib/command_tower/impersonation/activity_declaration.rb
1143
1153
  - lib/command_tower/impersonation/apply_overlay.rb
1144
1154
  - lib/command_tower/impersonation/clear_overlay_for_audit.rb