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.
@@ -6,6 +6,7 @@ import { ContextDropMcpDispatcher } from "../mcp/dispatcher.js";
6
6
  import { resolveHostEnvironment } from "../mcp/environment-router.js";
7
7
  import { MANDATORY_SERVER_EXCLUDED_SELECTORS, SensitiveElementError, sanitizeElementReference, sanitizeGenericMetadata } from "./sanitizer.js";
8
8
  import { createLocalStorageAdapter } from "./storage/local.js";
9
+ import { matchesOwnFeedback } from "./storage/memory.js";
9
10
  import { VERSION } from "./types.js";
10
11
  import { DEFAULT_ALLOWED_CONTENT_TYPES, UploadValidationError, decodeBase64DataUrl, validateBinaryUpload } from "./upload-validator.js";
11
12
  const VALID_POSITIONS = [
@@ -14,7 +15,10 @@ const VALID_POSITIONS = [
14
15
  "top_right",
15
16
  "top_left"
16
17
  ];
18
+ const MAX_OWNERSHIP_TOKENS = 50;
19
+ const OWNERSHIP_TOKEN_DOMAIN = "cd_own:v1";
17
20
  let sharedDefaultLocalStorage = null;
21
+ const fallbackOwnershipSecret = crypto.randomBytes(32);
18
22
  function getSharedDefaultStorage(storageDir) {
19
23
  if (storageDir) {
20
24
  return createLocalStorageAdapter({ dir: storageDir });
@@ -92,8 +96,8 @@ function buildCorsHeaders(request, allowedOrigins) {
92
96
  "Access-Control-Allow-Origin": origin,
93
97
  Vary: "Origin",
94
98
  "Access-Control-Allow-Credentials": "true",
95
- "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
96
- "Access-Control-Allow-Headers": "Content-Type, Accept, X-CSRF-Token, X-Context-Drop-Client, Authorization",
99
+ "Access-Control-Allow-Methods": "GET, POST, PATCH, PUT, DELETE, OPTIONS",
100
+ "Access-Control-Allow-Headers": "Content-Type, Accept, X-CSRF-Token, X-Context-Drop-Client, X-Context-Drop-Ownership-Token, X-Context-Drop-Ownership-Tokens, Authorization",
97
101
  "Access-Control-Max-Age": "86400"
98
102
  };
99
103
  }
@@ -133,27 +137,84 @@ function resolveClientIp(request) {
133
137
  return realIp;
134
138
  return "127.0.0.1";
135
139
  }
136
- function extractHashedSessionId(request) {
140
+ const SESSION_COOKIE_NAME = "cd_session";
141
+ const SESSION_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
142
+ function extractRawSessionCookie(request) {
137
143
  const cookieHeader = request.headers.get("cookie");
138
- if (!cookieHeader)
144
+ if (!cookieHeader || cookieHeader.trim().length === 0)
139
145
  return null;
140
- return crypto.createHash("sha256").update(cookieHeader).digest("hex").slice(0, 32);
146
+ const pairs = cookieHeader.split(";");
147
+ for (const pair of pairs) {
148
+ const eqIdx = pair.indexOf("=");
149
+ if (eqIdx <= 0)
150
+ continue;
151
+ const name = pair.slice(0, eqIdx).trim();
152
+ if (name !== SESSION_COOKIE_NAME)
153
+ continue;
154
+ const rawVal = pair.slice(eqIdx + 1).trim();
155
+ if (/^[a-f0-9]{32,64}$/i.test(rawVal)) {
156
+ return rawVal.toLowerCase();
157
+ }
158
+ }
159
+ return null;
160
+ }
161
+ function hashSessionCookieValue(rawToken) {
162
+ return crypto
163
+ .createHash("sha256")
164
+ .update(`cd_session:v1:${rawToken}`)
165
+ .digest("hex")
166
+ .slice(0, 32);
141
167
  }
142
- function resolveSubRoute(pathname) {
168
+ function extractHashedSessionId(request) {
169
+ const rawToken = extractRawSessionCookie(request);
170
+ if (!rawToken)
171
+ return null;
172
+ return hashSessionCookieValue(rawToken);
173
+ }
174
+ function buildSessionSetCookieHeader(rawToken, isSecure) {
175
+ const parts = [
176
+ `${SESSION_COOKIE_NAME}=${rawToken}`,
177
+ "Path=/",
178
+ `Max-Age=${SESSION_COOKIE_MAX_AGE_SECONDS}`,
179
+ "HttpOnly",
180
+ "SameSite=Lax"
181
+ ];
182
+ if (isSecure) {
183
+ parts.push("Secure");
184
+ }
185
+ return parts.join("; ");
186
+ }
187
+ function parseSubRoute(pathname) {
143
188
  const clean = pathname.replace(/\/+$/, "");
144
- if (clean.endsWith("/assets/context_drop.js"))
145
- return "assets/context_drop.js";
189
+ const fbAttMatch = /\/feedback\/([^/]+)\/attachments\/([^/]+)$/.exec(clean);
190
+ if (fbAttMatch) {
191
+ return {
192
+ kind: "feedback_attachment",
193
+ feedbackId: decodeURIComponent(fbAttMatch[1]),
194
+ attachmentId: decodeURIComponent(fbAttMatch[2])
195
+ };
196
+ }
197
+ const fbItemMatch = /\/feedback\/([^/]+)$/.exec(clean);
198
+ if (fbItemMatch) {
199
+ return {
200
+ kind: "feedback_item",
201
+ feedbackId: decodeURIComponent(fbItemMatch[1])
202
+ };
203
+ }
204
+ if (clean.endsWith("/assets/context_drop.js")) {
205
+ return { kind: "static", name: "assets/context_drop.js" };
206
+ }
146
207
  if (clean.endsWith("/config"))
147
- return "config";
208
+ return { kind: "static", name: "config" };
148
209
  if (clean.endsWith("/attachments"))
149
- return "attachments";
210
+ return { kind: "static", name: "attachments" };
150
211
  if (clean.endsWith("/feedback"))
151
- return "feedback";
212
+ return { kind: "static", name: "feedback" };
152
213
  if (clean.endsWith("/health"))
153
- return "health";
214
+ return { kind: "static", name: "health" };
154
215
  if (clean.endsWith("/mcp"))
155
- return "mcp";
156
- return "";
216
+ return { kind: "static", name: "mcp" };
217
+ return { kind: "unknown" };
157
218
  }
158
219
  function timingSafeCompareStrings(a, b) {
159
220
  const bufA = Buffer.from(a, "utf8");
@@ -163,6 +224,137 @@ function timingSafeCompareStrings(a, b) {
163
224
  }
164
225
  return crypto.timingSafeEqual(bufA, bufB);
165
226
  }
227
+ function computeOwnershipHmac(idStr, nonce, secret) {
228
+ return crypto
229
+ .createHmac("sha256", secret)
230
+ .update(`${OWNERSHIP_TOKEN_DOMAIN}:${idStr}:${nonce}`)
231
+ .digest("hex");
232
+ }
233
+ export function generateOwnershipToken(feedbackId, secret) {
234
+ const idStr = String(feedbackId).trim();
235
+ const nonce = crypto.randomBytes(8).toString("hex");
236
+ const sig = computeOwnershipHmac(idStr, nonce, secret);
237
+ return `${idStr}.${nonce}.${sig}`;
238
+ }
239
+ export function verifyOwnershipToken(token, feedbackId, secret) {
240
+ if (!token)
241
+ return false;
242
+ const raw = token.trim();
243
+ const targetId = String(feedbackId).trim();
244
+ if (!raw || !targetId)
245
+ return false;
246
+ const firstDot = raw.indexOf(".");
247
+ if (firstDot <= 0)
248
+ return false;
249
+ const secondDot = raw.indexOf(".", firstDot + 1);
250
+ if (secondDot <= firstDot + 1)
251
+ return false;
252
+ const idPart = raw.slice(0, firstDot);
253
+ const noncePart = raw.slice(firstDot + 1, secondDot);
254
+ const sigPart = raw.slice(secondDot + 1);
255
+ if (idPart !== targetId || !noncePart || !sigPart)
256
+ return false;
257
+ const expected = computeOwnershipHmac(targetId, noncePart, secret);
258
+ return timingSafeCompareStrings(sigPart, expected);
259
+ }
260
+ export function extractVerifiedOwnershipIds(rawTokens, secret) {
261
+ if (!rawTokens)
262
+ return [];
263
+ const parts = rawTokens
264
+ .split(",")
265
+ .map((s) => s.trim())
266
+ .filter(Boolean)
267
+ .slice(0, MAX_OWNERSHIP_TOKENS);
268
+ const verified = new Set();
269
+ for (const tok of parts) {
270
+ const firstDot = tok.indexOf(".");
271
+ if (firstDot <= 0)
272
+ continue;
273
+ const secondDot = tok.indexOf(".", firstDot + 1);
274
+ if (secondDot <= firstDot + 1)
275
+ continue;
276
+ const idPart = tok.slice(0, firstDot);
277
+ const noncePart = tok.slice(firstDot + 1, secondDot);
278
+ const sigPart = tok.slice(secondDot + 1);
279
+ if (!idPart || !noncePart || !sigPart)
280
+ continue;
281
+ const expected = computeOwnershipHmac(idPart, noncePart, secret);
282
+ if (timingSafeCompareStrings(sigPart, expected)) {
283
+ verified.add(idPart);
284
+ }
285
+ }
286
+ return Array.from(verified);
287
+ }
288
+ function findOwnershipTokenFor(rawTokens, feedbackId, secret) {
289
+ if (!rawTokens)
290
+ return null;
291
+ const parts = rawTokens
292
+ .split(",")
293
+ .map((s) => s.trim())
294
+ .filter(Boolean)
295
+ .slice(0, MAX_OWNERSHIP_TOKENS);
296
+ for (const tok of parts) {
297
+ if (verifyOwnershipToken(tok, feedbackId, secret)) {
298
+ return tok;
299
+ }
300
+ }
301
+ return null;
302
+ }
303
+ function combineRequestOwnershipTokens(request, url, extraToken) {
304
+ return [
305
+ typeof extraToken === "string" ? extraToken : "",
306
+ request.headers.get("x-context-drop-ownership-token") ?? "",
307
+ request.headers.get("x-context-drop-ownership-tokens") ?? "",
308
+ url.searchParams.get("ownership_token") ?? "",
309
+ url.searchParams.get("ownership_tokens") ?? ""
310
+ ]
311
+ .map((s) => s.trim())
312
+ .filter(Boolean)
313
+ .join(",");
314
+ }
315
+ function serializeOwnFeedback(record, ownershipToken) {
316
+ const elById = new Map();
317
+ for (const el of record.element_references) {
318
+ elById.set(String(el.id), el);
319
+ }
320
+ return {
321
+ id: record.id,
322
+ environment: record.environment,
323
+ status: record.status,
324
+ message: record.message,
325
+ page_url: record.page_url,
326
+ ownership_token: ownershipToken,
327
+ created_at: record.created_at,
328
+ updated_at: record.updated_at,
329
+ element_references: record.element_references.map((el) => ({
330
+ id: el.id,
331
+ client_ref: el.client_ref,
332
+ tag_name: el.tag_name,
333
+ selector: el.selector,
334
+ dom_path: el.dom_path,
335
+ text_content: el.text_content,
336
+ attributes_snapshot: el.attributes_snapshot ?? {},
337
+ bounding_rect: el.bounding_rect ?? {},
338
+ viewport: el.viewport ?? {},
339
+ metadata: el.metadata ?? {},
340
+ captured_at: el.captured_at
341
+ })),
342
+ attachments: record.attachments.map((att) => {
343
+ const linkedEl = att.element_reference_id !== null ? elById.get(String(att.element_reference_id)) : undefined;
344
+ return {
345
+ id: att.id,
346
+ attachment_type: att.attachment_type,
347
+ element_reference_id: att.element_reference_id,
348
+ element_reference_ref: linkedEl?.client_ref ?? null,
349
+ filename: att.filename,
350
+ content_type: att.content_type,
351
+ byte_size: att.byte_size,
352
+ metadata: att.metadata ?? {},
353
+ created_at: att.created_at
354
+ };
355
+ })
356
+ };
357
+ }
166
358
  function resolveWidgetBundleFilePath() {
167
359
  try {
168
360
  const currentFile = fileURLToPath(import.meta.url);
@@ -187,6 +379,18 @@ export function defineContextDropConfig(config) {
187
379
  export function createContextDropFetchHandler(config = {}) {
188
380
  const rateLimitStore = new Map();
189
381
  const getStorage = () => config.storage ?? getSharedDefaultStorage(config.storageDir);
382
+ const getOwnershipSecret = () => {
383
+ const explicit = config.ownershipSecret?.trim() ||
384
+ process.env.CONTEXT_DROP_SECRET_KEY?.trim() ||
385
+ process.env.CONTEXT_DROP_SECRET?.trim();
386
+ if (explicit) {
387
+ return crypto.createHash("sha256").update(explicit).digest();
388
+ }
389
+ const storageSecret = getStorage().getOwnershipSecret?.();
390
+ if (storageSecret)
391
+ return storageSecret;
392
+ return fallbackOwnershipSecret;
393
+ };
190
394
  const isEnabled = () => {
191
395
  if (config.enabled !== undefined)
192
396
  return Boolean(config.enabled);
@@ -295,6 +499,61 @@ export function createContextDropFetchHandler(config = {}) {
295
499
  existing.count += 1;
296
500
  return existing.count <= maxRequests;
297
501
  };
502
+ const parseNewAttachmentSpec = async (attObj, storage, uploadOpts) => {
503
+ const attTypeRaw = String(attObj["attachment_type"] ?? attObj["type"] ?? "image")
504
+ .trim()
505
+ .toLowerCase();
506
+ const attType = attTypeRaw === "screenshot" ? "screenshot" : "image";
507
+ const attMeta = sanitizeGenericMetadata(attObj["metadata"]);
508
+ const linkedRef = String(attObj["element_reference_ref"] ??
509
+ attObj["element_attachment_ref"] ??
510
+ attObj["client_ref"] ??
511
+ attMeta["element_attachment_ref"] ??
512
+ attMeta["client_ref"] ??
513
+ "").trim() || null;
514
+ const signedBlobId = String(attObj["signed_blob_id"] ?? "").trim();
515
+ const rawDataUrl = String(attObj["data_url"] ?? attObj["data"] ?? "").trim();
516
+ if (signedBlobId) {
517
+ const consumed = await storage.consumePendingBlob(signedBlobId);
518
+ if (!consumed) {
519
+ throw new UploadValidationError("Invalid or expired signed_blob_id");
520
+ }
521
+ if (consumed.dimensions && !attMeta["image_dimensions"]) {
522
+ attMeta["image_dimensions"] = {
523
+ width: consumed.dimensions[0],
524
+ height: consumed.dimensions[1]
525
+ };
526
+ }
527
+ return {
528
+ attachment_type: attType,
529
+ element_client_ref: linkedRef,
530
+ filename: consumed.filename,
531
+ content_type: consumed.content_type,
532
+ byte_size: consumed.byte_size,
533
+ data: consumed.data,
534
+ metadata: attMeta
535
+ };
536
+ }
537
+ if (rawDataUrl) {
538
+ const decoded = decodeBase64DataUrl(rawDataUrl, typeof attObj["filename"] === "string" ? attObj["filename"] : "screenshot.png", uploadOpts);
539
+ if (decoded.dimensions && !attMeta["image_dimensions"]) {
540
+ attMeta["image_dimensions"] = {
541
+ width: decoded.dimensions[0],
542
+ height: decoded.dimensions[1]
543
+ };
544
+ }
545
+ return {
546
+ attachment_type: attType,
547
+ element_client_ref: linkedRef,
548
+ filename: decoded.filename,
549
+ content_type: decoded.content_type,
550
+ byte_size: decoded.byte_size,
551
+ data: decoded.data,
552
+ metadata: attMeta
553
+ };
554
+ }
555
+ throw new UploadValidationError("Attachment must include signed_blob_id or data_url");
556
+ };
298
557
  const handleMcpEndpoint = async (request) => {
299
558
  const expectedApiKey = (config.mcp?.apiKey ??
300
559
  process.env.CONTEXT_DROP_MCP_API_KEY ??
@@ -351,10 +610,10 @@ export function createContextDropFetchHandler(config = {}) {
351
610
  };
352
611
  const handler = async (request) => {
353
612
  const url = new URL(request.url, "http://localhost");
354
- const subRoute = resolveSubRoute(url.pathname);
613
+ const parsedRoute = parseSubRoute(url.pathname);
355
614
  const method = request.method.toUpperCase();
356
615
  // Remote MCP endpoint has independent enablement & auth (matching Rails McpController)
357
- if (subRoute === "mcp" && method === "POST") {
616
+ if (parsedRoute.kind === "static" && parsedRoute.name === "mcp" && method === "POST") {
358
617
  return handleMcpEndpoint(request);
359
618
  }
360
619
  const corsHeaders = buildCorsHeaders(request, config.allowedOrigins);
@@ -371,14 +630,16 @@ export function createContextDropFetchHandler(config = {}) {
371
630
  if (!isEnabled()) {
372
631
  return jsonResponse({ error: "Not Found" }, 404, corsHeaders);
373
632
  }
374
- if (subRoute === "health" && method === "GET") {
633
+ if (parsedRoute.kind === "static" && parsedRoute.name === "health" && method === "GET") {
375
634
  return jsonResponse({
376
635
  status: "ok",
377
636
  environment: getEnvironment(),
378
637
  version: VERSION
379
638
  }, 200, corsHeaders);
380
639
  }
381
- if (subRoute === "assets/context_drop.js" && method === "GET") {
640
+ if (parsedRoute.kind === "static" &&
641
+ parsedRoute.name === "assets/context_drop.js" &&
642
+ method === "GET") {
382
643
  const bundlePath = resolveWidgetBundleFilePath();
383
644
  if (!bundlePath) {
384
645
  return new Response("Not Found", { status: 404, headers: corsHeaders });
@@ -393,14 +654,14 @@ export function createContextDropFetchHandler(config = {}) {
393
654
  }
394
655
  });
395
656
  }
396
- if (subRoute === "config" && method === "GET") {
657
+ if (parsedRoute.kind === "static" && parsedRoute.name === "config" && method === "GET") {
397
658
  const auth = await checkSubmissionAuth(request);
398
659
  if (!auth.ok) {
399
660
  return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
400
661
  }
401
662
  return jsonResponse(buildPublicWidgetConfig(), 200, corsHeaders);
402
663
  }
403
- if (subRoute === "attachments" && method === "POST") {
664
+ if (parsedRoute.kind === "static" && parsedRoute.name === "attachments" && method === "POST") {
404
665
  const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
405
666
  if (!originCheck.ok) {
406
667
  return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
@@ -437,7 +698,35 @@ export function createContextDropFetchHandler(config = {}) {
437
698
  return jsonResponse({ error: err.message || "Invalid attachment upload" }, 422, corsHeaders);
438
699
  }
439
700
  }
440
- if (subRoute === "feedback" && method === "POST") {
701
+ if (parsedRoute.kind === "static" && parsedRoute.name === "feedback" && method === "GET") {
702
+ const auth = await checkSubmissionAuth(request);
703
+ if (!auth.ok) {
704
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
705
+ }
706
+ const rawLimitParam = url.searchParams.get("limit");
707
+ const parsedLimit = rawLimitParam ? Number(rawLimitParam) : 20;
708
+ const limit = Math.max(1, Math.min(50, Number.isFinite(parsedLimit) ? Math.trunc(parsedLimit) : 20));
709
+ const secret = getOwnershipSecret();
710
+ const rawTokens = combineRequestOwnershipTokens(request, url);
711
+ const tokenIds = extractVerifiedOwnershipIds(rawTokens, secret);
712
+ const ownRes = await getStorage().listOwnFeedbacks({
713
+ submitter: auth.submitter,
714
+ session_id: extractHashedSessionId(request),
715
+ token_ids: tokenIds,
716
+ limit
717
+ });
718
+ const feedbacks = ownRes.records.map((rec) => {
719
+ const tok = findOwnershipTokenFor(rawTokens, rec.id, secret) ??
720
+ generateOwnershipToken(rec.id, secret);
721
+ return serializeOwnFeedback(rec, tok);
722
+ });
723
+ return jsonResponse({
724
+ total_count: ownRes.total,
725
+ total: ownRes.total,
726
+ feedbacks
727
+ }, 200, corsHeaders);
728
+ }
729
+ if (parsedRoute.kind === "static" && parsedRoute.name === "feedback" && method === "POST") {
441
730
  const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
442
731
  if (!originCheck.ok) {
443
732
  return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
@@ -475,62 +764,7 @@ export function createContextDropFetchHandler(config = {}) {
475
764
  const storage = getStorage();
476
765
  const preparedAttachments = [];
477
766
  for (const rawAtt of rawAttachments) {
478
- const attObj = asRecord(rawAtt);
479
- const attTypeRaw = String(attObj["attachment_type"] ?? attObj["type"] ?? "image")
480
- .trim()
481
- .toLowerCase();
482
- const attType = attTypeRaw === "screenshot" ? "screenshot" : "image";
483
- const attMeta = sanitizeGenericMetadata(attObj["metadata"]);
484
- const linkedRef = String(attObj["element_reference_ref"] ??
485
- attObj["element_attachment_ref"] ??
486
- attObj["client_ref"] ??
487
- attMeta["element_attachment_ref"] ??
488
- attMeta["client_ref"] ??
489
- "").trim() || null;
490
- const signedBlobId = String(attObj["signed_blob_id"] ?? "").trim();
491
- const rawDataUrl = String(attObj["data_url"] ?? attObj["data"] ?? "").trim();
492
- if (signedBlobId) {
493
- const consumed = await storage.consumePendingBlob(signedBlobId);
494
- if (!consumed) {
495
- throw new UploadValidationError("Invalid or expired signed_blob_id");
496
- }
497
- if (consumed.dimensions && !attMeta["image_dimensions"]) {
498
- attMeta["image_dimensions"] = {
499
- width: consumed.dimensions[0],
500
- height: consumed.dimensions[1]
501
- };
502
- }
503
- preparedAttachments.push({
504
- attachment_type: attType,
505
- element_client_ref: linkedRef,
506
- filename: consumed.filename,
507
- content_type: consumed.content_type,
508
- byte_size: consumed.byte_size,
509
- data: consumed.data,
510
- metadata: attMeta
511
- });
512
- }
513
- else if (rawDataUrl) {
514
- const decoded = decodeBase64DataUrl(rawDataUrl, typeof attObj["filename"] === "string" ? attObj["filename"] : "screenshot.png", uploadOpts);
515
- if (decoded.dimensions && !attMeta["image_dimensions"]) {
516
- attMeta["image_dimensions"] = {
517
- width: decoded.dimensions[0],
518
- height: decoded.dimensions[1]
519
- };
520
- }
521
- preparedAttachments.push({
522
- attachment_type: attType,
523
- element_client_ref: linkedRef,
524
- filename: decoded.filename,
525
- content_type: decoded.content_type,
526
- byte_size: decoded.byte_size,
527
- data: decoded.data,
528
- metadata: attMeta
529
- });
530
- }
531
- else {
532
- throw new UploadValidationError("Attachment must include signed_blob_id or data_url");
533
- }
767
+ preparedAttachments.push(await parseNewAttachmentSpec(asRecord(rawAtt), storage, uploadOpts));
534
768
  }
535
769
  const messageStr = String(payload["message"] ?? "").trim();
536
770
  const message = messageStr.length > 0 ? messageStr : null;
@@ -551,12 +785,15 @@ export function createContextDropFetchHandler(config = {}) {
551
785
  const userAgent = String(payload["user_agent"] ?? "").trim() ||
552
786
  request.headers.get("user-agent")?.trim() ||
553
787
  null;
788
+ const existingSessionToken = extractRawSessionCookie(request);
789
+ const rawSessionToken = existingSessionToken ?? crypto.randomBytes(16).toString("hex");
790
+ const hashedSessionId = hashSessionCookieValue(rawSessionToken);
554
791
  const created = await storage.createFeedback({
555
792
  environment: hostEnv,
556
793
  message,
557
794
  page_url: pageUrl,
558
795
  user_agent: userAgent,
559
- session_id: extractHashedSessionId(request),
796
+ session_id: hashedSessionId,
560
797
  submitter: auth.submitter,
561
798
  metadata: sanitizedMeta,
562
799
  element_references: sanitizedElements,
@@ -570,14 +807,22 @@ export function createContextDropFetchHandler(config = {}) {
570
807
  console.error("[context-drop] onFeedbackCreated callback error:", cbErr);
571
808
  }
572
809
  }
810
+ const ownershipToken = generateOwnershipToken(created.id, getOwnershipSecret());
811
+ const responseHeaders = { ...corsHeaders };
812
+ if (!existingSessionToken) {
813
+ responseHeaders["Set-Cookie"] = buildSessionSetCookieHeader(rawSessionToken, url.protocol === "https:");
814
+ }
573
815
  return jsonResponse({
574
816
  id: created.id,
575
817
  environment: created.environment,
576
818
  status: created.status,
577
819
  attachments_count: created.attachments.length,
578
820
  element_references_count: created.element_references.length,
579
- created_at: created.created_at
580
- }, 201, corsHeaders);
821
+ ownership_token: ownershipToken,
822
+ feedback: serializeOwnFeedback(created, ownershipToken),
823
+ created_at: created.created_at,
824
+ updated_at: created.updated_at
825
+ }, 201, responseHeaders);
581
826
  }
582
827
  catch (err) {
583
828
  if (err instanceof SensitiveElementError || err instanceof UploadValidationError) {
@@ -586,6 +831,261 @@ export function createContextDropFetchHandler(config = {}) {
586
831
  return jsonResponse({ error: err.message || "Failed to process feedback" }, 422, corsHeaders);
587
832
  }
588
833
  }
834
+ if (parsedRoute.kind === "feedback_item" &&
835
+ (method === "PATCH" || method === "PUT")) {
836
+ const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
837
+ if (!originCheck.ok) {
838
+ return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
839
+ }
840
+ const auth = await checkSubmissionAuth(request);
841
+ if (!auth.ok) {
842
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
843
+ }
844
+ if (!checkRateLimit(request)) {
845
+ return jsonResponse({ error: "Rate limit exceeded. Please try again later." }, 429, corsHeaders);
846
+ }
847
+ const storage = getStorage();
848
+ const existing = await storage.getFeedback(parsedRoute.feedbackId);
849
+ if (!existing || existing.deleted_at) {
850
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
851
+ }
852
+ try {
853
+ const rawJson = (await request.json().catch(() => ({})));
854
+ const payload = rawJson["feedback"] && typeof rawJson["feedback"] === "object"
855
+ ? asRecord(rawJson["feedback"])
856
+ : asRecord(rawJson);
857
+ const secret = getOwnershipSecret();
858
+ const rawTokens = combineRequestOwnershipTokens(request, url, payload["ownership_token"] ?? rawJson["ownership_token"]);
859
+ const tokenIds = extractVerifiedOwnershipIds(rawTokens, secret);
860
+ if (!matchesOwnFeedback(existing, {
861
+ submitter: auth.submitter,
862
+ session_id: extractHashedSessionId(request),
863
+ token_ids: tokenIds
864
+ })) {
865
+ return jsonResponse({ error: "Forbidden" }, 403, corsHeaders);
866
+ }
867
+ const hasMessageKey = Object.prototype.hasOwnProperty.call(payload, "message");
868
+ const hasMetadataKey = Object.prototype.hasOwnProperty.call(payload, "metadata");
869
+ const hasElementsKey = Object.prototype.hasOwnProperty.call(payload, "element_references");
870
+ const hasAttachmentsKey = Object.prototype.hasOwnProperty.call(payload, "attachments");
871
+ const rawElements = hasElementsKey
872
+ ? Array.isArray(payload["element_references"])
873
+ ? payload["element_references"]
874
+ : []
875
+ : undefined;
876
+ const rawAttachments = hasAttachmentsKey
877
+ ? Array.isArray(payload["attachments"])
878
+ ? payload["attachments"]
879
+ : []
880
+ : undefined;
881
+ const maxAttachments = config.limits?.maxAttachments ?? 10;
882
+ const maxElements = config.limits?.maxElementReferences ?? 10;
883
+ if (rawAttachments && rawAttachments.length > maxAttachments) {
884
+ return jsonResponse({
885
+ error: `Attachments count (${rawAttachments.length}) exceeds maximum allowed (${maxAttachments})`
886
+ }, 422, corsHeaders);
887
+ }
888
+ if (rawElements && rawElements.length > maxElements) {
889
+ return jsonResponse({
890
+ error: `Element references count (${rawElements.length}) exceeds maximum allowed (${maxElements})`
891
+ }, 422, corsHeaders);
892
+ }
893
+ const sanitizedElements = rawElements
894
+ ? rawElements.map((el) => sanitizeElementReference(el))
895
+ : undefined;
896
+ let preparedAttachmentSpecs;
897
+ if (rawAttachments) {
898
+ const uploadOpts = getUploadValidationOptions();
899
+ const existingAttIds = new Set(existing.attachments.map((a) => String(a.id)));
900
+ preparedAttachmentSpecs = [];
901
+ for (const rawAtt of rawAttachments) {
902
+ const attObj = asRecord(rawAtt);
903
+ const hasNewBinary = Boolean(String(attObj["signed_blob_id"] ?? "").trim() ||
904
+ String(attObj["data_url"] ?? attObj["data"] ?? "").trim());
905
+ const existingIdRaw = String(attObj["existing_id"] ?? (!hasNewBinary ? attObj["id"] ?? "" : "")).trim();
906
+ if (existingIdRaw) {
907
+ if (!existingAttIds.has(existingIdRaw)) {
908
+ return jsonResponse({ error: "Attachment does not belong to this feedback" }, 422, corsHeaders);
909
+ }
910
+ const hasCustomMeta = Object.prototype.hasOwnProperty.call(attObj, "metadata") &&
911
+ typeof attObj["metadata"] === "object" &&
912
+ attObj["metadata"] !== null;
913
+ const sanitizedCustomMeta = hasCustomMeta
914
+ ? sanitizeGenericMetadata(attObj["metadata"])
915
+ : undefined;
916
+ const hasExplicitLinkKey = Object.prototype.hasOwnProperty.call(attObj, "element_reference_ref") ||
917
+ Object.prototype.hasOwnProperty.call(attObj, "element_attachment_ref") ||
918
+ Object.prototype.hasOwnProperty.call(attObj, "client_ref");
919
+ const linkedRef = hasExplicitLinkKey
920
+ ? String(attObj["element_reference_ref"] ??
921
+ attObj["element_attachment_ref"] ??
922
+ attObj["client_ref"] ??
923
+ "").trim() || null
924
+ : undefined;
925
+ preparedAttachmentSpecs.push({
926
+ kind: "retain",
927
+ existing_id: existingIdRaw,
928
+ element_client_ref: linkedRef,
929
+ metadata: sanitizedCustomMeta,
930
+ update_metadata: hasCustomMeta
931
+ });
932
+ }
933
+ else {
934
+ const createdSpec = await parseNewAttachmentSpec(attObj, storage, uploadOpts);
935
+ preparedAttachmentSpecs.push({
936
+ kind: "create",
937
+ ...createdSpec
938
+ });
939
+ }
940
+ }
941
+ }
942
+ const nextMessage = hasMessageKey
943
+ ? String(payload["message"] ?? "").trim() || null
944
+ : existing.message;
945
+ const nextElementsCount = sanitizedElements
946
+ ? sanitizedElements.length
947
+ : existing.element_references.length;
948
+ const nextAttachmentsCount = preparedAttachmentSpecs
949
+ ? preparedAttachmentSpecs.length
950
+ : existing.attachments.length;
951
+ if (!nextMessage && nextElementsCount === 0 && nextAttachmentsCount === 0) {
952
+ return jsonResponse({
953
+ error: "Feedback must include a message, an attachment, or a selected DOM element"
954
+ }, 422, corsHeaders);
955
+ }
956
+ let nextMetadata;
957
+ if (hasMetadataKey) {
958
+ nextMetadata = sanitizeGenericMetadata(payload["metadata"]);
959
+ nextMetadata["environment"] = existing.environment;
960
+ }
961
+ const updated = await storage.updateFeedback(existing.id, {
962
+ ...(hasMessageKey ? { message: nextMessage } : {}),
963
+ ...(nextMetadata !== undefined ? { metadata: nextMetadata } : {}),
964
+ ...(sanitizedElements !== undefined ? { element_references: sanitizedElements } : {}),
965
+ ...(preparedAttachmentSpecs !== undefined ? { attachments: preparedAttachmentSpecs } : {})
966
+ });
967
+ if (!updated) {
968
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
969
+ }
970
+ if (config.onFeedbackUpdated) {
971
+ try {
972
+ await config.onFeedbackUpdated(updated);
973
+ }
974
+ catch (cbErr) {
975
+ console.error("[context-drop] onFeedbackUpdated callback error:", cbErr);
976
+ }
977
+ }
978
+ const ownershipToken = findOwnershipTokenFor(rawTokens, updated.id, secret) ??
979
+ generateOwnershipToken(updated.id, secret);
980
+ return jsonResponse({
981
+ id: updated.id,
982
+ environment: updated.environment,
983
+ status: updated.status,
984
+ message: updated.message,
985
+ attachments_count: updated.attachments.length,
986
+ element_references_count: updated.element_references.length,
987
+ ownership_token: ownershipToken,
988
+ feedback: serializeOwnFeedback(updated, ownershipToken),
989
+ created_at: updated.created_at,
990
+ updated_at: updated.updated_at
991
+ }, 200, corsHeaders);
992
+ }
993
+ catch (err) {
994
+ if (err instanceof SensitiveElementError || err instanceof UploadValidationError) {
995
+ return jsonResponse({ error: err.message }, err.status, corsHeaders);
996
+ }
997
+ return jsonResponse({ error: err.message || "Failed to update feedback" }, 422, corsHeaders);
998
+ }
999
+ }
1000
+ if (parsedRoute.kind === "feedback_item" && method === "DELETE") {
1001
+ const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
1002
+ if (!originCheck.ok) {
1003
+ return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
1004
+ }
1005
+ const auth = await checkSubmissionAuth(request);
1006
+ if (!auth.ok) {
1007
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
1008
+ }
1009
+ if (!checkRateLimit(request)) {
1010
+ return jsonResponse({ error: "Rate limit exceeded. Please try again later." }, 429, corsHeaders);
1011
+ }
1012
+ const storage = getStorage();
1013
+ const existing = await storage.getFeedback(parsedRoute.feedbackId);
1014
+ if (!existing || existing.deleted_at) {
1015
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
1016
+ }
1017
+ const rawJson = (await request.json().catch(() => ({})));
1018
+ const payload = rawJson["feedback"] && typeof rawJson["feedback"] === "object"
1019
+ ? asRecord(rawJson["feedback"])
1020
+ : asRecord(rawJson);
1021
+ const secret = getOwnershipSecret();
1022
+ const rawTokens = combineRequestOwnershipTokens(request, url, payload["ownership_token"] ?? rawJson["ownership_token"]);
1023
+ const tokenIds = extractVerifiedOwnershipIds(rawTokens, secret);
1024
+ if (!matchesOwnFeedback(existing, {
1025
+ submitter: auth.submitter,
1026
+ session_id: extractHashedSessionId(request),
1027
+ token_ids: tokenIds
1028
+ })) {
1029
+ return jsonResponse({ error: "Forbidden" }, 403, corsHeaders);
1030
+ }
1031
+ const deleted = await storage.softDeleteFeedback(existing.id);
1032
+ if (!deleted) {
1033
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
1034
+ }
1035
+ if (config.onFeedbackDeleted) {
1036
+ try {
1037
+ await config.onFeedbackDeleted(deleted);
1038
+ }
1039
+ catch (cbErr) {
1040
+ console.error("[context-drop] onFeedbackDeleted callback error:", cbErr);
1041
+ }
1042
+ }
1043
+ return jsonResponse({
1044
+ id: deleted.id,
1045
+ deleted: true,
1046
+ deleted_at: deleted.deleted_at ?? new Date().toISOString()
1047
+ }, 200, corsHeaders);
1048
+ }
1049
+ if (parsedRoute.kind === "feedback_attachment" && method === "GET") {
1050
+ const auth = await checkSubmissionAuth(request);
1051
+ if (!auth.ok) {
1052
+ return new Response("Forbidden", { status: auth.status, headers: corsHeaders });
1053
+ }
1054
+ const storage = getStorage();
1055
+ const existing = await storage.getFeedback(parsedRoute.feedbackId);
1056
+ if (!existing || existing.deleted_at) {
1057
+ return new Response("Not Found", { status: 404, headers: corsHeaders });
1058
+ }
1059
+ const secret = getOwnershipSecret();
1060
+ const rawTokens = combineRequestOwnershipTokens(request, url);
1061
+ const tokenIds = extractVerifiedOwnershipIds(rawTokens, secret);
1062
+ if (!matchesOwnFeedback(existing, {
1063
+ submitter: auth.submitter,
1064
+ session_id: extractHashedSessionId(request),
1065
+ token_ids: tokenIds
1066
+ })) {
1067
+ return new Response("Forbidden", { status: 403, headers: corsHeaders });
1068
+ }
1069
+ const attMeta = existing.attachments.find((a) => String(a.id) === String(parsedRoute.attachmentId));
1070
+ if (!attMeta) {
1071
+ return new Response("Not Found", { status: 404, headers: corsHeaders });
1072
+ }
1073
+ const bytes = await storage.getAttachmentBytes(attMeta.id);
1074
+ if (!bytes) {
1075
+ return new Response("Not Found", { status: 404, headers: corsHeaders });
1076
+ }
1077
+ const bodyCopy = new Uint8Array(bytes.byteLength);
1078
+ bodyCopy.set(bytes);
1079
+ return new Response(bodyCopy, {
1080
+ status: 200,
1081
+ headers: {
1082
+ "Content-Type": attMeta.content_type || "image/png",
1083
+ "Cache-Control": "private, max-age=3600",
1084
+ "Content-Security-Policy": "default-src 'none'; sandbox",
1085
+ ...corsHeaders
1086
+ }
1087
+ });
1088
+ }
589
1089
  return jsonResponse({ error: "Not Found" }, 404, corsHeaders);
590
1090
  };
591
1091
  return Object.assign(handler, {
@@ -599,7 +1099,7 @@ export function createContextDropFetchHandler(config = {}) {
599
1099
  * @example
600
1100
  * ```ts
601
1101
  * import { createContextDropNextHandler } from "context-drop/next/server";
602
- * export const { GET, POST, OPTIONS } = createContextDropNextHandler();
1102
+ * export const { GET, POST, PATCH, PUT, DELETE, OPTIONS } = createContextDropNextHandler();
603
1103
  * ```
604
1104
  */
605
1105
  export function createContextDropNextHandler(config = {}) {
@@ -607,6 +1107,9 @@ export function createContextDropNextHandler(config = {}) {
607
1107
  return {
608
1108
  GET: (request) => fetchHandler(request),
609
1109
  POST: (request) => fetchHandler(request),
1110
+ PATCH: (request) => fetchHandler(request),
1111
+ PUT: (request) => fetchHandler(request),
1112
+ DELETE: (request) => fetchHandler(request),
610
1113
  OPTIONS: (request) => fetchHandler(request),
611
1114
  handler: fetchHandler
612
1115
  };