API Reference
Signatures and docstrings below are generated from the current source. The CLI
parses configuration and supplies defaults before constructing these objects;
Python callers must do that themselves. In particular, TCP constructors default
to enable_tls=False: pass True explicitly for verified TLS. UDP
constructors require a password and force TLS control.
Applications embedding the client must initialize and clean up GamepadInput
and manage run() / shutdown(). There is no public send_input method.
For wire formats see Protocol, not the message constructors alone.
Examples
Password challenge-response with a plaintext client and hashed server:
from padrelay.security.auth import Authenticator
server = Authenticator(Authenticator.hash_password("example-password"))
client = Authenticator("example-password")
client.set_parameters(server.salt, server.iterations)
challenge = server.generate_tcp_challenge()
response = client.generate_tcp_response(challenge)
assert server.verify_tcp_response(challenge, response)
An input message serializes a complete canonical state:
import json
from padrelay.core.controller_state import InputState
from padrelay.protocol.messages import InputMessage, validate_input_message
message = InputMessage(InputState(frozenset({"a", "dpad_up"}),
left_y=0.5, trigger_right=0.7))
assert validate_input_message(json.loads(message.to_json()))
Admission and request budgets use ConnectionTracker; there is no separate
RateLimiter class. Reservation and authentication counts are separate:
from padrelay.security.rate_limiting import ConnectionTracker
tracker = ConnectionTracker(max_connections=1, max_requests=2)
peer = ("192.0.2.1", 1234)
assert tracker.reserve(peer)
tracker.authenticate(peer)
assert tracker.active_connections == 1
assert not tracker.is_rate_limited(peer)
tracker.disconnect(peer)
Use TLS and Certificate Trust for certificate generation. Session parameters
are secret and may be transmitted only inside authenticated TLS; creating a
UDPSession alone does not establish peer trust.
Client
Application
Client application
- class padrelay.client.client_app.VirtualGamepadClient(server_ip: str, server_port: int, protocol: str, gamepad: GamepadInput, update_rate: int = 60, password: str | None = None, config: object | None = None, enable_tls: bool = False, ca_path: Path | None = None, server_hostname: str | None = None)[source]
Client controller
- __init__(server_ip: str, server_port: int, protocol: str, gamepad: GamepadInput, update_rate: int = 60, password: str | None = None, config: object | None = None, enable_tls: bool = False, ca_path: Path | None = None, server_hostname: str | None = None) None[source]
Construct the client and configure networking
Input
Physical device lifecycle and client-side normalization.
Constants
Constants used by the client portion of the bridge
Controller Profiles
Validated physical bindings and atomic, device-bound profile persistence.
- class padrelay.client.controller_profile.DeviceIdentity(guid: str, name: str, platform: str, buttons: int, axes: int, hats: int)[source]
-
- classmethod read(joystick: Any) DeviceIdentity[source]
- class padrelay.client.controller_profile.ControllerProfile(identity: DeviceIdentity, bindings: dict, dead_zone: float = 0.1, trigger_threshold: float = 0.05)[source]
Own a validated copy of bindings; no caller can mutate the live profile.
- __init__(identity: DeviceIdentity, bindings: dict, dead_zone: float = 0.1, trigger_threshold: float = 0.05)[source]
- read(joystick: Any) InputState[source]
- classmethod load(path: Path) ControllerProfile[source]
Server
Application
Server application for the PadRelay
- class padrelay.server.server_app.VirtualGamepadServer(host, port, password, gamepad_type='xbox360', config=None, rate_limit_window=60, max_requests=100, block_duration=2, protocol='tcp', enable_tls=False, cert_path: Path | None = None, key_path: Path | None = None)[source]
Server controller
- __init__(host, port, password, gamepad_type='xbox360', config=None, rate_limit_window=60, max_requests=100, block_duration=2, protocol='tcp', enable_tls=False, cert_path: Path | None = None, key_path: Path | None = None)[source]
Construct the server instance
- Parameters:
host – Host to bind to
port – Port to listen on
password – Authentication password
gamepad_type – Type of virtual gamepad to create
config – Configuration object (optional)
rate_limit_window – Time window for rate limiting in seconds
max_requests – Maximum number of requests per window
block_duration – How long to block clients that exceed the rate limit
protocol – Transport protocol (‘tcp’ or ‘udp’)
enable_tls – Enable TLS for TCP data; UDP control always requires TLS
cert_path – Path to TLS certificate (optional)
key_path – Path to TLS private key (optional)
Input Processing
Apply canonical input snapshots and expire stale input independently of heartbeat.
- class padrelay.server.input_processor.GamepadHandler(gamepad: VirtualGamepad, config: ConfigParser | None = None)[source]
- __init__(gamepad: VirtualGamepad, config: ConfigParser | None = None)[source]
Virtual Gamepad
The only adapter that knows vgamepad/ViGEm target details.
Constants
Constants used by the server
Protocol
TCP
TCP protocol utilities for the PadRelay
UDP
UDP protocol utilities for the PadRelay
- class padrelay.protocol.udp.UDPProtocolHandler(transport=None, remote_addr=None)[source]
Handle UDP communication on the client
- class padrelay.protocol.udp.UDPServerProtocol(gamepad_handler, sessions=None, tracker=None)[source]
Accept only encrypted input for a live TLS-authenticated session.
Messages
Message types and validators for the PadRelay
- class padrelay.protocol.messages.InputMessage(state: InputState | None = None)[source]
Serialize exactly one canonical state; physical layouts never reach the wire.
- __init__(state: InputState | None = None)[source]
Create a message of
msg_type
- class padrelay.protocol.messages.AuthFailedMessage(message='Authentication failed')[source]
Authentication failed
Constants
Constants shared by client and server.
Security
Authentication
Authentication utilities for the PadRelay
- class padrelay.security.auth.Authenticator(password: str | None = None)[source]
Authentication handler for both client and server
- PBKDF2_PREFIX = 'pbkdf2_sha256'
- DEFAULT_ITERATIONS = 100000
- MIN_ITERATIONS = 100000
- MAX_ITERATIONS = 600000
- MAX_SALT_LENGTH = 128
- __init__(password: str | None = None) None[source]
Initialize an authenticator
- Parameters:
password – Plaintext password or encoded PBKDF2 hash (optional)
- static validate_parameters(salt: str, iterations: int) None[source]
Reject unsupported PBKDF2 work factors and salt sizes before hashing.
- async set_parameters_async(salt: str, iterations: int) None[source]
Validate before scheduling; commit only after completed derivation.
- static hash_password(password: str, iterations: int = 100000) str[source]
Return a PBKDF2 hash string for a password
- generate_tcp_challenge() str[source]
Generate a challenge for TCP authentication
- Returns:
Random challenge string
- Return type:
UDP Sessions
TLS-provisioned one-way AES-GCM datagrams with bounded replay state.
- class padrelay.security.udp_session.UDPSession(session_id: bytes, key: bytes, peer_ip: str = '')[source]
Encrypt client input with a fresh key from its TLS control connection.
- MAGIC = b'PRU2'
- HEADER_SIZE = 28
- WINDOW = 64
- LIFETIME = 600
- MAX_SEQUENCE = 4294967296
- classmethod create(peer_ip: str) UDPSession[source]
- classmethod from_parameters(parameters: dict) UDPSession[source]
Admission Limits
Bounded IP/global token buckets and atomic connection reservations.
- class padrelay.security.rate_limiting.ConnectionTracker(max_connections: int = 1, rate_limit_window: int = 60, max_requests: int = 100, block_duration: int = 2, max_tracked_ips: int = 1024, global_max_requests: int = 12000)[source]
Admission operations run synchronously on the server event loop.
TLS
TLS/SSL utilities for secure communication
- padrelay.security.tls_utils.get_default_cert_paths() Tuple[Path, Path][source]
Get default paths for certificate and key files
- Returns:
Tuple of (cert_path, key_path)
- padrelay.security.tls_utils.ensure_cert_dir_exists() Path[source]
Ensure certificate directory exists with proper permissions
- Returns:
Path to certificate directory
- padrelay.security.tls_utils.generate_self_signed_cert(cert_path: Path | None = None, key_path: Path | None = None, days_valid: int = 365, country: str = 'US', state: str = 'State', locality: str = 'City', organization: str = 'PadRelay', common_name: str = 'localhost') Tuple[Path, Path][source]
Generate a self-signed certificate for TLS
- Parameters:
cert_path – Path where certificate will be saved (default: ~/.padrelay/certs/server.crt)
key_path – Path where private key will be saved (default: ~/.padrelay/certs/server.key)
days_valid – Number of days the certificate is valid (default: 365)
country – Country code for certificate (default: US)
state – State/Province for certificate
locality – City for certificate
organization – Organization name for certificate
common_name – Common name (hostname) for certificate
- Returns:
Tuple of (cert_path, key_path)
- padrelay.security.tls_utils.create_server_ssl_context(cert_path: Path | None = None, key_path: Path | None = None, auto_generate: bool = True) SSLContext[source]
Create SSL context for server
- Parameters:
cert_path – Path to certificate file
key_path – Path to private key file
auto_generate – If True, automatically generate certificate if not found
- Returns:
SSLContext. Missing, incomplete or invalid identities raise an error.
- padrelay.security.tls_utils.create_client_ssl_context(verify_cert: bool = True, ca_path: Path | None = None) SSLContext[source]
Create SSL context for client
- Parameters:
verify_cert – Verify server identity; False is an explicit insecure opt-out.
ca_path – Trusted CA bundle or self-signed server certificate. If omitted, use the system trust store. An invalid path always raises an error.
- Returns:
SSLContext configured for client
- padrelay.security.tls_utils.check_cert_expiration(cert_path: Path | None = None) datetime | None[source]
Check certificate expiration date
- Parameters:
cert_path – Path to certificate file
- Returns:
Expiration datetime or None if cert doesn’t exist or error
- padrelay.security.tls_utils.warn_if_cert_expiring_soon(cert_path: Path | None = None, days_warning: int = 30) bool[source]
Check if certificate is expiring soon and warn
- Parameters:
cert_path – Path to certificate file
days_warning – Warn if certificate expires within this many days
- Returns:
True if certificate is expiring soon, False otherwise
Password Warnings
Password strength checking utilities
- padrelay.security.password_strength.check_password_strength(password: str) Tuple[str, int, List[str]][source]
Check password strength and provide recommendations
- Parameters:
password – The password to check
- Returns:
Tuple of (strength_level, score, recommendations) - strength_level: “very_weak”, “weak”, “medium”, “strong”, “very_strong” - score: Integer score from 0-100 - recommendations: List of improvement suggestions
Core
Controller State
The single logical input model shared by capture, protocol and output.
- class padrelay.core.controller_state.InputState(pressed: frozenset[str] = frozenset({}), left_x: float = 0.0, left_y: float = 0.0, right_x: float = 0.0, right_y: float = 0.0, trigger_left: float = 0.0, trigger_right: float = 0.0)[source]
Full snapshot: positive stick Y is up; triggers are released at zero.
- classmethod from_message(message: Any) InputState[source]
Configuration
Helpers for reading and validating configuration
- padrelay.core.config.validate_controller_config(config: ConfigParser | None) None[source]
Reject obsolete physical maps before native output allocation.
- padrelay.core.config.load_config(config_path: str) ConfigParser | None[source]
Exceptions
Exception hierarchy for the PadRelay
- exception padrelay.core.exceptions.GamepadBridgeError(message: str = 'An error occurred in the PadRelay', details: Any | None = None)[source]
Base exception for bridge errors
- exception padrelay.core.exceptions.ProtocolError(message: str = 'Protocol error', details: Any | None = None, protocol_version: str | None = None)[source]
Protocol-related error
- exception padrelay.core.exceptions.AuthenticationError(message: str = 'Authentication failed', details: Any | None = None, addr: str | None = None)[source]
Authentication failed
- exception padrelay.core.exceptions.ConnectionError(message: str = 'Connection error', details: Any | None = None, addr: str | None = None, reconnect_attempt: int | None = None)[source]
Connection related error
- exception padrelay.core.exceptions.ConfigurationError(message: str = 'Configuration error', details: Any | None = None, config_file: str | None = None, setting: str | None = None)[source]
Configuration problem
Logging
Logging utilities
- padrelay.core.logging_utils.get_logger(name: str) Logger[source]
Return a
logging.Loggerconfigured for the project
Entry Points
Client
Entry point for the PadRelay client
Server
Entry point for the PadRelay server
Key Mapper
Capture a device-bound client profile using terminal prompts and raw inputs.