@slopit/behavioral 0.1.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.
- package/LICENSE +21 -0
- package/README.md +947 -0
- package/dist/index.d.ts +1822 -0
- package/dist/index.js +2748 -0
- package/dist/index.js.map +1 -0
- package/package.json +57 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2748 @@
|
|
|
1
|
+
import { simpleHash, hashText } from '@slopit/core';
|
|
2
|
+
|
|
3
|
+
// src/collectors/clipboard.ts
|
|
4
|
+
var ClipboardCollector = class {
|
|
5
|
+
/**
|
|
6
|
+
* Creates a new ClipboardCollector.
|
|
7
|
+
*
|
|
8
|
+
* @param config - Configuration options for clipboard capture
|
|
9
|
+
* @param startTime - Reference time for event timestamps (typically performance.now())
|
|
10
|
+
* @param getRecentKeystrokes - Function returning keystroke count in recent window
|
|
11
|
+
* @param onPasteEvent - Optional callback invoked for each paste event
|
|
12
|
+
* @param onCopyEvent - Optional callback invoked for each copy/cut event
|
|
13
|
+
*/
|
|
14
|
+
constructor(config, startTime, getRecentKeystrokes, onPasteEvent, onCopyEvent) {
|
|
15
|
+
this.config = config;
|
|
16
|
+
this.getRecentKeystrokes = getRecentKeystrokes;
|
|
17
|
+
this.onPasteEvent = onPasteEvent;
|
|
18
|
+
this.onCopyEvent = onCopyEvent;
|
|
19
|
+
this.startTime = startTime;
|
|
20
|
+
this.boundPaste = this.handlePaste.bind(this);
|
|
21
|
+
this.boundCopy = this.handleCopy.bind(this);
|
|
22
|
+
this.boundCut = this.handleCut.bind(this);
|
|
23
|
+
}
|
|
24
|
+
pasteEvents = [];
|
|
25
|
+
copyEvents = [];
|
|
26
|
+
element = null;
|
|
27
|
+
startTime;
|
|
28
|
+
boundPaste;
|
|
29
|
+
boundCopy;
|
|
30
|
+
boundCut;
|
|
31
|
+
/**
|
|
32
|
+
* Attach collector to an element.
|
|
33
|
+
*
|
|
34
|
+
* @param element - The DOM element or document to attach listeners to
|
|
35
|
+
*/
|
|
36
|
+
attach(element) {
|
|
37
|
+
this.element = element;
|
|
38
|
+
if (this.config.capturePaste) {
|
|
39
|
+
element.addEventListener("paste", this.boundPaste);
|
|
40
|
+
}
|
|
41
|
+
if (this.config.captureCopyCut) {
|
|
42
|
+
element.addEventListener("copy", this.boundCopy);
|
|
43
|
+
element.addEventListener("cut", this.boundCut);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Detach collector from element.
|
|
48
|
+
*/
|
|
49
|
+
detach() {
|
|
50
|
+
if (this.element) {
|
|
51
|
+
this.element.removeEventListener("paste", this.boundPaste);
|
|
52
|
+
this.element.removeEventListener("copy", this.boundCopy);
|
|
53
|
+
this.element.removeEventListener("cut", this.boundCut);
|
|
54
|
+
this.element = null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Reset collected data.
|
|
59
|
+
*
|
|
60
|
+
* @param newStartTime - Optional new reference time for timestamps
|
|
61
|
+
*/
|
|
62
|
+
reset(newStartTime) {
|
|
63
|
+
this.pasteEvents = [];
|
|
64
|
+
this.copyEvents = [];
|
|
65
|
+
if (newStartTime !== void 0) {
|
|
66
|
+
this.startTime = newStartTime;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Get all collected paste events.
|
|
71
|
+
*
|
|
72
|
+
* @returns Copy of paste events array
|
|
73
|
+
*/
|
|
74
|
+
getPasteEvents() {
|
|
75
|
+
return [...this.pasteEvents];
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Get all collected copy/cut events.
|
|
79
|
+
*
|
|
80
|
+
* @returns Copy of copy/cut events array
|
|
81
|
+
*/
|
|
82
|
+
getCopyEvents() {
|
|
83
|
+
return [...this.copyEvents];
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Get all clipboard events combined.
|
|
87
|
+
*
|
|
88
|
+
* @returns Array of all paste and copy/cut events, sorted by time
|
|
89
|
+
*/
|
|
90
|
+
getAllEvents() {
|
|
91
|
+
const all = [...this.pasteEvents, ...this.copyEvents];
|
|
92
|
+
return all.sort((a, b) => a.time - b.time);
|
|
93
|
+
}
|
|
94
|
+
handlePaste(e) {
|
|
95
|
+
const text = e.clipboardData?.getData("text/plain") ?? "";
|
|
96
|
+
const time = performance.now() - this.startTime;
|
|
97
|
+
const precedingKeystrokes = this.getRecentKeystrokes();
|
|
98
|
+
if (this.config.prevent) {
|
|
99
|
+
e.preventDefault();
|
|
100
|
+
if (this.config.warnMessage) {
|
|
101
|
+
alert(this.config.warnMessage);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const event = {
|
|
105
|
+
time,
|
|
106
|
+
textLength: text.length,
|
|
107
|
+
precedingKeystrokes,
|
|
108
|
+
blocked: this.config.prevent,
|
|
109
|
+
...this.config.capturePreview ? { textPreview: text.slice(0, this.config.previewLength) } : {},
|
|
110
|
+
// Hash asynchronously but use sync hash for immediate event
|
|
111
|
+
textHash: simpleHash(text)
|
|
112
|
+
};
|
|
113
|
+
this.pasteEvents.push(event);
|
|
114
|
+
this.onPasteEvent?.(event);
|
|
115
|
+
if (text.length > 0) {
|
|
116
|
+
hashText(text).then((hash) => {
|
|
117
|
+
event.textHash = hash;
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
handleCopy(e) {
|
|
122
|
+
this.handleCopyCut(e, "copy");
|
|
123
|
+
}
|
|
124
|
+
handleCut(e) {
|
|
125
|
+
this.handleCopyCut(e, "cut");
|
|
126
|
+
}
|
|
127
|
+
handleCopyCut(_e, eventType) {
|
|
128
|
+
const time = performance.now() - this.startTime;
|
|
129
|
+
const selection = window.getSelection();
|
|
130
|
+
const text = selection?.toString() ?? "";
|
|
131
|
+
let selectionStart;
|
|
132
|
+
let selectionEnd;
|
|
133
|
+
const activeElement = document.activeElement;
|
|
134
|
+
if (activeElement instanceof HTMLInputElement || activeElement instanceof HTMLTextAreaElement) {
|
|
135
|
+
selectionStart = activeElement.selectionStart ?? void 0;
|
|
136
|
+
selectionEnd = activeElement.selectionEnd ?? void 0;
|
|
137
|
+
}
|
|
138
|
+
const event = {
|
|
139
|
+
time,
|
|
140
|
+
event: eventType,
|
|
141
|
+
textLength: text.length,
|
|
142
|
+
...this.config.capturePreview ? { textPreview: text.slice(0, this.config.previewLength) } : {},
|
|
143
|
+
textHash: simpleHash(text),
|
|
144
|
+
...selectionStart !== void 0 ? { selectionStart } : {},
|
|
145
|
+
...selectionEnd !== void 0 ? { selectionEnd } : {}
|
|
146
|
+
};
|
|
147
|
+
this.copyEvents.push(event);
|
|
148
|
+
this.onCopyEvent?.(event);
|
|
149
|
+
if (text.length > 0) {
|
|
150
|
+
hashText(text).then((hash) => {
|
|
151
|
+
event.textHash = hash;
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
// src/collectors/focus.ts
|
|
158
|
+
var FocusCollector = class {
|
|
159
|
+
constructor(config, startTime, onEvent) {
|
|
160
|
+
this.config = config;
|
|
161
|
+
this.onEvent = onEvent;
|
|
162
|
+
this.startTime = startTime;
|
|
163
|
+
this.boundFocus = this.handleFocus.bind(this);
|
|
164
|
+
this.boundBlur = this.handleBlur.bind(this);
|
|
165
|
+
this.boundVisibility = this.handleVisibilityChange.bind(this);
|
|
166
|
+
}
|
|
167
|
+
events = [];
|
|
168
|
+
startTime;
|
|
169
|
+
lastBlurTime;
|
|
170
|
+
lastHiddenTime;
|
|
171
|
+
boundFocus;
|
|
172
|
+
boundBlur;
|
|
173
|
+
boundVisibility;
|
|
174
|
+
attached = false;
|
|
175
|
+
/**
|
|
176
|
+
* Attach collector to document.
|
|
177
|
+
*/
|
|
178
|
+
attach(_element) {
|
|
179
|
+
if (this.attached) return;
|
|
180
|
+
if (this.config.useBlurFocus) {
|
|
181
|
+
window.addEventListener("focus", this.boundFocus);
|
|
182
|
+
window.addEventListener("blur", this.boundBlur);
|
|
183
|
+
}
|
|
184
|
+
if (this.config.useVisibilityAPI) {
|
|
185
|
+
document.addEventListener("visibilitychange", this.boundVisibility);
|
|
186
|
+
}
|
|
187
|
+
this.attached = true;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Detach collector.
|
|
191
|
+
*/
|
|
192
|
+
detach() {
|
|
193
|
+
if (!this.attached) return;
|
|
194
|
+
window.removeEventListener("focus", this.boundFocus);
|
|
195
|
+
window.removeEventListener("blur", this.boundBlur);
|
|
196
|
+
document.removeEventListener("visibilitychange", this.boundVisibility);
|
|
197
|
+
if (this.lastBlurTime !== void 0) {
|
|
198
|
+
this.updateLastBlurDuration();
|
|
199
|
+
}
|
|
200
|
+
this.attached = false;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Reset collected data.
|
|
204
|
+
*/
|
|
205
|
+
reset(newStartTime) {
|
|
206
|
+
this.events = [];
|
|
207
|
+
this.lastBlurTime = void 0;
|
|
208
|
+
this.lastHiddenTime = void 0;
|
|
209
|
+
if (newStartTime !== void 0) {
|
|
210
|
+
this.startTime = newStartTime;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Get all collected events.
|
|
215
|
+
*/
|
|
216
|
+
getEvents() {
|
|
217
|
+
return [...this.events];
|
|
218
|
+
}
|
|
219
|
+
handleFocus() {
|
|
220
|
+
const time = performance.now() - this.startTime;
|
|
221
|
+
this.updateLastBlurDuration();
|
|
222
|
+
const event = {
|
|
223
|
+
time,
|
|
224
|
+
event: "focus"
|
|
225
|
+
};
|
|
226
|
+
this.events.push(event);
|
|
227
|
+
this.onEvent?.(event);
|
|
228
|
+
}
|
|
229
|
+
handleBlur() {
|
|
230
|
+
const time = performance.now() - this.startTime;
|
|
231
|
+
this.lastBlurTime = time;
|
|
232
|
+
const event = {
|
|
233
|
+
time,
|
|
234
|
+
event: "blur"
|
|
235
|
+
};
|
|
236
|
+
this.events.push(event);
|
|
237
|
+
this.onEvent?.(event);
|
|
238
|
+
}
|
|
239
|
+
handleVisibilityChange() {
|
|
240
|
+
const time = performance.now() - this.startTime;
|
|
241
|
+
const visibility = document.visibilityState;
|
|
242
|
+
if (visibility === "hidden") {
|
|
243
|
+
this.lastHiddenTime = time;
|
|
244
|
+
}
|
|
245
|
+
const event = {
|
|
246
|
+
time,
|
|
247
|
+
event: "visibilitychange",
|
|
248
|
+
visibility
|
|
249
|
+
};
|
|
250
|
+
this.events.push(event);
|
|
251
|
+
this.onEvent?.(event);
|
|
252
|
+
}
|
|
253
|
+
updateLastBlurDuration() {
|
|
254
|
+
if (this.lastBlurTime === void 0) return;
|
|
255
|
+
const currentTime = performance.now() - this.startTime;
|
|
256
|
+
const blurDuration = currentTime - this.lastBlurTime;
|
|
257
|
+
for (let i = this.events.length - 1; i >= 0; i--) {
|
|
258
|
+
const evt = this.events[i];
|
|
259
|
+
if (evt?.event === "blur" && evt.blurDuration === void 0) {
|
|
260
|
+
evt.blurDuration = blurDuration;
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
this.lastBlurTime = void 0;
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
// src/collectors/input-duration.ts
|
|
269
|
+
var InputDurationCollector = class {
|
|
270
|
+
constructor(config, startTime, onEvent) {
|
|
271
|
+
this.config = config;
|
|
272
|
+
this.onEvent = onEvent;
|
|
273
|
+
this.startTime = startTime;
|
|
274
|
+
this.boundFocus = this.handleFocus.bind(this);
|
|
275
|
+
this.boundBlur = this.handleBlur.bind(this);
|
|
276
|
+
}
|
|
277
|
+
events = [];
|
|
278
|
+
element = null;
|
|
279
|
+
startTime;
|
|
280
|
+
currentFocusStart = null;
|
|
281
|
+
currentKeystrokeCount = 0;
|
|
282
|
+
currentPasteCount = 0;
|
|
283
|
+
boundFocus;
|
|
284
|
+
boundBlur;
|
|
285
|
+
/**
|
|
286
|
+
* Attach collector to an element.
|
|
287
|
+
*
|
|
288
|
+
* @param element - The element to monitor for focus events.
|
|
289
|
+
*/
|
|
290
|
+
attach(element) {
|
|
291
|
+
if (element instanceof Document) {
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
this.element = element;
|
|
295
|
+
element.addEventListener("focus", this.boundFocus);
|
|
296
|
+
element.addEventListener("blur", this.boundBlur);
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Detach collector from element.
|
|
300
|
+
*/
|
|
301
|
+
detach() {
|
|
302
|
+
if (this.element) {
|
|
303
|
+
this.element.removeEventListener("focus", this.boundFocus);
|
|
304
|
+
this.element.removeEventListener("blur", this.boundBlur);
|
|
305
|
+
this.element = null;
|
|
306
|
+
}
|
|
307
|
+
if (this.currentFocusStart !== null) {
|
|
308
|
+
this.finalizeCurrentSession();
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Reset collected data.
|
|
313
|
+
*
|
|
314
|
+
* @param newStartTime - Optional new start time for relative timing.
|
|
315
|
+
*/
|
|
316
|
+
reset(newStartTime) {
|
|
317
|
+
this.events = [];
|
|
318
|
+
this.currentFocusStart = null;
|
|
319
|
+
this.currentKeystrokeCount = 0;
|
|
320
|
+
this.currentPasteCount = 0;
|
|
321
|
+
if (newStartTime !== void 0) {
|
|
322
|
+
this.startTime = newStartTime;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Get all collected events.
|
|
327
|
+
*
|
|
328
|
+
* @returns A copy of the collected input duration events.
|
|
329
|
+
*/
|
|
330
|
+
getEvents() {
|
|
331
|
+
return [...this.events];
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Get the start time of the current focus session.
|
|
335
|
+
*
|
|
336
|
+
* @returns The focus start time relative to startTime, or null if not focused.
|
|
337
|
+
*/
|
|
338
|
+
getCurrentFocusStart() {
|
|
339
|
+
return this.currentFocusStart;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Increment the keystroke count for the current focus session.
|
|
343
|
+
*
|
|
344
|
+
* This method is called externally by the orchestrator when a keystroke
|
|
345
|
+
* occurs on the tracked element.
|
|
346
|
+
*/
|
|
347
|
+
incrementKeystrokes() {
|
|
348
|
+
if (this.config.trackKeystrokes && this.currentFocusStart !== null) {
|
|
349
|
+
this.currentKeystrokeCount++;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Increment the paste count for the current focus session.
|
|
354
|
+
*
|
|
355
|
+
* This method is called externally by the orchestrator when a paste
|
|
356
|
+
* event occurs on the tracked element.
|
|
357
|
+
*/
|
|
358
|
+
incrementPastes() {
|
|
359
|
+
if (this.config.trackPastes && this.currentFocusStart !== null) {
|
|
360
|
+
this.currentPasteCount++;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
handleFocus(_e) {
|
|
364
|
+
if (this.currentFocusStart === null) {
|
|
365
|
+
this.currentFocusStart = performance.now() - this.startTime;
|
|
366
|
+
this.currentKeystrokeCount = 0;
|
|
367
|
+
this.currentPasteCount = 0;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
handleBlur(_e) {
|
|
371
|
+
this.finalizeCurrentSession();
|
|
372
|
+
}
|
|
373
|
+
finalizeCurrentSession() {
|
|
374
|
+
if (this.currentFocusStart === null) {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const blurTime = performance.now() - this.startTime;
|
|
378
|
+
const duration = blurTime - this.currentFocusStart;
|
|
379
|
+
const elementId = this.getElementId();
|
|
380
|
+
const event = {
|
|
381
|
+
focusTime: this.currentFocusStart,
|
|
382
|
+
blurTime,
|
|
383
|
+
duration
|
|
384
|
+
};
|
|
385
|
+
if (elementId !== void 0) {
|
|
386
|
+
event.elementId = elementId;
|
|
387
|
+
}
|
|
388
|
+
if (this.config.trackKeystrokes) {
|
|
389
|
+
event.keystrokesDuringFocus = this.currentKeystrokeCount;
|
|
390
|
+
}
|
|
391
|
+
if (this.config.trackPastes) {
|
|
392
|
+
event.pastesDuringFocus = this.currentPasteCount;
|
|
393
|
+
}
|
|
394
|
+
this.events.push(event);
|
|
395
|
+
this.onEvent?.(event);
|
|
396
|
+
this.currentFocusStart = null;
|
|
397
|
+
this.currentKeystrokeCount = 0;
|
|
398
|
+
this.currentPasteCount = 0;
|
|
399
|
+
}
|
|
400
|
+
getElementId() {
|
|
401
|
+
if (!this.element) {
|
|
402
|
+
return void 0;
|
|
403
|
+
}
|
|
404
|
+
if (this.element.id) {
|
|
405
|
+
return this.element.id;
|
|
406
|
+
}
|
|
407
|
+
if (this.element instanceof HTMLInputElement || this.element instanceof HTMLTextAreaElement) {
|
|
408
|
+
return this.element.name || void 0;
|
|
409
|
+
}
|
|
410
|
+
return void 0;
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
// src/collectors/keystroke.ts
|
|
415
|
+
var KeystrokeCollector = class {
|
|
416
|
+
constructor(config, startTime, onEvent) {
|
|
417
|
+
this.config = config;
|
|
418
|
+
this.onEvent = onEvent;
|
|
419
|
+
this.startTime = startTime;
|
|
420
|
+
this.boundKeydown = this.handleKeydown.bind(this);
|
|
421
|
+
this.boundKeyup = this.handleKeyup.bind(this);
|
|
422
|
+
}
|
|
423
|
+
events = [];
|
|
424
|
+
element = null;
|
|
425
|
+
startTime;
|
|
426
|
+
firstKeystrokeTime;
|
|
427
|
+
boundKeydown;
|
|
428
|
+
boundKeyup;
|
|
429
|
+
/**
|
|
430
|
+
* Attach collector to an element.
|
|
431
|
+
*/
|
|
432
|
+
attach(element) {
|
|
433
|
+
this.element = element;
|
|
434
|
+
element.addEventListener("keydown", this.boundKeydown);
|
|
435
|
+
if (this.config.captureKeyUp) {
|
|
436
|
+
element.addEventListener("keyup", this.boundKeyup);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Detach collector from element.
|
|
441
|
+
*/
|
|
442
|
+
detach() {
|
|
443
|
+
if (this.element) {
|
|
444
|
+
this.element.removeEventListener("keydown", this.boundKeydown);
|
|
445
|
+
this.element.removeEventListener("keyup", this.boundKeyup);
|
|
446
|
+
this.element = null;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Reset collected data.
|
|
451
|
+
*/
|
|
452
|
+
reset(newStartTime) {
|
|
453
|
+
this.events = [];
|
|
454
|
+
this.firstKeystrokeTime = void 0;
|
|
455
|
+
if (newStartTime !== void 0) {
|
|
456
|
+
this.startTime = newStartTime;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Get all collected events.
|
|
461
|
+
*/
|
|
462
|
+
getEvents() {
|
|
463
|
+
return [...this.events];
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Get time of first keystroke.
|
|
467
|
+
*/
|
|
468
|
+
getFirstKeystrokeTime() {
|
|
469
|
+
return this.firstKeystrokeTime;
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Get count of keystrokes in the last N milliseconds.
|
|
473
|
+
*/
|
|
474
|
+
getRecentCount(windowMs) {
|
|
475
|
+
const now = performance.now();
|
|
476
|
+
const cutoff = now - this.startTime - windowMs;
|
|
477
|
+
return this.events.filter((e) => e.time >= cutoff).length;
|
|
478
|
+
}
|
|
479
|
+
handleKeydown(e) {
|
|
480
|
+
this.recordEvent(e, "keydown");
|
|
481
|
+
}
|
|
482
|
+
handleKeyup(e) {
|
|
483
|
+
this.recordEvent(e, "keyup");
|
|
484
|
+
}
|
|
485
|
+
recordEvent(e, type) {
|
|
486
|
+
const time = performance.now() - this.startTime;
|
|
487
|
+
if (this.firstKeystrokeTime === void 0 && type === "keydown") {
|
|
488
|
+
this.firstKeystrokeTime = time;
|
|
489
|
+
}
|
|
490
|
+
const textLength = this.getTextLength(e.target);
|
|
491
|
+
const event = {
|
|
492
|
+
time,
|
|
493
|
+
key: e.key,
|
|
494
|
+
code: e.code,
|
|
495
|
+
event: type,
|
|
496
|
+
...textLength !== void 0 ? { textLength } : {},
|
|
497
|
+
...this.config.includeModifiers ? { modifiers: this.getModifiers(e) } : {}
|
|
498
|
+
};
|
|
499
|
+
this.events.push(event);
|
|
500
|
+
this.onEvent?.(event);
|
|
501
|
+
}
|
|
502
|
+
getTextLength(target) {
|
|
503
|
+
if (target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement) {
|
|
504
|
+
return target.value.length;
|
|
505
|
+
}
|
|
506
|
+
if (target instanceof HTMLElement && target.isContentEditable) {
|
|
507
|
+
return target.textContent?.length;
|
|
508
|
+
}
|
|
509
|
+
return void 0;
|
|
510
|
+
}
|
|
511
|
+
getModifiers(e) {
|
|
512
|
+
return {
|
|
513
|
+
shift: e.shiftKey,
|
|
514
|
+
ctrl: e.ctrlKey,
|
|
515
|
+
alt: e.altKey,
|
|
516
|
+
meta: e.metaKey
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
// src/collectors/mouse.ts
|
|
522
|
+
var MouseCollector = class {
|
|
523
|
+
constructor(config, startTime, onEvent) {
|
|
524
|
+
this.config = config;
|
|
525
|
+
this.onEvent = onEvent;
|
|
526
|
+
this.startTime = startTime;
|
|
527
|
+
this.boundMousemove = this.handleMousemove.bind(this);
|
|
528
|
+
this.boundMousedown = this.handleMousedown.bind(this);
|
|
529
|
+
this.boundMouseup = this.handleMouseup.bind(this);
|
|
530
|
+
this.boundClick = this.handleClick.bind(this);
|
|
531
|
+
}
|
|
532
|
+
events = [];
|
|
533
|
+
element = null;
|
|
534
|
+
startTime;
|
|
535
|
+
lastMoveTime = null;
|
|
536
|
+
lastX = null;
|
|
537
|
+
lastY = null;
|
|
538
|
+
isDragging = false;
|
|
539
|
+
idlePeriods = [];
|
|
540
|
+
idleStart = null;
|
|
541
|
+
idleCheckInterval = null;
|
|
542
|
+
boundMousemove;
|
|
543
|
+
boundMousedown;
|
|
544
|
+
boundMouseup;
|
|
545
|
+
boundClick;
|
|
546
|
+
throttledMoveHandler = null;
|
|
547
|
+
lastThrottledCall = 0;
|
|
548
|
+
/**
|
|
549
|
+
* Attach collector to an element.
|
|
550
|
+
*
|
|
551
|
+
* @param element - The DOM element or document to attach listeners to
|
|
552
|
+
*/
|
|
553
|
+
attach(element) {
|
|
554
|
+
this.element = element;
|
|
555
|
+
if (this.config.captureMovement) {
|
|
556
|
+
this.throttledMoveHandler = this.createThrottledHandler(
|
|
557
|
+
this.boundMousemove,
|
|
558
|
+
this.config.throttleMs
|
|
559
|
+
);
|
|
560
|
+
element.addEventListener("mousemove", this.throttledMoveHandler);
|
|
561
|
+
}
|
|
562
|
+
if (this.config.captureClicks) {
|
|
563
|
+
element.addEventListener("mousedown", this.boundMousedown);
|
|
564
|
+
element.addEventListener("mouseup", this.boundMouseup);
|
|
565
|
+
element.addEventListener("click", this.boundClick);
|
|
566
|
+
}
|
|
567
|
+
this.startIdleDetection();
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Detach collector from element.
|
|
571
|
+
*/
|
|
572
|
+
detach() {
|
|
573
|
+
if (this.element) {
|
|
574
|
+
if (this.throttledMoveHandler) {
|
|
575
|
+
this.element.removeEventListener("mousemove", this.throttledMoveHandler);
|
|
576
|
+
}
|
|
577
|
+
this.element.removeEventListener("mousedown", this.boundMousedown);
|
|
578
|
+
this.element.removeEventListener("mouseup", this.boundMouseup);
|
|
579
|
+
this.element.removeEventListener("click", this.boundClick);
|
|
580
|
+
this.element = null;
|
|
581
|
+
}
|
|
582
|
+
this.stopIdleDetection();
|
|
583
|
+
if (this.idleStart !== null) {
|
|
584
|
+
const now = performance.now() - this.startTime;
|
|
585
|
+
this.idlePeriods.push({
|
|
586
|
+
start: this.idleStart,
|
|
587
|
+
end: now,
|
|
588
|
+
duration: now - this.idleStart
|
|
589
|
+
});
|
|
590
|
+
this.idleStart = null;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Reset collected data.
|
|
595
|
+
*
|
|
596
|
+
* @param newStartTime - Optional new start time to use for relative timestamps
|
|
597
|
+
*/
|
|
598
|
+
reset(newStartTime) {
|
|
599
|
+
this.events = [];
|
|
600
|
+
this.idlePeriods = [];
|
|
601
|
+
this.lastMoveTime = null;
|
|
602
|
+
this.lastX = null;
|
|
603
|
+
this.lastY = null;
|
|
604
|
+
this.isDragging = false;
|
|
605
|
+
this.idleStart = null;
|
|
606
|
+
this.lastThrottledCall = 0;
|
|
607
|
+
if (newStartTime !== void 0) {
|
|
608
|
+
this.startTime = newStartTime;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Get all collected events.
|
|
613
|
+
*
|
|
614
|
+
* @returns A copy of the collected mouse events array
|
|
615
|
+
*/
|
|
616
|
+
getEvents() {
|
|
617
|
+
return [...this.events];
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Get all detected idle periods.
|
|
621
|
+
*
|
|
622
|
+
* @returns A copy of the idle periods array
|
|
623
|
+
*/
|
|
624
|
+
getIdlePeriods() {
|
|
625
|
+
return [...this.idlePeriods];
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Get total idle time in milliseconds.
|
|
629
|
+
*
|
|
630
|
+
* @returns Sum of all idle period durations
|
|
631
|
+
*/
|
|
632
|
+
getTotalIdleTime() {
|
|
633
|
+
return this.idlePeriods.reduce((sum, period) => sum + period.duration, 0);
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Get total distance traveled by the cursor in pixels.
|
|
637
|
+
*
|
|
638
|
+
* @returns Sum of all distance values from mousemove events
|
|
639
|
+
*/
|
|
640
|
+
getTotalDistance() {
|
|
641
|
+
return this.events.filter((e) => e.event === "mousemove" && e.distance !== void 0).reduce((sum, e) => sum + (e.distance ?? 0), 0);
|
|
642
|
+
}
|
|
643
|
+
createThrottledHandler(handler, throttleMs) {
|
|
644
|
+
return (e) => {
|
|
645
|
+
const now = performance.now();
|
|
646
|
+
if (now - this.lastThrottledCall >= throttleMs) {
|
|
647
|
+
this.lastThrottledCall = now;
|
|
648
|
+
handler(e);
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
handleMousemove(e) {
|
|
653
|
+
const time = performance.now() - this.startTime;
|
|
654
|
+
const x = e.clientX;
|
|
655
|
+
const y = e.clientY;
|
|
656
|
+
let velocity;
|
|
657
|
+
let distance;
|
|
658
|
+
let deltaTime;
|
|
659
|
+
if (this.lastX !== null && this.lastY !== null && this.lastMoveTime !== null) {
|
|
660
|
+
const dx = x - this.lastX;
|
|
661
|
+
const dy = y - this.lastY;
|
|
662
|
+
distance = Math.sqrt(dx * dx + dy * dy);
|
|
663
|
+
deltaTime = time - this.lastMoveTime;
|
|
664
|
+
if (deltaTime > 0) {
|
|
665
|
+
velocity = distance / deltaTime;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
const event = {
|
|
669
|
+
time,
|
|
670
|
+
event: "mousemove",
|
|
671
|
+
x,
|
|
672
|
+
y,
|
|
673
|
+
...velocity !== void 0 ? { velocity } : {},
|
|
674
|
+
...distance !== void 0 ? { distance } : {},
|
|
675
|
+
...deltaTime !== void 0 ? { deltaTime } : {},
|
|
676
|
+
...this.isDragging ? { isDragging: true } : {}
|
|
677
|
+
};
|
|
678
|
+
this.events.push(event);
|
|
679
|
+
this.onEvent?.(event);
|
|
680
|
+
this.lastX = x;
|
|
681
|
+
this.lastY = y;
|
|
682
|
+
this.lastMoveTime = time;
|
|
683
|
+
this.recordActivity(time);
|
|
684
|
+
}
|
|
685
|
+
handleMousedown(e) {
|
|
686
|
+
const time = performance.now() - this.startTime;
|
|
687
|
+
this.isDragging = true;
|
|
688
|
+
const event = {
|
|
689
|
+
time,
|
|
690
|
+
event: "mousedown",
|
|
691
|
+
x: e.clientX,
|
|
692
|
+
y: e.clientY
|
|
693
|
+
};
|
|
694
|
+
this.events.push(event);
|
|
695
|
+
this.onEvent?.(event);
|
|
696
|
+
this.recordActivity(time);
|
|
697
|
+
}
|
|
698
|
+
handleMouseup(e) {
|
|
699
|
+
const time = performance.now() - this.startTime;
|
|
700
|
+
const wasDragging = this.isDragging;
|
|
701
|
+
this.isDragging = false;
|
|
702
|
+
const event = {
|
|
703
|
+
time,
|
|
704
|
+
event: "mouseup",
|
|
705
|
+
x: e.clientX,
|
|
706
|
+
y: e.clientY,
|
|
707
|
+
...wasDragging ? { isDragging: true } : {}
|
|
708
|
+
};
|
|
709
|
+
this.events.push(event);
|
|
710
|
+
this.onEvent?.(event);
|
|
711
|
+
this.recordActivity(time);
|
|
712
|
+
}
|
|
713
|
+
handleClick(e) {
|
|
714
|
+
const time = performance.now() - this.startTime;
|
|
715
|
+
const event = {
|
|
716
|
+
time,
|
|
717
|
+
event: "click",
|
|
718
|
+
x: e.clientX,
|
|
719
|
+
y: e.clientY
|
|
720
|
+
};
|
|
721
|
+
this.events.push(event);
|
|
722
|
+
this.onEvent?.(event);
|
|
723
|
+
this.recordActivity(time);
|
|
724
|
+
}
|
|
725
|
+
recordActivity(time) {
|
|
726
|
+
if (this.idleStart !== null) {
|
|
727
|
+
this.idlePeriods.push({
|
|
728
|
+
start: this.idleStart,
|
|
729
|
+
end: time,
|
|
730
|
+
duration: time - this.idleStart
|
|
731
|
+
});
|
|
732
|
+
this.idleStart = null;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
startIdleDetection() {
|
|
736
|
+
this.idleCheckInterval = setInterval(() => {
|
|
737
|
+
const now = performance.now() - this.startTime;
|
|
738
|
+
const lastEventTime = this.getLastEventTime();
|
|
739
|
+
if (lastEventTime !== null) {
|
|
740
|
+
const timeSinceLastEvent = now - lastEventTime;
|
|
741
|
+
if (timeSinceLastEvent >= this.config.idleThresholdMs && this.idleStart === null) {
|
|
742
|
+
this.idleStart = lastEventTime + this.config.idleThresholdMs;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
}, 1e3);
|
|
746
|
+
}
|
|
747
|
+
stopIdleDetection() {
|
|
748
|
+
if (this.idleCheckInterval !== null) {
|
|
749
|
+
clearInterval(this.idleCheckInterval);
|
|
750
|
+
this.idleCheckInterval = null;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
getLastEventTime() {
|
|
754
|
+
if (this.events.length === 0) {
|
|
755
|
+
return null;
|
|
756
|
+
}
|
|
757
|
+
const lastEvent = this.events[this.events.length - 1];
|
|
758
|
+
return lastEvent?.time ?? null;
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
|
|
762
|
+
// src/collectors/scroll.ts
|
|
763
|
+
var ScrollCollector = class {
|
|
764
|
+
constructor(config, startTime, onEvent) {
|
|
765
|
+
this.config = config;
|
|
766
|
+
this.onEvent = onEvent;
|
|
767
|
+
this.startTime = startTime;
|
|
768
|
+
this.boundScroll = this.handleScroll.bind(this);
|
|
769
|
+
}
|
|
770
|
+
events = [];
|
|
771
|
+
element = null;
|
|
772
|
+
startTime;
|
|
773
|
+
lastScrollTime;
|
|
774
|
+
lastScrollTop;
|
|
775
|
+
lastDirection;
|
|
776
|
+
directionChanges = 0;
|
|
777
|
+
throttleTimer = null;
|
|
778
|
+
boundScroll;
|
|
779
|
+
/**
|
|
780
|
+
* Attach collector to an element.
|
|
781
|
+
*
|
|
782
|
+
* @param element - The element to attach scroll listeners to.
|
|
783
|
+
*/
|
|
784
|
+
attach(element) {
|
|
785
|
+
this.element = element;
|
|
786
|
+
element.addEventListener("scroll", this.boundScroll, { passive: true });
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Detach collector from element.
|
|
790
|
+
*/
|
|
791
|
+
detach() {
|
|
792
|
+
if (this.element) {
|
|
793
|
+
this.element.removeEventListener("scroll", this.boundScroll);
|
|
794
|
+
this.element = null;
|
|
795
|
+
}
|
|
796
|
+
if (this.throttleTimer !== null) {
|
|
797
|
+
clearTimeout(this.throttleTimer);
|
|
798
|
+
this.throttleTimer = null;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Reset collected data.
|
|
803
|
+
*
|
|
804
|
+
* @param newStartTime - Optional new start time for timing calculations.
|
|
805
|
+
*/
|
|
806
|
+
reset(newStartTime) {
|
|
807
|
+
this.events = [];
|
|
808
|
+
this.lastScrollTime = void 0;
|
|
809
|
+
this.lastScrollTop = void 0;
|
|
810
|
+
this.lastDirection = void 0;
|
|
811
|
+
this.directionChanges = 0;
|
|
812
|
+
if (newStartTime !== void 0) {
|
|
813
|
+
this.startTime = newStartTime;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Get all collected events.
|
|
818
|
+
*
|
|
819
|
+
* @returns A copy of the collected scroll events.
|
|
820
|
+
*/
|
|
821
|
+
getEvents() {
|
|
822
|
+
return [...this.events];
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Get the number of scroll direction changes.
|
|
826
|
+
*
|
|
827
|
+
* Direction changes may indicate review behavior (scrolling up and down
|
|
828
|
+
* to read previously written content) rather than linear composition.
|
|
829
|
+
*
|
|
830
|
+
* @returns The count of direction changes.
|
|
831
|
+
*/
|
|
832
|
+
getDirectionChanges() {
|
|
833
|
+
return this.directionChanges;
|
|
834
|
+
}
|
|
835
|
+
handleScroll(e) {
|
|
836
|
+
if (!this.config.enabled) {
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
if (this.throttleTimer !== null) {
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
this.throttleTimer = setTimeout(() => {
|
|
843
|
+
this.throttleTimer = null;
|
|
844
|
+
}, this.config.throttleMs);
|
|
845
|
+
this.recordEvent(e);
|
|
846
|
+
}
|
|
847
|
+
recordEvent(e) {
|
|
848
|
+
const time = performance.now() - this.startTime;
|
|
849
|
+
const target = this.getScrollTarget(e);
|
|
850
|
+
if (!target) {
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
const scrollTop = target.scrollTop;
|
|
854
|
+
const scrollHeight = target.scrollHeight;
|
|
855
|
+
const clientHeight = target.clientHeight;
|
|
856
|
+
const deltaY = this.lastScrollTop !== void 0 ? scrollTop - this.lastScrollTop : 0;
|
|
857
|
+
const direction = deltaY >= 0 ? "down" : "up";
|
|
858
|
+
if (this.config.captureDirection && this.lastDirection !== void 0) {
|
|
859
|
+
if (direction !== this.lastDirection) {
|
|
860
|
+
this.directionChanges++;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
let velocity;
|
|
864
|
+
if (this.lastScrollTime !== void 0 && this.lastScrollTop !== void 0) {
|
|
865
|
+
const timeDelta = time - this.lastScrollTime;
|
|
866
|
+
if (timeDelta > 0) {
|
|
867
|
+
velocity = Math.abs(deltaY) / timeDelta;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
const event = {
|
|
871
|
+
time,
|
|
872
|
+
direction,
|
|
873
|
+
deltaY,
|
|
874
|
+
scrollTop,
|
|
875
|
+
scrollHeight,
|
|
876
|
+
clientHeight,
|
|
877
|
+
...velocity !== void 0 ? { velocity } : {}
|
|
878
|
+
};
|
|
879
|
+
this.events.push(event);
|
|
880
|
+
this.onEvent?.(event);
|
|
881
|
+
this.lastScrollTime = time;
|
|
882
|
+
this.lastScrollTop = scrollTop;
|
|
883
|
+
this.lastDirection = direction;
|
|
884
|
+
}
|
|
885
|
+
getScrollTarget(e) {
|
|
886
|
+
const target = e.target;
|
|
887
|
+
if (target instanceof Document) {
|
|
888
|
+
const docEl = target.documentElement;
|
|
889
|
+
return {
|
|
890
|
+
scrollTop: docEl.scrollTop,
|
|
891
|
+
scrollHeight: docEl.scrollHeight,
|
|
892
|
+
clientHeight: docEl.clientHeight
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
if (target instanceof HTMLElement) {
|
|
896
|
+
return {
|
|
897
|
+
scrollTop: target.scrollTop,
|
|
898
|
+
scrollHeight: target.scrollHeight,
|
|
899
|
+
clientHeight: target.clientHeight
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
return null;
|
|
903
|
+
}
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
// src/metrics/focus-metrics.ts
|
|
907
|
+
function computeFocusMetrics(focusEvents) {
|
|
908
|
+
let blurCount = 0;
|
|
909
|
+
let totalBlurDuration = 0;
|
|
910
|
+
let hiddenCount = 0;
|
|
911
|
+
let totalHiddenDuration = 0;
|
|
912
|
+
let lastHiddenTime;
|
|
913
|
+
for (const event of focusEvents) {
|
|
914
|
+
switch (event.event) {
|
|
915
|
+
case "blur":
|
|
916
|
+
blurCount++;
|
|
917
|
+
if (event.blurDuration !== void 0) {
|
|
918
|
+
totalBlurDuration += event.blurDuration;
|
|
919
|
+
}
|
|
920
|
+
break;
|
|
921
|
+
case "visibilitychange":
|
|
922
|
+
if (event.visibility === "hidden") {
|
|
923
|
+
hiddenCount++;
|
|
924
|
+
lastHiddenTime = event.time;
|
|
925
|
+
} else if (event.visibility === "visible" && lastHiddenTime !== void 0) {
|
|
926
|
+
totalHiddenDuration += event.time - lastHiddenTime;
|
|
927
|
+
lastHiddenTime = void 0;
|
|
928
|
+
}
|
|
929
|
+
break;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
return {
|
|
933
|
+
blurCount,
|
|
934
|
+
totalBlurDuration,
|
|
935
|
+
hiddenCount,
|
|
936
|
+
totalHiddenDuration
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// src/metrics/input-duration-metrics.ts
|
|
941
|
+
function computeInputDurationMetrics(events) {
|
|
942
|
+
if (events.length === 0) {
|
|
943
|
+
return {
|
|
944
|
+
totalFocusDuration: 0,
|
|
945
|
+
meanFocusDuration: 0,
|
|
946
|
+
focusSessionCount: 0,
|
|
947
|
+
maxFocusDuration: 0
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
const durations = events.map((e) => e.duration);
|
|
951
|
+
const totalFocusDuration = durations.reduce((a, b) => a + b, 0);
|
|
952
|
+
const meanFocusDuration = totalFocusDuration / events.length;
|
|
953
|
+
const maxFocusDuration = Math.max(...durations);
|
|
954
|
+
return {
|
|
955
|
+
totalFocusDuration,
|
|
956
|
+
meanFocusDuration,
|
|
957
|
+
focusSessionCount: events.length,
|
|
958
|
+
maxFocusDuration
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
// src/metrics/keystroke-metrics.ts
|
|
963
|
+
var DEFAULT_PAUSE_THRESHOLD = 2e3;
|
|
964
|
+
function computeKeystrokeMetrics(keystrokes, pauseThreshold = DEFAULT_PAUSE_THRESHOLD) {
|
|
965
|
+
const keydowns = keystrokes.filter((k) => k.event === "keydown");
|
|
966
|
+
if (keydowns.length === 0) {
|
|
967
|
+
return {
|
|
968
|
+
totalKeystrokes: 0,
|
|
969
|
+
printableKeystrokes: 0,
|
|
970
|
+
deletions: 0,
|
|
971
|
+
meanIKI: 0,
|
|
972
|
+
stdIKI: 0,
|
|
973
|
+
medianIKI: 0,
|
|
974
|
+
pauseCount: 0,
|
|
975
|
+
productProcessRatio: 0
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
const printableKeystrokes = keydowns.filter((k) => k.key.length === 1).length;
|
|
979
|
+
const deletions = keydowns.filter((k) => k.key === "Backspace" || k.key === "Delete").length;
|
|
980
|
+
const ikis = computeIKIs(keydowns);
|
|
981
|
+
const { mean, std, median } = computeIKIStats(ikis);
|
|
982
|
+
const pauseCount = ikis.filter((iki) => iki > pauseThreshold).length;
|
|
983
|
+
const lastEvent = keydowns[keydowns.length - 1];
|
|
984
|
+
const finalLength = lastEvent?.textLength ?? 0;
|
|
985
|
+
const productProcessRatio = keydowns.length > 0 ? finalLength / keydowns.length : 0;
|
|
986
|
+
return {
|
|
987
|
+
totalKeystrokes: keydowns.length,
|
|
988
|
+
printableKeystrokes,
|
|
989
|
+
deletions,
|
|
990
|
+
meanIKI: mean,
|
|
991
|
+
stdIKI: std,
|
|
992
|
+
medianIKI: median,
|
|
993
|
+
pauseCount,
|
|
994
|
+
productProcessRatio
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
function computeIKIs(keydowns) {
|
|
998
|
+
if (keydowns.length < 2) {
|
|
999
|
+
return [];
|
|
1000
|
+
}
|
|
1001
|
+
const ikis = [];
|
|
1002
|
+
for (let i = 1; i < keydowns.length; i++) {
|
|
1003
|
+
const prev = keydowns[i - 1];
|
|
1004
|
+
const curr = keydowns[i];
|
|
1005
|
+
if (prev && curr) {
|
|
1006
|
+
ikis.push(curr.time - prev.time);
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
return ikis;
|
|
1010
|
+
}
|
|
1011
|
+
function computeIKIStats(ikis) {
|
|
1012
|
+
if (ikis.length === 0) {
|
|
1013
|
+
return { mean: 0, std: 0, median: 0 };
|
|
1014
|
+
}
|
|
1015
|
+
const sum = ikis.reduce((a, b) => a + b, 0);
|
|
1016
|
+
const mean = sum / ikis.length;
|
|
1017
|
+
const squaredDiffs = ikis.map((iki) => (iki - mean) ** 2);
|
|
1018
|
+
const variance = squaredDiffs.reduce((a, b) => a + b, 0) / ikis.length;
|
|
1019
|
+
const std = Math.sqrt(variance);
|
|
1020
|
+
const sorted = [...ikis].sort((a, b) => a - b);
|
|
1021
|
+
const mid = Math.floor(sorted.length / 2);
|
|
1022
|
+
const median = sorted.length % 2 === 0 ? ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2 : sorted[mid] ?? 0;
|
|
1023
|
+
return { mean, std, median };
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
// src/metrics/mouse-metrics.ts
|
|
1027
|
+
function computeMouseMetrics(events, idlePeriods) {
|
|
1028
|
+
if (events.length === 0) {
|
|
1029
|
+
return {
|
|
1030
|
+
totalEvents: 0,
|
|
1031
|
+
clickCount: 0,
|
|
1032
|
+
meanVelocity: 0,
|
|
1033
|
+
totalDistance: 0,
|
|
1034
|
+
totalIdleTime: 0,
|
|
1035
|
+
idlePeriodCount: 0
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
const clickCount = events.filter((e) => e.event === "click").length;
|
|
1039
|
+
const moveEvents = events.filter((e) => e.event === "mousemove" && e.velocity !== void 0);
|
|
1040
|
+
const velocities = moveEvents.map((e) => e.velocity ?? 0);
|
|
1041
|
+
const meanVelocity = velocities.length > 0 ? velocities.reduce((a, b) => a + b, 0) / velocities.length : 0;
|
|
1042
|
+
const totalDistance = events.filter((e) => e.event === "mousemove" && e.distance !== void 0).reduce((sum, e) => sum + (e.distance ?? 0), 0);
|
|
1043
|
+
const totalIdleTime = idlePeriods.reduce((sum, p) => sum + p.duration, 0);
|
|
1044
|
+
return {
|
|
1045
|
+
totalEvents: events.length,
|
|
1046
|
+
clickCount,
|
|
1047
|
+
meanVelocity,
|
|
1048
|
+
totalDistance,
|
|
1049
|
+
totalIdleTime,
|
|
1050
|
+
idlePeriodCount: idlePeriods.length
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// src/metrics/scroll-metrics.ts
|
|
1055
|
+
function computeScrollMetrics(events, directionChanges) {
|
|
1056
|
+
if (events.length === 0) {
|
|
1057
|
+
return {
|
|
1058
|
+
totalScrollEvents: 0,
|
|
1059
|
+
totalScrollDistance: 0,
|
|
1060
|
+
directionChanges: 0,
|
|
1061
|
+
meanScrollVelocity: 0,
|
|
1062
|
+
upDownRatio: 0
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
const totalScrollDistance = events.reduce((sum, e) => sum + Math.abs(e.deltaY), 0);
|
|
1066
|
+
const eventsWithVelocity = events.filter((e) => e.velocity !== void 0);
|
|
1067
|
+
const velocities = eventsWithVelocity.map((e) => e.velocity ?? 0);
|
|
1068
|
+
const meanScrollVelocity = velocities.length > 0 ? velocities.reduce((a, b) => a + b, 0) / velocities.length : 0;
|
|
1069
|
+
const upCount = events.filter((e) => e.direction === "up").length;
|
|
1070
|
+
const downCount = events.filter((e) => e.direction === "down").length;
|
|
1071
|
+
const upDownRatio = downCount > 0 ? upCount / downCount : upCount > 0 ? 1 : 0;
|
|
1072
|
+
return {
|
|
1073
|
+
totalScrollEvents: events.length,
|
|
1074
|
+
totalScrollDistance,
|
|
1075
|
+
directionChanges,
|
|
1076
|
+
meanScrollVelocity,
|
|
1077
|
+
upDownRatio
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// src/metrics/timing-metrics.ts
|
|
1082
|
+
function computeTimingMetrics(keystrokes, totalResponseTime) {
|
|
1083
|
+
const keydowns = keystrokes.filter((k) => k.event === "keydown");
|
|
1084
|
+
const firstKeystroke = keydowns[0];
|
|
1085
|
+
const firstKeystrokeLatency = firstKeystroke?.time;
|
|
1086
|
+
const printableCount = keydowns.filter((k) => k.key.length === 1).length;
|
|
1087
|
+
const deletionCount = keydowns.filter((k) => k.key === "Backspace" || k.key === "Delete").length;
|
|
1088
|
+
const netCharacters = Math.max(0, printableCount - deletionCount);
|
|
1089
|
+
const minutes = totalResponseTime / 6e4;
|
|
1090
|
+
const charactersPerMinute = minutes > 0 ? netCharacters / minutes : null;
|
|
1091
|
+
return {
|
|
1092
|
+
...firstKeystrokeLatency !== void 0 ? { firstKeystrokeLatency } : {},
|
|
1093
|
+
totalResponseTime,
|
|
1094
|
+
...charactersPerMinute !== null ? { charactersPerMinute } : {}
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
// src/capture.ts
|
|
1099
|
+
var BehavioralCapture = class {
|
|
1100
|
+
config;
|
|
1101
|
+
keystrokeCollector = null;
|
|
1102
|
+
focusCollector = null;
|
|
1103
|
+
clipboardCollector = null;
|
|
1104
|
+
mouseCollector = null;
|
|
1105
|
+
scrollCollector = null;
|
|
1106
|
+
inputDurationCollector = null;
|
|
1107
|
+
attachedElement = null;
|
|
1108
|
+
trialStartTime = 0;
|
|
1109
|
+
listeners = /* @__PURE__ */ new Map();
|
|
1110
|
+
constructor(config) {
|
|
1111
|
+
this.config = this.normalizeConfig(config);
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Attach capture to a DOM element.
|
|
1115
|
+
*
|
|
1116
|
+
* For text input capture, attach to the input or textarea element.
|
|
1117
|
+
* For document-level focus tracking, attach to document.
|
|
1118
|
+
*
|
|
1119
|
+
* @param element - The element to attach to
|
|
1120
|
+
* @param startTime - Optional trial start time (defaults to now)
|
|
1121
|
+
*/
|
|
1122
|
+
attach(element, startTime) {
|
|
1123
|
+
this.trialStartTime = startTime ?? performance.now();
|
|
1124
|
+
this.attachedElement = element instanceof Document ? document.body : element;
|
|
1125
|
+
if (this.config.inputDuration.enabled) {
|
|
1126
|
+
this.inputDurationCollector = new InputDurationCollector(
|
|
1127
|
+
this.config.inputDuration,
|
|
1128
|
+
this.trialStartTime,
|
|
1129
|
+
(event) => this.emit("inputDuration", event)
|
|
1130
|
+
);
|
|
1131
|
+
this.inputDurationCollector.attach(element);
|
|
1132
|
+
}
|
|
1133
|
+
if (this.config.keystroke.enabled) {
|
|
1134
|
+
this.keystrokeCollector = new KeystrokeCollector(
|
|
1135
|
+
this.config.keystroke,
|
|
1136
|
+
this.trialStartTime,
|
|
1137
|
+
(event) => {
|
|
1138
|
+
this.emit("keystroke", event);
|
|
1139
|
+
this.inputDurationCollector?.incrementKeystrokes();
|
|
1140
|
+
}
|
|
1141
|
+
);
|
|
1142
|
+
this.keystrokeCollector.attach(element);
|
|
1143
|
+
}
|
|
1144
|
+
if (this.config.focus.enabled) {
|
|
1145
|
+
this.focusCollector = new FocusCollector(
|
|
1146
|
+
this.config.focus,
|
|
1147
|
+
this.trialStartTime,
|
|
1148
|
+
(event) => this.emit("focus", event)
|
|
1149
|
+
);
|
|
1150
|
+
this.focusCollector.attach(document);
|
|
1151
|
+
}
|
|
1152
|
+
if (this.config.clipboard.enabled) {
|
|
1153
|
+
this.clipboardCollector = new ClipboardCollector(
|
|
1154
|
+
this.config.clipboard,
|
|
1155
|
+
this.trialStartTime,
|
|
1156
|
+
() => this.keystrokeCollector?.getRecentCount(2e3) ?? 0,
|
|
1157
|
+
(event) => {
|
|
1158
|
+
this.emit("paste", event);
|
|
1159
|
+
this.inputDurationCollector?.incrementPastes();
|
|
1160
|
+
},
|
|
1161
|
+
(event) => this.emit("clipboard", event)
|
|
1162
|
+
);
|
|
1163
|
+
this.clipboardCollector.attach(element);
|
|
1164
|
+
}
|
|
1165
|
+
if (this.config.mouse.enabled) {
|
|
1166
|
+
this.mouseCollector = new MouseCollector(
|
|
1167
|
+
this.config.mouse,
|
|
1168
|
+
this.trialStartTime,
|
|
1169
|
+
(event) => this.emit("mouse", event)
|
|
1170
|
+
);
|
|
1171
|
+
this.mouseCollector.attach(element);
|
|
1172
|
+
}
|
|
1173
|
+
if (this.config.scroll.enabled) {
|
|
1174
|
+
this.scrollCollector = new ScrollCollector(
|
|
1175
|
+
this.config.scroll,
|
|
1176
|
+
this.trialStartTime,
|
|
1177
|
+
(event) => this.emit("scroll", event)
|
|
1178
|
+
);
|
|
1179
|
+
this.scrollCollector.attach(element);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Detach capture and clean up event listeners.
|
|
1184
|
+
*/
|
|
1185
|
+
detach() {
|
|
1186
|
+
this.keystrokeCollector?.detach();
|
|
1187
|
+
this.focusCollector?.detach();
|
|
1188
|
+
this.clipboardCollector?.detach();
|
|
1189
|
+
this.mouseCollector?.detach();
|
|
1190
|
+
this.scrollCollector?.detach();
|
|
1191
|
+
this.inputDurationCollector?.detach();
|
|
1192
|
+
this.keystrokeCollector = null;
|
|
1193
|
+
this.focusCollector = null;
|
|
1194
|
+
this.clipboardCollector = null;
|
|
1195
|
+
this.mouseCollector = null;
|
|
1196
|
+
this.scrollCollector = null;
|
|
1197
|
+
this.inputDurationCollector = null;
|
|
1198
|
+
this.attachedElement = null;
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* Reset all collected data without detaching.
|
|
1202
|
+
*
|
|
1203
|
+
* @param newStartTime - Optional new start time
|
|
1204
|
+
*/
|
|
1205
|
+
reset(newStartTime) {
|
|
1206
|
+
this.trialStartTime = newStartTime ?? performance.now();
|
|
1207
|
+
this.keystrokeCollector?.reset(this.trialStartTime);
|
|
1208
|
+
this.focusCollector?.reset(this.trialStartTime);
|
|
1209
|
+
this.clipboardCollector?.reset(this.trialStartTime);
|
|
1210
|
+
this.mouseCollector?.reset(this.trialStartTime);
|
|
1211
|
+
this.scrollCollector?.reset(this.trialStartTime);
|
|
1212
|
+
this.inputDurationCollector?.reset(this.trialStartTime);
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Get all collected behavioral data.
|
|
1216
|
+
*/
|
|
1217
|
+
getData() {
|
|
1218
|
+
return {
|
|
1219
|
+
keystrokes: this.keystrokeCollector?.getEvents() ?? [],
|
|
1220
|
+
focus: this.focusCollector?.getEvents() ?? [],
|
|
1221
|
+
paste: this.clipboardCollector?.getPasteEvents() ?? [],
|
|
1222
|
+
mouse: this.mouseCollector?.getEvents() ?? [],
|
|
1223
|
+
scroll: this.scrollCollector?.getEvents() ?? [],
|
|
1224
|
+
clipboard: this.clipboardCollector?.getCopyEvents() ?? [],
|
|
1225
|
+
inputDuration: this.inputDurationCollector?.getEvents() ?? [],
|
|
1226
|
+
metrics: this.getMetrics()
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Get computed metrics from collected data.
|
|
1231
|
+
*/
|
|
1232
|
+
getMetrics() {
|
|
1233
|
+
const keystrokes = this.keystrokeCollector?.getEvents() ?? [];
|
|
1234
|
+
const focusEvents = this.focusCollector?.getEvents() ?? [];
|
|
1235
|
+
const mouseEvents = this.mouseCollector?.getEvents() ?? [];
|
|
1236
|
+
const mouseIdlePeriods = this.mouseCollector?.getIdlePeriods() ?? [];
|
|
1237
|
+
const scrollEvents = this.scrollCollector?.getEvents() ?? [];
|
|
1238
|
+
const scrollDirectionChanges = this.scrollCollector?.getDirectionChanges() ?? 0;
|
|
1239
|
+
const inputDurationEvents = this.inputDurationCollector?.getEvents() ?? [];
|
|
1240
|
+
const currentTime = performance.now();
|
|
1241
|
+
const totalResponseTime = currentTime - this.trialStartTime;
|
|
1242
|
+
const keystrokeMetrics = keystrokes.length > 0 ? computeKeystrokeMetrics(keystrokes) : null;
|
|
1243
|
+
const focusMetrics = focusEvents.length > 0 ? computeFocusMetrics(focusEvents) : null;
|
|
1244
|
+
const mouseMetrics = mouseEvents.length > 0 ? computeMouseMetrics(mouseEvents, mouseIdlePeriods) : null;
|
|
1245
|
+
const scrollMetrics = scrollEvents.length > 0 ? computeScrollMetrics(scrollEvents, scrollDirectionChanges) : null;
|
|
1246
|
+
const inputDurationMetrics = inputDurationEvents.length > 0 ? computeInputDurationMetrics(inputDurationEvents) : null;
|
|
1247
|
+
return {
|
|
1248
|
+
...keystrokeMetrics !== null ? { keystroke: keystrokeMetrics } : {},
|
|
1249
|
+
...focusMetrics !== null ? { focus: focusMetrics } : {},
|
|
1250
|
+
timing: computeTimingMetrics(keystrokes, totalResponseTime),
|
|
1251
|
+
...mouseMetrics !== null ? { mouse: mouseMetrics } : {},
|
|
1252
|
+
...scrollMetrics !== null ? { scroll: scrollMetrics } : {},
|
|
1253
|
+
...inputDurationMetrics !== null ? { inputDuration: inputDurationMetrics } : {}
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* Get flags generated during capture.
|
|
1258
|
+
*/
|
|
1259
|
+
getFlags() {
|
|
1260
|
+
const flags = [];
|
|
1261
|
+
const pasteEvents = this.clipboardCollector?.getPasteEvents() ?? [];
|
|
1262
|
+
if (pasteEvents.length > 0) {
|
|
1263
|
+
flags.push({
|
|
1264
|
+
type: "paste_detected",
|
|
1265
|
+
severity: "medium",
|
|
1266
|
+
message: `${pasteEvents.length} paste event(s) detected`,
|
|
1267
|
+
timestamp: Date.now(),
|
|
1268
|
+
details: { count: pasteEvents.length }
|
|
1269
|
+
});
|
|
1270
|
+
}
|
|
1271
|
+
const focusEvents = this.focusCollector?.getEvents() ?? [];
|
|
1272
|
+
const blurCount = focusEvents.filter((e) => e.event === "blur").length;
|
|
1273
|
+
if (blurCount > 5) {
|
|
1274
|
+
flags.push({
|
|
1275
|
+
type: "excessive_blur",
|
|
1276
|
+
severity: "low",
|
|
1277
|
+
message: `${blurCount} window blur events detected`,
|
|
1278
|
+
timestamp: Date.now(),
|
|
1279
|
+
details: { count: blurCount }
|
|
1280
|
+
});
|
|
1281
|
+
}
|
|
1282
|
+
const mouseIdlePeriods = this.mouseCollector?.getIdlePeriods() ?? [];
|
|
1283
|
+
const longIdlePeriods = mouseIdlePeriods.filter((p) => p.duration > 3e4);
|
|
1284
|
+
if (longIdlePeriods.length > 0) {
|
|
1285
|
+
const totalIdleTime = longIdlePeriods.reduce((sum, p) => sum + p.duration, 0);
|
|
1286
|
+
flags.push({
|
|
1287
|
+
type: "mouse_idle_anomaly",
|
|
1288
|
+
severity: "low",
|
|
1289
|
+
message: `${longIdlePeriods.length} long mouse idle period(s) detected (${Math.round(totalIdleTime / 1e3)}s total)`,
|
|
1290
|
+
timestamp: Date.now(),
|
|
1291
|
+
details: {
|
|
1292
|
+
count: longIdlePeriods.length,
|
|
1293
|
+
totalIdleMs: totalIdleTime,
|
|
1294
|
+
periods: longIdlePeriods
|
|
1295
|
+
}
|
|
1296
|
+
});
|
|
1297
|
+
}
|
|
1298
|
+
const copyEvents = this.clipboardCollector?.getCopyEvents() ?? [];
|
|
1299
|
+
for (const paste of pasteEvents) {
|
|
1300
|
+
const recentCopies = copyEvents.filter(
|
|
1301
|
+
(c) => c.time < paste.time && paste.time - c.time < 5e3
|
|
1302
|
+
);
|
|
1303
|
+
if (recentCopies.length > 0 && paste.precedingKeystrokes < 5) {
|
|
1304
|
+
flags.push({
|
|
1305
|
+
type: "sudden_text_appearance",
|
|
1306
|
+
severity: "medium",
|
|
1307
|
+
message: "Text pasted shortly after internal copy with minimal typing, potential pre-composed content",
|
|
1308
|
+
timestamp: Date.now(),
|
|
1309
|
+
details: {
|
|
1310
|
+
pasteTime: paste.time,
|
|
1311
|
+
pasteLength: paste.textLength,
|
|
1312
|
+
precedingKeystrokes: paste.precedingKeystrokes,
|
|
1313
|
+
recentCopyCount: recentCopies.length
|
|
1314
|
+
}
|
|
1315
|
+
});
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
return flags;
|
|
1319
|
+
}
|
|
1320
|
+
/**
|
|
1321
|
+
* Subscribe to capture events.
|
|
1322
|
+
*/
|
|
1323
|
+
on(event, handler) {
|
|
1324
|
+
if (!this.listeners.has(event)) {
|
|
1325
|
+
this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
1326
|
+
}
|
|
1327
|
+
this.listeners.get(event)?.add(handler);
|
|
1328
|
+
}
|
|
1329
|
+
/**
|
|
1330
|
+
* Unsubscribe from capture events.
|
|
1331
|
+
*/
|
|
1332
|
+
off(event, handler) {
|
|
1333
|
+
this.listeners.get(event)?.delete(handler);
|
|
1334
|
+
}
|
|
1335
|
+
emit(event, data) {
|
|
1336
|
+
for (const handler of this.listeners.get(event) ?? []) {
|
|
1337
|
+
handler(data);
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
normalizeConfig(config) {
|
|
1341
|
+
const pasteWarnMessage = config.paste?.warnMessage;
|
|
1342
|
+
const clipboardWarnMessage = config.clipboard?.warnMessage;
|
|
1343
|
+
return {
|
|
1344
|
+
keystroke: {
|
|
1345
|
+
enabled: config.keystroke?.enabled ?? true,
|
|
1346
|
+
captureKeyUp: config.keystroke?.captureKeyUp ?? true,
|
|
1347
|
+
includeModifiers: config.keystroke?.includeModifiers ?? true
|
|
1348
|
+
},
|
|
1349
|
+
focus: {
|
|
1350
|
+
enabled: config.focus?.enabled ?? true,
|
|
1351
|
+
useVisibilityAPI: config.focus?.useVisibilityAPI ?? true,
|
|
1352
|
+
useBlurFocus: config.focus?.useBlurFocus ?? true
|
|
1353
|
+
},
|
|
1354
|
+
paste: {
|
|
1355
|
+
enabled: config.paste?.enabled ?? true,
|
|
1356
|
+
prevent: config.paste?.prevent ?? false,
|
|
1357
|
+
capturePreview: config.paste?.capturePreview ?? true,
|
|
1358
|
+
previewLength: config.paste?.previewLength ?? 100,
|
|
1359
|
+
...pasteWarnMessage !== void 0 ? { warnMessage: pasteWarnMessage } : {}
|
|
1360
|
+
},
|
|
1361
|
+
inputDuration: {
|
|
1362
|
+
enabled: config.inputDuration?.enabled ?? true,
|
|
1363
|
+
trackKeystrokes: config.inputDuration?.trackKeystrokes ?? true,
|
|
1364
|
+
trackPastes: config.inputDuration?.trackPastes ?? true
|
|
1365
|
+
},
|
|
1366
|
+
clipboard: {
|
|
1367
|
+
enabled: config.clipboard?.enabled ?? true,
|
|
1368
|
+
capturePaste: config.clipboard?.capturePaste ?? true,
|
|
1369
|
+
captureCopyCut: config.clipboard?.captureCopyCut ?? true,
|
|
1370
|
+
prevent: config.clipboard?.prevent ?? false,
|
|
1371
|
+
capturePreview: config.clipboard?.capturePreview ?? true,
|
|
1372
|
+
previewLength: config.clipboard?.previewLength ?? 100,
|
|
1373
|
+
...clipboardWarnMessage !== void 0 ? { warnMessage: clipboardWarnMessage } : {}
|
|
1374
|
+
},
|
|
1375
|
+
mouse: {
|
|
1376
|
+
enabled: config.mouse?.enabled ?? true,
|
|
1377
|
+
captureClicks: config.mouse?.captureClicks ?? true,
|
|
1378
|
+
captureMovement: config.mouse?.captureMovement ?? true,
|
|
1379
|
+
throttleMs: config.mouse?.throttleMs ?? 50,
|
|
1380
|
+
idleThresholdMs: config.mouse?.idleThresholdMs ?? 5e3
|
|
1381
|
+
},
|
|
1382
|
+
scroll: {
|
|
1383
|
+
enabled: config.scroll?.enabled ?? true,
|
|
1384
|
+
throttleMs: config.scroll?.throttleMs ?? 100,
|
|
1385
|
+
captureDirection: config.scroll?.captureDirection ?? true
|
|
1386
|
+
}
|
|
1387
|
+
};
|
|
1388
|
+
}
|
|
1389
|
+
};
|
|
1390
|
+
function createBehavioralCapture(config) {
|
|
1391
|
+
return new BehavioralCapture(config);
|
|
1392
|
+
}
|
|
1393
|
+
var PasteCollector = class {
|
|
1394
|
+
constructor(config, startTime, getRecentKeystrokes, onEvent) {
|
|
1395
|
+
this.config = config;
|
|
1396
|
+
this.getRecentKeystrokes = getRecentKeystrokes;
|
|
1397
|
+
this.onEvent = onEvent;
|
|
1398
|
+
this.startTime = startTime;
|
|
1399
|
+
this.boundPaste = this.handlePaste.bind(this);
|
|
1400
|
+
}
|
|
1401
|
+
events = [];
|
|
1402
|
+
element = null;
|
|
1403
|
+
startTime;
|
|
1404
|
+
boundPaste;
|
|
1405
|
+
/**
|
|
1406
|
+
* Attach collector to an element.
|
|
1407
|
+
*/
|
|
1408
|
+
attach(element) {
|
|
1409
|
+
this.element = element;
|
|
1410
|
+
element.addEventListener("paste", this.boundPaste);
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* Detach collector from element.
|
|
1414
|
+
*/
|
|
1415
|
+
detach() {
|
|
1416
|
+
if (this.element) {
|
|
1417
|
+
this.element.removeEventListener("paste", this.boundPaste);
|
|
1418
|
+
this.element = null;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
/**
|
|
1422
|
+
* Reset collected data.
|
|
1423
|
+
*/
|
|
1424
|
+
reset(newStartTime) {
|
|
1425
|
+
this.events = [];
|
|
1426
|
+
if (newStartTime !== void 0) {
|
|
1427
|
+
this.startTime = newStartTime;
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
/**
|
|
1431
|
+
* Get all collected events.
|
|
1432
|
+
*/
|
|
1433
|
+
getEvents() {
|
|
1434
|
+
return [...this.events];
|
|
1435
|
+
}
|
|
1436
|
+
handlePaste(e) {
|
|
1437
|
+
const text = e.clipboardData?.getData("text/plain") ?? "";
|
|
1438
|
+
const time = performance.now() - this.startTime;
|
|
1439
|
+
const precedingKeystrokes = this.getRecentKeystrokes();
|
|
1440
|
+
if (this.config.prevent) {
|
|
1441
|
+
e.preventDefault();
|
|
1442
|
+
if (this.config.warnMessage) {
|
|
1443
|
+
alert(this.config.warnMessage);
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
const event = {
|
|
1447
|
+
time,
|
|
1448
|
+
textLength: text.length,
|
|
1449
|
+
precedingKeystrokes,
|
|
1450
|
+
blocked: this.config.prevent,
|
|
1451
|
+
...this.config.capturePreview ? { textPreview: text.slice(0, this.config.previewLength) } : {},
|
|
1452
|
+
// Hash asynchronously but use sync hash for immediate event
|
|
1453
|
+
textHash: simpleHash(text)
|
|
1454
|
+
};
|
|
1455
|
+
this.events.push(event);
|
|
1456
|
+
this.onEvent?.(event);
|
|
1457
|
+
if (text.length > 0) {
|
|
1458
|
+
hashText(text).then((hash) => {
|
|
1459
|
+
event.textHash = hash;
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
};
|
|
1464
|
+
|
|
1465
|
+
// src/detection/text-appearance.ts
|
|
1466
|
+
var DEFAULT_CONFIG = {
|
|
1467
|
+
minTextLength: 50,
|
|
1468
|
+
timeWindowMs: 2e3
|
|
1469
|
+
};
|
|
1470
|
+
var TextAppearanceDetector = class {
|
|
1471
|
+
name = "text_appearance";
|
|
1472
|
+
observer = null;
|
|
1473
|
+
indicators = [];
|
|
1474
|
+
lastTextLength = /* @__PURE__ */ new Map();
|
|
1475
|
+
keystrokeCallback;
|
|
1476
|
+
pasteCallback;
|
|
1477
|
+
config;
|
|
1478
|
+
startTime;
|
|
1479
|
+
monitoredElement = null;
|
|
1480
|
+
inputHandler = null;
|
|
1481
|
+
/**
|
|
1482
|
+
* Creates a new TextAppearanceDetector.
|
|
1483
|
+
*
|
|
1484
|
+
* @param config - Configuration options
|
|
1485
|
+
* @param callbacks - Callbacks for checking keystroke and paste activity
|
|
1486
|
+
*/
|
|
1487
|
+
constructor(config = {}, callbacks) {
|
|
1488
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
1489
|
+
this.keystrokeCallback = callbacks?.getRecentKeystrokes;
|
|
1490
|
+
this.pasteCallback = callbacks?.hadRecentPaste;
|
|
1491
|
+
this.startTime = performance.now();
|
|
1492
|
+
}
|
|
1493
|
+
/**
|
|
1494
|
+
* Returns detection results with all recorded indicators.
|
|
1495
|
+
*
|
|
1496
|
+
* @returns Detection result with indicators of sudden text appearance
|
|
1497
|
+
*/
|
|
1498
|
+
detect() {
|
|
1499
|
+
const detected = this.indicators.length > 0;
|
|
1500
|
+
const confidence = detected ? this.calculateConfidence() : 0;
|
|
1501
|
+
return {
|
|
1502
|
+
detected,
|
|
1503
|
+
confidence,
|
|
1504
|
+
message: detected ? `Detected ${this.indicators.length} instance(s) of sudden text appearance` : "No sudden text appearance detected",
|
|
1505
|
+
indicators: [...this.indicators]
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
/**
|
|
1509
|
+
* Starts monitoring an element for sudden text appearance.
|
|
1510
|
+
*
|
|
1511
|
+
* Watches for text changes in input/textarea elements and content changes
|
|
1512
|
+
* in contenteditable elements via MutationObserver.
|
|
1513
|
+
*
|
|
1514
|
+
* @param element - The element to monitor
|
|
1515
|
+
*/
|
|
1516
|
+
startMonitoring(element) {
|
|
1517
|
+
if (this.observer) {
|
|
1518
|
+
this.stopMonitoring();
|
|
1519
|
+
}
|
|
1520
|
+
this.monitoredElement = element;
|
|
1521
|
+
this.startTime = performance.now();
|
|
1522
|
+
this.initializeTextLengths(element);
|
|
1523
|
+
this.inputHandler = this.handleInputEvent.bind(this);
|
|
1524
|
+
element.addEventListener("input", this.inputHandler, true);
|
|
1525
|
+
this.observer = new MutationObserver(this.handleMutations.bind(this));
|
|
1526
|
+
this.observer.observe(element, {
|
|
1527
|
+
characterData: true,
|
|
1528
|
+
childList: true,
|
|
1529
|
+
subtree: true,
|
|
1530
|
+
characterDataOldValue: true
|
|
1531
|
+
});
|
|
1532
|
+
}
|
|
1533
|
+
/**
|
|
1534
|
+
* Stops monitoring and cleans up resources.
|
|
1535
|
+
*/
|
|
1536
|
+
stopMonitoring() {
|
|
1537
|
+
if (this.observer) {
|
|
1538
|
+
this.observer.disconnect();
|
|
1539
|
+
this.observer = null;
|
|
1540
|
+
}
|
|
1541
|
+
if (this.monitoredElement && this.inputHandler) {
|
|
1542
|
+
this.monitoredElement.removeEventListener("input", this.inputHandler, true);
|
|
1543
|
+
this.inputHandler = null;
|
|
1544
|
+
}
|
|
1545
|
+
this.monitoredElement = null;
|
|
1546
|
+
this.lastTextLength.clear();
|
|
1547
|
+
}
|
|
1548
|
+
/**
|
|
1549
|
+
* Resets the detector state.
|
|
1550
|
+
*
|
|
1551
|
+
* @param newStartTime - Optional new start time for timing calculations
|
|
1552
|
+
*/
|
|
1553
|
+
reset(newStartTime) {
|
|
1554
|
+
this.indicators = [];
|
|
1555
|
+
this.lastTextLength.clear();
|
|
1556
|
+
if (newStartTime !== void 0) {
|
|
1557
|
+
this.startTime = newStartTime;
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
/**
|
|
1561
|
+
* Returns the current list of indicators.
|
|
1562
|
+
*
|
|
1563
|
+
* @returns Copy of the indicators array
|
|
1564
|
+
*/
|
|
1565
|
+
getIndicators() {
|
|
1566
|
+
return [...this.indicators];
|
|
1567
|
+
}
|
|
1568
|
+
initializeTextLengths(element) {
|
|
1569
|
+
const inputs = element.querySelectorAll("input, textarea");
|
|
1570
|
+
for (const input of inputs) {
|
|
1571
|
+
if (input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement) {
|
|
1572
|
+
this.lastTextLength.set(input, input.value.length);
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
const editables = element.querySelectorAll("[contenteditable]");
|
|
1576
|
+
for (const editable of editables) {
|
|
1577
|
+
this.lastTextLength.set(editable, editable.textContent?.length ?? 0);
|
|
1578
|
+
}
|
|
1579
|
+
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
|
|
1580
|
+
this.lastTextLength.set(element, element.value.length);
|
|
1581
|
+
} else if (element.isContentEditable) {
|
|
1582
|
+
this.lastTextLength.set(element, element.textContent?.length ?? 0);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
handleInputEvent(e) {
|
|
1586
|
+
const target = e.target;
|
|
1587
|
+
if (!target) {
|
|
1588
|
+
return;
|
|
1589
|
+
}
|
|
1590
|
+
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
|
|
1591
|
+
this.checkTextChange(target, target.value.length);
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
handleMutations(mutations) {
|
|
1595
|
+
for (const mutation of mutations) {
|
|
1596
|
+
if (mutation.type === "characterData" && mutation.target.parentElement) {
|
|
1597
|
+
const parent = mutation.target.parentElement;
|
|
1598
|
+
if (parent.isContentEditable) {
|
|
1599
|
+
const newLength = parent.textContent?.length ?? 0;
|
|
1600
|
+
this.checkTextChange(parent, newLength);
|
|
1601
|
+
}
|
|
1602
|
+
} else if (mutation.type === "childList") {
|
|
1603
|
+
const target = mutation.target;
|
|
1604
|
+
if (target instanceof HTMLElement && target.isContentEditable) {
|
|
1605
|
+
const newLength = target.textContent?.length ?? 0;
|
|
1606
|
+
this.checkTextChange(target, newLength);
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
checkTextChange(element, newLength) {
|
|
1612
|
+
const previousLength = this.lastTextLength.get(element) ?? 0;
|
|
1613
|
+
const lengthChange = newLength - previousLength;
|
|
1614
|
+
this.lastTextLength.set(element, newLength);
|
|
1615
|
+
if (lengthChange < this.config.minTextLength) {
|
|
1616
|
+
return;
|
|
1617
|
+
}
|
|
1618
|
+
const recentKeystrokes = this.keystrokeCallback?.() ?? 0;
|
|
1619
|
+
const hadPaste = this.pasteCallback?.() ?? false;
|
|
1620
|
+
if (recentKeystrokes < lengthChange && !hadPaste) {
|
|
1621
|
+
const time = performance.now() - this.startTime;
|
|
1622
|
+
const selector = this.getSelector(element);
|
|
1623
|
+
this.indicators.push({
|
|
1624
|
+
type: "sudden_text_appearance",
|
|
1625
|
+
selector,
|
|
1626
|
+
details: {
|
|
1627
|
+
characterCount: lengthChange,
|
|
1628
|
+
previousLength,
|
|
1629
|
+
newLength,
|
|
1630
|
+
recentKeystrokes,
|
|
1631
|
+
hadPaste,
|
|
1632
|
+
time
|
|
1633
|
+
}
|
|
1634
|
+
});
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
getSelector(element) {
|
|
1638
|
+
if (element.id) {
|
|
1639
|
+
return `#${element.id}`;
|
|
1640
|
+
}
|
|
1641
|
+
if (element.className && typeof element.className === "string") {
|
|
1642
|
+
const classes = element.className.trim().split(/\s+/).join(".");
|
|
1643
|
+
if (classes) {
|
|
1644
|
+
return `${element.tagName.toLowerCase()}.${classes}`;
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
return element.tagName.toLowerCase();
|
|
1648
|
+
}
|
|
1649
|
+
calculateConfidence() {
|
|
1650
|
+
if (this.indicators.length === 0) {
|
|
1651
|
+
return 0;
|
|
1652
|
+
}
|
|
1653
|
+
const totalCharacters = this.indicators.reduce((sum, ind) => {
|
|
1654
|
+
const count = ind.details?.["characterCount"] ?? 0;
|
|
1655
|
+
return sum + count;
|
|
1656
|
+
}, 0);
|
|
1657
|
+
let confidence = 0.5;
|
|
1658
|
+
if (totalCharacters > 100) {
|
|
1659
|
+
confidence += 0.2;
|
|
1660
|
+
}
|
|
1661
|
+
if (totalCharacters > 500) {
|
|
1662
|
+
confidence += 0.2;
|
|
1663
|
+
}
|
|
1664
|
+
confidence += Math.min(0.1 * this.indicators.length, 0.1);
|
|
1665
|
+
return Math.min(confidence, 1);
|
|
1666
|
+
}
|
|
1667
|
+
};
|
|
1668
|
+
|
|
1669
|
+
// src/detection/extension.ts
|
|
1670
|
+
var KNOWN_DOM_SELECTORS = [
|
|
1671
|
+
"[data-grammarly-shadow-root]",
|
|
1672
|
+
'[class*="grammarly"]',
|
|
1673
|
+
'[class*="ai-assistant"]',
|
|
1674
|
+
'[class*="copilot"]',
|
|
1675
|
+
'[class*="chatgpt"]',
|
|
1676
|
+
"#quillbot-extension-portal"
|
|
1677
|
+
];
|
|
1678
|
+
var KNOWN_GLOBALS = ["__GRAMMARLY__", "__COPILOT__", "__QUILLBOT__"];
|
|
1679
|
+
var ExtensionDetector = class {
|
|
1680
|
+
name = "extension-detector";
|
|
1681
|
+
config;
|
|
1682
|
+
allSelectors;
|
|
1683
|
+
allGlobals;
|
|
1684
|
+
observer = null;
|
|
1685
|
+
monitoredIndicators = [];
|
|
1686
|
+
constructor(config = {}) {
|
|
1687
|
+
this.config = {
|
|
1688
|
+
customSelectors: config.customSelectors ?? [],
|
|
1689
|
+
customGlobals: config.customGlobals ?? [],
|
|
1690
|
+
monitor: {
|
|
1691
|
+
attributes: config.monitor?.attributes ?? true,
|
|
1692
|
+
childList: config.monitor?.childList ?? true,
|
|
1693
|
+
subtree: config.monitor?.subtree ?? true
|
|
1694
|
+
}
|
|
1695
|
+
};
|
|
1696
|
+
this.allSelectors = [...KNOWN_DOM_SELECTORS, ...this.config.customSelectors];
|
|
1697
|
+
this.allGlobals = [...KNOWN_GLOBALS, ...this.config.customGlobals];
|
|
1698
|
+
}
|
|
1699
|
+
/**
|
|
1700
|
+
* Performs a one-shot detection scan for extension signatures.
|
|
1701
|
+
*
|
|
1702
|
+
* @returns Detection result with found indicators
|
|
1703
|
+
*/
|
|
1704
|
+
detect() {
|
|
1705
|
+
const startTime = performance.now();
|
|
1706
|
+
const indicators = [];
|
|
1707
|
+
for (const selector of this.allSelectors) {
|
|
1708
|
+
const elements = this.queryElements(selector);
|
|
1709
|
+
if (elements.length > 0) {
|
|
1710
|
+
indicators.push({
|
|
1711
|
+
type: "dom_element",
|
|
1712
|
+
selector,
|
|
1713
|
+
details: {
|
|
1714
|
+
matchCount: elements.length,
|
|
1715
|
+
isKnown: KNOWN_DOM_SELECTORS.includes(selector)
|
|
1716
|
+
}
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
for (const globalName of this.allGlobals) {
|
|
1721
|
+
if (this.hasGlobal(globalName)) {
|
|
1722
|
+
indicators.push({
|
|
1723
|
+
type: "global_variable",
|
|
1724
|
+
selector: globalName,
|
|
1725
|
+
details: {
|
|
1726
|
+
isKnown: KNOWN_GLOBALS.includes(globalName)
|
|
1727
|
+
}
|
|
1728
|
+
});
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
performance.now() - startTime;
|
|
1732
|
+
return {
|
|
1733
|
+
detected: indicators.length > 0,
|
|
1734
|
+
confidence: this.calculateConfidence(indicators),
|
|
1735
|
+
message: this.generateMessage(indicators),
|
|
1736
|
+
indicators
|
|
1737
|
+
};
|
|
1738
|
+
}
|
|
1739
|
+
/**
|
|
1740
|
+
* Starts continuous monitoring for dynamically injected extension elements.
|
|
1741
|
+
*
|
|
1742
|
+
* Uses MutationObserver to watch for DOM changes that match extension patterns.
|
|
1743
|
+
*/
|
|
1744
|
+
startMonitoring() {
|
|
1745
|
+
if (this.observer !== null) {
|
|
1746
|
+
return;
|
|
1747
|
+
}
|
|
1748
|
+
this.observer = new MutationObserver((mutations) => {
|
|
1749
|
+
this.handleMutations(mutations);
|
|
1750
|
+
});
|
|
1751
|
+
this.observer.observe(document.documentElement, {
|
|
1752
|
+
attributes: this.config.monitor.attributes,
|
|
1753
|
+
childList: this.config.monitor.childList,
|
|
1754
|
+
subtree: this.config.monitor.subtree,
|
|
1755
|
+
attributeFilter: ["class", "data-grammarly-shadow-root"]
|
|
1756
|
+
});
|
|
1757
|
+
}
|
|
1758
|
+
/**
|
|
1759
|
+
* Stops continuous monitoring and disconnects the MutationObserver.
|
|
1760
|
+
*/
|
|
1761
|
+
stopMonitoring() {
|
|
1762
|
+
if (this.observer !== null) {
|
|
1763
|
+
this.observer.disconnect();
|
|
1764
|
+
this.observer = null;
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
/**
|
|
1768
|
+
* Gets all indicators detected during monitoring.
|
|
1769
|
+
*
|
|
1770
|
+
* @returns Array of detection indicators found during monitoring
|
|
1771
|
+
*/
|
|
1772
|
+
getMonitoredIndicators() {
|
|
1773
|
+
return [...this.monitoredIndicators];
|
|
1774
|
+
}
|
|
1775
|
+
/**
|
|
1776
|
+
* Resets all collected monitoring data.
|
|
1777
|
+
*/
|
|
1778
|
+
reset() {
|
|
1779
|
+
this.monitoredIndicators = [];
|
|
1780
|
+
}
|
|
1781
|
+
/**
|
|
1782
|
+
* Queries the DOM for elements matching a selector.
|
|
1783
|
+
*/
|
|
1784
|
+
queryElements(selector) {
|
|
1785
|
+
try {
|
|
1786
|
+
return Array.from(document.querySelectorAll(selector));
|
|
1787
|
+
} catch {
|
|
1788
|
+
return [];
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
/**
|
|
1792
|
+
* Checks if a global variable exists on the window object.
|
|
1793
|
+
*/
|
|
1794
|
+
hasGlobal(name) {
|
|
1795
|
+
try {
|
|
1796
|
+
return name in window;
|
|
1797
|
+
} catch {
|
|
1798
|
+
return false;
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
/**
|
|
1802
|
+
* Handles mutation events from the MutationObserver.
|
|
1803
|
+
*/
|
|
1804
|
+
handleMutations(mutations) {
|
|
1805
|
+
for (const mutation of mutations) {
|
|
1806
|
+
if (mutation.type === "childList") {
|
|
1807
|
+
this.handleChildListMutation(mutation);
|
|
1808
|
+
} else if (mutation.type === "attributes") {
|
|
1809
|
+
this.handleAttributeMutation(mutation);
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
/**
|
|
1814
|
+
* Handles child list mutations, checking new nodes for extension patterns.
|
|
1815
|
+
*/
|
|
1816
|
+
handleChildListMutation(mutation) {
|
|
1817
|
+
for (const node of mutation.addedNodes) {
|
|
1818
|
+
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
1819
|
+
continue;
|
|
1820
|
+
}
|
|
1821
|
+
const element = node;
|
|
1822
|
+
for (const selector of this.allSelectors) {
|
|
1823
|
+
if (this.elementMatchesSelector(element, selector)) {
|
|
1824
|
+
this.addMonitoredIndicator("dom_element", selector, {
|
|
1825
|
+
trigger: "added_node",
|
|
1826
|
+
tagName: element.tagName.toLowerCase()
|
|
1827
|
+
});
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
for (const selector of this.allSelectors) {
|
|
1831
|
+
const matches = this.querySelectorSafe(element, selector);
|
|
1832
|
+
if (matches.length > 0) {
|
|
1833
|
+
this.addMonitoredIndicator("dom_element", selector, {
|
|
1834
|
+
trigger: "added_descendant",
|
|
1835
|
+
matchCount: matches.length
|
|
1836
|
+
});
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
/**
|
|
1842
|
+
* Handles attribute mutations, checking if changes match extension patterns.
|
|
1843
|
+
*/
|
|
1844
|
+
handleAttributeMutation(mutation) {
|
|
1845
|
+
const element = mutation.target;
|
|
1846
|
+
for (const selector of this.allSelectors) {
|
|
1847
|
+
if (this.elementMatchesSelector(element, selector)) {
|
|
1848
|
+
this.addMonitoredIndicator("dom_element", selector, {
|
|
1849
|
+
trigger: "attribute_change",
|
|
1850
|
+
attribute: mutation.attributeName,
|
|
1851
|
+
tagName: element.tagName.toLowerCase()
|
|
1852
|
+
});
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
/**
|
|
1857
|
+
* Safely checks if an element matches a selector.
|
|
1858
|
+
*/
|
|
1859
|
+
elementMatchesSelector(element, selector) {
|
|
1860
|
+
try {
|
|
1861
|
+
return element.matches(selector);
|
|
1862
|
+
} catch {
|
|
1863
|
+
return false;
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Safely queries for elements within a parent.
|
|
1868
|
+
*/
|
|
1869
|
+
querySelectorSafe(parent, selector) {
|
|
1870
|
+
try {
|
|
1871
|
+
return Array.from(parent.querySelectorAll(selector));
|
|
1872
|
+
} catch {
|
|
1873
|
+
return [];
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
/**
|
|
1877
|
+
* Adds an indicator to the monitored indicators list.
|
|
1878
|
+
*/
|
|
1879
|
+
addMonitoredIndicator(type, selector, details) {
|
|
1880
|
+
const indicator = {
|
|
1881
|
+
type,
|
|
1882
|
+
selector,
|
|
1883
|
+
details: {
|
|
1884
|
+
...details,
|
|
1885
|
+
timestamp: performance.now(),
|
|
1886
|
+
isKnown: type === "dom_element" ? KNOWN_DOM_SELECTORS.includes(selector) : KNOWN_GLOBALS.includes(selector)
|
|
1887
|
+
}
|
|
1888
|
+
};
|
|
1889
|
+
this.monitoredIndicators.push(indicator);
|
|
1890
|
+
}
|
|
1891
|
+
/**
|
|
1892
|
+
* Calculates a confidence score based on indicators.
|
|
1893
|
+
*/
|
|
1894
|
+
calculateConfidence(indicators) {
|
|
1895
|
+
if (indicators.length === 0) {
|
|
1896
|
+
return 0;
|
|
1897
|
+
}
|
|
1898
|
+
const knownCount = indicators.filter((i) => i.details?.["isKnown"] === true).length;
|
|
1899
|
+
const unknownCount = indicators.length - knownCount;
|
|
1900
|
+
const score = Math.min(1, knownCount * 0.3 + unknownCount * 0.15);
|
|
1901
|
+
return Math.round(score * 100) / 100;
|
|
1902
|
+
}
|
|
1903
|
+
/**
|
|
1904
|
+
* Generates a human-readable message from indicators.
|
|
1905
|
+
*/
|
|
1906
|
+
generateMessage(indicators) {
|
|
1907
|
+
if (indicators.length === 0) {
|
|
1908
|
+
return "No AI assistant browser extensions detected";
|
|
1909
|
+
}
|
|
1910
|
+
const domCount = indicators.filter((i) => i.type === "dom_element").length;
|
|
1911
|
+
const globalCount = indicators.filter((i) => i.type === "global_variable").length;
|
|
1912
|
+
const parts = [];
|
|
1913
|
+
if (domCount > 0) {
|
|
1914
|
+
parts.push(`${domCount} DOM element${domCount > 1 ? "s" : ""}`);
|
|
1915
|
+
}
|
|
1916
|
+
if (globalCount > 0) {
|
|
1917
|
+
parts.push(`${globalCount} global variable${globalCount > 1 ? "s" : ""}`);
|
|
1918
|
+
}
|
|
1919
|
+
return `AI assistant extension signatures detected: ${parts.join(", ")}`;
|
|
1920
|
+
}
|
|
1921
|
+
};
|
|
1922
|
+
function createExtensionDetector(config) {
|
|
1923
|
+
return new ExtensionDetector(config);
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
// src/intervention/intervention-manager.ts
|
|
1927
|
+
var INTERVENTION_LEVELS = ["warning", "friction", "challenge", "block"];
|
|
1928
|
+
var InterventionManager = class {
|
|
1929
|
+
triggers;
|
|
1930
|
+
escalate;
|
|
1931
|
+
interventionHistory = [];
|
|
1932
|
+
callbacks = /* @__PURE__ */ new Map();
|
|
1933
|
+
triggerCounts = /* @__PURE__ */ new Map();
|
|
1934
|
+
/**
|
|
1935
|
+
* Creates a new InterventionManager.
|
|
1936
|
+
*
|
|
1937
|
+
* @param config - Configuration with triggers and escalation settings
|
|
1938
|
+
*/
|
|
1939
|
+
constructor(config) {
|
|
1940
|
+
this.triggers = config.triggers;
|
|
1941
|
+
this.escalate = config.escalate ?? false;
|
|
1942
|
+
for (const type of INTERVENTION_LEVELS) {
|
|
1943
|
+
this.callbacks.set(type, []);
|
|
1944
|
+
}
|
|
1945
|
+
for (const trigger of this.triggers) {
|
|
1946
|
+
this.triggerCounts.set(trigger, 0);
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
/**
|
|
1950
|
+
* Evaluates triggers against the current behavioral state.
|
|
1951
|
+
*
|
|
1952
|
+
* Checks each configured trigger against the provided state and returns
|
|
1953
|
+
* an InterventionResult if any trigger fires. Only the first matching
|
|
1954
|
+
* trigger is returned.
|
|
1955
|
+
*
|
|
1956
|
+
* @param state - Current behavioral state to evaluate
|
|
1957
|
+
* @returns InterventionResult if a trigger fires, null otherwise
|
|
1958
|
+
*
|
|
1959
|
+
* @example
|
|
1960
|
+
* ```typescript
|
|
1961
|
+
* const result = manager.evaluate({
|
|
1962
|
+
* pasteEvents: [{ textLength: 500, precedingKeystrokes: 2 }],
|
|
1963
|
+
* blurCount: 5,
|
|
1964
|
+
* totalBlurDuration: 15000,
|
|
1965
|
+
* });
|
|
1966
|
+
* ```
|
|
1967
|
+
*/
|
|
1968
|
+
evaluate(state) {
|
|
1969
|
+
for (const trigger of this.triggers) {
|
|
1970
|
+
const result = this.evaluateTrigger(trigger, state);
|
|
1971
|
+
if (result !== null) {
|
|
1972
|
+
const currentCount = this.triggerCounts.get(trigger) ?? 0;
|
|
1973
|
+
this.triggerCounts.set(trigger, currentCount + 1);
|
|
1974
|
+
const finalResult = this.escalate ? this.applyEscalation(result, trigger) : result;
|
|
1975
|
+
this.interventionHistory.push(finalResult);
|
|
1976
|
+
this.fireCallbacks(finalResult);
|
|
1977
|
+
return finalResult;
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
return null;
|
|
1981
|
+
}
|
|
1982
|
+
/**
|
|
1983
|
+
* Registers a callback for a specific intervention type.
|
|
1984
|
+
*
|
|
1985
|
+
* Callbacks are invoked whenever an intervention of the specified type
|
|
1986
|
+
* is triggered during evaluation.
|
|
1987
|
+
*
|
|
1988
|
+
* @param type - The intervention type to listen for
|
|
1989
|
+
* @param callback - Function to call when the intervention fires
|
|
1990
|
+
*
|
|
1991
|
+
* @example
|
|
1992
|
+
* ```typescript
|
|
1993
|
+
* manager.onIntervention("warning", (result) => {
|
|
1994
|
+
* alert(result.reason);
|
|
1995
|
+
* });
|
|
1996
|
+
*
|
|
1997
|
+
* manager.onIntervention("block", (result) => {
|
|
1998
|
+
* disableSubmitButton();
|
|
1999
|
+
* });
|
|
2000
|
+
* ```
|
|
2001
|
+
*/
|
|
2002
|
+
onIntervention(type, callback) {
|
|
2003
|
+
const callbacks = this.callbacks.get(type);
|
|
2004
|
+
if (callbacks !== void 0) {
|
|
2005
|
+
callbacks.push(callback);
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
/**
|
|
2009
|
+
* Returns the history of all triggered interventions.
|
|
2010
|
+
*
|
|
2011
|
+
* @returns Copy of the intervention history array
|
|
2012
|
+
*
|
|
2013
|
+
* @example
|
|
2014
|
+
* ```typescript
|
|
2015
|
+
* const history = manager.getHistory();
|
|
2016
|
+
* console.log(`Total interventions: ${history.length}`);
|
|
2017
|
+
* ```
|
|
2018
|
+
*/
|
|
2019
|
+
getHistory() {
|
|
2020
|
+
return [...this.interventionHistory];
|
|
2021
|
+
}
|
|
2022
|
+
/**
|
|
2023
|
+
* Resets the intervention history and trigger counts.
|
|
2024
|
+
*
|
|
2025
|
+
* Call this method to clear all recorded interventions and reset
|
|
2026
|
+
* escalation counters.
|
|
2027
|
+
*
|
|
2028
|
+
* @example
|
|
2029
|
+
* ```typescript
|
|
2030
|
+
* manager.reset();
|
|
2031
|
+
* // History is now empty and escalation counters are reset
|
|
2032
|
+
* ```
|
|
2033
|
+
*/
|
|
2034
|
+
reset() {
|
|
2035
|
+
this.interventionHistory = [];
|
|
2036
|
+
for (const trigger of this.triggers) {
|
|
2037
|
+
this.triggerCounts.set(trigger, 0);
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
/**
|
|
2041
|
+
* Evaluates a single trigger against the behavioral state.
|
|
2042
|
+
*/
|
|
2043
|
+
evaluateTrigger(trigger, state) {
|
|
2044
|
+
switch (trigger.type) {
|
|
2045
|
+
case "paste":
|
|
2046
|
+
return this.evaluatePasteTrigger(trigger, state);
|
|
2047
|
+
case "blur":
|
|
2048
|
+
return this.evaluateBlurTrigger(trigger, state);
|
|
2049
|
+
case "idle":
|
|
2050
|
+
return this.evaluateIdleTrigger(trigger, state);
|
|
2051
|
+
case "timing":
|
|
2052
|
+
return this.evaluateTimingTrigger(trigger, state);
|
|
2053
|
+
case "composite":
|
|
2054
|
+
return this.evaluateCompositeTrigger(trigger, state);
|
|
2055
|
+
default:
|
|
2056
|
+
return null;
|
|
2057
|
+
}
|
|
2058
|
+
}
|
|
2059
|
+
/**
|
|
2060
|
+
* Evaluates a paste-based trigger.
|
|
2061
|
+
*/
|
|
2062
|
+
evaluatePasteTrigger(trigger, state) {
|
|
2063
|
+
const threshold = trigger.threshold.paste;
|
|
2064
|
+
if (threshold === void 0 || state.pasteEvents === void 0) {
|
|
2065
|
+
return null;
|
|
2066
|
+
}
|
|
2067
|
+
for (const event of state.pasteEvents) {
|
|
2068
|
+
if (event.textLength >= threshold.minLength && event.precedingKeystrokes <= threshold.maxPrecedingKeystrokes) {
|
|
2069
|
+
return this.createResult(
|
|
2070
|
+
trigger,
|
|
2071
|
+
`Large paste detected (${event.textLength} characters) with minimal preceding keystrokes (${event.precedingKeystrokes})`
|
|
2072
|
+
);
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
return null;
|
|
2076
|
+
}
|
|
2077
|
+
/**
|
|
2078
|
+
* Evaluates a blur-based trigger.
|
|
2079
|
+
*/
|
|
2080
|
+
evaluateBlurTrigger(trigger, state) {
|
|
2081
|
+
const threshold = trigger.threshold.blur;
|
|
2082
|
+
if (threshold === void 0) {
|
|
2083
|
+
return null;
|
|
2084
|
+
}
|
|
2085
|
+
const blurCount = state.blurCount ?? 0;
|
|
2086
|
+
const totalBlurDuration = state.totalBlurDuration ?? 0;
|
|
2087
|
+
if (blurCount >= threshold.countThreshold || totalBlurDuration >= threshold.durationThreshold) {
|
|
2088
|
+
const reasons = [];
|
|
2089
|
+
if (blurCount >= threshold.countThreshold) {
|
|
2090
|
+
reasons.push(`blur count (${blurCount}) exceeded threshold (${threshold.countThreshold})`);
|
|
2091
|
+
}
|
|
2092
|
+
if (totalBlurDuration >= threshold.durationThreshold) {
|
|
2093
|
+
reasons.push(
|
|
2094
|
+
`blur duration (${totalBlurDuration}ms) exceeded threshold (${threshold.durationThreshold}ms)`
|
|
2095
|
+
);
|
|
2096
|
+
}
|
|
2097
|
+
return this.createResult(trigger, `Focus loss detected: ${reasons.join("; ")}`);
|
|
2098
|
+
}
|
|
2099
|
+
return null;
|
|
2100
|
+
}
|
|
2101
|
+
/**
|
|
2102
|
+
* Evaluates an idle-based trigger.
|
|
2103
|
+
*/
|
|
2104
|
+
evaluateIdleTrigger(trigger, state) {
|
|
2105
|
+
const threshold = trigger.threshold.idle;
|
|
2106
|
+
if (threshold === void 0 || state.idleDuration === void 0) {
|
|
2107
|
+
return null;
|
|
2108
|
+
}
|
|
2109
|
+
if (state.idleDuration >= threshold.durationMs) {
|
|
2110
|
+
return this.createResult(
|
|
2111
|
+
trigger,
|
|
2112
|
+
`Idle period detected (${state.idleDuration}ms) exceeded threshold (${threshold.durationMs}ms)`
|
|
2113
|
+
);
|
|
2114
|
+
}
|
|
2115
|
+
return null;
|
|
2116
|
+
}
|
|
2117
|
+
/**
|
|
2118
|
+
* Evaluates a timing-based trigger.
|
|
2119
|
+
*/
|
|
2120
|
+
evaluateTimingTrigger(trigger, state) {
|
|
2121
|
+
const threshold = trigger.threshold.timing;
|
|
2122
|
+
if (threshold === void 0 || state.charactersPerSecond === void 0) {
|
|
2123
|
+
return null;
|
|
2124
|
+
}
|
|
2125
|
+
if (state.charactersPerSecond > threshold.maxCharactersPerSecond) {
|
|
2126
|
+
return this.createResult(
|
|
2127
|
+
trigger,
|
|
2128
|
+
`Typing speed (${state.charactersPerSecond.toFixed(1)} chars/sec) exceeded threshold (${threshold.maxCharactersPerSecond} chars/sec)`
|
|
2129
|
+
);
|
|
2130
|
+
}
|
|
2131
|
+
return null;
|
|
2132
|
+
}
|
|
2133
|
+
/**
|
|
2134
|
+
* Evaluates a composite trigger (combination of multiple factors).
|
|
2135
|
+
*/
|
|
2136
|
+
evaluateCompositeTrigger(trigger, state) {
|
|
2137
|
+
const triggeredConditions = [];
|
|
2138
|
+
if (trigger.threshold.paste !== void 0 && state.pasteEvents !== void 0) {
|
|
2139
|
+
const threshold = trigger.threshold.paste;
|
|
2140
|
+
for (const event of state.pasteEvents) {
|
|
2141
|
+
if (event.textLength >= threshold.minLength && event.precedingKeystrokes <= threshold.maxPrecedingKeystrokes) {
|
|
2142
|
+
triggeredConditions.push("suspicious paste");
|
|
2143
|
+
break;
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
if (trigger.threshold.blur !== void 0) {
|
|
2148
|
+
const threshold = trigger.threshold.blur;
|
|
2149
|
+
const blurCount = state.blurCount ?? 0;
|
|
2150
|
+
const totalBlurDuration = state.totalBlurDuration ?? 0;
|
|
2151
|
+
if (blurCount >= threshold.countThreshold || totalBlurDuration >= threshold.durationThreshold) {
|
|
2152
|
+
triggeredConditions.push("excessive focus loss");
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
if (trigger.threshold.idle !== void 0 && state.idleDuration !== void 0) {
|
|
2156
|
+
if (state.idleDuration >= trigger.threshold.idle.durationMs) {
|
|
2157
|
+
triggeredConditions.push("extended idle period");
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
if (trigger.threshold.timing !== void 0 && state.charactersPerSecond !== void 0) {
|
|
2161
|
+
if (state.charactersPerSecond > trigger.threshold.timing.maxCharactersPerSecond) {
|
|
2162
|
+
triggeredConditions.push("abnormal typing speed");
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
if (triggeredConditions.length >= 2) {
|
|
2166
|
+
return this.createResult(
|
|
2167
|
+
trigger,
|
|
2168
|
+
`Multiple behavioral anomalies detected: ${triggeredConditions.join(", ")}`
|
|
2169
|
+
);
|
|
2170
|
+
}
|
|
2171
|
+
return null;
|
|
2172
|
+
}
|
|
2173
|
+
/**
|
|
2174
|
+
* Creates an InterventionResult from a trigger.
|
|
2175
|
+
*/
|
|
2176
|
+
createResult(trigger, reason) {
|
|
2177
|
+
return {
|
|
2178
|
+
type: trigger.intervention,
|
|
2179
|
+
triggered: true,
|
|
2180
|
+
reason,
|
|
2181
|
+
triggerConfig: trigger,
|
|
2182
|
+
timestamp: performance.now()
|
|
2183
|
+
};
|
|
2184
|
+
}
|
|
2185
|
+
/**
|
|
2186
|
+
* Applies escalation to an intervention result based on trigger count.
|
|
2187
|
+
*/
|
|
2188
|
+
applyEscalation(result, trigger) {
|
|
2189
|
+
const count = this.triggerCounts.get(trigger) ?? 0;
|
|
2190
|
+
const currentIndex = INTERVENTION_LEVELS.indexOf(result.type);
|
|
2191
|
+
if (currentIndex === -1) {
|
|
2192
|
+
return result;
|
|
2193
|
+
}
|
|
2194
|
+
const escalationSteps = Math.floor(count / 2);
|
|
2195
|
+
const newIndex = Math.min(currentIndex + escalationSteps, INTERVENTION_LEVELS.length - 1);
|
|
2196
|
+
if (newIndex === currentIndex) {
|
|
2197
|
+
return result;
|
|
2198
|
+
}
|
|
2199
|
+
const escalatedType = INTERVENTION_LEVELS[newIndex];
|
|
2200
|
+
if (escalatedType === void 0) {
|
|
2201
|
+
return result;
|
|
2202
|
+
}
|
|
2203
|
+
return {
|
|
2204
|
+
...result,
|
|
2205
|
+
type: escalatedType,
|
|
2206
|
+
reason: `${result.reason} (escalated from ${result.type} due to repeated triggers)`
|
|
2207
|
+
};
|
|
2208
|
+
}
|
|
2209
|
+
/**
|
|
2210
|
+
* Fires callbacks for an intervention result.
|
|
2211
|
+
*/
|
|
2212
|
+
fireCallbacks(result) {
|
|
2213
|
+
const callbacks = this.callbacks.get(result.type);
|
|
2214
|
+
if (callbacks !== void 0) {
|
|
2215
|
+
for (const callback of callbacks) {
|
|
2216
|
+
callback(result);
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
};
|
|
2221
|
+
function createInterventionManager(config) {
|
|
2222
|
+
return new InterventionManager(config);
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
// src/intervention/challenges.ts
|
|
2226
|
+
var TypingTestChallenge = class {
|
|
2227
|
+
container = null;
|
|
2228
|
+
startTime = 0;
|
|
2229
|
+
keystrokes = [];
|
|
2230
|
+
boundHandlers = { keydown: null, keyup: null };
|
|
2231
|
+
/**
|
|
2232
|
+
* Render the typing test challenge.
|
|
2233
|
+
*
|
|
2234
|
+
* @param config - Challenge configuration with `data.text` containing the text to type
|
|
2235
|
+
* @param container - Container element for the challenge UI
|
|
2236
|
+
* @returns Promise resolving to challenge result with typing accuracy and keystroke data
|
|
2237
|
+
*/
|
|
2238
|
+
async render(config, container) {
|
|
2239
|
+
this.container = container;
|
|
2240
|
+
this.keystrokes = [];
|
|
2241
|
+
const targetText = config.data?.["text"] ?? "";
|
|
2242
|
+
return new Promise((resolve) => {
|
|
2243
|
+
const wrapper = document.createElement("div");
|
|
2244
|
+
wrapper.className = "slopit-typing-challenge";
|
|
2245
|
+
const promptEl = document.createElement("p");
|
|
2246
|
+
promptEl.className = "slopit-challenge-prompt";
|
|
2247
|
+
promptEl.textContent = config.prompt;
|
|
2248
|
+
wrapper.appendChild(promptEl);
|
|
2249
|
+
const targetEl = document.createElement("div");
|
|
2250
|
+
targetEl.className = "slopit-typing-target";
|
|
2251
|
+
targetEl.textContent = targetText;
|
|
2252
|
+
wrapper.appendChild(targetEl);
|
|
2253
|
+
const inputEl = document.createElement("textarea");
|
|
2254
|
+
inputEl.className = "slopit-typing-input";
|
|
2255
|
+
inputEl.placeholder = "Type the text above...";
|
|
2256
|
+
inputEl.rows = 3;
|
|
2257
|
+
wrapper.appendChild(inputEl);
|
|
2258
|
+
const submitBtn = document.createElement("button");
|
|
2259
|
+
submitBtn.className = "slopit-challenge-submit";
|
|
2260
|
+
submitBtn.textContent = "Submit";
|
|
2261
|
+
submitBtn.type = "button";
|
|
2262
|
+
wrapper.appendChild(submitBtn);
|
|
2263
|
+
container.appendChild(wrapper);
|
|
2264
|
+
this.startTime = performance.now();
|
|
2265
|
+
this.boundHandlers.keydown = (e) => {
|
|
2266
|
+
this.keystrokes.push({
|
|
2267
|
+
key: e.key,
|
|
2268
|
+
time: performance.now() - this.startTime,
|
|
2269
|
+
event: "keydown"
|
|
2270
|
+
});
|
|
2271
|
+
};
|
|
2272
|
+
this.boundHandlers.keyup = (e) => {
|
|
2273
|
+
this.keystrokes.push({
|
|
2274
|
+
key: e.key,
|
|
2275
|
+
time: performance.now() - this.startTime,
|
|
2276
|
+
event: "keyup"
|
|
2277
|
+
});
|
|
2278
|
+
};
|
|
2279
|
+
inputEl.addEventListener("keydown", this.boundHandlers.keydown);
|
|
2280
|
+
inputEl.addEventListener("keyup", this.boundHandlers.keyup);
|
|
2281
|
+
const submit = () => {
|
|
2282
|
+
const completionTime = performance.now() - this.startTime;
|
|
2283
|
+
const response = inputEl.value;
|
|
2284
|
+
const accuracy = this.calculateAccuracy(targetText, response);
|
|
2285
|
+
const passed = accuracy >= 0.9;
|
|
2286
|
+
resolve({
|
|
2287
|
+
passed,
|
|
2288
|
+
response,
|
|
2289
|
+
completionTime,
|
|
2290
|
+
behavioralData: {
|
|
2291
|
+
keystrokes: [...this.keystrokes],
|
|
2292
|
+
targetText,
|
|
2293
|
+
accuracy
|
|
2294
|
+
}
|
|
2295
|
+
});
|
|
2296
|
+
};
|
|
2297
|
+
submitBtn.addEventListener("click", submit);
|
|
2298
|
+
if (config.timeLimit !== void 0) {
|
|
2299
|
+
setTimeout(() => {
|
|
2300
|
+
submit();
|
|
2301
|
+
}, config.timeLimit);
|
|
2302
|
+
}
|
|
2303
|
+
inputEl.focus();
|
|
2304
|
+
});
|
|
2305
|
+
}
|
|
2306
|
+
/**
|
|
2307
|
+
* Clean up challenge UI and event listeners.
|
|
2308
|
+
*/
|
|
2309
|
+
cleanup() {
|
|
2310
|
+
if (this.container) {
|
|
2311
|
+
const wrapper = this.container.querySelector(".slopit-typing-challenge");
|
|
2312
|
+
if (wrapper) {
|
|
2313
|
+
const input = wrapper.querySelector(".slopit-typing-input");
|
|
2314
|
+
if (input && this.boundHandlers.keydown) {
|
|
2315
|
+
input.removeEventListener("keydown", this.boundHandlers.keydown);
|
|
2316
|
+
}
|
|
2317
|
+
if (input && this.boundHandlers.keyup) {
|
|
2318
|
+
input.removeEventListener("keyup", this.boundHandlers.keyup);
|
|
2319
|
+
}
|
|
2320
|
+
wrapper.remove();
|
|
2321
|
+
}
|
|
2322
|
+
this.container = null;
|
|
2323
|
+
}
|
|
2324
|
+
this.boundHandlers = { keydown: null, keyup: null };
|
|
2325
|
+
this.keystrokes = [];
|
|
2326
|
+
}
|
|
2327
|
+
/**
|
|
2328
|
+
* Calculate typing accuracy as a ratio (0-1).
|
|
2329
|
+
* Uses a simple character-by-character comparison with length normalization.
|
|
2330
|
+
*/
|
|
2331
|
+
calculateAccuracy(target, actual) {
|
|
2332
|
+
if (target.length === 0) {
|
|
2333
|
+
return actual.length === 0 ? 1 : 0;
|
|
2334
|
+
}
|
|
2335
|
+
const maxLen = Math.max(target.length, actual.length);
|
|
2336
|
+
let matches = 0;
|
|
2337
|
+
for (let i = 0; i < Math.min(target.length, actual.length); i++) {
|
|
2338
|
+
if (target[i] === actual[i]) {
|
|
2339
|
+
matches++;
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
return matches / maxLen;
|
|
2343
|
+
}
|
|
2344
|
+
};
|
|
2345
|
+
var MemoryRecallChallenge = class {
|
|
2346
|
+
container = null;
|
|
2347
|
+
startTime = 0;
|
|
2348
|
+
keystrokes = [];
|
|
2349
|
+
boundHandlers = { keydown: null, keyup: null };
|
|
2350
|
+
/**
|
|
2351
|
+
* Render the memory recall challenge.
|
|
2352
|
+
*
|
|
2353
|
+
* @param config - Challenge configuration with optional `expectedKeywords`
|
|
2354
|
+
* @param container - Container element for the challenge UI
|
|
2355
|
+
* @returns Promise resolving to challenge result with keyword matching status
|
|
2356
|
+
*/
|
|
2357
|
+
async render(config, container) {
|
|
2358
|
+
this.container = container;
|
|
2359
|
+
this.keystrokes = [];
|
|
2360
|
+
return new Promise((resolve) => {
|
|
2361
|
+
const wrapper = document.createElement("div");
|
|
2362
|
+
wrapper.className = "slopit-memory-challenge";
|
|
2363
|
+
const promptEl = document.createElement("p");
|
|
2364
|
+
promptEl.className = "slopit-challenge-prompt";
|
|
2365
|
+
promptEl.textContent = config.prompt;
|
|
2366
|
+
wrapper.appendChild(promptEl);
|
|
2367
|
+
const inputEl = document.createElement("textarea");
|
|
2368
|
+
inputEl.className = "slopit-memory-input";
|
|
2369
|
+
inputEl.placeholder = "Type your answer...";
|
|
2370
|
+
inputEl.rows = 3;
|
|
2371
|
+
wrapper.appendChild(inputEl);
|
|
2372
|
+
const submitBtn = document.createElement("button");
|
|
2373
|
+
submitBtn.className = "slopit-challenge-submit";
|
|
2374
|
+
submitBtn.textContent = "Submit";
|
|
2375
|
+
submitBtn.type = "button";
|
|
2376
|
+
wrapper.appendChild(submitBtn);
|
|
2377
|
+
container.appendChild(wrapper);
|
|
2378
|
+
this.startTime = performance.now();
|
|
2379
|
+
this.boundHandlers.keydown = (e) => {
|
|
2380
|
+
this.keystrokes.push({
|
|
2381
|
+
key: e.key,
|
|
2382
|
+
time: performance.now() - this.startTime,
|
|
2383
|
+
event: "keydown"
|
|
2384
|
+
});
|
|
2385
|
+
};
|
|
2386
|
+
this.boundHandlers.keyup = (e) => {
|
|
2387
|
+
this.keystrokes.push({
|
|
2388
|
+
key: e.key,
|
|
2389
|
+
time: performance.now() - this.startTime,
|
|
2390
|
+
event: "keyup"
|
|
2391
|
+
});
|
|
2392
|
+
};
|
|
2393
|
+
inputEl.addEventListener("keydown", this.boundHandlers.keydown);
|
|
2394
|
+
inputEl.addEventListener("keyup", this.boundHandlers.keyup);
|
|
2395
|
+
const submit = () => {
|
|
2396
|
+
const completionTime = performance.now() - this.startTime;
|
|
2397
|
+
const response = inputEl.value;
|
|
2398
|
+
const passed = this.checkKeywords(response, config.expectedKeywords ?? []);
|
|
2399
|
+
resolve({
|
|
2400
|
+
passed,
|
|
2401
|
+
response,
|
|
2402
|
+
completionTime,
|
|
2403
|
+
behavioralData: {
|
|
2404
|
+
keystrokes: [...this.keystrokes],
|
|
2405
|
+
expectedKeywords: config.expectedKeywords,
|
|
2406
|
+
matchedKeywords: this.getMatchedKeywords(response, config.expectedKeywords ?? [])
|
|
2407
|
+
}
|
|
2408
|
+
});
|
|
2409
|
+
};
|
|
2410
|
+
submitBtn.addEventListener("click", submit);
|
|
2411
|
+
if (config.timeLimit !== void 0) {
|
|
2412
|
+
setTimeout(() => {
|
|
2413
|
+
submit();
|
|
2414
|
+
}, config.timeLimit);
|
|
2415
|
+
}
|
|
2416
|
+
inputEl.focus();
|
|
2417
|
+
});
|
|
2418
|
+
}
|
|
2419
|
+
/**
|
|
2420
|
+
* Clean up challenge UI and event listeners.
|
|
2421
|
+
*/
|
|
2422
|
+
cleanup() {
|
|
2423
|
+
if (this.container) {
|
|
2424
|
+
const wrapper = this.container.querySelector(".slopit-memory-challenge");
|
|
2425
|
+
if (wrapper) {
|
|
2426
|
+
const input = wrapper.querySelector(".slopit-memory-input");
|
|
2427
|
+
if (input && this.boundHandlers.keydown) {
|
|
2428
|
+
input.removeEventListener("keydown", this.boundHandlers.keydown);
|
|
2429
|
+
}
|
|
2430
|
+
if (input && this.boundHandlers.keyup) {
|
|
2431
|
+
input.removeEventListener("keyup", this.boundHandlers.keyup);
|
|
2432
|
+
}
|
|
2433
|
+
wrapper.remove();
|
|
2434
|
+
}
|
|
2435
|
+
this.container = null;
|
|
2436
|
+
}
|
|
2437
|
+
this.boundHandlers = { keydown: null, keyup: null };
|
|
2438
|
+
this.keystrokes = [];
|
|
2439
|
+
}
|
|
2440
|
+
/**
|
|
2441
|
+
* Check if response contains all expected keywords.
|
|
2442
|
+
*/
|
|
2443
|
+
checkKeywords(response, keywords) {
|
|
2444
|
+
if (keywords.length === 0) {
|
|
2445
|
+
return true;
|
|
2446
|
+
}
|
|
2447
|
+
const lowerResponse = response.toLowerCase();
|
|
2448
|
+
return keywords.every((keyword) => lowerResponse.includes(keyword.toLowerCase()));
|
|
2449
|
+
}
|
|
2450
|
+
/**
|
|
2451
|
+
* Get list of keywords that were matched in the response.
|
|
2452
|
+
*/
|
|
2453
|
+
getMatchedKeywords(response, keywords) {
|
|
2454
|
+
const lowerResponse = response.toLowerCase();
|
|
2455
|
+
return keywords.filter((keyword) => lowerResponse.includes(keyword.toLowerCase()));
|
|
2456
|
+
}
|
|
2457
|
+
};
|
|
2458
|
+
function createChallenge(type) {
|
|
2459
|
+
switch (type) {
|
|
2460
|
+
case "typing_test":
|
|
2461
|
+
return new TypingTestChallenge();
|
|
2462
|
+
case "memory_recall":
|
|
2463
|
+
return new MemoryRecallChallenge();
|
|
2464
|
+
case "audio_transcription":
|
|
2465
|
+
case "image_description":
|
|
2466
|
+
case "consistency_check":
|
|
2467
|
+
return null;
|
|
2468
|
+
default: {
|
|
2469
|
+
const _exhaustive = type;
|
|
2470
|
+
return _exhaustive;
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
|
|
2475
|
+
// src/wrappers/input-wrapper.ts
|
|
2476
|
+
var InputWrapper = class {
|
|
2477
|
+
element = null;
|
|
2478
|
+
capture;
|
|
2479
|
+
interventionManager;
|
|
2480
|
+
detectors = [];
|
|
2481
|
+
detectionInterval;
|
|
2482
|
+
detectionTimer;
|
|
2483
|
+
detectionResults = [];
|
|
2484
|
+
interventionResults = [];
|
|
2485
|
+
listeners = /* @__PURE__ */ new Map();
|
|
2486
|
+
isInterventionInProgress = false;
|
|
2487
|
+
/**
|
|
2488
|
+
* Creates a new InputWrapper instance.
|
|
2489
|
+
*
|
|
2490
|
+
* @param config - Configuration options for the wrapper
|
|
2491
|
+
*/
|
|
2492
|
+
constructor(config = {}) {
|
|
2493
|
+
this.capture = new BehavioralCapture(config.capture ?? {});
|
|
2494
|
+
if (config.interventionManager !== void 0) {
|
|
2495
|
+
this.interventionManager = config.interventionManager;
|
|
2496
|
+
}
|
|
2497
|
+
this.detectors = config.detectors ?? [];
|
|
2498
|
+
this.detectionInterval = config.detectionInterval ?? 5e3;
|
|
2499
|
+
}
|
|
2500
|
+
/**
|
|
2501
|
+
* Wraps an input element with behavioral capture.
|
|
2502
|
+
*
|
|
2503
|
+
* Attaches event listeners to the element and starts detection
|
|
2504
|
+
* if detectors are configured.
|
|
2505
|
+
*
|
|
2506
|
+
* @param element - The textarea or input element to wrap
|
|
2507
|
+
* @throws {Error} If the wrapper is already attached to an element
|
|
2508
|
+
*
|
|
2509
|
+
* @example
|
|
2510
|
+
* ```typescript
|
|
2511
|
+
* const wrapper = createInputWrapper();
|
|
2512
|
+
* const input = document.querySelector("textarea");
|
|
2513
|
+
* wrapper.wrap(input);
|
|
2514
|
+
* ```
|
|
2515
|
+
*/
|
|
2516
|
+
wrap(element) {
|
|
2517
|
+
if (this.element !== null) {
|
|
2518
|
+
throw new Error("InputWrapper already attached. Call unwrap() first.");
|
|
2519
|
+
}
|
|
2520
|
+
this.element = element;
|
|
2521
|
+
this.capture.attach(element);
|
|
2522
|
+
if (this.detectors.length > 0) {
|
|
2523
|
+
this.startDetection();
|
|
2524
|
+
}
|
|
2525
|
+
if (this.interventionManager !== void 0) {
|
|
2526
|
+
this.setupInterventionChecks();
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
/**
|
|
2530
|
+
* Unwraps the element and cleans up all resources.
|
|
2531
|
+
*
|
|
2532
|
+
* Stops detection, detaches capture, and clears all internal state.
|
|
2533
|
+
*
|
|
2534
|
+
* @example
|
|
2535
|
+
* ```typescript
|
|
2536
|
+
* wrapper.unwrap();
|
|
2537
|
+
* // Can now wrap a different element
|
|
2538
|
+
* wrapper.wrap(anotherElement);
|
|
2539
|
+
* ```
|
|
2540
|
+
*/
|
|
2541
|
+
unwrap() {
|
|
2542
|
+
this.stopDetection();
|
|
2543
|
+
this.capture.detach();
|
|
2544
|
+
this.element = null;
|
|
2545
|
+
}
|
|
2546
|
+
/**
|
|
2547
|
+
* Resets all collected data without unwrapping.
|
|
2548
|
+
*
|
|
2549
|
+
* Clears captured data, detection results, and intervention results
|
|
2550
|
+
* while maintaining the element attachment.
|
|
2551
|
+
*
|
|
2552
|
+
* @param newStartTime - Optional new start time for capture timing
|
|
2553
|
+
*/
|
|
2554
|
+
reset(newStartTime) {
|
|
2555
|
+
this.capture.reset(newStartTime);
|
|
2556
|
+
this.detectionResults = [];
|
|
2557
|
+
this.interventionResults = [];
|
|
2558
|
+
if (this.interventionManager !== void 0) {
|
|
2559
|
+
this.interventionManager.reset();
|
|
2560
|
+
}
|
|
2561
|
+
}
|
|
2562
|
+
/**
|
|
2563
|
+
* Gets all captured data including flags, detection results, and interventions.
|
|
2564
|
+
*
|
|
2565
|
+
* @returns Enhanced behavioral data with all capture information
|
|
2566
|
+
*
|
|
2567
|
+
* @example
|
|
2568
|
+
* ```typescript
|
|
2569
|
+
* const data = wrapper.getData();
|
|
2570
|
+
* console.log("Keystrokes:", data.keystrokes?.length);
|
|
2571
|
+
* console.log("Flags:", data.flags.length);
|
|
2572
|
+
* console.log("Detections:", data.detectionResults.length);
|
|
2573
|
+
* ```
|
|
2574
|
+
*/
|
|
2575
|
+
getData() {
|
|
2576
|
+
return {
|
|
2577
|
+
...this.capture.getData(),
|
|
2578
|
+
flags: this.capture.getFlags(),
|
|
2579
|
+
detectionResults: [...this.detectionResults],
|
|
2580
|
+
interventions: [...this.interventionResults]
|
|
2581
|
+
};
|
|
2582
|
+
}
|
|
2583
|
+
/**
|
|
2584
|
+
* Gets flags generated during capture.
|
|
2585
|
+
*
|
|
2586
|
+
* @returns Array of capture flags
|
|
2587
|
+
*/
|
|
2588
|
+
getFlags() {
|
|
2589
|
+
return this.capture.getFlags();
|
|
2590
|
+
}
|
|
2591
|
+
/**
|
|
2592
|
+
* Gets all detection results from detector runs.
|
|
2593
|
+
*
|
|
2594
|
+
* @returns Array of detection results
|
|
2595
|
+
*/
|
|
2596
|
+
getDetectionResults() {
|
|
2597
|
+
return [...this.detectionResults];
|
|
2598
|
+
}
|
|
2599
|
+
/**
|
|
2600
|
+
* Gets all intervention results.
|
|
2601
|
+
*
|
|
2602
|
+
* @returns Array of intervention results
|
|
2603
|
+
*/
|
|
2604
|
+
getInterventionResults() {
|
|
2605
|
+
return [...this.interventionResults];
|
|
2606
|
+
}
|
|
2607
|
+
/**
|
|
2608
|
+
* Manually triggers all detectors immediately.
|
|
2609
|
+
*
|
|
2610
|
+
* Useful for running detection on demand rather than waiting
|
|
2611
|
+
* for the next scheduled interval.
|
|
2612
|
+
*
|
|
2613
|
+
* @returns Array of detection results from this run
|
|
2614
|
+
*/
|
|
2615
|
+
runDetection() {
|
|
2616
|
+
const results = [];
|
|
2617
|
+
for (const detector of this.detectors) {
|
|
2618
|
+
const result = detector.detect();
|
|
2619
|
+
results.push(result);
|
|
2620
|
+
this.detectionResults.push(result);
|
|
2621
|
+
this.emit("detection", result);
|
|
2622
|
+
}
|
|
2623
|
+
return results;
|
|
2624
|
+
}
|
|
2625
|
+
/**
|
|
2626
|
+
* Subscribes to wrapper events.
|
|
2627
|
+
*
|
|
2628
|
+
* @param event - The event type to subscribe to
|
|
2629
|
+
* @param handler - The callback function to invoke
|
|
2630
|
+
*
|
|
2631
|
+
* @example
|
|
2632
|
+
* ```typescript
|
|
2633
|
+
* wrapper.on("flag", (flag) => {
|
|
2634
|
+
* console.log("Flag generated:", flag.type);
|
|
2635
|
+
* });
|
|
2636
|
+
*
|
|
2637
|
+
* wrapper.on("detection", (result) => {
|
|
2638
|
+
* if (result.detected) {
|
|
2639
|
+
* console.log("Detected:", result.message);
|
|
2640
|
+
* }
|
|
2641
|
+
* });
|
|
2642
|
+
* ```
|
|
2643
|
+
*/
|
|
2644
|
+
on(event, handler) {
|
|
2645
|
+
if (!this.listeners.has(event)) {
|
|
2646
|
+
this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
2647
|
+
}
|
|
2648
|
+
this.listeners.get(event)?.add(handler);
|
|
2649
|
+
}
|
|
2650
|
+
/**
|
|
2651
|
+
* Unsubscribes from wrapper events.
|
|
2652
|
+
*
|
|
2653
|
+
* @param event - The event type to unsubscribe from
|
|
2654
|
+
* @param handler - The callback function to remove
|
|
2655
|
+
*/
|
|
2656
|
+
off(event, handler) {
|
|
2657
|
+
this.listeners.get(event)?.delete(handler);
|
|
2658
|
+
}
|
|
2659
|
+
/**
|
|
2660
|
+
* Starts the detection timer for periodic detector runs.
|
|
2661
|
+
*/
|
|
2662
|
+
startDetection() {
|
|
2663
|
+
if (this.detectionTimer !== void 0) {
|
|
2664
|
+
return;
|
|
2665
|
+
}
|
|
2666
|
+
for (const detector of this.detectors) {
|
|
2667
|
+
if (detector.startMonitoring !== void 0 && this.element !== null) {
|
|
2668
|
+
detector.startMonitoring(this.element);
|
|
2669
|
+
}
|
|
2670
|
+
}
|
|
2671
|
+
this.detectionTimer = setInterval(() => {
|
|
2672
|
+
this.runDetection();
|
|
2673
|
+
}, this.detectionInterval);
|
|
2674
|
+
}
|
|
2675
|
+
/**
|
|
2676
|
+
* Stops the detection timer and monitoring.
|
|
2677
|
+
*/
|
|
2678
|
+
stopDetection() {
|
|
2679
|
+
if (this.detectionTimer !== void 0) {
|
|
2680
|
+
clearInterval(this.detectionTimer);
|
|
2681
|
+
delete this.detectionTimer;
|
|
2682
|
+
}
|
|
2683
|
+
for (const detector of this.detectors) {
|
|
2684
|
+
if (detector.stopMonitoring !== void 0) {
|
|
2685
|
+
detector.stopMonitoring();
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
}
|
|
2689
|
+
/**
|
|
2690
|
+
* Sets up intervention checks on behavioral capture events.
|
|
2691
|
+
*/
|
|
2692
|
+
setupInterventionChecks() {
|
|
2693
|
+
if (this.interventionManager === void 0) {
|
|
2694
|
+
return;
|
|
2695
|
+
}
|
|
2696
|
+
this.capture.on("keystroke", () => {
|
|
2697
|
+
void this.checkIntervention();
|
|
2698
|
+
});
|
|
2699
|
+
this.capture.on("paste", () => {
|
|
2700
|
+
void this.checkIntervention();
|
|
2701
|
+
});
|
|
2702
|
+
this.capture.on("focus", () => {
|
|
2703
|
+
void this.checkIntervention();
|
|
2704
|
+
});
|
|
2705
|
+
}
|
|
2706
|
+
/**
|
|
2707
|
+
* Checks if an intervention should be triggered and executes it.
|
|
2708
|
+
*/
|
|
2709
|
+
async checkIntervention() {
|
|
2710
|
+
if (this.interventionManager === void 0 || this.isInterventionInProgress) {
|
|
2711
|
+
return;
|
|
2712
|
+
}
|
|
2713
|
+
const data = this.capture.getData();
|
|
2714
|
+
const flags = this.capture.getFlags();
|
|
2715
|
+
if (this.interventionManager.shouldIntervene(data, flags)) {
|
|
2716
|
+
this.isInterventionInProgress = true;
|
|
2717
|
+
try {
|
|
2718
|
+
const result = await this.interventionManager.intervene(data, flags);
|
|
2719
|
+
this.interventionResults.push(result);
|
|
2720
|
+
this.emit("intervention", result);
|
|
2721
|
+
} finally {
|
|
2722
|
+
this.isInterventionInProgress = false;
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
/**
|
|
2727
|
+
* Emits an event to all subscribed handlers.
|
|
2728
|
+
*
|
|
2729
|
+
* @param event - The event type
|
|
2730
|
+
* @param data - The event data
|
|
2731
|
+
*/
|
|
2732
|
+
emit(event, data) {
|
|
2733
|
+
const handlers = this.listeners.get(event);
|
|
2734
|
+
if (handlers === void 0) {
|
|
2735
|
+
return;
|
|
2736
|
+
}
|
|
2737
|
+
for (const handler of handlers) {
|
|
2738
|
+
handler(data);
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
};
|
|
2742
|
+
function createInputWrapper(config) {
|
|
2743
|
+
return new InputWrapper(config);
|
|
2744
|
+
}
|
|
2745
|
+
|
|
2746
|
+
export { BehavioralCapture, ClipboardCollector, ExtensionDetector, FocusCollector, InputWrapper, InterventionManager, KeystrokeCollector, MemoryRecallChallenge, PasteCollector, TextAppearanceDetector, TypingTestChallenge, computeFocusMetrics, computeKeystrokeMetrics, computeTimingMetrics, createBehavioralCapture, createChallenge, createExtensionDetector, createInputWrapper, createInterventionManager };
|
|
2747
|
+
//# sourceMappingURL=index.js.map
|
|
2748
|
+
//# sourceMappingURL=index.js.map
|