From f93143c133ce7ec549f068019563add6a141728d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20G=C3=B6ls?=
<6608231+Abrynos@users.noreply.github.com>
Date: Thu, 14 Oct 2021 23:41:12 +0200
Subject: [PATCH] Add ASF 2FA service endpoints (#2426)
* Add ASF 2FA service endpoints
* Misc.
* Move back to .../TwoFactorAuthentication
* Remove duplicate endpoints
* Remove now useless constructor
* Apply feedback
---
.../IPC/Controllers/Api/BotController.cs | 66 -------
.../Api/TwoFactorAuthenticationController.cs | 167 ++++++++++++++++++
ArchiSteamFarm/Steam/Bot.cs | 49 ++++-
3 files changed, 211 insertions(+), 71 deletions(-)
create mode 100644 ArchiSteamFarm/IPC/Controllers/Api/TwoFactorAuthenticationController.cs
diff --git a/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs b/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs
index ef27512ac..00e79b613 100644
--- a/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs
+++ b/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs
@@ -458,71 +458,5 @@ namespace ArchiSteamFarm.IPC.Controllers.Api {
return Ok(new GenericResponse(results.All(static result => result.Success), string.Join(Environment.NewLine, results.Select(static result => result.Message))));
}
-
- ///
- /// Handles 2FA confirmations of given bots, requires ASF 2FA module to be active on them.
- ///
- [HttpPost("{botNames:required}/TwoFactorAuthentication/Confirmations")]
- [ProducesResponseType(typeof(GenericResponse>>>), (int) HttpStatusCode.OK)]
- [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
- public async Task> TwoFactorAuthenticationConfirmationsPost(string botNames, [FromBody] TwoFactorAuthenticationConfirmationsRequest request) {
- if (string.IsNullOrEmpty(botNames)) {
- throw new ArgumentNullException(nameof(botNames));
- }
-
- if (request == null) {
- throw new ArgumentNullException(nameof(request));
- }
-
- if (request.AcceptedType.HasValue && ((request.AcceptedType.Value == Confirmation.EType.Unknown) || !Enum.IsDefined(typeof(Confirmation.EType), request.AcceptedType.Value))) {
- return BadRequest(new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsInvalid, nameof(request.AcceptedType))));
- }
-
- HashSet? bots = Bot.GetBots(botNames);
-
- if ((bots == null) || (bots.Count == 0)) {
- return BadRequest(new GenericResponse>>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
- }
-
- IList<(bool Success, IReadOnlyCollection? HandledConfirmations, string Message)> results = await Utilities.InParallel(bots.Select(bot => bot.Actions.HandleTwoFactorAuthenticationConfirmations(request.Accept, request.AcceptedType, request.AcceptedCreatorIDs.Count > 0 ? request.AcceptedCreatorIDs : null, request.WaitIfNeeded))).ConfigureAwait(false);
-
- Dictionary>> result = new(bots.Count, Bot.BotsComparer);
-
- foreach (Bot bot in bots) {
- (bool success, IReadOnlyCollection? handledConfirmations, string message) = results[result.Count];
- result[bot.BotName] = new GenericResponse>(success, message, handledConfirmations);
- }
-
- return Ok(new GenericResponse>>>(result));
- }
-
- ///
- /// Fetches 2FA tokens of given bots, requires ASF 2FA module to be active on them.
- ///
- [HttpGet("{botNames:required}/TwoFactorAuthentication/Token")]
- [ProducesResponseType(typeof(GenericResponse>>), (int) HttpStatusCode.OK)]
- [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
- public async Task> TwoFactorAuthenticationTokenGet(string botNames) {
- if (string.IsNullOrEmpty(botNames)) {
- throw new ArgumentNullException(nameof(botNames));
- }
-
- HashSet? bots = Bot.GetBots(botNames);
-
- if ((bots == null) || (bots.Count == 0)) {
- return BadRequest(new GenericResponse>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
- }
-
- IList<(bool Success, string? Token, string Message)> results = await Utilities.InParallel(bots.Select(static bot => bot.Actions.GenerateTwoFactorAuthenticationToken())).ConfigureAwait(false);
-
- Dictionary> result = new(bots.Count, Bot.BotsComparer);
-
- foreach (Bot bot in bots) {
- (bool success, string? token, string message) = results[result.Count];
- result[bot.BotName] = new GenericResponse(success, message, token);
- }
-
- return Ok(new GenericResponse>>(result));
- }
}
}
diff --git a/ArchiSteamFarm/IPC/Controllers/Api/TwoFactorAuthenticationController.cs b/ArchiSteamFarm/IPC/Controllers/Api/TwoFactorAuthenticationController.cs
new file mode 100644
index 000000000..024eb9d83
--- /dev/null
+++ b/ArchiSteamFarm/IPC/Controllers/Api/TwoFactorAuthenticationController.cs
@@ -0,0 +1,167 @@
+// _ _ _ ____ _ _____
+// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
+// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
+// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
+// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
+// |
+// Copyright 2015-2021 Łukasz "JustArchi" Domeradzki
+// Contact: JustArchi@JustArchi.net
+// |
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// |
+// http://www.apache.org/licenses/LICENSE-2.0
+// |
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#if NETFRAMEWORK
+using JustArchiNET.Madness;
+#endif
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Threading.Tasks;
+using ArchiSteamFarm.Core;
+using ArchiSteamFarm.IPC.Requests;
+using ArchiSteamFarm.IPC.Responses;
+using ArchiSteamFarm.Localization;
+using ArchiSteamFarm.Steam;
+using ArchiSteamFarm.Steam.Security;
+using Microsoft.AspNetCore.Mvc;
+
+namespace ArchiSteamFarm.IPC.Controllers.Api {
+ [Route("Api/Bot/{botNames:required}/TwoFactorAuthentication")]
+ public sealed class TwoFactorAuthenticationController : ArchiController {
+ ///
+ /// Deletes the MobileAuthenticator of given bots if an ASF 2FA module is active on them.
+ ///
+ [HttpDelete]
+ [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)]
+ [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
+ public async Task> AuthenticatorDelete(string botNames) {
+ if (string.IsNullOrEmpty(botNames)) {
+ throw new ArgumentNullException(nameof(botNames));
+ }
+
+ HashSet? bots = Bot.GetBots(botNames);
+
+ if ((bots == null) || (bots.Count == 0)) {
+ return BadRequest(new GenericResponse>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
+ }
+
+ IList<(bool Success, string? Message)> results = await Utilities.InParallel(bots.Select(static bot => Task.Run(bot.RemoveAuthenticator))).ConfigureAwait(false);
+
+ Dictionary> result = new (bots.Count, Bot.BotsComparer);
+
+ foreach (Bot bot in bots) {
+ (bool success, string? message) = results[result.Count];
+ result[bot.BotName] = new GenericResponse(success, message);
+ }
+
+ return Ok(new GenericResponse>>(result));
+ }
+
+ ///
+ /// Imports a MobileAuthenticator into the ASF 2FA module of a given bot.
+ ///
+ [Consumes("application/json")]
+ [HttpPost]
+ [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)]
+ [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
+ public ActionResult AuthenticatorPost(string botNames, [FromBody] MobileAuthenticator authenticator) {
+ if (string.IsNullOrEmpty(botNames)) {
+ throw new ArgumentNullException(nameof(botNames));
+ }
+
+ Bot? bot = Bot.GetBot(botNames);
+
+ if (bot == null) {
+ return BadRequest(new GenericResponse>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
+ }
+
+ if (authenticator == null) {
+ throw new ArgumentNullException(nameof(authenticator));
+ }
+
+ if (bot.TryImportAuthenticator(authenticator)) {
+ return Ok(new GenericResponse(true));
+ }
+
+ return BadRequest(new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.WarningFailed)));
+ }
+
+ ///
+ /// Handles 2FA confirmations of given bots, requires ASF 2FA module to be active on them.
+ ///
+ [Consumes("application/json")]
+ [HttpPost("Confirmations")]
+ [ProducesResponseType(typeof(GenericResponse>>>), (int) HttpStatusCode.OK)]
+ [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
+ public async Task> ConfirmationsPost(string botNames, [FromBody] TwoFactorAuthenticationConfirmationsRequest request) {
+ if (string.IsNullOrEmpty(botNames)) {
+ throw new ArgumentNullException(nameof(botNames));
+ }
+
+ if (request == null) {
+ throw new ArgumentNullException(nameof(request));
+ }
+
+ if (request.AcceptedType.HasValue && ((request.AcceptedType.Value == Confirmation.EType.Unknown) || !Enum.IsDefined(typeof(Confirmation.EType), request.AcceptedType.Value))) {
+ return BadRequest(new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsInvalid, nameof(request.AcceptedType))));
+ }
+
+ HashSet? bots = Bot.GetBots(botNames);
+
+ if ((bots == null) || (bots.Count == 0)) {
+ return BadRequest(new GenericResponse>>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
+ }
+
+ IList<(bool Success, IReadOnlyCollection? HandledConfirmations, string Message)> results = await Utilities.InParallel(bots.Select(bot => bot.Actions.HandleTwoFactorAuthenticationConfirmations(request.Accept, request.AcceptedType, request.AcceptedCreatorIDs.Count > 0 ? request.AcceptedCreatorIDs : null, request.WaitIfNeeded))).ConfigureAwait(false);
+
+ Dictionary>> result = new(bots.Count, Bot.BotsComparer);
+
+ foreach (Bot bot in bots) {
+ (bool success, IReadOnlyCollection? handledConfirmations, string message) = results[result.Count];
+ result[bot.BotName] = new GenericResponse>(success, message, handledConfirmations);
+ }
+
+ return Ok(new GenericResponse>>>(result));
+ }
+
+ ///
+ /// Fetches 2FA tokens of given bots, requires ASF 2FA module to be active on them.
+ ///
+ [HttpGet("Token")]
+ [ProducesResponseType(typeof(GenericResponse>>), (int) HttpStatusCode.OK)]
+ [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)]
+ public async Task> TokenGet(string botNames) {
+ if (string.IsNullOrEmpty(botNames)) {
+ throw new ArgumentNullException(nameof(botNames));
+ }
+
+ HashSet? bots = Bot.GetBots(botNames);
+
+ if ((bots == null) || (bots.Count == 0)) {
+ return BadRequest(new GenericResponse>>(false, string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)));
+ }
+
+ IList<(bool Success, string? Token, string Message)> results = await Utilities.InParallel(bots.Select(static bot => bot.Actions.GenerateTwoFactorAuthenticationToken())).ConfigureAwait(false);
+
+ Dictionary> result = new (bots.Count, Bot.BotsComparer);
+
+ foreach (Bot bot in bots) {
+ (bool success, string? token, string message) = results[result.Count];
+ result[bot.BotName] = new GenericResponse(success, message, token);
+ }
+
+ return Ok(new GenericResponse>>(result));
+ }
+ }
+}
diff --git a/ArchiSteamFarm/Steam/Bot.cs b/ArchiSteamFarm/Steam/Bot.cs
index f3da8355e..55e86375d 100644
--- a/ArchiSteamFarm/Steam/Bot.cs
+++ b/ArchiSteamFarm/Steam/Bot.cs
@@ -487,7 +487,9 @@ namespace ArchiSteamFarm.Steam {
Regex regex;
try {
+#pragma warning disable CA3012
regex = new Regex(botsPattern, botsRegex);
+#pragma warning restore CA3012
} catch (ArgumentException e) {
ASF.ArchiLogger.LogGenericWarningException(e);
@@ -1647,7 +1649,7 @@ namespace ArchiSteamFarm.Steam {
}
if (File.Exists(mobileAuthenticatorFilePath)) {
- await ImportAuthenticator(mobileAuthenticatorFilePath).ConfigureAwait(false);
+ await ImportAuthenticatorFromFile(mobileAuthenticatorFilePath).ConfigureAwait(false);
}
}
@@ -1918,7 +1920,7 @@ namespace ArchiSteamFarm.Steam {
}
}
- private async Task ImportAuthenticator(string maFilePath) {
+ private async Task ImportAuthenticatorFromFile(string maFilePath) {
if (HasMobileAuthenticator || !File.Exists(maFilePath)) {
return;
}
@@ -1942,8 +1944,9 @@ namespace ArchiSteamFarm.Steam {
return;
}
- authenticator.Init(this);
- BotDatabase.MobileAuthenticator = authenticator;
+ if (!TryImportAuthenticator(authenticator)) {
+ return;
+ }
File.Delete(maFilePath);
} catch (Exception e) {
@@ -1955,6 +1958,42 @@ namespace ArchiSteamFarm.Steam {
ArchiLogger.LogGenericInfo(Strings.BotAuthenticatorImportFinished);
}
+ internal bool TryImportAuthenticator(MobileAuthenticator authenticator) {
+ if (authenticator == null) {
+ throw new ArgumentNullException(nameof(authenticator));
+ }
+
+ if (HasMobileAuthenticator) {
+ return false;
+ }
+
+ try {
+ authenticator.Init(this);
+ BotDatabase.MobileAuthenticator = authenticator;
+ } catch (Exception e) {
+ ArchiLogger.LogGenericException(e);
+
+ return false;
+ }
+
+ ArchiLogger.LogGenericInfo(Strings.BotAuthenticatorImportFinished);
+
+ return true;
+ }
+
+ internal (bool Success, string? Message) RemoveAuthenticator() {
+ MobileAuthenticator? authenticator = BotDatabase.MobileAuthenticator;
+
+ if (authenticator == null) {
+ return (false, Strings.BotNoASFAuthenticator);
+ }
+
+ BotDatabase.MobileAuthenticator = null;
+ authenticator.Dispose();
+
+ return (true, null);
+ }
+
private void InitConnectionFailureTimer() {
if (ConnectionFailureTimer != null) {
return;
@@ -2743,7 +2782,7 @@ namespace ArchiSteamFarm.Steam {
string maFilePath = Path.Combine(SharedInfo.ConfigDirectory, SteamID + SharedInfo.MobileAuthenticatorExtension);
if (File.Exists(maFilePath)) {
- await ImportAuthenticator(maFilePath).ConfigureAwait(false);
+ await ImportAuthenticatorFromFile(maFilePath).ConfigureAwait(false);
}
}