commit 06d03bd65e0a1df6f3a2742ed1a5bbc23cb9c802 Author: b016488d-939a-4910-a596-93b77fc9ab9c Date: Fri Jul 24 14:58:44 2026 +0000 njcw5kgsAEy-LEoXmiN5Vg diff --git a/AuthStuff.cs b/AuthStuff.cs new file mode 100644 index 0000000..8024f0d --- /dev/null +++ b/AuthStuff.cs @@ -0,0 +1,129 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.IdentityModel.Tokens; +using sscs2023.Classes.DBs; +using sscs2023.Classes.DBs.DBClasses; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using System.Text.Json; +using static sscs2023.Classes.DBs.DBClasses.PlayerDBClasses; + +namespace sscs2023.Auth +{ + public static class AuthStuff + { + private static readonly string Secret = Environment.GetEnvironmentVariable("JWT_SECRET") ?? "THECRYINGMELONBOYFORTNITETHEBACKROOMSALLSEEINGSKIDDING"; + private static readonly string Issuer = "VANADIUMPROMOROTY"; + + public static string Encode(long accountId) + { + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secret)); + var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + + var player = PlayerDB.Players.FindById(accountId); + var roles = new List(); + roles.Add("gameClient"); + + if (player?.PlayerRoles != null) + { + if (player.PlayerRoles.Contains(PlayerRoles.Developer)) + roles.Add("developer"); + if (player.PlayerRoles.Contains(PlayerRoles.Moderator)) + roles.Add("moderator"); + if (player.PlayerRoles.Contains(PlayerRoles.Keepsake)) + roles.Add("keepsake"); + if (player?.Player?.IsJunior == true) + roles.Add("junior"); + } + + var claims = new List + { + new Claim("sub", accountId.ToString()), + new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64) + }; + + if (roles.Count > 0) + claims.Add(new Claim("role", JsonSerializer.Serialize(roles), JsonClaimValueTypes.JsonArray)); + + var token = new JwtSecurityToken( + issuer: Issuer, + claims: claims, + expires: DateTime.UtcNow.AddHours(12), + signingCredentials: creds + ); + + return new JwtSecurityTokenHandler().WriteToken(token); + } + + public static string GenRefreshToken(long accountId) + { + var player = PlayerDB.Players.FindById(accountId); + if (player == null) + return ""; + + var refreshToken = Convert.ToBase64String(Guid.NewGuid().ToByteArray()) + .Replace('+', '-') + .Replace('/', '_') + .TrimEnd('='); + + player.RefreshToken = refreshToken; + player.RefreshTokenExpires = DateTime.UtcNow.AddHours(12); + PlayerDB.Players.Update(player); + + return refreshToken; + } + + public static long? ValidateRefreshToken(string refreshToken) + { + var player = PlayerDB.Players.FindOne(p => p.RefreshToken == refreshToken); + if (player == null) + return null; + + if (player.RefreshTokenExpires < DateTime.UtcNow) + return null; + + return player.PlayerId; + } + + public static long? GetPlayerId(HttpRequest request) + { + var auth = request.Headers["Authorization"].FirstOrDefault(); + if (string.IsNullOrEmpty(auth) || !auth.StartsWith("Bearer ")) + return null; + + var tokenStr = auth.Substring("Bearer ".Length).Trim(); + + try + { + var handler = new JwtSecurityTokenHandler(); + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secret)); + + handler.ValidateToken(tokenStr, new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = key, + ValidateIssuer = true, + ValidIssuer = Issuer, + ValidateAudience = false, + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero + }, out var validated); + + var jwt = (JwtSecurityToken)validated; + var sub = jwt.Claims.FirstOrDefault(c => c.Type == "sub")?.Value; + + return sub != null ? long.Parse(sub) : null; + } + catch + { + return null; + } + } + + public static FullPlayer? GetCurrentPlayer(HttpRequest request) + { + var id = GetPlayerId(request); + return id.HasValue ? PlayerDB.Players.FindById(id.Value) : null; + } + } +} \ No newline at end of file diff --git a/NameGen.cs b/NameGen.cs new file mode 100644 index 0000000..a3c2088 --- /dev/null +++ b/NameGen.cs @@ -0,0 +1,251 @@ +namespace sscs2023.Classes +{ + public class NameGen + { + public static Random random = new Random(); + + public static List Nouns = new List + { + "Aardvark", "Alpaca", "Ant", "Armadillo", "Badger", "Bat", "Bear", "Bee", "Buffalo", "Butterfly", + "Capybara", "Cat", "Caterpillar", "Chameleon", "Cheetah", "Chicken", "Chimpanzee", "Cobra", + "Coyote", "Crane", "Cricket", "Crow", "Deer", "Dog", "Dolphin", "Donkey", "Dove", "Duck", "Eagle", + "Echidna", "Elephant", "Elk", "Emu", "Ferret", "Flamingo", "Fish", "Fox", "Frog", "Gazelle", "Giraffe", + "Goat", "Goose", "Gorilla", "Hamster", "Hedgehog", "Hippo", "Horse", "Hyena", "Iguana", "Jaguar", + "Jellyfish", + "Kangaroo", + "Kitten", + "Koala", + "Lemming", + "Leopard", + "Lion", + "Lizard", + "Llama", + "Marmoset", + "Monkey", + "Moose", + "Mouse", + "Mule", + "Newt", + "Octopus", + "Opposum", + "Ostrich", + "Otter", + "Owl", + "Oyster", + "Panda", + "Panther", + "Parrot", + "Penguin", + "Pig", + "Pigeon", + "Piranha", + "Platypus", + "Pony", + "Possum", + "Puppy", + "Quail", + "Rabbit", + "Raven", + "Salmon", + "Scorpion", + "Seal", + "Shark", + "Sheep", + "Sloth", + "Snail", + "Squid", + "Squirrel", + "Stork", + "Tapir", + "Tiger", + "Tortoise", + "Tuna", + "Turtle", + "Urchin", + "Viper", + "Vulture", + "Walrus", + "Whale", + "Wombat", + "Yak", + "Zebra" + }; + + public static List Adjectives = new List + { + "Adamant", + "Adorable", + "Adventurous", + "Agreeable", + "Aimless", + "Alert", + "Amused", + "Aromatic", + "Bashful", + "Beautiful", + "Bored", + "Brave", + "Bulbous", + "Busy", + "Calm", + "Carefree", + "Careless", + "Caring", + "Charming", + "Cheerful", + "Clever", + "Clumsy", + "Courageous", + "Cowardly", + "Cozy", + "Crabby", + "Cranky", + "Crawling", + "Creaky", + "Creative", + "Crispy", + "Decisive", + "Deep", + "Delightful", + "Determined", + "Diligent", + "Dull", + "Eager", + "Elated", + "Emotional", + "Enchanting", + "Encouraging", + "Endless", + "Energetic", + "Enthusiastic", + "Excited", + "Exuberant", + "Fair", + "Faithful", + "Fantastic", + "Fastidious", + "Fine", + "Fluttering", + "Fragrant", + "Friendly", + "Fulsome", + "Funny", + "Fussy", + "Fuzzy", + "Generous", + "Gentle", + "Glassy", + "Gloomy", + "Glorious", + "Glowing", + "Good", + "Grand", + "Great", + "Greedy", + "Grimy", + "Happy", + "Hardworking", + "Hasty", + "Healthy", + "Heavy", + "Helpful", + "Hilarious", + "Hopeful", + "Icy", + "Important", + "Inquisitive", + "Jolly", + "Joyful", + "Joyous", + "Kind", + "Lazy", + "Lively", + "Loud", + "Lovely", + "Loyal", + "Lucky", + "Luminous", + "Lumpy", + "Majestic", + "Meek", + "Melodic", + "Mighty", + "Moody", + "Nice", + "Nimble", + "Odd", + "Optimistic", + "Perfect", + "Pervasive", + "Pleasant", + "Plucky", + "Plush", + "Polite", + "Practical", + "Proud", + "Quick", + "Quiet", + "Rapid", + "Redolent", + "Reliable", + "Relieved", + "Royal", + "Rusty", + "Scared", + "Selfish", + "Sensible", + "Sensitive", + "Shining", + "Shrill", + "Silly", + "Sincere", + "Sizzling", + "Sleepy", + "Smiling", + "Smooth", + "Snug", + "Soaring", + "Sparkling", + "Speedy", + "Spiky", + "Splendid", + "Spoiled", + "Steaming", + "Still", + "Strict", + "Stuffed", + "Sturdy", + "Successful", + "Surprised", + "Swift", + "Taciturn", + "Tense", + "Thankful", + "Thoughtful", + "Thrifty", + "Tough", + "Tricky", + "Truthful", + "Ubiquitous", + "Unusual", + "Versatile", + "Victorious", + "Wild", + "Wise", + "Witty", + "Wonderful", + "Worried", + "Wrinkly", + "Zany", + "Zealous" + }; + + public static string GetRandomName() + { + string adjective = Adjectives[random.Next(Adjectives.Count)]; + string noun = Nouns[random.Next(Nouns.Count)]; + int number = random.Next(1000, 99999); + return adjective + noun + number; + } + } +} diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..969b4fc --- /dev/null +++ b/Program.cs @@ -0,0 +1,191 @@ +using System.Runtime.InteropServices; +using Microsoft.AspNetCore.HttpOverrides; +using System.Linq; +using Microsoft.AspNetCore.SignalR; +using Microsoft.AspNetCore.Http.Features; +using sscs2023.Classes.DBs; +using sscs2023.Controllers; +using sscs2023.Hubs; +using sscs2023.Utils.NotiController; +using sscs2023.Services; +using System.Collections.Concurrent; +using System.Net.WebSockets; + +namespace sscs2023 +{ + public class Program + { + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr GetStdHandle(int nStdHandle); + + public static string dataDir = Path.Join(Environment.CurrentDirectory, "Data"); + public static ConcurrentDictionary PendingConnections = new(); + public static ConcurrentDictionary ActiveSockets = new(); + + public static async Task Main(string[] args) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + var handle = GetStdHandle(-11); + SetConsoleMode(handle, 0x0001 | 0x0002 | 0x0004); + } + + var builder = WebApplication.CreateBuilder(args); + + builder.Logging.ClearProviders(); + builder.Logging.AddConsole(); + builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning); + builder.Logging.AddFilter("Microsoft.AspNetCore.Routing", LogLevel.Warning); + builder.Logging.AddFilter("Microsoft.AspNetCore.Mvc", LogLevel.Warning); + builder.Logging.AddFilter("Microsoft.AspNetCore.Hosting", LogLevel.Warning); + + if (!Directory.Exists(dataDir)) + { + Console.WriteLine("Setting up data directory..."); + string[] foldersToCreate = + { + dataDir, + Path.Join(dataDir, "Images"), + Path.Join(dataDir, "Images", "PlayerImages"), + Path.Join(dataDir, "Images", "PolaroidImages"), + Path.Join(dataDir, "CDN", "DataBlobs"), + Path.Join(dataDir, "CDN", "InventionBlobs"), + Path.Join(dataDir, "CDN", "RoomBlobs"), + Path.Join(dataDir, "Imports"), + Path.Join(dataDir, "DBs") + }; + foreach (var folder in foldersToCreate) + Directory.CreateDirectory(folder); + + Console.WriteLine($"Data directory created at {dataDir}"); + } + + builder.Services.Configure(o => + { + o.MultipartBodyLengthLimit = 10_000_000; + }); + + builder.Services.AddControllers().AddJsonOptions(o => + { + o.JsonSerializerOptions.PropertyNamingPolicy = null; + }); + + builder.Services.AddHttpClient(); + + builder.Services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.All; + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); + }); + + builder.Services.AddSignalR(options => + { + options.KeepAliveInterval = TimeSpan.FromSeconds(10); + options.ClientTimeoutInterval = TimeSpan.FromSeconds(30); + options.MaximumReceiveMessageSize = 1_048_576; + options.EnableDetailedErrors = true; + }); + + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddHostedService(); + + var app = builder.Build(); + + var notiService = app.Services.GetRequiredService(); + NotificationsController.Init(notiService); + DiscordBotController.Init(notiService); + + app.Use(async (context, next) => + { + await next(); + + string timeStr = DateTime.UtcNow.ToString("HH:mm:ss"); + string timePart = $"\u001b[91m[{timeStr}]\u001b[0m"; + + string method = context.Request.Method.ToUpper(); + string methodColor = "\u001b[37m"; + + if (method == "GET") + methodColor = "\u001b[32m"; + else if (method == "POST" || method == "PUT") + methodColor = "\u001b[33m"; + else if (method == "DELETE") + methodColor = "\u001b[31m"; + + string methodPart = $"{methodColor}{method}\u001b[0m"; + + string fullUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}"; + string urlPart = $"\u001b[37m{fullUrl}\u001b[0m"; + + int statusCode = context.Response.StatusCode; + string statusColor = "\u001b[37m"; + + if (statusCode >= 100 && statusCode < 200) + statusColor = "\u001b[33m"; + else if (statusCode >= 200 && statusCode < 300) + statusColor = "\u001b[32m"; + else if (statusCode >= 400) + statusColor = "\u001b[31m"; + + string statusPart = $"{statusColor}{statusCode}\u001b[0m"; + + string ip = context.Request.Headers["CF-Connecting-IP"].FirstOrDefault() + ?? context.Connection.RemoteIpAddress?.ToString() + ?? "Unknown"; + + string ipPart = $"\u001b[38;5;208m[{ip}]\u001b[0m"; + + Console.WriteLine($"{timePart} {ipPart} {methodPart}: {urlPart} {statusPart}"); + }); + + app.UseForwardedHeaders(); + app.UseWebSockets(new WebSocketOptions + { + KeepAliveInterval = TimeSpan.FromSeconds(30) + }); + + app.Use(async (context, next) => + { + if (context.Request.Path.StartsWithSegments("/noti/hub/v1") && + !context.Request.Path.Value!.Contains("negotiate") && + context.WebSockets.IsWebSocketRequest) + { + var connectionId = context.Request.Query["id"].ToString(); + + if (!Program.PendingConnections.TryRemove(connectionId, out var playerId)) + { + context.Response.StatusCode = 401; + return; + } + + var ws = await context.WebSockets.AcceptWebSocketAsync(); + await NotificationsController.HandleConnectionAsync(playerId, ws); + return; + } + await next(); + }); + + app.UseRouting(); + app.UseAuthorization(); + app.MapControllers(); + + var adminPlayer = PlayerDB.Players.FindById(1); + if (adminPlayer?.Player != null) + { + adminPlayer.Player.Level = 99; + adminPlayer.Player.XP = PlayerDB.GetXPForLevel(99); + PlayerDB.Players.Update(adminPlayer); + } + + DiscordBotService.Init(notiService); + + sscs2023.Cloudflare.StartCloudflared(); + app.Run("http://localhost:2059"); + } + } +} \ No newline at end of file diff --git a/Sanitize.cs b/Sanitize.cs new file mode 100644 index 0000000..af05d7e --- /dev/null +++ b/Sanitize.cs @@ -0,0 +1,136 @@ +using System.Text; +using System.Text.RegularExpressions; + +namespace sscs2023.Classes +{ + public class Sanitize + { + public string Context { get; set; } = "RoomChat"; + public int Intent { get; set; } = 1; + public bool PreRemoveBlockedCharacters { get; set; } = true; + public string ReplacementChar { get; set; } = "*"; + public string Value { get; set; } = ""; + public int ruleset { get; set; } = 0; + + private const char MaskChar = '*'; + + + private static readonly HashSet Whitelist = new(StringComparer.OrdinalIgnoreCase) + { + "password", + "pass", + "class", + "assistant", + "account" + }; + + private static readonly List<(string Word, Regex Pattern)> SwearPatterns; + + static Sanitize() + { + var swears = File.ReadAllLines("Data/badwords.txt") + .Select(x => x.Trim().ToLowerInvariant()) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Distinct() + .ToList(); + + SwearPatterns = swears + .Select(word => (word, BuildFuzzyRegex(word))) + .ToList(); + } + + public static bool ContainsSwears(string message) + { + if (string.IsNullOrWhiteSpace(message)) + return false; + + if (ServerConfig.AllowSwears) + return false; + + var normalized = Normalize(message); + + return SwearPatterns.Any(p => p.Pattern.IsMatch(normalized)); + } + + public static string SanitizeMessage(string message) + { + if (string.IsNullOrWhiteSpace(message)) + return message; + + var tokens = Regex.Split(message, @"(\W+)"); + var sb = new StringBuilder(message.Length); + + foreach (var token in tokens) + { + if (!IsWord(token)) + { + sb.Append(token); + continue; + } + + var normalized = Normalize(token); + + if (normalized.Length < 3) + { + sb.Append(token); + continue; + } + + if (Whitelist.Contains(normalized)) + { + sb.Append(token); + continue; + } + + bool replaced = false; + + foreach (var (_, pattern) in SwearPatterns) + { + if (pattern.IsMatch(normalized)) + { + sb.Append(new string(MaskChar, token.Length)); + Console.WriteLine($"[Sanitize] Censored word in message: '{token}'"); + replaced = true; + break; + } + } + + if (!replaced) + sb.Append(token); + } + + return sb.ToString(); + } + + private static bool IsWord(string input) => + input.Any(char.IsLetterOrDigit); + + private static Regex BuildFuzzyRegex(string word) + { + var pattern = string.Join(".{0,1}", + word.Select(c => Regex.Escape(c.ToString()))); + + return new Regex( + $"^{pattern}$", + RegexOptions.IgnoreCase | RegexOptions.Compiled + ); + } + + private static string Normalize(string input) + { + input = input.ToLowerInvariant(); + + input = Regex.Replace(input, @"[0@]", "o"); + input = Regex.Replace(input, @"[1!|]", "i"); + input = Regex.Replace(input, @"[$5]", "s"); + input = Regex.Replace(input, @"3", "e"); + input = Regex.Replace(input, @"7", "t"); + + input = Regex.Replace(input, @"[^a-z]", ""); + + input = Regex.Replace(input, @"(.)\1{2,}", "$1$1"); + + return input; + } + } +} \ No newline at end of file diff --git a/VanaNet 2023.csproj b/VanaNet 2023.csproj new file mode 100644 index 0000000..2c149da --- /dev/null +++ b/VanaNet 2023.csproj @@ -0,0 +1,27 @@ + + + + net8.0 + enable + true + enable + + + + + + + + + + + + + + + + + + + +