Add auto-SAS verification hook

This commit is contained in:
Astra Logical 2026-07-23 10:23:09 -04:00
parent 99af2b483a
commit bda6076240

View file

@ -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)