From 2a417445a7f9d5f4018f3c22812358b5561605a6 Mon Sep 17 00:00:00 2001
From: Him188 <Him188@mamoe.net>
Date: Mon, 2 May 2022 10:12:34 +0100
Subject: [PATCH] Invalidate account.secretes on failure to lo in

---
 .../kotlin/network/components/SsoProcessor.kt | 26 ++++++++++++-------
 1 file changed, 16 insertions(+), 10 deletions(-)

diff --git a/mirai-core/src/commonMain/kotlin/network/components/SsoProcessor.kt b/mirai-core/src/commonMain/kotlin/network/components/SsoProcessor.kt
index d54c60df6..d240b1b33 100644
--- a/mirai-core/src/commonMain/kotlin/network/components/SsoProcessor.kt
+++ b/mirai-core/src/commonMain/kotlin/network/components/SsoProcessor.kt
@@ -119,18 +119,24 @@ internal class SsoProcessorImpl(
     @Throws(LoginFailedException::class)
     override suspend fun login(handler: NetworkHandler) = withExceptionCollector {
         components[BdhSessionSyncer].loadServerListFromCache()
-        if (client.wLoginSigInfoInitialized) {
-            ssoContext.bot.components[EcdhInitialPublicKeyUpdater].refreshInitialPublicKeyAndApplyECDH()
-            kotlin.runCatching {
-                FastLoginImpl(handler).doLogin()
-            }.onFailure { e ->
-                collectException(e)
+        try {
+            if (client.wLoginSigInfoInitialized) {
+                ssoContext.bot.components[EcdhInitialPublicKeyUpdater].refreshInitialPublicKeyAndApplyECDH()
+                kotlin.runCatching {
+                    FastLoginImpl(handler).doLogin()
+                }.onFailure { e ->
+                    collectException(e)
+                    SlowLoginImpl(handler).doLogin()
+                }
+            } else {
+                client = createClient(ssoContext.bot)
+                ssoContext.bot.components[EcdhInitialPublicKeyUpdater].refreshInitialPublicKeyAndApplyECDH()
                 SlowLoginImpl(handler).doLogin()
             }
-        } else {
-            client = createClient(ssoContext.bot)
-            ssoContext.bot.components[EcdhInitialPublicKeyUpdater].refreshInitialPublicKeyAndApplyECDH()
-            SlowLoginImpl(handler).doLogin()
+        } catch (e: Exception) {
+            // Failed to log in, invalidate secrets.
+            ssoContext.bot.components[AccountSecretsManager].invalidate()
+            throw e
         }
         components[AccountSecretsManager].saveSecrets(ssoContext.account, AccountSecretsImpl(client))
         registerClientOnline(handler)