@@ -79,8 +79,9 @@ def __init__(
7979 self ._http_ssl_param = None
8080 self ._waiting_auth = False
8181
82- self ._keyexchange_mode = KEYEXCHANGE_MODES [ 0 ]
82+ self ._keyexchange_mode_idx = 0
8383 self ._auth_mode_idx = 0
84+ self ._auth_failed_event = asyncio .Event ()
8485
8586 self .ready = asyncio .Event ()
8687 self ._handshake_lock = asyncio .Lock ()
@@ -118,7 +119,21 @@ def shutdown(self):
118119
119120 async def wait_until_ready (self , timeout = 45 ):
120121 """Wait until connection is authenticated and LoxAPP3 is loaded."""
121- await asyncio .wait_for (self .ready .wait (), timeout = timeout )
122+ ready_task = self .loop .create_task (self .ready .wait ())
123+ failed_task = self .loop .create_task (self ._auth_failed_event .wait ())
124+ done , pending = await asyncio .wait (
125+ {ready_task , failed_task },
126+ timeout = timeout ,
127+ return_when = asyncio .FIRST_COMPLETED ,
128+ )
129+ for task in pending :
130+ task .cancel ()
131+
132+ if not done :
133+ raise TimeoutError ("Timed out waiting for miniserver readiness" )
134+ if failed_task in done and failed_task .result ():
135+ raise PermissionError ("Miniserver authentication failed" )
136+
122137 if self ._keep_alive_task is None :
123138 self ._keep_alive_task = self .loop .create_task (self .keep_alive ())
124139
@@ -127,12 +142,17 @@ def async_session_handler(self, state):
127142 if state == STATE_RUNNING :
128143 self ._connected = True
129144 self ._authenticated = False
145+ self ._waiting_auth = False
146+ self ._auth_mode_idx = 0
147+ self ._keyexchange_mode_idx = 0
148+ self ._auth_failed_event .clear ()
130149 self .ready .clear ()
131150 self .async_connection_status_callback (False )
132151 self .loop .create_task (self ._async_begin_handshake ())
133152 else :
134153 self ._connected = False
135154 self ._authenticated = False
155+ self ._waiting_auth = False
136156 self .ready .clear ()
137157 self .async_connection_status_callback (False )
138158
@@ -149,7 +169,7 @@ async def _async_begin_handshake(self):
149169 _LOGGER .debug ("Skip keyexchange send because websocket is not ready" )
150170 return
151171
152- self .wsclient . send ( f"jdev/sys/keyexchange/ { self . _encrypted_session_key () } " )
172+ self ._send_keyexchange ( )
153173 except Exception as err : # pylint: disable=broad-except
154174 _LOGGER .error ("Handshake start failed: %s" , err )
155175
@@ -212,10 +232,37 @@ def _prepare_session_crypto(self):
212232 self ._command_salt = None
213233 self ._waiting_auth = False
214234
235+ def _keyexchange_mode (self ):
236+ return KEYEXCHANGE_MODES [self ._keyexchange_mode_idx ]
237+
238+ def _send_keyexchange (self ):
239+ self .wsclient .send (f"jdev/sys/keyexchange/{ self ._encrypted_session_key ()} " )
240+
241+ def _try_next_keyexchange_mode (self ) -> bool :
242+ """Advance keyexchange mode and resend while modes remain."""
243+ current_idx = self ._keyexchange_mode_idx
244+ current_mode = KEYEXCHANGE_MODES [current_idx ]
245+ next_idx = current_idx + 1
246+ if next_idx >= len (KEYEXCHANGE_MODES ):
247+ _LOGGER .debug ("All keyexchange modes exhausted; authentication failed" )
248+ self ._auth_failed_event .set ()
249+ return False
250+
251+ next_mode = KEYEXCHANGE_MODES [next_idx ]
252+ self ._keyexchange_mode_idx = next_idx
253+ self ._prepare_session_crypto ()
254+ _LOGGER .debug (
255+ "Keyexchange rejected with 401 using mode '%s'; retrying mode '%s'" ,
256+ current_mode ,
257+ next_mode ,
258+ )
259+ self ._send_keyexchange ()
260+ return True
261+
215262 def _encrypted_session_key (self ):
216263 payload = f"{ self ._aes_key_hex } :{ self ._aes_iv_hex } " .encode ("utf-8" )
217264
218- mode = self ._keyexchange_mode
265+ mode = self ._keyexchange_mode ()
219266 if mode .startswith ("oaep" ):
220267 cipher = PKCS1_OAEP .new (self .public_key )
221268 else :
@@ -273,6 +320,7 @@ def _send_next_auth_mode(self) -> bool:
273320 if idx >= len (AUTH_MODES ):
274321 _LOGGER .debug ("All auth modes exhausted without success" )
275322 self ._waiting_auth = False
323+ self ._auth_failed_event .set ()
276324 return False
277325
278326 endpoint , hash_mode , permissions = AUTH_MODES [idx ]
@@ -329,23 +377,25 @@ class _FallbackHeader:
329377 code = str (ll .get ("Code" , ll .get ("code" , "" )))
330378 value = ll .get ("value" )
331379
332- if control :
380+ if control and any (
381+ token in control
382+ for token in (
383+ "keyexchange" ,
384+ "getkey2" ,
385+ "getjwt" ,
386+ "gettoken" ,
387+ "LoxAPP3.json" ,
388+ "enablebinstatusupdate" ,
389+ )
390+ ):
333391 _LOGGER .debug ("Processed websocket control='%s' code='%s'" , control , code )
334392
335393 if "keyexchange" in control :
336394 if code == "401" :
337- try :
338- idx = KEYEXCHANGE_MODES .index (self ._keyexchange_mode )
339- except ValueError :
340- idx = 0
341- self ._keyexchange_mode = KEYEXCHANGE_MODES [(idx + 1 ) % len (KEYEXCHANGE_MODES )]
342- _LOGGER .debug (
343- "Keyexchange rejected with 401 using mode '%s'; next reconnect will try '%s'" ,
344- KEYEXCHANGE_MODES [idx ],
345- self ._keyexchange_mode ,
346- )
395+ self ._try_next_keyexchange_mode ()
347396 return
348397
398+ self ._auth_mode_idx = 0
349399 self .wsclient .send (self .encrypt_command (f"jdev/sys/getkey2/{ self .username } " ))
350400 return
351401
@@ -362,21 +412,24 @@ class _FallbackHeader:
362412 raw_alg ,
363413 self ._server_hash_alg ,
364414 )
415+ self ._auth_mode_idx = 0
365416 self ._send_next_auth_mode ()
366417 return
367418
368419 if "getjwt" in control or "gettoken" in control :
369420 self ._waiting_auth = False
370421 if code != "200" :
371422 _LOGGER .debug (
372- "Auth endpoint rejected (control='%s' code=%s); next reconnect uses auth mode index=%s" ,
423+ "Auth endpoint rejected (control='%s' code=%s); trying next auth mode index=%s" ,
373424 control ,
374425 code ,
375426 self ._auth_mode_idx ,
376427 )
428+ self ._send_next_auth_mode ()
377429 return
378430
379431 self ._auth_mode_idx = 0
432+ self ._auth_failed_event .clear ()
380433 self ._token = value .get ("token" ) if isinstance (value , dict ) else None
381434 self ._authenticated = True
382435 self .wsclient .send ("data/LoxAPP3.json" )
@@ -386,9 +439,10 @@ class _FallbackHeader:
386439 if self ._waiting_auth :
387440 self ._waiting_auth = False
388441 _LOGGER .debug (
389- "Encrypted auth response 401; next reconnect uses auth mode index=%s" ,
442+ "Encrypted auth response 401; trying next auth mode index=%s" ,
390443 self ._auth_mode_idx ,
391444 )
445+ self ._send_next_auth_mode ()
392446 return
393447
394448 if "LoxAPP3.json" in control :
0 commit comments