@slopit/behavioral 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { KeystrokeEvent, FocusEvent, PasteEvent, InputDurationEvent, ClipboardCopyEvent, MouseEvent, ScrollEvent, BehavioralData, BehavioralMetrics, CaptureFlag, KeystrokeMetrics, FocusMetrics, TimingMetrics } from '@slopit/core';
1
+ import { KeystrokeEvent, FocusEvent, PasteEvent, InputDurationEvent, ClipboardCopyEvent, MouseEvent, ScrollEvent, BehavioralData, BehavioralMetrics, CaptureFlag, ResponseControlsData, FocusMetrics, KeystrokeMetrics, TimingMetrics } from '@slopit/core';
2
2
 
3
3
  /**
4
4
  * Configuration for behavioral capture.
@@ -260,8 +260,8 @@ declare class BehavioralCapture {
260
260
  private mouseCollector;
261
261
  private scrollCollector;
262
262
  private inputDurationCollector;
263
- private attachedElement;
264
263
  private trialStartTime;
264
+ private attachedElement;
265
265
  private listeners;
266
266
  constructor(config: BehavioralCaptureConfig);
267
267
  /**
@@ -313,20 +313,67 @@ declare class BehavioralCapture {
313
313
  declare function createBehavioralCapture(config: BehavioralCaptureConfig): BehavioralCapture;
314
314
 
315
315
  /**
316
- * Collects keystroke events from DOM elements.
316
+ * Clipboard collector for paste and copy/cut events.
317
+ *
318
+ * @module
317
319
  */
318
- declare class KeystrokeCollector {
320
+
321
+ /**
322
+ * Collects clipboard events (paste, copy, cut) from DOM elements.
323
+ *
324
+ * This collector unifies paste event tracking with copy/cut event tracking,
325
+ * capturing selection context for copy/cut operations.
326
+ *
327
+ * @example
328
+ * ```typescript
329
+ * const collector = new ClipboardCollector(
330
+ * {
331
+ * enabled: true,
332
+ * capturePaste: true,
333
+ * captureCopyCut: true,
334
+ * prevent: false,
335
+ * capturePreview: true,
336
+ * previewLength: 100,
337
+ * },
338
+ * performance.now(),
339
+ * () => keystrokeCollector.getRecentCount(2000),
340
+ * );
341
+ *
342
+ * collector.attach(document);
343
+ * // ... capture events
344
+ * const pasteEvents = collector.getPasteEvents();
345
+ * const copyEvents = collector.getCopyEvents();
346
+ * collector.detach();
347
+ * ```
348
+ */
349
+ declare class ClipboardCollector {
319
350
  private config;
320
- private onEvent?;
321
- private events;
351
+ private getRecentKeystrokes;
352
+ private onPasteEvent?;
353
+ private onCopyEvent?;
354
+ private pasteEvents;
355
+ private copyEvents;
322
356
  private element;
323
357
  private startTime;
324
- private firstKeystrokeTime;
325
- private boundKeydown;
326
- private boundKeyup;
327
- constructor(config: Required<KeystrokeCaptureConfig>, startTime: number, onEvent?: ((event: KeystrokeEvent) => void) | undefined);
358
+ private boundPaste;
359
+ private boundCopy;
360
+ private boundCut;
361
+ /**
362
+ * Creates a new ClipboardCollector.
363
+ *
364
+ * @param config - Configuration options for clipboard capture
365
+ * @param startTime - Reference time for event timestamps (typically performance.now())
366
+ * @param getRecentKeystrokes - Function returning keystroke count in recent window
367
+ * @param onPasteEvent - Optional callback invoked for each paste event
368
+ * @param onCopyEvent - Optional callback invoked for each copy/cut event
369
+ */
370
+ constructor(config: Required<Omit<ClipboardCaptureConfig, "warnMessage">> & {
371
+ warnMessage?: string;
372
+ }, startTime: number, getRecentKeystrokes: () => number, onPasteEvent?: ((event: PasteEvent) => void) | undefined, onCopyEvent?: ((event: ClipboardCopyEvent) => void) | undefined);
328
373
  /**
329
374
  * Attach collector to an element.
375
+ *
376
+ * @param element - The DOM element or document to attach listeners to
330
377
  */
331
378
  attach(element: HTMLElement | Document): void;
332
379
  /**
@@ -335,25 +382,32 @@ declare class KeystrokeCollector {
335
382
  detach(): void;
336
383
  /**
337
384
  * Reset collected data.
385
+ *
386
+ * @param newStartTime - Optional new reference time for timestamps
338
387
  */
339
388
  reset(newStartTime?: number): void;
340
389
  /**
341
- * Get all collected events.
390
+ * Get all collected paste events.
391
+ *
392
+ * @returns Copy of paste events array
342
393
  */
343
- getEvents(): KeystrokeEvent[];
394
+ getPasteEvents(): PasteEvent[];
344
395
  /**
345
- * Get time of first keystroke.
396
+ * Get all collected copy/cut events.
397
+ *
398
+ * @returns Copy of copy/cut events array
346
399
  */
347
- getFirstKeystrokeTime(): number | undefined;
400
+ getCopyEvents(): ClipboardCopyEvent[];
348
401
  /**
349
- * Get count of keystrokes in the last N milliseconds.
402
+ * Get all clipboard events combined.
403
+ *
404
+ * @returns Array of all paste and copy/cut events, sorted by time
350
405
  */
351
- getRecentCount(windowMs: number): number;
352
- private handleKeydown;
353
- private handleKeyup;
354
- private recordEvent;
355
- private getTextLength;
356
- private getModifiers;
406
+ getAllEvents(): Array<PasteEvent | ClipboardCopyEvent>;
407
+ private handlePaste;
408
+ private handleCopy;
409
+ private handleCut;
410
+ private handleCopyCut;
357
411
  }
358
412
 
359
413
  /**
@@ -394,19 +448,18 @@ declare class FocusCollector {
394
448
  }
395
449
 
396
450
  /**
397
- * Collects paste events from DOM elements.
451
+ * Collects keystroke events from DOM elements.
398
452
  */
399
- declare class PasteCollector {
453
+ declare class KeystrokeCollector {
400
454
  private config;
401
- private getRecentKeystrokes;
402
455
  private onEvent?;
403
456
  private events;
404
457
  private element;
405
458
  private startTime;
406
- private boundPaste;
407
- constructor(config: Required<Omit<PasteCaptureConfig, "warnMessage">> & {
408
- warnMessage?: string;
409
- }, startTime: number, getRecentKeystrokes: () => number, onEvent?: ((event: PasteEvent) => void) | undefined);
459
+ private firstKeystrokeTime;
460
+ private boundKeydown;
461
+ private boundKeyup;
462
+ constructor(config: Required<KeystrokeCaptureConfig>, startTime: number, onEvent?: ((event: KeystrokeEvent) => void) | undefined);
410
463
  /**
411
464
  * Attach collector to an element.
412
465
  */
@@ -422,72 +475,38 @@ declare class PasteCollector {
422
475
  /**
423
476
  * Get all collected events.
424
477
  */
425
- getEvents(): PasteEvent[];
426
- private handlePaste;
478
+ getEvents(): KeystrokeEvent[];
479
+ /**
480
+ * Get time of first keystroke.
481
+ */
482
+ getFirstKeystrokeTime(): number | undefined;
483
+ /**
484
+ * Get count of keystrokes in the last N milliseconds.
485
+ */
486
+ getRecentCount(windowMs: number): number;
487
+ private handleKeydown;
488
+ private handleKeyup;
489
+ private recordEvent;
490
+ private getTextLength;
491
+ private getModifiers;
427
492
  }
428
493
 
429
494
  /**
430
- * Clipboard collector for paste and copy/cut events.
431
- *
432
- * @module
433
- */
434
-
435
- /**
436
- * Collects clipboard events (paste, copy, cut) from DOM elements.
437
- *
438
- * This collector unifies paste event tracking with copy/cut event tracking,
439
- * capturing selection context for copy/cut operations.
440
- *
441
- * @example
442
- * ```typescript
443
- * const collector = new ClipboardCollector(
444
- * {
445
- * enabled: true,
446
- * capturePaste: true,
447
- * captureCopyCut: true,
448
- * prevent: false,
449
- * capturePreview: true,
450
- * previewLength: 100,
451
- * },
452
- * performance.now(),
453
- * () => keystrokeCollector.getRecentCount(2000),
454
- * );
455
- *
456
- * collector.attach(document);
457
- * // ... capture events
458
- * const pasteEvents = collector.getPasteEvents();
459
- * const copyEvents = collector.getCopyEvents();
460
- * collector.detach();
461
- * ```
495
+ * Collects paste events from DOM elements.
462
496
  */
463
- declare class ClipboardCollector {
497
+ declare class PasteCollector {
464
498
  private config;
465
499
  private getRecentKeystrokes;
466
- private onPasteEvent?;
467
- private onCopyEvent?;
468
- private pasteEvents;
469
- private copyEvents;
500
+ private onEvent?;
501
+ private events;
470
502
  private element;
471
503
  private startTime;
472
504
  private boundPaste;
473
- private boundCopy;
474
- private boundCut;
475
- /**
476
- * Creates a new ClipboardCollector.
477
- *
478
- * @param config - Configuration options for clipboard capture
479
- * @param startTime - Reference time for event timestamps (typically performance.now())
480
- * @param getRecentKeystrokes - Function returning keystroke count in recent window
481
- * @param onPasteEvent - Optional callback invoked for each paste event
482
- * @param onCopyEvent - Optional callback invoked for each copy/cut event
483
- */
484
- constructor(config: Required<Omit<ClipboardCaptureConfig, "warnMessage">> & {
505
+ constructor(config: Required<Omit<PasteCaptureConfig, "warnMessage">> & {
485
506
  warnMessage?: string;
486
- }, startTime: number, getRecentKeystrokes: () => number, onPasteEvent?: ((event: PasteEvent) => void) | undefined, onCopyEvent?: ((event: ClipboardCopyEvent) => void) | undefined);
507
+ }, startTime: number, getRecentKeystrokes: () => number, onEvent?: ((event: PasteEvent) => void) | undefined);
487
508
  /**
488
509
  * Attach collector to an element.
489
- *
490
- * @param element - The DOM element or document to attach listeners to
491
510
  */
492
511
  attach(element: HTMLElement | Document): void;
493
512
  /**
@@ -496,60 +515,30 @@ declare class ClipboardCollector {
496
515
  detach(): void;
497
516
  /**
498
517
  * Reset collected data.
499
- *
500
- * @param newStartTime - Optional new reference time for timestamps
501
518
  */
502
519
  reset(newStartTime?: number): void;
503
520
  /**
504
- * Get all collected paste events.
505
- *
506
- * @returns Copy of paste events array
507
- */
508
- getPasteEvents(): PasteEvent[];
509
- /**
510
- * Get all collected copy/cut events.
511
- *
512
- * @returns Copy of copy/cut events array
513
- */
514
- getCopyEvents(): ClipboardCopyEvent[];
515
- /**
516
- * Get all clipboard events combined.
517
- *
518
- * @returns Array of all paste and copy/cut events, sorted by time
521
+ * Get all collected events.
519
522
  */
520
- getAllEvents(): Array<PasteEvent | ClipboardCopyEvent>;
523
+ getEvents(): PasteEvent[];
521
524
  private handlePaste;
522
- private handleCopy;
523
- private handleCut;
524
- private handleCopyCut;
525
525
  }
526
526
 
527
+ /** A study must grant consent before response-control listeners are attached. */
528
+ interface ResponseControlsConfig {
529
+ targetSelector: string;
530
+ hasConsent: () => boolean;
531
+ /** Optional lifetime signal, for instance when a participant withdraws. */
532
+ signal?: AbortSignal;
533
+ }
527
534
  /**
528
- * Compute metrics from keystroke events.
529
- *
530
- * @param keystrokes - Array of keystroke events
531
- * @param pauseThreshold - Minimum IKI to count as a pause (default: 2000ms)
532
- * @returns Computed keystroke metrics
533
- */
534
- declare function computeKeystrokeMetrics(keystrokes: KeystrokeEvent[], pauseThreshold?: number): KeystrokeMetrics;
535
-
536
- /**
537
- * Compute metrics from focus events.
538
- *
539
- * @param focusEvents - Array of focus events
540
- * @returns Computed focus metrics
541
- */
542
- declare function computeFocusMetrics(focusEvents: FocusEvent[]): FocusMetrics;
543
-
544
- /**
545
- * Compute timing metrics from keystroke events.
535
+ * Capture timing and provenance inside selected controls.
546
536
  *
547
- * @param keystrokes - Array of keystroke events
548
- * @param trialStartTime - Trial start time (for first keystroke latency)
549
- * @param totalResponseTime - Total response time in milliseconds
550
- * @returns Computed timing metrics
537
+ * Event payloads never include field values, raw text keys, key codes, or clipboard data.
551
538
  */
552
- declare function computeTimingMetrics(keystrokes: KeystrokeEvent[], totalResponseTime: number): TimingMetrics;
539
+ declare function captureResponseControls(container: HTMLElement, config: ResponseControlsConfig, trialStart: number): {
540
+ finish: () => ResponseControlsData | null;
541
+ } | null;
553
542
 
554
543
  /**
555
544
  * Base types for detection modules.
@@ -649,28 +638,194 @@ interface Detector {
649
638
  }
650
639
 
651
640
  /**
652
- * Detector for sudden text appearance without keystroke or paste source.
641
+ * Detector for AI assistant browser extension signatures.
642
+ *
643
+ * Scans the DOM and global window object for known patterns associated with
644
+ * browser extensions like Grammarly, Copilot, Quillbot, and other AI assistants.
653
645
  *
654
646
  * @module
655
647
  */
656
648
 
657
649
  /**
658
- * Configuration for the text appearance detector.
650
+ * Monitor configuration for MutationObserver settings.
659
651
  */
660
- interface TextAppearanceDetectorConfig {
652
+ interface MonitorConfig {
661
653
  /**
662
- * Minimum character count to flag as suspicious.
663
- * @default 50
654
+ * Whether to observe attribute changes.
655
+ * @default true
664
656
  */
665
- minTextLength?: number;
657
+ attributes: boolean;
666
658
  /**
667
- * Time window in milliseconds to check for keystroke activity.
668
- * @default 2000
659
+ * Whether to observe child node additions/removals.
660
+ * @default true
669
661
  */
670
- timeWindowMs?: number;
662
+ childList: boolean;
663
+ /**
664
+ * Whether to observe the entire subtree.
665
+ * @default true
666
+ */
667
+ subtree: boolean;
671
668
  }
672
669
  /**
673
- * Callbacks for checking keystroke and paste activity.
670
+ * Configuration for the ExtensionDetector.
671
+ */
672
+ interface ExtensionDetectorConfig {
673
+ /**
674
+ * Additional DOM selectors to scan for extension signatures.
675
+ */
676
+ customSelectors?: string[];
677
+ /**
678
+ * Additional global window properties to check.
679
+ */
680
+ customGlobals?: string[];
681
+ /**
682
+ * Configuration for continuous monitoring via MutationObserver.
683
+ */
684
+ monitor?: Partial<MonitorConfig>;
685
+ }
686
+ /**
687
+ * Detects AI assistant browser extension signatures.
688
+ *
689
+ * Scans for:
690
+ * - Known DOM elements injected by extensions (e.g., Grammarly shadow roots)
691
+ * - Global variables set by extensions
692
+ * - Custom patterns provided via configuration
693
+ *
694
+ * @example
695
+ * ```typescript
696
+ * const detector = new ExtensionDetector();
697
+ * const result = detector.detect();
698
+ *
699
+ * if (result.detected) {
700
+ * console.log("Extensions found:", result.indicators);
701
+ * }
702
+ * ```
703
+ *
704
+ * @example
705
+ * ```typescript
706
+ * // With continuous monitoring
707
+ * const detector = new ExtensionDetector({
708
+ * customSelectors: ['[data-my-extension]'],
709
+ * });
710
+ *
711
+ * detector.startMonitoring();
712
+ * // ... later
713
+ * detector.stopMonitoring();
714
+ * ```
715
+ */
716
+ declare class ExtensionDetector implements Detector {
717
+ readonly name = "extension-detector";
718
+ private readonly config;
719
+ private readonly allSelectors;
720
+ private readonly allGlobals;
721
+ private observer;
722
+ private monitoredIndicators;
723
+ constructor(config?: ExtensionDetectorConfig);
724
+ /**
725
+ * Performs a one-shot detection scan for extension signatures.
726
+ *
727
+ * @returns Detection result with found indicators
728
+ */
729
+ detect(): DetectionResult;
730
+ /**
731
+ * Starts continuous monitoring for dynamically injected extension elements.
732
+ *
733
+ * Uses MutationObserver to watch for DOM changes that match extension patterns.
734
+ */
735
+ startMonitoring(): void;
736
+ /**
737
+ * Stops continuous monitoring and disconnects the MutationObserver.
738
+ */
739
+ stopMonitoring(): void;
740
+ /**
741
+ * Gets all indicators detected during monitoring.
742
+ *
743
+ * @returns Array of detection indicators found during monitoring
744
+ */
745
+ getMonitoredIndicators(): DetectionIndicator[];
746
+ /**
747
+ * Resets all collected monitoring data.
748
+ */
749
+ reset(): void;
750
+ /**
751
+ * Queries the DOM for elements matching a selector.
752
+ */
753
+ private queryElements;
754
+ /**
755
+ * Checks if a global variable exists on the window object.
756
+ */
757
+ private hasGlobal;
758
+ /**
759
+ * Handles mutation events from the MutationObserver.
760
+ */
761
+ private handleMutations;
762
+ /**
763
+ * Handles child list mutations, checking new nodes for extension patterns.
764
+ */
765
+ private handleChildListMutation;
766
+ /**
767
+ * Handles attribute mutations, checking if changes match extension patterns.
768
+ */
769
+ private handleAttributeMutation;
770
+ /**
771
+ * Safely checks if an element matches a selector.
772
+ */
773
+ private elementMatchesSelector;
774
+ /**
775
+ * Safely queries for elements within a parent.
776
+ */
777
+ private querySelectorSafe;
778
+ /**
779
+ * Adds an indicator to the monitored indicators list.
780
+ */
781
+ private addMonitoredIndicator;
782
+ /**
783
+ * Calculates a confidence score based on indicators.
784
+ */
785
+ private calculateConfidence;
786
+ /**
787
+ * Generates a human-readable message from indicators.
788
+ */
789
+ private generateMessage;
790
+ }
791
+ /**
792
+ * Creates a new ExtensionDetector instance.
793
+ *
794
+ * @param config - Configuration options
795
+ * @returns New ExtensionDetector instance
796
+ *
797
+ * @example
798
+ * ```typescript
799
+ * const detector = createExtensionDetector({
800
+ * customSelectors: ['[data-custom-ai]'],
801
+ * });
802
+ * ```
803
+ */
804
+ declare function createExtensionDetector(config?: ExtensionDetectorConfig): ExtensionDetector;
805
+
806
+ /**
807
+ * Detector for sudden text appearance without keystroke or paste source.
808
+ *
809
+ * @module
810
+ */
811
+
812
+ /**
813
+ * Configuration for the text appearance detector.
814
+ */
815
+ interface TextAppearanceDetectorConfig {
816
+ /**
817
+ * Minimum character count to flag as suspicious.
818
+ * @default 50
819
+ */
820
+ minTextLength?: number;
821
+ /**
822
+ * Time window in milliseconds to check for keystroke activity.
823
+ * @default 2000
824
+ */
825
+ timeWindowMs?: number;
826
+ }
827
+ /**
828
+ * Callbacks for checking keystroke and paste activity.
674
829
  */
675
830
  interface TextAppearanceCallbacks {
676
831
  /**
@@ -764,170 +919,237 @@ declare class TextAppearanceDetector implements Detector {
764
919
  }
765
920
 
766
921
  /**
767
- * Detector for AI assistant browser extension signatures.
922
+ * Challenge system for verifying human presence during behavioral capture.
768
923
  *
769
- * Scans the DOM and global window object for known patterns associated with
770
- * browser extensions like Grammarly, Copilot, Quillbot, and other AI assistants.
924
+ * Challenges are interactive tasks that collect behavioral data while
925
+ * verifying participant engagement. Researchers can implement custom
926
+ * challenge renderers or use the provided implementations.
771
927
  *
772
928
  * @module
773
929
  */
774
-
775
930
  /**
776
- * Monitor configuration for MutationObserver settings.
931
+ * Available challenge types.
932
+ *
933
+ * - `audio_transcription`: User transcribes audio content
934
+ * - `image_description`: User describes visual content
935
+ * - `typing_test`: User types displayed text (captures natural rhythm)
936
+ * - `memory_recall`: User answers questions about previously shown content
937
+ * - `consistency_check`: User re-answers a previous question for comparison
777
938
  */
778
- interface MonitorConfig {
939
+ type ChallengeType = "audio_transcription" | "image_description" | "typing_test" | "memory_recall" | "consistency_check";
940
+ /**
941
+ * Configuration for a challenge.
942
+ */
943
+ interface ChallengeConfig {
779
944
  /**
780
- * Whether to observe attribute changes.
781
- * @default true
945
+ * Type of challenge to present.
782
946
  */
783
- attributes: boolean;
947
+ type: ChallengeType;
784
948
  /**
785
- * Whether to observe child node additions/removals.
786
- * @default true
949
+ * Prompt or instructions to display to the participant.
787
950
  */
788
- childList: boolean;
951
+ prompt: string;
789
952
  /**
790
- * Whether to observe the entire subtree.
791
- * @default true
953
+ * Keywords expected in a valid response.
954
+ * Used for automatic verification of memory recall and description challenges.
792
955
  */
793
- subtree: boolean;
956
+ expectedKeywords?: string[];
957
+ /**
958
+ * Time limit for completing the challenge in milliseconds.
959
+ * When exceeded, the challenge should auto-submit with current response.
960
+ */
961
+ timeLimit?: number;
962
+ /**
963
+ * Type-specific configuration data.
964
+ *
965
+ * For `typing_test`: `{ text: string }` - the text to type
966
+ * For `audio_transcription`: `{ audioUrl: string }` - URL of audio file
967
+ * For `image_description`: `{ imageUrl: string }` - URL of image
968
+ * For `memory_recall`: `{ question: string, context?: string }`
969
+ * For `consistency_check`: `{ originalQuestion: string, originalAnswer: string }`
970
+ */
971
+ data?: Record<string, unknown>;
794
972
  }
795
973
  /**
796
- * Configuration for the ExtensionDetector.
974
+ * Result from a completed challenge.
797
975
  */
798
- interface ExtensionDetectorConfig {
976
+ interface ChallengeResult {
799
977
  /**
800
- * Additional DOM selectors to scan for extension signatures.
978
+ * Whether the challenge was successfully completed.
979
+ * For typing tests, this indicates accuracy threshold was met.
980
+ * For keyword-based challenges, this indicates required keywords were present.
801
981
  */
802
- customSelectors?: string[];
982
+ passed: boolean;
803
983
  /**
804
- * Additional global window properties to check.
984
+ * The participant's response text.
805
985
  */
806
- customGlobals?: string[];
986
+ response: string;
807
987
  /**
808
- * Configuration for continuous monitoring via MutationObserver.
988
+ * Time taken to complete the challenge in milliseconds.
809
989
  */
810
- monitor?: Partial<MonitorConfig>;
990
+ completionTime: number;
991
+ /**
992
+ * Behavioral data captured during the challenge.
993
+ * Contains keystroke events, timing patterns, and other captured signals.
994
+ */
995
+ behavioralData?: unknown;
811
996
  }
812
997
  /**
813
- * Detects AI assistant browser extension signatures.
998
+ * Interface for challenge renderers.
814
999
  *
815
- * Scans for:
816
- * - Known DOM elements injected by extensions (e.g., Grammarly shadow roots)
817
- * - Global variables set by extensions
818
- * - Custom patterns provided via configuration
1000
+ * Researchers implement this interface to customize how challenges
1001
+ * are presented to participants. The library provides default
1002
+ * implementations for common challenge types.
819
1003
  *
820
1004
  * @example
821
1005
  * ```typescript
822
- * const detector = new ExtensionDetector();
823
- * const result = detector.detect();
824
- *
825
- * if (result.detected) {
826
- * console.log("Extensions found:", result.indicators);
827
- * }
828
- * ```
1006
+ * class CustomChallenge implements ChallengeRenderer {
1007
+ * private cleanup: (() => void) | null = null;
829
1008
  *
830
- * @example
831
- * ```typescript
832
- * // With continuous monitoring
833
- * const detector = new ExtensionDetector({
834
- * customSelectors: ['[data-my-extension]'],
835
- * });
1009
+ * async render(
1010
+ * config: ChallengeConfig,
1011
+ * container: HTMLElement
1012
+ * ): Promise<ChallengeResult> {
1013
+ * // Create and append UI elements to container
1014
+ * // Set up event listeners and capture
1015
+ * // Return result when participant submits
1016
+ * }
836
1017
  *
837
- * detector.startMonitoring();
838
- * // ... later
839
- * detector.stopMonitoring();
1018
+ * cleanup(): void {
1019
+ * // Remove elements and event listeners
1020
+ * }
1021
+ * }
840
1022
  * ```
841
1023
  */
842
- declare class ExtensionDetector implements Detector {
843
- readonly name = "extension-detector";
844
- private readonly config;
845
- private readonly allSelectors;
846
- private readonly allGlobals;
847
- private observer;
848
- private monitoredIndicators;
849
- constructor(config?: ExtensionDetectorConfig);
850
- /**
851
- * Performs a one-shot detection scan for extension signatures.
852
- *
853
- * @returns Detection result with found indicators
854
- */
855
- detect(): DetectionResult;
1024
+ interface ChallengeRenderer {
856
1025
  /**
857
- * Starts continuous monitoring for dynamically injected extension elements.
1026
+ * Render the challenge UI and wait for completion.
858
1027
  *
859
- * Uses MutationObserver to watch for DOM changes that match extension patterns.
1028
+ * @param config - Challenge configuration
1029
+ * @param container - DOM element to render the challenge into
1030
+ * @returns Promise that resolves with the challenge result when submitted
860
1031
  */
861
- startMonitoring(): void;
1032
+ render(config: ChallengeConfig, container: HTMLElement): Promise<ChallengeResult>;
862
1033
  /**
863
- * Stops continuous monitoring and disconnects the MutationObserver.
1034
+ * Clean up the challenge UI and release resources.
1035
+ * Called after the challenge completes or is cancelled.
864
1036
  */
865
- stopMonitoring(): void;
1037
+ cleanup(): void;
1038
+ }
1039
+ /**
1040
+ * Typing test challenge that captures natural typing rhythm.
1041
+ *
1042
+ * Displays text for the participant to type, capturing keystroke
1043
+ * timing patterns that can be compared against their regular typing
1044
+ * behavior. This helps verify the same person is responding throughout
1045
+ * the study.
1046
+ *
1047
+ * @example
1048
+ * ```typescript
1049
+ * const challenge = new TypingTestChallenge();
1050
+ * const result = await challenge.render(
1051
+ * {
1052
+ * type: "typing_test",
1053
+ * prompt: "Please type the following text exactly as shown:",
1054
+ * data: { text: "The quick brown fox jumps over the lazy dog." },
1055
+ * timeLimit: 60000,
1056
+ * },
1057
+ * document.getElementById("challenge-container")!
1058
+ * );
1059
+ * console.log(result.passed, result.behavioralData);
1060
+ * challenge.cleanup();
1061
+ * ```
1062
+ */
1063
+ declare class TypingTestChallenge implements ChallengeRenderer {
1064
+ private container;
1065
+ private startTime;
1066
+ private keystrokes;
1067
+ private boundHandlers;
866
1068
  /**
867
- * Gets all indicators detected during monitoring.
1069
+ * Render the typing test challenge.
868
1070
  *
869
- * @returns Array of detection indicators found during monitoring
870
- */
871
- getMonitoredIndicators(): DetectionIndicator[];
872
- /**
873
- * Resets all collected monitoring data.
874
- */
875
- reset(): void;
876
- /**
877
- * Queries the DOM for elements matching a selector.
878
- */
879
- private queryElements;
880
- /**
881
- * Checks if a global variable exists on the window object.
882
- */
883
- private hasGlobal;
884
- /**
885
- * Handles mutation events from the MutationObserver.
886
- */
887
- private handleMutations;
888
- /**
889
- * Handles child list mutations, checking new nodes for extension patterns.
1071
+ * @param config - Challenge configuration with `data.text` containing the text to type
1072
+ * @param container - Container element for the challenge UI
1073
+ * @returns Promise resolving to challenge result with typing accuracy and keystroke data
890
1074
  */
891
- private handleChildListMutation;
1075
+ render(config: ChallengeConfig, container: HTMLElement): Promise<ChallengeResult>;
892
1076
  /**
893
- * Handles attribute mutations, checking if changes match extension patterns.
1077
+ * Clean up challenge UI and event listeners.
894
1078
  */
895
- private handleAttributeMutation;
1079
+ cleanup(): void;
896
1080
  /**
897
- * Safely checks if an element matches a selector.
1081
+ * Calculate typing accuracy as a ratio (0-1).
1082
+ * Uses a simple character-by-character comparison with length normalization.
898
1083
  */
899
- private elementMatchesSelector;
1084
+ private calculateAccuracy;
1085
+ }
1086
+ /**
1087
+ * Memory recall challenge that verifies participant engagement.
1088
+ *
1089
+ * Presents a question about previously shown content and checks
1090
+ * if the response contains expected keywords. Captures typing
1091
+ * behavior during the response.
1092
+ *
1093
+ * @example
1094
+ * ```typescript
1095
+ * const challenge = new MemoryRecallChallenge();
1096
+ * const result = await challenge.render(
1097
+ * {
1098
+ * type: "memory_recall",
1099
+ * prompt: "What color was the car in the image you saw earlier?",
1100
+ * expectedKeywords: ["red", "sedan"],
1101
+ * timeLimit: 30000,
1102
+ * },
1103
+ * document.getElementById("challenge-container")!
1104
+ * );
1105
+ * ```
1106
+ */
1107
+ declare class MemoryRecallChallenge implements ChallengeRenderer {
1108
+ private container;
1109
+ private startTime;
1110
+ private keystrokes;
1111
+ private boundHandlers;
900
1112
  /**
901
- * Safely queries for elements within a parent.
1113
+ * Render the memory recall challenge.
1114
+ *
1115
+ * @param config - Challenge configuration with optional `expectedKeywords`
1116
+ * @param container - Container element for the challenge UI
1117
+ * @returns Promise resolving to challenge result with keyword matching status
902
1118
  */
903
- private querySelectorSafe;
1119
+ render(config: ChallengeConfig, container: HTMLElement): Promise<ChallengeResult>;
904
1120
  /**
905
- * Adds an indicator to the monitored indicators list.
1121
+ * Clean up challenge UI and event listeners.
906
1122
  */
907
- private addMonitoredIndicator;
1123
+ cleanup(): void;
908
1124
  /**
909
- * Calculates a confidence score based on indicators.
1125
+ * Check if response contains all expected keywords.
910
1126
  */
911
- private calculateConfidence;
1127
+ private checkKeywords;
912
1128
  /**
913
- * Generates a human-readable message from indicators.
1129
+ * Get list of keywords that were matched in the response.
914
1130
  */
915
- private generateMessage;
1131
+ private getMatchedKeywords;
916
1132
  }
917
1133
  /**
918
- * Creates a new ExtensionDetector instance.
1134
+ * Create a challenge renderer for the specified type.
1135
+ *
1136
+ * Returns a built-in renderer for supported types (typing_test, memory_recall),
1137
+ * or null for types that require custom implementation (audio_transcription,
1138
+ * image_description, consistency_check).
919
1139
  *
920
- * @param config - Configuration options
921
- * @returns New ExtensionDetector instance
1140
+ * @param type - The challenge type
1141
+ * @returns A challenge renderer instance, or null if type requires custom implementation
922
1142
  *
923
1143
  * @example
924
1144
  * ```typescript
925
- * const detector = createExtensionDetector({
926
- * customSelectors: ['[data-custom-ai]'],
927
- * });
1145
+ * const challenge = createChallenge("typing_test");
1146
+ * if (challenge) {
1147
+ * const result = await challenge.render(config, container);
1148
+ * challenge.cleanup();
1149
+ * }
928
1150
  * ```
929
1151
  */
930
- declare function createExtensionDetector(config?: ExtensionDetectorConfig): ExtensionDetector;
1152
+ declare function createChallenge(type: ChallengeType): ChallengeRenderer | null;
931
1153
 
932
1154
  /**
933
1155
  * Types for the intervention module.
@@ -1267,237 +1489,31 @@ declare class InterventionManager$1 {
1267
1489
  declare function createInterventionManager(config: InterventionManagerConfig): InterventionManager$1;
1268
1490
 
1269
1491
  /**
1270
- * Challenge system for verifying human presence during behavioral capture.
1271
- *
1272
- * Challenges are interactive tasks that collect behavioral data while
1273
- * verifying participant engagement. Researchers can implement custom
1274
- * challenge renderers or use the provided implementations.
1275
- *
1276
- * @module
1277
- */
1278
- /**
1279
- * Available challenge types.
1280
- *
1281
- * - `audio_transcription`: User transcribes audio content
1282
- * - `image_description`: User describes visual content
1283
- * - `typing_test`: User types displayed text (captures natural rhythm)
1284
- * - `memory_recall`: User answers questions about previously shown content
1285
- * - `consistency_check`: User re-answers a previous question for comparison
1286
- */
1287
- type ChallengeType = "audio_transcription" | "image_description" | "typing_test" | "memory_recall" | "consistency_check";
1288
- /**
1289
- * Configuration for a challenge.
1290
- */
1291
- interface ChallengeConfig {
1292
- /**
1293
- * Type of challenge to present.
1294
- */
1295
- type: ChallengeType;
1296
- /**
1297
- * Prompt or instructions to display to the participant.
1298
- */
1299
- prompt: string;
1300
- /**
1301
- * Keywords expected in a valid response.
1302
- * Used for automatic verification of memory recall and description challenges.
1303
- */
1304
- expectedKeywords?: string[];
1305
- /**
1306
- * Time limit for completing the challenge in milliseconds.
1307
- * When exceeded, the challenge should auto-submit with current response.
1308
- */
1309
- timeLimit?: number;
1310
- /**
1311
- * Type-specific configuration data.
1312
- *
1313
- * For `typing_test`: `{ text: string }` - the text to type
1314
- * For `audio_transcription`: `{ audioUrl: string }` - URL of audio file
1315
- * For `image_description`: `{ imageUrl: string }` - URL of image
1316
- * For `memory_recall`: `{ question: string, context?: string }`
1317
- * For `consistency_check`: `{ originalQuestion: string, originalAnswer: string }`
1318
- */
1319
- data?: Record<string, unknown>;
1320
- }
1321
- /**
1322
- * Result from a completed challenge.
1323
- */
1324
- interface ChallengeResult {
1325
- /**
1326
- * Whether the challenge was successfully completed.
1327
- * For typing tests, this indicates accuracy threshold was met.
1328
- * For keyword-based challenges, this indicates required keywords were present.
1329
- */
1330
- passed: boolean;
1331
- /**
1332
- * The participant's response text.
1333
- */
1334
- response: string;
1335
- /**
1336
- * Time taken to complete the challenge in milliseconds.
1337
- */
1338
- completionTime: number;
1339
- /**
1340
- * Behavioral data captured during the challenge.
1341
- * Contains keystroke events, timing patterns, and other captured signals.
1342
- */
1343
- behavioralData?: unknown;
1344
- }
1345
- /**
1346
- * Interface for challenge renderers.
1347
- *
1348
- * Researchers implement this interface to customize how challenges
1349
- * are presented to participants. The library provides default
1350
- * implementations for common challenge types.
1351
- *
1352
- * @example
1353
- * ```typescript
1354
- * class CustomChallenge implements ChallengeRenderer {
1355
- * private cleanup: (() => void) | null = null;
1356
- *
1357
- * async render(
1358
- * config: ChallengeConfig,
1359
- * container: HTMLElement
1360
- * ): Promise<ChallengeResult> {
1361
- * // Create and append UI elements to container
1362
- * // Set up event listeners and capture
1363
- * // Return result when participant submits
1364
- * }
1365
- *
1366
- * cleanup(): void {
1367
- * // Remove elements and event listeners
1368
- * }
1369
- * }
1370
- * ```
1371
- */
1372
- interface ChallengeRenderer {
1373
- /**
1374
- * Render the challenge UI and wait for completion.
1375
- *
1376
- * @param config - Challenge configuration
1377
- * @param container - DOM element to render the challenge into
1378
- * @returns Promise that resolves with the challenge result when submitted
1379
- */
1380
- render(config: ChallengeConfig, container: HTMLElement): Promise<ChallengeResult>;
1381
- /**
1382
- * Clean up the challenge UI and release resources.
1383
- * Called after the challenge completes or is cancelled.
1384
- */
1385
- cleanup(): void;
1386
- }
1387
- /**
1388
- * Typing test challenge that captures natural typing rhythm.
1389
- *
1390
- * Displays text for the participant to type, capturing keystroke
1391
- * timing patterns that can be compared against their regular typing
1392
- * behavior. This helps verify the same person is responding throughout
1393
- * the study.
1492
+ * Compute metrics from focus events.
1394
1493
  *
1395
- * @example
1396
- * ```typescript
1397
- * const challenge = new TypingTestChallenge();
1398
- * const result = await challenge.render(
1399
- * {
1400
- * type: "typing_test",
1401
- * prompt: "Please type the following text exactly as shown:",
1402
- * data: { text: "The quick brown fox jumps over the lazy dog." },
1403
- * timeLimit: 60000,
1404
- * },
1405
- * document.getElementById("challenge-container")!
1406
- * );
1407
- * console.log(result.passed, result.behavioralData);
1408
- * challenge.cleanup();
1409
- * ```
1494
+ * @param focusEvents - Array of focus events
1495
+ * @returns Computed focus metrics
1410
1496
  */
1411
- declare class TypingTestChallenge implements ChallengeRenderer {
1412
- private container;
1413
- private startTime;
1414
- private keystrokes;
1415
- private boundHandlers;
1416
- /**
1417
- * Render the typing test challenge.
1418
- *
1419
- * @param config - Challenge configuration with `data.text` containing the text to type
1420
- * @param container - Container element for the challenge UI
1421
- * @returns Promise resolving to challenge result with typing accuracy and keystroke data
1422
- */
1423
- render(config: ChallengeConfig, container: HTMLElement): Promise<ChallengeResult>;
1424
- /**
1425
- * Clean up challenge UI and event listeners.
1426
- */
1427
- cleanup(): void;
1428
- /**
1429
- * Calculate typing accuracy as a ratio (0-1).
1430
- * Uses a simple character-by-character comparison with length normalization.
1431
- */
1432
- private calculateAccuracy;
1433
- }
1497
+ declare function computeFocusMetrics(focusEvents: FocusEvent[]): FocusMetrics;
1498
+
1434
1499
  /**
1435
- * Memory recall challenge that verifies participant engagement.
1436
- *
1437
- * Presents a question about previously shown content and checks
1438
- * if the response contains expected keywords. Captures typing
1439
- * behavior during the response.
1500
+ * Compute metrics from keystroke events.
1440
1501
  *
1441
- * @example
1442
- * ```typescript
1443
- * const challenge = new MemoryRecallChallenge();
1444
- * const result = await challenge.render(
1445
- * {
1446
- * type: "memory_recall",
1447
- * prompt: "What color was the car in the image you saw earlier?",
1448
- * expectedKeywords: ["red", "sedan"],
1449
- * timeLimit: 30000,
1450
- * },
1451
- * document.getElementById("challenge-container")!
1452
- * );
1453
- * ```
1502
+ * @param keystrokes - Array of keystroke events
1503
+ * @param pauseThreshold - Minimum IKI to count as a pause (default: 2000ms)
1504
+ * @returns Computed keystroke metrics
1454
1505
  */
1455
- declare class MemoryRecallChallenge implements ChallengeRenderer {
1456
- private container;
1457
- private startTime;
1458
- private keystrokes;
1459
- private boundHandlers;
1460
- /**
1461
- * Render the memory recall challenge.
1462
- *
1463
- * @param config - Challenge configuration with optional `expectedKeywords`
1464
- * @param container - Container element for the challenge UI
1465
- * @returns Promise resolving to challenge result with keyword matching status
1466
- */
1467
- render(config: ChallengeConfig, container: HTMLElement): Promise<ChallengeResult>;
1468
- /**
1469
- * Clean up challenge UI and event listeners.
1470
- */
1471
- cleanup(): void;
1472
- /**
1473
- * Check if response contains all expected keywords.
1474
- */
1475
- private checkKeywords;
1476
- /**
1477
- * Get list of keywords that were matched in the response.
1478
- */
1479
- private getMatchedKeywords;
1480
- }
1506
+ declare function computeKeystrokeMetrics(keystrokes: KeystrokeEvent[], pauseThreshold?: number): KeystrokeMetrics;
1507
+
1481
1508
  /**
1482
- * Create a challenge renderer for the specified type.
1483
- *
1484
- * Returns a built-in renderer for supported types (typing_test, memory_recall),
1485
- * or null for types that require custom implementation (audio_transcription,
1486
- * image_description, consistency_check).
1487
- *
1488
- * @param type - The challenge type
1489
- * @returns A challenge renderer instance, or null if type requires custom implementation
1509
+ * Compute timing metrics from keystroke events.
1490
1510
  *
1491
- * @example
1492
- * ```typescript
1493
- * const challenge = createChallenge("typing_test");
1494
- * if (challenge) {
1495
- * const result = await challenge.render(config, container);
1496
- * challenge.cleanup();
1497
- * }
1498
- * ```
1511
+ * @param keystrokes - Array of keystroke events
1512
+ * @param trialStartTime - Trial start time (for first keystroke latency)
1513
+ * @param totalResponseTime - Total response time in milliseconds
1514
+ * @returns Computed timing metrics
1499
1515
  */
1500
- declare function createChallenge(type: ChallengeType): ChallengeRenderer | null;
1516
+ declare function computeTimingMetrics(keystrokes: KeystrokeEvent[], totalResponseTime: number): TimingMetrics;
1501
1517
 
1502
1518
  /**
1503
1519
  * Generic wrapper for HTML input elements combining behavioral capture with interventions.
@@ -1819,4 +1835,4 @@ declare class InputWrapper {
1819
1835
  */
1820
1836
  declare function createInputWrapper(config?: InputWrapperConfig): InputWrapper;
1821
1837
 
1822
- export { BehavioralCapture, type BehavioralCaptureConfig, type BehavioralCaptureEvents, type BehavioralState, type BlurThreshold, type ChallengeConfig, type ChallengeRenderer, type ChallengeResult, type ChallengeType, type ClipboardCaptureConfig, ClipboardCollector, type DetectionIndicator, type DetectionResult, type Detector, type EnhancedBehavioralData, ExtensionDetector, type ExtensionDetectorConfig, type FocusCaptureConfig, FocusCollector, type IdleThreshold, InputWrapper, type InputWrapperConfig, InterventionManager$1 as InterventionManager, type InterventionManagerConfig, type InterventionResult$1 as InterventionResult, type InterventionType, type KeystrokeCaptureConfig, KeystrokeCollector, MemoryRecallChallenge, type PasteCaptureConfig, PasteCollector, type PasteThreshold, type TextAppearanceCallbacks, TextAppearanceDetector, type TextAppearanceDetectorConfig, type TimingThreshold, type TriggerConfig, TypingTestChallenge, type WrapperEvent, type InterventionManager as WrapperInterventionManager, type InterventionResult as WrapperInterventionResult, computeFocusMetrics, computeKeystrokeMetrics, computeTimingMetrics, createBehavioralCapture, createChallenge, createExtensionDetector, createInputWrapper, createInterventionManager };
1838
+ export { BehavioralCapture, type BehavioralCaptureConfig, type BehavioralCaptureEvents, type BehavioralState, type BlurThreshold, type ChallengeConfig, type ChallengeRenderer, type ChallengeResult, type ChallengeType, type ClipboardCaptureConfig, ClipboardCollector, type DetectionIndicator, type DetectionResult, type Detector, type EnhancedBehavioralData, ExtensionDetector, type ExtensionDetectorConfig, type FocusCaptureConfig, FocusCollector, type IdleThreshold, InputWrapper, type InputWrapperConfig, InterventionManager$1 as InterventionManager, type InterventionManagerConfig, type InterventionResult$1 as InterventionResult, type InterventionType, type KeystrokeCaptureConfig, KeystrokeCollector, MemoryRecallChallenge, type PasteCaptureConfig, PasteCollector, type PasteThreshold, type ResponseControlsConfig, type TextAppearanceCallbacks, TextAppearanceDetector, type TextAppearanceDetectorConfig, type TimingThreshold, type TriggerConfig, TypingTestChallenge, type WrapperEvent, type InterventionManager as WrapperInterventionManager, type InterventionResult as WrapperInterventionResult, captureResponseControls, computeFocusMetrics, computeKeystrokeMetrics, computeTimingMetrics, createBehavioralCapture, createChallenge, createExtensionDetector, createInputWrapper, createInterventionManager };