@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/README.md ADDED
@@ -0,0 +1,947 @@
1
+ # @slopit/behavioral
2
+
3
+ Client-side behavioral data capture for detecting AI-assisted responses in crowdsourced research.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @slopit/behavioral
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { createBehavioralCapture } from "@slopit/behavioral";
15
+
16
+ // create capture instance with default configuration
17
+ const capture = createBehavioralCapture({
18
+ keystroke: { enabled: true },
19
+ focus: { enabled: true },
20
+ paste: { enabled: true },
21
+ });
22
+
23
+ // attach to a text input element
24
+ const textarea = document.getElementById("response") as HTMLTextAreaElement;
25
+ capture.attach(textarea);
26
+
27
+ // later, retrieve captured data and computed metrics
28
+ const data = capture.getData();
29
+ const flags = capture.getFlags();
30
+
31
+ // cleanup when done
32
+ capture.detach();
33
+ ```
34
+
35
+ ## API
36
+
37
+ ### BehavioralCapture
38
+
39
+ The main class for capturing behavioral data from DOM elements.
40
+
41
+ #### Constructor
42
+
43
+ ```typescript
44
+ new BehavioralCapture(config: BehavioralCaptureConfig)
45
+ ```
46
+
47
+ #### Methods
48
+
49
+ ##### attach(element: HTMLElement | Document, startTime?: number): void
50
+
51
+ Attaches behavioral capture to a DOM element. For text input capture, attach to the input or textarea element. For document-level focus tracking, attach to document.
52
+
53
+ ```typescript
54
+ capture.attach(textarea);
55
+ capture.attach(textarea, performance.now());
56
+ ```
57
+
58
+ ##### detach(): void
59
+
60
+ Detaches capture and cleans up all event listeners.
61
+
62
+ ```typescript
63
+ capture.detach();
64
+ ```
65
+
66
+ ##### reset(newStartTime?: number): void
67
+
68
+ Resets all collected data without detaching from the element.
69
+
70
+ ```typescript
71
+ capture.reset();
72
+ capture.reset(performance.now());
73
+ ```
74
+
75
+ ##### getData(): BehavioralData
76
+
77
+ Returns all collected behavioral data including keystrokes, focus events, paste events, mouse events, scroll events, and computed metrics.
78
+
79
+ ```typescript
80
+ const data = capture.getData();
81
+ console.log(data.keystrokes?.length);
82
+ console.log(data.metrics?.keystroke?.meanIKI);
83
+ ```
84
+
85
+ ##### getMetrics(): BehavioralMetrics
86
+
87
+ Returns computed metrics from the captured data.
88
+
89
+ ```typescript
90
+ const metrics = capture.getMetrics();
91
+ if (metrics.keystroke) {
92
+ console.log("Mean IKI:", metrics.keystroke.meanIKI);
93
+ console.log("Pause count:", metrics.keystroke.pauseCount);
94
+ }
95
+ ```
96
+
97
+ ##### getFlags(): CaptureFlag[]
98
+
99
+ Returns flags generated during capture (paste detection, excessive blur, etc.).
100
+
101
+ ```typescript
102
+ const flags = capture.getFlags();
103
+ for (const flag of flags) {
104
+ console.log(flag.type, flag.severity, flag.message);
105
+ }
106
+ ```
107
+
108
+ ##### on(event, handler): void
109
+
110
+ Subscribes to capture events for real-time monitoring.
111
+
112
+ ```typescript
113
+ capture.on("keystroke", (event) => {
114
+ console.log("Key pressed:", event.key);
115
+ });
116
+
117
+ capture.on("paste", (event) => {
118
+ console.log("Paste detected:", event.textLength, "characters");
119
+ });
120
+ ```
121
+
122
+ ##### off(event, handler): void
123
+
124
+ Unsubscribes from capture events.
125
+
126
+ ```typescript
127
+ capture.off("keystroke", myHandler);
128
+ ```
129
+
130
+ ## Configuration
131
+
132
+ ### BehavioralCaptureConfig
133
+
134
+ | Option | Type | Default | Description |
135
+ |--------|------|---------|-------------|
136
+ | keystroke | KeystrokeCaptureConfig | enabled | Keystroke capture settings |
137
+ | focus | FocusCaptureConfig | enabled | Focus/visibility tracking settings |
138
+ | paste | PasteCaptureConfig | enabled | Paste event capture settings |
139
+ | clipboard | ClipboardCaptureConfig | enabled | Full clipboard (paste, copy, cut) settings |
140
+ | mouse | MouseCaptureConfig | enabled | Mouse event capture settings |
141
+ | scroll | ScrollCaptureConfig | enabled | Scroll event capture settings |
142
+ | inputDuration | InputDurationCaptureConfig | enabled | Input focus duration tracking |
143
+
144
+ ### KeystrokeCaptureConfig
145
+
146
+ | Option | Type | Default | Description |
147
+ |--------|------|---------|-------------|
148
+ | enabled | boolean | true | Whether to capture keystrokes |
149
+ | captureKeyUp | boolean | true | Whether to capture keyup events in addition to keydown |
150
+ | includeModifiers | boolean | true | Whether to include modifier key states (shift, ctrl, alt, meta) |
151
+
152
+ ### FocusCaptureConfig
153
+
154
+ | Option | Type | Default | Description |
155
+ |--------|------|---------|-------------|
156
+ | enabled | boolean | true | Whether to capture focus events |
157
+ | useVisibilityAPI | boolean | true | Whether to use the Page Visibility API |
158
+ | useBlurFocus | boolean | true | Whether to use window blur/focus events |
159
+
160
+ ### PasteCaptureConfig
161
+
162
+ | Option | Type | Default | Description |
163
+ |--------|------|---------|-------------|
164
+ | enabled | boolean | true | Whether to capture paste events |
165
+ | prevent | boolean | false | Whether to prevent paste operations |
166
+ | warnMessage | string | undefined | Message to show when paste is prevented |
167
+ | capturePreview | boolean | true | Whether to capture a preview of pasted text |
168
+ | previewLength | number | 100 | Length of text preview to capture |
169
+
170
+ ### ClipboardCaptureConfig
171
+
172
+ | Option | Type | Default | Description |
173
+ |--------|------|---------|-------------|
174
+ | enabled | boolean | true | Whether clipboard capture is enabled |
175
+ | capturePaste | boolean | true | Whether to capture paste events |
176
+ | captureCopyCut | boolean | true | Whether to capture copy and cut events |
177
+ | prevent | boolean | false | Whether to prevent paste operations |
178
+ | warnMessage | string | undefined | Message to show when paste is prevented |
179
+ | capturePreview | boolean | true | Whether to capture a preview of clipboard text |
180
+ | previewLength | number | 100 | Length of text preview to capture |
181
+
182
+ ### MouseCaptureConfig
183
+
184
+ | Option | Type | Default | Description |
185
+ |--------|------|---------|-------------|
186
+ | enabled | boolean | true | Whether mouse capture is enabled |
187
+ | captureClicks | boolean | true | Whether to capture click events |
188
+ | captureMovement | boolean | true | Whether to capture mousemove events |
189
+ | throttleMs | number | 50 | Throttle interval for mousemove events |
190
+ | idleThresholdMs | number | 5000 | Threshold for detecting idle periods |
191
+
192
+ ### ScrollCaptureConfig
193
+
194
+ | Option | Type | Default | Description |
195
+ |--------|------|---------|-------------|
196
+ | enabled | boolean | true | Whether to capture scroll events |
197
+ | throttleMs | number | 100 | Throttle interval for scroll events |
198
+ | captureDirection | boolean | true | Whether to capture scroll direction changes |
199
+
200
+ ### InputDurationCaptureConfig
201
+
202
+ | Option | Type | Default | Description |
203
+ |--------|------|---------|-------------|
204
+ | enabled | boolean | true | Whether to capture input duration events |
205
+ | trackKeystrokes | boolean | true | Whether to count keystrokes during focus periods |
206
+ | trackPastes | boolean | true | Whether to count paste events during focus periods |
207
+
208
+ ## Individual Collectors
209
+
210
+ For advanced use cases, you can use the individual collectors directly.
211
+
212
+ ### KeystrokeCollector
213
+
214
+ ```typescript
215
+ import { KeystrokeCollector } from "@slopit/behavioral";
216
+
217
+ const collector = new KeystrokeCollector(
218
+ { enabled: true, captureKeyUp: true, includeModifiers: true },
219
+ performance.now(),
220
+ (event) => console.log("Keystroke:", event.key)
221
+ );
222
+
223
+ collector.attach(textarea);
224
+ // ... capture keystrokes
225
+ const events = collector.getEvents();
226
+ const firstKeystrokeTime = collector.getFirstKeystrokeTime();
227
+ collector.detach();
228
+ ```
229
+
230
+ ### FocusCollector
231
+
232
+ ```typescript
233
+ import { FocusCollector } from "@slopit/behavioral";
234
+
235
+ const collector = new FocusCollector(
236
+ { enabled: true, useVisibilityAPI: true, useBlurFocus: true },
237
+ performance.now(),
238
+ (event) => console.log("Focus event:", event.event)
239
+ );
240
+
241
+ collector.attach(document);
242
+ // ... capture focus events
243
+ const events = collector.getEvents();
244
+ collector.detach();
245
+ ```
246
+
247
+ ### PasteCollector
248
+
249
+ ```typescript
250
+ import { PasteCollector } from "@slopit/behavioral";
251
+
252
+ const collector = new PasteCollector(
253
+ { enabled: true, prevent: false, capturePreview: true, previewLength: 100 },
254
+ performance.now(),
255
+ () => keystrokeCollector.getRecentCount(2000),
256
+ (event) => console.log("Paste:", event.textLength, "chars")
257
+ );
258
+
259
+ collector.attach(textarea);
260
+ // ... capture paste events
261
+ const events = collector.getEvents();
262
+ collector.detach();
263
+ ```
264
+
265
+ ### ClipboardCollector
266
+
267
+ ```typescript
268
+ import { ClipboardCollector } from "@slopit/behavioral";
269
+
270
+ const collector = new ClipboardCollector(
271
+ {
272
+ enabled: true,
273
+ capturePaste: true,
274
+ captureCopyCut: true,
275
+ prevent: false,
276
+ capturePreview: true,
277
+ previewLength: 100,
278
+ },
279
+ performance.now(),
280
+ () => keystrokeCollector.getRecentCount(2000),
281
+ (pasteEvent) => console.log("Paste:", pasteEvent.textLength),
282
+ (copyEvent) => console.log("Copy:", copyEvent.event, copyEvent.textLength)
283
+ );
284
+
285
+ collector.attach(document);
286
+ // ... capture clipboard events
287
+ const pasteEvents = collector.getPasteEvents();
288
+ const copyEvents = collector.getCopyEvents();
289
+ collector.detach();
290
+ ```
291
+
292
+ ### MouseCollector
293
+
294
+ ```typescript
295
+ import { MouseCollector } from "@slopit/behavioral";
296
+
297
+ const collector = new MouseCollector(
298
+ {
299
+ enabled: true,
300
+ captureClicks: true,
301
+ captureMovement: true,
302
+ throttleMs: 50,
303
+ idleThresholdMs: 5000,
304
+ },
305
+ performance.now(),
306
+ (event) => console.log("Mouse:", event.event, event.x, event.y)
307
+ );
308
+
309
+ collector.attach(document);
310
+ // ... capture mouse events
311
+ const events = collector.getEvents();
312
+ const idlePeriods = collector.getIdlePeriods();
313
+ const totalDistance = collector.getTotalDistance();
314
+ collector.detach();
315
+ ```
316
+
317
+ ### ScrollCollector
318
+
319
+ ```typescript
320
+ import { ScrollCollector } from "@slopit/behavioral";
321
+
322
+ const collector = new ScrollCollector(
323
+ { enabled: true, throttleMs: 100, captureDirection: true },
324
+ performance.now(),
325
+ (event) => console.log("Scroll:", event.direction, event.deltaY)
326
+ );
327
+
328
+ collector.attach(document);
329
+ // ... capture scroll events
330
+ const events = collector.getEvents();
331
+ const directionChanges = collector.getDirectionChanges();
332
+ collector.detach();
333
+ ```
334
+
335
+ ### InputDurationCollector
336
+
337
+ ```typescript
338
+ import { InputDurationCollector } from "@slopit/behavioral";
339
+
340
+ const collector = new InputDurationCollector(
341
+ { enabled: true, trackKeystrokes: true, trackPastes: true },
342
+ performance.now(),
343
+ (event) => console.log("Focus session:", event.duration, "ms")
344
+ );
345
+
346
+ collector.attach(textarea);
347
+ // ... track focus duration
348
+ const events = collector.getEvents();
349
+ collector.detach();
350
+ ```
351
+
352
+ ## Detection Module
353
+
354
+ The detection module identifies potential AI assistance signatures.
355
+
356
+ ### ExtensionDetector
357
+
358
+ Detects AI assistant browser extensions (Grammarly, Copilot, Quillbot, etc.).
359
+
360
+ ```typescript
361
+ import { ExtensionDetector, createExtensionDetector } from "@slopit/behavioral";
362
+
363
+ // one-shot detection
364
+ const detector = new ExtensionDetector();
365
+ const result = detector.detect();
366
+
367
+ if (result.detected) {
368
+ console.log("Extensions found:", result.indicators);
369
+ console.log("Confidence:", result.confidence);
370
+ }
371
+
372
+ // continuous monitoring
373
+ const monitoringDetector = createExtensionDetector({
374
+ customSelectors: ["[data-custom-ai-extension]"],
375
+ customGlobals: ["__MY_AI_TOOL__"],
376
+ });
377
+
378
+ monitoringDetector.startMonitoring();
379
+ // ... extension elements may be injected dynamically
380
+ const indicators = monitoringDetector.getMonitoredIndicators();
381
+ monitoringDetector.stopMonitoring();
382
+ ```
383
+
384
+ #### ExtensionDetectorConfig
385
+
386
+ | Option | Type | Default | Description |
387
+ |--------|------|---------|-------------|
388
+ | customSelectors | string[] | [] | Additional DOM selectors to scan |
389
+ | customGlobals | string[] | [] | Additional global window properties to check |
390
+ | monitor | MonitorConfig | all enabled | MutationObserver settings |
391
+
392
+ ### TextAppearanceDetector
393
+
394
+ Detects sudden text appearance without corresponding keystroke or paste events.
395
+
396
+ ```typescript
397
+ import { TextAppearanceDetector } from "@slopit/behavioral";
398
+
399
+ const detector = new TextAppearanceDetector(
400
+ { minTextLength: 50, timeWindowMs: 2000 },
401
+ {
402
+ getRecentKeystrokes: () => keystrokeCollector.getRecentCount(2000),
403
+ hadRecentPaste: () => pasteEvents.some(p => Date.now() - p.time < 2000),
404
+ }
405
+ );
406
+
407
+ detector.startMonitoring(textarea);
408
+ // ... user interaction
409
+ const result = detector.detect();
410
+ if (result.detected) {
411
+ console.log("Suspicious text appearance:", result.indicators);
412
+ }
413
+ detector.stopMonitoring();
414
+ ```
415
+
416
+ #### TextAppearanceDetectorConfig
417
+
418
+ | Option | Type | Default | Description |
419
+ |--------|------|---------|-------------|
420
+ | minTextLength | number | 50 | Minimum character count to flag as suspicious |
421
+ | timeWindowMs | number | 2000 | Time window for checking keystroke activity |
422
+
423
+ ### DetectionResult
424
+
425
+ All detectors return a `DetectionResult`:
426
+
427
+ | Field | Type | Description |
428
+ |-------|------|-------------|
429
+ | detected | boolean | Whether the detector found evidence |
430
+ | confidence | number | Confidence score from 0 to 1 |
431
+ | message | string | Human-readable result description |
432
+ | indicators | DetectionIndicator[] | Specific indicators found |
433
+
434
+ ## Intervention Module
435
+
436
+ The intervention module triggers responses when suspicious behavior is detected.
437
+
438
+ ### InterventionManager
439
+
440
+ ```typescript
441
+ import { InterventionManager, createInterventionManager } from "@slopit/behavioral";
442
+
443
+ const manager = createInterventionManager({
444
+ triggers: [
445
+ {
446
+ type: "paste",
447
+ threshold: { paste: { minLength: 100, maxPrecedingKeystrokes: 5 } },
448
+ intervention: "warning",
449
+ },
450
+ {
451
+ type: "blur",
452
+ threshold: { blur: { countThreshold: 5, durationThreshold: 30000 } },
453
+ intervention: "friction",
454
+ },
455
+ {
456
+ type: "timing",
457
+ threshold: { timing: { maxCharactersPerSecond: 15 } },
458
+ intervention: "challenge",
459
+ },
460
+ ],
461
+ escalate: true, // escalate on repeated triggers
462
+ });
463
+
464
+ // register callbacks for each intervention type
465
+ manager.onIntervention("warning", (result) => {
466
+ alert(result.reason);
467
+ });
468
+
469
+ manager.onIntervention("challenge", (result) => {
470
+ showChallengeDialog();
471
+ });
472
+
473
+ manager.onIntervention("block", (result) => {
474
+ disableSubmitButton();
475
+ });
476
+
477
+ // evaluate behavioral state
478
+ const result = manager.evaluate({
479
+ pasteEvents: [{ textLength: 500, precedingKeystrokes: 2 }],
480
+ blurCount: 3,
481
+ totalBlurDuration: 15000,
482
+ charactersPerSecond: 8.5,
483
+ });
484
+
485
+ if (result) {
486
+ console.log("Intervention triggered:", result.type, result.reason);
487
+ }
488
+
489
+ // get intervention history
490
+ const history = manager.getHistory();
491
+
492
+ // reset for new trial
493
+ manager.reset();
494
+ ```
495
+
496
+ #### TriggerConfig
497
+
498
+ | Field | Type | Description |
499
+ |-------|------|-------------|
500
+ | type | "paste" \| "blur" \| "idle" \| "timing" \| "composite" | Trigger type |
501
+ | threshold | object | Threshold values for the trigger type |
502
+ | intervention | "warning" \| "friction" \| "challenge" \| "block" | Intervention to apply |
503
+
504
+ #### Threshold Types
505
+
506
+ **PasteThreshold:**
507
+ | Field | Type | Description |
508
+ |-------|------|-------------|
509
+ | minLength | number | Minimum text length to trigger |
510
+ | maxPrecedingKeystrokes | number | Maximum keystrokes before paste |
511
+
512
+ **BlurThreshold:**
513
+ | Field | Type | Description |
514
+ |-------|------|-------------|
515
+ | countThreshold | number | Number of blur events to trigger |
516
+ | durationThreshold | number | Total blur duration (ms) to trigger |
517
+
518
+ **IdleThreshold:**
519
+ | Field | Type | Description |
520
+ |-------|------|-------------|
521
+ | durationMs | number | Idle duration to trigger |
522
+
523
+ **TimingThreshold:**
524
+ | Field | Type | Description |
525
+ |-------|------|-------------|
526
+ | maxCharactersPerSecond | number | Maximum typing speed |
527
+
528
+ ### Challenges
529
+
530
+ Built-in challenge implementations for verifying human presence.
531
+
532
+ #### TypingTestChallenge
533
+
534
+ ```typescript
535
+ import { TypingTestChallenge, createChallenge } from "@slopit/behavioral";
536
+
537
+ const challenge = new TypingTestChallenge();
538
+ // or: const challenge = createChallenge("typing_test");
539
+
540
+ const result = await challenge.render(
541
+ {
542
+ type: "typing_test",
543
+ prompt: "Please type the following text exactly as shown:",
544
+ data: { text: "The quick brown fox jumps over the lazy dog." },
545
+ timeLimit: 60000,
546
+ },
547
+ document.getElementById("challenge-container")!
548
+ );
549
+
550
+ console.log("Passed:", result.passed);
551
+ console.log("Accuracy:", result.behavioralData?.accuracy);
552
+ console.log("Keystrokes captured:", result.behavioralData?.keystrokes.length);
553
+
554
+ challenge.cleanup();
555
+ ```
556
+
557
+ #### MemoryRecallChallenge
558
+
559
+ ```typescript
560
+ import { MemoryRecallChallenge } from "@slopit/behavioral";
561
+
562
+ const challenge = new MemoryRecallChallenge();
563
+
564
+ const result = await challenge.render(
565
+ {
566
+ type: "memory_recall",
567
+ prompt: "What color was the car in the image you saw earlier?",
568
+ expectedKeywords: ["red", "sedan"],
569
+ timeLimit: 30000,
570
+ },
571
+ document.getElementById("challenge-container")!
572
+ );
573
+
574
+ console.log("Passed:", result.passed);
575
+ console.log("Matched keywords:", result.behavioralData?.matchedKeywords);
576
+
577
+ challenge.cleanup();
578
+ ```
579
+
580
+ #### Custom Challenges
581
+
582
+ Implement the `ChallengeRenderer` interface for custom challenges:
583
+
584
+ ```typescript
585
+ import type { ChallengeRenderer, ChallengeConfig, ChallengeResult } from "@slopit/behavioral";
586
+
587
+ class AudioTranscriptionChallenge implements ChallengeRenderer {
588
+ private container: HTMLElement | null = null;
589
+
590
+ async render(config: ChallengeConfig, container: HTMLElement): Promise<ChallengeResult> {
591
+ this.container = container;
592
+ const audioUrl = config.data?.audioUrl as string;
593
+
594
+ // render audio player and text input
595
+ // capture behavioral data during transcription
596
+ // return result when submitted
597
+
598
+ return {
599
+ passed: true,
600
+ response: "transcribed text",
601
+ completionTime: 15000,
602
+ behavioralData: { /* captured data */ },
603
+ };
604
+ }
605
+
606
+ cleanup(): void {
607
+ if (this.container) {
608
+ this.container.innerHTML = "";
609
+ this.container = null;
610
+ }
611
+ }
612
+ }
613
+ ```
614
+
615
+ ## InputWrapper
616
+
617
+ A higher-level wrapper that combines capture, detection, and intervention.
618
+
619
+ ```typescript
620
+ import { InputWrapper, createInputWrapper, ExtensionDetector } from "@slopit/behavioral";
621
+
622
+ const wrapper = createInputWrapper({
623
+ capture: {
624
+ keystroke: { enabled: true },
625
+ focus: { enabled: true },
626
+ paste: { enabled: true },
627
+ },
628
+ detectors: [new ExtensionDetector()],
629
+ detectionInterval: 5000,
630
+ });
631
+
632
+ // wrap an input element
633
+ const textarea = document.getElementById("response") as HTMLTextAreaElement;
634
+ wrapper.wrap(textarea);
635
+
636
+ // subscribe to events
637
+ wrapper.on("detection", (result) => {
638
+ if (result.detected) {
639
+ console.log("Detection:", result.message);
640
+ }
641
+ });
642
+
643
+ wrapper.on("flag", (flag) => {
644
+ console.log("Flag:", flag.type, flag.severity);
645
+ });
646
+
647
+ // manually trigger detection
648
+ const results = wrapper.runDetection();
649
+
650
+ // get all captured data
651
+ const data = wrapper.getData();
652
+ console.log("Keystrokes:", data.keystrokes?.length);
653
+ console.log("Flags:", data.flags.length);
654
+ console.log("Detections:", data.detectionResults.length);
655
+
656
+ // cleanup
657
+ wrapper.unwrap();
658
+ ```
659
+
660
+ ### InputWrapperConfig
661
+
662
+ | Option | Type | Default | Description |
663
+ |--------|------|---------|-------------|
664
+ | capture | BehavioralCaptureConfig | {} | Configuration for behavioral capture |
665
+ | interventionManager | InterventionManager | undefined | Optional intervention manager |
666
+ | detectors | Detector[] | [] | Array of detectors to run periodically |
667
+ | detectionInterval | number | 5000 | Interval between detector runs (ms) |
668
+
669
+ ## Metrics Computation
670
+
671
+ ### computeKeystrokeMetrics
672
+
673
+ ```typescript
674
+ import { computeKeystrokeMetrics } from "@slopit/behavioral";
675
+
676
+ const metrics = computeKeystrokeMetrics(keystrokeEvents, 2000);
677
+
678
+ console.log("Total keystrokes:", metrics.totalKeystrokes);
679
+ console.log("Printable keystrokes:", metrics.printableKeystrokes);
680
+ console.log("Deletions:", metrics.deletions);
681
+ console.log("Mean IKI:", metrics.meanIKI);
682
+ console.log("Std IKI:", metrics.stdIKI);
683
+ console.log("Median IKI:", metrics.medianIKI);
684
+ console.log("Pause count:", metrics.pauseCount);
685
+ console.log("Product-process ratio:", metrics.productProcessRatio);
686
+ ```
687
+
688
+ ### computeFocusMetrics
689
+
690
+ ```typescript
691
+ import { computeFocusMetrics } from "@slopit/behavioral";
692
+
693
+ const metrics = computeFocusMetrics(focusEvents);
694
+
695
+ console.log("Blur count:", metrics.blurCount);
696
+ console.log("Total blur duration:", metrics.totalBlurDuration);
697
+ console.log("Hidden count:", metrics.hiddenCount);
698
+ console.log("Total hidden duration:", metrics.totalHiddenDuration);
699
+ ```
700
+
701
+ ### computeTimingMetrics
702
+
703
+ ```typescript
704
+ import { computeTimingMetrics } from "@slopit/behavioral";
705
+
706
+ const metrics = computeTimingMetrics(keystrokeEvents, totalResponseTime);
707
+
708
+ console.log("First keystroke latency:", metrics.firstKeystrokeLatency);
709
+ console.log("Total response time:", metrics.totalResponseTime);
710
+ console.log("Characters per minute:", metrics.charactersPerMinute);
711
+ ```
712
+
713
+ ## Examples
714
+
715
+ ### Basic Capture
716
+
717
+ Minimal setup for text input monitoring:
718
+
719
+ ```typescript
720
+ import { createBehavioralCapture } from "@slopit/behavioral";
721
+
722
+ const capture = createBehavioralCapture({});
723
+ capture.attach(document.querySelector("textarea")!);
724
+
725
+ document.querySelector("form")?.addEventListener("submit", () => {
726
+ const data = capture.getData();
727
+ // send data with form submission
728
+ capture.detach();
729
+ });
730
+ ```
731
+
732
+ ### Full Configuration
733
+
734
+ All options enabled with custom thresholds:
735
+
736
+ ```typescript
737
+ import { createBehavioralCapture } from "@slopit/behavioral";
738
+
739
+ const capture = createBehavioralCapture({
740
+ keystroke: {
741
+ enabled: true,
742
+ captureKeyUp: true,
743
+ includeModifiers: true,
744
+ },
745
+ focus: {
746
+ enabled: true,
747
+ useVisibilityAPI: true,
748
+ useBlurFocus: true,
749
+ },
750
+ paste: {
751
+ enabled: true,
752
+ prevent: false,
753
+ capturePreview: true,
754
+ previewLength: 200,
755
+ },
756
+ clipboard: {
757
+ enabled: true,
758
+ capturePaste: true,
759
+ captureCopyCut: true,
760
+ capturePreview: true,
761
+ previewLength: 200,
762
+ },
763
+ mouse: {
764
+ enabled: true,
765
+ captureClicks: true,
766
+ captureMovement: true,
767
+ throttleMs: 100,
768
+ idleThresholdMs: 10000,
769
+ },
770
+ scroll: {
771
+ enabled: true,
772
+ throttleMs: 150,
773
+ captureDirection: true,
774
+ },
775
+ inputDuration: {
776
+ enabled: true,
777
+ trackKeystrokes: true,
778
+ trackPastes: true,
779
+ },
780
+ });
781
+
782
+ capture.attach(document.querySelector("textarea")!);
783
+ ```
784
+
785
+ ### Real-time Monitoring
786
+
787
+ Event subscriptions and live metrics:
788
+
789
+ ```typescript
790
+ import { createBehavioralCapture } from "@slopit/behavioral";
791
+
792
+ const capture = createBehavioralCapture({});
793
+ const textarea = document.querySelector("textarea")!;
794
+ capture.attach(textarea);
795
+
796
+ // real-time keystroke monitoring
797
+ capture.on("keystroke", (event) => {
798
+ const metrics = capture.getMetrics();
799
+ updateTypingSpeedDisplay(metrics.timing?.charactersPerMinute ?? 0);
800
+ });
801
+
802
+ // paste detection
803
+ capture.on("paste", (event) => {
804
+ if (event.textLength > 100 && event.precedingKeystrokes < 5) {
805
+ showPasteWarning();
806
+ }
807
+ });
808
+
809
+ // focus tracking
810
+ capture.on("focus", (event) => {
811
+ if (event.event === "blur") {
812
+ console.log("User left the page");
813
+ }
814
+ });
815
+ ```
816
+
817
+ ### Detection Integration
818
+
819
+ Using ExtensionDetector and TextAppearanceDetector:
820
+
821
+ ```typescript
822
+ import {
823
+ createBehavioralCapture,
824
+ ExtensionDetector,
825
+ TextAppearanceDetector,
826
+ } from "@slopit/behavioral";
827
+
828
+ const capture = createBehavioralCapture({});
829
+ const textarea = document.querySelector("textarea")!;
830
+ capture.attach(textarea);
831
+
832
+ // check for extensions on page load
833
+ const extensionDetector = new ExtensionDetector();
834
+ const extensionResult = extensionDetector.detect();
835
+ if (extensionResult.detected) {
836
+ console.log("AI extensions detected:", extensionResult.message);
837
+ }
838
+
839
+ // monitor for text appearance anomalies
840
+ const textDetector = new TextAppearanceDetector(
841
+ { minTextLength: 50 },
842
+ {
843
+ getRecentKeystrokes: () => {
844
+ const data = capture.getData();
845
+ const now = performance.now();
846
+ return data.keystrokes?.filter(k => now - k.time < 2000).length ?? 0;
847
+ },
848
+ }
849
+ );
850
+ textDetector.startMonitoring(textarea);
851
+
852
+ // check before submission
853
+ document.querySelector("form")?.addEventListener("submit", (e) => {
854
+ const textResult = textDetector.detect();
855
+ if (textResult.detected) {
856
+ e.preventDefault();
857
+ showSuspiciousTextWarning(textResult.indicators);
858
+ }
859
+ textDetector.stopMonitoring();
860
+ });
861
+ ```
862
+
863
+ ### Intervention Setup
864
+
865
+ Configuring triggers and challenges:
866
+
867
+ ```typescript
868
+ import {
869
+ createBehavioralCapture,
870
+ createInterventionManager,
871
+ TypingTestChallenge,
872
+ } from "@slopit/behavioral";
873
+
874
+ const capture = createBehavioralCapture({});
875
+ capture.attach(document.querySelector("textarea")!);
876
+
877
+ const manager = createInterventionManager({
878
+ triggers: [
879
+ {
880
+ type: "paste",
881
+ threshold: { paste: { minLength: 100, maxPrecedingKeystrokes: 5 } },
882
+ intervention: "warning",
883
+ },
884
+ {
885
+ type: "composite",
886
+ threshold: {
887
+ paste: { minLength: 50, maxPrecedingKeystrokes: 10 },
888
+ blur: { countThreshold: 3, durationThreshold: 10000 },
889
+ },
890
+ intervention: "challenge",
891
+ },
892
+ ],
893
+ escalate: true,
894
+ });
895
+
896
+ manager.onIntervention("warning", (result) => {
897
+ showWarningModal(result.reason);
898
+ });
899
+
900
+ manager.onIntervention("challenge", async (result) => {
901
+ const challenge = new TypingTestChallenge();
902
+ const challengeResult = await challenge.render(
903
+ {
904
+ type: "typing_test",
905
+ prompt: "Please type this sentence to continue:",
906
+ data: { text: "I am completing this survey myself without AI assistance." },
907
+ timeLimit: 30000,
908
+ },
909
+ document.getElementById("challenge-container")!
910
+ );
911
+ challenge.cleanup();
912
+
913
+ if (!challengeResult.passed) {
914
+ disableSubmission();
915
+ }
916
+ });
917
+
918
+ // evaluate periodically
919
+ capture.on("paste", () => {
920
+ const data = capture.getData();
921
+ const state = {
922
+ pasteEvents: data.paste?.map(p => ({
923
+ textLength: p.textLength,
924
+ precedingKeystrokes: p.precedingKeystrokes,
925
+ })),
926
+ };
927
+ manager.evaluate(state);
928
+ });
929
+ ```
930
+
931
+ ## Event Types
932
+
933
+ ### BehavioralCaptureEvents
934
+
935
+ | Event | Payload | Description |
936
+ |-------|---------|-------------|
937
+ | keystroke | KeystrokeEvent | Fired for each keydown/keyup event |
938
+ | focus | FocusEvent | Fired for blur, focus, and visibility changes |
939
+ | paste | PasteEvent | Fired when text is pasted |
940
+ | clipboard | ClipboardCopyEvent | Fired for copy/cut events |
941
+ | mouse | MouseEvent | Fired for mouse events |
942
+ | scroll | ScrollEvent | Fired for scroll events |
943
+ | inputDuration | InputDurationEvent | Fired when input focus sessions end |
944
+
945
+ ## License
946
+
947
+ MIT