thecore_backend_commons 3.11.0 → 3.13.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e1313e7488ceeae1db673766f1cc21ed36c712b080ab79a8af290571a2b0feab
4
- data.tar.gz: 752a81ca8ffe4334a6496c0f25ba81e6dd4660c38487837d114c07a0fb6796b4
3
+ metadata.gz: 7bd05bf610b8141ce78e757ad18ee1b96b4c1a84c0abefa8c757fe658603509d
4
+ data.tar.gz: ff38f13ba218105c0c79c7e5404bdf0f8355698a5687fe887c09a5e371c91d7f
5
5
  SHA512:
6
- metadata.gz: 0cbc2f2aef141df09a26d98b7574c1642c6ec6bdf7d88fb07ad5bc5e24f3095b1f6a73a6dcfc3d94726bc6bd2aec57ba12f112e4657c9c13e0216d7ff2e5f0fb
7
- data.tar.gz: bd837ed59a16c2e45932fc5d6c3ecf6341f11b55bfeb472261da09a8da45f881e021011f2240353449ed668e65c4b559d8620951f641ba9e438e2da1a0b3da4e
6
+ metadata.gz: 9aee70a9bd8503b6108b2a7b417be59342c2e7effa2cac086a6a7c7aac2a5f1ddf334f671fb3b00a4879a34301e77b1c89568fec96e9ad0c8fcceddc1b1ec051
7
+ data.tar.gz: 521d853a007b71cc1af8dc736a06a497f9927fc5f8e20799c0d5735a1b1133ae1ee3ddadf4acb09878581b46accf0d3a835fbd9a18743daabfd1a2975ff2ab45
data/README.md CHANGED
@@ -2,6 +2,20 @@ This is part of [Thecore framework](https://github.com/gabrieletassoni/thecore/t
2
2
 
3
3
  ---
4
4
 
5
+ ## Real-time messages (Action Cable): guide for frontend developers
6
+
7
+ **[docs/frontend/action-cable.md](docs/frontend/action-cable.md)** is the contract for frontends: how
8
+ to connect to `/cable` with the JWT, `PushNotificationChannel`, `ActivityLogChannel` and the shape of
9
+ each message.
10
+
11
+ Record-change messages (`ActivityLogChannel`, the `messages` room) are **off by default** since
12
+ 3.13.0: an installation turns them on with the setting `action_cable.broadcast_record_changes` =
13
+ `true` (RailsAdmin → Settings). When on, a message says which record changed (`class`, `id`,
14
+ `action`) and whether it succeeded, never the record's data: clients read the data through the REST
15
+ API.
16
+
17
+ ---
18
+
5
19
  ## Web Push notifications (VAPID)
6
20
 
7
21
  Self-contained browser push notifications — no Firebase, no APNs, no third-party account required. The gem provides the server-side half: models, dispatch service, and ActionCable channel. The client integration guide (React + service worker) lives in the [`model_driven_api` README](../model_driven_api/README.md#web-push-vapid-from-a-react-client).
@@ -1,13 +1,21 @@
1
+ # Record-change notifications (ThecoreBackendCommons::ActivityLog). The room exists only when the
2
+ # installation turns broadcasting on: otherwise the subscription is rejected. Frontend contract:
3
+ # docs/frontend/action-cable.md.
1
4
  class ActivityLogChannel < ApplicationCable::Channel
2
5
  def subscribed
3
- stream_from "messages"
6
+ return reject unless ThecoreBackendCommons::ActivityLog.enabled?
7
+
8
+ stream_from ThecoreBackendCommons::ActivityLog::ROOM
4
9
  end
5
10
 
6
11
  def unsubscribed
7
12
  # Any cleanup needed when channel is unsubscribed
8
13
  end
9
14
 
15
+ # Connection check for clients: the answer goes back to the sender only, never to the room.
10
16
  def receive(data)
11
- ActionCable.server.broadcast("messages", {message: "ActionCable is connected and received: #{data["message"]}", topic: data["topic"].presence || "general"}) if data["namespace"] == "subscriptions"
17
+ return unless data["namespace"] == "subscriptions"
18
+
19
+ transmit({ message: "ActionCable is connected and received: #{data["message"]}", topic: data["topic"].presence || "general" })
12
20
  end
13
21
  end
@@ -0,0 +1,6 @@
1
+ # Saving an action_cable setting forgets ActivityLog's cached value in this process at once
2
+ # (ThecoreBackendCommons::ActivityLog::SettingHook). to_prepare re-runs on reload: include once.
3
+ Rails.application.config.to_prepare do
4
+ hook = ThecoreBackendCommons::ActivityLog::SettingHook
5
+ ThecoreSettings::Setting.include(hook) unless ThecoreSettings::Setting.include?(hook)
6
+ end
@@ -44,25 +44,32 @@ module BaseApplicationRecordConcern
44
44
  end
45
45
  end
46
46
 
47
+ # Record-change notifications (ThecoreBackendCommons::ActivityLog): off unless the installation
48
+ # turns them on, and never carrying the record itself.
49
+ # Validation runs before any transaction callback knows the action: a new record is a create,
50
+ # anything else an update (a destroy is never validated).
47
51
  def validation_ko
48
- ActionCable.server.broadcast("messages", build_message(false, false, self.errors.full_messages.uniq)) if self.errors.any? && !is_model_forbidden
52
+ return unless errors.any?
53
+
54
+ broadcast_record_change(action: new_record? ? :create : :update, success: false, valid: false, errors: errors.full_messages.uniq)
49
55
  end
50
56
 
51
57
  def message_ok
52
- ActionCable.server.broadcast("messages", build_message(true, true, [])) unless is_model_forbidden
58
+ broadcast_record_change(action: detect_action, success: true, valid: true, errors: [])
53
59
  end
54
60
 
55
61
  def message_ko
56
- ActionCable.server.broadcast("messages", build_message(false, true, [])) unless is_model_forbidden
62
+ broadcast_record_change(action: detect_action, success: false, valid: true, errors: [])
57
63
  end
58
64
 
59
- def is_model_forbidden
60
- Rails.logger.debug("Checking if model #{self.class.name} is forbidden for ActionCable messages")
61
- ["User", "Role"].include?(self.class.name)
65
+ def broadcast_record_change(**outcome)
66
+ return if broadcast_excluded_model?
67
+
68
+ ThecoreBackendCommons::ActivityLog.broadcast(self, **outcome)
62
69
  end
63
70
 
64
- def build_message(success, valid, errors)
65
- { topic: :record, action: detect_action, class: self.class.name, success: success, valid: valid, errors: errors, record: self }
71
+ def broadcast_excluded_model?
72
+ ["User", "Role"].include?(self.class.name)
66
73
  end
67
74
 
68
75
  def detect_action
@@ -13,9 +13,10 @@ module CableConnectionConcern
13
13
 
14
14
  def find_verified_user
15
15
  # An already-authenticated Devise/Warden session (e.g. RailsAdmin in the browser) is
16
- # trusted as-is, before looking at any token.
17
- warden_user = env["warden"]&.user
18
- return warden_user if warden_user
16
+ # trusted, before looking at any token. Devise throws :warden when it refuses the session's
17
+ # user (a locked one): outside the Warden middleware nobody catches it, so catch it here.
18
+ warden_user = catch(:warden) { env["warden"]&.user }
19
+ return active_or_reject(warden_user) if warden_user.is_a?(User)
19
20
 
20
21
  # Looks for a token in the query parameters, or in the "Authorization" header.
21
22
  m = request.query_parameters["token"].presence ||
@@ -28,21 +29,27 @@ module CableConnectionConcern
28
29
  if User.column_names.include?("encrypted_access_token")
29
30
  m2m_user = User.where.not(encrypted_access_token: nil)
30
31
  .find { |u| BCrypt::Password.new(u.encrypted_access_token) == m } rescue nil
31
- return m2m_user if m2m_user
32
+ return active_or_reject(m2m_user) if m2m_user
32
33
  end
33
34
 
34
35
  # JWT: the signature MUST be verified, exactly like every REST request. Decoding with the
35
36
  # verification disabled (the previous behaviour) let a forged token carrying an arbitrary
36
- # user_id authenticate as any user over the WebSocket — and ActivityLogChannel streams every
37
- # record change, so that was a full read bypass. See docs/adr and the issue tracker.
37
+ # user_id authenticate as any user over the WebSocket. See docs/adr and the issue tracker.
38
38
  body = decode_verified_jwt(m)
39
39
  jwt_user = User.find_by(id: body[:user_id]) if body && body[:user_id]
40
- return jwt_user if jwt_user
40
+ return active_or_reject(jwt_user) if jwt_user
41
41
 
42
42
  # Neither a valid m2m nor a valid JWT token: refuse the connection.
43
43
  reject_unauthorized_connection
44
44
  end
45
45
 
46
+ # A locked user is refused whatever credential they still hold (session, m2m token, JWT):
47
+ # User#active_for_authentication? is the check every login channel uses (thecore_auth_commons
48
+ # >= 3.7.0; Odoo #6051).
49
+ def active_or_reject(user)
50
+ user.active_for_authentication? ? user : reject_unauthorized_connection
51
+ end
52
+
46
53
  # Decodes and VERIFIES a JWT. Reuses model_driven_api's JsonWebToken when present, so the
47
54
  # WebSocket shares the REST API's signing key, key-rotation and single-session handling;
48
55
  # falls back to a signature-verifying decode so this gem still works on its own. Returns nil
data/db/seeds.rb CHANGED
@@ -21,4 +21,9 @@ unless ThecoreSettings::Setting.where(ns: :vapid, key: :public_key).where.not(ra
21
21
  puts " Generated new VAPID key pair"
22
22
  end
23
23
  Thecore::Seed.save_setting :vapid, :contact_email, "" unless ThecoreSettings::Setting.where(ns: :vapid, key: :contact_email).exists?
24
- Thecore::Seed.save_setting :vapid, :max_messages_per_subscriber, "500" unless ThecoreSettings::Setting.where(ns: :vapid, key: :max_messages_per_subscriber).exists?
24
+ Thecore::Seed.save_setting :vapid, :max_messages_per_subscriber, "500" unless ThecoreSettings::Setting.where(ns: :vapid, key: :max_messages_per_subscriber).exists?
25
+ puts "Loading ThecoreBackendCommons Action Cable config"
26
+ # Record-change notifications on the "messages" room (ActivityLogChannel): off unless an admin sets
27
+ # it to "true". save_setting writes only when the value is blank, so an admin's choice survives
28
+ # every deploy. See docs/frontend/action-cable.md.
29
+ Thecore::Seed.save_setting :action_cable, :broadcast_record_changes, "false"
@@ -0,0 +1,78 @@
1
+ module ThecoreBackendCommons
2
+ # Record-change notifications on the "messages" Action Cable room (ActivityLogChannel).
3
+ #
4
+ # Off unless the installation sets the ThecoreSettings value action_cable.broadcast_record_changes
5
+ # to true (seeded "false"). When on, a message says which record changed and how it went, never
6
+ # what it contains: clients that need the data read it through the REST API, where each user's
7
+ # permissions apply. See docs/frontend/action-cable.md.
8
+ module ActivityLog
9
+ ROOM = "messages".freeze
10
+ SETTING_NS = "action_cable".freeze
11
+ SETTING_KEY = "broadcast_record_changes".freeze
12
+ TRUE_VALUES = %w[true 1 yes on].freeze
13
+ # The setting is read at most once per this many seconds per process, so a save never pays a
14
+ # query for it. The process that saves the setting forgets the cached value at once (SettingHook);
15
+ # every other process (web workers, Sidekiq) sees the change within this delay.
16
+ CACHE_SECONDS = 60
17
+
18
+ # Included into ThecoreSettings::Setting (config/initializers/activity_log.rb).
19
+ module SettingHook
20
+ extend ActiveSupport::Concern
21
+
22
+ included do
23
+ after_commit :forget_activity_log_setting, if: -> { ns.to_s == ActivityLog::SETTING_NS }
24
+ end
25
+
26
+ private
27
+
28
+ def forget_activity_log_setting
29
+ ActivityLog.reset!
30
+ end
31
+ end
32
+
33
+ class << self
34
+ def enabled?
35
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
36
+ cached = @cached
37
+ return cached[:value] if cached && now < cached[:expires_at]
38
+
39
+ value = read_setting
40
+ @cached = { value: value, expires_at: now + CACHE_SECONDS }
41
+ value
42
+ end
43
+
44
+ # Forgets the cached setting: the next enabled? reads it again.
45
+ def reset!
46
+ @cached = nil
47
+ end
48
+
49
+ # The only message the room carries for a record change: identity and outcome, no attributes.
50
+ def message(record, action:, success:, valid:, errors:)
51
+ {
52
+ topic: :record,
53
+ action: action,
54
+ class: record.class.name,
55
+ id: record.id,
56
+ success: success,
57
+ valid: valid,
58
+ errors: errors,
59
+ }
60
+ end
61
+
62
+ def broadcast(record, **outcome)
63
+ return unless enabled?
64
+
65
+ ActionCable.server.broadcast(ROOM, message(record, **outcome))
66
+ end
67
+
68
+ private
69
+
70
+ def read_setting
71
+ raw = ThecoreSettings::Setting.where(ns: SETTING_NS, key: SETTING_KEY).pick(:raw)
72
+ TRUE_VALUES.include?(raw.to_s.strip.downcase)
73
+ rescue ActiveRecord::ActiveRecordError
74
+ false
75
+ end
76
+ end
77
+ end
78
+ end
@@ -1,3 +1,3 @@
1
1
  module ThecoreBackendCommons
2
- VERSION = "3.11.0".freeze
2
+ VERSION = "3.13.0".freeze
3
3
  end
@@ -19,6 +19,7 @@ require "thecore_backend_commons/smtp_config"
19
19
  require "thecore_backend_commons/smtp_tester"
20
20
  require "thecore_backend_commons/push_notification_service"
21
21
  require "thecore_backend_commons/default_module_registry"
22
+ require "thecore_backend_commons/activity_log"
22
23
  require "thecore_backend_commons/discarded_job_logger"
23
24
  require "thecore_backend_commons/job_failure_policy"
24
25
 
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: thecore_backend_commons
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.11.0
4
+ version: 3.13.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Gabriele Tassoni
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-24 00:00:00.000000000 Z
11
+ date: 2026-11-30 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: thecore_auth_commons
@@ -16,14 +16,14 @@ dependencies:
16
16
  requirements:
17
17
  - - "~>"
18
18
  - !ruby/object:Gem::Version
19
- version: '3.2'
19
+ version: '3.7'
20
20
  type: :runtime
21
21
  prerelease: false
22
22
  version_requirements: !ruby/object:Gem::Requirement
23
23
  requirements:
24
24
  - - "~>"
25
25
  - !ruby/object:Gem::Version
26
- version: '3.2'
26
+ version: '3.7'
27
27
  - !ruby/object:Gem::Dependency
28
28
  name: thecore_background_jobs
29
29
  requirement: !ruby/object:Gem::Requirement
@@ -230,6 +230,7 @@ files:
230
230
  - app/models/push_message.rb
231
231
  - app/models/push_subscriber.rb
232
232
  - config/initializers/abilities.rb
233
+ - config/initializers/activity_log.rb
233
234
  - config/initializers/add_to_db_migrations.rb
234
235
  - config/initializers/after_initialize.rb
235
236
  - config/initializers/application_config.rb
@@ -254,6 +255,7 @@ files:
254
255
  - db/seeds.rb
255
256
  - lib/tasks/thecore_backend_commons_tasks.rake
256
257
  - lib/thecore_backend_commons.rb
258
+ - lib/thecore_backend_commons/activity_log.rb
257
259
  - lib/thecore_backend_commons/default_module_registry.rb
258
260
  - lib/thecore_backend_commons/discarded_job_logger.rb
259
261
  - lib/thecore_backend_commons/engine.rb