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

async run() → bool[source]

Run the client using the chosen protocol

async shutdown() → bool[source]

Shut down tasks and clean up resources

Input

Physical device lifecycle and client-side normalization.

class padrelay.client.input.GamepadInput(joystick_index: int = 0, profile_path: Path | None = None)[source]

One selected device; profiles and reconnect identity belong to this instance.

__init__(joystick_index: int = 0, profile_path: Path | None = None)[source]
initialize() → bool[source]
is_available() → bool[source]
poll() → dict | None[source]
cleanup() → None[source]

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]
guid: str
name: str
platform: str
buttons: int
axes: int
hats: int
classmethod read(joystick: Any) → DeviceIdentity[source]
__init__(guid: str, name: str, platform: str, buttons: int, axes: int, hats: int) → None
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]
save(path: Path) → None[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)

async run()[source]

Run the server with the configured protocol

async shutdown()[source]

Close all connections and shut down

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]
reset() → None[source]
process(message: dict) → None[source]
expire_input() → None[source]

Virtual Gamepad

The only adapter that knows vgamepad/ViGEm target details.

class padrelay.server.virtual_gamepad.VirtualGamepad(gamepad_type: str = 'xbox360', config: ConfigParser | None = None)[source]
__init__(gamepad_type: str = 'xbox360', config: ConfigParser | None = None)[source]
reset_gamepad_state() → None[source]
apply_state(state: InputState) → None[source]

Constants

Constants used by the server

Protocol

TCP

TCP protocol utilities for the PadRelay

class padrelay.protocol.tcp.TCPProtocolHandler(reader=None, writer=None)[source]

Handle TCP communication

__init__(reader=None, writer=None)[source]

Initialize with optional reader/writer

async read_message()[source]

Read and decode a length-prefixed message

async send_message(message)[source]

Send a length-prefixed message

async drain()[source]

Flush the writer buffer

close()[source]

Close the writer connection

async wait_closed() → None[source]

Allow one second for graceful close, then release the transport.

UDP

UDP protocol utilities for the PadRelay

class padrelay.protocol.udp.UDPProtocolHandler(transport=None, remote_addr=None)[source]

Handle UDP communication on the client

__init__(transport=None, remote_addr=None)[source]

Initialize with optional transport and address

send_message(message)[source]

Send a UDP message

close()[source]

Close the UDP transport

class padrelay.protocol.udp.UDPServerProtocol(gamepad_handler, sessions=None, tracker=None)[source]

Accept only encrypted input for a live TLS-authenticated session.

__init__(gamepad_handler, sessions=None, tracker=None)[source]
connection_made(transport)[source]

Called when a connection is made.

The argument is the transport representing the pipe connection. To receive data, wait for data_received() calls. When the connection is closed, connection_lost() is called.

datagram_received(data, addr)[source]

Called when some datagram is received.

error_received(exc: Exception) → None[source]

Called when a send or receive operation raises an OSError.

(Other than BlockingIOError or InterruptedError.)

Messages

Message types and validators for the PadRelay

class padrelay.protocol.messages.BaseMessage(msg_type, *, payload=None)[source]

Base message class

__init__(msg_type, *, payload=None)[source]

Create a message of msg_type

to_json()[source]

Return a JSON representation

to_bytes()[source]

Return a UTF-8 encoded bytes object

classmethod from_dict(data)[source]

Create a message from data

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

classmethod from_dict(data)[source]

Create a message from data

class padrelay.protocol.messages.HeartbeatMessage[source]

Heartbeat ping

__init__()[source]

Create a heartbeat message

classmethod from_dict(data)[source]

Build from data

class padrelay.protocol.messages.HeartbeatAckMessage[source]

Heartbeat acknowledgment

__init__()[source]

Create an acknowledgment message

classmethod from_dict(data)[source]

Build from data

class padrelay.protocol.messages.AuthChallengeMessage(challenge)[source]

Authentication challenge

__init__(challenge)[source]

Create a challenge with challenge string

classmethod from_dict(data)[source]

Build from data

class padrelay.protocol.messages.AuthResponseMessage(response)[source]

Authentication response

__init__(response)[source]

Create a response containing response

classmethod from_dict(data)[source]

Build from data

class padrelay.protocol.messages.AuthSuccessMessage[source]

Authentication success

__init__()[source]

Create a success message

classmethod from_dict(data)[source]

Build from data

class padrelay.protocol.messages.AuthFailedMessage(message='Authentication failed')[source]

Authentication failed

__init__(message='Authentication failed')[source]

Create a failure message

classmethod from_dict(data)[source]

Build from data

class padrelay.protocol.messages.ErrorMessage(message='Unknown error')[source]

Represents an error

__init__(message='Unknown error')[source]

Create an error message

classmethod from_dict(data)[source]

Build from data

padrelay.protocol.messages.validate_input_message(message)[source]

Return True if message is a valid input payload

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.

set_parameters(salt: str, iterations: int) → None[source]
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

get_hash_string() → str | None[source]
verify_password(password: str) → bool[source]
generate_tcp_challenge() → str[source]

Generate a challenge for TCP authentication

Returns:

Random challenge string

Return type:

str

verify_tcp_response(challenge: str, response: str) → bool[source]

Verify a TCP authentication response

Parameters:
  • challenge – Challenge string

  • response – HMAC response to verify

Returns:

True if response is valid, False otherwise

Return type:

bool

generate_tcp_response(challenge: str) → str[source]

Generate a response to a TCP authentication challenge

Parameters:

challenge – Challenge string

Returns:

HMAC response

Return type:

str

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
__init__(session_id: bytes, key: bytes, peer_ip: str = '') → None[source]
classmethod create(peer_ip: str) → UDPSession[source]
parameters() → dict[source]

Send only inside the authenticated TLS control stream.

classmethod from_parameters(parameters: dict) → UDPSession[source]
encode(message: dict) → bytes[source]
decode(packet: bytes) → dict | None[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.

__init__(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) → None[source]
property active_connections: int
property pending_connections: int
can_connect(addr: tuple) → bool[source]
reserve(addr: tuple) → bool[source]

Claim a connection slot synchronously before network waits.

authenticate(addr: tuple) → None[source]
disconnect(addr: tuple) → None[source]
is_rate_limited(addr: tuple) → bool[source]
is_blocked(addr: tuple) → bool[source]

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

padrelay.security.password_strength.warn_weak_password(password: str) → bool[source]

Check password strength and warn if weak

Parameters:

password – The password to check

Returns:

True if password is acceptable, False if very weak

padrelay.security.password_strength.generate_password_suggestion() → str[source]

Generate a strong password suggestion

Returns:

A suggested strong password

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.

pressed: frozenset[str]
left_x: float
left_y: float
right_x: float
right_y: float
trigger_left: float
trigger_right: float
to_message() → dict[str, Any][source]
classmethod from_message(message: Any) → InputState[source]
__init__(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) → None

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]
padrelay.core.config.parse_client_args() → Tuple[Namespace, ConfigParser | None][source]
padrelay.core.config.parse_server_args() → Tuple[Namespace, ConfigParser | None][source]
padrelay.core.config.validate_server_config(args: Namespace, config_obj: ConfigParser | None) → None[source]

Validate the server configuration arguments

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

__init__(message: str = 'An error occurred in the PadRelay', details: Any | None = None) → None[source]
exception padrelay.core.exceptions.ProtocolError(message: str = 'Protocol error', details: Any | None = None, protocol_version: str | None = None)[source]

Protocol-related error

__init__(message: str = 'Protocol error', details: Any | None = None, protocol_version: str | None = None) → None[source]
exception padrelay.core.exceptions.AuthenticationError(message: str = 'Authentication failed', details: Any | None = None, addr: str | None = None)[source]

Authentication failed

__init__(message: str = 'Authentication failed', details: Any | None = None, addr: str | None = None) → None[source]
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

__init__(message: str = 'Connection error', details: Any | None = None, addr: str | None = None, reconnect_attempt: int | None = None) → None[source]
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

__init__(message: str = 'Configuration error', details: Any | None = None, config_file: str | None = None, setting: str | None = None) → None[source]
exception padrelay.core.exceptions.InputError(message: str = 'Input error', details: Any | None = None, input_type: str | None = None, input_value: Any | None = None)[source]

Gamepad input error

__init__(message: str = 'Input error', details: Any | None = None, input_type: str | None = None, input_value: Any | None = None) → None[source]

Logging

Logging utilities

padrelay.core.logging_utils.get_logger(name: str) → Logger[source]

Return a logging.Logger configured for the project

padrelay.core.logging_utils.sanitize_for_logging(value: str, max_length: int = 200) → str[source]

Sanitize user input before logging to prevent log injection

Parameters:
  • value – The string to sanitize

  • max_length – Maximum length of the output string

Returns:

Sanitized string safe for logging

Entry Points

Client

Entry point for the PadRelay client

async padrelay.scripts.client.async_main()[source]
padrelay.scripts.client.main()[source]

Server

Entry point for the PadRelay server

async padrelay.scripts.server.async_main()[source]
padrelay.scripts.server.main()[source]

Key Mapper

Capture a device-bound client profile using terminal prompts and raw inputs.

class padrelay.scripts.key_mapper.ControllerMapper(output_path: str, polling_interval: float = 0.01, joystick_index: int = 0)[source]
__init__(output_path: str, polling_interval: float = 0.01, joystick_index: int = 0)[source]
detect_controller() → bool[source]
check_for_skip() → bool[source]
capture_button(timeout: float = 20) → dict | None[source]
capture_axis(timeout: float = 5, *, bidirectional: bool = False) → dict | None[source]
generate_config() → None[source]
verify_mapping() → None[source]
run() → None[source]
padrelay.scripts.key_mapper.main() → None[source]