context-drop 0.0.0-stage → 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 (60) hide show
  1. package/MIT-LICENSE +21 -0
  2. package/README.md +710 -2
  3. package/app/assets/javascripts/context_drop/context_drop.js +9949 -0
  4. package/dist/app/javascript/context_drop/api-client.d.ts +53 -0
  5. package/dist/app/javascript/context_drop/api-client.js +470 -0
  6. package/dist/app/javascript/context_drop/element-picker.d.ts +111 -0
  7. package/dist/app/javascript/context_drop/element-picker.js +1428 -0
  8. package/dist/app/javascript/context_drop/icons.d.ts +34 -0
  9. package/dist/app/javascript/context_drop/icons.js +34 -0
  10. package/dist/app/javascript/context_drop/index.d.ts +7 -0
  11. package/dist/app/javascript/context_drop/index.js +9 -0
  12. package/dist/app/javascript/context_drop/markdown.d.ts +7 -0
  13. package/dist/app/javascript/context_drop/markdown.js +129 -0
  14. package/dist/app/javascript/context_drop/sanitizer.d.ts +38 -0
  15. package/dist/app/javascript/context_drop/sanitizer.js +769 -0
  16. package/dist/app/javascript/context_drop/screenshot.d.ts +21 -0
  17. package/dist/app/javascript/context_drop/screenshot.js +245 -0
  18. package/dist/app/javascript/context_drop/styles.d.ts +1 -0
  19. package/dist/app/javascript/context_drop/styles.js +2196 -0
  20. package/dist/app/javascript/context_drop/types.d.ts +316 -0
  21. package/dist/app/javascript/context_drop/types.js +1 -0
  22. package/dist/app/javascript/context_drop/widget.d.ts +206 -0
  23. package/dist/app/javascript/context_drop/widget.js +3752 -0
  24. package/dist/src/cli.d.ts +3 -0
  25. package/dist/src/cli.js +207 -0
  26. package/dist/src/index.d.ts +5 -0
  27. package/dist/src/index.js +5 -0
  28. package/dist/src/mcp/dispatcher.d.ts +42 -0
  29. package/dist/src/mcp/dispatcher.js +895 -0
  30. package/dist/src/mcp/environment-router.d.ts +38 -0
  31. package/dist/src/mcp/environment-router.js +174 -0
  32. package/dist/src/mcp/index.d.ts +24 -0
  33. package/dist/src/mcp/index.js +75 -0
  34. package/dist/src/mcp/remote-client.d.ts +25 -0
  35. package/dist/src/mcp/remote-client.js +98 -0
  36. package/dist/src/next/index.d.ts +13 -0
  37. package/dist/src/next/index.js +25 -0
  38. package/dist/src/next/server.d.ts +1 -0
  39. package/dist/src/next/server.js +1 -0
  40. package/dist/src/react/index.d.ts +104 -0
  41. package/dist/src/react/index.js +144 -0
  42. package/dist/src/server/handler.d.ts +48 -0
  43. package/dist/src/server/handler.js +1180 -0
  44. package/dist/src/server/index.d.ts +8 -0
  45. package/dist/src/server/index.js +8 -0
  46. package/dist/src/server/sanitizer.d.ts +15 -0
  47. package/dist/src/server/sanitizer.js +201 -0
  48. package/dist/src/server/storage/local.d.ts +22 -0
  49. package/dist/src/server/storage/local.js +827 -0
  50. package/dist/src/server/storage/memory.d.ts +8 -0
  51. package/dist/src/server/storage/memory.js +387 -0
  52. package/dist/src/server/storage/postgres.d.ts +27 -0
  53. package/dist/src/server/storage/postgres.js +629 -0
  54. package/dist/src/server/types.d.ts +227 -0
  55. package/dist/src/server/types.js +7 -0
  56. package/dist/src/server/upload-validator.d.ts +16 -0
  57. package/dist/src/server/upload-validator.js +196 -0
  58. package/dist/src/widget/index.d.ts +1 -0
  59. package/dist/src/widget/index.js +1 -0
  60. package/package.json +99 -4
@@ -0,0 +1,1180 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { ContextDropMcpDispatcher } from "../mcp/dispatcher.js";
6
+ import { resolveHostEnvironment } from "../mcp/environment-router.js";
7
+ import { MANDATORY_SERVER_EXCLUDED_SELECTORS, SensitiveElementError, sanitizeElementReference, sanitizeGenericMetadata } from "./sanitizer.js";
8
+ import { createLocalStorageAdapter } from "./storage/local.js";
9
+ import { matchesOwnFeedback } from "./storage/memory.js";
10
+ import { VERSION } from "./types.js";
11
+ import { DEFAULT_ALLOWED_CONTENT_TYPES, UploadValidationError, decodeBase64DataUrl, validateBinaryUpload } from "./upload-validator.js";
12
+ const VALID_POSITIONS = [
13
+ "bottom_right",
14
+ "bottom_left",
15
+ "top_right",
16
+ "top_left"
17
+ ];
18
+ const MAX_OWNERSHIP_TOKENS = 50;
19
+ const OWNERSHIP_TOKEN_DOMAIN = "cd_own:v1";
20
+ let sharedDefaultLocalStorage = null;
21
+ const fallbackOwnershipSecret = crypto.randomBytes(32);
22
+ function getSharedDefaultStorage(storageDir) {
23
+ if (storageDir) {
24
+ return createLocalStorageAdapter({ dir: storageDir });
25
+ }
26
+ if (!sharedDefaultLocalStorage) {
27
+ sharedDefaultLocalStorage = createLocalStorageAdapter();
28
+ }
29
+ return sharedDefaultLocalStorage;
30
+ }
31
+ function asRecord(input) {
32
+ if (input && typeof input === "object" && !Array.isArray(input)) {
33
+ return input;
34
+ }
35
+ return {};
36
+ }
37
+ function jsonResponse(body, status = 200, extraHeaders = {}) {
38
+ return new Response(JSON.stringify(body), {
39
+ status,
40
+ headers: {
41
+ "Content-Type": "application/json; charset=utf-8",
42
+ "Cache-Control": "no-store",
43
+ ...extraHeaders
44
+ }
45
+ });
46
+ }
47
+ function resolveRequestExpectedOrigins(request) {
48
+ const origins = new Set();
49
+ try {
50
+ const reqUrl = new URL(request.url);
51
+ origins.add(reqUrl.origin.toLowerCase());
52
+ const fwdHost = request.headers
53
+ .get("x-forwarded-host")
54
+ ?.split(",")[0]
55
+ ?.trim();
56
+ const host = fwdHost || request.headers.get("host")?.trim();
57
+ const fwdProto = request.headers
58
+ .get("x-forwarded-proto")
59
+ ?.split(",")[0]
60
+ ?.trim()
61
+ .toLowerCase();
62
+ const proto = fwdProto || reqUrl.protocol.replace(":", "");
63
+ if (host && proto) {
64
+ origins.add(`${proto}://${host}`.toLowerCase());
65
+ }
66
+ }
67
+ catch {
68
+ // Ignore malformed URL
69
+ }
70
+ return origins;
71
+ }
72
+ export function isOriginExplicitlyAllowed(originHeader, allowedOrigins) {
73
+ const origin = (originHeader ?? "").trim().replace(/\/+$/, "");
74
+ if (!origin || !allowedOrigins || allowedOrigins.length === 0)
75
+ return false;
76
+ for (const rule of allowedOrigins) {
77
+ if (rule instanceof RegExp) {
78
+ if (rule.test(origin))
79
+ return true;
80
+ }
81
+ else if (typeof rule === "string") {
82
+ const normalized = rule.trim().replace(/\/+$/, "");
83
+ if (normalized && normalized !== "*" && normalized.toLowerCase() === origin.toLowerCase()) {
84
+ return true;
85
+ }
86
+ }
87
+ }
88
+ return false;
89
+ }
90
+ function buildCorsHeaders(request, allowedOrigins) {
91
+ const origin = request.headers.get("origin")?.trim();
92
+ if (!origin || !isOriginExplicitlyAllowed(origin, allowedOrigins)) {
93
+ return {};
94
+ }
95
+ return {
96
+ "Access-Control-Allow-Origin": origin,
97
+ Vary: "Origin",
98
+ "Access-Control-Allow-Credentials": "true",
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",
101
+ "Access-Control-Max-Age": "86400"
102
+ };
103
+ }
104
+ function verifyMutationOrigin(request, allowedOrigins) {
105
+ const origin = request.headers.get("origin")?.trim().replace(/\/+$/, "");
106
+ const secFetchSite = request.headers.get("sec-fetch-site")?.trim().toLowerCase();
107
+ if (origin) {
108
+ if (isOriginExplicitlyAllowed(origin, allowedOrigins)) {
109
+ return { ok: true };
110
+ }
111
+ const selfOrigins = resolveRequestExpectedOrigins(request);
112
+ if (selfOrigins.has(origin.toLowerCase())) {
113
+ return { ok: true };
114
+ }
115
+ return {
116
+ ok: false,
117
+ error: "Cross-origin feedback submission rejected: Origin is not allowed"
118
+ };
119
+ }
120
+ if (secFetchSite === "cross-site") {
121
+ return {
122
+ ok: false,
123
+ error: "Cross-site feedback submission rejected"
124
+ };
125
+ }
126
+ return { ok: true };
127
+ }
128
+ function resolveClientIp(request) {
129
+ const xff = request.headers.get("x-forwarded-for");
130
+ if (xff) {
131
+ const first = xff.split(",")[0]?.trim();
132
+ if (first)
133
+ return first;
134
+ }
135
+ const realIp = request.headers.get("x-real-ip")?.trim();
136
+ if (realIp)
137
+ return realIp;
138
+ return "127.0.0.1";
139
+ }
140
+ const SESSION_COOKIE_NAME = "cd_session";
141
+ const SESSION_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
142
+ function extractRawSessionCookie(request) {
143
+ const cookieHeader = request.headers.get("cookie");
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)
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) {
188
+ const clean = pathname.replace(/\/+$/, "");
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
+ }
207
+ if (clean.endsWith("/config"))
208
+ return { kind: "static", name: "config" };
209
+ if (clean.endsWith("/attachments"))
210
+ return { kind: "static", name: "attachments" };
211
+ if (clean.endsWith("/feedback"))
212
+ return { kind: "static", name: "feedback" };
213
+ if (clean.endsWith("/health"))
214
+ return { kind: "static", name: "health" };
215
+ if (clean.endsWith("/mcp"))
216
+ return { kind: "static", name: "mcp" };
217
+ return { kind: "unknown" };
218
+ }
219
+ function timingSafeCompareStrings(a, b) {
220
+ const bufA = Buffer.from(a, "utf8");
221
+ const bufB = Buffer.from(b, "utf8");
222
+ if (bufA.byteLength !== bufB.byteLength || bufA.byteLength === 0) {
223
+ return false;
224
+ }
225
+ return crypto.timingSafeEqual(bufA, bufB);
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
+ }
358
+ function resolveWidgetBundleFilePath() {
359
+ try {
360
+ const currentFile = fileURLToPath(import.meta.url);
361
+ const candidates = [
362
+ path.resolve(path.dirname(currentFile), "../../app/assets/javascripts/context_drop/context_drop.js"),
363
+ path.resolve(path.dirname(currentFile), "../../../app/assets/javascripts/context_drop/context_drop.js")
364
+ ];
365
+ for (const candidate of candidates) {
366
+ if (fs.existsSync(candidate)) {
367
+ return candidate;
368
+ }
369
+ }
370
+ }
371
+ catch {
372
+ // Ignore file URL resolution errors on edge runtimes
373
+ }
374
+ return null;
375
+ }
376
+ export function defineContextDropConfig(config) {
377
+ return config;
378
+ }
379
+ export function createContextDropFetchHandler(config = {}) {
380
+ const rateLimitStore = new Map();
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
+ };
394
+ const isEnabled = () => {
395
+ if (config.enabled !== undefined)
396
+ return Boolean(config.enabled);
397
+ const envFlag = (process.env.CONTEXT_DROP_ENABLED ?? "").trim().toLowerCase();
398
+ if (envFlag === "false" || envFlag === "0")
399
+ return false;
400
+ return true;
401
+ };
402
+ const getEnvironment = () => resolveHostEnvironment(config.environment);
403
+ const getResolvedSelectionMode = (envName) => {
404
+ if (config.selectionMode === "smart")
405
+ return "smart";
406
+ if (config.selectionMode === "verbose")
407
+ return "verbose";
408
+ return envName === "production" ? "smart" : "verbose";
409
+ };
410
+ const getUploadValidationOptions = () => ({
411
+ maxAttachmentSize: config.limits?.maxAttachmentSize ?? 10 * 1024 * 1024,
412
+ allowedContentTypes: config.limits?.allowedContentTypes ?? [...DEFAULT_ALLOWED_CONTENT_TYPES],
413
+ maxImageDimensions: config.limits?.maxImageDimensions ?? [4096, 4096]
414
+ });
415
+ const buildPublicWidgetConfig = () => {
416
+ const envName = getEnvironment();
417
+ const pos = config.position && VALID_POSITIONS.includes(config.position)
418
+ ? config.position
419
+ : "bottom_right";
420
+ const excluded = Array.from(new Set([
421
+ ...MANDATORY_SERVER_EXCLUDED_SELECTORS,
422
+ ...(config.privacy?.excludedSelectors ?? [])
423
+ ]));
424
+ return {
425
+ enabled: isEnabled(),
426
+ environment: envName,
427
+ position: pos,
428
+ placeholder: config.placeholder || "What would you like to tell us?",
429
+ csrf_token: null,
430
+ agent: {
431
+ enabled: false
432
+ },
433
+ features: {
434
+ element_selection: config.features?.elementSelection ?? true,
435
+ selection_mode: getResolvedSelectionMode(envName),
436
+ screenshot_capture: config.features?.screenshotCapture ?? true,
437
+ element_capture_padding: config.features?.elementCapturePadding ?? 16,
438
+ smart_capture_padding: config.features?.smartCapturePadding ?? 84
439
+ },
440
+ limits: {
441
+ max_attachments: config.limits?.maxAttachments ?? 10,
442
+ max_element_references: config.limits?.maxElementReferences ?? 10,
443
+ max_attachment_size: config.limits?.maxAttachmentSize ?? 10 * 1024 * 1024,
444
+ allowed_content_types: config.limits?.allowedContentTypes ?? [
445
+ ...DEFAULT_ALLOWED_CONTENT_TYPES
446
+ ],
447
+ max_image_dimensions: config.limits?.maxImageDimensions ?? [4096, 4096]
448
+ },
449
+ privacy: {
450
+ excluded_selectors: excluded
451
+ }
452
+ };
453
+ };
454
+ const checkSubmissionAuth = async (request) => {
455
+ const resolved = config.resolveSubmitter ? await config.resolveSubmitter(request) : null;
456
+ const allowAnon = config.allowAnonymous ?? true;
457
+ if (!allowAnon && (!resolved || (resolved.id === undefined && !resolved.label))) {
458
+ return {
459
+ ok: false,
460
+ status: 401,
461
+ error: "Authentication required to submit feedback"
462
+ };
463
+ }
464
+ if (config.authorizeSubmission) {
465
+ const permitted = await config.authorizeSubmission(request, resolved);
466
+ if (!permitted) {
467
+ return { ok: false, status: 403, error: "Forbidden" };
468
+ }
469
+ }
470
+ return {
471
+ ok: true,
472
+ submitter: resolved ?? {}
473
+ };
474
+ };
475
+ const checkRateLimit = (request) => {
476
+ if (config.rateLimit === false)
477
+ return true;
478
+ const maxRequests = config.rateLimit?.maxRequests ?? 20;
479
+ const periodSeconds = config.rateLimit?.periodSeconds ?? 3600;
480
+ if (maxRequests <= 0 || periodSeconds <= 0)
481
+ return true;
482
+ const nowMs = Date.now();
483
+ for (const [k, v] of rateLimitStore.entries()) {
484
+ if (v.expiresAtMs <= nowMs) {
485
+ rateLimitStore.delete(k);
486
+ }
487
+ }
488
+ const ip = resolveClientIp(request);
489
+ const windowBucket = Math.floor(nowMs / (periodSeconds * 1000));
490
+ const key = `${ip}:${windowBucket}`;
491
+ const existing = rateLimitStore.get(key);
492
+ if (!existing) {
493
+ rateLimitStore.set(key, {
494
+ count: 1,
495
+ expiresAtMs: (windowBucket + 1) * periodSeconds * 1000
496
+ });
497
+ return true;
498
+ }
499
+ existing.count += 1;
500
+ return existing.count <= maxRequests;
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
+ };
557
+ const handleMcpEndpoint = async (request) => {
558
+ const expectedApiKey = (config.mcp?.apiKey ??
559
+ process.env.CONTEXT_DROP_MCP_API_KEY ??
560
+ "").trim();
561
+ const mcpEnabled = config.mcp?.enabled !== undefined
562
+ ? Boolean(config.mcp.enabled)
563
+ : process.env.CONTEXT_DROP_MCP_ENABLED === "true" || expectedApiKey.length > 0;
564
+ if (!mcpEnabled) {
565
+ return jsonResponse({ error: "Not Found" }, 404);
566
+ }
567
+ if (config.mcp?.authorize) {
568
+ const ok = await config.mcp.authorize(request);
569
+ if (!ok) {
570
+ return jsonResponse({ error: "Unauthorized MCP request" }, 401);
571
+ }
572
+ }
573
+ else {
574
+ if (!expectedApiKey) {
575
+ return jsonResponse({ error: "Unauthorized: MCP API key is not configured" }, 401);
576
+ }
577
+ const authHeader = request.headers.get("authorization") ?? "";
578
+ const provided = authHeader.toLowerCase().startsWith("bearer ")
579
+ ? authHeader.slice(7).trim()
580
+ : "";
581
+ if (!timingSafeCompareStrings(provided, expectedApiKey)) {
582
+ return jsonResponse({ error: "Unauthorized: Invalid or missing Bearer token" }, 401);
583
+ }
584
+ }
585
+ const rawBody = await request.text();
586
+ let parsedPayload;
587
+ try {
588
+ parsedPayload = JSON.parse(rawBody);
589
+ }
590
+ catch (err) {
591
+ return jsonResponse({
592
+ jsonrpc: "2.0",
593
+ id: null,
594
+ error: {
595
+ code: -32700,
596
+ message: `Parse error: ${err.message}`
597
+ }
598
+ }, 200);
599
+ }
600
+ const dispatcher = new ContextDropMcpDispatcher({
601
+ storage: getStorage(),
602
+ hostEnvironment: getEnvironment(),
603
+ localOnly: true
604
+ });
605
+ const rpcResponse = await dispatcher.dispatch(parsedPayload);
606
+ if (rpcResponse === null) {
607
+ return new Response(null, { status: 202 });
608
+ }
609
+ return jsonResponse(rpcResponse, 200);
610
+ };
611
+ const handler = async (request) => {
612
+ const url = new URL(request.url, "http://localhost");
613
+ const parsedRoute = parseSubRoute(url.pathname);
614
+ const method = request.method.toUpperCase();
615
+ // Remote MCP endpoint has independent enablement & auth (matching Rails McpController)
616
+ if (parsedRoute.kind === "static" && parsedRoute.name === "mcp" && method === "POST") {
617
+ return handleMcpEndpoint(request);
618
+ }
619
+ const corsHeaders = buildCorsHeaders(request, config.allowedOrigins);
620
+ if (method === "OPTIONS") {
621
+ if (Object.keys(corsHeaders).length > 0) {
622
+ return new Response(null, { status: 204, headers: corsHeaders });
623
+ }
624
+ const origin = request.headers.get("origin");
625
+ if (origin && resolveRequestExpectedOrigins(request).has(origin.toLowerCase())) {
626
+ return new Response(null, { status: 204 });
627
+ }
628
+ return new Response(null, { status: 403 });
629
+ }
630
+ if (!isEnabled()) {
631
+ return jsonResponse({ error: "Not Found" }, 404, corsHeaders);
632
+ }
633
+ if (parsedRoute.kind === "static" && parsedRoute.name === "health" && method === "GET") {
634
+ return jsonResponse({
635
+ status: "ok",
636
+ environment: getEnvironment(),
637
+ version: VERSION
638
+ }, 200, corsHeaders);
639
+ }
640
+ if (parsedRoute.kind === "static" &&
641
+ parsedRoute.name === "assets/context_drop.js" &&
642
+ method === "GET") {
643
+ const bundlePath = resolveWidgetBundleFilePath();
644
+ if (!bundlePath) {
645
+ return new Response("Not Found", { status: 404, headers: corsHeaders });
646
+ }
647
+ const jsContent = fs.readFileSync(bundlePath, "utf8");
648
+ return new Response(jsContent, {
649
+ status: 200,
650
+ headers: {
651
+ "Content-Type": "application/javascript; charset=utf-8",
652
+ "Cache-Control": "public, max-age=3600",
653
+ ...corsHeaders
654
+ }
655
+ });
656
+ }
657
+ if (parsedRoute.kind === "static" && parsedRoute.name === "config" && method === "GET") {
658
+ const auth = await checkSubmissionAuth(request);
659
+ if (!auth.ok) {
660
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
661
+ }
662
+ return jsonResponse(buildPublicWidgetConfig(), 200, corsHeaders);
663
+ }
664
+ if (parsedRoute.kind === "static" && parsedRoute.name === "attachments" && method === "POST") {
665
+ const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
666
+ if (!originCheck.ok) {
667
+ return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
668
+ }
669
+ const auth = await checkSubmissionAuth(request);
670
+ if (!auth.ok) {
671
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
672
+ }
673
+ if (!checkRateLimit(request)) {
674
+ return jsonResponse({ error: "Rate limit exceeded. Please try again later." }, 429, corsHeaders);
675
+ }
676
+ try {
677
+ const formData = await request.formData();
678
+ const fileEntry = formData.get("file");
679
+ if (!fileEntry || typeof fileEntry.arrayBuffer !== "function") {
680
+ throw new UploadValidationError("Missing file upload");
681
+ }
682
+ const blobObj = fileEntry;
683
+ const ab = await blobObj.arrayBuffer();
684
+ const validated = validateBinaryUpload(new Uint8Array(ab), typeof blobObj.name === "string" ? blobObj.name : "attachment.png", getUploadValidationOptions());
685
+ const saved = await getStorage().savePendingBlob(validated);
686
+ return jsonResponse({
687
+ signed_blob_id: saved.signed_blob_id,
688
+ filename: validated.filename,
689
+ content_type: validated.content_type,
690
+ byte_size: validated.byte_size,
691
+ dimensions: validated.dimensions
692
+ }, 201, corsHeaders);
693
+ }
694
+ catch (err) {
695
+ if (err instanceof UploadValidationError) {
696
+ return jsonResponse({ error: err.message }, err.status, corsHeaders);
697
+ }
698
+ return jsonResponse({ error: err.message || "Invalid attachment upload" }, 422, corsHeaders);
699
+ }
700
+ }
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") {
730
+ const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
731
+ if (!originCheck.ok) {
732
+ return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
733
+ }
734
+ const auth = await checkSubmissionAuth(request);
735
+ if (!auth.ok) {
736
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
737
+ }
738
+ if (!checkRateLimit(request)) {
739
+ return jsonResponse({ error: "Rate limit exceeded. Please try again later." }, 429, corsHeaders);
740
+ }
741
+ try {
742
+ const rawJson = (await request.json().catch(() => ({})));
743
+ const payload = rawJson["feedback"] && typeof rawJson["feedback"] === "object"
744
+ ? asRecord(rawJson["feedback"])
745
+ : asRecord(rawJson);
746
+ const rawElements = Array.isArray(payload["element_references"])
747
+ ? payload["element_references"]
748
+ : [];
749
+ const rawAttachments = Array.isArray(payload["attachments"]) ? payload["attachments"] : [];
750
+ const maxAttachments = config.limits?.maxAttachments ?? 10;
751
+ const maxElements = config.limits?.maxElementReferences ?? 10;
752
+ if (rawAttachments.length > maxAttachments) {
753
+ return jsonResponse({
754
+ error: `Attachments count (${rawAttachments.length}) exceeds maximum allowed (${maxAttachments})`
755
+ }, 422, corsHeaders);
756
+ }
757
+ if (rawElements.length > maxElements) {
758
+ return jsonResponse({
759
+ error: `Element references count (${rawElements.length}) exceeds maximum allowed (${maxElements})`
760
+ }, 422, corsHeaders);
761
+ }
762
+ const sanitizedElements = rawElements.map((el) => sanitizeElementReference(el));
763
+ const uploadOpts = getUploadValidationOptions();
764
+ const storage = getStorage();
765
+ const preparedAttachments = [];
766
+ for (const rawAtt of rawAttachments) {
767
+ preparedAttachments.push(await parseNewAttachmentSpec(asRecord(rawAtt), storage, uploadOpts));
768
+ }
769
+ const messageStr = String(payload["message"] ?? "").trim();
770
+ const message = messageStr.length > 0 ? messageStr : null;
771
+ const pageUrl = (String(payload["page_url"] ?? "").trim() ||
772
+ request.headers.get("referer")?.trim() ||
773
+ "");
774
+ if (!pageUrl) {
775
+ return jsonResponse({ error: "Page url can't be blank" }, 422, corsHeaders);
776
+ }
777
+ if (!message && sanitizedElements.length === 0 && preparedAttachments.length === 0) {
778
+ return jsonResponse({
779
+ error: "Feedback must include a message, an attachment, or a selected DOM element"
780
+ }, 422, corsHeaders);
781
+ }
782
+ const hostEnv = getEnvironment();
783
+ const sanitizedMeta = sanitizeGenericMetadata(payload["metadata"]);
784
+ sanitizedMeta["environment"] = hostEnv;
785
+ const userAgent = String(payload["user_agent"] ?? "").trim() ||
786
+ request.headers.get("user-agent")?.trim() ||
787
+ null;
788
+ const existingSessionToken = extractRawSessionCookie(request);
789
+ const rawSessionToken = existingSessionToken ?? crypto.randomBytes(16).toString("hex");
790
+ const hashedSessionId = hashSessionCookieValue(rawSessionToken);
791
+ const created = await storage.createFeedback({
792
+ environment: hostEnv,
793
+ message,
794
+ page_url: pageUrl,
795
+ user_agent: userAgent,
796
+ session_id: hashedSessionId,
797
+ submitter: auth.submitter,
798
+ metadata: sanitizedMeta,
799
+ element_references: sanitizedElements,
800
+ attachments: preparedAttachments
801
+ });
802
+ if (config.onFeedbackCreated) {
803
+ try {
804
+ await config.onFeedbackCreated(created);
805
+ }
806
+ catch (cbErr) {
807
+ console.error("[context-drop] onFeedbackCreated callback error:", cbErr);
808
+ }
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
+ }
815
+ return jsonResponse({
816
+ id: created.id,
817
+ environment: created.environment,
818
+ status: created.status,
819
+ attachments_count: created.attachments.length,
820
+ element_references_count: created.element_references.length,
821
+ ownership_token: ownershipToken,
822
+ feedback: serializeOwnFeedback(created, ownershipToken),
823
+ created_at: created.created_at,
824
+ updated_at: created.updated_at
825
+ }, 201, responseHeaders);
826
+ }
827
+ catch (err) {
828
+ if (err instanceof SensitiveElementError || err instanceof UploadValidationError) {
829
+ return jsonResponse({ error: err.message }, err.status, corsHeaders);
830
+ }
831
+ return jsonResponse({ error: err.message || "Failed to process feedback" }, 422, corsHeaders);
832
+ }
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
+ }
1089
+ return jsonResponse({ error: "Not Found" }, 404, corsHeaders);
1090
+ };
1091
+ return Object.assign(handler, {
1092
+ resetRateLimits: () => rateLimitStore.clear(),
1093
+ getStorage
1094
+ });
1095
+ }
1096
+ /**
1097
+ * Next.js App Router route handler factory (`app/api/context-drop/[[...path]]/route.ts`).
1098
+ *
1099
+ * @example
1100
+ * ```ts
1101
+ * import { createContextDropNextHandler } from "context-drop/next/server";
1102
+ * export const { GET, POST, PATCH, PUT, DELETE, OPTIONS } = createContextDropNextHandler();
1103
+ * ```
1104
+ */
1105
+ export function createContextDropNextHandler(config = {}) {
1106
+ const fetchHandler = createContextDropFetchHandler(config);
1107
+ return {
1108
+ GET: (request) => fetchHandler(request),
1109
+ POST: (request) => fetchHandler(request),
1110
+ PATCH: (request) => fetchHandler(request),
1111
+ PUT: (request) => fetchHandler(request),
1112
+ DELETE: (request) => fetchHandler(request),
1113
+ OPTIONS: (request) => fetchHandler(request),
1114
+ handler: fetchHandler
1115
+ };
1116
+ }
1117
+ /**
1118
+ * Next.js Pages Router / Node HTTP handler factory (`pages/api/context-drop/[[...path]].ts`).
1119
+ *
1120
+ * Works both with `export const config = { api: { bodyParser: false } }` (required for
1121
+ * multipart `/attachments` uploads) and with pre-parsed JSON bodies.
1122
+ */
1123
+ export function createContextDropPagesHandler(config = {}) {
1124
+ const fetchHandler = createContextDropFetchHandler(config);
1125
+ return async function pagesApiHandler(req, res) {
1126
+ const proto = (typeof req.headers["x-forwarded-proto"] === "string"
1127
+ ? req.headers["x-forwarded-proto"].split(",")[0]?.trim()
1128
+ : undefined) || "http";
1129
+ const host = (typeof req.headers["x-forwarded-host"] === "string"
1130
+ ? req.headers["x-forwarded-host"].split(",")[0]?.trim()
1131
+ : undefined) ||
1132
+ req.headers.host ||
1133
+ "localhost";
1134
+ const fullUrl = `${proto}://${host}${req.url || "/"}`;
1135
+ const headers = new Headers();
1136
+ for (const [k, v] of Object.entries(req.headers)) {
1137
+ if (Array.isArray(v)) {
1138
+ for (const item of v)
1139
+ headers.append(k, item);
1140
+ }
1141
+ else if (typeof v === "string") {
1142
+ headers.set(k, v);
1143
+ }
1144
+ }
1145
+ const method = (req.method || "GET").toUpperCase();
1146
+ let bodyBuffer;
1147
+ if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS") {
1148
+ if (req.body !== undefined && req.body !== null) {
1149
+ if (Buffer.isBuffer(req.body)) {
1150
+ bodyBuffer = req.body;
1151
+ }
1152
+ else if (typeof req.body === "string") {
1153
+ bodyBuffer = Buffer.from(req.body, "utf8");
1154
+ }
1155
+ else {
1156
+ bodyBuffer = Buffer.from(JSON.stringify(req.body), "utf8");
1157
+ }
1158
+ }
1159
+ else {
1160
+ const chunks = [];
1161
+ for await (const chunk of req) {
1162
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1163
+ }
1164
+ bodyBuffer = Buffer.concat(chunks);
1165
+ }
1166
+ }
1167
+ const webRequest = new Request(fullUrl, {
1168
+ method,
1169
+ headers,
1170
+ body: bodyBuffer ? new Uint8Array(bodyBuffer) : undefined
1171
+ });
1172
+ const webResponse = await fetchHandler(webRequest);
1173
+ res.statusCode = webResponse.status;
1174
+ webResponse.headers.forEach((value, key) => {
1175
+ res.setHeader(key, value);
1176
+ });
1177
+ const responseBuffer = Buffer.from(await webResponse.arrayBuffer());
1178
+ res.end(responseBuffer);
1179
+ };
1180
+ }