feat(www): Add logic to the homepage and Steam integration (#258)

## Description
<!-- Briefly describe the purpose and scope of your changes -->


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Upgraded API and authentication services with dynamic scaling,
enhanced load balancing, and real-time interaction endpoints.
- Introduced new commands to streamline local development and container
builds.
- Added new endpoints for retrieving Steam account information and
managing connections.
- Implemented a QR code authentication interface for Steam, enhancing
user login experiences.

- **Database Updates**
- Rolled out comprehensive schema migrations that improve data integrity
and indexing.
- Introduced new tables for managing Steam user credentials and machine
information.

- **UI Enhancements**
- Added refreshed animated assets and an improved QR code login flow for
a more engaging experience.
	- Introduced new styled components for displaying friends and games.

- **Maintenance**
- Completed extensive refactoring and configuration updates to optimize
performance and development workflows.
- Updated logging configurations and improved error handling mechanisms.
	- Streamlined resource definitions in the configuration files.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
Wanjohi
2025-04-13 14:30:45 +03:00
committed by GitHub
parent 8394bb4259
commit f408ec56cb
103 changed files with 12755 additions and 2053 deletions

View File

@@ -2,7 +2,8 @@
## files generated by popular Visual Studio add-ons.
##
## Get latest from `dotnet new gitignore`
bin
obj
# dotenv files
.env
@@ -24,6 +25,8 @@ mono_crash.*
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
bin/
obj/
x64/
x86/
[Ww][Ii][Nn]32/
@@ -228,6 +231,8 @@ _pkginfo.txt
*.appx
*.appxbundle
*.appxupload
#Steam credentials file
*steam*.json
# Visual Studio cache files
# files ending in .cache can be ignored

View File

@@ -1,18 +0,0 @@
using Microsoft.EntityFrameworkCore;
public class SteamDbContext : DbContext
{
public DbSet<SteamUserCredential> SteamUserCredentials { get; set; }
public SteamDbContext(DbContextOptions<SteamDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Create a unique index on TeamId and UserId
modelBuilder.Entity<SteamUserCredential>()
.HasIndex(c => new { c.TeamId, c.UserId })
.IsUnique();
}
}

View File

@@ -1,12 +0,0 @@
public class SteamUserCredential
{
public int Id { get; set; }
public required string TeamId { get; set; }
public required string UserId { get; set; }
public required string AccountName { get; set; }
public required string RefreshToken { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
// Composite key of TeamId and UserId will be unique
}

View File

@@ -0,0 +1,42 @@
using System.Net.Http.Headers;
using System.Net.Sockets;
namespace Steam;
public class HttpClientFactory
{
public static HttpClient CreateHttpClient()
{
var client = new HttpClient(new SocketsHttpHandler
{
ConnectCallback = IPv4ConnectAsync
});
var assemblyVersion = typeof(HttpClientFactory).Assembly.GetName().Version?.ToString(fieldCount: 3);
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("DepotDownloader", assemblyVersion));
return client;
}
static async ValueTask<Stream> IPv4ConnectAsync(SocketsHttpConnectionContext context, CancellationToken cancellationToken)
{
// By default, we create dual-mode sockets:
// Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
{
NoDelay = true
};
try
{
await socket.ConnectAsync(context.DnsEndPoint, cancellationToken).ConfigureAwait(false);
return new NetworkStream(socket, ownsSocket: true);
}
catch
{
socket.Dispose();
throw;
}
}
}

View File

@@ -0,0 +1,28 @@
using System.Text;
namespace Steam;
/// <summary>
/// Provides information about the machine that the application is running on.
/// For Steam Guard purposes, these values must return consistent results when run
/// on the same machine / in the same container / etc., otherwise it will be treated
/// as a separate machine and you may need to reauthenticate.
/// </summary>
public class IMachineInfoProvider : SteamKit2.IMachineInfoProvider
{
/// <summary>
/// Provides a unique machine ID as binary data.
/// </summary>
/// <returns>The unique machine ID, or <c>null</c> if no such value could be found.</returns>
public byte[]? GetMachineGuid() => Encoding.UTF8.GetBytes("Nestri-Machine");
/// <summary>
/// Provides the primary MAC address as binary data.
/// </summary>
/// <returns>The primary MAC address, or <c>null</c> if no such value could be found.</returns>
public byte[]? GetMacAddress() => Encoding.UTF8.GetBytes("Nestri-MacAddress");
/// <summary>
/// Provides the boot disk's unique ID as binary data.
/// </summary>
/// <returns>The boot disk's unique ID, or <c>null</c> if no such value could be found.</returns>
public byte[]? GetDiskId() => Encoding.UTF8.GetBytes("Nestri-DiskId");
}

View File

@@ -1,60 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace steam.Migrations
{
[DbContext(typeof(SteamDbContext))]
[Migration("20250322023207_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
modelBuilder.Entity("SteamUserCredential", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("AccountName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("RefreshToken")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("TeamId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TeamId", "UserId")
.IsUnique();
b.ToTable("SteamUserCredentials");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,46 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace steam.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "SteamUserCredentials",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
TeamId = table.Column<string>(type: "TEXT", nullable: false),
UserId = table.Column<string>(type: "TEXT", nullable: false),
AccountName = table.Column<string>(type: "TEXT", nullable: false),
RefreshToken = table.Column<string>(type: "TEXT", nullable: false),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SteamUserCredentials", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_SteamUserCredentials_TeamId_UserId",
table: "SteamUserCredentials",
columns: new[] { "TeamId", "UserId" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SteamUserCredentials");
}
}
}

View File

@@ -1,57 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace steam.Migrations
{
[DbContext(typeof(SteamDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
modelBuilder.Entity("SteamUserCredential", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("AccountName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("RefreshToken")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("TeamId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TeamId", "UserId")
.IsUnique();
b.ToTable("SteamUserCredentials");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,331 +1,118 @@
using System.Text;
using System.Text.Json;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
// FYI: Am very new to C# if you find any bugs or have any feedback hit me up :P
// TBH i dunno what this code does, only God and Claude know(in the slightest) what it does.
// And yes! It does not sit right with me - am learning C# as we go, i guess 🤧
// This is the server to connect to the Steam APIs and do stuff like:
// - authenticate a user,
// - get their library,
// - generate .vdf files for Steam Client (Steam manifest files), etc etc
var builder = WebApplication.CreateBuilder(args);
// Add JWT Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
namespace Steam
{
public class Program
{
options.TokenValidationParameters = new TokenValidationParameters
const string UnixSocketPath = "/tmp/steam.sock";
public static void Main(string[] args)
{
ValidateIssuer = true,
ValidIssuer = Environment.GetEnvironmentVariable("NESTRI_AUTH_JWKS_URL"),
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
RequireSignedTokens = true,
RequireExpirationTime = true,
ClockSkew = TimeSpan.Zero,
// Configure the issuer signing key provider
IssuerSigningKeyResolver = (token, securityToken, kid, validationParameters) =>
// Delete the socket file if it exists
if (File.Exists(UnixSocketPath))
{
// Fetch the JWKS manually
var jwksUrl = $"{Environment.GetEnvironmentVariable("NESTRI_AUTH_JWKS_URL")}/.well-known/jwks.json";
var httpClient = new HttpClient();
var jwksJson = httpClient.GetStringAsync(jwksUrl).Result;
var jwks = JsonSerializer.Deserialize<JsonWebKeySet>(jwksJson);
// Return all keys or filter by kid if provided
if (string.IsNullOrEmpty(kid))
return jwks?.Keys;
else
return jwks?.Keys.Where(k => k.Kid == kid);
File.Delete(UnixSocketPath);
}
};
// Add logging for debugging
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
var builder = WebApplication.CreateBuilder(args);
// Configure Kestrel to listen on Unix socket
builder.WebHost.ConfigureKestrel(options =>
{
Console.WriteLine($"Authentication failed: {context.Exception.Message}");
return Task.CompletedTask;
},
OnTokenValidated = context =>
options.ListenUnixSocket(UnixSocketPath);
options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(10);
options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(5);
});
builder.Services.AddControllers();
builder.Services.AddSingleton<SteamAuthService>();
var app = builder.Build();
// Health check endpoint
app.MapGet("/", () => "Steam Auth Service is running");
// QR Code login endpoint with Server-Sent Events
app.MapGet("/api/steam/login", async (HttpResponse response, SteamAuthService steamService) =>
{
Console.WriteLine("Token successfully validated");
return Task.CompletedTask;
}
};
});
// Generate a unique session ID for this login attempt
string sessionId = Guid.NewGuid().ToString();
Console.WriteLine($"Starting new login session: {sessionId}");
builder.Services.AddAuthorization();
// Set up SSE response
response.Headers.Append("Content-Type", "text/event-stream");
response.Headers.Append("Cache-Control", "no-cache");
response.Headers.Append("Connection", "keep-alive");
// Configure CORS
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddSingleton<SteamService>();
builder.Services.AddDbContext<SteamDbContext>(options =>
options.UseSqlite($"Data Source=/tmp/steam.db"));
var app = builder.Build();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/", () => "Hello World!");
app.MapGet("/status", [Authorize] async (HttpContext context, SteamService steamService) =>
{
// Validate JWT
var jwtToken = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
var (isValid, userId, email) = await ValidateJwtToken(jwtToken);
if (!isValid)
{
return Results.Unauthorized();
}
// Get team ID
var teamId = context.Request.Headers["x-nestri-team"].ToString();
if (string.IsNullOrEmpty(teamId))
{
return Results.BadRequest("Missing team ID");
}
// Check if user is authenticated with Steam
var userInfo = await steamService.GetUserInfoFromStoredCredentials(teamId, userId!);
if (userInfo == null)
{
return Results.Ok(new { isAuthenticated = false });
}
return Results.Ok(new
{
isAuthenticated = true,
steamId = userInfo.SteamId,
username = userInfo.Username
});
});
app.MapGet("/login", [Authorize] async (HttpContext context, SteamService steamService) =>
{
// Validate JWT
var jwtToken = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
var (isValid, userId, email) = await ValidateJwtToken(jwtToken);
Console.WriteLine($"User data: {userId}:{email}");
if (!isValid)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Invalid JWT token");
return;
}
// Get team ID
var teamId = context.Request.Headers["x-nestri-team"].ToString();
if (string.IsNullOrEmpty(teamId))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsync("Missing team ID");
return;
}
// Set SSE headers
context.Response.Headers.Append("Connection", "keep-alive");
context.Response.Headers.Append("Cache-Control", "no-cache");
context.Response.Headers.Append("Content-Type", "text/event-stream");
context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
// Disable response buffering
var responseBodyFeature = context.Features.Get<IHttpResponseBodyFeature>();
if (responseBodyFeature != null)
{
responseBodyFeature.DisableBuffering();
}
// Create unique client ID
var clientId = $"{teamId}:{userId}";
var cancellationToken = context.RequestAborted;
// Start Steam authentication
await steamService.StartAuthentication(teamId, userId!);
// Register for updates
var subscription = steamService.SubscribeToEvents(clientId, async (evt) =>
{
try
{
// Serialize the event to SSE format
string eventMessage = evt.Serialize();
byte[] buffer = Encoding.UTF8.GetBytes(eventMessage);
await context.Response.Body.WriteAsync(buffer, 0, buffer.Length, cancellationToken);
await context.Response.Body.FlushAsync(cancellationToken);
Console.WriteLine($"Sent event type '{evt.Type}' to client {clientId}");
}
catch (Exception ex)
{
Console.WriteLine($"Error sending event to client {clientId}: {ex.Message}");
}
});
// Keep the connection alive until canceled
try
{
await Task.Delay(Timeout.Infinite, cancellationToken);
}
catch (TaskCanceledException)
{
Console.WriteLine($"Client {clientId} disconnected");
}
finally
{
steamService.Unsubscribe(clientId, subscription);
}
});
app.MapGet("/user", [Authorize] async (HttpContext context, SteamService steamService) =>
{
// Validate JWT
var jwtToken = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
var (isValid, userId, email) = await ValidateJwtToken(jwtToken);
if (!isValid)
{
return Results.Unauthorized();
}
// Get team ID
var teamId = context.Request.Headers["x-nestri-team"].ToString();
if (string.IsNullOrEmpty(teamId))
{
return Results.BadRequest("Missing team ID");
}
// Get user info from stored credentials
var userInfo = await steamService.GetUserInfoFromStoredCredentials(teamId, userId);
if (userInfo == null)
{
return Results.NotFound(new { error = "User not authenticated with Steam" });
}
return Results.Ok(new
{
steamId = userInfo.SteamId,
username = userInfo.Username
});
});
app.MapPost("/logout", [Authorize] async (HttpContext context, SteamService steamService) =>
{
// Validate JWT
var jwtToken = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
var (isValid, userId, email) = await ValidateJwtToken(jwtToken);
if (!isValid)
{
return Results.Unauthorized();
}
// Get team ID
var teamId = context.Request.Headers["x-nestri-team"].ToString();
if (string.IsNullOrEmpty(teamId))
{
return Results.BadRequest("Missing team ID");
}
// Delete the stored credentials
using var scope = context.RequestServices.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<SteamDbContext>();
var credentials = await dbContext.SteamUserCredentials
.FirstOrDefaultAsync(c => c.TeamId == teamId && c.UserId == userId);
if (credentials != null)
{
dbContext.SteamUserCredentials.Remove(credentials);
await dbContext.SaveChangesAsync();
return Results.Ok(new { message = "Steam authentication revoked" });
}
return Results.NotFound(new { error = "No Steam authentication found" });
});
// JWT validation function
async Task<(bool IsValid, string? UserId, string? Email)> ValidateJwtToken(string token)
{
try
{
var jwksUrl = Environment.GetEnvironmentVariable("NESTRI_AUTH_JWKS_URL");
var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadJwtToken(token);
// Log all claims for debugging
// Console.WriteLine("JWT Claims:");
// foreach (var claim in jwtToken.Claims)
// {
// Console.WriteLine($" {claim.Type}: {claim.Value}");
// }
// Validate token using JWKS
var httpClient = new HttpClient();
var jwksJson = await httpClient.GetStringAsync($"{jwksUrl}/.well-known/jwks.json");
var jwks = JsonSerializer.Deserialize<JsonWebKeySet>(jwksJson);
// Extract the properties claim which contains nested JSON
var propertiesClaim = jwtToken.Claims.FirstOrDefault(c => c.Type == "properties")?.Value;
if (!string.IsNullOrEmpty(propertiesClaim))
{
// Parse the nested JSON
var properties = JsonSerializer.Deserialize<Dictionary<string, string>>(propertiesClaim);
// Extract userID from properties
var email = properties?.GetValueOrDefault("email");
var userId = properties?.GetValueOrDefault("userID");
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email))
{
// Also check standard claims as fallback
userId = jwtToken.Claims.FirstOrDefault(c => c.Type == "sub")?.Value;
email = jwtToken.Claims.FirstOrDefault(c => c.Type == "email")?.Value;
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email))
try
{
return (false, null, null);
// Start QR login session with SSE updates
await steamService.StartQrLoginSessionAsync(response, sessionId);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in login session {sessionId}: {ex.Message}");
// Send error message as SSE
await response.WriteAsync($"event: error\n");
await response.WriteAsync($"data: {{\"message\":\"{ex.Message}\"}}\n\n");
await response.Body.FlushAsync();
}
});
return (true, userId, email);
// Login with credentials endpoint (returns JSON)
app.MapPost("/api/steam/login-with-credentials", async (LoginCredentials credentials, SteamAuthService steamService) =>
{
if (string.IsNullOrEmpty(credentials.Username) || string.IsNullOrEmpty(credentials.RefreshToken))
{
return Results.BadRequest("Username and refresh token are required");
}
try
{
var result = await steamService.LoginWithCredentialsAsync(
credentials.Username,
credentials.RefreshToken);
return Results.Ok(result);
}
catch (Exception ex)
{
Console.WriteLine($"Error logging in with credentials: {ex.Message}");
return Results.Problem(ex.Message);
}
});
// Get user info endpoint (returns JSON)
app.MapGet("/api/steam/user", async (HttpRequest request, SteamAuthService steamService) =>
{
// Get credentials from headers
var username = request.Headers["X-Steam-Username"].ToString();
var refreshToken = request.Headers["X-Steam-Token"].ToString();
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(refreshToken))
{
return Results.BadRequest("Username and refresh token headers are required");
}
try
{
var userInfo = await steamService.GetUserInfoAsync(username, refreshToken);
return Results.Ok(userInfo);
}
catch (Exception ex)
{
Console.WriteLine($"Error getting user info: {ex.Message}");
return Results.Problem(ex.Message);
}
});
app.Run();
}
return (false, null, null);
}
catch (Exception ex)
public class LoginCredentials
{
Console.WriteLine($"JWT validation error: {ex.Message}");
return (false, null, null);
public string Username { get; set; } = string.Empty;
public string RefreshToken { get; set; } = string.Empty;
}
}
Console.WriteLine("Server started. Press Ctrl+C to stop.");
await app.RunAsync();
}

View File

@@ -4,8 +4,8 @@
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:12427",
"sslPort": 44354
"applicationUrl": "http://localhost:41347",
"sslPort": 44359
}
},
"profiles": {
@@ -13,7 +13,8 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5289",
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5221",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@@ -22,7 +23,8 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7168;http://localhost:5289",
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7060;http://localhost:5221",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@@ -30,6 +32,7 @@
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}

View File

@@ -1,19 +0,0 @@
using System.Text.Json;
public class ServerSentEvent
{
public string Type { get; set; }
public object Data { get; set; }
public ServerSentEvent(string type, object data)
{
Type = type;
Data = data;
}
public string Serialize()
{
var dataJson = JsonSerializer.Serialize(Data);
return $"event: {Type}\ndata: {dataJson}\n\n";
}
}

View File

@@ -0,0 +1,389 @@
using SteamKit2;
using SteamKit2.Authentication;
namespace Steam
{
public class SteamAuthService
{
private readonly SteamClient _steamClient;
private readonly SteamUser _steamUser;
private readonly SteamFriends _steamFriends;
private readonly CallbackManager _manager;
private CancellationTokenSource? _cts;
private Task? _callbackTask;
private readonly Dictionary<string, TaskCompletionSource<bool>> _authCompletionSources = new();
public SteamAuthService()
{
var configuration = SteamConfiguration.Create(config =>
{
config.WithHttpClientFactory(HttpClientFactory.CreateHttpClient);
config.WithMachineInfoProvider(new IMachineInfoProvider());
config.WithConnectionTimeout(TimeSpan.FromSeconds(10));
});
_steamClient = new SteamClient(configuration);
_manager = new CallbackManager(_steamClient);
_steamUser = _steamClient.GetHandler<SteamUser>() ?? throw new InvalidOperationException("SteamUser handler not available");
_steamFriends = _steamClient.GetHandler<SteamFriends>() ?? throw new InvalidOperationException("SteamFriends handler not available");
// Register basic callbacks
_manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
_manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
_manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
_manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
}
// Main login method - initiates QR authentication and sends SSE updates
public async Task StartQrLoginSessionAsync(HttpResponse response, string sessionId)
{
response.Headers.Append("Content-Type", "text/event-stream");
response.Headers.Append("Cache-Control", "no-cache");
response.Headers.Append("Connection", "keep-alive");
// Create a completion source for this session
var tcs = new TaskCompletionSource<bool>();
_authCompletionSources[sessionId] = tcs;
try
{
// Connect to Steam if not already connected
await EnsureConnectedAsync();
// Send initial status
await SendSseEvent(response, "status", new { message = "Starting QR authentication..." });
// Begin auth session
var authSession = await _steamClient.Authentication.BeginAuthSessionViaQRAsync(
new AuthSessionDetails
{
PlatformType = SteamKit2.Internal.EAuthTokenPlatformType.k_EAuthTokenPlatformType_SteamClient,
DeviceFriendlyName = "Nestri Cloud Gaming",
ClientOSType = EOSType.Linux5x
}
);
// Handle URL changes
authSession.ChallengeURLChanged = async () =>
{
await SendSseEvent(response, "challenge_url", new { url = authSession.ChallengeURL });
};
// Send initial QR code URL
await SendSseEvent(response, "challenge_url", new { url = authSession.ChallengeURL });
// Poll for authentication result
try
{
var pollResponse = await authSession.PollingWaitForResultAsync();
// Send credentials to client
await SendSseEvent(response, "credentials", new
{
username = pollResponse.AccountName,
refreshToken = pollResponse.RefreshToken
});
// Log in with obtained credentials
await SendSseEvent(response, "status", new { message = $"Logging in as '{pollResponse.AccountName}'..." });
_steamUser.LogOn(new SteamUser.LogOnDetails
{
Username = pollResponse.AccountName,
MachineName = "Nestri Cloud Gaming",
ClientOSType = EOSType.Linux5x,
AccessToken = pollResponse.RefreshToken
});
// Wait for login to complete (handled by OnLoggedOn callback)
await tcs.Task;
// Send final success message
await SendSseEvent(response, "login-successful", new
{
steamId = _steamUser.SteamID?.ConvertToUInt64(),
username = pollResponse.AccountName
});
}
catch (Exception ex)
{
await SendSseEvent(response, "login-unsuccessful", new { error = ex.Message });
}
}
catch (Exception ex)
{
await SendSseEvent(response, "error", new { message = ex.Message });
}
finally
{
// Clean up
_authCompletionSources.Remove(sessionId);
await response.Body.FlushAsync();
}
}
// Method to login with existing credentials and return result (no SSE)
public async Task<LoginResult> LoginWithCredentialsAsync(string username, string refreshToken)
{
var sessionId = Guid.NewGuid().ToString();
var tcs = new TaskCompletionSource<bool>();
_authCompletionSources[sessionId] = tcs;
try
{
// Connect to Steam if not already connected
await EnsureConnectedAsync();
// Log in with provided credentials
_steamUser.LogOn(new SteamUser.LogOnDetails
{
Username = username,
MachineName = "Nestri Cloud Gaming",
AccessToken = refreshToken,
ClientOSType = EOSType.Linux5x,
});
// Wait for login to complete (handled by OnLoggedOn callback)
var success = await tcs.Task;
if (success)
{
return new LoginResult
{
Success = true,
SteamId = _steamUser.SteamID?.ConvertToUInt64(),
Username = username
};
}
else
{
return new LoginResult
{
Success = false,
ErrorMessage = "Login failed"
};
}
}
catch (Exception ex)
{
return new LoginResult
{
Success = false,
ErrorMessage = ex.Message
};
}
finally
{
_authCompletionSources.Remove(sessionId);
}
}
// Method to get user information - waits for all required callbacks to complete
public async Task<UserInfo> GetUserInfoAsync(string username, string refreshToken)
{
// First ensure we're logged in
var loginResult = await LoginWithCredentialsAsync(username, refreshToken);
if (!loginResult.Success)
{
throw new Exception($"Failed to log in: {loginResult.ErrorMessage}");
}
var userInfo = new UserInfo
{
SteamId = _steamUser.SteamID?.ConvertToUInt64() ?? 0,
Username = username
};
// Set up completion sources for each piece of information
var accountInfoTcs = new TaskCompletionSource<bool>();
var personaStateTcs = new TaskCompletionSource<bool>();
var emailInfoTcs = new TaskCompletionSource<bool>();
// Subscribe to one-time callbacks
var accountSub = _manager.Subscribe<SteamUser.AccountInfoCallback>(callback =>
{
userInfo.Country = callback.Country;
userInfo.PersonaName = callback.PersonaName;
accountInfoTcs.TrySetResult(true);
});
var personaSub = _manager.Subscribe<SteamFriends.PersonaStateCallback>(callback =>
{
if (callback.FriendID == _steamUser.SteamID)
{
// Convert avatar hash to URL
if (callback.AvatarHash != null && callback.AvatarHash.Length > 0)
{
var avatarStr = BitConverter.ToString(callback.AvatarHash).Replace("-", "").ToLowerInvariant();
userInfo.AvatarUrl = $"https://avatars.akamai.steamstatic.com/{avatarStr}_full.jpg";
}
userInfo.PersonaName = callback.Name;
userInfo.GameId = callback.GameID?.ToUInt64() ?? 0;
userInfo.GamePlayingName = callback.GameName;
userInfo.LastLogOn = callback.LastLogOn;
userInfo.LastLogOff = callback.LastLogOff;
personaStateTcs.TrySetResult(true);
}
});
var emailSub = _manager.Subscribe<SteamUser.EmailAddrInfoCallback>(callback =>
{
userInfo.Email = callback.EmailAddress;
emailInfoTcs.TrySetResult(true);
});
try
{
// Request all the info
if (_steamUser.SteamID != null)
{
_steamFriends.RequestFriendInfo(_steamUser.SteamID);
}
// Wait for all callbacks with timeout
var timeoutTask = Task.Delay(TimeSpan.FromSeconds(10));
var tasks = new[]
{
accountInfoTcs.Task,
personaStateTcs.Task,
emailInfoTcs.Task
};
await Task.WhenAny(Task.WhenAll(tasks), timeoutTask);
return userInfo;
}
finally
{
// Unsubscribe from callbacks
// _manager.Unsubscribe(accountSub);
// _manager.Unsubscribe(personaSub);
// _manager.Unsubscribe(emailSub);
}
}
public void Disconnect()
{
_cts?.Cancel();
if (_steamUser.SteamID != null)
{
_steamUser.LogOff();
}
_steamClient.Disconnect();
}
#region Private Helper Methods
private async Task EnsureConnectedAsync()
{
if (_callbackTask == null)
{
_cts = new CancellationTokenSource();
_steamClient.Connect();
// Run callback loop in background
_callbackTask = Task.Run(() =>
{
while (!_cts.Token.IsCancellationRequested)
{
_manager.RunWaitCallbacks(TimeSpan.FromMilliseconds(500));
Thread.Sleep(10);
}
}, _cts.Token);
var connectionTcs = new TaskCompletionSource<bool>();
var connectionSub = _manager.Subscribe<SteamClient.ConnectedCallback>(_ =>
{
connectionTcs.TrySetResult(true);
});
try
{
// Wait up to 10 seconds for connection
var timeoutTask = Task.Delay(TimeSpan.FromSeconds(10));
var completedTask = await Task.WhenAny(connectionTcs.Task, timeoutTask);
if (completedTask == timeoutTask)
{
throw new TimeoutException("Connection to Steam timed out");
}
}
finally
{
// _manager.Unsubscribe(connectionSub);
}
}
}
private static async Task SendSseEvent(HttpResponse response, string eventType, object data)
{
var json = System.Text.Json.JsonSerializer.Serialize(data);
await response.WriteAsync($"event: {eventType}\n");
await response.WriteAsync($"data: {json}\n\n");
await response.Body.FlushAsync();
}
#endregion
#region Callback Handlers
private void OnConnected(SteamClient.ConnectedCallback callback)
{
Console.WriteLine("Connected to Steam");
}
private void OnDisconnected(SteamClient.DisconnectedCallback callback)
{
Console.WriteLine("Disconnected from Steam");
// Only try to reconnect if not deliberately disconnected
if (_callbackTask != null && !_cts!.IsCancellationRequested)
{
Task.Delay(TimeSpan.FromSeconds(5)).ContinueWith(_ => _steamClient.Connect());
}
}
private void OnLoggedOn(SteamUser.LoggedOnCallback callback)
{
var success = callback.Result == EResult.OK;
Console.WriteLine($"Logged on: {success}");
// Complete all pending auth completion sources
foreach (var tcs in _authCompletionSources.Values)
{
tcs.TrySetResult(success);
}
}
private void OnLoggedOff(SteamUser.LoggedOffCallback callback)
{
Console.WriteLine($"Logged off: {callback.Result}");
}
#endregion
}
public class LoginResult
{
public bool Success { get; set; }
public ulong? SteamId { get; set; }
public string? Username { get; set; }
public string? ErrorMessage { get; set; }
}
public class UserInfo
{
public ulong SteamId { get; set; }
public string? Username { get; set; }
public string? PersonaName { get; set; }
public string? Country { get; set; }
public string? Email { get; set; }
public string? AvatarUrl { get; set; }
public ulong GameId { get; set; }
public string? GamePlayingName { get; set; }
public DateTime LastLogOn { get; set; }
public DateTime LastLogOff { get; set; }
}
}

View File

@@ -1,357 +0,0 @@
using SteamKit2;
using SteamKit2.Authentication;
// Steam client handler
public class SteamClientHandler
{
private readonly string _clientId;
private readonly SteamClient _steamClient;
private readonly CallbackManager _manager;
private readonly SteamUser _steamUser;
public event Action<ServerSentEvent>? OnEvent;
private readonly List<Action<string>> _subscribers = new();
private QrAuthSession? _authSession;
private Task? _callbackTask;
private CancellationTokenSource? _cts;
private bool _isAuthenticated = false;
public SteamUserInfo? UserInfo { get; private set; }
// Add a callback for when credentials are obtained
private readonly Action<string, string>? _onCredentialsObtained;
// Update constructor to optionally receive the callback
public SteamClientHandler(string clientId, Action<string, string>? onCredentialsObtained = null)
{
_clientId = clientId;
_onCredentialsObtained = onCredentialsObtained;
_steamClient = new SteamClient(SteamConfiguration.Create(e => e.WithConnectionTimeout(TimeSpan.FromSeconds(120))));
_manager = new CallbackManager(_steamClient);
_steamUser = _steamClient.GetHandler<SteamUser>()!;
// Register callbacks
_manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
_manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
_manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
_manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
}
// Add method to login with stored credentials
public async Task<bool> LoginWithStoredCredentialsAsync(string accountName, string refreshToken)
{
if (_callbackTask != null)
{
return _isAuthenticated; // Already connected
}
_cts = new CancellationTokenSource();
// Connect to Steam
Console.WriteLine($"[{_clientId}] Connecting to Steam with stored credentials...");
_steamClient.Connect();
// Start callback loop
_callbackTask = Task.Run(async () =>
{
while (!_cts.Token.IsCancellationRequested)
{
_manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
await Task.Delay(10);
}
}, _cts.Token);
// Wait for connection
var connectionTask = new TaskCompletionSource<bool>();
var connectedHandler = _manager.Subscribe<SteamClient.ConnectedCallback>(callback =>
{
// Once connected, try to log in with stored credentials
Console.WriteLine($"[{_clientId}] Connected to Steam, logging in with stored credentials");
_steamUser.LogOn(new SteamUser.LogOnDetails
{
Username = accountName,
AccessToken = refreshToken
});
connectionTask.TrySetResult(true);
});
// Set up a handler for the login result
var loginResultTask = new TaskCompletionSource<bool>();
var loggedOnHandler = _manager.Subscribe<SteamUser.LoggedOnCallback>(callback =>
{
if (callback.Result == EResult.OK)
{
Console.WriteLine($"[{_clientId}] Successfully logged on with stored credentials");
_isAuthenticated = true;
UserInfo = new SteamUserInfo
{
SteamId = callback.ClientSteamID.ToString(),
Username = accountName
};
loginResultTask.TrySetResult(true);
}
else
{
Console.WriteLine($"[{_clientId}] Failed to log on with stored credentials: {callback.Result}");
loginResultTask.TrySetResult(false);
}
});
// Add a timeout
var timeoutTask = Task.Delay(TimeSpan.FromSeconds(30));
try
{
await connectionTask.Task;
var completedTask = await Task.WhenAny(loginResultTask.Task, timeoutTask);
if (completedTask == timeoutTask)
{
Console.WriteLine($"[{_clientId}] Login with stored credentials timed out");
Shutdown();
return false;
}
return await loginResultTask.Task;
}
catch (Exception ex)
{
Console.WriteLine($"[{_clientId}] Error logging in with stored credentials: {ex.Message}");
return false;
}
// finally
// {
// _manager.Unsubscribe(connectedHandler);
// _manager.Unsubscribe(loggedOnHandler);
// }
}
public async Task StartAuthenticationAsync()
{
if (_callbackTask != null)
{
// Authentication already in progress
if (_authSession != null)
{
// Just resend the current QR code URL to all subscribers
NotifySubscribers(_authSession.ChallengeURL);
}
return;
}
_cts = new CancellationTokenSource();
// Connect to Steam
Console.WriteLine($"[{_clientId}] Connecting to Steam...");
_steamClient.Connect();
// Start callback loop
_callbackTask = Task.Run(async () =>
{
while (!_cts.Token.IsCancellationRequested)
{
_manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
await Task.Delay(10);
}
}, _cts.Token);
}
private void NotifyEvent(ServerSentEvent evt)
{
OnEvent?.Invoke(evt);
// Also notify the legacy subscribers with just the URL if this is a URL event
if (evt.Type == "url" && evt.Data is string url)
{
NotifySubscribers(url);
}
}
private async void OnConnected(SteamClient.ConnectedCallback callback)
{
Console.WriteLine($"[{_clientId}] Connected to Steam");
try
{
// Start QR authentication session
_authSession = await _steamClient.Authentication.BeginAuthSessionViaQRAsync(new AuthSessionDetails());
// Handle QR code URL changes
_authSession.ChallengeURLChanged = () =>
{
Console.WriteLine($"[{_clientId}] QR challenge URL refreshed");
NotifyEvent(new ServerSentEvent("url", _authSession.ChallengeURL));
};
// Send initial QR code URL
NotifyEvent(new ServerSentEvent("url", _authSession.ChallengeURL));
// Start polling for authentication result
await Task.Run(async () =>
{
try
{
var pollResponse = await _authSession.PollingWaitForResultAsync();
Console.WriteLine($"[{_clientId}] Logging in as '{pollResponse.AccountName}'");
// Send login attempt event
NotifyEvent(new ServerSentEvent("login-attempt", new { username = pollResponse.AccountName }));
// Login to Steam
_steamUser.LogOn(new SteamUser.LogOnDetails
{
Username = pollResponse.AccountName,
AccessToken = pollResponse.RefreshToken,
});
}
catch (Exception ex)
{
Console.WriteLine($"[{_clientId}] Authentication polling error: {ex.Message}");
NotifyEvent(new ServerSentEvent("login-unsuccessful", new { error = ex.Message }));
}
});
}
catch (Exception ex)
{
Console.WriteLine($"[{_clientId}] Error starting authentication: {ex.Message}");
NotifyEvent(new ServerSentEvent("login-unsuccessful", new { error = ex.Message }));
}
}
private void OnDisconnected(SteamClient.DisconnectedCallback callback)
{
Console.WriteLine($"[{_clientId}] Disconnected from Steam");
_isAuthenticated = false;
UserInfo = null;
// Reconnect if not intentionally stopped
if (_callbackTask != null && !_cts.IsCancellationRequested)
{
Console.WriteLine($"[{_clientId}] Reconnecting...");
_steamClient.Connect();
}
}
private void OnLoggedOn(SteamUser.LoggedOnCallback callback)
{
if (callback.Result != EResult.OK)
{
Console.WriteLine($"[{_clientId}] Unable to log on to Steam: {callback.Result} / {callback.ExtendedResult}");
NotifyEvent(new ServerSentEvent("login-unsuccessful", new
{
error = $"Steam login failed: {callback.Result}",
extendedError = callback.ExtendedResult.ToString()
}));
return;
}
Console.WriteLine($"[{_clientId}] Successfully logged on as {callback.ClientSteamID}");
_isAuthenticated = true;
// Get the username from the authentication session
string accountName = _authSession?.PollingWaitForResultAsync().Result.AccountName ?? "Unknown";
string refreshToken = _authSession?.PollingWaitForResultAsync().Result.RefreshToken ?? "";
UserInfo = new SteamUserInfo
{
SteamId = callback.ClientSteamID.ToString(),
Username = accountName
};
// Send login success event
NotifyEvent(new ServerSentEvent("login-success", new
{
steamId = callback.ClientSteamID.ToString(),
username = accountName
}));
// Save credentials if callback is provided
if (_onCredentialsObtained != null && !string.IsNullOrEmpty(refreshToken))
{
_onCredentialsObtained(accountName, refreshToken);
}
}
private void OnLoggedOff(SteamUser.LoggedOffCallback callback)
{
Console.WriteLine($"[{_clientId}] Logged off of Steam: {callback.Result}");
_isAuthenticated = false;
UserInfo = null;
//Unnecessary but just in case the frontend wants to listen to this
NotifyEvent(new ServerSentEvent("logged-off", new
{
reason = callback.Result.ToString()
}));
}
public Action Subscribe(Action<ServerSentEvent> callback)
{
OnEvent += callback;
// If we already have a QR code URL, send it immediately
if (_authSession != null)
{
callback(new ServerSentEvent("url", _authSession.ChallengeURL));
}
return () => OnEvent -= callback;
}
// Keep the old Subscribe method for backward compatibility
public Action Subscribe(Action<string> callback)
{
lock (_subscribers)
{
_subscribers.Add(callback);
// If we already have a QR code URL, send it immediately
if (_authSession != null)
{
callback(_authSession.ChallengeURL);
}
}
return () =>
{
lock (_subscribers)
{
_subscribers.Remove(callback);
}
};
}
private void NotifySubscribers(string url)
{
lock (_subscribers)
{
foreach (var subscriber in _subscribers)
{
try
{
subscriber(url);
}
catch (Exception ex)
{
Console.WriteLine($"[{_clientId}] Error notifying subscriber: {ex.Message}");
}
}
}
}
public void Shutdown()
{
_cts?.Cancel();
_steamClient.Disconnect();
}
}
public class SteamUserInfo
{
public string SteamId { get; set; } = string.Empty;
public string Username { get; set; } = string.Empty;
}

View File

@@ -1,156 +0,0 @@
using SteamKit2;
using SteamKit2.Authentication;
using Microsoft.EntityFrameworkCore;
using System.Collections.Concurrent;
// Steam Service
public class SteamService
{
private readonly ConcurrentDictionary<string, SteamClientHandler> _clientHandlers = new();
private readonly IServiceProvider _serviceProvider;
public SteamService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public Action SubscribeToEvents(string clientId, Action<ServerSentEvent> callback)
{
if (_clientHandlers.TryGetValue(clientId, out var handler))
{
return handler.Subscribe(callback);
}
return () => { }; // Empty unsubscribe function
}
public async Task StartAuthentication(string teamId, string userId)
{
var clientId = $"{teamId}:{userId}";
// Check if we already have stored credentials
using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<SteamDbContext>();
var storedCredential = await dbContext.SteamUserCredentials
.FirstOrDefaultAsync(c => c.TeamId == teamId && c.UserId == userId);
var handler = _clientHandlers.GetOrAdd(clientId, id => new SteamClientHandler(id,
async (accountName, refreshToken) => await SaveCredentials(teamId, userId, accountName, refreshToken)));
if (storedCredential != null)
{
// We have stored credentials, try to use them
var success = await handler.LoginWithStoredCredentialsAsync(storedCredential.AccountName, storedCredential.RefreshToken);
// If login failed, start fresh authentication
if (!success)
{
await handler.StartAuthenticationAsync();
}
return;
}
// No stored credentials, start fresh authentication
await handler.StartAuthenticationAsync();
}
private async Task SaveCredentials(string teamId, string userId, string accountName, string refreshToken)
{
try
{
using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<SteamDbContext>();
var existingCredential = await dbContext.SteamUserCredentials
.FirstOrDefaultAsync(c => c.TeamId == teamId && c.UserId == userId);
if (existingCredential != null)
{
// Update existing record
existingCredential.AccountName = accountName;
existingCredential.RefreshToken = refreshToken;
existingCredential.UpdatedAt = DateTime.UtcNow;
}
else
{
// Create new record
dbContext.SteamUserCredentials.Add(new SteamUserCredential
{
TeamId = teamId,
UserId = userId,
AccountName = accountName,
RefreshToken = refreshToken
});
}
await dbContext.SaveChangesAsync();
Console.WriteLine($"Saved Steam credentials for {teamId}:{userId}");
}
catch (Exception ex)
{
Console.WriteLine($"Error saving credentials: {ex.Message}");
}
}
public async Task<SteamUserInfo?> GetUserInfoFromStoredCredentials(string teamId, string userId)
{
var clientId = $"{teamId}:{userId}";
// Check if we have an active session
if (_clientHandlers.TryGetValue(clientId, out var activeHandler) && activeHandler.UserInfo != null)
{
return activeHandler.UserInfo;
}
// Try to get stored credentials
using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<SteamDbContext>();
var storedCredential = await dbContext.SteamUserCredentials
.FirstOrDefaultAsync(c => c.TeamId == teamId && c.UserId == userId);
if (storedCredential == null)
{
return null; // No stored credentials
}
// Create a new handler and try to log in
var handler = new SteamClientHandler(clientId);
var success = await handler.LoginWithStoredCredentialsAsync(
storedCredential.AccountName,
storedCredential.RefreshToken);
if (success)
{
_clientHandlers.TryAdd(clientId, handler);
return handler.UserInfo;
}
// Login failed, credentials might be invalid
return null;
}
public Action Subscribe(string clientId, Action<string> callback)
{
if (_clientHandlers.TryGetValue(clientId, out var handler))
{
return handler.Subscribe(callback);
}
return () => { }; // Empty unsubscribe function
}
public void Unsubscribe(string clientId, Action unsubscribeAction)
{
unsubscribeAction();
}
public SteamUserInfo? GetUserInfo(string clientId)
{
if (_clientHandlers.TryGetValue(clientId, out var handler))
{
return handler.UserInfo;
}
return null;
}
}

View File

@@ -2,7 +2,8 @@
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
}
}

347
packages/steam/index.ts Normal file
View File

@@ -0,0 +1,347 @@
// steam-auth-client.ts
import { request as httpRequest } from 'node:http';
import { connect as netConnect } from 'node:net';
import { Socket } from 'node:net';
/**
* Event types emitted by the SteamAuthClient
*/
export enum SteamAuthEvent {
CHALLENGE_URL = 'challenge_url',
STATUS_UPDATE = 'status_update',
CREDENTIALS = 'credentials',
LOGIN_SUCCESS = 'login_success',
LOGIN_ERROR = 'login_error',
ERROR = 'error'
}
/**
* Interface for Steam credentials
*/
export interface SteamCredentials {
username: string;
refreshToken: string;
}
/**
* Options for SteamAuthClient constructor
*/
export interface SteamAuthClientOptions {
socketPath?: string;
}
/**
* SteamAuthClient provides methods to authenticate with Steam
* through a C# service over Unix sockets.
*/
export class SteamAuthClient {
private socketPath: string;
private activeSocket: Socket | null = null;
private eventListeners: Map<string, Function[]> = new Map();
/**
* Creates a new Steam authentication client
*
* @param options Configuration options
*/
constructor(options: SteamAuthClientOptions = {}) {
this.socketPath = options.socketPath || '/tmp/steam.sock';
}
/**
* Checks if the Steam service is healthy
*
* @returns Promise resolving to true if service is healthy
*/
async checkHealth(): Promise<boolean> {
try {
await this.makeRequest({ method: 'GET', path: '/' });
return true;
} catch (error) {
return false;
}
}
/**
* Starts the QR code login flow
*
* @returns Promise that resolves when login completes (success or failure)
*/
startQRLogin(): Promise<void> {
return new Promise<void>((resolve) => {
// Create Socket connection for SSE
this.activeSocket = netConnect({ path: this.socketPath });
// Build the HTTP request manually for SSE
const request =
'GET /api/steam/login HTTP/1.1\r\n' +
'Host: localhost\r\n' +
'Accept: text/event-stream\r\n' +
'Cache-Control: no-cache\r\n' +
'Connection: keep-alive\r\n\r\n';
this.activeSocket.on('connect', () => {
this.activeSocket?.write(request);
});
this.activeSocket.on('error', (error) => {
this.emit(SteamAuthEvent.ERROR, { error: error.message });
resolve();
});
// Simple parser for SSE events over raw socket
let buffer = '';
let eventType = '';
let eventData = '';
this.activeSocket.on('data', (data) => {
const chunk = data.toString();
buffer += chunk;
// Skip HTTP headers if present
if (buffer.includes('\r\n\r\n')) {
const headerEnd = buffer.indexOf('\r\n\r\n');
buffer = buffer.substring(headerEnd + 4);
}
// Process each complete event
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // Keep the last incomplete line in buffer
for (const line of lines) {
if (line.startsWith('event: ')) {
eventType = line.substring(7);
} else if (line.startsWith('data: ')) {
eventData = line.substring(6);
// Complete event received
if (eventType && eventData) {
try {
const parsedData = JSON.parse(eventData);
// Handle specific events
if (eventType === 'challenge_url') {
this.emit(SteamAuthEvent.CHALLENGE_URL, parsedData);
} else if (eventType === 'credentials') {
this.emit(SteamAuthEvent.CREDENTIALS, {
username: parsedData.username,
refreshToken: parsedData.refreshToken
});
} else if (eventType === 'login-success') {
this.emit(SteamAuthEvent.LOGIN_SUCCESS, { steamId: parsedData.steamId });
this.closeSocket();
resolve();
} else if (eventType === 'status') {
this.emit(SteamAuthEvent.STATUS_UPDATE, parsedData);
} else if (eventType === 'error' || eventType === 'login-unsuccessful') {
this.emit(SteamAuthEvent.LOGIN_ERROR, {
message: parsedData.message || parsedData.error
});
this.closeSocket();
resolve();
} else {
// Emit any other events as is
this.emit(eventType, parsedData);
}
} catch (e) {
this.emit(SteamAuthEvent.ERROR, {
error: `Error parsing event data: ${e}`
});
}
// Reset for next event
eventType = '';
eventData = '';
}
}
}
});
});
}
/**
* Logs in with existing credentials
*
* @param credentials Steam credentials
* @returns Promise resolving to login result
*/
async loginWithCredentials(credentials: SteamCredentials): Promise<{
success: boolean,
steamId?: string,
errorMessage?: string
}> {
try {
const response = await this.makeRequest({
method: 'POST',
path: '/api/steam/login-with-credentials',
body: credentials
});
if (response.success) {
return {
success: true,
steamId: response.steamId
};
} else {
return {
success: false,
errorMessage: response.errorMessage || 'Unknown error'
};
}
} catch (error: any) {
return {
success: false,
errorMessage: error.message
};
}
}
/**
* Gets user information using the provided credentials
*
* @param credentials Steam credentials
* @returns Promise resolving to user information
*/
async getUserInfo(credentials: SteamCredentials): Promise<any> {
try {
return await this.makeRequest({
method: 'GET',
path: '/api/steam/user',
headers: {
'X-Steam-Username': credentials.username,
'X-Steam-Token': credentials.refreshToken
}
});
} catch (error: any) {
throw new Error(`Failed to fetch user info: ${error.message}`);
}
}
/**
* Adds an event listener
*
* @param event Event name to listen for
* @param callback Function to call when event occurs
*/
on(event: string, callback: Function): void {
if (!this.eventListeners.has(event)) {
this.eventListeners.set(event, []);
}
this.eventListeners.get(event)?.push(callback);
}
/**
* Removes an event listener
*
* @param event Event name
* @param callback Function to remove
*/
off(event: string, callback: Function): void {
if (!this.eventListeners.has(event)) {
return;
}
const listeners = this.eventListeners.get(event);
if (listeners) {
const index = listeners.indexOf(callback);
if (index !== -1) {
listeners.splice(index, 1);
}
}
}
/**
* Removes all event listeners
*/
removeAllListeners(): void {
this.eventListeners.clear();
}
/**
* Closes the active socket connection
*/
closeSocket(): void {
if (this.activeSocket) {
this.activeSocket.end();
this.activeSocket = null;
}
}
/**
* Cleans up resources
*/
destroy(): void {
this.closeSocket();
this.removeAllListeners();
}
/**
* Internal method to emit events to listeners
*
* @param event Event name
* @param data Event data
*/
private emit(event: string, data: any): void {
const listeners = this.eventListeners.get(event);
if (listeners) {
for (const callback of listeners) {
callback(data);
}
}
}
/**
* Makes HTTP requests over Unix socket
*
* @param options Request options
* @returns Promise resolving to response
*/
private makeRequest(options: {
method: string;
path: string;
headers?: Record<string, string>;
body?: any;
}): Promise<any> {
return new Promise((resolve, reject) => {
const req = httpRequest({
socketPath: this.socketPath,
method: options.method,
path: options.path,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
...options.headers
}
}, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
try {
if (data && data.length > 0) {
resolve(JSON.parse(data));
} else {
resolve(null);
}
} catch (e) {
resolve(data); // Return raw data if not JSON
}
} else {
reject(new Error(`Request failed with status ${res.statusCode}: ${data}`));
}
});
});
req.on('error', (error) => {
reject(error);
});
if (options.body) {
req.write(JSON.stringify(options.body));
}
req.end();
});
}
}

View File

@@ -0,0 +1,26 @@
{
"name": "steam",
"module": "index.ts",
"type": "module",
"private": true,
"scripts": {
"dev": "dotnet watch run",
"client": "bun index",
"client:node": "ts-node index",
"build": "dotnet build",
"db:migrate": "dotnet ef migrations add"
},
"devDependencies": {
"@types/bun": "latest",
"ts-node": "^10.9.2"
},
"peerDependencies": {
"typescript": "^5"
},
"dependencies": {
"eventsource": "^3.0.6",
"qrcode": "^1.5.4",
"qrcode-terminal": "^0.12.0",
"ws": "^8.18.1"
}
}

9
packages/steam/sst-env.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
/* This file is auto-generated by SST. Do not edit. */
/* tslint:disable */
/* eslint-disable */
/* deno-fmt-ignore-file */
/// <reference path="../../sst-env.d.ts" />
import "sst"
export {}

View File

@@ -7,13 +7,14 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.14" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.14" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.3" />
<PackageReference Include="SteamKit2" Version="3.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,6 @@
@steam_HostAddress = http://localhost:5221
GET {{steam_HostAddress}}/weatherforecast/
Accept: application/json
###

301
packages/steam/terminal.ts Normal file
View File

@@ -0,0 +1,301 @@
import { Agent, request as httpRequest } from 'node:http';
import { connect as netConnect } from 'node:net';
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import qrcode from 'qrcode-terminal';
import { createInterface } from 'node:readline';
// Socket path matching the one in your C# code
const SOCKET_PATH = '/tmp/steam.sock';
const CREDENTIALS_PATH = join(process.cwd(), 'steam-credentials.json');
// Create readline interface for user input
const rl = createInterface({
input: process.stdin,
output: process.stdout
});
// Function to prompt user for input
const question = (query: string): Promise<string> => {
return new Promise(resolve => rl.question(query, resolve));
};
// Function to make HTTP requests over Unix socket
function makeRequest(options: {
method: string;
path: string;
headers?: Record<string, string>;
body?: any;
}): Promise<any> {
return new Promise((resolve, reject) => {
const req = httpRequest({
socketPath: SOCKET_PATH,
method: options.method,
path: options.path,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
...options.headers
}
}, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
try {
if (data && data.length > 0) {
resolve(JSON.parse(data));
} else {
resolve(null);
}
} catch (e) {
resolve(data); // Return raw data if not JSON
}
} else {
reject(new Error(`Request failed with status ${res.statusCode}: ${data}`));
}
});
});
req.on('error', (error) => {
reject(error);
});
if (options.body) {
req.write(JSON.stringify(options.body));
}
req.end();
});
}
// Check if credentials file exists
const credentialsExist = (): boolean => {
return existsSync(CREDENTIALS_PATH);
};
// Load saved credentials
const loadCredentials = (): { username: string, refreshToken: string } => {
try {
const data = readFileSync(CREDENTIALS_PATH, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('Error loading credentials:', error);
return { username: '', refreshToken: '' };
}
};
// Save credentials to file
const saveCredentials = (credentials: { username: string, refreshToken: string }): void => {
try {
writeFileSync(CREDENTIALS_PATH, JSON.stringify(credentials, null, 2));
console.log('💾 Credentials saved to', CREDENTIALS_PATH);
} catch (error) {
console.error('Error saving credentials:', error);
}
};
// Test health check endpoint
async function testHealthCheck(): Promise<boolean> {
console.log('\n🔍 Testing health check endpoint...');
try {
const response = await makeRequest({ method: 'GET', path: '/' });
console.log('✅ Health check successful:', response);
return true;
} catch (error: any) {
console.error('❌ Health check failed:', error.message);
return false;
}
}
// Test QR code login endpoint (SSE)
async function loginWithQrCode(): Promise<{ username: string, refreshToken: string } | null> {
console.log('\n🔍 Starting QR code login...');
return new Promise<{ username: string, refreshToken: string } | null>((resolve) => {
// Create Socket connection for SSE
const socket = netConnect({ path: SOCKET_PATH });
// Build the HTTP request manually for SSE
const request =
'GET /api/steam/login HTTP/1.1\r\n' +
'Host: localhost\r\n' +
'Accept: text/event-stream\r\n' +
'Cache-Control: no-cache\r\n' +
'Connection: keep-alive\r\n\r\n';
socket.on('connect', () => {
console.log('📡 Connected to socket, sending SSE request...');
socket.write(request);
});
socket.on('error', (error) => {
console.error('❌ Socket error:', error.message);
resolve(null);
});
// Simple parser for SSE events over raw socket
let buffer = '';
let eventType = '';
let eventData = '';
let credentials: { username: string, refreshToken: string } | null = null;
socket.on('data', (data) => {
const chunk = data.toString();
buffer += chunk;
// Skip HTTP headers if present
if (buffer.includes('\r\n\r\n')) {
const headerEnd = buffer.indexOf('\r\n\r\n');
buffer = buffer.substring(headerEnd + 4);
}
// Process each complete event
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // Keep the last incomplete line in buffer
for (const line of lines) {
if (line.startsWith('event: ')) {
eventType = line.substring(7);
} else if (line.startsWith('data: ')) {
eventData = line.substring(6);
// Complete event received
if (eventType && eventData) {
try {
const parsedData = JSON.parse(eventData);
console.log(`📬 Received event [${eventType}]`);
// Handle specific events
if (eventType === 'challenge_url') {
console.log('⚠️ Please scan this QR code with the Steam mobile app to authenticate:');
qrcode.generate(parsedData.url, { small: true });
} else if (eventType === 'credentials') {
console.log('🔑 Received credentials!');
credentials = {
username: parsedData.username,
refreshToken: parsedData.refreshToken
};
}else if (eventType === 'status') {
console.log(`\n🔄 Status: ${parsedData.message}\n`);
} else if (eventType === 'login-success' || eventType === 'login-successful') {
console.log(`\n✅ Login successful, Steam ID: ${parsedData.steamId}\n`);
socket.end();
if (credentials) {
saveCredentials(credentials);
}
resolve(credentials);
} else if (eventType === 'error' || eventType === 'login-unsuccessful') {
console.error('❌ Login failed:', parsedData.message || parsedData.error);
socket.end();
resolve(null);
}
} catch (e) {
console.error('❌ Error parsing event data:', e);
}
// Reset for next event
eventType = '';
eventData = '';
}
}
}
});
});
}
// Login with existing credentials
async function loginWithCredentials(credentials: { username: string, refreshToken: string }): Promise<boolean> {
console.log('\n🔍 Logging in with saved credentials...');
try {
const response = await makeRequest({
method: 'POST',
path: '/api/steam/login-with-credentials',
body: credentials
});
if (response.success) {
console.log('✅ Login successful, Steam ID:', response.steamId);
return true;
} else {
console.error('❌ Login failed:', response.errorMessage);
return false;
}
} catch (error: any) {
console.error('❌ Login request failed:', error.message);
return false;
}
}
// Get user info
async function getUserInfo(credentials: { username: string, refreshToken: string }): Promise<any> {
console.log('\n🔍 Fetching user info...');
try {
const response = await makeRequest({
method: 'GET',
path: '/api/steam/user',
headers: {
'X-Steam-Username': credentials.username,
'X-Steam-Token': credentials.refreshToken
}
});
return response;
} catch (error: any) {
console.error('❌ Failed to fetch user info:', error.message);
return null;
}
}
// Main function
async function main() {
// Check health first
const isHealthy = await testHealthCheck();
if (!isHealthy) {
console.error('❌ Service appears to be down. Exiting...');
rl.close();
return;
}
let credentials: { username: string, refreshToken: string } | null = null;
// Check if we have saved credentials
if (credentialsExist()) {
const useExisting = await question('🔑 Found saved credentials. Use them? (y/n): ');
if (useExisting.toLowerCase() === 'y') {
credentials = loadCredentials();
const success = await loginWithCredentials(credentials);
if (!success) {
console.log('⚠️ Saved credentials failed. Let\'s try QR login instead.');
credentials = await loginWithQrCode();
}
} else {
credentials = await loginWithQrCode();
}
} else {
console.log('🔑 No saved credentials found. Starting QR login...');
credentials = await loginWithQrCode();
}
// If we have valid credentials, offer to fetch user info
if (credentials) {
const getInfo = await question('📋 Fetch user info? (y/n): ');
if (getInfo.toLowerCase() === 'y') {
const userInfo = await getUserInfo(credentials);
if (userInfo) {
console.log('\n👤 User Information:');
console.log(JSON.stringify(userInfo, null, 2));
}
}
} else {
console.log('❌ Failed to obtain valid credentials.');
}
rl.close();
}
// Start the program
main().catch(error => {
console.error('Unhandled error:', error);
rl.close();
});

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
// Enable latest features
"lib": ["ESNext", "DOM"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
}
}