context-drop 0.2.0 → 0.3.1

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,91 @@ 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)
145
+ return null;
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);
167
+ }
168
+ function extractHashedSessionId(request) {
169
+ const rawToken = extractRawSessionCookie(request);
170
+ if (!rawToken)
139
171
  return null;
140
- return crypto.createHash("sha256").update(cookieHeader).digest("hex").slice(0, 32);
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("; ");
141
186
  }
142
- function resolveSubRoute(pathname) {
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 fbCommentsMatch = /\/feedback\/([^/]+)\/comments$/.exec(clean);
198
+ if (fbCommentsMatch) {
199
+ return {
200
+ kind: "feedback_comments",
201
+ feedbackId: decodeURIComponent(fbCommentsMatch[1])
202
+ };
203
+ }
204
+ const fbItemMatch = /\/feedback\/([^/]+)$/.exec(clean);
205
+ if (fbItemMatch) {
206
+ return {
207
+ kind: "feedback_item",
208
+ feedbackId: decodeURIComponent(fbItemMatch[1])
209
+ };
210
+ }
211
+ if (clean.endsWith("/assets/context_drop.js")) {
212
+ return { kind: "static", name: "assets/context_drop.js" };
213
+ }
146
214
  if (clean.endsWith("/config"))
147
- return "config";
215
+ return { kind: "static", name: "config" };
148
216
  if (clean.endsWith("/attachments"))
149
- return "attachments";
217
+ return { kind: "static", name: "attachments" };
150
218
  if (clean.endsWith("/feedback"))
151
- return "feedback";
219
+ return { kind: "static", name: "feedback" };
152
220
  if (clean.endsWith("/health"))
153
- return "health";
221
+ return { kind: "static", name: "health" };
154
222
  if (clean.endsWith("/mcp"))
155
- return "mcp";
156
- return "";
223
+ return { kind: "static", name: "mcp" };
224
+ return { kind: "unknown" };
157
225
  }
158
226
  function timingSafeCompareStrings(a, b) {
159
227
  const bufA = Buffer.from(a, "utf8");
@@ -163,6 +231,158 @@ function timingSafeCompareStrings(a, b) {
163
231
  }
164
232
  return crypto.timingSafeEqual(bufA, bufB);
165
233
  }
234
+ function computeOwnershipHmac(idStr, nonce, secret) {
235
+ return crypto
236
+ .createHmac("sha256", secret)
237
+ .update(`${OWNERSHIP_TOKEN_DOMAIN}:${idStr}:${nonce}`)
238
+ .digest("hex");
239
+ }
240
+ export function generateOwnershipToken(feedbackId, secret) {
241
+ const idStr = String(feedbackId).trim();
242
+ const nonce = crypto.randomBytes(8).toString("hex");
243
+ const sig = computeOwnershipHmac(idStr, nonce, secret);
244
+ return `${idStr}.${nonce}.${sig}`;
245
+ }
246
+ export function verifyOwnershipToken(token, feedbackId, secret) {
247
+ if (!token)
248
+ return false;
249
+ const raw = token.trim();
250
+ const targetId = String(feedbackId).trim();
251
+ if (!raw || !targetId)
252
+ return false;
253
+ const firstDot = raw.indexOf(".");
254
+ if (firstDot <= 0)
255
+ return false;
256
+ const secondDot = raw.indexOf(".", firstDot + 1);
257
+ if (secondDot <= firstDot + 1)
258
+ return false;
259
+ const idPart = raw.slice(0, firstDot);
260
+ const noncePart = raw.slice(firstDot + 1, secondDot);
261
+ const sigPart = raw.slice(secondDot + 1);
262
+ if (idPart !== targetId || !noncePart || !sigPart)
263
+ return false;
264
+ const expected = computeOwnershipHmac(targetId, noncePart, secret);
265
+ return timingSafeCompareStrings(sigPart, expected);
266
+ }
267
+ export function extractVerifiedOwnershipIds(rawTokens, secret) {
268
+ if (!rawTokens)
269
+ return [];
270
+ const parts = rawTokens
271
+ .split(",")
272
+ .map((s) => s.trim())
273
+ .filter(Boolean)
274
+ .slice(0, MAX_OWNERSHIP_TOKENS);
275
+ const verified = new Set();
276
+ for (const tok of parts) {
277
+ const firstDot = tok.indexOf(".");
278
+ if (firstDot <= 0)
279
+ continue;
280
+ const secondDot = tok.indexOf(".", firstDot + 1);
281
+ if (secondDot <= firstDot + 1)
282
+ continue;
283
+ const idPart = tok.slice(0, firstDot);
284
+ const noncePart = tok.slice(firstDot + 1, secondDot);
285
+ const sigPart = tok.slice(secondDot + 1);
286
+ if (!idPart || !noncePart || !sigPart)
287
+ continue;
288
+ const expected = computeOwnershipHmac(idPart, noncePart, secret);
289
+ if (timingSafeCompareStrings(sigPart, expected)) {
290
+ verified.add(idPart);
291
+ }
292
+ }
293
+ return Array.from(verified);
294
+ }
295
+ function findOwnershipTokenFor(rawTokens, feedbackId, secret) {
296
+ if (!rawTokens)
297
+ return null;
298
+ const parts = rawTokens
299
+ .split(",")
300
+ .map((s) => s.trim())
301
+ .filter(Boolean)
302
+ .slice(0, MAX_OWNERSHIP_TOKENS);
303
+ for (const tok of parts) {
304
+ if (verifyOwnershipToken(tok, feedbackId, secret)) {
305
+ return tok;
306
+ }
307
+ }
308
+ return null;
309
+ }
310
+ function combineRequestOwnershipTokens(request, url, extraToken) {
311
+ return [
312
+ typeof extraToken === "string" ? extraToken : "",
313
+ request.headers.get("x-context-drop-ownership-token") ?? "",
314
+ request.headers.get("x-context-drop-ownership-tokens") ?? "",
315
+ url.searchParams.get("ownership_token") ?? "",
316
+ url.searchParams.get("ownership_tokens") ?? ""
317
+ ]
318
+ .map((s) => s.trim())
319
+ .filter(Boolean)
320
+ .join(",");
321
+ }
322
+ function serializeOwnFeedback(record, ownershipToken) {
323
+ const elById = new Map();
324
+ for (const el of record.element_references) {
325
+ elById.set(String(el.id), el);
326
+ }
327
+ return {
328
+ id: record.id,
329
+ environment: record.environment,
330
+ status: record.status,
331
+ message: record.message,
332
+ page_url: record.page_url,
333
+ ownership_token: ownershipToken,
334
+ created_at: record.created_at,
335
+ updated_at: record.updated_at,
336
+ element_references: record.element_references.map((el) => ({
337
+ id: el.id,
338
+ client_ref: el.client_ref,
339
+ tag_name: el.tag_name,
340
+ selector: el.selector,
341
+ dom_path: el.dom_path,
342
+ text_content: el.text_content,
343
+ attributes_snapshot: el.attributes_snapshot ?? {},
344
+ bounding_rect: el.bounding_rect ?? {},
345
+ viewport: el.viewport ?? {},
346
+ metadata: el.metadata ?? {},
347
+ captured_at: el.captured_at
348
+ })),
349
+ attachments: record.attachments.map((att) => {
350
+ const linkedEl = att.element_reference_id !== null ? elById.get(String(att.element_reference_id)) : undefined;
351
+ return {
352
+ id: att.id,
353
+ attachment_type: att.attachment_type,
354
+ element_reference_id: att.element_reference_id,
355
+ element_reference_ref: linkedEl?.client_ref ?? null,
356
+ filename: att.filename,
357
+ content_type: att.content_type,
358
+ byte_size: att.byte_size,
359
+ metadata: att.metadata ?? {},
360
+ created_at: att.created_at
361
+ };
362
+ }),
363
+ comments_count: (record.comments ?? []).length,
364
+ comments: (record.comments ?? []).map((comment) => ({
365
+ id: comment.id,
366
+ feedback_id: comment.feedback_id,
367
+ author_label: comment.author_label,
368
+ author_type: comment.author_type ?? null,
369
+ body: comment.body,
370
+ attachments: (comment.attachments ?? []).map((att) => ({
371
+ id: att.id,
372
+ attachment_type: att.attachment_type,
373
+ element_reference_id: null,
374
+ element_reference_ref: null,
375
+ filename: att.filename,
376
+ content_type: att.content_type,
377
+ byte_size: att.byte_size,
378
+ metadata: att.metadata ?? {},
379
+ created_at: att.created_at
380
+ })),
381
+ created_at: comment.created_at,
382
+ updated_at: comment.updated_at
383
+ }))
384
+ };
385
+ }
166
386
  function resolveWidgetBundleFilePath() {
167
387
  try {
168
388
  const currentFile = fileURLToPath(import.meta.url);
@@ -187,6 +407,18 @@ export function defineContextDropConfig(config) {
187
407
  export function createContextDropFetchHandler(config = {}) {
188
408
  const rateLimitStore = new Map();
189
409
  const getStorage = () => config.storage ?? getSharedDefaultStorage(config.storageDir);
410
+ const getOwnershipSecret = () => {
411
+ const explicit = config.ownershipSecret?.trim() ||
412
+ process.env.CONTEXT_DROP_SECRET_KEY?.trim() ||
413
+ process.env.CONTEXT_DROP_SECRET?.trim();
414
+ if (explicit) {
415
+ return crypto.createHash("sha256").update(explicit).digest();
416
+ }
417
+ const storageSecret = getStorage().getOwnershipSecret?.();
418
+ if (storageSecret)
419
+ return storageSecret;
420
+ return fallbackOwnershipSecret;
421
+ };
190
422
  const isEnabled = () => {
191
423
  if (config.enabled !== undefined)
192
424
  return Boolean(config.enabled);
@@ -295,6 +527,61 @@ export function createContextDropFetchHandler(config = {}) {
295
527
  existing.count += 1;
296
528
  return existing.count <= maxRequests;
297
529
  };
530
+ const parseNewAttachmentSpec = async (attObj, storage, uploadOpts) => {
531
+ const attTypeRaw = String(attObj["attachment_type"] ?? attObj["type"] ?? "image")
532
+ .trim()
533
+ .toLowerCase();
534
+ const attType = attTypeRaw === "screenshot" ? "screenshot" : "image";
535
+ const attMeta = sanitizeGenericMetadata(attObj["metadata"]);
536
+ const linkedRef = String(attObj["element_reference_ref"] ??
537
+ attObj["element_attachment_ref"] ??
538
+ attObj["client_ref"] ??
539
+ attMeta["element_attachment_ref"] ??
540
+ attMeta["client_ref"] ??
541
+ "").trim() || null;
542
+ const signedBlobId = String(attObj["signed_blob_id"] ?? "").trim();
543
+ const rawDataUrl = String(attObj["data_url"] ?? attObj["data"] ?? "").trim();
544
+ if (signedBlobId) {
545
+ const consumed = await storage.consumePendingBlob(signedBlobId);
546
+ if (!consumed) {
547
+ throw new UploadValidationError("Invalid or expired signed_blob_id");
548
+ }
549
+ if (consumed.dimensions && !attMeta["image_dimensions"]) {
550
+ attMeta["image_dimensions"] = {
551
+ width: consumed.dimensions[0],
552
+ height: consumed.dimensions[1]
553
+ };
554
+ }
555
+ return {
556
+ attachment_type: attType,
557
+ element_client_ref: linkedRef,
558
+ filename: consumed.filename,
559
+ content_type: consumed.content_type,
560
+ byte_size: consumed.byte_size,
561
+ data: consumed.data,
562
+ metadata: attMeta
563
+ };
564
+ }
565
+ if (rawDataUrl) {
566
+ const decoded = decodeBase64DataUrl(rawDataUrl, typeof attObj["filename"] === "string" ? attObj["filename"] : "screenshot.png", uploadOpts);
567
+ if (decoded.dimensions && !attMeta["image_dimensions"]) {
568
+ attMeta["image_dimensions"] = {
569
+ width: decoded.dimensions[0],
570
+ height: decoded.dimensions[1]
571
+ };
572
+ }
573
+ return {
574
+ attachment_type: attType,
575
+ element_client_ref: linkedRef,
576
+ filename: decoded.filename,
577
+ content_type: decoded.content_type,
578
+ byte_size: decoded.byte_size,
579
+ data: decoded.data,
580
+ metadata: attMeta
581
+ };
582
+ }
583
+ throw new UploadValidationError("Attachment must include signed_blob_id or data_url");
584
+ };
298
585
  const handleMcpEndpoint = async (request) => {
299
586
  const expectedApiKey = (config.mcp?.apiKey ??
300
587
  process.env.CONTEXT_DROP_MCP_API_KEY ??
@@ -351,10 +638,10 @@ export function createContextDropFetchHandler(config = {}) {
351
638
  };
352
639
  const handler = async (request) => {
353
640
  const url = new URL(request.url, "http://localhost");
354
- const subRoute = resolveSubRoute(url.pathname);
641
+ const parsedRoute = parseSubRoute(url.pathname);
355
642
  const method = request.method.toUpperCase();
356
643
  // Remote MCP endpoint has independent enablement & auth (matching Rails McpController)
357
- if (subRoute === "mcp" && method === "POST") {
644
+ if (parsedRoute.kind === "static" && parsedRoute.name === "mcp" && method === "POST") {
358
645
  return handleMcpEndpoint(request);
359
646
  }
360
647
  const corsHeaders = buildCorsHeaders(request, config.allowedOrigins);
@@ -371,14 +658,16 @@ export function createContextDropFetchHandler(config = {}) {
371
658
  if (!isEnabled()) {
372
659
  return jsonResponse({ error: "Not Found" }, 404, corsHeaders);
373
660
  }
374
- if (subRoute === "health" && method === "GET") {
661
+ if (parsedRoute.kind === "static" && parsedRoute.name === "health" && method === "GET") {
375
662
  return jsonResponse({
376
663
  status: "ok",
377
664
  environment: getEnvironment(),
378
665
  version: VERSION
379
666
  }, 200, corsHeaders);
380
667
  }
381
- if (subRoute === "assets/context_drop.js" && method === "GET") {
668
+ if (parsedRoute.kind === "static" &&
669
+ parsedRoute.name === "assets/context_drop.js" &&
670
+ method === "GET") {
382
671
  const bundlePath = resolveWidgetBundleFilePath();
383
672
  if (!bundlePath) {
384
673
  return new Response("Not Found", { status: 404, headers: corsHeaders });
@@ -393,14 +682,14 @@ export function createContextDropFetchHandler(config = {}) {
393
682
  }
394
683
  });
395
684
  }
396
- if (subRoute === "config" && method === "GET") {
685
+ if (parsedRoute.kind === "static" && parsedRoute.name === "config" && method === "GET") {
397
686
  const auth = await checkSubmissionAuth(request);
398
687
  if (!auth.ok) {
399
688
  return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
400
689
  }
401
690
  return jsonResponse(buildPublicWidgetConfig(), 200, corsHeaders);
402
691
  }
403
- if (subRoute === "attachments" && method === "POST") {
692
+ if (parsedRoute.kind === "static" && parsedRoute.name === "attachments" && method === "POST") {
404
693
  const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
405
694
  if (!originCheck.ok) {
406
695
  return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
@@ -437,7 +726,35 @@ export function createContextDropFetchHandler(config = {}) {
437
726
  return jsonResponse({ error: err.message || "Invalid attachment upload" }, 422, corsHeaders);
438
727
  }
439
728
  }
440
- if (subRoute === "feedback" && method === "POST") {
729
+ if (parsedRoute.kind === "static" && parsedRoute.name === "feedback" && method === "GET") {
730
+ const auth = await checkSubmissionAuth(request);
731
+ if (!auth.ok) {
732
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
733
+ }
734
+ const rawLimitParam = url.searchParams.get("limit");
735
+ const parsedLimit = rawLimitParam ? Number(rawLimitParam) : 20;
736
+ const limit = Math.max(1, Math.min(50, Number.isFinite(parsedLimit) ? Math.trunc(parsedLimit) : 20));
737
+ const secret = getOwnershipSecret();
738
+ const rawTokens = combineRequestOwnershipTokens(request, url);
739
+ const tokenIds = extractVerifiedOwnershipIds(rawTokens, secret);
740
+ const ownRes = await getStorage().listOwnFeedbacks({
741
+ submitter: auth.submitter,
742
+ session_id: extractHashedSessionId(request),
743
+ token_ids: tokenIds,
744
+ limit
745
+ });
746
+ const feedbacks = ownRes.records.map((rec) => {
747
+ const tok = findOwnershipTokenFor(rawTokens, rec.id, secret) ??
748
+ generateOwnershipToken(rec.id, secret);
749
+ return serializeOwnFeedback(rec, tok);
750
+ });
751
+ return jsonResponse({
752
+ total_count: ownRes.total,
753
+ total: ownRes.total,
754
+ feedbacks
755
+ }, 200, corsHeaders);
756
+ }
757
+ if (parsedRoute.kind === "static" && parsedRoute.name === "feedback" && method === "POST") {
441
758
  const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
442
759
  if (!originCheck.ok) {
443
760
  return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
@@ -475,62 +792,7 @@ export function createContextDropFetchHandler(config = {}) {
475
792
  const storage = getStorage();
476
793
  const preparedAttachments = [];
477
794
  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
- }
795
+ preparedAttachments.push(await parseNewAttachmentSpec(asRecord(rawAtt), storage, uploadOpts));
534
796
  }
535
797
  const messageStr = String(payload["message"] ?? "").trim();
536
798
  const message = messageStr.length > 0 ? messageStr : null;
@@ -551,12 +813,15 @@ export function createContextDropFetchHandler(config = {}) {
551
813
  const userAgent = String(payload["user_agent"] ?? "").trim() ||
552
814
  request.headers.get("user-agent")?.trim() ||
553
815
  null;
816
+ const existingSessionToken = extractRawSessionCookie(request);
817
+ const rawSessionToken = existingSessionToken ?? crypto.randomBytes(16).toString("hex");
818
+ const hashedSessionId = hashSessionCookieValue(rawSessionToken);
554
819
  const created = await storage.createFeedback({
555
820
  environment: hostEnv,
556
821
  message,
557
822
  page_url: pageUrl,
558
823
  user_agent: userAgent,
559
- session_id: extractHashedSessionId(request),
824
+ session_id: hashedSessionId,
560
825
  submitter: auth.submitter,
561
826
  metadata: sanitizedMeta,
562
827
  element_references: sanitizedElements,
@@ -570,14 +835,22 @@ export function createContextDropFetchHandler(config = {}) {
570
835
  console.error("[context-drop] onFeedbackCreated callback error:", cbErr);
571
836
  }
572
837
  }
838
+ const ownershipToken = generateOwnershipToken(created.id, getOwnershipSecret());
839
+ const responseHeaders = { ...corsHeaders };
840
+ if (!existingSessionToken) {
841
+ responseHeaders["Set-Cookie"] = buildSessionSetCookieHeader(rawSessionToken, url.protocol === "https:");
842
+ }
573
843
  return jsonResponse({
574
844
  id: created.id,
575
845
  environment: created.environment,
576
846
  status: created.status,
577
847
  attachments_count: created.attachments.length,
578
848
  element_references_count: created.element_references.length,
579
- created_at: created.created_at
580
- }, 201, corsHeaders);
849
+ ownership_token: ownershipToken,
850
+ feedback: serializeOwnFeedback(created, ownershipToken),
851
+ created_at: created.created_at,
852
+ updated_at: created.updated_at
853
+ }, 201, responseHeaders);
581
854
  }
582
855
  catch (err) {
583
856
  if (err instanceof SensitiveElementError || err instanceof UploadValidationError) {
@@ -586,6 +859,359 @@ export function createContextDropFetchHandler(config = {}) {
586
859
  return jsonResponse({ error: err.message || "Failed to process feedback" }, 422, corsHeaders);
587
860
  }
588
861
  }
862
+ if (parsedRoute.kind === "feedback_item" &&
863
+ (method === "PATCH" || method === "PUT")) {
864
+ const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
865
+ if (!originCheck.ok) {
866
+ return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
867
+ }
868
+ const auth = await checkSubmissionAuth(request);
869
+ if (!auth.ok) {
870
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
871
+ }
872
+ if (!checkRateLimit(request)) {
873
+ return jsonResponse({ error: "Rate limit exceeded. Please try again later." }, 429, corsHeaders);
874
+ }
875
+ const storage = getStorage();
876
+ const existing = await storage.getFeedback(parsedRoute.feedbackId);
877
+ if (!existing || existing.deleted_at) {
878
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
879
+ }
880
+ try {
881
+ const rawJson = (await request.json().catch(() => ({})));
882
+ const payload = rawJson["feedback"] && typeof rawJson["feedback"] === "object"
883
+ ? asRecord(rawJson["feedback"])
884
+ : asRecord(rawJson);
885
+ const secret = getOwnershipSecret();
886
+ const rawTokens = combineRequestOwnershipTokens(request, url, payload["ownership_token"] ?? rawJson["ownership_token"]);
887
+ const tokenIds = extractVerifiedOwnershipIds(rawTokens, secret);
888
+ if (!matchesOwnFeedback(existing, {
889
+ submitter: auth.submitter,
890
+ session_id: extractHashedSessionId(request),
891
+ token_ids: tokenIds
892
+ })) {
893
+ return jsonResponse({ error: "Forbidden" }, 403, corsHeaders);
894
+ }
895
+ const hasMessageKey = Object.prototype.hasOwnProperty.call(payload, "message");
896
+ const hasMetadataKey = Object.prototype.hasOwnProperty.call(payload, "metadata");
897
+ const hasElementsKey = Object.prototype.hasOwnProperty.call(payload, "element_references");
898
+ const hasAttachmentsKey = Object.prototype.hasOwnProperty.call(payload, "attachments");
899
+ const hasStatusKey = Object.prototype.hasOwnProperty.call(payload, "status");
900
+ const requestedStatus = hasStatusKey ? String(payload["status"] ?? "").trim() : undefined;
901
+ if (hasStatusKey && requestedStatus !== "reviewed" && requestedStatus !== "dismissed") {
902
+ return jsonResponse({ error: `Invalid status '${requestedStatus}'` }, 422, corsHeaders);
903
+ }
904
+ const rawElements = hasElementsKey
905
+ ? Array.isArray(payload["element_references"])
906
+ ? payload["element_references"]
907
+ : []
908
+ : undefined;
909
+ const rawAttachments = hasAttachmentsKey
910
+ ? Array.isArray(payload["attachments"])
911
+ ? payload["attachments"]
912
+ : []
913
+ : undefined;
914
+ const maxAttachments = config.limits?.maxAttachments ?? 10;
915
+ const maxElements = config.limits?.maxElementReferences ?? 10;
916
+ if (rawAttachments && rawAttachments.length > maxAttachments) {
917
+ return jsonResponse({
918
+ error: `Attachments count (${rawAttachments.length}) exceeds maximum allowed (${maxAttachments})`
919
+ }, 422, corsHeaders);
920
+ }
921
+ if (rawElements && rawElements.length > maxElements) {
922
+ return jsonResponse({
923
+ error: `Element references count (${rawElements.length}) exceeds maximum allowed (${maxElements})`
924
+ }, 422, corsHeaders);
925
+ }
926
+ const sanitizedElements = rawElements
927
+ ? rawElements.map((el) => sanitizeElementReference(el))
928
+ : undefined;
929
+ let preparedAttachmentSpecs;
930
+ if (rawAttachments) {
931
+ const uploadOpts = getUploadValidationOptions();
932
+ const existingAttIds = new Set(existing.attachments.map((a) => String(a.id)));
933
+ preparedAttachmentSpecs = [];
934
+ for (const rawAtt of rawAttachments) {
935
+ const attObj = asRecord(rawAtt);
936
+ const hasNewBinary = Boolean(String(attObj["signed_blob_id"] ?? "").trim() ||
937
+ String(attObj["data_url"] ?? attObj["data"] ?? "").trim());
938
+ const existingIdRaw = String(attObj["existing_id"] ?? (!hasNewBinary ? attObj["id"] ?? "" : "")).trim();
939
+ if (existingIdRaw) {
940
+ if (!existingAttIds.has(existingIdRaw)) {
941
+ return jsonResponse({ error: "Attachment does not belong to this feedback" }, 422, corsHeaders);
942
+ }
943
+ const hasCustomMeta = Object.prototype.hasOwnProperty.call(attObj, "metadata") &&
944
+ typeof attObj["metadata"] === "object" &&
945
+ attObj["metadata"] !== null;
946
+ const sanitizedCustomMeta = hasCustomMeta
947
+ ? sanitizeGenericMetadata(attObj["metadata"])
948
+ : undefined;
949
+ const hasExplicitLinkKey = Object.prototype.hasOwnProperty.call(attObj, "element_reference_ref") ||
950
+ Object.prototype.hasOwnProperty.call(attObj, "element_attachment_ref") ||
951
+ Object.prototype.hasOwnProperty.call(attObj, "client_ref");
952
+ const linkedRef = hasExplicitLinkKey
953
+ ? String(attObj["element_reference_ref"] ??
954
+ attObj["element_attachment_ref"] ??
955
+ attObj["client_ref"] ??
956
+ "").trim() || null
957
+ : undefined;
958
+ preparedAttachmentSpecs.push({
959
+ kind: "retain",
960
+ existing_id: existingIdRaw,
961
+ element_client_ref: linkedRef,
962
+ metadata: sanitizedCustomMeta,
963
+ update_metadata: hasCustomMeta
964
+ });
965
+ }
966
+ else {
967
+ const createdSpec = await parseNewAttachmentSpec(attObj, storage, uploadOpts);
968
+ preparedAttachmentSpecs.push({
969
+ kind: "create",
970
+ ...createdSpec
971
+ });
972
+ }
973
+ }
974
+ }
975
+ const nextMessage = hasMessageKey
976
+ ? String(payload["message"] ?? "").trim() || null
977
+ : existing.message;
978
+ const nextElementsCount = sanitizedElements
979
+ ? sanitizedElements.length
980
+ : existing.element_references.length;
981
+ const nextAttachmentsCount = preparedAttachmentSpecs
982
+ ? preparedAttachmentSpecs.length
983
+ : existing.attachments.length;
984
+ if (!nextMessage && nextElementsCount === 0 && nextAttachmentsCount === 0) {
985
+ return jsonResponse({
986
+ error: "Feedback must include a message, an attachment, or a selected DOM element"
987
+ }, 422, corsHeaders);
988
+ }
989
+ let nextMetadata;
990
+ if (hasMetadataKey) {
991
+ nextMetadata = sanitizeGenericMetadata(payload["metadata"]);
992
+ nextMetadata["environment"] = existing.environment;
993
+ }
994
+ const updated = await storage.updateFeedback(existing.id, {
995
+ ...(hasMessageKey ? { message: nextMessage } : {}),
996
+ ...(hasStatusKey ? { status: requestedStatus } : {}),
997
+ ...(nextMetadata !== undefined ? { metadata: nextMetadata } : {}),
998
+ ...(sanitizedElements !== undefined ? { element_references: sanitizedElements } : {}),
999
+ ...(preparedAttachmentSpecs !== undefined ? { attachments: preparedAttachmentSpecs } : {})
1000
+ });
1001
+ if (!updated) {
1002
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
1003
+ }
1004
+ if (config.onFeedbackUpdated) {
1005
+ try {
1006
+ await config.onFeedbackUpdated(updated);
1007
+ }
1008
+ catch (cbErr) {
1009
+ console.error("[context-drop] onFeedbackUpdated callback error:", cbErr);
1010
+ }
1011
+ }
1012
+ const ownershipToken = findOwnershipTokenFor(rawTokens, updated.id, secret) ??
1013
+ generateOwnershipToken(updated.id, secret);
1014
+ return jsonResponse({
1015
+ id: updated.id,
1016
+ environment: updated.environment,
1017
+ status: updated.status,
1018
+ message: updated.message,
1019
+ attachments_count: updated.attachments.length,
1020
+ element_references_count: updated.element_references.length,
1021
+ ownership_token: ownershipToken,
1022
+ feedback: serializeOwnFeedback(updated, ownershipToken),
1023
+ created_at: updated.created_at,
1024
+ updated_at: updated.updated_at
1025
+ }, 200, corsHeaders);
1026
+ }
1027
+ catch (err) {
1028
+ if (err instanceof SensitiveElementError || err instanceof UploadValidationError) {
1029
+ return jsonResponse({ error: err.message }, err.status, corsHeaders);
1030
+ }
1031
+ return jsonResponse({ error: err.message || "Failed to update feedback" }, 422, corsHeaders);
1032
+ }
1033
+ }
1034
+ if (parsedRoute.kind === "feedback_comments" && method === "POST") {
1035
+ const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
1036
+ if (!originCheck.ok) {
1037
+ return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
1038
+ }
1039
+ const auth = await checkSubmissionAuth(request);
1040
+ if (!auth.ok) {
1041
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
1042
+ }
1043
+ if (!checkRateLimit(request)) {
1044
+ return jsonResponse({ error: "Rate limit exceeded. Please try again later." }, 429, corsHeaders);
1045
+ }
1046
+ const storage = getStorage();
1047
+ const existing = await storage.getFeedback(parsedRoute.feedbackId);
1048
+ if (!existing || existing.deleted_at) {
1049
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
1050
+ }
1051
+ try {
1052
+ const rawJson = (await request.json().catch(() => ({})));
1053
+ const payload = rawJson["comment"] && typeof rawJson["comment"] === "object"
1054
+ ? asRecord(rawJson["comment"])
1055
+ : asRecord(rawJson);
1056
+ const secret = getOwnershipSecret();
1057
+ const rawTokens = combineRequestOwnershipTokens(request, url, payload["ownership_token"] ?? rawJson["ownership_token"]);
1058
+ const tokenIds = extractVerifiedOwnershipIds(rawTokens, secret);
1059
+ if (!matchesOwnFeedback(existing, {
1060
+ submitter: auth.submitter,
1061
+ session_id: extractHashedSessionId(request),
1062
+ token_ids: tokenIds
1063
+ })) {
1064
+ return jsonResponse({ error: "Forbidden" }, 403, corsHeaders);
1065
+ }
1066
+ const rawAttachments = Array.isArray(payload["attachments"]) ? payload["attachments"] : [];
1067
+ const maxAttachments = config.limits?.maxAttachments ?? 10;
1068
+ if (rawAttachments.length > maxAttachments) {
1069
+ return jsonResponse({
1070
+ error: `Attachments count (${rawAttachments.length}) exceeds maximum allowed (${maxAttachments})`
1071
+ }, 422, corsHeaders);
1072
+ }
1073
+ const uploadOpts = getUploadValidationOptions();
1074
+ const preparedAttachments = await Promise.all(rawAttachments.map((rawAtt) => parseNewAttachmentSpec(rawAtt, storage, uploadOpts)));
1075
+ const bodyText = String(payload["body"] ?? "").trim() || null;
1076
+ if (!bodyText && preparedAttachments.length === 0) {
1077
+ return jsonResponse({ error: "Comment must include text or an image attachment" }, 422, corsHeaders);
1078
+ }
1079
+ if (!storage.addComment) {
1080
+ return jsonResponse({ error: "Storage adapter does not support comments" }, 501, corsHeaders);
1081
+ }
1082
+ const authorLabel = auth.submitter?.label ||
1083
+ (auth.submitter?.type && auth.submitter?.id !== undefined && auth.submitter?.id !== null
1084
+ ? `${auth.submitter.type}#${auth.submitter.id}`
1085
+ : "You");
1086
+ const result = await storage.addComment(existing.id, {
1087
+ author_type: auth.submitter?.type ?? "User",
1088
+ author_label: authorLabel,
1089
+ body: bodyText,
1090
+ attachments: preparedAttachments,
1091
+ status: "updated"
1092
+ });
1093
+ if (!result) {
1094
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
1095
+ }
1096
+ if (config.onFeedbackUpdated) {
1097
+ try {
1098
+ await config.onFeedbackUpdated(result.feedback);
1099
+ }
1100
+ catch (cbErr) {
1101
+ console.error("[context-drop] onFeedbackUpdated callback error:", cbErr);
1102
+ }
1103
+ }
1104
+ const ownershipToken = findOwnershipTokenFor(rawTokens, result.feedback.id, secret) ??
1105
+ generateOwnershipToken(result.feedback.id, secret);
1106
+ return jsonResponse({
1107
+ id: result.comment.id,
1108
+ feedback_id: result.feedback.id,
1109
+ status: result.feedback.status,
1110
+ comment: result.comment,
1111
+ feedback: serializeOwnFeedback(result.feedback, ownershipToken),
1112
+ created_at: result.comment.created_at
1113
+ }, 201, corsHeaders);
1114
+ }
1115
+ catch (err) {
1116
+ if (err instanceof SensitiveElementError || err instanceof UploadValidationError) {
1117
+ return jsonResponse({ error: err.message }, err.status, corsHeaders);
1118
+ }
1119
+ return jsonResponse({ error: err.message || "Failed to add comment" }, 422, corsHeaders);
1120
+ }
1121
+ }
1122
+ if (parsedRoute.kind === "feedback_item" && method === "DELETE") {
1123
+ const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
1124
+ if (!originCheck.ok) {
1125
+ return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
1126
+ }
1127
+ const auth = await checkSubmissionAuth(request);
1128
+ if (!auth.ok) {
1129
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
1130
+ }
1131
+ if (!checkRateLimit(request)) {
1132
+ return jsonResponse({ error: "Rate limit exceeded. Please try again later." }, 429, corsHeaders);
1133
+ }
1134
+ const storage = getStorage();
1135
+ const existing = await storage.getFeedback(parsedRoute.feedbackId);
1136
+ if (!existing || existing.deleted_at) {
1137
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
1138
+ }
1139
+ const rawJson = (await request.json().catch(() => ({})));
1140
+ const payload = rawJson["feedback"] && typeof rawJson["feedback"] === "object"
1141
+ ? asRecord(rawJson["feedback"])
1142
+ : asRecord(rawJson);
1143
+ const secret = getOwnershipSecret();
1144
+ const rawTokens = combineRequestOwnershipTokens(request, url, payload["ownership_token"] ?? rawJson["ownership_token"]);
1145
+ const tokenIds = extractVerifiedOwnershipIds(rawTokens, secret);
1146
+ if (!matchesOwnFeedback(existing, {
1147
+ submitter: auth.submitter,
1148
+ session_id: extractHashedSessionId(request),
1149
+ token_ids: tokenIds
1150
+ })) {
1151
+ return jsonResponse({ error: "Forbidden" }, 403, corsHeaders);
1152
+ }
1153
+ const deleted = await storage.softDeleteFeedback(existing.id);
1154
+ if (!deleted) {
1155
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
1156
+ }
1157
+ if (config.onFeedbackDeleted) {
1158
+ try {
1159
+ await config.onFeedbackDeleted(deleted);
1160
+ }
1161
+ catch (cbErr) {
1162
+ console.error("[context-drop] onFeedbackDeleted callback error:", cbErr);
1163
+ }
1164
+ }
1165
+ return jsonResponse({
1166
+ id: deleted.id,
1167
+ deleted: true,
1168
+ deleted_at: deleted.deleted_at ?? new Date().toISOString()
1169
+ }, 200, corsHeaders);
1170
+ }
1171
+ if (parsedRoute.kind === "feedback_attachment" && method === "GET") {
1172
+ const auth = await checkSubmissionAuth(request);
1173
+ if (!auth.ok) {
1174
+ return new Response("Forbidden", { status: auth.status, headers: corsHeaders });
1175
+ }
1176
+ const storage = getStorage();
1177
+ const existing = await storage.getFeedback(parsedRoute.feedbackId);
1178
+ if (!existing || existing.deleted_at) {
1179
+ return new Response("Not Found", { status: 404, headers: corsHeaders });
1180
+ }
1181
+ const secret = getOwnershipSecret();
1182
+ const rawTokens = combineRequestOwnershipTokens(request, url);
1183
+ const tokenIds = extractVerifiedOwnershipIds(rawTokens, secret);
1184
+ if (!matchesOwnFeedback(existing, {
1185
+ submitter: auth.submitter,
1186
+ session_id: extractHashedSessionId(request),
1187
+ token_ids: tokenIds
1188
+ })) {
1189
+ return new Response("Forbidden", { status: 403, headers: corsHeaders });
1190
+ }
1191
+ const allFeedbackAttachments = [
1192
+ ...existing.attachments,
1193
+ ...(existing.comments ?? []).flatMap((c) => c.attachments ?? [])
1194
+ ];
1195
+ const attMeta = allFeedbackAttachments.find((a) => String(a.id) === String(parsedRoute.attachmentId));
1196
+ if (!attMeta) {
1197
+ return new Response("Not Found", { status: 404, headers: corsHeaders });
1198
+ }
1199
+ const bytes = await storage.getAttachmentBytes(attMeta.id);
1200
+ if (!bytes) {
1201
+ return new Response("Not Found", { status: 404, headers: corsHeaders });
1202
+ }
1203
+ const bodyCopy = new Uint8Array(bytes.byteLength);
1204
+ bodyCopy.set(bytes);
1205
+ return new Response(bodyCopy, {
1206
+ status: 200,
1207
+ headers: {
1208
+ "Content-Type": attMeta.content_type || "image/png",
1209
+ "Cache-Control": "private, max-age=3600",
1210
+ "Content-Security-Policy": "default-src 'none'; sandbox",
1211
+ ...corsHeaders
1212
+ }
1213
+ });
1214
+ }
589
1215
  return jsonResponse({ error: "Not Found" }, 404, corsHeaders);
590
1216
  };
591
1217
  return Object.assign(handler, {
@@ -599,7 +1225,7 @@ export function createContextDropFetchHandler(config = {}) {
599
1225
  * @example
600
1226
  * ```ts
601
1227
  * import { createContextDropNextHandler } from "context-drop/next/server";
602
- * export const { GET, POST, OPTIONS } = createContextDropNextHandler();
1228
+ * export const { GET, POST, PATCH, PUT, DELETE, OPTIONS } = createContextDropNextHandler();
603
1229
  * ```
604
1230
  */
605
1231
  export function createContextDropNextHandler(config = {}) {
@@ -607,6 +1233,9 @@ export function createContextDropNextHandler(config = {}) {
607
1233
  return {
608
1234
  GET: (request) => fetchHandler(request),
609
1235
  POST: (request) => fetchHandler(request),
1236
+ PATCH: (request) => fetchHandler(request),
1237
+ PUT: (request) => fetchHandler(request),
1238
+ DELETE: (request) => fetchHandler(request),
610
1239
  OPTIONS: (request) => fetchHandler(request),
611
1240
  handler: fetchHandler
612
1241
  };