context_drop 0.3.3 → 0.3.5

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 (34) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +74 -1
  3. data/app/assets/javascripts/context_drop/context_drop.js +152 -11
  4. data/app/controllers/context_drop/application_controller.rb +12 -0
  5. data/app/controllers/context_drop/dashboard/feedbacks_controller.rb +38 -0
  6. data/app/controllers/context_drop/dashboard/integrations_controller.rb +140 -0
  7. data/app/controllers/context_drop/feedbacks_controller.rb +38 -14
  8. data/app/controllers/context_drop/mcp_events_controller.rb +66 -0
  9. data/app/helpers/context_drop/dashboard_helper.rb +6 -0
  10. data/app/javascript/context_drop/__tests__/widget.test.ts +229 -18
  11. data/app/javascript/context_drop/styles.ts +16 -0
  12. data/app/javascript/context_drop/widget.ts +136 -11
  13. data/app/models/context_drop/event_occurrence.rb +34 -0
  14. data/app/models/context_drop/mcp_event_subscription.rb +25 -0
  15. data/app/models/context_drop/notification_destination.rb +84 -0
  16. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +8 -10
  17. data/app/views/context_drop/dashboard/integrations/_form.html.erb +92 -0
  18. data/app/views/context_drop/dashboard/integrations/edit.html.erb +13 -0
  19. data/app/views/context_drop/dashboard/integrations/index.html.erb +101 -0
  20. data/app/views/context_drop/dashboard/integrations/new.html.erb +13 -0
  21. data/app/views/layouts/context_drop/application.html.erb +78 -0
  22. data/config/routes.rb +5 -0
  23. data/db/migrate/20261124000001_create_context_drop_events_and_notifications.rb +47 -0
  24. data/lib/context_drop/feedback_events/publisher.rb +100 -0
  25. data/lib/context_drop/mcp/dispatcher.rb +20 -5
  26. data/lib/context_drop/mcp/event_stream_registry.rb +34 -0
  27. data/lib/context_drop/mcp/events.rb +178 -0
  28. data/lib/context_drop/notification_secrets.rb +85 -0
  29. data/lib/context_drop/notifications/deliverer.rb +49 -0
  30. data/lib/context_drop/notifications/lark_client.rb +140 -0
  31. data/lib/context_drop/notifications/webhook_client.rb +103 -0
  32. data/lib/context_drop/version.rb +1 -1
  33. data/lib/context_drop.rb +5 -0
  34. metadata +21 -4
@@ -0,0 +1,13 @@
1
+ <% content_for :cd_breadcrumbs do %>
2
+ <%= link_to "Integrations", dashboard_integrations_path, class: "cd-crumb-link" %>
3
+ <span class="cd-crumb-sep">/</span>
4
+ <span class="cd-crumb-current">New destination</span>
5
+ <% end %>
6
+
7
+ <div class="cd-page-head">
8
+ <h1 class="cd-page-title">Add notification destination</h1>
9
+ </div>
10
+
11
+ <div class="cd-card" style="padding: 1.25rem 1.5rem 1.5rem;">
12
+ <%= render "form" %>
13
+ </div>
@@ -828,6 +828,79 @@
828
828
  }
829
829
  .cd-meta-list dt { color: var(--cd-muted); font-weight: 500; }
830
830
  .cd-meta-list dd { margin: 0; overflow-wrap: anywhere; }
831
+ .cd-page-head {
832
+ display: flex;
833
+ flex-wrap: wrap;
834
+ align-items: flex-start;
835
+ justify-content: space-between;
836
+ gap: 1rem;
837
+ margin-bottom: 1rem;
838
+ }
839
+ .cd-page-title { margin: 0; font-size: 1.35rem; font-weight: 650; letter-spacing: -0.02em; }
840
+ .cd-page-lede { margin: 0.35rem 0 0; color: var(--cd-muted); font-size: 0.875rem; max-width: 52rem; line-height: 1.45; }
841
+ .cd-page-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; }
842
+ .cd-section-title { margin: 0 0 0.35rem; font-size: 0.9375rem; font-weight: 650; }
843
+ .cd-section-hint { margin: 0; color: var(--cd-muted); font-size: 0.8125rem; line-height: 1.45; }
844
+ .cd-inline-code {
845
+ font-family: var(--cd-font-mono);
846
+ font-size: 0.8125rem;
847
+ background: var(--cd-surface-recessed);
848
+ border: 1px solid var(--cd-border-subtle);
849
+ border-radius: 4px;
850
+ padding: 0.1rem 0.35rem;
851
+ }
852
+ .cd-chip-list { display: flex; flex-wrap: wrap; gap: 0.4rem; list-style: none; margin: 0.5rem 0 0; padding: 0; }
853
+ .cd-chip-row { display: flex; flex-wrap: wrap; gap: 0.35rem; }
854
+ .cd-chip {
855
+ display: inline-flex;
856
+ align-items: center;
857
+ font-size: 0.75rem;
858
+ padding: 0.15rem 0.45rem;
859
+ border-radius: 5px;
860
+ border: 1px solid var(--cd-border-subtle);
861
+ background: var(--cd-surface-recessed);
862
+ color: var(--cd-text-secondary);
863
+ }
864
+ .cd-chip-mono { font-family: var(--cd-font-mono); }
865
+ .cd-chip-compact { padding: 0.08rem 0.35rem; }
866
+ .cd-card-inset {
867
+ background: var(--cd-surface-subtle);
868
+ border-style: dashed;
869
+ }
870
+ .cd-form-stack { display: grid; gap: 0.75rem; }
871
+ .cd-form-grid {
872
+ display: grid;
873
+ grid-template-columns: repeat(2, minmax(0, 1fr));
874
+ gap: 0.75rem 1rem;
875
+ }
876
+ .cd-field { display: grid; gap: 0.3rem; font-size: 0.875rem; }
877
+ .cd-field-span { grid-column: 1 / -1; }
878
+ .cd-label { color: var(--cd-muted); font-weight: 500; }
879
+ .cd-check-grid { display: grid; gap: 0.35rem; margin-top: 0.35rem; }
880
+ .cd-check-row { display: inline-flex; align-items: center; gap: 0.45rem; cursor: pointer; }
881
+ .cd-form-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-top: 1.25rem; }
882
+ .cd-btn-compact { padding: 0.25rem 0.55rem; font-size: 0.8125rem; }
883
+ .cd-btn-danger { color: var(--cd-deleted-text); border-color: var(--cd-deleted-border); background: var(--cd-deleted-bg); }
884
+ .cd-btn-row { display: flex; flex-wrap: wrap; gap: 0.35rem; justify-content: flex-end; }
885
+ .cd-break-all { overflow-wrap: anywhere; font-family: var(--cd-font-mono); font-size: 0.75rem; }
886
+ .cd-crumb-link { color: var(--cd-primary); text-decoration: none; font-weight: 500; }
887
+ .cd-crumb-link:hover { text-decoration: underline; }
888
+ .cd-crumb-current { color: var(--cd-muted); font-weight: 500; }
889
+ .cd-header-nav {
890
+ display: inline-flex;
891
+ align-items: center;
892
+ gap: 0.35rem;
893
+ margin-left: 0.75rem;
894
+ font-size: 0.8125rem;
895
+ }
896
+ .cd-header-nav a {
897
+ color: var(--cd-text-secondary);
898
+ text-decoration: none;
899
+ padding: 0.2rem 0.45rem;
900
+ border-radius: 5px;
901
+ }
902
+ .cd-header-nav a:hover { background: var(--cd-surface-recessed); color: var(--cd-text); }
903
+ .cd-header-nav a.active { background: var(--cd-primary-soft); color: var(--cd-primary-hover); font-weight: 600; }
831
904
  </style>
832
905
  </head>
833
906
  <body>
@@ -848,6 +921,11 @@
848
921
  <span class="cd-context-chip" style="font-family: var(--cd-font-mono);"><%= ContextDrop.configuration.resolved_environment %></span>
849
922
  </a>
850
923
 
924
+ <nav class="cd-header-nav" aria-label="Dashboard sections">
925
+ <%= link_to "Feedback", dashboard_feedbacks_path, class: (controller_path == "context_drop/dashboard/feedbacks" ? "active" : nil) %>
926
+ <%= link_to "Integrations", dashboard_integrations_path, class: (controller_path == "context_drop/dashboard/integrations" ? "active" : nil) %>
927
+ </nav>
928
+
851
929
  <% if content_for?(:cd_breadcrumbs) %>
852
930
  <span class="cd-crumb-sep">/</span>
853
931
  <%= yield :cd_breadcrumbs %>
data/config/routes.rb CHANGED
@@ -20,6 +20,7 @@ ContextDrop::Engine.routes.draw do
20
20
  get "feedback/:feedback_id/attachments/:id", to: "feedbacks#attachment"
21
21
  get "health", to: "health#show"
22
22
  post "mcp", to: "mcp#create"
23
+ get "mcp/events/stream", to: "mcp_events#stream"
23
24
 
24
25
  scope "agent" do
25
26
  get "status", to: "agent#status"
@@ -34,8 +35,12 @@ ContextDrop::Engine.routes.draw do
34
35
 
35
36
  namespace :dashboard do
36
37
  root to: "feedbacks#index"
38
+ resources :integrations, only: %i[index new create edit update destroy] do
39
+ post :test_delivery, on: :member
40
+ end
37
41
  resources :feedbacks, only: %i[index show update] do
38
42
  post :comments, on: :member, action: :create_comment
43
+ get "attachments/:attachment_id", on: :member, action: :attachment, as: :attachment
39
44
  end
40
45
  end
41
46
 
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateContextDropEventsAndNotifications < ActiveRecord::Migration[7.1]
4
+ def change
5
+ create_table :context_drop_event_occurrences do |t|
6
+ t.string :event_id, null: false
7
+ t.string :name, null: false
8
+ t.bigint :feedback_id
9
+ t.json :data, null: false, default: {}
10
+ t.datetime :occurred_at, null: false
11
+ t.timestamps
12
+ end
13
+ add_index :context_drop_event_occurrences, :event_id, unique: true
14
+ add_index :context_drop_event_occurrences, %i[name occurred_at id], name: "idx_cd_events_name_time"
15
+ add_index :context_drop_event_occurrences, :feedback_id
16
+
17
+ create_table :context_drop_notification_destinations do |t|
18
+ t.string :name, null: false
19
+ t.boolean :enabled, null: false, default: true
20
+ t.string :destination_type, null: false
21
+ t.json :event_types, null: false, default: []
22
+ t.json :settings, null: false, default: {}
23
+ t.text :secrets_ciphertext
24
+ t.string :last_delivery_status
25
+ t.text :last_delivery_error
26
+ t.datetime :last_delivered_at
27
+ t.timestamps
28
+ end
29
+ add_index :context_drop_notification_destinations, :enabled
30
+ add_index :context_drop_notification_destinations, :destination_type, name: "idx_cd_notif_dest_type"
31
+
32
+ create_table :context_drop_mcp_event_subscriptions do |t|
33
+ t.string :subscription_id, null: false
34
+ t.string :event_name, null: false
35
+ t.json :arguments, null: false, default: {}
36
+ t.string :callback_url, null: false
37
+ t.string :signing_secret, null: false
38
+ t.string :delivery_mode, null: false, default: "webhook"
39
+ t.datetime :expires_at, null: false
40
+ t.string :last_cursor
41
+ t.timestamps
42
+ end
43
+ add_index :context_drop_mcp_event_subscriptions, :subscription_id, unique: true
44
+ add_index :context_drop_mcp_event_subscriptions, :expires_at
45
+ add_index :context_drop_mcp_event_subscriptions, :event_name
46
+ end
47
+ end
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module ContextDrop
6
+ module FeedbackEvents
7
+ class Publisher
8
+ class << self
9
+ def publish(event_name, feedback, **context)
10
+ return unless persistence_ready?
11
+
12
+ data = build_payload(event_name, feedback, context)
13
+ occurrence = ContextDrop::EventOccurrence.create!(
14
+ event_id: stable_event_id(event_name, feedback, data),
15
+ name: event_name,
16
+ feedback_id: feedback.respond_to?(:id) ? feedback.id : nil,
17
+ data: data,
18
+ occurred_at: Time.current
19
+ )
20
+
21
+ deliver_notifications(occurrence)
22
+ deliver_mcp_webhook_subscriptions(occurrence)
23
+ ContextDrop::MCP::EventStreamRegistry.broadcast(occurrence)
24
+ occurrence
25
+ rescue StandardError => e
26
+ log_error("publish", e)
27
+ nil
28
+ end
29
+
30
+ def map_lifecycle_callback(hook_name, feedback, previous_status: nil, dashboard_url: nil)
31
+ ctx = { previous_status: previous_status, dashboard_url: dashboard_url }
32
+ case hook_name
33
+ when :on_feedback_created
34
+ publish("feedback.created", feedback, **ctx)
35
+ when :on_feedback_updated
36
+ if previous_status.present? && previous_status.to_s != feedback.status.to_s
37
+ publish("feedback.status_changed", feedback, **ctx)
38
+ else
39
+ publish("feedback.updated", feedback, **ctx)
40
+ end
41
+ when :on_feedback_deleted
42
+ publish("feedback.deleted", feedback, **ctx)
43
+ end
44
+ end
45
+
46
+ private
47
+
48
+ def persistence_ready?
49
+ defined?(ContextDrop::EventOccurrence) &&
50
+ ContextDrop::EventOccurrence.connection.data_source_exists?("context_drop_event_occurrences")
51
+ end
52
+
53
+ def stable_event_id(event_name, feedback, _data)
54
+ fb_id = feedback.respond_to?(:id) ? feedback.id : "unknown"
55
+ "#{event_name}:#{fb_id}:#{SecureRandom.uuid}"
56
+ end
57
+
58
+ def build_payload(event_name, feedback, context)
59
+ {
60
+ event: event_name,
61
+ feedback_id: feedback.id,
62
+ environment: feedback.respond_to?(:environment_name) ? feedback.environment_name : ContextDrop.config.resolved_environment,
63
+ status: feedback.status,
64
+ previous_status: context[:previous_status],
65
+ message: feedback.message.to_s.truncate(500),
66
+ page_url: feedback.page_url,
67
+ submitter_label: feedback.respond_to?(:submitter_label) ? feedback.submitter_label : nil,
68
+ element_references_count: feedback.respond_to?(:element_references) ? feedback.element_references.size : 0,
69
+ attachments_count: feedback.respond_to?(:attachments) ? feedback.attachments.size : 0,
70
+ created_at: feedback.created_at&.iso8601,
71
+ updated_at: feedback.updated_at&.iso8601,
72
+ deleted_at: (feedback.deleted_at_value&.iso8601 if feedback.respond_to?(:deleted_at_value)),
73
+ dashboard_url: context[:dashboard_url].presence
74
+ }.compact
75
+ end
76
+
77
+ def deliver_notifications(occurrence)
78
+ ContextDrop::Notifications::Deliverer.deliver_for_occurrence(occurrence)
79
+ end
80
+
81
+ def deliver_mcp_webhook_subscriptions(occurrence)
82
+ return unless defined?(ContextDrop::McpEventSubscription)
83
+ return unless ContextDrop::McpEventSubscription.connection.data_source_exists?("context_drop_mcp_event_subscriptions")
84
+
85
+ ContextDrop::McpEventSubscription.active.find_each do |sub|
86
+ next unless sub.matches_occurrence?(occurrence)
87
+
88
+ ContextDrop::Notifications::WebhookClient.deliver_mcp_subscription(sub, occurrence)
89
+ end
90
+ end
91
+
92
+ def log_error(phase, err)
93
+ return unless defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger
94
+
95
+ Rails.logger.error("[ContextDrop::FeedbackEvents] #{phase}: #{err.class}: #{err.message}")
96
+ end
97
+ end
98
+ end
99
+ end
100
+ end
@@ -1,11 +1,14 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
+ require_relative "events"
5
+ require_relative "event_stream_registry"
4
6
 
5
7
  module ContextDrop
6
8
  module MCP
7
9
  class Dispatcher
8
10
  PROTOCOL_VERSION = "2025-03-26"
11
+ EVENTS_PROTOCOL_VERSION = "2026-07-28"
9
12
 
10
13
  TOOLS = {
11
14
  "list_environments" => ContextDrop::MCP::Tools::ListEnvironments,
@@ -85,13 +88,17 @@ module ContextDrop
85
88
  when "initialize"
86
89
  client_version = params["protocolVersion"].to_s.strip
87
90
  negotiated_version = client_version.empty? ? PROTOCOL_VERSION : client_version
91
+ caps = {
92
+ tools: { listChanged: false },
93
+ resources: { subscribe: false, listChanged: false },
94
+ prompts: { listChanged: false },
95
+ extensions: {
96
+ ContextDrop::MCP::Events::EXTENSION_ID => ContextDrop::MCP::Events.capability_payload
97
+ }
98
+ }
88
99
  jsonrpc_result(id, {
89
100
  protocolVersion: negotiated_version,
90
- capabilities: {
91
- tools: { listChanged: false },
92
- resources: { subscribe: false, listChanged: false },
93
- prompts: { listChanged: false }
94
- },
101
+ capabilities: caps,
95
102
  serverInfo: {
96
103
  name: "context_drop",
97
104
  version: ContextDrop::VERSION,
@@ -119,6 +126,14 @@ module ContextDrop
119
126
  })
120
127
  when "prompts/get"
121
128
  handle_prompt_get(id, params)
129
+ when "events/list"
130
+ jsonrpc_result(id, ContextDrop::MCP::Events.list(params))
131
+ when "events/poll"
132
+ jsonrpc_result(id, ContextDrop::MCP::Events.poll(params))
133
+ when "events/subscribe"
134
+ jsonrpc_result(id, ContextDrop::MCP::Events.subscribe(params, request: params["_context_drop_request"]))
135
+ when "events/unsubscribe"
136
+ jsonrpc_result(id, ContextDrop::MCP::Events.unsubscribe(params))
122
137
  else
123
138
  jsonrpc_error(id, -32_601, "Method not found: #{method}")
124
139
  end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "monitor"
4
+
5
+ module ContextDrop
6
+ module MCP
7
+ class EventStreamRegistry
8
+ @mutex = Monitor.new
9
+ @subscribers = []
10
+
11
+ class << self
12
+ def subscribe(queue)
13
+ @mutex.synchronize { @subscribers << queue }
14
+ queue
15
+ end
16
+
17
+ def unsubscribe(queue)
18
+ @mutex.synchronize { @subscribers.delete(queue) }
19
+ end
20
+
21
+ def broadcast(occurrence)
22
+ payload = occurrence.occurrence_payload
23
+ @mutex.synchronize do
24
+ @subscribers.each do |queue|
25
+ queue << payload
26
+ rescue StandardError
27
+ nil
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,178 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "securerandom"
5
+
6
+ module ContextDrop
7
+ module MCP
8
+ module Events
9
+ EXTENSION_ID = "io.modelcontextprotocol/events"
10
+ POLL_DEFAULT_MS = 3_000
11
+ SUBSCRIPTION_TTL_HOURS = 24
12
+
13
+ class << self
14
+ def event_types
15
+ @event_types ||= [
16
+ event_type_entry("feedback.created", "A new ContextDrop feedback submission was persisted."),
17
+ event_type_entry("feedback.updated", "Feedback content or attachments were updated without a status transition."),
18
+ event_type_entry("feedback.status_changed", "Feedback status changed (triage workflow)."),
19
+ event_type_entry("feedback.deleted", "Feedback was soft-deleted.")
20
+ ].freeze
21
+ end
22
+ def capability_payload
23
+ { listChanged: false }
24
+ end
25
+
26
+ def list(_params = {})
27
+ { events: event_types }
28
+ end
29
+
30
+ def poll(params)
31
+ name = params["name"].to_s
32
+ arguments = params["arguments"].is_a?(Hash) ? params["arguments"] : {}
33
+ cursor = params["cursor"]
34
+ env = arguments["environment"].to_s.strip
35
+
36
+ scope = occurrence_scope(name)
37
+ scope = scope.where("context_drop_event_occurrences.id > ?", cursor.to_i) if cursor.present?
38
+
39
+ if env.present? && scope.klass.column_names.include?("data")
40
+ # SQLite JSON filtering via LIKE for portability in tests; AR records filter in Ruby below.
41
+ end
42
+
43
+ records = scope.limit(50).to_a
44
+ if env.present?
45
+ records = records.select do |row|
46
+ row.data.is_a?(Hash) && row.data["environment"].to_s.casecmp?(env)
47
+ end
48
+ end
49
+
50
+ events = records.map(&:occurrence_payload)
51
+ next_cursor = records.last&.cursor
52
+ {
53
+ events: events,
54
+ cursor: next_cursor,
55
+ nextPollMs: POLL_DEFAULT_MS,
56
+ truncated: false
57
+ }
58
+ end
59
+
60
+ def subscribe(params, request: nil)
61
+ ensure_subscription_table!
62
+ name = params["name"].to_s
63
+ arguments = params["arguments"].is_a?(Hash) ? params["arguments"] : {}
64
+ callback_url = params["callbackUrl"].to_s.strip
65
+ ttl_hours = (params["ttlHours"] || SUBSCRIPTION_TTL_HOURS).to_i.clamp(1, 168)
66
+
67
+ raise ContextDrop::Error, "callbackUrl is required" if callback_url.empty?
68
+
69
+ ContextDrop::Notifications::WebhookClient.validate_https_uri!(callback_url)
70
+ signing_secret = SecureRandom.hex(32)
71
+ subscription = ContextDrop::McpEventSubscription.create!(
72
+ subscription_id: SecureRandom.uuid,
73
+ event_name: name,
74
+ arguments: arguments,
75
+ callback_url: callback_url,
76
+ signing_secret: signing_secret,
77
+ delivery_mode: "webhook",
78
+ expires_at: ttl_hours.hours.from_now
79
+ )
80
+
81
+ verification_token = nil
82
+ if request
83
+ verification_token = perform_callback_verification(request, subscription, signing_secret)
84
+ end
85
+
86
+ {
87
+ subscriptionId: subscription.subscription_id,
88
+ expiresAt: subscription.expires_at.iso8601,
89
+ signingSecret: signing_secret,
90
+ verificationChallenge: verification_token
91
+ }
92
+ end
93
+
94
+ def unsubscribe(params)
95
+ ensure_subscription_table!
96
+ sub_id = params["subscriptionId"].to_s.strip
97
+ sub = ContextDrop::McpEventSubscription.find_by(subscription_id: sub_id)
98
+ sub&.destroy
99
+ { removed: !sub.nil? }
100
+ end
101
+
102
+ private
103
+
104
+ def occurrence_scope(name)
105
+ ensure_occurrence_table!
106
+ scope = ContextDrop::EventOccurrence.chronological
107
+ scope = scope.named(name) if name.present?
108
+ scope
109
+ end
110
+
111
+ def ensure_occurrence_table!
112
+ return if ContextDrop::EventOccurrence.connection.data_source_exists?("context_drop_event_occurrences")
113
+
114
+ raise ContextDrop::Error, "ContextDrop events persistence is not installed (run engine migrations)"
115
+ end
116
+
117
+ def ensure_subscription_table!
118
+ return if ContextDrop::McpEventSubscription.connection.data_source_exists?("context_drop_mcp_event_subscriptions")
119
+
120
+ raise ContextDrop::Error, "ContextDrop MCP webhook subscriptions are not installed (run engine migrations)"
121
+ end
122
+
123
+ def perform_callback_verification(_request, subscription, signing_secret)
124
+ challenge = SecureRandom.hex(16)
125
+ occurrence = ContextDrop::EventOccurrence.new(
126
+ event_id: "verification:#{subscription.subscription_id}",
127
+ name: subscription.event_name,
128
+ data: { "verification" => true, "challenge" => challenge },
129
+ occurred_at: Time.current
130
+ )
131
+ ContextDrop::Notifications::WebhookClient.deliver_mcp_subscription(subscription, occurrence)
132
+ challenge
133
+ rescue StandardError
134
+ nil
135
+ end
136
+
137
+ def event_type_entry(name, description)
138
+ {
139
+ name: name,
140
+ description: description,
141
+ inputSchema: environment_filter_schema,
142
+ payloadSchema: feedback_payload_schema,
143
+ delivery: %w[poll push webhook]
144
+ }
145
+ end
146
+
147
+ def environment_filter_schema
148
+ {
149
+ type: "object",
150
+ properties: {
151
+ environment: {
152
+ type: "string",
153
+ description: "Optional ContextDrop environment filter (e.g. staging, production)."
154
+ }
155
+ },
156
+ additionalProperties: false
157
+ }
158
+ end
159
+
160
+ def feedback_payload_schema
161
+ {
162
+ type: "object",
163
+ properties: {
164
+ feedback_id: { type: "integer" },
165
+ environment: { type: "string" },
166
+ status: { type: "string" },
167
+ previous_status: { type: %w[string null] },
168
+ message: { type: "string" },
169
+ page_url: { type: "string" },
170
+ dashboard_url: { type: "string" }
171
+ },
172
+ required: %w[feedback_id environment status page_url]
173
+ }
174
+ end
175
+ end
176
+ end
177
+ end
178
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "openssl"
5
+ require "securerandom"
6
+ require "fileutils"
7
+ require "digest"
8
+ require_relative "../context_drop/base64_util"
9
+
10
+ module ContextDrop
11
+ class NotificationSecrets
12
+ CIPHER_NAME = "aes-256-gcm"
13
+
14
+ class << self
15
+ def encrypt(hash)
16
+ return nil if hash.nil? || hash.empty?
17
+
18
+ cipher = OpenSSL::Cipher.new(CIPHER_NAME)
19
+ cipher.encrypt
20
+ cipher.key = master_key
21
+ iv = cipher.random_iv
22
+ cipher.auth_data = ""
23
+ ciphertext = cipher.update(JSON.generate(hash)) + cipher.final
24
+ tag = cipher.auth_tag
25
+ {
26
+ "v" => 1,
27
+ "iv" => ContextDrop::Base64Util.strict_encode64(iv),
28
+ "tag" => ContextDrop::Base64Util.strict_encode64(tag),
29
+ "ciphertext" => ContextDrop::Base64Util.strict_encode64(ciphertext)
30
+ }
31
+ end
32
+
33
+ def decrypt(blob)
34
+ return {} if blob.nil? || blob.empty?
35
+ return blob if blob.is_a?(Hash) && blob["ciphertext"].nil?
36
+
37
+ payload = blob.is_a?(Hash) ? blob : JSON.parse(blob.to_s)
38
+ cipher = OpenSSL::Cipher.new(CIPHER_NAME)
39
+ cipher.decrypt
40
+ cipher.key = master_key
41
+ cipher.iv = ContextDrop::Base64Util.strict_decode64(payload["iv"].to_s)
42
+ cipher.auth_tag = ContextDrop::Base64Util.strict_decode64(payload["tag"].to_s)
43
+ cipher.auth_data = ""
44
+ JSON.parse(cipher.update(ContextDrop::Base64Util.strict_decode64(payload["ciphertext"].to_s)) + cipher.final)
45
+ rescue StandardError
46
+ {}
47
+ end
48
+
49
+ def mask_secret(raw)
50
+ str = raw.to_s.strip
51
+ return nil if str.empty?
52
+ return "••••••••" if str.length <= 6
53
+
54
+ "••••#{str[-4, 4]}"
55
+ end
56
+
57
+ private
58
+
59
+ def master_key
60
+ explicit = ContextDrop.config.ownership_secret.to_s.strip
61
+ return Digest::SHA256.digest(explicit) if explicit.bytesize >= 16
62
+
63
+ path = resolved_master_key_path
64
+ if File.exist?(path)
65
+ raw = File.binread(path)
66
+ return raw if raw.bytesize == 32
67
+ end
68
+
69
+ FileUtils.mkdir_p(File.dirname(path))
70
+ raw = SecureRandom.random_bytes(32)
71
+ File.binwrite(path, raw)
72
+ raw
73
+ end
74
+
75
+ def resolved_master_key_path
76
+ root = if defined?(Rails) && Rails.respond_to?(:root) && Rails.root
77
+ Rails.root.to_s
78
+ else
79
+ Dir.pwd
80
+ end
81
+ File.join(root, "tmp", "context_drop_notification.key")
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContextDrop
4
+ module Notifications
5
+ class Deliverer
6
+ class << self
7
+ def deliver_for_occurrence(occurrence)
8
+ return unless destinations_ready?
9
+
10
+ ContextDrop::NotificationDestination.enabled.find_each do |destination|
11
+ next unless destination.subscribed_to?(occurrence.name)
12
+
13
+ deliver_destination(destination, occurrence)
14
+ end
15
+ end
16
+
17
+ def deliver_destination(destination, occurrence)
18
+ case destination.destination_type
19
+ when "lark"
20
+ LarkClient.deliver(destination, occurrence)
21
+ when "webhook"
22
+ WebhookClient.deliver_destination(destination, occurrence)
23
+ else
24
+ raise LarkClient::DeliveryError, "Unknown destination type #{destination.destination_type}"
25
+ end
26
+ destination.record_delivery!(status: "delivered")
27
+ rescue StandardError => e
28
+ destination.record_delivery!(status: "failed", error: e.message)
29
+ log_error(destination, e)
30
+ end
31
+
32
+ private
33
+
34
+ def destinations_ready?
35
+ defined?(ContextDrop::NotificationDestination) &&
36
+ ContextDrop::NotificationDestination.connection.data_source_exists?("context_drop_notification_destinations")
37
+ end
38
+
39
+ def log_error(destination, err)
40
+ return unless defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger
41
+
42
+ Rails.logger.warn(
43
+ "[ContextDrop::Notifications] destination ##{destination.id} #{destination.name}: #{err.class}: #{err.message}"
44
+ )
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end