context-drop 0.0.0-stage → 0.2.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 +709 -2
  3. package/app/assets/javascripts/context_drop/context_drop.js +8936 -0
  4. package/dist/app/javascript/context_drop/api-client.d.ts +41 -0
  5. package/dist/app/javascript/context_drop/api-client.js +279 -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 +32 -0
  9. package/dist/app/javascript/context_drop/icons.js +32 -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 +2015 -0
  20. package/dist/app/javascript/context_drop/types.d.ts +239 -0
  21. package/dist/app/javascript/context_drop/types.js +1 -0
  22. package/dist/app/javascript/context_drop/widget.d.ts +188 -0
  23. package/dist/app/javascript/context_drop/widget.js +3227 -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 +869 -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 +90 -0
  41. package/dist/src/react/index.js +124 -0
  42. package/dist/src/server/handler.d.ts +42 -0
  43. package/dist/src/server/handler.js +677 -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 +574 -0
  50. package/dist/src/server/storage/memory.d.ts +5 -0
  51. package/dist/src/server/storage/memory.js +221 -0
  52. package/dist/src/server/storage/postgres.d.ts +27 -0
  53. package/dist/src/server/storage/postgres.js +446 -0
  54. package/dist/src/server/types.d.ts +190 -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,677 @@
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 { VERSION } from "./types.js";
10
+ import { DEFAULT_ALLOWED_CONTENT_TYPES, UploadValidationError, decodeBase64DataUrl, validateBinaryUpload } from "./upload-validator.js";
11
+ const VALID_POSITIONS = [
12
+ "bottom_right",
13
+ "bottom_left",
14
+ "top_right",
15
+ "top_left"
16
+ ];
17
+ let sharedDefaultLocalStorage = null;
18
+ function getSharedDefaultStorage(storageDir) {
19
+ if (storageDir) {
20
+ return createLocalStorageAdapter({ dir: storageDir });
21
+ }
22
+ if (!sharedDefaultLocalStorage) {
23
+ sharedDefaultLocalStorage = createLocalStorageAdapter();
24
+ }
25
+ return sharedDefaultLocalStorage;
26
+ }
27
+ function asRecord(input) {
28
+ if (input && typeof input === "object" && !Array.isArray(input)) {
29
+ return input;
30
+ }
31
+ return {};
32
+ }
33
+ function jsonResponse(body, status = 200, extraHeaders = {}) {
34
+ return new Response(JSON.stringify(body), {
35
+ status,
36
+ headers: {
37
+ "Content-Type": "application/json; charset=utf-8",
38
+ "Cache-Control": "no-store",
39
+ ...extraHeaders
40
+ }
41
+ });
42
+ }
43
+ function resolveRequestExpectedOrigins(request) {
44
+ const origins = new Set();
45
+ try {
46
+ const reqUrl = new URL(request.url);
47
+ origins.add(reqUrl.origin.toLowerCase());
48
+ const fwdHost = request.headers
49
+ .get("x-forwarded-host")
50
+ ?.split(",")[0]
51
+ ?.trim();
52
+ const host = fwdHost || request.headers.get("host")?.trim();
53
+ const fwdProto = request.headers
54
+ .get("x-forwarded-proto")
55
+ ?.split(",")[0]
56
+ ?.trim()
57
+ .toLowerCase();
58
+ const proto = fwdProto || reqUrl.protocol.replace(":", "");
59
+ if (host && proto) {
60
+ origins.add(`${proto}://${host}`.toLowerCase());
61
+ }
62
+ }
63
+ catch {
64
+ // Ignore malformed URL
65
+ }
66
+ return origins;
67
+ }
68
+ export function isOriginExplicitlyAllowed(originHeader, allowedOrigins) {
69
+ const origin = (originHeader ?? "").trim().replace(/\/+$/, "");
70
+ if (!origin || !allowedOrigins || allowedOrigins.length === 0)
71
+ return false;
72
+ for (const rule of allowedOrigins) {
73
+ if (rule instanceof RegExp) {
74
+ if (rule.test(origin))
75
+ return true;
76
+ }
77
+ else if (typeof rule === "string") {
78
+ const normalized = rule.trim().replace(/\/+$/, "");
79
+ if (normalized && normalized !== "*" && normalized.toLowerCase() === origin.toLowerCase()) {
80
+ return true;
81
+ }
82
+ }
83
+ }
84
+ return false;
85
+ }
86
+ function buildCorsHeaders(request, allowedOrigins) {
87
+ const origin = request.headers.get("origin")?.trim();
88
+ if (!origin || !isOriginExplicitlyAllowed(origin, allowedOrigins)) {
89
+ return {};
90
+ }
91
+ return {
92
+ "Access-Control-Allow-Origin": origin,
93
+ Vary: "Origin",
94
+ "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",
97
+ "Access-Control-Max-Age": "86400"
98
+ };
99
+ }
100
+ function verifyMutationOrigin(request, allowedOrigins) {
101
+ const origin = request.headers.get("origin")?.trim().replace(/\/+$/, "");
102
+ const secFetchSite = request.headers.get("sec-fetch-site")?.trim().toLowerCase();
103
+ if (origin) {
104
+ if (isOriginExplicitlyAllowed(origin, allowedOrigins)) {
105
+ return { ok: true };
106
+ }
107
+ const selfOrigins = resolveRequestExpectedOrigins(request);
108
+ if (selfOrigins.has(origin.toLowerCase())) {
109
+ return { ok: true };
110
+ }
111
+ return {
112
+ ok: false,
113
+ error: "Cross-origin feedback submission rejected: Origin is not allowed"
114
+ };
115
+ }
116
+ if (secFetchSite === "cross-site") {
117
+ return {
118
+ ok: false,
119
+ error: "Cross-site feedback submission rejected"
120
+ };
121
+ }
122
+ return { ok: true };
123
+ }
124
+ function resolveClientIp(request) {
125
+ const xff = request.headers.get("x-forwarded-for");
126
+ if (xff) {
127
+ const first = xff.split(",")[0]?.trim();
128
+ if (first)
129
+ return first;
130
+ }
131
+ const realIp = request.headers.get("x-real-ip")?.trim();
132
+ if (realIp)
133
+ return realIp;
134
+ return "127.0.0.1";
135
+ }
136
+ function extractHashedSessionId(request) {
137
+ const cookieHeader = request.headers.get("cookie");
138
+ if (!cookieHeader)
139
+ return null;
140
+ return crypto.createHash("sha256").update(cookieHeader).digest("hex").slice(0, 32);
141
+ }
142
+ function resolveSubRoute(pathname) {
143
+ const clean = pathname.replace(/\/+$/, "");
144
+ if (clean.endsWith("/assets/context_drop.js"))
145
+ return "assets/context_drop.js";
146
+ if (clean.endsWith("/config"))
147
+ return "config";
148
+ if (clean.endsWith("/attachments"))
149
+ return "attachments";
150
+ if (clean.endsWith("/feedback"))
151
+ return "feedback";
152
+ if (clean.endsWith("/health"))
153
+ return "health";
154
+ if (clean.endsWith("/mcp"))
155
+ return "mcp";
156
+ return "";
157
+ }
158
+ function timingSafeCompareStrings(a, b) {
159
+ const bufA = Buffer.from(a, "utf8");
160
+ const bufB = Buffer.from(b, "utf8");
161
+ if (bufA.byteLength !== bufB.byteLength || bufA.byteLength === 0) {
162
+ return false;
163
+ }
164
+ return crypto.timingSafeEqual(bufA, bufB);
165
+ }
166
+ function resolveWidgetBundleFilePath() {
167
+ try {
168
+ const currentFile = fileURLToPath(import.meta.url);
169
+ const candidates = [
170
+ path.resolve(path.dirname(currentFile), "../../app/assets/javascripts/context_drop/context_drop.js"),
171
+ path.resolve(path.dirname(currentFile), "../../../app/assets/javascripts/context_drop/context_drop.js")
172
+ ];
173
+ for (const candidate of candidates) {
174
+ if (fs.existsSync(candidate)) {
175
+ return candidate;
176
+ }
177
+ }
178
+ }
179
+ catch {
180
+ // Ignore file URL resolution errors on edge runtimes
181
+ }
182
+ return null;
183
+ }
184
+ export function defineContextDropConfig(config) {
185
+ return config;
186
+ }
187
+ export function createContextDropFetchHandler(config = {}) {
188
+ const rateLimitStore = new Map();
189
+ const getStorage = () => config.storage ?? getSharedDefaultStorage(config.storageDir);
190
+ const isEnabled = () => {
191
+ if (config.enabled !== undefined)
192
+ return Boolean(config.enabled);
193
+ const envFlag = (process.env.CONTEXT_DROP_ENABLED ?? "").trim().toLowerCase();
194
+ if (envFlag === "false" || envFlag === "0")
195
+ return false;
196
+ return true;
197
+ };
198
+ const getEnvironment = () => resolveHostEnvironment(config.environment);
199
+ const getResolvedSelectionMode = (envName) => {
200
+ if (config.selectionMode === "smart")
201
+ return "smart";
202
+ if (config.selectionMode === "verbose")
203
+ return "verbose";
204
+ return envName === "production" ? "smart" : "verbose";
205
+ };
206
+ const getUploadValidationOptions = () => ({
207
+ maxAttachmentSize: config.limits?.maxAttachmentSize ?? 10 * 1024 * 1024,
208
+ allowedContentTypes: config.limits?.allowedContentTypes ?? [...DEFAULT_ALLOWED_CONTENT_TYPES],
209
+ maxImageDimensions: config.limits?.maxImageDimensions ?? [4096, 4096]
210
+ });
211
+ const buildPublicWidgetConfig = () => {
212
+ const envName = getEnvironment();
213
+ const pos = config.position && VALID_POSITIONS.includes(config.position)
214
+ ? config.position
215
+ : "bottom_right";
216
+ const excluded = Array.from(new Set([
217
+ ...MANDATORY_SERVER_EXCLUDED_SELECTORS,
218
+ ...(config.privacy?.excludedSelectors ?? [])
219
+ ]));
220
+ return {
221
+ enabled: isEnabled(),
222
+ environment: envName,
223
+ position: pos,
224
+ placeholder: config.placeholder || "What would you like to tell us?",
225
+ csrf_token: null,
226
+ agent: {
227
+ enabled: false
228
+ },
229
+ features: {
230
+ element_selection: config.features?.elementSelection ?? true,
231
+ selection_mode: getResolvedSelectionMode(envName),
232
+ screenshot_capture: config.features?.screenshotCapture ?? true,
233
+ element_capture_padding: config.features?.elementCapturePadding ?? 16,
234
+ smart_capture_padding: config.features?.smartCapturePadding ?? 84
235
+ },
236
+ limits: {
237
+ max_attachments: config.limits?.maxAttachments ?? 10,
238
+ max_element_references: config.limits?.maxElementReferences ?? 10,
239
+ max_attachment_size: config.limits?.maxAttachmentSize ?? 10 * 1024 * 1024,
240
+ allowed_content_types: config.limits?.allowedContentTypes ?? [
241
+ ...DEFAULT_ALLOWED_CONTENT_TYPES
242
+ ],
243
+ max_image_dimensions: config.limits?.maxImageDimensions ?? [4096, 4096]
244
+ },
245
+ privacy: {
246
+ excluded_selectors: excluded
247
+ }
248
+ };
249
+ };
250
+ const checkSubmissionAuth = async (request) => {
251
+ const resolved = config.resolveSubmitter ? await config.resolveSubmitter(request) : null;
252
+ const allowAnon = config.allowAnonymous ?? true;
253
+ if (!allowAnon && (!resolved || (resolved.id === undefined && !resolved.label))) {
254
+ return {
255
+ ok: false,
256
+ status: 401,
257
+ error: "Authentication required to submit feedback"
258
+ };
259
+ }
260
+ if (config.authorizeSubmission) {
261
+ const permitted = await config.authorizeSubmission(request, resolved);
262
+ if (!permitted) {
263
+ return { ok: false, status: 403, error: "Forbidden" };
264
+ }
265
+ }
266
+ return {
267
+ ok: true,
268
+ submitter: resolved ?? {}
269
+ };
270
+ };
271
+ const checkRateLimit = (request) => {
272
+ if (config.rateLimit === false)
273
+ return true;
274
+ const maxRequests = config.rateLimit?.maxRequests ?? 20;
275
+ const periodSeconds = config.rateLimit?.periodSeconds ?? 3600;
276
+ if (maxRequests <= 0 || periodSeconds <= 0)
277
+ return true;
278
+ const nowMs = Date.now();
279
+ for (const [k, v] of rateLimitStore.entries()) {
280
+ if (v.expiresAtMs <= nowMs) {
281
+ rateLimitStore.delete(k);
282
+ }
283
+ }
284
+ const ip = resolveClientIp(request);
285
+ const windowBucket = Math.floor(nowMs / (periodSeconds * 1000));
286
+ const key = `${ip}:${windowBucket}`;
287
+ const existing = rateLimitStore.get(key);
288
+ if (!existing) {
289
+ rateLimitStore.set(key, {
290
+ count: 1,
291
+ expiresAtMs: (windowBucket + 1) * periodSeconds * 1000
292
+ });
293
+ return true;
294
+ }
295
+ existing.count += 1;
296
+ return existing.count <= maxRequests;
297
+ };
298
+ const handleMcpEndpoint = async (request) => {
299
+ const expectedApiKey = (config.mcp?.apiKey ??
300
+ process.env.CONTEXT_DROP_MCP_API_KEY ??
301
+ "").trim();
302
+ const mcpEnabled = config.mcp?.enabled !== undefined
303
+ ? Boolean(config.mcp.enabled)
304
+ : process.env.CONTEXT_DROP_MCP_ENABLED === "true" || expectedApiKey.length > 0;
305
+ if (!mcpEnabled) {
306
+ return jsonResponse({ error: "Not Found" }, 404);
307
+ }
308
+ if (config.mcp?.authorize) {
309
+ const ok = await config.mcp.authorize(request);
310
+ if (!ok) {
311
+ return jsonResponse({ error: "Unauthorized MCP request" }, 401);
312
+ }
313
+ }
314
+ else {
315
+ if (!expectedApiKey) {
316
+ return jsonResponse({ error: "Unauthorized: MCP API key is not configured" }, 401);
317
+ }
318
+ const authHeader = request.headers.get("authorization") ?? "";
319
+ const provided = authHeader.toLowerCase().startsWith("bearer ")
320
+ ? authHeader.slice(7).trim()
321
+ : "";
322
+ if (!timingSafeCompareStrings(provided, expectedApiKey)) {
323
+ return jsonResponse({ error: "Unauthorized: Invalid or missing Bearer token" }, 401);
324
+ }
325
+ }
326
+ const rawBody = await request.text();
327
+ let parsedPayload;
328
+ try {
329
+ parsedPayload = JSON.parse(rawBody);
330
+ }
331
+ catch (err) {
332
+ return jsonResponse({
333
+ jsonrpc: "2.0",
334
+ id: null,
335
+ error: {
336
+ code: -32700,
337
+ message: `Parse error: ${err.message}`
338
+ }
339
+ }, 200);
340
+ }
341
+ const dispatcher = new ContextDropMcpDispatcher({
342
+ storage: getStorage(),
343
+ hostEnvironment: getEnvironment(),
344
+ localOnly: true
345
+ });
346
+ const rpcResponse = await dispatcher.dispatch(parsedPayload);
347
+ if (rpcResponse === null) {
348
+ return new Response(null, { status: 202 });
349
+ }
350
+ return jsonResponse(rpcResponse, 200);
351
+ };
352
+ const handler = async (request) => {
353
+ const url = new URL(request.url, "http://localhost");
354
+ const subRoute = resolveSubRoute(url.pathname);
355
+ const method = request.method.toUpperCase();
356
+ // Remote MCP endpoint has independent enablement & auth (matching Rails McpController)
357
+ if (subRoute === "mcp" && method === "POST") {
358
+ return handleMcpEndpoint(request);
359
+ }
360
+ const corsHeaders = buildCorsHeaders(request, config.allowedOrigins);
361
+ if (method === "OPTIONS") {
362
+ if (Object.keys(corsHeaders).length > 0) {
363
+ return new Response(null, { status: 204, headers: corsHeaders });
364
+ }
365
+ const origin = request.headers.get("origin");
366
+ if (origin && resolveRequestExpectedOrigins(request).has(origin.toLowerCase())) {
367
+ return new Response(null, { status: 204 });
368
+ }
369
+ return new Response(null, { status: 403 });
370
+ }
371
+ if (!isEnabled()) {
372
+ return jsonResponse({ error: "Not Found" }, 404, corsHeaders);
373
+ }
374
+ if (subRoute === "health" && method === "GET") {
375
+ return jsonResponse({
376
+ status: "ok",
377
+ environment: getEnvironment(),
378
+ version: VERSION
379
+ }, 200, corsHeaders);
380
+ }
381
+ if (subRoute === "assets/context_drop.js" && method === "GET") {
382
+ const bundlePath = resolveWidgetBundleFilePath();
383
+ if (!bundlePath) {
384
+ return new Response("Not Found", { status: 404, headers: corsHeaders });
385
+ }
386
+ const jsContent = fs.readFileSync(bundlePath, "utf8");
387
+ return new Response(jsContent, {
388
+ status: 200,
389
+ headers: {
390
+ "Content-Type": "application/javascript; charset=utf-8",
391
+ "Cache-Control": "public, max-age=3600",
392
+ ...corsHeaders
393
+ }
394
+ });
395
+ }
396
+ if (subRoute === "config" && method === "GET") {
397
+ const auth = await checkSubmissionAuth(request);
398
+ if (!auth.ok) {
399
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
400
+ }
401
+ return jsonResponse(buildPublicWidgetConfig(), 200, corsHeaders);
402
+ }
403
+ if (subRoute === "attachments" && method === "POST") {
404
+ const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
405
+ if (!originCheck.ok) {
406
+ return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
407
+ }
408
+ const auth = await checkSubmissionAuth(request);
409
+ if (!auth.ok) {
410
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
411
+ }
412
+ if (!checkRateLimit(request)) {
413
+ return jsonResponse({ error: "Rate limit exceeded. Please try again later." }, 429, corsHeaders);
414
+ }
415
+ try {
416
+ const formData = await request.formData();
417
+ const fileEntry = formData.get("file");
418
+ if (!fileEntry || typeof fileEntry.arrayBuffer !== "function") {
419
+ throw new UploadValidationError("Missing file upload");
420
+ }
421
+ const blobObj = fileEntry;
422
+ const ab = await blobObj.arrayBuffer();
423
+ const validated = validateBinaryUpload(new Uint8Array(ab), typeof blobObj.name === "string" ? blobObj.name : "attachment.png", getUploadValidationOptions());
424
+ const saved = await getStorage().savePendingBlob(validated);
425
+ return jsonResponse({
426
+ signed_blob_id: saved.signed_blob_id,
427
+ filename: validated.filename,
428
+ content_type: validated.content_type,
429
+ byte_size: validated.byte_size,
430
+ dimensions: validated.dimensions
431
+ }, 201, corsHeaders);
432
+ }
433
+ catch (err) {
434
+ if (err instanceof UploadValidationError) {
435
+ return jsonResponse({ error: err.message }, err.status, corsHeaders);
436
+ }
437
+ return jsonResponse({ error: err.message || "Invalid attachment upload" }, 422, corsHeaders);
438
+ }
439
+ }
440
+ if (subRoute === "feedback" && method === "POST") {
441
+ const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
442
+ if (!originCheck.ok) {
443
+ return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
444
+ }
445
+ const auth = await checkSubmissionAuth(request);
446
+ if (!auth.ok) {
447
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
448
+ }
449
+ if (!checkRateLimit(request)) {
450
+ return jsonResponse({ error: "Rate limit exceeded. Please try again later." }, 429, corsHeaders);
451
+ }
452
+ try {
453
+ const rawJson = (await request.json().catch(() => ({})));
454
+ const payload = rawJson["feedback"] && typeof rawJson["feedback"] === "object"
455
+ ? asRecord(rawJson["feedback"])
456
+ : asRecord(rawJson);
457
+ const rawElements = Array.isArray(payload["element_references"])
458
+ ? payload["element_references"]
459
+ : [];
460
+ const rawAttachments = Array.isArray(payload["attachments"]) ? payload["attachments"] : [];
461
+ const maxAttachments = config.limits?.maxAttachments ?? 10;
462
+ const maxElements = config.limits?.maxElementReferences ?? 10;
463
+ if (rawAttachments.length > maxAttachments) {
464
+ return jsonResponse({
465
+ error: `Attachments count (${rawAttachments.length}) exceeds maximum allowed (${maxAttachments})`
466
+ }, 422, corsHeaders);
467
+ }
468
+ if (rawElements.length > maxElements) {
469
+ return jsonResponse({
470
+ error: `Element references count (${rawElements.length}) exceeds maximum allowed (${maxElements})`
471
+ }, 422, corsHeaders);
472
+ }
473
+ const sanitizedElements = rawElements.map((el) => sanitizeElementReference(el));
474
+ const uploadOpts = getUploadValidationOptions();
475
+ const storage = getStorage();
476
+ const preparedAttachments = [];
477
+ 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
+ }
534
+ }
535
+ const messageStr = String(payload["message"] ?? "").trim();
536
+ const message = messageStr.length > 0 ? messageStr : null;
537
+ const pageUrl = (String(payload["page_url"] ?? "").trim() ||
538
+ request.headers.get("referer")?.trim() ||
539
+ "");
540
+ if (!pageUrl) {
541
+ return jsonResponse({ error: "Page url can't be blank" }, 422, corsHeaders);
542
+ }
543
+ if (!message && sanitizedElements.length === 0 && preparedAttachments.length === 0) {
544
+ return jsonResponse({
545
+ error: "Feedback must include a message, an attachment, or a selected DOM element"
546
+ }, 422, corsHeaders);
547
+ }
548
+ const hostEnv = getEnvironment();
549
+ const sanitizedMeta = sanitizeGenericMetadata(payload["metadata"]);
550
+ sanitizedMeta["environment"] = hostEnv;
551
+ const userAgent = String(payload["user_agent"] ?? "").trim() ||
552
+ request.headers.get("user-agent")?.trim() ||
553
+ null;
554
+ const created = await storage.createFeedback({
555
+ environment: hostEnv,
556
+ message,
557
+ page_url: pageUrl,
558
+ user_agent: userAgent,
559
+ session_id: extractHashedSessionId(request),
560
+ submitter: auth.submitter,
561
+ metadata: sanitizedMeta,
562
+ element_references: sanitizedElements,
563
+ attachments: preparedAttachments
564
+ });
565
+ if (config.onFeedbackCreated) {
566
+ try {
567
+ await config.onFeedbackCreated(created);
568
+ }
569
+ catch (cbErr) {
570
+ console.error("[context-drop] onFeedbackCreated callback error:", cbErr);
571
+ }
572
+ }
573
+ return jsonResponse({
574
+ id: created.id,
575
+ environment: created.environment,
576
+ status: created.status,
577
+ attachments_count: created.attachments.length,
578
+ element_references_count: created.element_references.length,
579
+ created_at: created.created_at
580
+ }, 201, corsHeaders);
581
+ }
582
+ catch (err) {
583
+ if (err instanceof SensitiveElementError || err instanceof UploadValidationError) {
584
+ return jsonResponse({ error: err.message }, err.status, corsHeaders);
585
+ }
586
+ return jsonResponse({ error: err.message || "Failed to process feedback" }, 422, corsHeaders);
587
+ }
588
+ }
589
+ return jsonResponse({ error: "Not Found" }, 404, corsHeaders);
590
+ };
591
+ return Object.assign(handler, {
592
+ resetRateLimits: () => rateLimitStore.clear(),
593
+ getStorage
594
+ });
595
+ }
596
+ /**
597
+ * Next.js App Router route handler factory (`app/api/context-drop/[[...path]]/route.ts`).
598
+ *
599
+ * @example
600
+ * ```ts
601
+ * import { createContextDropNextHandler } from "context-drop/next/server";
602
+ * export const { GET, POST, OPTIONS } = createContextDropNextHandler();
603
+ * ```
604
+ */
605
+ export function createContextDropNextHandler(config = {}) {
606
+ const fetchHandler = createContextDropFetchHandler(config);
607
+ return {
608
+ GET: (request) => fetchHandler(request),
609
+ POST: (request) => fetchHandler(request),
610
+ OPTIONS: (request) => fetchHandler(request),
611
+ handler: fetchHandler
612
+ };
613
+ }
614
+ /**
615
+ * Next.js Pages Router / Node HTTP handler factory (`pages/api/context-drop/[[...path]].ts`).
616
+ *
617
+ * Works both with `export const config = { api: { bodyParser: false } }` (required for
618
+ * multipart `/attachments` uploads) and with pre-parsed JSON bodies.
619
+ */
620
+ export function createContextDropPagesHandler(config = {}) {
621
+ const fetchHandler = createContextDropFetchHandler(config);
622
+ return async function pagesApiHandler(req, res) {
623
+ const proto = (typeof req.headers["x-forwarded-proto"] === "string"
624
+ ? req.headers["x-forwarded-proto"].split(",")[0]?.trim()
625
+ : undefined) || "http";
626
+ const host = (typeof req.headers["x-forwarded-host"] === "string"
627
+ ? req.headers["x-forwarded-host"].split(",")[0]?.trim()
628
+ : undefined) ||
629
+ req.headers.host ||
630
+ "localhost";
631
+ const fullUrl = `${proto}://${host}${req.url || "/"}`;
632
+ const headers = new Headers();
633
+ for (const [k, v] of Object.entries(req.headers)) {
634
+ if (Array.isArray(v)) {
635
+ for (const item of v)
636
+ headers.append(k, item);
637
+ }
638
+ else if (typeof v === "string") {
639
+ headers.set(k, v);
640
+ }
641
+ }
642
+ const method = (req.method || "GET").toUpperCase();
643
+ let bodyBuffer;
644
+ if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS") {
645
+ if (req.body !== undefined && req.body !== null) {
646
+ if (Buffer.isBuffer(req.body)) {
647
+ bodyBuffer = req.body;
648
+ }
649
+ else if (typeof req.body === "string") {
650
+ bodyBuffer = Buffer.from(req.body, "utf8");
651
+ }
652
+ else {
653
+ bodyBuffer = Buffer.from(JSON.stringify(req.body), "utf8");
654
+ }
655
+ }
656
+ else {
657
+ const chunks = [];
658
+ for await (const chunk of req) {
659
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
660
+ }
661
+ bodyBuffer = Buffer.concat(chunks);
662
+ }
663
+ }
664
+ const webRequest = new Request(fullUrl, {
665
+ method,
666
+ headers,
667
+ body: bodyBuffer ? new Uint8Array(bodyBuffer) : undefined
668
+ });
669
+ const webResponse = await fetchHandler(webRequest);
670
+ res.statusCode = webResponse.status;
671
+ webResponse.headers.forEach((value, key) => {
672
+ res.setHeader(key, value);
673
+ });
674
+ const responseBuffer = Buffer.from(await webResponse.arrayBuffer());
675
+ res.end(responseBuffer);
676
+ };
677
+ }
@@ -0,0 +1,8 @@
1
+ export * from "./types.js";
2
+ export * from "./sanitizer.js";
3
+ export * from "./upload-validator.js";
4
+ export * from "./storage/memory.js";
5
+ export * from "./storage/local.js";
6
+ export * from "./storage/postgres.js";
7
+ export * from "./handler.js";
8
+ export { ContextDropMcpDispatcher, EnvironmentRouter, MCP_PROTOCOL_VERSION, RemoteMcpClient, RemoteMcpError, createContextDropMcpServer, runContextDropMcpStdio } from "../mcp/index.js";