Skip to content

Commit

Permalink
🎨 winAuth test fixs
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzaz committed Dec 21, 2023
1 parent 9fa45eb commit 64b6d9d
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 28 deletions.
10 changes: 8 additions & 2 deletions src/BD.SteamClient8.Impl/WebApi/SteamAuthenticatorServiceImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public SteamAuthenticatorServiceImpl(
{ "authenticator_time", authenticator_time },
{ "authenticator_type", authenticator_type },
{ "device_identifier", device_identifier ?? "" },
{ "sms_phone_id", sms_phone_id }
{ "sms_phone_id", sms_phone_id },
};

using var sendArgs = new WebApiClientSendArgs(SteamApiUrls.STEAM_AUTHENTICATOR_ADD.Format(steamSession.AccessToken))
Expand Down Expand Up @@ -258,7 +258,13 @@ public async Task<ApiRspImpl<string>> RefreshAccessToken(string steam_id)
throw new Exception("Failed to refresh token: " + ex.Message);
}

return ApiRspHelper.Ok(response.ThrowIsNull()?.Response?.AccessToken ?? string.Empty)!;
var accessToken = response.ThrowIsNull()?.Response?.AccessToken ?? string.Empty;
if (string.IsNullOrEmpty(accessToken))
{
steamSession.AccessToken = accessToken;
_sessionService.AddOrSetSession(steamSession);
}
return ApiRspHelper.Ok(accessToken)!;
}

#region Private
Expand Down
4 changes: 4 additions & 0 deletions src/BD.SteamClient8.Models/Converter/SteamDataIntConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ public override int Read(ref Utf8JsonReader reader, Type typeToConvert, SystemTe
{
return value;
}
else if (reader.TokenType == JsonTokenType.Number)
{
return reader.GetInt32();
}

return 0; // 返回默认值或其他自定义逻辑
}
Expand Down
22 changes: 20 additions & 2 deletions src/BD.SteamClient8.UnitTest/Helpers/SteamAuthenticatorHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static partial class SteamAuthenticatorHelper
if (OperatingSystem.IsWindows())
steamAuthenticatorCache = ProtectedData.Unprotect(
steamAuthenticatorCache, null, DataProtectionScope.LocalMachine);
steamAuthenticator = Serializable.DMP2<SteamAuthenticator>(steamAuthenticatorCache);
steamAuthenticator = Serializable.DJSON<SteamAuthenticator>(Serializable.JsonImplType.SystemTextJson, Encoding.UTF8.GetString(steamAuthenticatorCache));
steamAuthenticator.ThrowIsNull();
}
catch
Expand All @@ -43,7 +43,7 @@ public static async ValueTask<bool> SaveSteamAuthenticatorAsync(SteamAuthenticat
"..", steamAuthenticatorCacheFileName);
try
{
byte[] steamAuthenticatorCache = Serializable.SMP2(steamAuthenticator);
byte[] steamAuthenticatorCache = Encoding.UTF8.GetBytes(Serializable.SJSON(Serializable.JsonImplType.SystemTextJson, steamAuthenticator));
if (OperatingSystem.IsWindows())
steamAuthenticatorCache = ProtectedData.Protect(
steamAuthenticatorCache, null, DataProtectionScope.LocalMachine);
Expand All @@ -56,4 +56,22 @@ public static async ValueTask<bool> SaveSteamAuthenticatorAsync(SteamAuthenticat
}
}
}

public static async ValueTask<bool> DeleteSteamAuthenticatorAsync()
{
using (await lock_GetSteamAuthenticatorAsync.AcquireLockAsync(CancellationToken.None))
{
var steamAuthenticatorCacheFilePath = Path.Combine(ProjPath,
"..", steamAuthenticatorCacheFileName);
try
{
File.Delete(steamAuthenticatorCacheFilePath);
return true;
}
catch (Exception)
{
return false;
}
}
}
}
18 changes: 14 additions & 4 deletions src/BD.SteamClient8.UnitTest/Helpers/SteamLoginStateHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ public static async ValueTask<SteamLoginState> GetSteamLoginStateAsync(
steamLoginStateCache, null, DataProtectionScope.LocalMachine);
steamLoginState = Serializable.DMP2<SteamLoginState>(steamLoginStateCache);
steamLoginState.ThrowIsNull();
if (steamLoginState.Username != configuration["steamUsername"])
var check = await steamAccountService.CheckAccessTokenValidation(steamLoginState.AccessToken!);
if (steamLoginState.Username != configuration["steamUsername"] || !check.Content)
throw new ArgumentException();

var session = new SteamSession();
Expand All @@ -46,10 +47,19 @@ public static async ValueTask<SteamLoginState> GetSteamLoginStateAsync(
Password = configuration["steamPassword"],
};
await steamAccountService.DoLoginV2Async(steamLoginState);
if (!steamLoginState.Success && steamLoginState.Requires2FA)
if (!steamLoginState.Success && (steamLoginState.Requires2FA || steamLoginState.RequiresEmailAuth))
{
// input your TwoFactorCode
steamLoginState.TwofactorCode.ThrowIsNull();
if (steamLoginState.Requires2FA)
{
// input your TwoFactorCode
steamLoginState.TwofactorCode.ThrowIsNull();
}
else if (steamLoginState.RequiresEmailAuth)
{
// input your EmailCode
steamLoginState.EmailCode.ThrowIsNull();
}

await steamAccountService.DoLoginV2Async(steamLoginState);
}
byte[] steamLoginStateCache = Serializable.SMP2(steamLoginState);
Expand Down
23 changes: 18 additions & 5 deletions src/BD.SteamClient8.UnitTest/SteamTradeServiceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,26 @@ public override async ValueTask Setup()

steamLoginState = await GetSteamLoginStateAsync(configuration, steamAccountService, GetRequiredService<ISteamSessionService>());

var identitySecret = configuration["identitySecret"].ThrowIsNull();
var serverTime = (await steamAuthenticatorService.TwoFAQueryTime())?.Content?.Response?.ServerTime.ThrowIsNull();
var diff = (long.Parse(serverTime!) * 1000L) - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var steamAuthenticator = await GetSteamAuthenticatorAsync();
var identitySecret = configuration["identitySecret"];
long serverTimeDiff;
// 本地令牌获取相关信息
if (identitySecret is null)
{
var steamData = SystemTextJsonSerializer.Deserialize<SteamConvertSteamDataJsonStruct>(steamAuthenticator.ThrowIsNull().SteamData!);
identitySecret = steamData!.IdentitySecret;
serverTimeDiff = steamAuthenticator.ServerTimeDiff;
}
else // 用户机密获取 identitySecret 以及临时请求服务器时间
{
var serverTime = (await steamAuthenticatorService.TwoFAQueryTime())?.Content?.Response?.ServerTime.ThrowIsNull();
serverTimeDiff = (long.Parse(serverTime!) * 1000L) - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}

var session = steamSessionService.RentSession(steamLoginState.SteamId.ToString());
if (session != null)
if (session is not null)
{
session.ServerTimeDiff = diff;
session.ServerTimeDiff = serverTimeDiff;
session.IdentitySecret = identitySecret;
session.APIKey = ApiKey = (await steamAccountService.GetApiKey(steamLoginState)).Content ?? (await steamAccountService.RegisterApiKey(steamLoginState)).Content.ThrowIsNull();
steamSessionService.AddOrSetSession(session);
Expand Down
32 changes: 18 additions & 14 deletions src/BD.SteamClient8.UnitTest/WinAuthTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ sealed class WinAuthTest : ServiceTestBase
ISteamAuthenticatorService steamAuthenticatorService = null!;
IConfiguration configuration = null!;

SteamAuthenticator? steamAuthenticator;
SteamAuthenticator steamAuthenticator;
SteamAuthenticator.EnrollState enrollState;

/// <inheritdoc/>
Expand All @@ -36,7 +36,7 @@ public override async ValueTask Setup()
steamAuthenticatorService = GetRequiredService<ISteamAuthenticatorService>();
steamLoginState = await GetSteamLoginStateAsync(configuration, steamAccountService, GetRequiredService<ISteamSessionService>());

steamAuthenticator ??= await SteamAuthenticatorHelper.GetSteamAuthenticatorAsync();
steamAuthenticator ??= await GetSteamAuthenticatorAsync() ?? new();
enrollState ??= new();
}

Expand All @@ -52,11 +52,7 @@ public async Task AddAuthenticator_Test(string phone_number)
{
Assert.That(steamLoginState.AccessToken, Is.Not.Null);
Assert.That(steamLoginState.RefreshToken, Is.Not.Null);

// 账号是否已添加令牌
Assert.That(steamAuthenticator, Is.Null);
});
steamAuthenticator = new();

enrollState.AccessToken = steamLoginState.AccessToken;
enrollState.RefreshToken = steamLoginState.RefreshToken;
Expand Down Expand Up @@ -88,7 +84,7 @@ public async Task AddAuthenticator_Test(string phone_number)
var finalize = await steamAuthenticator.FinalizeAddAuthenticatorAsync(enrollState);
Assert.That(finalize);

UpdateSteamSession();
Assert.That(await Update());
}
}

Expand All @@ -103,8 +99,6 @@ public async Task RemoveAuthenticator_Test()
{
Assert.That(steamLoginState.AccessToken, Is.Not.Null);
Assert.That(steamLoginState.RefreshToken, Is.Not.Null);

Assert.That(steamAuthenticator, Is.Not.Null);
});
enrollState.AccessToken ??= steamLoginState.AccessToken;
enrollState.RefreshToken ??= steamLoginState.RefreshToken;
Expand All @@ -115,22 +109,24 @@ public async Task RemoveAuthenticator_Test()

Assert.That(removeStart_result);

// 手机验证码
var phoneVerifyCode = "7C86B";
var removeContinue_result = await steamAuthenticator.RemoveAuthenticatorViaChallengeContinueSync(enrollState.SteamId.ToString(), phoneVerifyCode);

Assert.That(removeContinue_result);

UpdateSteamSession();
Assert.That(await Update());
}

/// <summary>
/// 解绑(移除) 令牌
/// </summary>
/// <param name="scheme">1 = 移除令牌验证器但保留邮箱验证,2 = 移除所有防护</param>
/// <returns></returns>
[Test]
public async Task UnBindingAuthenticator()
[TestCase(2)]
public async Task UnBindingAuthenticator(int scheme)
{
Assert.That(steamAuthenticator, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(steamLoginState.AccessToken, Is.Not.Null);
Expand All @@ -139,9 +135,11 @@ public async Task UnBindingAuthenticator()
Assert.That(!string.IsNullOrEmpty(steamAuthenticator.RecoveryCode));
});

var remove_result = await steamAuthenticator.RemoveAuthenticatorAsync(steamLoginState.AccessToken);
var remove_result = await steamAuthenticator.RemoveAuthenticatorAsync(steamLoginState.SteamId.ToString(), scheme);

Assert.That(remove_result);

Assert.That(await DeleteSteamAuthenticatorAsync());
}

/// <summary>
Expand All @@ -150,12 +148,16 @@ public async Task UnBindingAuthenticator()
/// <returns></returns>
public async Task GetUserCountry()
{
Assert.That(steamAuthenticator, Is.Not.Null);

var country = await steamAuthenticator.GetUserCountry(steamLoginState.SteamId.ToString());
Assert.That(string.IsNullOrEmpty(country));
}

private void UpdateSteamSession()
private async Task<bool> Update()
{
Assert.That(steamAuthenticator, Is.Not.Null);

var steamData = SystemTextJsonSerializer.Deserialize<SteamConvertSteamDataJsonStruct>(steamAuthenticator.SteamData!);

var session = steamSessionService.RentSession(steamData.ThrowIsNull().SteamId.ToString());
Expand All @@ -165,5 +167,7 @@ private void UpdateSteamSession()
session.IdentitySecret = steamData.IdentitySecret;
session.ServerTimeDiff = steamAuthenticator.ServerTimeDiff;
steamSessionService.AddOrSetSession(session);

return await SaveSteamAuthenticatorAsync(steamAuthenticator);
}
}
1 change: 1 addition & 0 deletions src/Shared/GlobalUsings.BD.SteamClient8.UnitTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@
global using BD.SteamClient8.UnitTest.Abstractions;
global using BD.SteamClient8.UnitTest.Helpers;

global using static BD.SteamClient8.UnitTest.Helpers.SteamAuthenticatorHelper;
global using static BD.SteamClient8.UnitTest.Helpers.SteamLoginStateHelper;
2 changes: 1 addition & 1 deletion src/WinAuth/WinAuth/SteamAuthenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ public async Task<bool> AddAuthenticatorAsync(EnrollState state)
await Task.Run(Sync);
var deviceId = BuildRandomId();

var response = await AuthenticatorService.AddAuthenticatorAsync(state.SteamId.ToString(), ServerTime.ToString(), deviceId, state.AccessToken);
var response = await AuthenticatorService.AddAuthenticatorAsync(state.SteamId.ToString(), ServerTime.ToString(), deviceId);
var tfaResponse = response.Content;

if (tfaResponse?.Response == null)
Expand Down

0 comments on commit 64b6d9d

Please sign in to comment.