Skip to content

sweetbean.protection

Pluggable protections (bot/agent detection, ...) for SweetBean experiments.

Pass instances to :class:sweetbean.Experiment via protections=[...]. See :mod:sweetbean.protection.protection for the hook contract.

BotDetection

Bases: Protection

Bot/agent detection layer.

Source code in sweetbean/protection/bot_detection.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class BotDetection(Protection):
    """Bot/agent detection layer."""

    name = "bot_detection"

    def __init__(
        self,
        enable_countermeasures: bool = True,
        track_sliders: bool = True,
    ):
        """
        Arguments:
            enable_countermeasures: when False, only passive logging runs —
                no honeypot DOM, no clipboard/devtools blocking, no inline
                traps. Useful for pilots / debugging.
            track_sliders: when True, install a document-level ``input``
                listener that calls ``BotDetection.recordSliderMove()`` for
                every range slider, so per-trial slider stats are captured
                without modifying any stimulus class.
        """
        self.enable_countermeasures = enable_countermeasures
        self.track_sliders = track_sliders

    def runtime_js(self) -> str:
        return _ASSET_PATH.read_text(encoding="utf-8")

    def init_js(self) -> str:
        cm = "true" if self.enable_countermeasures else "false"
        js = f"BotDetection.initialize({cm});"
        if self.track_sliders:
            js += (
                "document.addEventListener('input',function(e){"
                "if(e.target&&e.target.type==='range'){"
                "if(window.BotDetection){BotDetection.recordSliderMove();}}"
                "},true);"
            )
        return js

    def summary_js(self) -> str:
        return "BotDetection.getSummary()"

    def on_load_for_stimulus(self, stimulus) -> str:
        return "if(window.BotDetection){BotDetection.resetTrialTracking();}"

    def on_finish_for_stimulus(self, stimulus) -> str:
        return (
            "if(window.BotDetection){"
            "if(typeof data.rt==='number'){BotDetection.addRT(data.rt);}"
            "Object.assign(data,BotDetection.getTrialInteractionData());"
            "Object.assign(data,BotDetection.getTrialLevelSummary());"
            "}"
        )

__init__(enable_countermeasures=True, track_sliders=True)

Parameters:

Name Type Description Default
enable_countermeasures bool

when False, only passive logging runs — no honeypot DOM, no clipboard/devtools blocking, no inline traps. Useful for pilots / debugging.

True
track_sliders bool

when True, install a document-level input listener that calls BotDetection.recordSliderMove() for every range slider, so per-trial slider stats are captured without modifying any stimulus class.

True
Source code in sweetbean/protection/bot_detection.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def __init__(
    self,
    enable_countermeasures: bool = True,
    track_sliders: bool = True,
):
    """
    Arguments:
        enable_countermeasures: when False, only passive logging runs —
            no honeypot DOM, no clipboard/devtools blocking, no inline
            traps. Useful for pilots / debugging.
        track_sliders: when True, install a document-level ``input``
            listener that calls ``BotDetection.recordSliderMove()`` for
            every range slider, so per-trial slider stats are captured
            without modifying any stimulus class.
    """
    self.enable_countermeasures = enable_countermeasures
    self.track_sliders = track_sliders

Protection

Base class — see module docstring for the hook contract.

Source code in sweetbean/protection/protection.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Protection:
    """Base class — see module docstring for the hook contract."""

    name: str = "protection"

    def head_assets(self) -> str:
        """Extra HTML injected into ``<head>``. Used by ``Experiment.to_html``."""
        return ""

    def runtime_js(self) -> str:
        """JS source emitted before ``initJsPsych``. Typically the protection
        library (IIFE) being inlined into the page."""
        return ""

    def init_js(self) -> str:
        """JS source run after ``initJsPsych`` but before trials run. Typical
        use: call the library's ``initialize`` and register global handlers."""
        return ""

    def summary_js(self) -> str:
        """JS expression that evaluates to a summary object. Empty disables.
        Wired into the experiment's ``on_finish`` so it lands on every row of
        saved data via ``jsPsych.data.addProperties``."""
        return ""

    def on_load_for_stimulus(self, stimulus) -> str:
        """Per-trial JS injected into the stimulus's ``on_load`` callback.

        Return ``""`` to no-op for this stimulus type. Implementations may
        inspect ``stimulus`` (e.g. ``isinstance``) to specialize.
        """
        return ""

    def on_finish_for_stimulus(self, stimulus) -> str:
        """Per-trial JS injected into the stimulus's ``on_finish`` callback.

        ``data`` is in scope and refers to the trial's data row — mutate it
        directly to attach per-trial signals.
        """
        return ""

head_assets()

Extra HTML injected into <head>. Used by Experiment.to_html.

Source code in sweetbean/protection/protection.py
36
37
38
def head_assets(self) -> str:
    """Extra HTML injected into ``<head>``. Used by ``Experiment.to_html``."""
    return ""

init_js()

JS source run after initJsPsych but before trials run. Typical use: call the library's initialize and register global handlers.

Source code in sweetbean/protection/protection.py
45
46
47
48
def init_js(self) -> str:
    """JS source run after ``initJsPsych`` but before trials run. Typical
    use: call the library's ``initialize`` and register global handlers."""
    return ""

on_finish_for_stimulus(stimulus)

Per-trial JS injected into the stimulus's on_finish callback.

data is in scope and refers to the trial's data row — mutate it directly to attach per-trial signals.

Source code in sweetbean/protection/protection.py
64
65
66
67
68
69
70
def on_finish_for_stimulus(self, stimulus) -> str:
    """Per-trial JS injected into the stimulus's ``on_finish`` callback.

    ``data`` is in scope and refers to the trial's data row — mutate it
    directly to attach per-trial signals.
    """
    return ""

on_load_for_stimulus(stimulus)

Per-trial JS injected into the stimulus's on_load callback.

Return "" to no-op for this stimulus type. Implementations may inspect stimulus (e.g. isinstance) to specialize.

Source code in sweetbean/protection/protection.py
56
57
58
59
60
61
62
def on_load_for_stimulus(self, stimulus) -> str:
    """Per-trial JS injected into the stimulus's ``on_load`` callback.

    Return ``""`` to no-op for this stimulus type. Implementations may
    inspect ``stimulus`` (e.g. ``isinstance``) to specialize.
    """
    return ""

runtime_js()

JS source emitted before initJsPsych. Typically the protection library (IIFE) being inlined into the page.

Source code in sweetbean/protection/protection.py
40
41
42
43
def runtime_js(self) -> str:
    """JS source emitted before ``initJsPsych``. Typically the protection
    library (IIFE) being inlined into the page."""
    return ""

summary_js()

JS expression that evaluates to a summary object. Empty disables. Wired into the experiment's on_finish so it lands on every row of saved data via jsPsych.data.addProperties.

Source code in sweetbean/protection/protection.py
50
51
52
53
54
def summary_js(self) -> str:
    """JS expression that evaluates to a summary object. Empty disables.
    Wired into the experiment's ``on_finish`` so it lands on every row of
    saved data via ``jsPsych.data.addProperties``."""
    return ""