context_drop 0.3.4 → 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 (30) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +74 -1
  3. data/app/controllers/context_drop/application_controller.rb +12 -0
  4. data/app/controllers/context_drop/dashboard/feedbacks_controller.rb +38 -0
  5. data/app/controllers/context_drop/dashboard/integrations_controller.rb +140 -0
  6. data/app/controllers/context_drop/feedbacks_controller.rb +38 -14
  7. data/app/controllers/context_drop/mcp_events_controller.rb +66 -0
  8. data/app/helpers/context_drop/dashboard_helper.rb +6 -0
  9. data/app/models/context_drop/event_occurrence.rb +34 -0
  10. data/app/models/context_drop/mcp_event_subscription.rb +25 -0
  11. data/app/models/context_drop/notification_destination.rb +84 -0
  12. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +8 -10
  13. data/app/views/context_drop/dashboard/integrations/_form.html.erb +92 -0
  14. data/app/views/context_drop/dashboard/integrations/edit.html.erb +13 -0
  15. data/app/views/context_drop/dashboard/integrations/index.html.erb +101 -0
  16. data/app/views/context_drop/dashboard/integrations/new.html.erb +13 -0
  17. data/app/views/layouts/context_drop/application.html.erb +78 -0
  18. data/config/routes.rb +5 -0
  19. data/db/migrate/20261124000001_create_context_drop_events_and_notifications.rb +47 -0
  20. data/lib/context_drop/feedback_events/publisher.rb +100 -0
  21. data/lib/context_drop/mcp/dispatcher.rb +20 -5
  22. data/lib/context_drop/mcp/event_stream_registry.rb +34 -0
  23. data/lib/context_drop/mcp/events.rb +178 -0
  24. data/lib/context_drop/notification_secrets.rb +85 -0
  25. data/lib/context_drop/notifications/deliverer.rb +49 -0
  26. data/lib/context_drop/notifications/lark_client.rb +140 -0
  27. data/lib/context_drop/notifications/webhook_client.rb +103 -0
  28. data/lib/context_drop/version.rb +1 -1
  29. data/lib/context_drop.rb +5 -0
  30. metadata +21 -4
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: bafb19959bf7ef41bfd4825d64d21ef117a9bf2f3828a70f6d90d4f154fc838c
4
- data.tar.gz: 9c9daf6ea6de9189b7b064f37e84cd3f4b89abdd47f005dfa3bc40a4b01c98a9
3
+ metadata.gz: 2e667b7c0a99e4f141d1f5b1a4418570ca0ff9879725d067d57ae775e972faae
4
+ data.tar.gz: a24283e1c5812b17eb46f4a5c65ced33d815cf21cd73cf1fde438bfb318e36d8
5
5
  SHA512:
6
- metadata.gz: 392551e1428b9ffb7f2a506a193fe9a5827ebd055d39568a2a17ec8e09e9d61b5a40a2fc2f8572aa2557b3c0af9a41116b57ccecd39262c15ae6e7d54ab4edd5
7
- data.tar.gz: d8ac287732bd6d58657a7ad5a05157e319fd856c1dfca8703938edff58e4914bb453ba95b8db0dcae0f443a084aa8422f3fb99f6bbd69111e430db0408176ff3
6
+ metadata.gz: 1dd43b47aa0367f25767e149f9028ce81986597ae30f41bae280d8bd9b98328bc6dc3c1b53197c03d969ec82dc47bdb740a9b83579331e5a3bea605c965c6374
7
+ data.tar.gz: 88d3a00c38b2e988376a5a7231b0e59fdaf57459c87f3ceb9d7f8a0515f69e1ef0d63c42afb8e24703ae6f9b8d27b57aa8addb82342b5da42babe2749852b0b7
data/README.md CHANGED
@@ -266,7 +266,7 @@ Already running `ContextDrop::Engine` on Rails? Point `<ContextDrop />` at your
266
266
 
267
267
  ### Requirements
268
268
 
269
- - **Ruby** `>= 3.1`
269
+ - **Ruby** `>= 3.3.14` (`3.3.14+`, `3.4.13+`, or `4.0.10+` to address [CVE-2026-132825](https://www.ruby-lang.org/en/news/2026/11/18/multiple-vulnerabilities-in-regexp-and-string/))
270
270
  - **Ruby on Rails** `>= 7.1` (`7.1`, `7.2`, `8.0+`)
271
271
  - **Active Storage** installed in the host application (`bin/rails active_storage:install`)
272
272
 
@@ -440,6 +440,79 @@ ContextDrop ships with a built-in **Model Context Protocol (MCP)** server (`Cont
440
440
  | **Resource** | `contextdrop://feedbacks/{id}` | Full JSON snapshot of a specific feedback submission, its pinned elements, and attachment metadata. |
441
441
  | **Prompt** | `investigate_feedback` | Generates a structured root-cause investigation brief (with attached screenshots) for any local or remote `feedback_id` (`"staging:18"`). |
442
442
 
443
+ ### MCP Events, Webhooks & Lark (v0.3+)
444
+
445
+ ContextDrop implements the official MCP **Events** extension ([overview](https://modelcontextprotocol.io/extensions/events/overview)) so agents can react to feedback without constant tool polling.
446
+
447
+ | Delivery | Rails | `@context-drop` (Next.js / Node) |
448
+ |---|---|---|
449
+ | **Poll** | `events/poll` via `POST /context_drop/mcp` | `events/poll` via `POST …/mcp` |
450
+ | **Push (SSE)** | `GET /context_drop/mcp/events/stream` | `GET …/mcp/events/stream` |
451
+ | **Webhook** | `events/subscribe` (signed HTTPS callbacks) | Same |
452
+
453
+ **Lifecycle event types:** `feedback.created`, `feedback.updated`, `feedback.status_changed`, `feedback.deleted`.
454
+
455
+ **Rails — configure destinations in the dashboard**
456
+
457
+ 1. Run `bin/rails db:migrate` (includes event/notification tables).
458
+ 2. Open **`/context_drop/dashboard/integrations`** (header: **Integrations**).
459
+ 3. Add **Lark** (App ID, App Secret, `chat_id` / `receive_id`) or **HTTPS webhook** (callback URL + optional signing secret). Credentials are encrypted at rest. Use **Test** to verify delivery.
460
+
461
+ **Lark:** Create a custom app with Bot + `im:chat` / `im:message`, add the bot to your triage group, copy `chat_id` from the [API Explorer](https://open.larksuite.com/api-explorer) or group settings ([message card guide](https://open.larksuite.com/document/)).
462
+
463
+ **Standalone Node / Next.js — REST integrations API**
464
+
465
+ When you deploy with `createContextDropNextHandler` / `createContextDropPagesHandler`, destinations are stored under `<CONTEXT_DROP_STORAGE_DIR>/events-state.json`:
466
+
467
+ ```bash
468
+ curl -sS -X POST "https://your-app.com/api/context-drop/integrations/destinations" \
469
+ -H "Authorization: Bearer $CONTEXT_DROP_INTEGRATIONS_API_KEY" \
470
+ -H "Content-Type: application/json" \
471
+ -d '{
472
+ "name": "Lark triage",
473
+ "destination_type": "lark",
474
+ "event_types": ["feedback.created"],
475
+ "settings": { "receive_id": "oc_xxx", "receive_id_type": "chat_id" },
476
+ "secrets": { "app_id": "cli_xxx", "app_secret": "..." }
477
+ }'
478
+ ```
479
+
480
+ Defaults: authorize with `CONTEXT_DROP_INTEGRATIONS_API_KEY` (or the MCP API key); disable the pipeline with `notifications: { enabled: false }` in handler config.
481
+
482
+ **Example MCP client calls**
483
+
484
+ ```json
485
+ { "jsonrpc": "2.0", "id": 1, "method": "events/list" }
486
+ ```
487
+
488
+ ```json
489
+ {
490
+ "jsonrpc": "2.0",
491
+ "id": 2,
492
+ "method": "events/poll",
493
+ "params": {
494
+ "name": "feedback.created",
495
+ "arguments": { "environment": "production" },
496
+ "cursor": null
497
+ }
498
+ }
499
+ ```
500
+
501
+ ```json
502
+ {
503
+ "jsonrpc": "2.0",
504
+ "id": 3,
505
+ "method": "events/subscribe",
506
+ "params": {
507
+ "name": "feedback.created",
508
+ "callbackUrl": "https://agent.example/hooks/contextdrop",
509
+ "ttlHours": 24
510
+ }
511
+ }
512
+ ```
513
+
514
+ `npx context-drop mcp` stdio sessions use the same `events/*` methods and persist occurrences in `.context-drop/` alongside feedback storage.
515
+
443
516
  ---
444
517
 
445
518
  ### Recommended Setup: One Unified MCP Server for All Environments (`local` + `staging` + `production`)
@@ -159,5 +159,17 @@ module ContextDrop
159
159
  request.headers["X-Context-Drop-Ownership-Token"].to_s.strip.present? ||
160
160
  request.content_type.to_s.downcase.start_with?("application/json")
161
161
  end
162
+
163
+ def stream_context_drop_attachment!(attachment)
164
+ return false unless attachment.respond_to?(:file) && attachment.file.attached?
165
+
166
+ response.set_header("Cache-Control", "private, max-age=3600")
167
+ response.set_header("Content-Security-Policy", "default-src 'none'; sandbox")
168
+ send_data attachment.file.download,
169
+ type: attachment.file.content_type || "image/png",
170
+ disposition: "inline",
171
+ filename: attachment.file.filename.to_s
172
+ true
173
+ end
162
174
  end
163
175
  end
@@ -101,7 +101,14 @@ module ContextDrop
101
101
  return
102
102
  end
103
103
 
104
+ previous_status = @feedback.status
104
105
  @feedback.update!(status: next_status)
106
+ invoke_lifecycle_callback(
107
+ :on_feedback_updated,
108
+ @feedback,
109
+ previous_status: previous_status,
110
+ dashboard_url: dashboard_feedback_url(@feedback)
111
+ )
105
112
 
106
113
  respond_to do |format|
107
114
  format.json do
@@ -117,6 +124,17 @@ module ContextDrop
117
124
  end
118
125
  end
119
126
 
127
+ def attachment
128
+ @feedback = ContextDrop::Feedback.find_by(id: params[:id])
129
+ if @feedback.nil?
130
+ head :not_found
131
+ return
132
+ end
133
+
134
+ att = ContextDrop::Attachment.where(feedback_id: @feedback.id).find_by(id: params[:attachment_id])
135
+ head(:not_found) unless att && stream_context_drop_attachment!(att)
136
+ end
137
+
120
138
  def create_comment
121
139
  @feedback = ContextDrop::Feedback.find(params[:id])
122
140
  body = (params[:body] || params.dig(:comment, :body)).to_s.strip.presence
@@ -198,6 +216,26 @@ module ContextDrop
198
216
 
199
217
  private
200
218
 
219
+ def invoke_lifecycle_callback(hook_name, feedback, **context)
220
+ return unless ContextDrop.config.respond_to?(hook_name)
221
+
222
+ callback = ContextDrop.config.public_send(hook_name)
223
+ callback.call(feedback) if callback.respond_to?(:call)
224
+ ContextDrop::FeedbackEvents::Publisher.map_lifecycle_callback(
225
+ hook_name,
226
+ feedback,
227
+ **context
228
+ )
229
+ rescue StandardError => e
230
+ Rails.logger.error("[ContextDrop] #{hook_name} callback error: #{e.class}: #{e.message}") if defined?(Rails.logger) && Rails.logger
231
+ end
232
+
233
+ def dashboard_feedback_url(feedback)
234
+ url_for(controller: "context_drop/dashboard/feedbacks", action: :show, id: feedback.id, only_path: false)
235
+ rescue StandardError
236
+ "/context_drop/dashboard/feedbacks/#{feedback.id}"
237
+ end
238
+
201
239
  def enforce_dashboard_authorization!
202
240
  return if ContextDrop.config.dashboard_authorized?(self)
203
241
 
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module ContextDrop
6
+ module Dashboard
7
+ class IntegrationsController < ApplicationController
8
+ layout "context_drop/application"
9
+ helper ContextDrop::DashboardHelper
10
+
11
+ before_action :enforce_dashboard_authorization!
12
+ before_action :ensure_tables!
13
+ before_action :set_destination, only: %i[edit update destroy test_delivery]
14
+
15
+ PERMITTED_EVENTS = ContextDrop::EventOccurrence::EVENT_NAMES
16
+
17
+ def index
18
+ @destinations = ContextDrop::NotificationDestination.order(created_at: :desc)
19
+ @mcp_subscriptions = if subscription_table?
20
+ ContextDrop::McpEventSubscription.active.order(expires_at: :asc).limit(20)
21
+ else
22
+ []
23
+ end
24
+ end
25
+
26
+ def new
27
+ @destination = ContextDrop::NotificationDestination.new(
28
+ enabled: true,
29
+ destination_type: params[:destination_type].presence || "lark",
30
+ event_types: ["feedback.created"]
31
+ )
32
+ end
33
+
34
+ def create
35
+ @destination = ContextDrop::NotificationDestination.new(destination_params)
36
+ apply_secret_params!(@destination)
37
+ if @destination.save
38
+ redirect_to dashboard_integrations_path, notice: "Notification destination \"#{@destination.name}\" created."
39
+ else
40
+ render :new, status: :unprocessable_entity
41
+ end
42
+ end
43
+
44
+ def edit; end
45
+
46
+ def update
47
+ @destination.assign_attributes(destination_params)
48
+ apply_secret_params!(@destination)
49
+ if @destination.save
50
+ redirect_to dashboard_integrations_path, notice: "Saved \"#{@destination.name}\"."
51
+ else
52
+ render :edit, status: :unprocessable_entity
53
+ end
54
+ end
55
+
56
+ def destroy
57
+ name = @destination.name
58
+ @destination.destroy
59
+ redirect_to dashboard_integrations_path, notice: "Removed \"#{name}\"."
60
+ end
61
+
62
+ def test_delivery
63
+ occurrence = ContextDrop::EventOccurrence.new(
64
+ event_id: "test:#{SecureRandom.uuid}",
65
+ name: (@destination.event_types.first || "feedback.created"),
66
+ data: {
67
+ "feedback_id" => 0,
68
+ "environment" => ContextDrop.config.resolved_environment,
69
+ "status" => "new",
70
+ "message" => "Test notification from ContextDrop dashboard.",
71
+ "page_url" => "/",
72
+ "dashboard_url" => dashboard_integrations_url(only_path: false)
73
+ },
74
+ occurred_at: Time.current
75
+ )
76
+ ContextDrop::Notifications::Deliverer.deliver_destination(@destination, occurrence)
77
+ @destination.reload
78
+ if @destination.last_delivery_status == "delivered"
79
+ redirect_to dashboard_integrations_path, notice: "Test notification delivered for \"#{@destination.name}\"."
80
+ else
81
+ redirect_to dashboard_integrations_path,
82
+ alert: "Test failed: #{@destination.last_delivery_error.presence || 'unknown error'}"
83
+ end
84
+ rescue StandardError => e
85
+ redirect_to dashboard_integrations_path, alert: "Test failed: #{e.message}"
86
+ end
87
+
88
+ private
89
+
90
+ def set_destination
91
+ @destination = ContextDrop::NotificationDestination.find(params[:id])
92
+ end
93
+
94
+ def destination_params
95
+ raw = params.require(:notification_destination)
96
+ permitted = raw.permit(
97
+ :name,
98
+ :enabled,
99
+ :destination_type,
100
+ event_types: [],
101
+ settings: %i[url receive_id receive_id_type api_host]
102
+ )
103
+ permitted[:event_types] = Array(permitted[:event_types]).map(&:to_s).select do |ev|
104
+ PERMITTED_EVENTS.include?(ev)
105
+ end
106
+ permitted[:settings] = (permitted[:settings] || {}).to_h.compact_blank
107
+ permitted
108
+ end
109
+
110
+ def apply_secret_params!(destination)
111
+ raw = params[:notification_destination] || {}
112
+ secrets = {}
113
+ case destination.destination_type
114
+ when "lark"
115
+ secrets["app_id"] = raw[:app_id].to_s.strip if raw[:app_id].present?
116
+ secrets["app_secret"] = raw[:app_secret].to_s.strip if raw[:app_secret].present?
117
+ when "webhook"
118
+ secrets["signing_secret"] = raw[:signing_secret].to_s.strip if raw[:signing_secret].present?
119
+ end
120
+ destination.merge_secrets!(secrets) if secrets.any?
121
+ end
122
+
123
+ def enforce_dashboard_authorization!
124
+ return if ContextDrop.config.dashboard_authorized?(self)
125
+
126
+ render plain: "403 Forbidden — Not authorized to configure integrations", status: :forbidden
127
+ end
128
+
129
+ def ensure_tables!
130
+ return if ContextDrop::NotificationDestination.connection.data_source_exists?("context_drop_notification_destinations")
131
+
132
+ render plain: "Run ContextDrop engine migrations to enable integrations.", status: :service_unavailable
133
+ end
134
+
135
+ def subscription_table?
136
+ ContextDrop::McpEventSubscription.connection.data_source_exists?("context_drop_mcp_event_subscriptions")
137
+ end
138
+ end
139
+ end
140
+ end
@@ -54,6 +54,7 @@ module ContextDrop
54
54
  end
55
55
 
56
56
  feedback = nil
57
+ previous_status = nil
57
58
 
58
59
  ContextDrop::Feedback.transaction do
59
60
  sanitized_meta = ContextDrop::MetadataSanitizer.sanitize_feedback_metadata(payload["metadata"])
@@ -126,7 +127,11 @@ module ContextDrop
126
127
  return if performed?
127
128
 
128
129
  feedback.reload
129
- invoke_lifecycle_callback(:on_feedback_created, feedback)
130
+ invoke_lifecycle_callback(
131
+ :on_feedback_created,
132
+ feedback,
133
+ dashboard_url: feedback_dashboard_url(feedback)
134
+ )
130
135
  ownership_token = ContextDrop::OwnershipToken.generate(feedback.id)
131
136
 
132
137
  render json: {
@@ -144,6 +149,7 @@ module ContextDrop
144
149
 
145
150
  def update
146
151
  feedback = ContextDrop::Feedback.includes(:element_references, :attachments, comments: :attachments).find_by(id: params[:id])
152
+ previous_status = feedback&.status
147
153
  if feedback.nil? || feedback.deleted?
148
154
  render json: { error: "Feedback not found" }, status: :not_found
149
155
  return
@@ -323,7 +329,12 @@ module ContextDrop
323
329
  return if performed?
324
330
 
325
331
  feedback.reload
326
- invoke_lifecycle_callback(:on_feedback_updated, feedback)
332
+ invoke_lifecycle_callback(
333
+ :on_feedback_updated,
334
+ feedback,
335
+ previous_status: previous_status,
336
+ dashboard_url: feedback_dashboard_url(feedback)
337
+ )
327
338
 
328
339
  raw_tokens = combined_raw_ownership_tokens(payload["ownership_token"])
329
340
  ownership_token = ContextDrop::OwnershipToken.find_token_for(raw_tokens, feedback.id) ||
@@ -357,7 +368,11 @@ module ContextDrop
357
368
  end
358
369
 
359
370
  feedback.soft_delete!
360
- invoke_lifecycle_callback(:on_feedback_deleted, feedback)
371
+ invoke_lifecycle_callback(
372
+ :on_feedback_deleted,
373
+ feedback,
374
+ dashboard_url: feedback_dashboard_url(feedback)
375
+ )
361
376
 
362
377
  render json: {
363
378
  id: feedback.id,
@@ -387,6 +402,8 @@ module ContextDrop
387
402
  return
388
403
  end
389
404
 
405
+ previous_status = feedback.status
406
+
390
407
  submitter = current_context_drop_submitter
391
408
  author_label = if submitter
392
409
  if submitter.respond_to?(:name) && submitter.name.present?
@@ -451,7 +468,12 @@ module ContextDrop
451
468
  return if performed?
452
469
 
453
470
  feedback.reload
454
- invoke_lifecycle_callback(:on_feedback_updated, feedback)
471
+ invoke_lifecycle_callback(
472
+ :on_feedback_updated,
473
+ feedback,
474
+ previous_status: previous_status,
475
+ dashboard_url: feedback_dashboard_url(feedback)
476
+ )
455
477
 
456
478
  raw_tokens = combined_raw_ownership_tokens(payload["ownership_token"])
457
479
  ownership_token = ContextDrop::OwnershipToken.find_token_for(raw_tokens, feedback.id) ||
@@ -480,17 +502,9 @@ module ContextDrop
480
502
  end
481
503
 
482
504
  att = ContextDrop::Attachment.where(feedback_id: feedback.id).find_by(id: params[:id])
483
- if att.nil? || !att.respond_to?(:file) || !att.file.attached?
505
+ if att.nil? || !stream_context_drop_attachment!(att)
484
506
  head :not_found
485
- return
486
507
  end
487
-
488
- response.set_header("Cache-Control", "private, max-age=3600")
489
- response.set_header("Content-Security-Policy", "default-src 'none'; sandbox")
490
- send_data att.file.download,
491
- type: att.file.content_type || "image/png",
492
- disposition: "inline",
493
- filename: att.file.filename.to_s
494
508
  end
495
509
 
496
510
  private
@@ -715,15 +729,25 @@ module ContextDrop
715
729
  raise ContextDrop::UploadValidator::ValidationError, "Invalid base64 attachment data"
716
730
  end
717
731
 
718
- def invoke_lifecycle_callback(hook_name, feedback)
732
+ def invoke_lifecycle_callback(hook_name, feedback, **context)
719
733
  return unless ContextDrop.config.respond_to?(hook_name)
720
734
 
721
735
  callback = ContextDrop.config.public_send(hook_name)
722
736
  callback.call(feedback) if callback.respond_to?(:call)
737
+ ContextDrop::FeedbackEvents::Publisher.map_lifecycle_callback(hook_name, feedback, **context)
723
738
  rescue StandardError => e
724
739
  Rails.logger.error("[ContextDrop] #{hook_name} callback error: #{e.class}: #{e.message}") if defined?(Rails.logger) && Rails.logger
725
740
  end
726
741
 
742
+ def feedback_dashboard_url(feedback)
743
+ path = "/context_drop/dashboard/feedbacks/#{feedback.id}"
744
+ if respond_to?(:request) && request&.base_url.present?
745
+ "#{request.base_url}#{path}"
746
+ else
747
+ path
748
+ end
749
+ end
750
+
727
751
  def stringify_hash(obj)
728
752
  if obj.respond_to?(:to_unsafe_h)
729
753
  obj.to_unsafe_h.transform_keys(&:to_s)
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module ContextDrop
6
+ class McpEventsController < ApplicationController
7
+ skip_before_action :verify_authenticity_token
8
+ skip_before_action :ensure_context_drop_enabled!
9
+
10
+ before_action :ensure_mcp_enabled!
11
+ before_action :authenticate_mcp_request!
12
+ include ActionController::Live
13
+
14
+ def stream
15
+ response.headers["Content-Type"] = "text/event-stream"
16
+ response.headers["Cache-Control"] = "no-cache"
17
+ response.headers["X-Accel-Buffering"] = "no"
18
+
19
+ queue = Queue.new
20
+ ContextDrop::MCP::EventStreamRegistry.subscribe(queue)
21
+
22
+ response.stream.write("event: ready\ndata: {}\n\n")
23
+
24
+ loop do
25
+ payload = queue.pop
26
+ response.stream.write("event: mcp-event\ndata: #{JSON.generate(payload)}\n\n")
27
+ end
28
+ rescue IOError, ActionController::Live::ClientDisconnected
29
+ nil
30
+ ensure
31
+ ContextDrop::MCP::EventStreamRegistry.unsubscribe(queue) if queue
32
+ response.stream.close
33
+ end
34
+
35
+ private
36
+
37
+ def ensure_mcp_enabled!
38
+ return if ContextDrop.config.mcp_enabled
39
+
40
+ head :not_found
41
+ end
42
+
43
+ def authenticate_mcp_request!
44
+ if ContextDrop.config.authorize_mcp.respond_to?(:call)
45
+ return if ContextDrop.config.authorize_mcp.call(self)
46
+
47
+ head :unauthorized
48
+ return
49
+ end
50
+
51
+ expected_key = ContextDrop.config.mcp_api_key.to_s
52
+ if expected_key.strip.empty?
53
+ head :unauthorized
54
+ return
55
+ end
56
+
57
+ auth_header = request.headers["Authorization"].to_s
58
+ provided_token = auth_header.start_with?("Bearer ") ? auth_header.sub(/\ABearer\s+/i, "").strip : ""
59
+
60
+ unless provided_token.bytesize == expected_key.bytesize &&
61
+ ActiveSupport::SecurityUtils.secure_compare(provided_token, expected_key)
62
+ head :unauthorized
63
+ end
64
+ end
65
+ end
66
+ end
@@ -70,6 +70,12 @@ module ContextDrop
70
70
  def cd_icon_comment(size: 13)
71
71
  %(<svg width="#{size}" height="#{size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>).html_safe
72
72
  end
73
+
74
+ # Serve binaries through the mounted engine (not host Active Storage URLs) so
75
+ # screenshots work when the host app uses a relative URL root or proxies storage.
76
+ def cd_dashboard_attachment_path(attachment)
77
+ attachment_dashboard_feedback_path(attachment.feedback_id, attachment_id: attachment.id)
78
+ end
73
79
  end
74
80
  end
75
81
 
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContextDrop
4
+ class EventOccurrence < ApplicationRecord
5
+ self.table_name = "context_drop_event_occurrences"
6
+
7
+ EVENT_NAMES = %w[
8
+ feedback.created
9
+ feedback.updated
10
+ feedback.status_changed
11
+ feedback.deleted
12
+ ].freeze
13
+
14
+ validates :event_id, :name, :occurred_at, presence: true
15
+ validates :name, inclusion: { in: EVENT_NAMES }
16
+
17
+ scope :chronological, -> { order(occurred_at: :asc, id: :asc) }
18
+ scope :named, ->(event_name) { where(name: event_name) }
19
+
20
+ def cursor
21
+ id.to_s
22
+ end
23
+
24
+ def occurrence_payload
25
+ {
26
+ eventId: event_id,
27
+ name: name,
28
+ timestamp: occurred_at.iso8601(3),
29
+ cursor: cursor,
30
+ data: data.is_a?(Hash) ? data : {}
31
+ }
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContextDrop
4
+ class McpEventSubscription < ApplicationRecord
5
+ self.table_name = "context_drop_mcp_event_subscriptions"
6
+
7
+ scope :active, -> { where("expires_at > ?", Time.current) }
8
+
9
+ validates :subscription_id, :event_name, :callback_url, :signing_secret, :expires_at, presence: true
10
+
11
+ def expired?
12
+ expires_at <= Time.current
13
+ end
14
+
15
+ def matches_occurrence?(occurrence)
16
+ return false unless occurrence.name == event_name
17
+
18
+ arg_env = arguments.is_a?(Hash) ? arguments["environment"].to_s.strip : ""
19
+ return true if arg_env.empty?
20
+
21
+ data_env = occurrence.data.is_a?(Hash) ? occurrence.data["environment"].to_s.strip : ""
22
+ arg_env.casecmp?(data_env)
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ContextDrop
4
+ class NotificationDestination < ApplicationRecord
5
+ self.table_name = "context_drop_notification_destinations"
6
+
7
+ DESTINATION_TYPES = %w[lark webhook].freeze
8
+
9
+ validates :name, :destination_type, presence: true
10
+ validates :destination_type, inclusion: { in: DESTINATION_TYPES }
11
+ validate :validate_event_types
12
+ validate :validate_settings_shape
13
+ validate :validate_destination_secrets
14
+
15
+ scope :enabled, -> { where(enabled: true) }
16
+
17
+ def secrets
18
+ @secrets ||= ContextDrop::NotificationSecrets.decrypt(secrets_ciphertext)
19
+ end
20
+
21
+ def secrets=(hash)
22
+ @secrets = (hash || {}).transform_keys(&:to_s).compact_blank
23
+ self.secrets_ciphertext = @secrets.empty? ? nil : ContextDrop::NotificationSecrets.encrypt(@secrets)
24
+ end
25
+
26
+ def merge_secrets!(updates)
27
+ current = secrets
28
+ updates.each do |key, val|
29
+ next if val.to_s.strip.empty?
30
+
31
+ current[key.to_s] = val.to_s.strip
32
+ end
33
+ self.secrets = current
34
+ end
35
+
36
+ def subscribed_to?(event_name)
37
+ Array(event_types).map(&:to_s).include?(event_name.to_s)
38
+ end
39
+
40
+ def masked_secrets
41
+ secrets.transform_values { |v| ContextDrop::NotificationSecrets.mask_secret(v) }
42
+ end
43
+
44
+ def record_delivery!(status:, error: nil)
45
+ update_columns(
46
+ last_delivery_status: status.to_s,
47
+ last_delivery_error: error&.to_s&.truncate(2000),
48
+ last_delivered_at: Time.current,
49
+ updated_at: Time.current
50
+ )
51
+ end
52
+
53
+ private
54
+
55
+ def validate_event_types
56
+ invalid = Array(event_types).map(&:to_s) - ContextDrop::EventOccurrence::EVENT_NAMES
57
+ errors.add(:event_types, "include unsupported events: #{invalid.join(', ')}") if invalid.any?
58
+ end
59
+
60
+ def validate_destination_secrets
61
+ return unless enabled
62
+
63
+ case destination_type
64
+ when "lark"
65
+ errors.add(:secrets, "require Lark app_id") if secrets["app_id"].to_s.strip.empty?
66
+ if secrets["app_secret"].to_s.strip.empty? && secrets_ciphertext.blank?
67
+ errors.add(:secrets, "require Lark app_secret")
68
+ end
69
+ end
70
+ end
71
+
72
+ def validate_settings_shape
73
+ return unless enabled
74
+
75
+ case destination_type
76
+ when "lark"
77
+ errors.add(:settings, "require receive_id for Lark") if settings.is_a?(Hash) && settings["receive_id"].to_s.strip.empty?
78
+ when "webhook"
79
+ url = settings.is_a?(Hash) ? settings["url"].to_s.strip : ""
80
+ errors.add(:settings, "require HTTPS url for webhook") if url.empty?
81
+ end
82
+ end
83
+ end
84
+ end