| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692 |
- using System;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Hosting;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using SteamAuth;
- using SteamKit2;
- using SteamKit2.Authentication;
- var builder = WebApplication.CreateBuilder(args);
- // ── 限制每个主机的最大并发连接数,防止连接耗尽 ──
- System.Net.ServicePointManager.DefaultConnectionLimit = 200;
- var app = builder.Build();
- // ── 全局异常处理:防止未捕获的异常导致进程崩溃 ──
- app.UseExceptionHandler(errorApp =>
- {
- errorApp.Run(async context =>
- {
- context.Response.StatusCode = 500;
- context.Response.ContentType = "application/json; charset=utf-8";
- var errorId = Guid.NewGuid().ToString("N")[..8];
- Console.Error.WriteLine($"[UNHANDLED] error_id={errorId} path={context.Request.Path}");
- await context.Response.WriteAsync($"{{\"error\":\"Internal server error\",\"error_id\":\"{errorId}\"}}");
- });
- });
- // ── 请求超时中间件:防止慢请求永久占用线程 ──
- app.Use(async (context, next) =>
- {
- using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60));
- try
- {
- await next.Invoke();
- }
- catch (OperationCanceledException)
- {
- context.Response.StatusCode = 504;
- context.Response.ContentType = "application/json";
- await context.Response.WriteAsync("{\"error\":\"Request timeout\"}");
- }
- });
- app.MapPost("/login", async (HttpContext http) =>
- {
- var req = await GetRequestBodyAsync(http);
- if (req == null)
- {
- http.Response.StatusCode = 400;
- await http.Response.WriteAsync("invalid request");
- return;
- }
- if (!File.Exists(req.MaFilePath))
- {
- http.Response.StatusCode = 400;
- await http.Response.WriteAsync("maFile not found");
- return;
- }
- SteamGuardAccount? account;
- try
- {
- var contents = await File.ReadAllTextAsync(req.MaFilePath);
- account = JsonConvert.DeserializeObject<SteamGuardAccount>(contents);
- }
- catch (Exception ex)
- {
- http.Response.StatusCode = 500;
- await http.Response.WriteAsync("failed to read maFile: " + ex.Message);
- return;
- }
- try
- {
- // Start SteamClient and authenticate using the maFile-provided SteamGuardAccount
- SteamClient steamClient = CreateSteamClient(req.ProxyUrl, app.Logger, "login");
- steamClient.Connect();
- var timeoutMs = 15000;
- var waited = 0;
- while (!steamClient.IsConnected && waited < timeoutMs)
- {
- await Task.Delay(200);
- waited += 200;
- }
- if (!steamClient.IsConnected)
- {
- http.Response.StatusCode = 500;
- await http.Response.WriteAsync("failed to connect to steam network");
- return;
- }
- CredentialsAuthSession authSession = await steamClient.Authentication.BeginAuthSessionViaCredentialsAsync(new AuthSessionDetails
- {
- Username = req.Username,
- Password = req.Password,
- IsPersistentSession = false,
- // PlatformType and ClientOSType are optional; omit to avoid enum symbol differences across SteamKit2 versions.
- Authenticator = new FileAuthenticator(account),
- });
- var pollResponse = await authSession.PollingWaitForResultAsync();
- var sessionData = new SessionData()
- {
- SteamID = authSession.SteamID.ConvertToUInt64(),
- AccessToken = pollResponse.AccessToken,
- RefreshToken = pollResponse.RefreshToken,
- };
- // Serialize cookies
- var uri = new Uri("https://steamcommunity.com");
- var cookies = sessionData.GetCookies().GetCookies(uri).Cast<Cookie>().Select(c => new
- {
- name = c.Name,
- value = c.Value,
- domain = c.Domain,
- path = c.Path,
- expires = c.Expires == DateTime.MinValue ? null : (DateTime?)c.Expires
- }).ToArray();
- var resp = new
- {
- session = new
- {
- steamId = sessionData.SteamID,
- accessToken = sessionData.AccessToken,
- refreshToken = sessionData.RefreshToken,
- sessionId = sessionData.SessionID
- },
- cookies = cookies
- };
- http.Response.ContentType = "application/json";
- await http.Response.WriteAsync(JsonConvert.SerializeObject(resp, Formatting.Indented));
- return;
- }
- catch (Exception ex)
- {
- http.Response.StatusCode = 500;
- await http.Response.WriteAsync("login failed: " + ex.Message);
- return;
- }
- });
- app.MapPost("/wallet-balance", async (HttpContext http) =>
- {
- var req = await GetWalletBalanceRequestBodyAsync(http);
- if (req == null || string.IsNullOrWhiteSpace(req.SteamLoginSecure))
- {
- http.Response.StatusCode = 400;
- await http.Response.WriteAsync("invalid request");
- return;
- }
- try
- {
- var handler = CreateHttpClientHandler(req.ProxyUrl, app.Logger, "wallet-balance");
- using var client = new HttpClient(handler, disposeHandler: true)
- {
- Timeout = TimeSpan.FromSeconds(20)
- };
- var request = new HttpRequestMessage(HttpMethod.Get, "https://store.steampowered.com/api/getfundwalletinfo/?cc=us&l=english");
- request.Headers.Add("Cookie", $"steamLoginSecure={req.SteamLoginSecure}");
- var response = await client.SendAsync(request);
- var body = await response.Content.ReadAsStringAsync();
- if (!response.IsSuccessStatusCode)
- {
- http.Response.StatusCode = 500;
- await http.Response.WriteAsync($"wallet request failed: {(int)response.StatusCode}");
- return;
- }
- var json = JsonConvert.DeserializeObject<JObject>(body);
- if (json == null || json["success"]?.Value<int>() != 1 || json["user_wallet"] is not JObject wallet)
- {
- http.Response.StatusCode = 500;
- await http.Response.WriteAsync("wallet response invalid");
- return;
- }
- var resp = new
- {
- amount = wallet["amount"]?.Value<string>() ?? "0",
- currency = wallet["currency"]?.Value<string>() ?? "USD"
- };
- http.Response.ContentType = "application/json";
- await http.Response.WriteAsync(JsonConvert.SerializeObject(resp));
- }
- catch (Exception ex)
- {
- http.Response.StatusCode = 500;
- await http.Response.WriteAsync("wallet query failed: " + ex.Message);
- }
- });
- app.MapPost("/trade-confirmations/list", async (HttpContext http) =>
- {
- var req = await GetTradeConfirmationsListRequestBodyAsync(http);
- if (req == null || string.IsNullOrWhiteSpace(req.MaFilePath) || req.Session == null)
- {
- http.Response.StatusCode = 400;
- await http.Response.WriteAsync("invalid request");
- return;
- }
- if (!File.Exists(req.MaFilePath))
- {
- http.Response.StatusCode = 400;
- await http.Response.WriteAsync("maFile not found");
- return;
- }
- try
- {
- var (proxyUrl, source) = ResolveProxyUrl(req.ProxyUrl);
- app.Logger.LogInformation(
- "[{Endpoint}] Proxy resolved. source={Source}, value={Proxy}",
- "trade-confirmations/list",
- source,
- MaskProxyUrlForLog(proxyUrl)
- );
- app.Logger.LogInformation(
- "[{Endpoint}] Calling Steam confirmation list. mode={Mode}, proxy={Proxy}",
- "trade-confirmations/list",
- string.IsNullOrWhiteSpace(proxyUrl) ? "direct" : "proxy",
- MaskProxyUrlForLog(proxyUrl)
- );
- var account = await BuildAccountWithSessionAsync(req.MaFilePath, req.Session);
- if (account == null)
- {
- http.Response.StatusCode = 500;
- await http.Response.WriteAsync("failed to build steam account session");
- return;
- }
- if (account.Session.IsRefreshTokenExpired())
- {
- http.Response.StatusCode = 401;
- await http.Response.WriteAsync("session refresh token expired");
- return;
- }
- var accessTokenRefreshed = false;
- if (account.Session.IsAccessTokenExpired())
- {
- await account.Session.RefreshAccessToken();
- accessTokenRefreshed = true;
- }
- var confirmations = await account.FetchConfirmationsAsync(proxyUrl);
- var resp = new
- {
- session = new
- {
- steamId = account.Session.SteamID,
- accessToken = account.Session.AccessToken,
- refreshToken = account.Session.RefreshToken,
- sessionId = account.Session.SessionID,
- accessTokenRefreshed
- },
- confirmations = confirmations.Select(c => new
- {
- id = c.ID,
- key = c.Key,
- creatorId = c.Creator,
- type = c.ConfType.ToString(),
- headline = c.Headline,
- summary = c.Summary,
- accept = c.Accept,
- cancel = c.Cancel,
- icon = c.Icon
- }).ToArray()
- };
- http.Response.ContentType = "application/json";
- await http.Response.WriteAsync(JsonConvert.SerializeObject(resp));
- }
- catch (Exception ex)
- {
- http.Response.StatusCode = 500;
- await http.Response.WriteAsync("fetch confirmations failed: " + ex.Message);
- }
- });
- app.MapPost("/trade-confirmations/operate", async (HttpContext http) =>
- {
- var req = await GetTradeConfirmationOperateRequestBodyAsync(http);
- if (req == null
- || string.IsNullOrWhiteSpace(req.MaFilePath)
- || req.Session == null
- || req.ConfirmationId == 0
- || string.IsNullOrWhiteSpace(req.Operation))
- {
- http.Response.StatusCode = 400;
- await http.Response.WriteAsync("invalid request");
- return;
- }
- if (!File.Exists(req.MaFilePath))
- {
- http.Response.StatusCode = 400;
- await http.Response.WriteAsync("maFile not found");
- return;
- }
- var op = req.Operation.Trim().ToLowerInvariant();
- if (op != "accept" && op != "cancel")
- {
- http.Response.StatusCode = 400;
- await http.Response.WriteAsync("invalid operation, expected accept or cancel");
- return;
- }
- try
- {
- var (proxyUrl, source) = ResolveProxyUrl(req.ProxyUrl);
- app.Logger.LogInformation(
- "[{Endpoint}] Proxy resolved. source={Source}, value={Proxy}",
- "trade-confirmations/operate",
- source,
- MaskProxyUrlForLog(proxyUrl)
- );
- app.Logger.LogInformation(
- "[{Endpoint}] Calling Steam confirmation operation. op={Op}, mode={Mode}, proxy={Proxy}",
- "trade-confirmations/operate",
- op,
- string.IsNullOrWhiteSpace(proxyUrl) ? "direct" : "proxy",
- MaskProxyUrlForLog(proxyUrl)
- );
- var account = await BuildAccountWithSessionAsync(req.MaFilePath, req.Session);
- if (account == null)
- {
- http.Response.StatusCode = 500;
- await http.Response.WriteAsync("failed to build steam account session");
- return;
- }
- if (account.Session.IsRefreshTokenExpired())
- {
- http.Response.StatusCode = 401;
- await http.Response.WriteAsync("session refresh token expired");
- return;
- }
- var accessTokenRefreshed = false;
- if (account.Session.IsAccessTokenExpired())
- {
- await account.Session.RefreshAccessToken();
- accessTokenRefreshed = true;
- }
- ulong confirmationKey = req.ConfirmationKey ?? 0;
- ulong effectiveConfirmationId = req.ConfirmationId;
- var keyResolvedFromList = false;
- var idResolvedFromList = false;
- var matchedBy = "request";
- if (confirmationKey == 0)
- {
- var confirmations = await account.FetchConfirmationsAsync(proxyUrl);
- var matched = confirmations.FirstOrDefault(c => c.ID == req.ConfirmationId);
- if (matched != null)
- {
- matchedBy = "id";
- }
- else
- {
- // buylisting 返回的 confirmation_id 在部分场景为 creator_id,
- // 这里回退按 creator_id 匹配,便于调用方仅传一个确认订单号即可完成确认。
- matched = confirmations.FirstOrDefault(c => c.Creator == req.ConfirmationId);
- if (matched != null)
- {
- matchedBy = "creator_id";
- }
- }
- if (matched == null || matched.Key == 0)
- {
- http.Response.StatusCode = 404;
- await http.Response.WriteAsync("confirmation not found or key unavailable");
- return;
- }
- effectiveConfirmationId = matched.ID;
- confirmationKey = matched.Key;
- keyResolvedFromList = true;
- idResolvedFromList = true;
- }
- var confirmation = new Confirmation
- {
- ID = effectiveConfirmationId,
- Key = confirmationKey
- };
- var success = op == "accept"
- ? await account.AcceptConfirmation(confirmation, proxyUrl)
- : await account.DenyConfirmation(confirmation, proxyUrl);
- var resp = new
- {
- success,
- operation = op,
- requestedConfirmationId = req.ConfirmationId,
- confirmationId = effectiveConfirmationId,
- confirmationKey,
- keyResolvedFromList,
- idResolvedFromList,
- matchedBy,
- session = new
- {
- steamId = account.Session.SteamID,
- accessToken = account.Session.AccessToken,
- refreshToken = account.Session.RefreshToken,
- sessionId = account.Session.SessionID,
- accessTokenRefreshed
- }
- };
- http.Response.ContentType = "application/json";
- await http.Response.WriteAsync(JsonConvert.SerializeObject(resp));
- }
- catch (Exception ex)
- {
- http.Response.StatusCode = 500;
- await http.Response.WriteAsync("operate confirmation failed: " + ex.Message);
- }
- });
- app.Run();
- async Task<LoginRequest?> GetRequestBodyAsync(HttpContext http)
- {
- try
- {
- using var sr = new StreamReader(http.Request.Body);
- var body = await sr.ReadToEndAsync();
- if (string.IsNullOrWhiteSpace(body)) return null;
- return JsonConvert.DeserializeObject<LoginRequest>(body);
- }
- catch
- {
- return null;
- }
- }
- async Task<WalletBalanceRequest?> GetWalletBalanceRequestBodyAsync(HttpContext http)
- {
- try
- {
- using var sr = new StreamReader(http.Request.Body);
- var body = await sr.ReadToEndAsync();
- if (string.IsNullOrWhiteSpace(body)) return null;
- return JsonConvert.DeserializeObject<WalletBalanceRequest>(body);
- }
- catch
- {
- return null;
- }
- }
- async Task<TradeConfirmationsListRequest?> GetTradeConfirmationsListRequestBodyAsync(HttpContext http)
- {
- try
- {
- using var sr = new StreamReader(http.Request.Body);
- var body = await sr.ReadToEndAsync();
- if (string.IsNullOrWhiteSpace(body)) return null;
- return JsonConvert.DeserializeObject<TradeConfirmationsListRequest>(body);
- }
- catch
- {
- return null;
- }
- }
- async Task<TradeConfirmationOperateRequest?> GetTradeConfirmationOperateRequestBodyAsync(HttpContext http)
- {
- try
- {
- using var sr = new StreamReader(http.Request.Body);
- var body = await sr.ReadToEndAsync();
- if (string.IsNullOrWhiteSpace(body)) return null;
- return JsonConvert.DeserializeObject<TradeConfirmationOperateRequest>(body);
- }
- catch
- {
- return null;
- }
- }
- async Task<SteamGuardAccount?> BuildAccountWithSessionAsync(string maFilePath, SessionPayload sessionPayload)
- {
- var contents = await File.ReadAllTextAsync(maFilePath);
- var account = JsonConvert.DeserializeObject<SteamGuardAccount>(contents);
- if (account == null)
- {
- return null;
- }
- if (string.IsNullOrWhiteSpace(account.DeviceID))
- {
- throw new Exception("maFile missing device_id");
- }
- account.Session = new SessionData
- {
- SteamID = sessionPayload.SteamId,
- AccessToken = sessionPayload.AccessToken,
- RefreshToken = sessionPayload.RefreshToken,
- SessionID = sessionPayload.SessionId
- };
- return account;
- }
- SteamClient CreateSteamClient(string? requestProxyUrl, ILogger logger, string endpointName)
- {
- var (proxyUrl, source) = ResolveProxyUrl(requestProxyUrl);
- logger.LogInformation(
- "[{Endpoint}] Proxy resolved. source={Source}, value={Proxy}",
- endpointName,
- source,
- MaskProxyUrlForLog(proxyUrl)
- );
- if (string.IsNullOrWhiteSpace(proxyUrl))
- {
- logger.LogInformation("[{Endpoint}] Proxy disabled for this request.", endpointName);
- return new SteamClient();
- }
- if (!Uri.TryCreate(proxyUrl, UriKind.Absolute, out var proxyUri))
- {
- logger.LogWarning(
- "[{Endpoint}] Proxy url invalid. raw={RawProxy}",
- endpointName,
- MaskProxyUrlForLog(proxyUrl)
- );
- throw new ArgumentException("invalid proxy url, expected format like http://127.0.0.1:7890");
- }
- var config = SteamConfiguration.Create(builder =>
- {
- // Force WebSocket so proxy can be applied through HttpClient.
- builder.WithProtocolTypes(ProtocolTypes.WebSocket);
- builder.WithHttpClientFactory(() =>
- {
- var handler = new HttpClientHandler
- {
- Proxy = new WebProxy(proxyUri),
- UseProxy = true
- };
- return new HttpClient(handler, disposeHandler: true);
- });
- });
- return new SteamClient(config);
- }
- HttpClientHandler CreateHttpClientHandler(string? requestProxyUrl, ILogger logger, string endpointName)
- {
- var (proxyUrl, source) = ResolveProxyUrl(requestProxyUrl);
- logger.LogInformation(
- "[{Endpoint}] Proxy resolved. source={Source}, value={Proxy}",
- endpointName,
- source,
- MaskProxyUrlForLog(proxyUrl)
- );
- var handler = new HttpClientHandler();
- if (string.IsNullOrWhiteSpace(proxyUrl))
- {
- logger.LogInformation("[{Endpoint}] Proxy disabled for this request.", endpointName);
- return handler;
- }
- if (!Uri.TryCreate(proxyUrl, UriKind.Absolute, out var proxyUri))
- {
- logger.LogWarning(
- "[{Endpoint}] Proxy url invalid. raw={RawProxy}",
- endpointName,
- MaskProxyUrlForLog(proxyUrl)
- );
- throw new ArgumentException("invalid proxy url, expected format like http://127.0.0.1:7890");
- }
- handler.Proxy = new WebProxy(proxyUri);
- handler.UseProxy = true;
- return handler;
- }
- (string? ProxyUrl, string Source) ResolveProxyUrl(string? requestProxyUrl)
- {
- if (!string.IsNullOrWhiteSpace(requestProxyUrl))
- {
- return (requestProxyUrl, "request.ProxyUrl");
- }
- var envProxy = Environment.GetEnvironmentVariable("STEAM_PROXY_URL");
- if (!string.IsNullOrWhiteSpace(envProxy))
- {
- return (envProxy, "env.STEAM_PROXY_URL");
- }
- return (null, "none");
- }
- string MaskProxyUrlForLog(string? proxyUrl)
- {
- if (string.IsNullOrWhiteSpace(proxyUrl))
- {
- return "<none>";
- }
- if (!Uri.TryCreate(proxyUrl, UriKind.Absolute, out var uri))
- {
- var trimmed = proxyUrl.Trim();
- if (trimmed.Length > 64)
- {
- trimmed = trimmed.Substring(0, 64) + "...";
- }
- return $"<invalid:{trimmed}>";
- }
- var hostPort = uri.IsDefaultPort ? uri.Host : $"{uri.Host}:{uri.Port}";
- return $"{uri.Scheme}://{hostPort}";
- }
- record LoginRequest(string Username, string Password, string MaFilePath, string? ProxyUrl = null);
- record WalletBalanceRequest(string SteamLoginSecure, string? ProxyUrl = null);
- record TradeConfirmationsListRequest(string MaFilePath, SessionPayload Session, string? ProxyUrl = null);
- record TradeConfirmationOperateRequest(
- string MaFilePath,
- SessionPayload Session,
- ulong ConfirmationId,
- ulong? ConfirmationKey,
- string Operation,
- string? ProxyUrl = null
- );
- record SessionPayload(ulong SteamId, string AccessToken, string RefreshToken, string? SessionId = null);
- internal class FileAuthenticator : IAuthenticator
- {
- private readonly SteamGuardAccount? account;
- private int deviceCodesGenerated = 0;
- public FileAuthenticator(SteamGuardAccount? account)
- {
- this.account = account;
- }
- public Task<bool> AcceptDeviceConfirmationAsync()
- {
- return Task.FromResult(false);
- }
- public async Task<string> GetDeviceCodeAsync(bool previousCodeWasIncorrect)
- {
- if (previousCodeWasIncorrect)
- {
- if (deviceCodesGenerated > 2)
- throw new Exception("failed to generate device code from maFile");
- await Task.Delay(30000);
- }
- if (account == null) return null;
- deviceCodesGenerated++;
- var code = await account.GenerateSteamGuardCodeAsync();
- return code ?? "";
- }
- public Task<string> GetEmailCodeAsync(string email, bool previousCodeWasIncorrect)
- {
- // This implementation does not support interactive email codes.
- return Task.FromResult(string.Empty);
- }
- }
|