using System.Text.Json; namespace ShellcoreDB; public sealed class SteamVerifier(IConfiguration configuration, HttpClient client) { public async Task Verify(string ticket, CancellationToken cancellationToken) { if (ticket.Length is < 2 or > 8192 || ticket.Length % 2 != 0 || !ticket.All(Uri.IsHexDigit)) return null; var key = configuration["Steam:PublisherKey"]; var appId = configuration["Steam:AppId"]; var identity = configuration["Steam:Identity"]; if (string.IsNullOrWhiteSpace(key) || !uint.TryParse(appId, out var parsedAppId) || parsedAppId == 0 || string.IsNullOrWhiteSpace(identity)) throw new SteamUnavailableException(); var url = "https://partner.steam-api.com/ISteamUserAuth/AuthenticateUserTicket/v1/" + $"?key={Uri.EscapeDataString(key)}&appid={parsedAppId}&ticket={ticket}&identity={Uri.EscapeDataString(identity)}"; try { using var response = await client.GetAsync(url, cancellationToken); if (!response.IsSuccessStatusCode) throw new SteamUnavailableException(); using var document = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken); if (!document.RootElement.TryGetProperty("response", out var responseBody)) throw new SteamUnavailableException(); if (!responseBody.TryGetProperty("params", out var root)) return responseBody.TryGetProperty("error", out _) ? null : throw new SteamUnavailableException(); if (root.GetProperty("result").GetString() != "OK") return null; var steamId = root.GetProperty("steamid").GetString(); return ulong.TryParse(steamId, out var parsed) && parsed != 0 ? steamId : null; } catch (HttpRequestException) { throw new SteamUnavailableException(); } catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested) { throw new SteamUnavailableException(); } catch (JsonException) { throw new SteamUnavailableException(); } catch (KeyNotFoundException) { throw new SteamUnavailableException(); } } } public sealed class SteamUnavailableException : Exception;