diff --git a/matrix_keycloak_bot.py b/matrix_keycloak_bot.py index a22ff13..7a53f7a 100644 --- a/matrix_keycloak_bot.py +++ b/matrix_keycloak_bot.py @@ -12,6 +12,10 @@ from nio import ( RoomSendResponse, InviteMemberEvent, OlmUnverifiedDeviceError, + KeyVerificationStart, + KeyVerificationKey, + KeyVerificationMac, + ToDeviceError, ) # ------------------------------------------------------------------------------ @@ -131,6 +135,26 @@ def get_requestable_groups(username: str) -> tuple[bool, str]: return False, f"Unexpected error: {str(e)}" +# ------------------------------------------------------------------------------ +# Auto-Verification Event Handler +# ------------------------------------------------------------------------------ +async def on_to_device(client: AsyncClient, event): + """Handles incoming interactive SAS key verification events automatically.""" + if isinstance(event, KeyVerificationStart): + print(f"Received key verification request from {event.sender} ({event.from_device}). Accepting...") + resp = await client.accept_key_verification(event.transaction_id) + if isinstance(resp, ToDeviceError): + print(f"Failed to accept verification: {resp}") + + elif isinstance(event, KeyVerificationKey): + print(f"Received SAS key from {event.sender}. Auto-confirming...") + resp = await client.confirm_short_auth_string(event.transaction_id) + if isinstance(resp, ToDeviceError): + print(f"Failed to confirm SAS: {resp}") + + elif isinstance(event, KeyVerificationMac): + print(f"✅ Key verification successfully completed with {event.sender} ({event.from_device})!") + # ------------------------------------------------------------------------------ # Matrix Message Sending Wrappers # ------------------------------------------------------------------------------ @@ -354,6 +378,10 @@ async def main(): client.add_event_callback( lambda room, event: on_invite(client, room, event), InviteMemberEvent ) + client.add_to_device_callback( + lambda event: on_to_device(client, event), + (KeyVerificationStart, KeyVerificationKey, KeyVerificationMac), + ) print(f"Connecting to Matrix homeserver {MATRIX_HOMESERVER}...") await client.login(MATRIX_BOT_PASSWORD)