context_drop 0.1.0 → 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 +93 -25
- data/app/assets/javascripts/context_drop/context_drop.js +209 -59
- 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/__tests__/widget.test.ts +499 -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 +56 -11
- data/lib/context_drop/version.rb +1 -1
- metadata +3 -2
|
@@ -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
|
+
});
|