context_drop 0.1.1 → 0.1.2
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.
- checksums.yaml +4 -4
- data/README.md +68 -11
- data/app/assets/javascripts/context_drop/context_drop.js +156 -48
- data/app/controllers/context_drop/configs_controller.rb +3 -1
- data/app/javascript/context_drop/__tests__/api-client.test.ts +310 -0
- data/app/javascript/context_drop/api-client.ts +153 -48
- data/app/javascript/context_drop/types.ts +1 -0
- data/app/javascript/context_drop/widget.ts +3 -0
- data/lib/context_drop/version.rb +1 -1
- metadata +2 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 8e85646e98e14b9d251eed6f1ec7ebca93d1139ce054423488256703b55d90f6
|
|
4
|
+
data.tar.gz: a548299755be327a69d04879210310c062c1bf843e7eb801afdf35bec5752b24
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 845dc9ae6803ed867276fffaa94324f8fc7ea7f5f526ed42f3c91bd9e2bd89dafbb45428b8a8b448bdac6d104220143354b5e46b26031f369de665d9f70347e5
|
|
7
|
+
data.tar.gz: e5e07b0ba1e732fa5a42752ea7385e513ae038484f0fd5c8895eb3f431cba1fb92a87e7dd2aa3bd5ee79bf1b6a1472a282cbca752b37a04e512619ff64057f03
|
data/README.md
CHANGED
|
@@ -203,33 +203,88 @@ Real-world Rails interfaces have sticky navbars, floating promo ribbons, translu
|
|
|
203
203
|
|
|
204
204
|
ContextDrop ships with a built-in **Model Context Protocol (MCP)** server (`ContextDrop::MCP::Server`) so you or your AI coding agent can pull bug reports, inspect exact CSS selectors and DOM paths, view multimodal screenshots, and mark issues resolved without leaving your editor.
|
|
205
205
|
|
|
206
|
-
|
|
207
|
-
-
|
|
208
|
-
|
|
206
|
+
<p align="center">
|
|
207
|
+
<img src="docs/images/demo-mcp-agent.png" alt="ContextDrop MCP server tool calls (list_feedbacks and get_feedback) and root-cause diagnosis inside an AI coding agent" width="100%" />
|
|
208
|
+
</p>
|
|
209
|
+
|
|
210
|
+
> **Above:** Triage flow inside an AI coding agent connected to the `context-drop` MCP server on the live playground. The agent invokes `list_feedbacks` (`{ status: "new" }`) and `get_feedback` (`{ id: 12, include_images: true }`), inspects both the structured `ElementReference` geometry (`button#upgrade-cluster-btn`, `169.1×33px`) and the redacted multimodal `image/png` screenshot block, and pinpoints the exact overlapping CSS rule in `demo/index.html`.
|
|
211
|
+
|
|
212
|
+
### Exposed MCP Capabilities
|
|
213
|
+
|
|
214
|
+
| Type | Name / URI | Description |
|
|
215
|
+
|---|---|---|
|
|
216
|
+
| **Tool** | `list_feedbacks` | Filter & paginate submissions by `status` (`new`, `reviewed`, `resolved`, `dismissed`), `page_url`, or free-text `query` across messages, selectors, and DOM paths. |
|
|
217
|
+
| **Tool** | `get_feedback` | Fetch full `Feedback`, all `ElementReference` DOM snapshots, and inline base64 `image` blocks (`include_images: true` by default). |
|
|
218
|
+
| **Tool** | `get_feedback_attachment` | Retrieve an individual `Attachment` record and its binary screenshot/image as an MCP `image` content block. |
|
|
219
|
+
| **Tool** | `update_feedback_status` | Transition a feedback record between `new`, `reviewed`, `resolved`, and `dismissed`. |
|
|
220
|
+
| **Resource** | `contextdrop://feedbacks/new` | Live JSON feed of unresolved `new` feedback records (up to 50 most recent). |
|
|
221
|
+
| **Resource** | `contextdrop://feedbacks/{id}` | Full JSON snapshot of a specific feedback submission, its pinned elements, and attachment metadata. |
|
|
222
|
+
| **Prompt** | `investigate_feedback` | Generates a structured root-cause investigation brief (with attached screenshots) for a given `feedback_id`. |
|
|
223
|
+
|
|
224
|
+
---
|
|
209
225
|
|
|
210
|
-
### Option 1: Local `stdio`
|
|
226
|
+
### Option 1: Project-Scoped Local `stdio` (Inherited Shell Environment)
|
|
211
227
|
|
|
212
|
-
|
|
228
|
+
When using a workspace-scoped MCP file (e.g., `.mcp.json` in Claude Code or `.cursor/mcp.json` launched from a terminal) where your IDE already runs inside the Rails root and inherits your Ruby shell `PATH`:
|
|
213
229
|
|
|
214
230
|
```json
|
|
215
231
|
{
|
|
216
232
|
"mcpServers": {
|
|
217
233
|
"context-drop": {
|
|
218
|
-
"command": "
|
|
219
|
-
"args": ["context_drop:mcp"]
|
|
234
|
+
"command": "bundle",
|
|
235
|
+
"args": ["exec", "./bin/rails", "context_drop:mcp"]
|
|
220
236
|
}
|
|
221
237
|
}
|
|
222
238
|
}
|
|
223
239
|
```
|
|
224
240
|
|
|
225
|
-
### Option 2:
|
|
241
|
+
### Option 2: Strict Sandboxes, Global IDE Configs & Ruby Version Managers (`rbenv`, `mise`, `asdf`, `rvm`)
|
|
242
|
+
|
|
243
|
+
Strict sandboxed coding agents and GUI-launched desktop IDEs (such as **Antigravity** `mcp_config.json`, **Claude Desktop**, global `~/.cursor/mcp.json`, **Windsurf**, or VS Code launched from macOS Finder / Linux desktop) typically spawn MCP subprocesses with:
|
|
244
|
+
1. **A non-project working directory** (often `/` or `$HOME`, causing relative `./bin/rails` or `Gemfile` lookup to fail), and
|
|
245
|
+
2. **A stripped minimal `PATH`** (`/usr/bin:/bin:/usr/sbin:/sbin`) without sourcing `~/.zshrc` or `~/.bashrc`—causing `/usr/bin/env ruby` inside `bin/rails` to hit an outdated system Ruby (e.g., macOS Ruby `2.6`) or fail to locate `bundle` and Homebrew native libraries (`libpq`, `sqlite3`, `vips`).
|
|
226
246
|
|
|
227
|
-
|
|
247
|
+
To make `stdio` work reliably in strict sandboxes, wrap the launch command with `/bin/zsh -c` (or `/bin/bash -c` on Linux), `cd` into your Rails application root, `exec` your version manager's `bundle` binary directly, and declare an explicit absolute `PATH`:
|
|
228
248
|
|
|
229
249
|
```json
|
|
230
250
|
{
|
|
231
251
|
"mcpServers": {
|
|
232
|
-
"context-drop
|
|
252
|
+
"context-drop": {
|
|
253
|
+
"command": "/bin/zsh",
|
|
254
|
+
"args": [
|
|
255
|
+
"-c",
|
|
256
|
+
"cd /absolute/path/to/your-rails-app && exec /Users/<you>/.rbenv/shims/bundle exec ./bin/rails context_drop:mcp"
|
|
257
|
+
],
|
|
258
|
+
"env": {
|
|
259
|
+
"PATH": "/Users/<you>/.rbenv/shims:/Users/<you>/.rbenv/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
> [!TIP]
|
|
267
|
+
> **Adapting Option 2 to any machine or Ruby version manager:**
|
|
268
|
+
> - **Use literal absolute paths (avoid `~` or `$HOME` inside JSON `env`):** MCP hosts pass `env` directly to `execve` without shell expansion. Run `pwd`, `which bundle`, and `echo $PATH` in your Rails app terminal to get your exact paths.
|
|
269
|
+
> - **Keep `exec` before `bundle`:** `exec` replaces the `zsh`/`bash` wrapper in-place so `stdin`/`stdout` JSON-RPC frames remain unbuffered and IDE shutdown signals (`SIGTERM`) cleanly terminate the Ruby process without leaving orphans.
|
|
270
|
+
> - **Debug `stdio` boot issues:** Set `"CONTEXT_DROP_MCP_DEBUG": "1"` inside `"env"` to stream verbose Rails/ActiveRecord boot diagnostics to `stderr` (MCP `stdout` always stays strictly reserved for JSON-RPC frames).
|
|
271
|
+
|
|
272
|
+
| Ruby Environment / OS | `<bundle-path>` for `exec` | Directories to Prepend to `env.PATH` |
|
|
273
|
+
|---|---|---|
|
|
274
|
+
| **`rbenv`** (macOS / Linux) | `/Users/<you>/.rbenv/shims/bundle` | `/Users/<you>/.rbenv/shims:/Users/<you>/.rbenv/bin` |
|
|
275
|
+
| **`mise`** (macOS / Linux) | `/Users/<you>/.local/share/mise/shims/bundle` | `/Users/<you>/.local/share/mise/shims` |
|
|
276
|
+
| **`asdf`** (macOS / Linux) | `/Users/<you>/.asdf/shims/bundle` | `/Users/<you>/.asdf/shims:/Users/<you>/.asdf/bin` |
|
|
277
|
+
| **`rvm`** (macOS / Linux) | `/Users/<you>/.rvm/wrappers/default/bundle` | `/Users/<you>/.rvm/gems/default/bin:/Users/<you>/.rvm/bin` |
|
|
278
|
+
| **Homebrew / Linux `/usr/local`** | `/opt/homebrew/opt/ruby/bin/bundle` or `/usr/local/bin/bundle` | `/opt/homebrew/opt/ruby/bin:/opt/homebrew/bin:/usr/local/bin` |
|
|
279
|
+
|
|
280
|
+
### Option 3: Streamable HTTP Transport (Docker, Isolated Sandboxes, Staging & Production)
|
|
281
|
+
|
|
282
|
+
If your Rails app runs inside **Docker / Devcontainers**, if your agent sandbox blocks host binary execution outside the workspace, or if you want to triage feedback directly from **staging or production**, enable the HTTP endpoint with a bearer token (`CONTEXT_DROP_MCP_ENABLED=true` and `CONTEXT_DROP_MCP_API_KEY=<your-secret-token>`) and point your MCP client to `POST /context_drop/mcp`:
|
|
283
|
+
|
|
284
|
+
```json
|
|
285
|
+
{
|
|
286
|
+
"mcpServers": {
|
|
287
|
+
"context-drop-http": {
|
|
233
288
|
"url": "https://staging.example.com/context_drop/mcp",
|
|
234
289
|
"headers": {
|
|
235
290
|
"Authorization": "Bearer <your-secret-token>"
|
|
@@ -239,8 +294,10 @@ Enable MCP on your staging or production server with a bearer token (`CONTEXT_DR
|
|
|
239
294
|
}
|
|
240
295
|
```
|
|
241
296
|
|
|
297
|
+
*(For local Docker or strict-sandbox setups, use `"url": "http://localhost:3000/context_drop/mcp"` against your running `bin/rails server`.)*
|
|
298
|
+
|
|
242
299
|
Once connected, prompt your coding agent directly in your IDE:
|
|
243
|
-
> *"
|
|
300
|
+
> *"Check the `context-drop` MCP server for new feedbacks, inspect the pinned element selector and screenshot, diagnose the root cause in our Rails views/CSS, and mark the feedback resolved."*
|
|
244
301
|
|
|
245
302
|
---
|
|
246
303
|
|
|
@@ -1157,83 +1157,188 @@
|
|
|
1157
1157
|
// --- Module: api-client.ts ---
|
|
1158
1158
|
class ContextDropApiClient {
|
|
1159
1159
|
baseUrl ;
|
|
1160
|
+
cachedCsrfToken = null;
|
|
1161
|
+
inFlightConfigPromise = null;
|
|
1160
1162
|
|
|
1161
1163
|
constructor(baseUrl = "/context_drop") {
|
|
1162
1164
|
this.baseUrl = baseUrl.replace(/\/+$/, "") || "/context_drop";
|
|
1163
1165
|
}
|
|
1164
1166
|
|
|
1165
1167
|
getCsrfToken() {
|
|
1168
|
+
const metaToken = this.getMetaCsrfToken();
|
|
1169
|
+
if (metaToken) {
|
|
1170
|
+
return metaToken;
|
|
1171
|
+
}
|
|
1172
|
+
return this.cachedCsrfToken;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
setCsrfToken(token ) {
|
|
1176
|
+
this.cachedCsrfToken = token ? token.trim() : null;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
getMetaCsrfToken() {
|
|
1166
1180
|
if (typeof document === "undefined") return null;
|
|
1167
1181
|
const meta = document.querySelector('meta[name="csrf-token"]');
|
|
1168
|
-
|
|
1182
|
+
const content = meta ? meta.getAttribute("content") : null;
|
|
1183
|
+
return content && content.trim().length > 0 ? content.trim() : null;
|
|
1169
1184
|
}
|
|
1170
1185
|
|
|
1171
1186
|
async fetchConfig() {
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1187
|
+
if (this.inFlightConfigPromise) {
|
|
1188
|
+
return this.inFlightConfigPromise;
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
this.inFlightConfigPromise = (async () => {
|
|
1192
|
+
try {
|
|
1193
|
+
const response = await fetch(`${this.baseUrl}/config`, {
|
|
1194
|
+
method: "GET",
|
|
1195
|
+
credentials: "same-origin",
|
|
1196
|
+
headers: {
|
|
1197
|
+
Accept: "application/json"
|
|
1198
|
+
}
|
|
1199
|
+
});
|
|
1200
|
+
|
|
1201
|
+
if (!response.ok) {
|
|
1202
|
+
throw new Error(`Failed to fetch ContextDrop config (${response.status})`);
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
const config = (await response.json()) ;
|
|
1206
|
+
if (config && typeof config.csrf_token === "string" && config.csrf_token.trim().length > 0) {
|
|
1207
|
+
this.cachedCsrfToken = config.csrf_token.trim();
|
|
1208
|
+
if (typeof document !== "undefined") {
|
|
1209
|
+
const meta = document.querySelector('meta[name="csrf-token"]');
|
|
1210
|
+
if (meta) {
|
|
1211
|
+
meta.setAttribute("content", this.cachedCsrfToken);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
return config;
|
|
1216
|
+
} finally {
|
|
1217
|
+
this.inFlightConfigPromise = null;
|
|
1177
1218
|
}
|
|
1178
|
-
});
|
|
1219
|
+
})();
|
|
1220
|
+
|
|
1221
|
+
return this.inFlightConfigPromise;
|
|
1222
|
+
}
|
|
1179
1223
|
|
|
1180
|
-
|
|
1181
|
-
|
|
1224
|
+
async resolveCsrfToken(forceRefresh = false) {
|
|
1225
|
+
if (!forceRefresh) {
|
|
1226
|
+
const metaToken = this.getMetaCsrfToken();
|
|
1227
|
+
if (metaToken) {
|
|
1228
|
+
return metaToken;
|
|
1229
|
+
}
|
|
1230
|
+
if (this.cachedCsrfToken) {
|
|
1231
|
+
return this.cachedCsrfToken;
|
|
1232
|
+
}
|
|
1182
1233
|
}
|
|
1183
1234
|
|
|
1184
|
-
|
|
1235
|
+
try {
|
|
1236
|
+
const config = await this.fetchConfig();
|
|
1237
|
+
if (config && config.csrf_token) {
|
|
1238
|
+
return config.csrf_token.trim();
|
|
1239
|
+
}
|
|
1240
|
+
} catch {
|
|
1241
|
+
// Continue and fall back to current token or null
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
return this.cachedCsrfToken || this.getMetaCsrfToken();
|
|
1185
1245
|
}
|
|
1186
1246
|
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1247
|
+
isCsrfError(status , message ) {
|
|
1248
|
+
if (status !== 422) return false;
|
|
1249
|
+
return /csrf|authenticity/i.test(message);
|
|
1250
|
+
}
|
|
1190
1251
|
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1252
|
+
async executeWithCsrfRetry (
|
|
1253
|
+
requestFn ,
|
|
1254
|
+
defaultErrorMessage
|
|
1255
|
+
) {
|
|
1256
|
+
let csrfToken = await this.resolveCsrfToken(false);
|
|
1257
|
+
let response = await requestFn(csrfToken);
|
|
1258
|
+
|
|
1259
|
+
if (response.ok) {
|
|
1260
|
+
return (await response.json()) ;
|
|
1197
1261
|
}
|
|
1198
1262
|
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1263
|
+
if (response.status === 422) {
|
|
1264
|
+
const rawText = await response.text();
|
|
1265
|
+
let parsedError = null;
|
|
1266
|
+
try {
|
|
1267
|
+
const json = JSON.parse(rawText) ;
|
|
1268
|
+
if (json && typeof json.error === "string") {
|
|
1269
|
+
parsedError = json.error;
|
|
1270
|
+
}
|
|
1271
|
+
} catch {
|
|
1272
|
+
// Not JSON
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
const errorMessage = parsedError || rawText || "";
|
|
1276
|
+
const shouldRetryCsrf =
|
|
1277
|
+
this.isCsrfError(response.status, errorMessage) || (!csrfToken && response.status === 422);
|
|
1278
|
+
|
|
1279
|
+
if (shouldRetryCsrf) {
|
|
1280
|
+
csrfToken = await this.resolveCsrfToken(true);
|
|
1281
|
+
response = await requestFn(csrfToken);
|
|
1282
|
+
if (response.ok) {
|
|
1283
|
+
return (await response.json()) ;
|
|
1284
|
+
}
|
|
1285
|
+
const retryErrBody = await response.json().catch(() => ({}));
|
|
1286
|
+
throw new Error(
|
|
1287
|
+
(retryErrBody ).error || `${defaultErrorMessage} (${response.status})`
|
|
1288
|
+
);
|
|
1289
|
+
}
|
|
1205
1290
|
|
|
1206
|
-
|
|
1207
|
-
const errBody = await response.json().catch(() => ({}));
|
|
1208
|
-
throw new Error((errBody ).error || `Upload failed (${response.status})`);
|
|
1291
|
+
throw new Error(parsedError || errorMessage || `${defaultErrorMessage} (${response.status})`);
|
|
1209
1292
|
}
|
|
1210
1293
|
|
|
1211
|
-
|
|
1294
|
+
const errBody = await response.json().catch(() => ({}));
|
|
1295
|
+
throw new Error(
|
|
1296
|
+
(errBody ).error || `${defaultErrorMessage} (${response.status})`
|
|
1297
|
+
);
|
|
1212
1298
|
}
|
|
1213
1299
|
|
|
1214
|
-
async
|
|
1215
|
-
const
|
|
1216
|
-
|
|
1217
|
-
|
|
1300
|
+
async uploadAttachment(file , filename ) {
|
|
1301
|
+
const makeRequest = async (csrfToken ) => {
|
|
1302
|
+
const formData = new FormData();
|
|
1303
|
+
formData.append("file", file, filename);
|
|
1304
|
+
|
|
1305
|
+
const headers = {
|
|
1306
|
+
Accept: "application/json"
|
|
1307
|
+
};
|
|
1308
|
+
if (csrfToken) {
|
|
1309
|
+
headers["X-CSRF-Token"] = csrfToken;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
return fetch(`${this.baseUrl}/attachments`, {
|
|
1313
|
+
method: "POST",
|
|
1314
|
+
credentials: "same-origin",
|
|
1315
|
+
headers,
|
|
1316
|
+
body: formData
|
|
1317
|
+
});
|
|
1218
1318
|
};
|
|
1219
|
-
const csrf = this.getCsrfToken();
|
|
1220
|
-
if (csrf) {
|
|
1221
|
-
headers["X-CSRF-Token"] = csrf;
|
|
1222
|
-
}
|
|
1223
1319
|
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
credentials: "same-origin",
|
|
1227
|
-
headers,
|
|
1228
|
-
body: JSON.stringify({ feedback: payload })
|
|
1229
|
-
});
|
|
1320
|
+
return this.executeWithCsrfRetry(makeRequest, "Upload failed");
|
|
1321
|
+
}
|
|
1230
1322
|
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1323
|
+
async submitFeedback(payload ) {
|
|
1324
|
+
const makeRequest = async (csrfToken ) => {
|
|
1325
|
+
const headers = {
|
|
1326
|
+
"Content-Type": "application/json",
|
|
1327
|
+
Accept: "application/json"
|
|
1328
|
+
};
|
|
1329
|
+
if (csrfToken) {
|
|
1330
|
+
headers["X-CSRF-Token"] = csrfToken;
|
|
1331
|
+
}
|
|
1235
1332
|
|
|
1236
|
-
|
|
1333
|
+
return fetch(`${this.baseUrl}/feedback`, {
|
|
1334
|
+
method: "POST",
|
|
1335
|
+
credentials: "same-origin",
|
|
1336
|
+
headers,
|
|
1337
|
+
body: JSON.stringify({ feedback: payload })
|
|
1338
|
+
});
|
|
1339
|
+
};
|
|
1340
|
+
|
|
1341
|
+
return this.executeWithCsrfRetry(makeRequest, "Submission failed");
|
|
1237
1342
|
}
|
|
1238
1343
|
}
|
|
1239
1344
|
|
|
@@ -2646,6 +2751,9 @@
|
|
|
2646
2751
|
limits: { ...this.config.limits, ...(parsed.limits || {}) },
|
|
2647
2752
|
privacy: { ...this.config.privacy, ...(parsed.privacy || {}) }
|
|
2648
2753
|
};
|
|
2754
|
+
if (parsed.csrf_token) {
|
|
2755
|
+
this.apiClient.setCsrfToken(parsed.csrf_token);
|
|
2756
|
+
}
|
|
2649
2757
|
} catch {
|
|
2650
2758
|
// Ignore malformed JSON attribute
|
|
2651
2759
|
}
|
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
module ContextDrop
|
|
4
4
|
class ConfigsController < ApplicationController
|
|
5
|
+
skip_forgery_protection only: [:widget_bundle] if respond_to?(:skip_forgery_protection)
|
|
5
6
|
before_action :enforce_submission_authorization!, only: [:show]
|
|
6
7
|
|
|
7
8
|
def show
|
|
8
|
-
|
|
9
|
+
token = form_authenticity_token if respond_to?(:form_authenticity_token, true)
|
|
10
|
+
render json: ContextDrop.config.public_widget_config.merge(csrf_token: token), status: :ok
|
|
9
11
|
end
|
|
10
12
|
|
|
11
13
|
def widget_bundle
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import { describe, it, beforeEach, afterEach } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { ContextDropApiClient } from "../api-client.ts";
|
|
4
|
+
|
|
5
|
+
describe("ContextDropApiClient CSRF handling & lazy bootstrap", () => {
|
|
6
|
+
const originalDocument = globalThis.document;
|
|
7
|
+
const originalFetch = globalThis.fetch;
|
|
8
|
+
|
|
9
|
+
let mockMetaContent: string | null = null;
|
|
10
|
+
let fetchCalls: Array<{ url: string; options: RequestInit }> = [];
|
|
11
|
+
let mockFetchHandler: (url: string, options: RequestInit) => Promise<Response>;
|
|
12
|
+
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
mockMetaContent = null;
|
|
15
|
+
fetchCalls = [];
|
|
16
|
+
|
|
17
|
+
// Mock document with querySelector for meta[name="csrf-token"]
|
|
18
|
+
(globalThis as unknown as { document: unknown }).document = {
|
|
19
|
+
querySelector: (selector: string) => {
|
|
20
|
+
if (selector === 'meta[name="csrf-token"]') {
|
|
21
|
+
if (mockMetaContent !== null) {
|
|
22
|
+
return {
|
|
23
|
+
getAttribute: (name: string) => (name === "content" ? mockMetaContent : null),
|
|
24
|
+
setAttribute: (name: string, value: string) => {
|
|
25
|
+
if (name === "content") mockMetaContent = value;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// Default mock fetch
|
|
36
|
+
mockFetchHandler = async (url: string, _options: RequestInit) => {
|
|
37
|
+
if (url.endsWith("/config")) {
|
|
38
|
+
return new Response(
|
|
39
|
+
JSON.stringify({
|
|
40
|
+
enabled: true,
|
|
41
|
+
position: "bottom_right",
|
|
42
|
+
csrf_token: "bootstrap-csrf-token-123"
|
|
43
|
+
}),
|
|
44
|
+
{ status: 200, headers: { "Content-Type": "application/json" } }
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
return new Response(JSON.stringify({ id: 1, status: "new" }), {
|
|
48
|
+
status: 201,
|
|
49
|
+
headers: { "Content-Type": "application/json" }
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
54
|
+
const url = typeof input === "string" ? input : input.toString();
|
|
55
|
+
const options = init || {};
|
|
56
|
+
fetchCalls.push({ url, options });
|
|
57
|
+
return mockFetchHandler(url, options);
|
|
58
|
+
};
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
afterEach(() => {
|
|
62
|
+
(globalThis as unknown as { document: unknown }).document = originalDocument;
|
|
63
|
+
globalThis.fetch = originalFetch;
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("prefers document meta[name='csrf-token'] when present", () => {
|
|
67
|
+
mockMetaContent = "dom-token-xyz";
|
|
68
|
+
const client = new ContextDropApiClient("/context_drop");
|
|
69
|
+
assert.equal(client.getCsrfToken(), "dom-token-xyz");
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it("returns null when meta is absent and no token has been cached", () => {
|
|
73
|
+
mockMetaContent = null;
|
|
74
|
+
const client = new ContextDropApiClient("/context_drop");
|
|
75
|
+
assert.equal(client.getCsrfToken(), null);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("caches csrf_token when fetchConfig() is called", async () => {
|
|
79
|
+
mockMetaContent = null;
|
|
80
|
+
const client = new ContextDropApiClient("/context_drop");
|
|
81
|
+
|
|
82
|
+
const config = await client.fetchConfig();
|
|
83
|
+
assert.equal(config.csrf_token, "bootstrap-csrf-token-123");
|
|
84
|
+
assert.equal(client.getCsrfToken(), "bootstrap-csrf-token-123");
|
|
85
|
+
assert.equal(fetchCalls.length, 1);
|
|
86
|
+
assert.equal(fetchCalls[0].url, "/context_drop/config");
|
|
87
|
+
assert.equal(fetchCalls[0].options.credentials, "same-origin");
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("deduplicates concurrent in-flight fetchConfig() calls", async () => {
|
|
91
|
+
mockMetaContent = null;
|
|
92
|
+
const client = new ContextDropApiClient("/context_drop");
|
|
93
|
+
|
|
94
|
+
const [cfg1, cfg2, cfg3] = await Promise.all([
|
|
95
|
+
client.fetchConfig(),
|
|
96
|
+
client.fetchConfig(),
|
|
97
|
+
client.fetchConfig()
|
|
98
|
+
]);
|
|
99
|
+
|
|
100
|
+
assert.equal(cfg1.csrf_token, "bootstrap-csrf-token-123");
|
|
101
|
+
assert.equal(cfg2.csrf_token, "bootstrap-csrf-token-123");
|
|
102
|
+
assert.equal(cfg3.csrf_token, "bootstrap-csrf-token-123");
|
|
103
|
+
assert.equal(fetchCalls.length, 1);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("uses DOM meta token directly in submitFeedback() without calling /config", async () => {
|
|
107
|
+
mockMetaContent = "meta-token-abc";
|
|
108
|
+
const client = new ContextDropApiClient("/context_drop");
|
|
109
|
+
|
|
110
|
+
await client.submitFeedback({
|
|
111
|
+
message: "Feedback from ERB page",
|
|
112
|
+
page_url: "http://localhost/erb",
|
|
113
|
+
user_agent: "test-agent",
|
|
114
|
+
metadata: {},
|
|
115
|
+
element_references: [],
|
|
116
|
+
attachments: []
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
assert.equal(fetchCalls.length, 1);
|
|
120
|
+
assert.equal(fetchCalls[0].url, "/context_drop/feedback");
|
|
121
|
+
const headers = fetchCalls[0].options.headers as Record<string, string>;
|
|
122
|
+
assert.equal(headers["X-CSRF-Token"], "meta-token-abc");
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("lazily bootstraps CSRF token from /config on static SPA page without meta tag", async () => {
|
|
126
|
+
mockMetaContent = null;
|
|
127
|
+
const client = new ContextDropApiClient("/context_drop");
|
|
128
|
+
|
|
129
|
+
await client.submitFeedback({
|
|
130
|
+
message: "Feedback from SPA page",
|
|
131
|
+
page_url: "http://localhost/spa",
|
|
132
|
+
user_agent: "test-agent",
|
|
133
|
+
metadata: {},
|
|
134
|
+
element_references: [],
|
|
135
|
+
attachments: []
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
// 1st call: GET /config to fetch csrf_token
|
|
139
|
+
// 2nd call: POST /feedback with X-CSRF-Token
|
|
140
|
+
assert.equal(fetchCalls.length, 2);
|
|
141
|
+
assert.equal(fetchCalls[0].url, "/context_drop/config");
|
|
142
|
+
assert.equal(fetchCalls[1].url, "/context_drop/feedback");
|
|
143
|
+
|
|
144
|
+
const postHeaders = fetchCalls[1].options.headers as Record<string, string>;
|
|
145
|
+
assert.equal(postHeaders["X-CSRF-Token"], "bootstrap-csrf-token-123");
|
|
146
|
+
|
|
147
|
+
// Next request reuses cached token without calling /config again
|
|
148
|
+
await client.submitFeedback({
|
|
149
|
+
message: "Second feedback from SPA page",
|
|
150
|
+
page_url: "http://localhost/spa",
|
|
151
|
+
user_agent: "test-agent",
|
|
152
|
+
metadata: {},
|
|
153
|
+
element_references: [],
|
|
154
|
+
attachments: []
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
assert.equal(fetchCalls.length, 3);
|
|
158
|
+
assert.equal(fetchCalls[2].url, "/context_drop/feedback");
|
|
159
|
+
const nextHeaders = fetchCalls[2].options.headers as Record<string, string>;
|
|
160
|
+
assert.equal(nextHeaders["X-CSRF-Token"], "bootstrap-csrf-token-123");
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("automatically refreshes token and retries once when receiving 422 CSRF authenticity error", async () => {
|
|
164
|
+
mockMetaContent = "stale-token-1";
|
|
165
|
+
const client = new ContextDropApiClient("/context_drop");
|
|
166
|
+
|
|
167
|
+
let postAttempt = 0;
|
|
168
|
+
mockFetchHandler = async (url: string, _options: RequestInit) => {
|
|
169
|
+
if (url.endsWith("/config")) {
|
|
170
|
+
return new Response(
|
|
171
|
+
JSON.stringify({
|
|
172
|
+
enabled: true,
|
|
173
|
+
position: "bottom_right",
|
|
174
|
+
csrf_token: "refreshed-session-token-456"
|
|
175
|
+
}),
|
|
176
|
+
{ status: 200, headers: { "Content-Type": "application/json" } }
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
if (url.endsWith("/feedback")) {
|
|
180
|
+
postAttempt++;
|
|
181
|
+
if (postAttempt === 1) {
|
|
182
|
+
// First attempt fails with 422 Rails CSRF error
|
|
183
|
+
return new Response(
|
|
184
|
+
JSON.stringify({ error: "Invalid or missing CSRF authenticity token" }),
|
|
185
|
+
{ status: 422, headers: { "Content-Type": "application/json" } }
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
// Second attempt succeeds
|
|
189
|
+
return new Response(
|
|
190
|
+
JSON.stringify({ id: 42, status: "new", created_at: "2026-11-11T00:00:00Z" }),
|
|
191
|
+
{ status: 201, headers: { "Content-Type": "application/json" } }
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
throw new Error(`Unexpected URL ${url}`);
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const res = await client.submitFeedback({
|
|
198
|
+
message: "Feedback with stale token",
|
|
199
|
+
page_url: "http://localhost/spa",
|
|
200
|
+
user_agent: "test-agent",
|
|
201
|
+
metadata: {},
|
|
202
|
+
element_references: [],
|
|
203
|
+
attachments: []
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
assert.equal(res.id, 42);
|
|
207
|
+
assert.equal(postAttempt, 2);
|
|
208
|
+
|
|
209
|
+
// Call 1: POST /feedback with stale-token-1
|
|
210
|
+
// Call 2: GET /config to refresh token
|
|
211
|
+
// Call 3: POST /feedback with refreshed-session-token-456
|
|
212
|
+
assert.equal(fetchCalls.length, 3);
|
|
213
|
+
assert.equal(fetchCalls[0].url, "/context_drop/feedback");
|
|
214
|
+
assert.equal(
|
|
215
|
+
(fetchCalls[0].options.headers as Record<string, string>)["X-CSRF-Token"],
|
|
216
|
+
"stale-token-1"
|
|
217
|
+
);
|
|
218
|
+
assert.equal(fetchCalls[1].url, "/context_drop/config");
|
|
219
|
+
assert.equal(fetchCalls[2].url, "/context_drop/feedback");
|
|
220
|
+
assert.equal(
|
|
221
|
+
(fetchCalls[2].options.headers as Record<string, string>)["X-CSRF-Token"],
|
|
222
|
+
"refreshed-session-token-456"
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
// DOM meta was also updated to new token
|
|
226
|
+
assert.equal(mockMetaContent, "refreshed-session-token-456");
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it("does not retry on non-CSRF 422 errors", async () => {
|
|
230
|
+
mockMetaContent = "valid-token";
|
|
231
|
+
const client = new ContextDropApiClient("/context_drop");
|
|
232
|
+
|
|
233
|
+
mockFetchHandler = async (url: string, _options: RequestInit) => {
|
|
234
|
+
if (url.endsWith("/feedback")) {
|
|
235
|
+
return new Response(
|
|
236
|
+
JSON.stringify({ error: "Feedback message cannot be blank" }),
|
|
237
|
+
{ status: 422, headers: { "Content-Type": "application/json" } }
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
return new Response("{}", { status: 200 });
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
await assert.rejects(
|
|
244
|
+
async () => {
|
|
245
|
+
await client.submitFeedback({
|
|
246
|
+
message: "",
|
|
247
|
+
page_url: "http://localhost/spa",
|
|
248
|
+
user_agent: "test-agent",
|
|
249
|
+
metadata: {},
|
|
250
|
+
element_references: [],
|
|
251
|
+
attachments: []
|
|
252
|
+
});
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
message: "Feedback message cannot be blank"
|
|
256
|
+
}
|
|
257
|
+
);
|
|
258
|
+
|
|
259
|
+
// Only 1 attempt was made; no retry or config refresh was triggered
|
|
260
|
+
assert.equal(fetchCalls.length, 1);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it("handles uploadAttachment CSRF token bootstrap and 422 retry", async () => {
|
|
264
|
+
mockMetaContent = null;
|
|
265
|
+
const client = new ContextDropApiClient("/context_drop");
|
|
266
|
+
|
|
267
|
+
let uploadAttempts = 0;
|
|
268
|
+
mockFetchHandler = async (url: string, _options: RequestInit) => {
|
|
269
|
+
if (url.endsWith("/config")) {
|
|
270
|
+
return new Response(
|
|
271
|
+
JSON.stringify({
|
|
272
|
+
enabled: true,
|
|
273
|
+
csrf_token: uploadAttempts === 0 ? "upload-token-1" : "upload-token-2"
|
|
274
|
+
}),
|
|
275
|
+
{ status: 200, headers: { "Content-Type": "application/json" } }
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
if (url.endsWith("/attachments")) {
|
|
279
|
+
uploadAttempts++;
|
|
280
|
+
if (uploadAttempts === 1) {
|
|
281
|
+
return new Response(
|
|
282
|
+
JSON.stringify({ error: "Can't verify CSRF token authenticity" }),
|
|
283
|
+
{ status: 422, headers: { "Content-Type": "application/json" } }
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
return new Response(JSON.stringify({ signed_blob_id: "blob-abc-123" }), {
|
|
287
|
+
status: 201,
|
|
288
|
+
headers: { "Content-Type": "application/json" }
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
throw new Error(`Unexpected URL ${url}`);
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
const dummyBlob = new Blob(["dummy content"], { type: "image/png" });
|
|
295
|
+
const res = await client.uploadAttachment(dummyBlob, "test.png");
|
|
296
|
+
|
|
297
|
+
assert.equal(res.signed_blob_id, "blob-abc-123");
|
|
298
|
+
assert.equal(uploadAttempts, 2);
|
|
299
|
+
|
|
300
|
+
// Call 1: GET /config (initial bootstrap)
|
|
301
|
+
// Call 2: POST /attachments (fails with 422 CSRF)
|
|
302
|
+
// Call 3: GET /config (refresh)
|
|
303
|
+
// Call 4: POST /attachments (retried with new token, succeeds)
|
|
304
|
+
assert.equal(fetchCalls.length, 4);
|
|
305
|
+
assert.equal(fetchCalls[0].url, "/context_drop/config");
|
|
306
|
+
assert.equal(fetchCalls[1].url, "/context_drop/attachments");
|
|
307
|
+
assert.equal(fetchCalls[2].url, "/context_drop/config");
|
|
308
|
+
assert.equal(fetchCalls[3].url, "/context_drop/attachments");
|
|
309
|
+
});
|
|
310
|
+
});
|
|
@@ -6,82 +6,187 @@ import type {
|
|
|
6
6
|
|
|
7
7
|
export class ContextDropApiClient {
|
|
8
8
|
private baseUrl: string;
|
|
9
|
+
private cachedCsrfToken: string | null = null;
|
|
10
|
+
private inFlightConfigPromise: Promise<WidgetConfig> | null = null;
|
|
9
11
|
|
|
10
12
|
constructor(baseUrl: string = "/context_drop") {
|
|
11
13
|
this.baseUrl = baseUrl.replace(/\/+$/, "") || "/context_drop";
|
|
12
14
|
}
|
|
13
15
|
|
|
14
16
|
public getCsrfToken(): string | null {
|
|
17
|
+
const metaToken = this.getMetaCsrfToken();
|
|
18
|
+
if (metaToken) {
|
|
19
|
+
return metaToken;
|
|
20
|
+
}
|
|
21
|
+
return this.cachedCsrfToken;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
public setCsrfToken(token: string | null): void {
|
|
25
|
+
this.cachedCsrfToken = token ? token.trim() : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
private getMetaCsrfToken(): string | null {
|
|
15
29
|
if (typeof document === "undefined") return null;
|
|
16
30
|
const meta = document.querySelector('meta[name="csrf-token"]');
|
|
17
|
-
|
|
31
|
+
const content = meta ? meta.getAttribute("content") : null;
|
|
32
|
+
return content && content.trim().length > 0 ? content.trim() : null;
|
|
18
33
|
}
|
|
19
34
|
|
|
20
35
|
public async fetchConfig(): Promise<WidgetConfig> {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
36
|
+
if (this.inFlightConfigPromise) {
|
|
37
|
+
return this.inFlightConfigPromise;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
this.inFlightConfigPromise = (async () => {
|
|
41
|
+
try {
|
|
42
|
+
const response = await fetch(`${this.baseUrl}/config`, {
|
|
43
|
+
method: "GET",
|
|
44
|
+
credentials: "same-origin",
|
|
45
|
+
headers: {
|
|
46
|
+
Accept: "application/json"
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
if (!response.ok) {
|
|
51
|
+
throw new Error(`Failed to fetch ContextDrop config (${response.status})`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const config = (await response.json()) as WidgetConfig;
|
|
55
|
+
if (config && typeof config.csrf_token === "string" && config.csrf_token.trim().length > 0) {
|
|
56
|
+
this.cachedCsrfToken = config.csrf_token.trim();
|
|
57
|
+
if (typeof document !== "undefined") {
|
|
58
|
+
const meta = document.querySelector('meta[name="csrf-token"]');
|
|
59
|
+
if (meta) {
|
|
60
|
+
meta.setAttribute("content", this.cachedCsrfToken);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return config;
|
|
65
|
+
} finally {
|
|
66
|
+
this.inFlightConfigPromise = null;
|
|
26
67
|
}
|
|
27
|
-
});
|
|
68
|
+
})();
|
|
28
69
|
|
|
29
|
-
|
|
30
|
-
|
|
70
|
+
return this.inFlightConfigPromise;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
public async resolveCsrfToken(forceRefresh = false): Promise<string | null> {
|
|
74
|
+
if (!forceRefresh) {
|
|
75
|
+
const metaToken = this.getMetaCsrfToken();
|
|
76
|
+
if (metaToken) {
|
|
77
|
+
return metaToken;
|
|
78
|
+
}
|
|
79
|
+
if (this.cachedCsrfToken) {
|
|
80
|
+
return this.cachedCsrfToken;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
const config = await this.fetchConfig();
|
|
86
|
+
if (config && config.csrf_token) {
|
|
87
|
+
return config.csrf_token.trim();
|
|
88
|
+
}
|
|
89
|
+
} catch {
|
|
90
|
+
// Continue and fall back to current token or null
|
|
31
91
|
}
|
|
32
92
|
|
|
33
|
-
return
|
|
93
|
+
return this.cachedCsrfToken || this.getMetaCsrfToken();
|
|
34
94
|
}
|
|
35
95
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
96
|
+
private isCsrfError(status: number, message: string): boolean {
|
|
97
|
+
if (status !== 422) return false;
|
|
98
|
+
return /csrf|authenticity/i.test(message);
|
|
99
|
+
}
|
|
39
100
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
101
|
+
private async executeWithCsrfRetry<T>(
|
|
102
|
+
requestFn: (csrfToken: string | null) => Promise<Response>,
|
|
103
|
+
defaultErrorMessage: string
|
|
104
|
+
): Promise<T> {
|
|
105
|
+
let csrfToken = await this.resolveCsrfToken(false);
|
|
106
|
+
let response = await requestFn(csrfToken);
|
|
107
|
+
|
|
108
|
+
if (response.ok) {
|
|
109
|
+
return (await response.json()) as T;
|
|
46
110
|
}
|
|
47
111
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
112
|
+
if (response.status === 422) {
|
|
113
|
+
const rawText = await response.text();
|
|
114
|
+
let parsedError: string | null = null;
|
|
115
|
+
try {
|
|
116
|
+
const json = JSON.parse(rawText) as { error?: string };
|
|
117
|
+
if (json && typeof json.error === "string") {
|
|
118
|
+
parsedError = json.error;
|
|
119
|
+
}
|
|
120
|
+
} catch {
|
|
121
|
+
// Not JSON
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const errorMessage = parsedError || rawText || "";
|
|
125
|
+
const shouldRetryCsrf =
|
|
126
|
+
this.isCsrfError(response.status, errorMessage) || (!csrfToken && response.status === 422);
|
|
127
|
+
|
|
128
|
+
if (shouldRetryCsrf) {
|
|
129
|
+
csrfToken = await this.resolveCsrfToken(true);
|
|
130
|
+
response = await requestFn(csrfToken);
|
|
131
|
+
if (response.ok) {
|
|
132
|
+
return (await response.json()) as T;
|
|
133
|
+
}
|
|
134
|
+
const retryErrBody = await response.json().catch(() => ({}));
|
|
135
|
+
throw new Error(
|
|
136
|
+
(retryErrBody as { error?: string }).error || `${defaultErrorMessage} (${response.status})`
|
|
137
|
+
);
|
|
138
|
+
}
|
|
54
139
|
|
|
55
|
-
|
|
56
|
-
const errBody = await response.json().catch(() => ({}));
|
|
57
|
-
throw new Error((errBody as { error?: string }).error || `Upload failed (${response.status})`);
|
|
140
|
+
throw new Error(parsedError || errorMessage || `${defaultErrorMessage} (${response.status})`);
|
|
58
141
|
}
|
|
59
142
|
|
|
60
|
-
|
|
143
|
+
const errBody = await response.json().catch(() => ({}));
|
|
144
|
+
throw new Error(
|
|
145
|
+
(errBody as { error?: string }).error || `${defaultErrorMessage} (${response.status})`
|
|
146
|
+
);
|
|
61
147
|
}
|
|
62
148
|
|
|
63
|
-
public async
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
149
|
+
public async uploadAttachment(file: Blob, filename: string): Promise<{ signed_blob_id: string }> {
|
|
150
|
+
const makeRequest = async (csrfToken: string | null) => {
|
|
151
|
+
const formData = new FormData();
|
|
152
|
+
formData.append("file", file, filename);
|
|
153
|
+
|
|
154
|
+
const headers: Record<string, string> = {
|
|
155
|
+
Accept: "application/json"
|
|
156
|
+
};
|
|
157
|
+
if (csrfToken) {
|
|
158
|
+
headers["X-CSRF-Token"] = csrfToken;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return fetch(`${this.baseUrl}/attachments`, {
|
|
162
|
+
method: "POST",
|
|
163
|
+
credentials: "same-origin",
|
|
164
|
+
headers,
|
|
165
|
+
body: formData
|
|
166
|
+
});
|
|
67
167
|
};
|
|
68
|
-
const csrf = this.getCsrfToken();
|
|
69
|
-
if (csrf) {
|
|
70
|
-
headers["X-CSRF-Token"] = csrf;
|
|
71
|
-
}
|
|
72
168
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
credentials: "same-origin",
|
|
76
|
-
headers,
|
|
77
|
-
body: JSON.stringify({ feedback: payload })
|
|
78
|
-
});
|
|
169
|
+
return this.executeWithCsrfRetry(makeRequest, "Upload failed");
|
|
170
|
+
}
|
|
79
171
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
172
|
+
public async submitFeedback(payload: FeedbackSubmissionPayload): Promise<FeedbackSubmissionResponse> {
|
|
173
|
+
const makeRequest = async (csrfToken: string | null) => {
|
|
174
|
+
const headers: Record<string, string> = {
|
|
175
|
+
"Content-Type": "application/json",
|
|
176
|
+
Accept: "application/json"
|
|
177
|
+
};
|
|
178
|
+
if (csrfToken) {
|
|
179
|
+
headers["X-CSRF-Token"] = csrfToken;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return fetch(`${this.baseUrl}/feedback`, {
|
|
183
|
+
method: "POST",
|
|
184
|
+
credentials: "same-origin",
|
|
185
|
+
headers,
|
|
186
|
+
body: JSON.stringify({ feedback: payload })
|
|
187
|
+
});
|
|
188
|
+
};
|
|
84
189
|
|
|
85
|
-
return
|
|
190
|
+
return this.executeWithCsrfRetry(makeRequest, "Submission failed");
|
|
86
191
|
}
|
|
87
192
|
}
|
|
@@ -261,6 +261,9 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
|
|
|
261
261
|
limits: { ...this.config.limits, ...(parsed.limits || {}) },
|
|
262
262
|
privacy: { ...this.config.privacy, ...(parsed.privacy || {}) }
|
|
263
263
|
};
|
|
264
|
+
if (parsed.csrf_token) {
|
|
265
|
+
this.apiClient.setCsrfToken(parsed.csrf_token);
|
|
266
|
+
}
|
|
264
267
|
} catch {
|
|
265
268
|
// Ignore malformed JSON attribute
|
|
266
269
|
}
|
data/lib/context_drop/version.rb
CHANGED
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: context_drop
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.1.
|
|
4
|
+
version: 0.1.2
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Kemal Elmizan
|
|
@@ -176,6 +176,7 @@ files:
|
|
|
176
176
|
- app/controllers/context_drop/health_controller.rb
|
|
177
177
|
- app/controllers/context_drop/mcp_controller.rb
|
|
178
178
|
- app/helpers/context_drop/widget_helper.rb
|
|
179
|
+
- app/javascript/context_drop/__tests__/api-client.test.ts
|
|
179
180
|
- app/javascript/context_drop/__tests__/widget.test.ts
|
|
180
181
|
- app/javascript/context_drop/api-client.ts
|
|
181
182
|
- app/javascript/context_drop/element-picker.ts
|