context_drop 0.2.0 → 0.3.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 (32) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +149 -12
  3. data/Rakefile +110 -1
  4. data/app/assets/javascripts/context_drop/context_drop.js +1230 -53
  5. data/app/controllers/context_drop/application_controller.rb +52 -3
  6. data/app/controllers/context_drop/configs_controller.rb +10 -1
  7. data/app/controllers/context_drop/dashboard/feedbacks_controller.rb +15 -11
  8. data/app/controllers/context_drop/feedbacks_controller.rb +383 -17
  9. data/app/javascript/context_drop/__tests__/api-client.test.ts +255 -0
  10. data/app/javascript/context_drop/__tests__/widget.test.ts +355 -1
  11. data/app/javascript/context_drop/api-client.ts +306 -22
  12. data/app/javascript/context_drop/element-picker.ts +1 -1
  13. data/app/javascript/context_drop/icons.ts +4 -0
  14. data/app/javascript/context_drop/screenshot.ts +1 -1
  15. data/app/javascript/context_drop/styles.ts +181 -0
  16. data/app/javascript/context_drop/types.ts +96 -6
  17. data/app/javascript/context_drop/widget.ts +752 -29
  18. data/app/models/context_drop/feedback.rb +65 -8
  19. data/app/services/context_drop/ownership_token.rb +114 -0
  20. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +8 -0
  21. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +9 -0
  22. data/app/views/layouts/context_drop/application.html.erb +5 -0
  23. data/config/routes.rb +11 -0
  24. data/db/migrate/20261113000005_add_deleted_at_to_context_drop_feedbacks.rb +11 -0
  25. data/lib/context_drop/configuration.rb +26 -0
  26. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +3 -1
  27. data/lib/context_drop/mcp/tools/get_feedback.rb +16 -5
  28. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +3 -0
  29. data/lib/context_drop/mcp/tools/list_feedbacks.rb +22 -2
  30. data/lib/context_drop/mcp/tools/update_feedback_status.rb +3 -1
  31. data/lib/context_drop/version.rb +1 -1
  32. metadata +4 -2
@@ -1,11 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "digest"
4
+ require "securerandom"
4
5
 
5
6
  module ContextDrop
6
7
  class ApplicationController < ActionController::Base
7
- protect_from_forgery with: :exception
8
+ protect_from_forgery with: :exception, unless: :verified_cross_origin_widget_request?
8
9
 
10
+ before_action :apply_widget_cors_headers!
9
11
  before_action :ensure_context_drop_enabled!
10
12
 
11
13
  rescue_from ActionController::InvalidAuthenticityToken, with: :handle_invalid_csrf_token
@@ -90,8 +92,19 @@ module ContextDrop
90
92
  end
91
93
  end
92
94
 
93
- def hashed_session_identifier
94
- raw_id = session.id.to_s if respond_to?(:session) && session.respond_to?(:id) && session.id
95
+ def hashed_session_identifier(initialize_if_missing: false)
96
+ raw_id = nil
97
+ if respond_to?(:session) && session
98
+ raw_id = session[:cd_sid].to_s if session.respond_to?(:[])
99
+ if raw_id.to_s.empty? && initialize_if_missing && session.respond_to?(:[]=)
100
+ generated = SecureRandom.hex(16)
101
+ session[:cd_sid] = generated
102
+ raw_id = generated
103
+ end
104
+ if raw_id.to_s.empty? && session.respond_to?(:id) && session.id
105
+ raw_id = session.id.to_s
106
+ end
107
+ end
95
108
  return nil if raw_id.nil? || raw_id.empty?
96
109
 
97
110
  Digest::SHA256.hexdigest(raw_id)[0, 32]
@@ -110,5 +123,41 @@ module ContextDrop
110
123
  def handle_sensitive_element_error(exception)
111
124
  render json: { error: exception.message }, status: :unprocessable_entity
112
125
  end
126
+
127
+ def cors_eligible_widget_endpoint?
128
+ is_a?(ContextDrop::ConfigsController) ||
129
+ is_a?(ContextDrop::AttachmentsController) ||
130
+ is_a?(ContextDrop::FeedbacksController) ||
131
+ is_a?(ContextDrop::HealthController)
132
+ end
133
+
134
+ def apply_widget_cors_headers!
135
+ return unless cors_eligible_widget_endpoint?
136
+
137
+ origin = request.headers["Origin"].to_s.strip
138
+ return if origin.empty? || !ContextDrop.config.origin_allowed?(origin)
139
+
140
+ response.set_header("Access-Control-Allow-Origin", origin)
141
+ response.set_header("Vary", "Origin")
142
+ response.set_header("Access-Control-Allow-Credentials", "true")
143
+ response.set_header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS")
144
+ response.set_header(
145
+ "Access-Control-Allow-Headers",
146
+ "Content-Type, Accept, X-CSRF-Token, X-Context-Drop-Client, X-Context-Drop-Ownership-Token, X-Context-Drop-Ownership-Tokens, Authorization"
147
+ )
148
+ response.set_header("Access-Control-Max-Age", "86400")
149
+ end
150
+
151
+ def verified_cross_origin_widget_request?
152
+ return false unless cors_eligible_widget_endpoint?
153
+
154
+ origin = request.headers["Origin"].to_s.strip
155
+ return false if origin.empty? || !ContextDrop.config.origin_allowed?(origin)
156
+
157
+ request.options? ||
158
+ request.headers["X-Context-Drop-Client"].to_s.strip == "1" ||
159
+ request.headers["X-Context-Drop-Ownership-Token"].to_s.strip.present? ||
160
+ request.content_type.to_s.downcase.start_with?("application/json")
161
+ end
113
162
  end
114
163
  end
@@ -2,7 +2,7 @@
2
2
 
3
3
  module ContextDrop
4
4
  class ConfigsController < ApplicationController
5
- skip_forgery_protection only: [:widget_bundle] if respond_to?(:skip_forgery_protection)
5
+ skip_forgery_protection only: %i[widget_bundle cors_preflight] if respond_to?(:skip_forgery_protection)
6
6
  before_action :enforce_submission_authorization!, only: [:show]
7
7
 
8
8
  def show
@@ -11,6 +11,15 @@ module ContextDrop
11
11
  render json: ContextDrop.config.public_widget_config(agent_enabled: agent_ok).merge(csrf_token: token), status: :ok
12
12
  end
13
13
 
14
+ def cors_preflight
15
+ origin = request.headers["Origin"].to_s.strip
16
+ if !origin.empty? && ContextDrop.config.origin_allowed?(origin)
17
+ head :no_content
18
+ else
19
+ head :forbidden
20
+ end
21
+ end
22
+
14
23
  def widget_bundle
15
24
  bundle_path = ContextDrop::Engine.root.join("app/assets/javascripts/context_drop/context_drop.js")
16
25
  if File.exist?(bundle_path)
@@ -13,21 +13,23 @@ module ContextDrop
13
13
 
14
14
  def index
15
15
  @status_counts = {
16
- "all" => ContextDrop::Feedback.count,
16
+ "all" => ContextDrop::Feedback.active.count,
17
17
  "new" => ContextDrop::Feedback.new_records.count,
18
18
  "reviewed" => ContextDrop::Feedback.reviewed.count,
19
19
  "resolved" => ContextDrop::Feedback.resolved.count,
20
- "dismissed" => ContextDrop::Feedback.dismissed.count
20
+ "dismissed" => ContextDrop::Feedback.dismissed.count,
21
+ "deleted" => ContextDrop::Feedback.deleted.count
21
22
  }
22
23
 
23
- scope = ContextDrop::Feedback.includes(:element_references, :attachments).recent
24
-
25
24
  @current_status = params[:status].to_s.strip
26
- if ContextDrop::Feedback::STATUSES.include?(@current_status)
27
- scope = scope.where(status: @current_status)
28
- else
29
- @current_status = ""
30
- end
25
+ scope = if @current_status == "deleted"
26
+ ContextDrop::Feedback.deleted.includes(:element_references, :attachments).recent
27
+ elsif ContextDrop::Feedback::STATUSES.include?(@current_status)
28
+ ContextDrop::Feedback.active.where(status: @current_status).includes(:element_references, :attachments).recent
29
+ else
30
+ @current_status = ""
31
+ ContextDrop::Feedback.active.includes(:element_references, :attachments).recent
32
+ end
31
33
 
32
34
  @page_url_filter = params[:page_url].to_s.strip
33
35
  if @page_url_filter.present?
@@ -59,8 +61,10 @@ module ContextDrop
59
61
  .includes(:element_references, :attachments)
60
62
  .find(params[:id])
61
63
 
64
+ nav_scope = @feedback.deleted? ? ContextDrop::Feedback.deleted : ContextDrop::Feedback.active
65
+
62
66
  # Newer feedback (previous in chronological newest-first list) and older feedback (next in list)
63
- @newer_feedback = ContextDrop::Feedback
67
+ @newer_feedback = nav_scope
64
68
  .where(
65
69
  "created_at > :ts OR (created_at = :ts AND id > :id)",
66
70
  ts: @feedback.created_at,
@@ -70,7 +74,7 @@ module ContextDrop
70
74
  .select(:id, :status)
71
75
  .first
72
76
 
73
- @older_feedback = ContextDrop::Feedback
77
+ @older_feedback = nav_scope
74
78
  .where(
75
79
  "created_at < :ts OR (created_at = :ts AND id < :id)",
76
80
  ts: @feedback.created_at,
@@ -3,7 +3,35 @@
3
3
  module ContextDrop
4
4
  class FeedbacksController < ApplicationController
5
5
  before_action :enforce_submission_authorization!
6
- before_action :enforce_rate_limit!
6
+ before_action :enforce_rate_limit!, only: %i[create update destroy]
7
+
8
+ MAX_OWN_FEEDBACKS_LIMIT = 50
9
+ DEFAULT_OWN_FEEDBACKS_LIMIT = 20
10
+
11
+ def index
12
+ raw_limit = params[:limit] ? params[:limit].to_i : DEFAULT_OWN_FEEDBACKS_LIMIT
13
+ limit = raw_limit.clamp(1, MAX_OWN_FEEDBACKS_LIMIT)
14
+
15
+ scope = own_active_feedbacks_scope
16
+ total = scope.count
17
+ raw_tokens = combined_raw_ownership_tokens
18
+
19
+ records = scope
20
+ .includes(:element_references, :attachments)
21
+ .recent
22
+ .limit(limit)
23
+ .map do |fb|
24
+ existing_tok = ContextDrop::OwnershipToken.find_token_for(raw_tokens, fb.id)
25
+ tok = existing_tok || ContextDrop::OwnershipToken.generate(fb.id)
26
+ serialize_own_feedback(fb, ownership_token: tok)
27
+ end
28
+
29
+ render json: {
30
+ total_count: total,
31
+ total: total,
32
+ feedbacks: records
33
+ }, status: :ok
34
+ end
7
35
 
8
36
  def create
9
37
  payload = extract_feedback_payload
@@ -33,7 +61,7 @@ module ContextDrop
33
61
 
34
62
  feedback_attrs = {
35
63
  submitter: current_context_drop_submitter,
36
- session_id: hashed_session_identifier,
64
+ session_id: hashed_session_identifier(initialize_if_missing: true),
37
65
  message: payload["message"].to_s.strip.presence,
38
66
  page_url: (payload["page_url"].presence || request.referer).to_s.strip,
39
67
  user_agent: (payload["user_agent"].presence || request.user_agent).to_s.strip.presence,
@@ -59,15 +87,7 @@ module ContextDrop
59
87
  att_hash = stringify_hash(raw_att)
60
88
  att_type = (att_hash["attachment_type"] || att_hash["type"] || "image").to_s.strip.downcase
61
89
  att_meta = ContextDrop::MetadataSanitizer.sanitize_attachment_metadata(att_hash["metadata"])
62
-
63
- linked_ref_key = (
64
- att_hash["element_reference_ref"] ||
65
- att_hash["element_attachment_ref"] ||
66
- att_hash["client_ref"] ||
67
- att_meta["element_attachment_ref"] ||
68
- att_meta["client_ref"]
69
- ).to_s.strip.presence
70
-
90
+ linked_ref_key = extract_linked_element_ref_key(att_hash, att_meta)
71
91
  linked_el = linked_ref_key ? element_refs_by_client_ref[linked_ref_key] : nil
72
92
  file_source = resolve_attachment_file_source(att_hash)
73
93
 
@@ -80,7 +100,7 @@ module ContextDrop
80
100
 
81
101
  att_record = feedback.attachments.build(
82
102
  attachment_type: att_type,
83
- element_reference: linked_el,
103
+ element_reference: (linked_el && !linked_el.new_record? ? linked_el : nil),
84
104
  metadata: att_meta
85
105
  )
86
106
  pending_file_attachments << [att_record, linked_el, file_source]
@@ -104,7 +124,9 @@ module ContextDrop
104
124
 
105
125
  return if performed?
106
126
 
107
- invoke_on_feedback_created(feedback)
127
+ feedback.reload
128
+ invoke_lifecycle_callback(:on_feedback_created, feedback)
129
+ ownership_token = ContextDrop::OwnershipToken.generate(feedback.id)
108
130
 
109
131
  render json: {
110
132
  id: feedback.id,
@@ -112,12 +134,354 @@ module ContextDrop
112
134
  status: feedback.status,
113
135
  attachments_count: feedback.attachments.size,
114
136
  element_references_count: feedback.element_references.size,
115
- created_at: feedback.created_at.iso8601
137
+ ownership_token: ownership_token,
138
+ feedback: serialize_own_feedback(feedback, ownership_token: ownership_token),
139
+ created_at: feedback.created_at.iso8601,
140
+ updated_at: feedback.updated_at.iso8601
116
141
  }, status: :created
117
142
  end
118
143
 
144
+ def update
145
+ feedback = ContextDrop::Feedback.includes(:element_references, :attachments).find_by(id: params[:id])
146
+ if feedback.nil? || feedback.deleted?
147
+ render json: { error: "Feedback not found" }, status: :not_found
148
+ return
149
+ end
150
+
151
+ payload = extract_feedback_payload
152
+ unless owns_feedback?(feedback, payload_token: payload["ownership_token"])
153
+ render json: { error: "Forbidden" }, status: :forbidden
154
+ return
155
+ end
156
+
157
+ has_elements_key = payload.key?("element_references")
158
+ has_attachments_key = payload.key?("attachments")
159
+ raw_elements = has_elements_key ? Array(payload["element_references"]) : nil
160
+ raw_attachments = has_attachments_key ? Array(payload["attachments"]) : nil
161
+
162
+ if has_attachments_key && raw_attachments.size > ContextDrop.config.max_attachments.to_i
163
+ render json: {
164
+ error: "Attachments count (#{raw_attachments.size}) exceeds maximum allowed (#{ContextDrop.config.max_attachments})"
165
+ }, status: :unprocessable_entity
166
+ return
167
+ end
168
+
169
+ if has_elements_key && raw_elements.size > ContextDrop.config.max_element_references.to_i
170
+ render json: {
171
+ error: "Element references count (#{raw_elements.size}) exceeds maximum allowed (#{ContextDrop.config.max_element_references})"
172
+ }, status: :unprocessable_entity
173
+ return
174
+ end
175
+
176
+ ContextDrop::Feedback.transaction do
177
+ if payload.key?("message")
178
+ feedback.message = payload["message"].to_s.strip.presence
179
+ end
180
+
181
+ if payload.key?("metadata")
182
+ sanitized_meta = ContextDrop::MetadataSanitizer.sanitize_feedback_metadata(payload["metadata"])
183
+ sanitized_meta["environment"] = feedback.environment_name
184
+ feedback.metadata = sanitized_meta
185
+ end
186
+
187
+ element_refs_by_client_ref = {}
188
+ if has_elements_key
189
+ sanitized_elements = raw_elements.map do |raw_el|
190
+ ContextDrop::MetadataSanitizer.sanitize_element_reference(raw_el)
191
+ end
192
+
193
+ feedback.element_references.each(&:mark_for_destruction)
194
+ sanitized_elements.each_with_index do |sanitized_el, idx|
195
+ el_record = feedback.element_references.build(sanitized_el)
196
+ client_key = sanitized_el[:client_ref].presence || idx.to_s
197
+ element_refs_by_client_ref[client_key] = el_record
198
+ end
199
+ else
200
+ feedback.element_references.each_with_index do |el_record, idx|
201
+ client_key = el_record.client_ref.presence || idx.to_s
202
+ element_refs_by_client_ref[client_key] = el_record
203
+ end
204
+ end
205
+
206
+ retained_attachment_updates = []
207
+ pending_file_attachments = []
208
+
209
+ if has_attachments_key
210
+ existing_by_id = feedback.attachments.index_by { |a| a.id.to_s }
211
+ retained_ids = {}
212
+
213
+ raw_attachments.each do |raw_att|
214
+ att_hash = stringify_hash(raw_att)
215
+ has_new_binary = att_hash["signed_blob_id"].present? ||
216
+ att_hash["file"].present? ||
217
+ att_hash["data_url"].present? ||
218
+ att_hash["data"].present?
219
+ existing_id = (att_hash["existing_id"] || (!has_new_binary ? att_hash["id"] : nil)).to_s.strip
220
+
221
+ if existing_id.present?
222
+ existing_att = existing_by_id[existing_id]
223
+ unless existing_att
224
+ render json: { error: "Attachment does not belong to this feedback" }, status: :unprocessable_entity
225
+ raise ActiveRecord::Rollback
226
+ end
227
+
228
+ retained_ids[existing_id] = true
229
+ has_custom_meta = att_hash.key?("metadata") && att_hash["metadata"].is_a?(Hash)
230
+ att_meta = if has_custom_meta
231
+ merged_meta = (existing_att.metadata.is_a?(Hash) ? existing_att.metadata : {}).merge(
232
+ ContextDrop::MetadataSanitizer.sanitize_attachment_metadata(att_hash["metadata"])
233
+ )
234
+ merged_meta
235
+ else
236
+ existing_att.metadata.is_a?(Hash) ? existing_att.metadata : {}
237
+ end
238
+
239
+ linked_ref_key = extract_linked_element_ref_key(att_hash, att_meta)
240
+ linked_el = if linked_ref_key
241
+ element_refs_by_client_ref[linked_ref_key]
242
+ elsif !has_elements_key
243
+ existing_att.element_reference
244
+ end
245
+
246
+ retained_attachment_updates << [existing_att, linked_el, att_meta, has_custom_meta]
247
+ else
248
+ att_type = (att_hash["attachment_type"] || att_hash["type"] || "image").to_s.strip.downcase
249
+ att_meta = ContextDrop::MetadataSanitizer.sanitize_attachment_metadata(att_hash["metadata"])
250
+ linked_ref_key = extract_linked_element_ref_key(att_hash, att_meta)
251
+ linked_el = linked_ref_key ? element_refs_by_client_ref[linked_ref_key] : nil
252
+ file_source = resolve_attachment_file_source(att_hash)
253
+
254
+ if file_source[:dimensions] && att_meta["image_dimensions"].nil?
255
+ att_meta["image_dimensions"] = {
256
+ "width" => file_source[:dimensions][0],
257
+ "height" => file_source[:dimensions][1]
258
+ }
259
+ end
260
+
261
+ att_record = feedback.attachments.build(
262
+ attachment_type: att_type,
263
+ element_reference: (linked_el && !linked_el.new_record? ? linked_el : nil),
264
+ metadata: att_meta
265
+ )
266
+ pending_file_attachments << [att_record, linked_el, file_source]
267
+ end
268
+ end
269
+
270
+ feedback.attachments.each do |att|
271
+ next if att.new_record?
272
+ next if retained_ids[att.id.to_s]
273
+
274
+ att.mark_for_destruction
275
+ end
276
+ end
277
+
278
+ unless feedback.valid?
279
+ render json: { error: feedback.errors.full_messages.join(", "), errors: feedback.errors.full_messages },
280
+ status: :unprocessable_entity
281
+ raise ActiveRecord::Rollback
282
+ end
283
+
284
+ feedback.element_references.select(&:marked_for_destruction?).each(&:destroy!)
285
+ feedback.attachments.select(&:marked_for_destruction?).each(&:destroy!)
286
+ feedback.updated_at = Time.current
287
+ feedback.save!
288
+
289
+ retained_attachment_updates.each do |existing_att, linked_el, att_meta, has_custom_meta|
290
+ attrs_to_update = { element_reference_id: linked_el&.id }
291
+ attrs_to_update[:metadata] = att_meta if has_custom_meta
292
+ existing_att.update_columns(attrs_to_update)
293
+ end
294
+
295
+ pending_file_attachments.each do |att_record, linked_el, file_source|
296
+ if linked_el && att_record.element_reference_id.nil?
297
+ att_record.update_column(:element_reference_id, linked_el.id)
298
+ end
299
+ attach_binary_to_record!(att_record, file_source)
300
+ end
301
+ end
302
+
303
+ return if performed?
304
+
305
+ feedback.reload
306
+ invoke_lifecycle_callback(:on_feedback_updated, feedback)
307
+
308
+ raw_tokens = combined_raw_ownership_tokens(payload["ownership_token"])
309
+ ownership_token = ContextDrop::OwnershipToken.find_token_for(raw_tokens, feedback.id) ||
310
+ ContextDrop::OwnershipToken.generate(feedback.id)
311
+
312
+ render json: {
313
+ id: feedback.id,
314
+ environment: feedback.environment_name,
315
+ status: feedback.status,
316
+ message: feedback.message,
317
+ attachments_count: feedback.attachments.size,
318
+ element_references_count: feedback.element_references.size,
319
+ ownership_token: ownership_token,
320
+ feedback: serialize_own_feedback(feedback, ownership_token: ownership_token),
321
+ created_at: feedback.created_at.iso8601,
322
+ updated_at: feedback.updated_at.iso8601
323
+ }, status: :ok
324
+ end
325
+
326
+ def destroy
327
+ feedback = ContextDrop::Feedback.find_by(id: params[:id])
328
+ if feedback.nil? || feedback.deleted?
329
+ render json: { error: "Feedback not found" }, status: :not_found
330
+ return
331
+ end
332
+
333
+ payload = extract_feedback_payload
334
+ unless owns_feedback?(feedback, payload_token: payload["ownership_token"])
335
+ render json: { error: "Forbidden" }, status: :forbidden
336
+ return
337
+ end
338
+
339
+ feedback.soft_delete!
340
+ invoke_lifecycle_callback(:on_feedback_deleted, feedback)
341
+
342
+ render json: {
343
+ id: feedback.id,
344
+ deleted: true,
345
+ deleted_at: feedback.deleted_at_value&.iso8601
346
+ }, status: :ok
347
+ end
348
+
349
+ def attachment
350
+ feedback = ContextDrop::Feedback.find_by(id: params[:feedback_id])
351
+ if feedback.nil? || feedback.deleted?
352
+ head :not_found
353
+ return
354
+ end
355
+
356
+ unless owns_feedback?(feedback)
357
+ head :forbidden
358
+ return
359
+ end
360
+
361
+ att = feedback.attachments.find_by(id: params[:id])
362
+ if att.nil? || !att.respond_to?(:file) || !att.file.attached?
363
+ head :not_found
364
+ return
365
+ end
366
+
367
+ response.set_header("Cache-Control", "private, max-age=3600")
368
+ response.set_header("Content-Security-Policy", "default-src 'none'; sandbox")
369
+ send_data att.file.download,
370
+ type: att.file.content_type || "image/png",
371
+ disposition: "inline",
372
+ filename: att.file.filename.to_s
373
+ end
374
+
119
375
  private
120
376
 
377
+ def own_active_feedbacks_scope
378
+ base = ContextDrop::Feedback.active
379
+ clauses = []
380
+
381
+ submitter = current_context_drop_submitter
382
+ if submitter && submitter.respond_to?(:id) && !submitter.id.nil?
383
+ clauses << base.where(submitter_type: submitter.class.name, submitter_id: submitter.id)
384
+ end
385
+
386
+ anon_base = base.where(submitter_id: nil)
387
+ sid = hashed_session_identifier(initialize_if_missing: false)
388
+ clauses << anon_base.where(session_id: sid) if sid.present?
389
+
390
+ token_ids = ContextDrop::OwnershipToken
391
+ .extract_verified_ids(combined_raw_ownership_tokens)
392
+ .map(&:to_i)
393
+ .select(&:positive?)
394
+ clauses << anon_base.where(id: token_ids) if token_ids.any?
395
+
396
+ return ContextDrop::Feedback.none if clauses.empty?
397
+
398
+ clauses.reduce { |acc, rel| acc.or(rel) }
399
+ end
400
+
401
+ def owns_feedback?(feedback, payload_token: nil)
402
+ submitter = current_context_drop_submitter
403
+
404
+ if feedback.submitter_id.present? || feedback.submitter_type.present?
405
+ return false unless submitter && submitter.respond_to?(:id) && !submitter.id.nil?
406
+
407
+ return feedback.submitter_type.to_s == submitter.class.name.to_s &&
408
+ feedback.submitter_id.to_s == submitter.id.to_s
409
+ end
410
+
411
+ raw_tokens = combined_raw_ownership_tokens(payload_token)
412
+ return true if ContextDrop::OwnershipToken.find_token_for(raw_tokens, feedback.id)
413
+
414
+ sid = hashed_session_identifier(initialize_if_missing: false)
415
+ return false if sid.blank? || feedback.session_id.blank?
416
+
417
+ ActiveSupport::SecurityUtils.secure_compare(feedback.session_id.to_s, sid.to_s)
418
+ end
419
+
420
+ def combined_raw_ownership_tokens(extra_token = nil)
421
+ [
422
+ extra_token,
423
+ request.headers["X-Context-Drop-Ownership-Token"],
424
+ request.headers["X-Context-Drop-Ownership-Tokens"],
425
+ params[:ownership_token],
426
+ params[:ownership_tokens]
427
+ ].compact.map(&:to_s).reject(&:empty?).join(",")
428
+ end
429
+
430
+ def serialize_own_feedback(feedback, ownership_token: nil)
431
+ elements_by_id = feedback.element_references.index_by(&:id)
432
+
433
+ {
434
+ id: feedback.id,
435
+ environment: feedback.environment_name,
436
+ status: feedback.status,
437
+ message: feedback.message,
438
+ page_url: feedback.page_url,
439
+ ownership_token: ownership_token,
440
+ created_at: feedback.created_at&.iso8601,
441
+ updated_at: feedback.updated_at&.iso8601,
442
+ element_references: feedback.element_references.map do |el|
443
+ {
444
+ id: el.id,
445
+ client_ref: el.client_ref,
446
+ tag_name: el.tag_name,
447
+ selector: el.selector,
448
+ dom_path: el.dom_path,
449
+ text_content: el.text_content,
450
+ attributes_snapshot: el.attributes_snapshot || {},
451
+ bounding_rect: el.bounding_rect || {},
452
+ viewport: el.viewport || {},
453
+ metadata: el.metadata || {},
454
+ captured_at: el.captured_at&.iso8601
455
+ }
456
+ end,
457
+ attachments: feedback.attachments.map do |att|
458
+ attached = att.respond_to?(:file) && att.file.attached?
459
+ linked_el = att.element_reference_id ? elements_by_id[att.element_reference_id] : att.element_reference
460
+ {
461
+ id: att.id,
462
+ attachment_type: att.attachment_type,
463
+ element_reference_id: att.element_reference_id,
464
+ element_reference_ref: linked_el&.client_ref,
465
+ filename: attached ? att.file.filename.to_s : nil,
466
+ content_type: attached ? att.file.content_type : nil,
467
+ byte_size: attached ? att.file.byte_size : nil,
468
+ metadata: att.metadata || {},
469
+ created_at: att.created_at&.iso8601
470
+ }
471
+ end
472
+ }
473
+ end
474
+
475
+ def extract_linked_element_ref_key(att_hash, att_meta)
476
+ (
477
+ att_hash["element_reference_ref"] ||
478
+ att_hash["element_attachment_ref"] ||
479
+ att_hash["client_ref"] ||
480
+ att_meta["element_attachment_ref"] ||
481
+ att_meta["client_ref"]
482
+ ).to_s.strip.presence
483
+ end
484
+
121
485
  def extract_feedback_payload
122
486
  raw = params[:feedback].is_a?(ActionController::Parameters) || params[:feedback].is_a?(Hash) ? params[:feedback] : params
123
487
  hash = stringify_hash(raw)
@@ -198,11 +562,13 @@ module ContextDrop
198
562
  raise ContextDrop::UploadValidator::ValidationError, "Invalid base64 attachment data"
199
563
  end
200
564
 
201
- def invoke_on_feedback_created(feedback)
202
- callback = ContextDrop.config.on_feedback_created
565
+ def invoke_lifecycle_callback(hook_name, feedback)
566
+ return unless ContextDrop.config.respond_to?(hook_name)
567
+
568
+ callback = ContextDrop.config.public_send(hook_name)
203
569
  callback.call(feedback) if callback.respond_to?(:call)
204
570
  rescue StandardError => e
205
- Rails.logger.error("[ContextDrop] on_feedback_created callback error: #{e.class}: #{e.message}") if defined?(Rails.logger) && Rails.logger
571
+ Rails.logger.error("[ContextDrop] #{hook_name} callback error: #{e.class}: #{e.message}") if defined?(Rails.logger) && Rails.logger
206
572
  end
207
573
 
208
574
  def stringify_hash(obj)