feat(www): Finish up on the onboarding (#210)

Merging this prematurely to make sure the team is on the same boat... like dang! We need to find a better way to do this. 

Plus it has become too big
This commit is contained in:
Wanjohi
2025-03-26 02:21:53 +03:00
committed by GitHub
parent 957eca7794
commit f62fc1fb4b
106 changed files with 6329 additions and 866 deletions

484
packages/steam/.gitignore vendored Normal file
View File

@@ -0,0 +1,484 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from `dotnet new gitignore`
# dotenv files
.env
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET
project.lock.json
project.fragment.lock.json
artifacts/
# Tye
.tye/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
.idea
##
## Visual studio for Mac
##
# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/
# Mac bundle stuff
*.dmg
*.app
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# Vim temporary swap files
*.swp

View File

@@ -0,0 +1,18 @@
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

@@ -0,0 +1,12 @@
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,60 @@
// <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

@@ -0,0 +1,46 @@
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

@@ -0,0 +1,57 @@
// <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
}
}
}

331
packages/steam/Program.cs Normal file
View File

@@ -0,0 +1,331 @@
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 =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
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) =>
{
// 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);
}
};
// Add logging for debugging
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Console.WriteLine($"Authentication failed: {context.Exception.Message}");
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
Console.WriteLine("Token successfully validated");
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorization();
// 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))
{
return (false, null, null);
}
}
return (true, userId, email);
}
return (false, null, null);
}
catch (Exception ex)
{
Console.WriteLine($"JWT validation error: {ex.Message}");
return (false, null, null);
}
}
Console.WriteLine("Server started. Press Ctrl+C to stop.");
await app.RunAsync();

View File

@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:12427",
"sslPort": 44354
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5289",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7168;http://localhost:5289",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,19 @@
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,357 @@
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

@@ -0,0 +1,156 @@
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

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" 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" />
</ItemGroup>
</Project>