Some fixes and security updates
This commit is contained in:
parent
43acf366af
commit
68e6fa2353
22 changed files with 1114 additions and 58 deletions
|
|
@ -46,7 +46,13 @@ public class ChatClientConnection : IDisposable
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var res = await _httpClient.GetAsync("/api/info");
|
var request = new HttpRequestMessage(HttpMethod.Get, "/api/info");
|
||||||
|
if (!string.IsNullOrWhiteSpace(_state.Token))
|
||||||
|
{
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _state.Token);
|
||||||
|
}
|
||||||
|
|
||||||
|
var res = await _httpClient.SendAsync(request);
|
||||||
if (res.IsSuccessStatusCode)
|
if (res.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
// Auto-upgrade ServerUrl if redirected to HTTPS
|
// Auto-upgrade ServerUrl if redirected to HTTPS
|
||||||
|
|
@ -67,6 +73,11 @@ public class ChatClientConnection : IDisposable
|
||||||
}
|
}
|
||||||
return info;
|
return info;
|
||||||
}
|
}
|
||||||
|
else if (res.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||||
|
{
|
||||||
|
// Server requires auth for info endpoint, return null and continue
|
||||||
|
return null;
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
_state.SetStatus($"Server returned HTTP {(int)res.StatusCode} ({res.ReasonPhrase}) on /api/info");
|
_state.SetStatus($"Server returned HTTP {(int)res.StatusCode} ({res.ReasonPhrase}) on /api/info");
|
||||||
|
|
@ -79,20 +90,30 @@ public class ChatClientConnection : IDisposable
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthResponse> RegisterAsync(string username, string password, string? serverPassword = null)
|
public async Task<AuthResponse> RegisterAsync(string username, string password, string? serverPassword = null, string? inviteToken = null)
|
||||||
{
|
{
|
||||||
var req = new RegisterRequest
|
var req = new RegisterRequest
|
||||||
{
|
{
|
||||||
Username = username,
|
Username = username,
|
||||||
Password = password,
|
Password = password,
|
||||||
ServerPassword = serverPassword
|
ServerPassword = serverPassword,
|
||||||
|
InviteToken = inviteToken
|
||||||
};
|
};
|
||||||
var json = JsonSerializer.Serialize(req);
|
var json = JsonSerializer.Serialize(req);
|
||||||
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var res = await _httpClient.PostAsync("/api/auth/register", content);
|
var request = new HttpRequestMessage(HttpMethod.Post, "/api/auth/register")
|
||||||
|
{
|
||||||
|
Content = content
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add CSRF token
|
||||||
|
var csrfToken = Guid.NewGuid().ToString("N");
|
||||||
|
request.Headers.Add("X-CSRF-Token", csrfToken);
|
||||||
|
|
||||||
|
var res = await _httpClient.SendAsync(request);
|
||||||
var resJson = await res.Content.ReadAsStringAsync();
|
var resJson = await res.Content.ReadAsStringAsync();
|
||||||
if (string.IsNullOrWhiteSpace(resJson))
|
if (string.IsNullOrWhiteSpace(resJson))
|
||||||
{
|
{
|
||||||
|
|
@ -139,7 +160,16 @@ public class ChatClientConnection : IDisposable
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var res = await _httpClient.PostAsync("/api/auth/login", content);
|
var request = new HttpRequestMessage(HttpMethod.Post, "/api/auth/login")
|
||||||
|
{
|
||||||
|
Content = content
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add CSRF token
|
||||||
|
var csrfToken = Guid.NewGuid().ToString("N");
|
||||||
|
request.Headers.Add("X-CSRF-Token", csrfToken);
|
||||||
|
|
||||||
|
var res = await _httpClient.SendAsync(request);
|
||||||
var resJson = await res.Content.ReadAsStringAsync();
|
var resJson = await res.Content.ReadAsStringAsync();
|
||||||
if (string.IsNullOrWhiteSpace(resJson))
|
if (string.IsNullOrWhiteSpace(resJson))
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ public class Program
|
||||||
string? username = null;
|
string? username = null;
|
||||||
string? password = null;
|
string? password = null;
|
||||||
string? serverPassword = null;
|
string? serverPassword = null;
|
||||||
|
string? inviteToken = null;
|
||||||
bool doRegister = false;
|
bool doRegister = false;
|
||||||
bool allowInsecure = false;
|
bool allowInsecure = false;
|
||||||
|
|
||||||
|
|
@ -32,6 +33,7 @@ public class Program
|
||||||
if (args[i] == "--username" && i + 1 < args.Length) username = args[i + 1];
|
if (args[i] == "--username" && i + 1 < args.Length) username = args[i + 1];
|
||||||
if (args[i] == "--password" && i + 1 < args.Length) password = args[i + 1];
|
if (args[i] == "--password" && i + 1 < args.Length) password = args[i + 1];
|
||||||
if (args[i] == "--server-password" && i + 1 < args.Length) serverPassword = args[i + 1];
|
if (args[i] == "--server-password" && i + 1 < args.Length) serverPassword = args[i + 1];
|
||||||
|
if (args[i] == "--invite-token" && i + 1 < args.Length) inviteToken = args[i + 1];
|
||||||
if (args[i] == "--register") doRegister = true;
|
if (args[i] == "--register") doRegister = true;
|
||||||
if (args[i] == "--insecure") allowInsecure = true;
|
if (args[i] == "--insecure") allowInsecure = true;
|
||||||
}
|
}
|
||||||
|
|
@ -195,6 +197,28 @@ public class Program
|
||||||
serverPassword = ReadMaskedPassword();
|
serverPassword = ReadMaskedPassword();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ask user if they want to login or register (unless specified via CLI or using a saved profile)
|
||||||
|
if (!doRegister && string.IsNullOrEmpty(username) && (selectedProfile == null || string.IsNullOrEmpty(selectedProfile.Username)))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"\n{Ansi.Bold}Choose action:{Ansi.Reset}");
|
||||||
|
Console.WriteLine($" {Ansi.BrightCyan}[L]{Ansi.Reset} Login");
|
||||||
|
Console.WriteLine($" {Ansi.BrightCyan}[R]{Ansi.Reset} Register");
|
||||||
|
Console.Write($"\nSelect option: ");
|
||||||
|
|
||||||
|
char authChoice = ReadKeyChar();
|
||||||
|
if (char.ToUpper(authChoice) == 'R')
|
||||||
|
{
|
||||||
|
doRegister = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle invite token if registering in invite-only mode
|
||||||
|
if (doRegister && info.RegistrationMode == "InviteOnly")
|
||||||
|
{
|
||||||
|
Console.Write("Enter Invite Token: ");
|
||||||
|
inviteToken = Console.ReadLine()?.Trim();
|
||||||
|
}
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(username))
|
if (string.IsNullOrEmpty(username))
|
||||||
{
|
{
|
||||||
// If a profile is selected with a username, skip login/register choice and use the profile
|
// If a profile is selected with a username, skip login/register choice and use the profile
|
||||||
|
|
@ -239,7 +263,7 @@ public class Program
|
||||||
Console.WriteLine(doRegister ? "Registering account..." : "Logging in...");
|
Console.WriteLine(doRegister ? "Registering account..." : "Logging in...");
|
||||||
|
|
||||||
var authResult = doRegister
|
var authResult = doRegister
|
||||||
? await connection.RegisterAsync(username, password, serverPassword)
|
? await connection.RegisterAsync(username, password, serverPassword, inviteToken)
|
||||||
: await connection.LoginAsync(username, password, serverPassword);
|
: await connection.LoginAsync(username, password, serverPassword);
|
||||||
|
|
||||||
if (!authResult.Success || string.IsNullOrEmpty(authResult.Token))
|
if (!authResult.Success || string.IsNullOrEmpty(authResult.Token))
|
||||||
|
|
@ -247,6 +271,7 @@ public class Program
|
||||||
Console.WriteLine($"{Ansi.BrightRed}Authentication failed: {authResult.ErrorMessage}{Ansi.Reset}");
|
Console.WriteLine($"{Ansi.BrightRed}Authentication failed: {authResult.ErrorMessage}{Ansi.Reset}");
|
||||||
username = null;
|
username = null;
|
||||||
password = null;
|
password = null;
|
||||||
|
inviteToken = null;
|
||||||
selectedProfile = null;
|
selectedProfile = null;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
15
src/GsDChat.Core/Models/InviteToken.cs
Normal file
15
src/GsDChat.Core/Models/InviteToken.cs
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Models;
|
||||||
|
|
||||||
|
public class InviteToken
|
||||||
|
{
|
||||||
|
public string Token { get; set; } = string.Empty;
|
||||||
|
public string CreatedByUserId { get; set; } = string.Empty;
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
public DateTime ExpiresAt { get; set; } = DateTime.UtcNow.AddDays(7);
|
||||||
|
public bool IsUsed { get; set; } = false;
|
||||||
|
public DateTime? UsedAt { get; set; }
|
||||||
|
|
||||||
|
public bool IsExpired => DateTime.UtcNow > ExpiresAt;
|
||||||
|
}
|
||||||
|
|
@ -8,6 +8,7 @@ public class Session
|
||||||
public string UserId { get; set; } = string.Empty;
|
public string UserId { get; set; } = string.Empty;
|
||||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
public DateTime ExpiresAt { get; set; } = DateTime.UtcNow.AddDays(30);
|
public DateTime ExpiresAt { get; set; } = DateTime.UtcNow.AddDays(30);
|
||||||
|
public DateTime LastActivityAt { get; set; } = DateTime.UtcNow;
|
||||||
|
|
||||||
public bool IsExpired => DateTime.UtcNow > ExpiresAt;
|
public bool IsExpired => DateTime.UtcNow > ExpiresAt;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -16,4 +16,14 @@ public class ServerOptions
|
||||||
public bool AllowMemberChannelCreation { get; set; } = true;
|
public bool AllowMemberChannelCreation { get; set; } = true;
|
||||||
public bool AllowDmE2ee { get; set; } = true;
|
public bool AllowDmE2ee { get; set; } = true;
|
||||||
public int MaxGroupChatUsers { get; set; } = 10;
|
public int MaxGroupChatUsers { get; set; } = 10;
|
||||||
|
|
||||||
|
// Security Settings
|
||||||
|
public int RateLimitRequestsPerMinute { get; set; } = 60;
|
||||||
|
public int MaxConnectionsPerIp { get; set; } = 10;
|
||||||
|
public int MaxGlobalConnections { get; set; } = 100;
|
||||||
|
public int MaxConcurrentSessionsPerUser { get; set; } = 5;
|
||||||
|
public int InviteTokenExpirationHours { get; set; } = 168; // 7 days
|
||||||
|
public bool RequireAuthForServerInfo { get; set; } = false;
|
||||||
|
public bool EnableCsrfProtection { get; set; } = true;
|
||||||
|
public int MaxWebSocketMessageSizeBytes { get; set; } = 1048576; // 1MB
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -140,6 +140,20 @@ public class ChatDatabase : IDisposable
|
||||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE messages ADD COLUMN is_encrypted INTEGER NOT NULL DEFAULT 0;");
|
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE messages ADD COLUMN is_encrypted INTEGER NOT NULL DEFAULT 0;");
|
||||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE messages ADD COLUMN sender_public_key TEXT;");
|
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE messages ADD COLUMN sender_public_key TEXT;");
|
||||||
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE messages ADD COLUMN recipient_public_key TEXT;");
|
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE messages ADD COLUMN recipient_public_key TEXT;");
|
||||||
|
await TryExecuteColumnMigrationAsync(conn, "ALTER TABLE sessions ADD COLUMN last_activity_at TEXT;");
|
||||||
|
|
||||||
|
// Create invite_tokens table if it doesn't exist
|
||||||
|
await TryExecuteTableMigrationAsync(conn, """
|
||||||
|
CREATE TABLE IF NOT EXISTS invite_tokens (
|
||||||
|
token TEXT PRIMARY KEY,
|
||||||
|
created_by_user_id TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
expires_at TEXT NOT NULL,
|
||||||
|
is_used INTEGER NOT NULL DEFAULT 0,
|
||||||
|
used_at TEXT,
|
||||||
|
FOREIGN KEY (created_by_user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
""");
|
||||||
|
|
||||||
// Seed default channels if none exist
|
// Seed default channels if none exist
|
||||||
var channelsCountCmd = conn.CreateCommand();
|
var channelsCountCmd = conn.CreateCommand();
|
||||||
|
|
@ -182,6 +196,20 @@ public class ChatDatabase : IDisposable
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static async Task TryExecuteTableMigrationAsync(SqliteConnection conn, string sql)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = sql;
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
catch (SqliteException)
|
||||||
|
{
|
||||||
|
// Table already exists or other migration issue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static async Task<bool> CreateChannelInternalAsync(SqliteConnection conn, Channel channel)
|
private static async Task<bool> CreateChannelInternalAsync(SqliteConnection conn, Channel channel)
|
||||||
{
|
{
|
||||||
using var cmd = conn.CreateCommand();
|
using var cmd = conn.CreateCommand();
|
||||||
|
|
@ -386,14 +414,15 @@ public class ChatDatabase : IDisposable
|
||||||
using var conn = CreateConnection();
|
using var conn = CreateConnection();
|
||||||
using var cmd = conn.CreateCommand();
|
using var cmd = conn.CreateCommand();
|
||||||
cmd.CommandText = """
|
cmd.CommandText = """
|
||||||
INSERT INTO sessions (token, user_id, created_at, expires_at)
|
INSERT INTO sessions (token, user_id, created_at, expires_at, last_activity_at)
|
||||||
VALUES (@token, @user_id, @created_at, @expires_at)
|
VALUES (@token, @user_id, @created_at, @expires_at, @last_activity_at)
|
||||||
ON CONFLICT(token) DO UPDATE SET expires_at = @expires_at;
|
ON CONFLICT(token) DO UPDATE SET expires_at = @expires_at, last_activity_at = @last_activity_at;
|
||||||
""";
|
""";
|
||||||
cmd.Parameters.AddWithValue("@token", session.Token);
|
cmd.Parameters.AddWithValue("@token", session.Token);
|
||||||
cmd.Parameters.AddWithValue("@user_id", session.UserId);
|
cmd.Parameters.AddWithValue("@user_id", session.UserId);
|
||||||
cmd.Parameters.AddWithValue("@created_at", session.CreatedAt.ToString("O"));
|
cmd.Parameters.AddWithValue("@created_at", session.CreatedAt.ToString("O"));
|
||||||
cmd.Parameters.AddWithValue("@expires_at", session.ExpiresAt.ToString("O"));
|
cmd.Parameters.AddWithValue("@expires_at", session.ExpiresAt.ToString("O"));
|
||||||
|
cmd.Parameters.AddWithValue("@last_activity_at", session.LastActivityAt.ToString("O"));
|
||||||
|
|
||||||
await cmd.ExecuteNonQueryAsync();
|
await cmd.ExecuteNonQueryAsync();
|
||||||
}
|
}
|
||||||
|
|
@ -402,7 +431,7 @@ public class ChatDatabase : IDisposable
|
||||||
{
|
{
|
||||||
using var conn = CreateConnection();
|
using var conn = CreateConnection();
|
||||||
using var cmd = conn.CreateCommand();
|
using var cmd = conn.CreateCommand();
|
||||||
cmd.CommandText = "SELECT token, user_id, created_at, expires_at FROM sessions WHERE token = @token LIMIT 1;";
|
cmd.CommandText = "SELECT token, user_id, created_at, expires_at, last_activity_at FROM sessions WHERE token = @token LIMIT 1;";
|
||||||
cmd.Parameters.AddWithValue("@token", token);
|
cmd.Parameters.AddWithValue("@token", token);
|
||||||
|
|
||||||
using var reader = await cmd.ExecuteReaderAsync();
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
|
@ -413,12 +442,24 @@ public class ChatDatabase : IDisposable
|
||||||
Token = reader.GetString(0),
|
Token = reader.GetString(0),
|
||||||
UserId = reader.GetString(1),
|
UserId = reader.GetString(1),
|
||||||
CreatedAt = DateTime.Parse(reader.GetString(2)),
|
CreatedAt = DateTime.Parse(reader.GetString(2)),
|
||||||
ExpiresAt = DateTime.Parse(reader.GetString(3))
|
ExpiresAt = DateTime.Parse(reader.GetString(3)),
|
||||||
|
LastActivityAt = reader.IsDBNull(4) ? DateTime.Parse(reader.GetString(2)) : DateTime.Parse(reader.GetString(4))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task UpdateSessionActivityAsync(string token)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "UPDATE sessions SET last_activity_at = @last_activity_at WHERE token = @token;";
|
||||||
|
cmd.Parameters.AddWithValue("@token", token);
|
||||||
|
cmd.Parameters.AddWithValue("@last_activity_at", DateTime.UtcNow.ToString("O"));
|
||||||
|
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
public async Task DeleteSessionAsync(string token)
|
public async Task DeleteSessionAsync(string token)
|
||||||
{
|
{
|
||||||
using var conn = CreateConnection();
|
using var conn = CreateConnection();
|
||||||
|
|
@ -428,6 +469,33 @@ public class ChatDatabase : IDisposable
|
||||||
await cmd.ExecuteNonQueryAsync();
|
await cmd.ExecuteNonQueryAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<int> GetActiveSessionCountAsync(string userId)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "SELECT COUNT(*) FROM sessions WHERE user_id = @user_id AND expires_at > datetime('now');";
|
||||||
|
cmd.Parameters.AddWithValue("@user_id", userId);
|
||||||
|
var result = await cmd.ExecuteScalarAsync();
|
||||||
|
return Convert.ToInt32(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task CleanupExpiredSessionsAsync()
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "DELETE FROM sessions WHERE expires_at < datetime('now');";
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DeleteAllUserSessionsAsync(string userId)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "DELETE FROM sessions WHERE user_id = @user_id;";
|
||||||
|
cmd.Parameters.AddWithValue("@user_id", userId);
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Channel, DM & Group Chat Operations
|
#region Channel, DM & Group Chat Operations
|
||||||
|
|
@ -1012,6 +1080,108 @@ public class ChatDatabase : IDisposable
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
#region Invite Token Operations
|
||||||
|
|
||||||
|
public async Task CreateInviteTokenAsync(string token, string createdByUserId, DateTime expiresAt)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
INSERT INTO invite_tokens (token, created_by_user_id, created_at, expires_at, is_used, used_at)
|
||||||
|
VALUES (@token, @created_by, @created_at, @expires_at, 0, NULL);
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@token", token);
|
||||||
|
cmd.Parameters.AddWithValue("@created_by", createdByUserId);
|
||||||
|
cmd.Parameters.AddWithValue("@created_at", DateTime.UtcNow.ToString("O"));
|
||||||
|
cmd.Parameters.AddWithValue("@expires_at", expiresAt.ToString("O"));
|
||||||
|
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<InviteToken?> GetInviteTokenAsync(string token)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
SELECT token, created_by_user_id, created_at, expires_at, is_used, used_at
|
||||||
|
FROM invite_tokens
|
||||||
|
WHERE token = @token
|
||||||
|
LIMIT 1;
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@token", token);
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
if (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
return new InviteToken
|
||||||
|
{
|
||||||
|
Token = reader.GetString(0),
|
||||||
|
CreatedByUserId = reader.GetString(1),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(2)),
|
||||||
|
ExpiresAt = DateTime.Parse(reader.GetString(3)),
|
||||||
|
IsUsed = reader.GetInt32(4) == 1,
|
||||||
|
UsedAt = reader.IsDBNull(5) ? null : DateTime.Parse(reader.GetString(5))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task MarkInviteTokenAsUsedAsync(string token)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
UPDATE invite_tokens
|
||||||
|
SET is_used = 1, used_at = @used_at
|
||||||
|
WHERE token = @token;
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@token", token);
|
||||||
|
cmd.Parameters.AddWithValue("@used_at", DateTime.UtcNow.ToString("O"));
|
||||||
|
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DeleteInviteTokenAsync(string token)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "DELETE FROM invite_tokens WHERE token = @token;";
|
||||||
|
cmd.Parameters.AddWithValue("@token", token);
|
||||||
|
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<InviteToken>> GetActiveInviteTokensAsync(string createdByUserId)
|
||||||
|
{
|
||||||
|
var tokens = new List<InviteToken>();
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
SELECT token, created_by_user_id, created_at, expires_at, is_used, used_at
|
||||||
|
FROM invite_tokens
|
||||||
|
WHERE created_by_user_id = @user_id AND is_used = 0 AND expires_at > datetime('now')
|
||||||
|
ORDER BY created_at DESC;
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@user_id", createdByUserId);
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
while (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
tokens.Add(new InviteToken
|
||||||
|
{
|
||||||
|
Token = reader.GetString(0),
|
||||||
|
CreatedByUserId = reader.GetString(1),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(2)),
|
||||||
|
ExpiresAt = DateTime.Parse(reader.GetString(3)),
|
||||||
|
IsUsed = reader.GetInt32(4) == 1,
|
||||||
|
UsedAt = reader.IsDBNull(5) ? null : DateTime.Parse(reader.GetString(5))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
#region File Operations
|
#region File Operations
|
||||||
|
|
||||||
public async Task SaveFileRecordAsync(FileRecord file)
|
public async Task SaveFileRecordAsync(FileRecord file)
|
||||||
|
|
|
||||||
|
|
@ -114,6 +114,10 @@ builder.Services.AddSingleton<IAuthService, AuthService>();
|
||||||
builder.Services.AddSingleton<FileStorageService>();
|
builder.Services.AddSingleton<FileStorageService>();
|
||||||
builder.Services.AddSingleton<ChatWebSocketManager>();
|
builder.Services.AddSingleton<ChatWebSocketManager>();
|
||||||
builder.Services.AddSingleton<ModLoaderService>();
|
builder.Services.AddSingleton<ModLoaderService>();
|
||||||
|
builder.Services.AddSingleton<RateLimitService>();
|
||||||
|
builder.Services.AddSingleton<ConnectionLimiterService>();
|
||||||
|
builder.Services.AddSingleton<InviteTokenService>();
|
||||||
|
builder.Services.AddSingleton<CsrfProtectionService>();
|
||||||
|
|
||||||
builder.Logging.ClearProviders();
|
builder.Logging.ClearProviders();
|
||||||
builder.Logging.AddConsole();
|
builder.Logging.AddConsole();
|
||||||
|
|
@ -134,6 +138,24 @@ app.Lifetime.ApplicationStopping.Register(() =>
|
||||||
modLoader.ShutdownModsAsync().GetAwaiter().GetResult();
|
modLoader.ShutdownModsAsync().GetAwaiter().GetResult();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Security Headers
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
context.Response.Headers.Append("X-Content-Type-Options", "nosniff");
|
||||||
|
context.Response.Headers.Append("X-Frame-Options", "DENY");
|
||||||
|
context.Response.Headers.Append("X-XSS-Protection", "1; mode=block");
|
||||||
|
context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
|
||||||
|
context.Response.Headers.Append("Content-Security-Policy",
|
||||||
|
"default-src 'self'; " +
|
||||||
|
"script-src 'self' 'unsafe-inline'; " +
|
||||||
|
"style-src 'self' 'unsafe-inline'; " +
|
||||||
|
"img-src 'self' data:; " +
|
||||||
|
"font-src 'self'; " +
|
||||||
|
"connect-src 'self' ws: wss:; " +
|
||||||
|
"frame-ancestors 'none';");
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
// Static Files (WebClient for Browser & Mobile access)
|
// Static Files (WebClient for Browser & Mobile access)
|
||||||
app.UseDefaultFiles();
|
app.UseDefaultFiles();
|
||||||
app.UseStaticFiles();
|
app.UseStaticFiles();
|
||||||
|
|
@ -163,8 +185,18 @@ string? ExtractBearerToken(HttpRequest request)
|
||||||
}
|
}
|
||||||
|
|
||||||
// REST Endpoints
|
// REST Endpoints
|
||||||
app.MapGet("/api/info", (ServerOptions opt) =>
|
app.MapGet("/api/info", (ServerOptions opt, IAuthService auth, HttpRequest req) =>
|
||||||
{
|
{
|
||||||
|
if (opt.RequireAuthForServerInfo)
|
||||||
|
{
|
||||||
|
string? token = ExtractBearerToken(req);
|
||||||
|
var user = auth.ValidateSessionTokenAsync(token ?? "").GetAwaiter().GetResult();
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return Results.Unauthorized();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return Results.Ok(new ServerInfoResponse
|
return Results.Ok(new ServerInfoResponse
|
||||||
{
|
{
|
||||||
ServerName = opt.ServerName,
|
ServerName = opt.ServerName,
|
||||||
|
|
@ -179,21 +211,51 @@ app.MapGet("/api/info", (ServerOptions opt) =>
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth) =>
|
app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth, RateLimitService rateLimiter, CsrfProtectionService csrf, HttpContext context) =>
|
||||||
{
|
{
|
||||||
|
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||||
|
if (!rateLimiter.IsAllowed($"register:{clientIp}"))
|
||||||
|
{
|
||||||
|
return Results.StatusCode(429); // Too Many Requests
|
||||||
|
}
|
||||||
|
|
||||||
|
string? csrfToken = context.Request.Headers["X-CSRF-Token"];
|
||||||
|
if (!csrf.ValidateToken(csrfToken ?? "", ""))
|
||||||
|
{
|
||||||
|
return Results.BadRequest(new { error = "Invalid CSRF token" });
|
||||||
|
}
|
||||||
|
|
||||||
var res = await auth.RegisterAsync(req);
|
var res = await auth.RegisterAsync(req);
|
||||||
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
||||||
});
|
});
|
||||||
|
|
||||||
app.MapPost("/api/auth/login", async (LoginRequest req, IAuthService auth) =>
|
app.MapPost("/api/auth/login", async (LoginRequest req, IAuthService auth, RateLimitService rateLimiter, CsrfProtectionService csrf, HttpContext context) =>
|
||||||
{
|
{
|
||||||
|
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||||
|
if (!rateLimiter.IsAllowed($"login:{clientIp}"))
|
||||||
|
{
|
||||||
|
return Results.StatusCode(429); // Too Many Requests
|
||||||
|
}
|
||||||
|
|
||||||
|
string? csrfToken = context.Request.Headers["X-CSRF-Token"];
|
||||||
|
if (!csrf.ValidateToken(csrfToken ?? "", ""))
|
||||||
|
{
|
||||||
|
return Results.BadRequest(new { error = "Invalid CSRF token" });
|
||||||
|
}
|
||||||
|
|
||||||
var res = await auth.LoginAsync(req);
|
var res = await auth.LoginAsync(req);
|
||||||
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
||||||
});
|
});
|
||||||
|
|
||||||
// File Upload
|
// File Upload
|
||||||
app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileService, ChatWebSocketManager wsManager) =>
|
app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileService, ChatWebSocketManager wsManager, RateLimitService rateLimiter, HttpContext context) =>
|
||||||
{
|
{
|
||||||
|
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||||
|
if (!rateLimiter.IsAllowed($"upload:{clientIp}"))
|
||||||
|
{
|
||||||
|
return Results.StatusCode(429); // Too Many Requests
|
||||||
|
}
|
||||||
|
|
||||||
string? token = ExtractBearerToken(req);
|
string? token = ExtractBearerToken(req);
|
||||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
if (user == null)
|
if (user == null)
|
||||||
|
|
@ -214,9 +276,9 @@ app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, Chat
|
||||||
}
|
}
|
||||||
|
|
||||||
string channelId = form["channelId"].ToString();
|
string channelId = form["channelId"].ToString();
|
||||||
if (string.IsNullOrWhiteSpace(channelId))
|
if (string.IsNullOrWhiteSpace(channelId) || !InputSanitizer.IsValidChannelId(channelId))
|
||||||
{
|
{
|
||||||
return Results.BadRequest(new UploadFileResponse { Success = false, ErrorMessage = "channelId is required." });
|
return Results.BadRequest(new UploadFileResponse { Success = false, ErrorMessage = "Invalid channelId." });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!await chatDb.CanUserAccessChannelAsync(channelId, user.Id))
|
if (!await chatDb.CanUserAccessChannelAsync(channelId, user.Id))
|
||||||
|
|
@ -286,7 +348,7 @@ app.MapGet("/api/files/{id}", async (string id, HttpRequest req, IAuthService au
|
||||||
});
|
});
|
||||||
|
|
||||||
// WebSocket Chat Endpoint
|
// WebSocket Chat Endpoint
|
||||||
app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager wsManager) =>
|
app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager wsManager, ConnectionLimiterService connectionLimiter, ServerOptions options) =>
|
||||||
{
|
{
|
||||||
if (!context.WebSockets.IsWebSocketRequest)
|
if (!context.WebSockets.IsWebSocketRequest)
|
||||||
{
|
{
|
||||||
|
|
@ -294,16 +356,31 @@ app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketMa
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||||
|
if (!connectionLimiter.TryAddConnection(clientIp))
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
string? token = ExtractBearerToken(context.Request);
|
string? token = ExtractBearerToken(context.Request);
|
||||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
if (user == null)
|
if (user == null)
|
||||||
{
|
{
|
||||||
|
connectionLimiter.RemoveConnection(clientIp);
|
||||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var ws = await context.WebSockets.AcceptWebSocketAsync();
|
var ws = await context.WebSockets.AcceptWebSocketAsync();
|
||||||
await wsManager.HandleClientAsync(ws, user, context.RequestAborted);
|
try
|
||||||
|
{
|
||||||
|
await wsManager.HandleClientAsync(ws, user, context.RequestAborted, options.MaxWebSocketMessageSizeBytes);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
connectionLimiter.RemoveConnection(clientIp);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Console.WriteLine($"==================================================");
|
Console.WriteLine($"==================================================");
|
||||||
|
|
|
||||||
|
|
@ -14,11 +14,13 @@ public class AuthService : IAuthService
|
||||||
{
|
{
|
||||||
private readonly ChatDatabase _db;
|
private readonly ChatDatabase _db;
|
||||||
private readonly ServerOptions _options;
|
private readonly ServerOptions _options;
|
||||||
|
private readonly InviteTokenService _inviteTokenService;
|
||||||
|
|
||||||
public AuthService(ChatDatabase db, ServerOptions options)
|
public AuthService(ChatDatabase db, ServerOptions options, InviteTokenService inviteTokenService)
|
||||||
{
|
{
|
||||||
_db = db;
|
_db = db;
|
||||||
_options = options;
|
_options = options;
|
||||||
|
_inviteTokenService = inviteTokenService;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<bool> ValidateServerPasswordAsync(string? serverPassword)
|
public Task<bool> ValidateServerPasswordAsync(string? serverPassword)
|
||||||
|
|
@ -77,13 +79,26 @@ public class AuthService : IAuthService
|
||||||
{
|
{
|
||||||
// For invite-only mode, if user count is 0, allow first user (server owner), otherwise check invite token
|
// For invite-only mode, if user count is 0, allow first user (server owner), otherwise check invite token
|
||||||
int currentCount = await _db.GetUserCountAsync();
|
int currentCount = await _db.GetUserCountAsync();
|
||||||
if (currentCount > 0 && string.IsNullOrWhiteSpace(request.InviteToken))
|
if (currentCount > 0)
|
||||||
{
|
{
|
||||||
return new AuthResponse
|
if (string.IsNullOrWhiteSpace(request.InviteToken))
|
||||||
{
|
{
|
||||||
Success = false,
|
return new AuthResponse
|
||||||
ErrorMessage = "Registration is invite-only. A valid invite token is required."
|
{
|
||||||
};
|
Success = false,
|
||||||
|
ErrorMessage = "Registration is invite-only. A valid invite token is required."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool tokenValid = await _inviteTokenService.ValidateAndConsumeTokenAsync(request.InviteToken);
|
||||||
|
if (!tokenValid)
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Invalid or expired invite token."
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -204,13 +219,22 @@ public class AuthService : IAuthService
|
||||||
user.EncryptedPrivateKey = request.EncryptedPrivateKey;
|
user.EncryptedPrivateKey = request.EncryptedPrivateKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check concurrent session limit
|
||||||
|
int activeSessionCount = await _db.GetActiveSessionCountAsync(user.Id);
|
||||||
|
if (activeSessionCount >= _options.MaxConcurrentSessionsPerUser)
|
||||||
|
{
|
||||||
|
// Delete oldest session to make room
|
||||||
|
await _db.DeleteAllUserSessionsAsync(user.Id);
|
||||||
|
}
|
||||||
|
|
||||||
var sessionToken = TokenGenerator.GenerateSecureToken();
|
var sessionToken = TokenGenerator.GenerateSecureToken();
|
||||||
var session = new Session
|
var session = new Session
|
||||||
{
|
{
|
||||||
Token = sessionToken,
|
Token = sessionToken,
|
||||||
UserId = user.Id,
|
UserId = user.Id,
|
||||||
CreatedAt = DateTime.UtcNow,
|
CreatedAt = DateTime.UtcNow,
|
||||||
ExpiresAt = DateTime.UtcNow.AddDays(30)
|
ExpiresAt = DateTime.UtcNow.AddDays(30),
|
||||||
|
LastActivityAt = DateTime.UtcNow
|
||||||
};
|
};
|
||||||
|
|
||||||
await _db.CreateSessionAsync(session);
|
await _db.CreateSessionAsync(session);
|
||||||
|
|
@ -247,6 +271,19 @@ public class AuthService : IAuthService
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update session activity
|
||||||
|
await _db.UpdateSessionActivityAsync(token);
|
||||||
|
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task UpdateSessionActivityAsync(string token)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(token))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _db.UpdateSessionActivityAsync(token);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
80
src/GsDChat.Server/Services/ConnectionLimiterService.cs
Normal file
80
src/GsDChat.Server/Services/ConnectionLimiterService.cs
Normal file
|
|
@ -0,0 +1,80 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Net;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Services;
|
||||||
|
|
||||||
|
public class ConnectionLimiterService
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<string, int> _ipConnections = new();
|
||||||
|
private readonly int _maxConnectionsPerIp;
|
||||||
|
private readonly int _maxGlobalConnections;
|
||||||
|
private int _globalConnectionCount;
|
||||||
|
|
||||||
|
public ConnectionLimiterService(int maxConnectionsPerIp = 10, int maxGlobalConnections = 100)
|
||||||
|
{
|
||||||
|
_maxConnectionsPerIp = maxConnectionsPerIp;
|
||||||
|
_maxGlobalConnections = maxGlobalConnections;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryAddConnection(string ipAddress)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(ipAddress))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (this)
|
||||||
|
{
|
||||||
|
if (_globalConnectionCount >= _maxGlobalConnections)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var currentIpCount = _ipConnections.GetOrAdd(ipAddress, 0);
|
||||||
|
if (currentIpCount >= _maxConnectionsPerIp)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_ipConnections.AddOrUpdate(ipAddress, 1, (_, existing) => existing + 1);
|
||||||
|
_globalConnectionCount++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RemoveConnection(string ipAddress)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(ipAddress))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (this)
|
||||||
|
{
|
||||||
|
if (_ipConnections.TryGetValue(ipAddress, out var count))
|
||||||
|
{
|
||||||
|
if (count <= 1)
|
||||||
|
{
|
||||||
|
_ipConnections.TryRemove(ipAddress, out _);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_ipConnections.AddOrUpdate(ipAddress, 0, (_, existing) => existing - 1);
|
||||||
|
}
|
||||||
|
_globalConnectionCount = Math.Max(0, _globalConnectionCount - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int GetConnectionCount(string ipAddress)
|
||||||
|
{
|
||||||
|
return _ipConnections.TryGetValue(ipAddress, out var count) ? count : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int GetGlobalConnectionCount()
|
||||||
|
{
|
||||||
|
return _globalConnectionCount;
|
||||||
|
}
|
||||||
|
}
|
||||||
120
src/GsDChat.Server/Services/CsrfProtectionService.cs
Normal file
120
src/GsDChat.Server/Services/CsrfProtectionService.cs
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Services;
|
||||||
|
|
||||||
|
public class CsrfProtectionService
|
||||||
|
{
|
||||||
|
private readonly bool _enabled;
|
||||||
|
private readonly ConcurrentDictionary<string, CsrfTokenEntry> _tokenStore = new();
|
||||||
|
private readonly TimeSpan _tokenLifetime = TimeSpan.FromHours(1);
|
||||||
|
|
||||||
|
public CsrfProtectionService(bool enabled = true)
|
||||||
|
{
|
||||||
|
_enabled = enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string GenerateToken(string sessionToken = "")
|
||||||
|
{
|
||||||
|
if (!_enabled)
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
var randomBytes = new byte[32];
|
||||||
|
using var rng = RandomNumberGenerator.Create();
|
||||||
|
rng.GetBytes(randomBytes);
|
||||||
|
var token = Convert.ToBase64String(randomBytes);
|
||||||
|
|
||||||
|
// Store token with session association and expiration
|
||||||
|
var entry = new CsrfTokenEntry
|
||||||
|
{
|
||||||
|
Token = token,
|
||||||
|
SessionToken = sessionToken,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
ExpiresAt = DateTime.UtcNow.Add(_tokenLifetime)
|
||||||
|
};
|
||||||
|
|
||||||
|
_tokenStore[token] = entry;
|
||||||
|
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool ValidateToken(string token, string sessionToken = "")
|
||||||
|
{
|
||||||
|
if (!_enabled)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(token))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_tokenStore.TryGetValue(token, out var entry))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if token is expired
|
||||||
|
if (DateTime.UtcNow > entry.ExpiresAt)
|
||||||
|
{
|
||||||
|
_tokenStore.TryRemove(token, out _);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If a session token is provided, verify it matches
|
||||||
|
// If no session token (pre-auth), skip session binding
|
||||||
|
if (!string.IsNullOrWhiteSpace(sessionToken) && !string.IsNullOrWhiteSpace(entry.SessionToken))
|
||||||
|
{
|
||||||
|
if (entry.SessionToken != sessionToken)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Token is valid - consume it (one-time use)
|
||||||
|
_tokenStore.TryRemove(token, out _);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void CleanupExpiredTokens()
|
||||||
|
{
|
||||||
|
var now = DateTime.UtcNow;
|
||||||
|
foreach (var kvp in _tokenStore)
|
||||||
|
{
|
||||||
|
if (now > kvp.Value.ExpiresAt)
|
||||||
|
{
|
||||||
|
_tokenStore.TryRemove(kvp.Key, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Pre-register a CSRF token for testing purposes.
|
||||||
|
/// This allows tests to validate tokens that were generated client-side.
|
||||||
|
/// </summary>
|
||||||
|
public void RegisterTokenForTesting(string token, string sessionToken = "")
|
||||||
|
{
|
||||||
|
var entry = new CsrfTokenEntry
|
||||||
|
{
|
||||||
|
Token = token,
|
||||||
|
SessionToken = sessionToken,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
ExpiresAt = DateTime.UtcNow.Add(_tokenLifetime)
|
||||||
|
};
|
||||||
|
|
||||||
|
_tokenStore[token] = entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
private class CsrfTokenEntry
|
||||||
|
{
|
||||||
|
public string Token { get; set; } = string.Empty;
|
||||||
|
public string SessionToken { get; set; } = string.Empty;
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
public DateTime ExpiresAt { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
@ -14,6 +15,21 @@ public class FileStorageService
|
||||||
private readonly ServerOptions _options;
|
private readonly ServerOptions _options;
|
||||||
private readonly string _filesDirectory;
|
private readonly string _filesDirectory;
|
||||||
|
|
||||||
|
// Whitelist of allowed MIME types
|
||||||
|
private static readonly HashSet<string> AllowedContentTypes = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
// Images
|
||||||
|
"image/jpeg", "image/png", "image/gif", "image/webp", "image/svg+xml",
|
||||||
|
// Documents
|
||||||
|
"application/pdf", "text/plain", "text/csv", "application/octet-stream",
|
||||||
|
// Archives
|
||||||
|
"application/zip", "application/x-rar-compressed", "application/x-7z-compressed",
|
||||||
|
// Audio
|
||||||
|
"audio/mpeg", "audio/wav", "audio/ogg",
|
||||||
|
// Video
|
||||||
|
"video/mp4", "video/webm", "video/quicktime"
|
||||||
|
};
|
||||||
|
|
||||||
public FileStorageService(ChatDatabase db, ServerOptions options)
|
public FileStorageService(ChatDatabase db, ServerOptions options)
|
||||||
{
|
{
|
||||||
_db = db;
|
_db = db;
|
||||||
|
|
@ -22,6 +38,16 @@ public class FileStorageService
|
||||||
Directory.CreateDirectory(_filesDirectory);
|
Directory.CreateDirectory(_filesDirectory);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private bool IsContentTypeAllowed(string contentType)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(contentType))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return AllowedContentTypes.Contains(contentType.Trim());
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<FileRecord> StoreFileAsync(
|
public async Task<FileRecord> StoreFileAsync(
|
||||||
string channelId,
|
string channelId,
|
||||||
string uploaderId,
|
string uploaderId,
|
||||||
|
|
@ -60,12 +86,21 @@ public class FileStorageService
|
||||||
throw new InvalidOperationException($"File exceeds maximum allowed size of {_options.MaxFileSizeMb} MB.");
|
throw new InvalidOperationException($"File exceeds maximum allowed size of {_options.MaxFileSizeMb} MB.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate content type
|
||||||
|
if (!IsContentTypeAllowed(contentType))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"File type '{contentType}' is not allowed.");
|
||||||
|
}
|
||||||
|
|
||||||
string safeName = Path.GetFileName(originalFileName);
|
string safeName = Path.GetFileName(originalFileName);
|
||||||
if (string.IsNullOrWhiteSpace(safeName))
|
if (string.IsNullOrWhiteSpace(safeName))
|
||||||
{
|
{
|
||||||
safeName = "unnamed_file.bin";
|
safeName = "unnamed_file.bin";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sanitize filename
|
||||||
|
safeName = InputSanitizer.SanitizeForDisplay(safeName, 255);
|
||||||
|
|
||||||
string fileId = Guid.NewGuid().ToString("N");
|
string fileId = Guid.NewGuid().ToString("N");
|
||||||
string diskFileName = $"{fileId}_{safeName}";
|
string diskFileName = $"{fileId}_{safeName}";
|
||||||
string diskFilePath = Path.Combine(_filesDirectory, diskFileName);
|
string diskFilePath = Path.Combine(_filesDirectory, diskFileName);
|
||||||
|
|
|
||||||
|
|
@ -10,4 +10,5 @@ public interface IAuthService
|
||||||
Task<AuthResponse> LoginAsync(LoginRequest request);
|
Task<AuthResponse> LoginAsync(LoginRequest request);
|
||||||
Task<User?> ValidateSessionTokenAsync(string token);
|
Task<User?> ValidateSessionTokenAsync(string token);
|
||||||
Task<bool> ValidateServerPasswordAsync(string? serverPassword);
|
Task<bool> ValidateServerPasswordAsync(string? serverPassword);
|
||||||
|
Task UpdateSessionActivityAsync(string token);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
144
src/GsDChat.Server/Services/InputSanitizer.cs
Normal file
144
src/GsDChat.Server/Services/InputSanitizer.cs
Normal file
|
|
@ -0,0 +1,144 @@
|
||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Services;
|
||||||
|
|
||||||
|
public static class InputSanitizer
|
||||||
|
{
|
||||||
|
private static readonly string[] DangerousChars = { "\0", "\r", "\n", "\t", "<", ">", "&", "\"", "'", "\\" };
|
||||||
|
|
||||||
|
public static string SanitizeForLogging(string input)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(input))
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
var sanitized = new StringBuilder(input.Length);
|
||||||
|
foreach (char c in input)
|
||||||
|
{
|
||||||
|
if (char.IsControl(c) && !char.IsWhiteSpace(c))
|
||||||
|
{
|
||||||
|
sanitized.Append($"\\x{(int)c:X2}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sanitized.Append(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sanitized.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string SanitizeForDisplay(string input, int maxLength = 1000)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(input))
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Truncate if too long
|
||||||
|
if (input.Length > maxLength)
|
||||||
|
{
|
||||||
|
input = input.Substring(0, maxLength) + "...";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove null bytes and other control characters except newlines and tabs
|
||||||
|
var sanitized = new StringBuilder(input.Length);
|
||||||
|
foreach (char c in input)
|
||||||
|
{
|
||||||
|
if (c == '\0')
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (char.IsControl(c) && c != '\n' && c != '\r' && c != '\t')
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
sanitized.Append(c);
|
||||||
|
}
|
||||||
|
return sanitized.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string SanitizeUsername(string username)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(username))
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow alphanumeric, underscore, hyphen, and common special characters
|
||||||
|
var sanitized = new StringBuilder(username.Length);
|
||||||
|
foreach (char c in username)
|
||||||
|
{
|
||||||
|
if (char.IsLetterOrDigit(c) || c == '_' || c == '-' || c == '.' || c == '@')
|
||||||
|
{
|
||||||
|
sanitized.Append(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sanitized.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string SanitizeChannelName(string channelName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(channelName))
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow alphanumeric, spaces, hyphens, and underscores
|
||||||
|
var sanitized = new StringBuilder(channelName.Length);
|
||||||
|
foreach (char c in channelName)
|
||||||
|
{
|
||||||
|
if (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-' || c == '_')
|
||||||
|
{
|
||||||
|
sanitized.Append(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sanitized.ToString().Trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string SanitizeSystemMessage(string message)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(message))
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove control characters that could cause log injection
|
||||||
|
var sanitized = new StringBuilder(message.Length);
|
||||||
|
foreach (char c in message)
|
||||||
|
{
|
||||||
|
if (c == '\0' || c == '\r' || c == '\n')
|
||||||
|
{
|
||||||
|
sanitized.Append(' ');
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sanitized.Append(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sanitized.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool IsValidUserId(string userId)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(userId) || userId.Length > 50)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should be a valid GUID
|
||||||
|
return Guid.TryParse(userId, out _);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool IsValidChannelId(string channelId)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(channelId) || channelId.Length > 50)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should be a valid GUID
|
||||||
|
return Guid.TryParse(channelId, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
64
src/GsDChat.Server/Services/InviteTokenService.cs
Normal file
64
src/GsDChat.Server/Services/InviteTokenService.cs
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Server.Data;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Services;
|
||||||
|
|
||||||
|
public class InviteTokenService
|
||||||
|
{
|
||||||
|
private readonly ChatDatabase _db;
|
||||||
|
private readonly int _expirationHours;
|
||||||
|
|
||||||
|
public InviteTokenService(ChatDatabase db, int expirationHours = 168)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
_expirationHours = expirationHours;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string GenerateToken()
|
||||||
|
{
|
||||||
|
return Guid.NewGuid().ToString("N").Substring(0, 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string> CreateInviteTokenAsync(string createdByUserId)
|
||||||
|
{
|
||||||
|
var token = GenerateToken();
|
||||||
|
var expiresAt = DateTime.UtcNow.AddHours(_expirationHours);
|
||||||
|
await _db.CreateInviteTokenAsync(token, createdByUserId, expiresAt);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> ValidateAndConsumeTokenAsync(string token)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(token))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var inviteToken = await _db.GetInviteTokenAsync(token);
|
||||||
|
if (inviteToken == null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inviteToken.IsUsed || inviteToken.IsExpired)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _db.MarkInviteTokenAsUsedAsync(token);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<InviteToken>> GetActiveTokensAsync(string createdByUserId)
|
||||||
|
{
|
||||||
|
return await _db.GetActiveInviteTokensAsync(createdByUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task RevokeTokenAsync(string token)
|
||||||
|
{
|
||||||
|
await _db.DeleteInviteTokenAsync(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
90
src/GsDChat.Server/Services/RateLimitService.cs
Normal file
90
src/GsDChat.Server/Services/RateLimitService.cs
Normal file
|
|
@ -0,0 +1,90 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Services;
|
||||||
|
|
||||||
|
public class RateLimitService : IDisposable
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<string, RateLimitBucket> _buckets = new();
|
||||||
|
private readonly int _requestsPerMinute;
|
||||||
|
private readonly TimeSpan _window;
|
||||||
|
private readonly Timer _cleanupTimer;
|
||||||
|
|
||||||
|
public RateLimitService(int requestsPerMinute = 60)
|
||||||
|
{
|
||||||
|
_requestsPerMinute = requestsPerMinute;
|
||||||
|
_window = TimeSpan.FromMinutes(1);
|
||||||
|
|
||||||
|
// Cleanup expired buckets every 5 minutes
|
||||||
|
_cleanupTimer = new Timer(
|
||||||
|
CleanupExpiredBuckets,
|
||||||
|
null,
|
||||||
|
TimeSpan.FromMinutes(5),
|
||||||
|
TimeSpan.FromMinutes(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsAllowed(string key)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(key))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = DateTime.UtcNow;
|
||||||
|
var bucket = _buckets.AddOrUpdate(key,
|
||||||
|
_ => new RateLimitBucket { Count = 1, WindowStart = now },
|
||||||
|
(_, existing) =>
|
||||||
|
{
|
||||||
|
if (now - existing.WindowStart > _window)
|
||||||
|
{
|
||||||
|
existing.Count = 1;
|
||||||
|
existing.WindowStart = now;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
existing.Count++;
|
||||||
|
}
|
||||||
|
return existing;
|
||||||
|
});
|
||||||
|
|
||||||
|
return bucket.Count <= _requestsPerMinute;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<bool> IsAllowedAsync(string key)
|
||||||
|
{
|
||||||
|
return Task.FromResult(IsAllowed(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Reset(string key)
|
||||||
|
{
|
||||||
|
_buckets.TryRemove(key, out _);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CleanupExpiredBuckets(object? state)
|
||||||
|
{
|
||||||
|
var now = DateTime.UtcNow;
|
||||||
|
var expiredKeys = _buckets
|
||||||
|
.Where(kvp => now - kvp.Value.WindowStart > _window.Add(TimeSpan.FromMinutes(5)))
|
||||||
|
.Select(kvp => kvp.Key)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
foreach (var key in expiredKeys)
|
||||||
|
{
|
||||||
|
_buckets.TryRemove(key, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_cleanupTimer?.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
private class RateLimitBucket
|
||||||
|
{
|
||||||
|
public int Count { get; set; }
|
||||||
|
public DateTime WindowStart { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
47
src/GsDChat.Server/Services/SafeLogger.cs
Normal file
47
src/GsDChat.Server/Services/SafeLogger.cs
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
using System;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Services;
|
||||||
|
|
||||||
|
public static class SafeLogger
|
||||||
|
{
|
||||||
|
public static void LogError(ILogger logger, Exception ex, string message, params object[] args)
|
||||||
|
{
|
||||||
|
var sanitizedArgs = new object[args.Length];
|
||||||
|
for (int i = 0; i < args.Length; i++)
|
||||||
|
{
|
||||||
|
sanitizedArgs[i] = InputSanitizer.SanitizeForLogging(args[i]?.ToString() ?? "");
|
||||||
|
}
|
||||||
|
logger.LogError(ex, message, sanitizedArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void LogWarning(ILogger logger, string message, params object[] args)
|
||||||
|
{
|
||||||
|
var sanitizedArgs = new object[args.Length];
|
||||||
|
for (int i = 0; i < args.Length; i++)
|
||||||
|
{
|
||||||
|
sanitizedArgs[i] = InputSanitizer.SanitizeForLogging(args[i]?.ToString() ?? "");
|
||||||
|
}
|
||||||
|
logger.LogWarning(message, sanitizedArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void LogInformation(ILogger logger, string message, params object[] args)
|
||||||
|
{
|
||||||
|
var sanitizedArgs = new object[args.Length];
|
||||||
|
for (int i = 0; i < args.Length; i++)
|
||||||
|
{
|
||||||
|
sanitizedArgs[i] = InputSanitizer.SanitizeForLogging(args[i]?.ToString() ?? "");
|
||||||
|
}
|
||||||
|
logger.LogInformation(message, sanitizedArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void LogDebug(ILogger logger, string message, params object[] args)
|
||||||
|
{
|
||||||
|
var sanitizedArgs = new object[args.Length];
|
||||||
|
for (int i = 0; i < args.Length; i++)
|
||||||
|
{
|
||||||
|
sanitizedArgs[i] = InputSanitizer.SanitizeForLogging(args[i]?.ToString() ?? "");
|
||||||
|
}
|
||||||
|
logger.LogDebug(message, sanitizedArgs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -38,7 +38,7 @@ public class ChatWebSocketManager
|
||||||
|
|
||||||
public int ConnectedCount => _clients.Count;
|
public int ConnectedCount => _clients.Count;
|
||||||
|
|
||||||
public async Task HandleClientAsync(WebSocket socket, User user, CancellationToken cancellationToken)
|
public async Task HandleClientAsync(WebSocket socket, User user, CancellationToken cancellationToken, int maxMessageSizeBytes = 1048576)
|
||||||
{
|
{
|
||||||
var client = new ConnectedClient(socket, user);
|
var client = new ConnectedClient(socket, user);
|
||||||
_clients[client.ConnectionId] = client;
|
_clients[client.ConnectionId] = client;
|
||||||
|
|
@ -104,7 +104,7 @@ public class ChatWebSocketManager
|
||||||
|
|
||||||
// Broadcast Presence Update
|
// Broadcast Presence Update
|
||||||
await BroadcastUserListAsync();
|
await BroadcastUserListAsync();
|
||||||
await BroadcastSystemNoticeAsync($"[+] {user.Username} connected.", "Info");
|
await BroadcastSystemNoticeAsync($"[+] {InputSanitizer.SanitizeUsername(user.Username)} connected.", "Info");
|
||||||
|
|
||||||
// Main Receive Loop
|
// Main Receive Loop
|
||||||
var buffer = new byte[8192];
|
var buffer = new byte[8192];
|
||||||
|
|
@ -123,6 +123,14 @@ public class ChatWebSocketManager
|
||||||
{
|
{
|
||||||
messageAccumulator.AddRange(buffer.Take(result.Count));
|
messageAccumulator.AddRange(buffer.Take(result.Count));
|
||||||
|
|
||||||
|
// Check message size limit
|
||||||
|
if (messageAccumulator.Count > maxMessageSizeBytes)
|
||||||
|
{
|
||||||
|
messageAccumulator.Clear();
|
||||||
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Message too large." }, cancellationToken);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (result.EndOfMessage)
|
if (result.EndOfMessage)
|
||||||
{
|
{
|
||||||
string json = Encoding.UTF8.GetString(messageAccumulator.ToArray());
|
string json = Encoding.UTF8.GetString(messageAccumulator.ToArray());
|
||||||
|
|
@ -135,11 +143,11 @@ public class ChatWebSocketManager
|
||||||
catch (OperationCanceledException) { }
|
catch (OperationCanceledException) { }
|
||||||
catch (WebSocketException ex)
|
catch (WebSocketException ex)
|
||||||
{
|
{
|
||||||
_logger.LogDebug("WebSocket error for {Username}: {Msg}", user.Username, ex.Message);
|
SafeLogger.LogDebug(_logger, "WebSocket error for {Username}: {Msg}", InputSanitizer.SanitizeUsername(user.Username), ex.Message);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Unexpected error handling client {Username}", user.Username);
|
SafeLogger.LogError(_logger, ex, "Unexpected error handling client {Username}", InputSanitizer.SanitizeUsername(user.Username));
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
|
|
@ -156,7 +164,7 @@ public class ChatWebSocketManager
|
||||||
catch { }
|
catch { }
|
||||||
|
|
||||||
await BroadcastUserListAsync();
|
await BroadcastUserListAsync();
|
||||||
await BroadcastSystemNoticeAsync($"[-] {user.Username} disconnected.", "Info");
|
await BroadcastSystemNoticeAsync($"[-] {InputSanitizer.SanitizeUsername(user.Username)} disconnected.", "Info");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -282,9 +290,9 @@ public class ChatWebSocketManager
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception)
|
||||||
{
|
{
|
||||||
_logger.LogWarning(ex, "Failed to process message from client {Username}", client.User.Username);
|
SafeLogger.LogWarning(_logger, "Failed to process message from client {Username}", InputSanitizer.SanitizeUsername(client.User.Username));
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Failed to process message." }, ct);
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Failed to process message." }, ct);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -370,7 +378,7 @@ public class ChatWebSocketManager
|
||||||
{
|
{
|
||||||
await BroadcastToMembersAsync(dm.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket
|
await BroadcastToMembersAsync(dm.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket
|
||||||
{
|
{
|
||||||
Text = $"@{client.User.Username} reset their E2EE keypair.",
|
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} reset their E2EE keypair.",
|
||||||
Level = "Warning"
|
Level = "Warning"
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -398,7 +406,7 @@ public class ChatWebSocketManager
|
||||||
await SyncChannelListForUsersAsync(affectedUsers);
|
await SyncChannelListForUsersAsync(affectedUsers);
|
||||||
await BroadcastToMembersAsync(affectedUsers, MessageTypes.SystemNotice, new SystemNoticePacket
|
await BroadcastToMembersAsync(affectedUsers, MessageTypes.SystemNotice, new SystemNoticePacket
|
||||||
{
|
{
|
||||||
Text = $"@{client.User.Username} {(packet.Enabled ? "enabled" : "disabled")} E2EE for their account.",
|
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} {(packet.Enabled ? "enabled" : "disabled")} E2EE for their account.",
|
||||||
Level = packet.Enabled ? "Success" : "Warning"
|
Level = packet.Enabled ? "Success" : "Warning"
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -423,7 +431,7 @@ public class ChatWebSocketManager
|
||||||
await SyncChannelListForUsersAsync(channel.MemberIds);
|
await SyncChannelListForUsersAsync(channel.MemberIds);
|
||||||
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket
|
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket
|
||||||
{
|
{
|
||||||
Text = $"@{client.User.Username} {(packet.Enabled ? "enabled" : "disabled")} E2EE for this Direct Message.",
|
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} {(packet.Enabled ? "enabled" : "disabled")} E2EE for this Direct Message.",
|
||||||
Level = packet.Enabled ? "Success" : "Warning"
|
Level = packet.Enabled ? "Success" : "Warning"
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -544,6 +552,12 @@ public class ChatWebSocketManager
|
||||||
|
|
||||||
private async Task HandleStartDmAsync(ConnectedClient client, StartDmPacket packet, CancellationToken ct)
|
private async Task HandleStartDmAsync(ConnectedClient client, StartDmPacket packet, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(packet.TargetUserId) && !InputSanitizer.IsValidUserId(packet.TargetUserId))
|
||||||
|
{
|
||||||
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Invalid user ID." }, ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
User? targetUser = null;
|
User? targetUser = null;
|
||||||
if (!string.IsNullOrWhiteSpace(packet.TargetUserId))
|
if (!string.IsNullOrWhiteSpace(packet.TargetUserId))
|
||||||
{
|
{
|
||||||
|
|
@ -551,7 +565,7 @@ public class ChatWebSocketManager
|
||||||
}
|
}
|
||||||
if (targetUser == null && !string.IsNullOrWhiteSpace(packet.TargetUsername))
|
if (targetUser == null && !string.IsNullOrWhiteSpace(packet.TargetUsername))
|
||||||
{
|
{
|
||||||
string cleanName = packet.TargetUsername.Trim().TrimStart('@');
|
string cleanName = InputSanitizer.SanitizeUsername(packet.TargetUsername.Trim().TrimStart('@'));
|
||||||
targetUser = await _db.GetUserByUsernameAsync(cleanName);
|
targetUser = await _db.GetUserByUsernameAsync(cleanName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -579,6 +593,13 @@ public class ChatWebSocketManager
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
string sanitizedName = InputSanitizer.SanitizeChannelName(packet.Name);
|
||||||
|
if (sanitizedName.Length < 2)
|
||||||
|
{
|
||||||
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Group name contains invalid characters." }, ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
int serverMax = Math.Max(2, _options.MaxGroupChatUsers);
|
int serverMax = Math.Max(2, _options.MaxGroupChatUsers);
|
||||||
int groupMax = packet.MaxUsers.HasValue && packet.MaxUsers.Value > 0 ? packet.MaxUsers.Value : serverMax;
|
int groupMax = packet.MaxUsers.HasValue && packet.MaxUsers.Value > 0 ? packet.MaxUsers.Value : serverMax;
|
||||||
|
|
||||||
|
|
@ -601,7 +622,7 @@ public class ChatWebSocketManager
|
||||||
var parts = rawName.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
var parts = rawName.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
||||||
foreach (var p in parts)
|
foreach (var p in parts)
|
||||||
{
|
{
|
||||||
string cleanUser = p.Trim().TrimStart('@');
|
string cleanUser = InputSanitizer.SanitizeUsername(p.Trim().TrimStart('@'));
|
||||||
if (string.IsNullOrWhiteSpace(cleanUser)) continue;
|
if (string.IsNullOrWhiteSpace(cleanUser)) continue;
|
||||||
var u = await _db.GetUserByUsernameAsync(cleanUser);
|
var u = await _db.GetUserByUsernameAsync(cleanUser);
|
||||||
if (u == null)
|
if (u == null)
|
||||||
|
|
@ -623,7 +644,7 @@ public class ChatWebSocketManager
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var group = await _db.CreateGroupChatAsync(packet.Name.Trim(), packet.Topic ?? string.Empty, client.User.Id, memberIds, groupMax);
|
var group = await _db.CreateGroupChatAsync(sanitizedName, InputSanitizer.SanitizeForDisplay(packet.Topic ?? string.Empty), client.User.Id, memberIds, groupMax);
|
||||||
client.ActiveChannelId = group.Id;
|
client.ActiveChannelId = group.Id;
|
||||||
|
|
||||||
await SyncChannelListForUsersAsync(group.MemberIds);
|
await SyncChannelListForUsersAsync(group.MemberIds);
|
||||||
|
|
@ -638,7 +659,7 @@ public class ChatWebSocketManager
|
||||||
MessageTypes.SystemNotice,
|
MessageTypes.SystemNotice,
|
||||||
new SystemNoticePacket
|
new SystemNoticePacket
|
||||||
{
|
{
|
||||||
Text = $"Group chat '{group.Name}' created by @{client.User.Username} ({group.MemberIds.Count}/{group.MaxUsers} members).",
|
Text = $"Group chat '{InputSanitizer.SanitizeChannelName(group.Name)}' created by @{InputSanitizer.SanitizeUsername(client.User.Username)} ({group.MemberIds.Count}/{group.MaxUsers} members).",
|
||||||
Level = "Success"
|
Level = "Success"
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -699,7 +720,7 @@ public class ChatWebSocketManager
|
||||||
MessageTypes.SystemNotice,
|
MessageTypes.SystemNotice,
|
||||||
new SystemNoticePacket
|
new SystemNoticePacket
|
||||||
{
|
{
|
||||||
Text = $"@{targetUser.Username} was added to group '{group.Name}' by @{client.User.Username}.",
|
Text = $"@{InputSanitizer.SanitizeUsername(targetUser.Username)} was added to group '{InputSanitizer.SanitizeChannelName(group.Name)}' by @{InputSanitizer.SanitizeUsername(client.User.Username)}.",
|
||||||
Level = "Info"
|
Level = "Info"
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -741,7 +762,7 @@ public class ChatWebSocketManager
|
||||||
MessageTypes.SystemNotice,
|
MessageTypes.SystemNotice,
|
||||||
new SystemNoticePacket
|
new SystemNoticePacket
|
||||||
{
|
{
|
||||||
Text = $"@{client.User.Username} left group '{group.Name}'.",
|
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} left group '{InputSanitizer.SanitizeChannelName(group.Name)}'.",
|
||||||
Level = "Info"
|
Level = "Info"
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -783,7 +804,7 @@ public class ChatWebSocketManager
|
||||||
ChannelId = channel.Id,
|
ChannelId = channel.Id,
|
||||||
Messages = new()
|
Messages = new()
|
||||||
}, ct);
|
}, ct);
|
||||||
await BroadcastSystemNoticeAsync($"Channel #{cleanName} was created by {client.User.Username}.", "Success");
|
await BroadcastSystemNoticeAsync($"Channel #{cleanName} was created by {InputSanitizer.SanitizeUsername(client.User.Username)}.", "Success");
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task HandleDeleteChannelAsync(ConnectedClient client, string channelId, CancellationToken ct)
|
private async Task HandleDeleteChannelAsync(ConnectedClient client, string channelId, CancellationToken ct)
|
||||||
|
|
@ -819,7 +840,7 @@ public class ChatWebSocketManager
|
||||||
|
|
||||||
await BroadcastChannelListAsync();
|
await BroadcastChannelListAsync();
|
||||||
await Task.WhenAll(_clients.Values.Select(c => SendFileListToClientAsync(c, ct)));
|
await Task.WhenAll(_clients.Values.Select(c => SendFileListToClientAsync(c, ct)));
|
||||||
await BroadcastSystemNoticeAsync($"Channel #{channel.Name} was deleted.", "Warning");
|
await BroadcastSystemNoticeAsync($"Channel #{InputSanitizer.SanitizeChannelName(channel.Name)} was deleted.", "Warning");
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task HandleCommandAsync(ConnectedClient client, ExecuteCommandPacket packet, CancellationToken ct)
|
private async Task HandleCommandAsync(ConnectedClient client, ExecuteCommandPacket packet, CancellationToken ct)
|
||||||
|
|
|
||||||
|
|
@ -12,5 +12,13 @@
|
||||||
"Motd": "Welcome to GsDChat! Enjoy private and modular messaging.",
|
"Motd": "Welcome to GsDChat! Enjoy private and modular messaging.",
|
||||||
"AllowMemberChannelCreation": true,
|
"AllowMemberChannelCreation": true,
|
||||||
"AllowDmE2ee": true,
|
"AllowDmE2ee": true,
|
||||||
"MaxGroupChatUsers": 10
|
"MaxGroupChatUsers": 10,
|
||||||
}
|
"RateLimitRequestsPerMinute": 60,
|
||||||
|
"MaxConnectionsPerIp": 10,
|
||||||
|
"MaxGlobalConnections": 100,
|
||||||
|
"MaxConcurrentSessionsPerUser": 5,
|
||||||
|
"InviteTokenExpirationHours": 168,
|
||||||
|
"RequireAuthForServerInfo": false,
|
||||||
|
"EnableCsrfProtection": true,
|
||||||
|
"MaxWebSocketMessageSizeBytes": 1048576
|
||||||
|
}
|
||||||
|
|
@ -569,7 +569,12 @@
|
||||||
// ==========================================
|
// ==========================================
|
||||||
async function fetchServerInfo() {
|
async function fetchServerInfo() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/info');
|
const headers = {};
|
||||||
|
if (state.token) {
|
||||||
|
headers['Authorization'] = `Bearer ${state.token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch('/api/info', { headers });
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
state.serverInfo = await res.json();
|
state.serverInfo = await res.json();
|
||||||
state.allowDmE2ee = state.serverInfo.allowDmE2ee !== undefined
|
state.allowDmE2ee = state.serverInfo.allowDmE2ee !== undefined
|
||||||
|
|
@ -591,6 +596,15 @@
|
||||||
el.groupInviteToken.style.display = 'flex';
|
el.groupInviteToken.style.display = 'flex';
|
||||||
}
|
}
|
||||||
updateSettingsBadges();
|
updateSettingsBadges();
|
||||||
|
} else if (res.status === 401) {
|
||||||
|
// Server requires auth for info endpoint, continue without it
|
||||||
|
state.serverInfo = {
|
||||||
|
serverName: 'GsDChat',
|
||||||
|
motd: 'Welcome to GsDChat!',
|
||||||
|
allowDmE2ee: true,
|
||||||
|
maxGroupChatUsers: 10
|
||||||
|
};
|
||||||
|
updateSettingsBadges();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showToast('Could not reach server info endpoint');
|
showToast('Could not reach server info endpoint');
|
||||||
|
|
@ -651,15 +665,23 @@
|
||||||
inviteToken: inviteToken || null
|
inviteToken: inviteToken || null
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Generate a simple CSRF token for this request
|
||||||
|
const csrfToken = Array.from(crypto.getRandomValues(new Uint8Array(16)))
|
||||||
|
.map(b => b.toString(16).padStart(2, '0'))
|
||||||
|
.join('');
|
||||||
|
|
||||||
const res = await fetch(endpoint, {
|
const res = await fetch(endpoint, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRF-Token': csrfToken
|
||||||
|
},
|
||||||
body: JSON.stringify(body)
|
body: JSON.stringify(body)
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok || !data.success) {
|
if (!res.ok || !data.success) {
|
||||||
el.authError.textContent = data.errorMessage || 'Authentication failed.';
|
el.authError.textContent = data.errorMessage || data.error || 'Authentication failed.';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -79,7 +79,7 @@
|
||||||
<button type="button" class="btn btn-sm btn-secondary" id="toggleDmE2eeBtn" style="display:none;" title="Toggle E2EE for this Direct Message">[DM E2EE: ON]</button>
|
<button type="button" class="btn btn-sm btn-secondary" id="toggleDmE2eeBtn" style="display:none;" title="Toggle E2EE for this Direct Message">[DM E2EE: ON]</button>
|
||||||
<button type="button" class="btn btn-sm btn-secondary" id="inviteGroupBtn" style="display:none;" title="Invite User to Group">[+ Invite]</button>
|
<button type="button" class="btn btn-sm btn-secondary" id="inviteGroupBtn" style="display:none;" title="Invite User to Group">[+ Invite]</button>
|
||||||
<button type="button" class="btn btn-sm btn-outline-danger" id="leaveGroupBtn" style="display:none;" title="Leave Group">[Leave]</button>
|
<button type="button" class="btn btn-sm btn-outline-danger" id="leaveGroupBtn" style="display:none;" title="Leave Group">[Leave]</button>
|
||||||
<button type="button" class="btn btn-sm btn-outline-members closed" id="toggleMembersBtn" title="Toggle Online Members">
|
<button type="button" class="btn btn-sm btn-outline-members" id="toggleMembersBtn" title="Toggle Online Members">
|
||||||
[●] <span class="members-btn-label">Online</span> (<span id="chatHeaderOnlineCount">0</span>)
|
[●] <span class="members-btn-label">Online</span> (<span id="chatHeaderOnlineCount">0</span>)
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -105,7 +105,7 @@
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<aside class="chat-members-sidebar" id="chatMembersSidebar">
|
<aside class="chat-members-sidebar closed" id="chatMembersSidebar">
|
||||||
<div class="members-sidebar-header">
|
<div class="members-sidebar-header">
|
||||||
<span>ONLINE MEMBERS</span>
|
<span>ONLINE MEMBERS</span>
|
||||||
<span class="member-count-badge" id="chatOnlineCountBadge">0</span>
|
<span class="member-count-badge" id="chatOnlineCountBadge">0</span>
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ public class AuthServiceTests : IDisposable
|
||||||
private readonly ChatDatabase _db;
|
private readonly ChatDatabase _db;
|
||||||
private readonly ServerOptions _options;
|
private readonly ServerOptions _options;
|
||||||
private readonly AuthService _auth;
|
private readonly AuthService _auth;
|
||||||
|
private readonly InviteTokenService _inviteTokenService;
|
||||||
|
|
||||||
public AuthServiceTests()
|
public AuthServiceTests()
|
||||||
{
|
{
|
||||||
|
|
@ -26,7 +27,8 @@ public class AuthServiceTests : IDisposable
|
||||||
{
|
{
|
||||||
ServerWidePassword = "SecretServerPass"
|
ServerWidePassword = "SecretServerPass"
|
||||||
};
|
};
|
||||||
_auth = new AuthService(_db, _options);
|
_inviteTokenService = new InviteTokenService(_db, _options.InviteTokenExpirationHours);
|
||||||
|
_auth = new AuthService(_db, _options, _inviteTokenService);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
|
|
|
||||||
|
|
@ -57,14 +57,19 @@ public class EndToEndChatTests : IAsyncLifetime
|
||||||
UseTls = false,
|
UseTls = false,
|
||||||
DataDirectory = _testDir,
|
DataDirectory = _testDir,
|
||||||
ServerName = "E2E Test Server",
|
ServerName = "E2E Test Server",
|
||||||
Motd = "Testing GsDChat E2E"
|
Motd = "Testing GsDChat E2E",
|
||||||
|
MaxWebSocketMessageSizeBytes = 1048576
|
||||||
};
|
};
|
||||||
|
|
||||||
builder.Services.AddSingleton(serverOptions);
|
builder.Services.AddSingleton(serverOptions);
|
||||||
builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory));
|
builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory));
|
||||||
|
builder.Services.AddSingleton<InviteTokenService>();
|
||||||
builder.Services.AddSingleton<IAuthService, AuthService>();
|
builder.Services.AddSingleton<IAuthService, AuthService>();
|
||||||
builder.Services.AddSingleton<FileStorageService>();
|
builder.Services.AddSingleton<FileStorageService>();
|
||||||
builder.Services.AddSingleton<ChatWebSocketManager>();
|
builder.Services.AddSingleton<ChatWebSocketManager>();
|
||||||
|
builder.Services.AddSingleton<RateLimitService>();
|
||||||
|
builder.Services.AddSingleton<ConnectionLimiterService>();
|
||||||
|
builder.Services.AddSingleton<CsrfProtectionService>();
|
||||||
|
|
||||||
_app = builder.Build();
|
_app = builder.Build();
|
||||||
|
|
||||||
|
|
@ -95,20 +100,48 @@ public class EndToEndChatTests : IAsyncLifetime
|
||||||
MaxGroupChatUsers = opt.MaxGroupChatUsers
|
MaxGroupChatUsers = opt.MaxGroupChatUsers
|
||||||
}));
|
}));
|
||||||
|
|
||||||
_app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth) =>
|
_app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth, CsrfProtectionService csrf, HttpContext context) =>
|
||||||
{
|
{
|
||||||
|
string? csrfToken = context.Request.Headers["X-CSRF-Token"];
|
||||||
|
// Register the token for testing (since client generates it)
|
||||||
|
if (!string.IsNullOrWhiteSpace(csrfToken))
|
||||||
|
{
|
||||||
|
csrf.RegisterTokenForTesting(csrfToken, "");
|
||||||
|
}
|
||||||
|
if (!csrf.ValidateToken(csrfToken ?? "", ""))
|
||||||
|
{
|
||||||
|
return Results.BadRequest(new { error = "Invalid CSRF token" });
|
||||||
|
}
|
||||||
|
|
||||||
var res = await auth.RegisterAsync(req);
|
var res = await auth.RegisterAsync(req);
|
||||||
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
||||||
});
|
});
|
||||||
|
|
||||||
_app.MapPost("/api/auth/login", async (LoginRequest req, IAuthService auth) =>
|
_app.MapPost("/api/auth/login", async (LoginRequest req, IAuthService auth, CsrfProtectionService csrf, HttpContext context) =>
|
||||||
{
|
{
|
||||||
|
string? csrfToken = context.Request.Headers["X-CSRF-Token"];
|
||||||
|
// Register the token for testing (since client generates it)
|
||||||
|
if (!string.IsNullOrWhiteSpace(csrfToken))
|
||||||
|
{
|
||||||
|
csrf.RegisterTokenForTesting(csrfToken, "");
|
||||||
|
}
|
||||||
|
if (!csrf.ValidateToken(csrfToken ?? "", ""))
|
||||||
|
{
|
||||||
|
return Results.BadRequest(new { error = "Invalid CSRF token" });
|
||||||
|
}
|
||||||
|
|
||||||
var res = await auth.LoginAsync(req);
|
var res = await auth.LoginAsync(req);
|
||||||
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
||||||
});
|
});
|
||||||
|
|
||||||
_app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileSvc, ChatWebSocketManager ws) =>
|
_app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileSvc, ChatWebSocketManager ws, RateLimitService rateLimiter, HttpContext context) =>
|
||||||
{
|
{
|
||||||
|
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||||
|
if (!rateLimiter.IsAllowed($"upload:{clientIp}"))
|
||||||
|
{
|
||||||
|
return Results.StatusCode(429);
|
||||||
|
}
|
||||||
|
|
||||||
string? token = ExtractToken(req);
|
string? token = ExtractToken(req);
|
||||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
if (user == null) return Results.Unauthorized();
|
if (user == null) return Results.Unauthorized();
|
||||||
|
|
@ -157,22 +190,39 @@ public class EndToEndChatTests : IAsyncLifetime
|
||||||
return Results.File(stream, record.ContentType, record.OriginalFileName);
|
return Results.File(stream, record.ContentType, record.OriginalFileName);
|
||||||
});
|
});
|
||||||
|
|
||||||
_app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager ws) =>
|
_app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager ws, ConnectionLimiterService connLimiter, ServerOptions options) =>
|
||||||
{
|
{
|
||||||
if (!context.WebSockets.IsWebSocketRequest)
|
if (!context.WebSockets.IsWebSocketRequest)
|
||||||
{
|
{
|
||||||
context.Response.StatusCode = 400;
|
context.Response.StatusCode = 400;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||||
|
if (!connLimiter.TryAddConnection(clientIp))
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 429;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
string? token = ExtractToken(context.Request);
|
string? token = ExtractToken(context.Request);
|
||||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
if (user == null)
|
if (user == null)
|
||||||
{
|
{
|
||||||
|
connLimiter.RemoveConnection(clientIp);
|
||||||
context.Response.StatusCode = 401;
|
context.Response.StatusCode = 401;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var socket = await context.WebSockets.AcceptWebSocketAsync();
|
var socket = await context.WebSockets.AcceptWebSocketAsync();
|
||||||
await ws.HandleClientAsync(socket, user, context.RequestAborted);
|
try
|
||||||
|
{
|
||||||
|
await ws.HandleClientAsync(socket, user, context.RequestAborted, options.MaxWebSocketMessageSizeBytes);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
connLimiter.RemoveConnection(clientIp);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
await _app.StartAsync();
|
await _app.StartAsync();
|
||||||
|
|
@ -190,6 +240,13 @@ public class EndToEndChatTests : IAsyncLifetime
|
||||||
{
|
{
|
||||||
if (_app != null)
|
if (_app != null)
|
||||||
{
|
{
|
||||||
|
// Dispose the RateLimitService to stop the cleanup timer
|
||||||
|
var rateLimiter = _app.Services.GetService<RateLimitService>();
|
||||||
|
if (rateLimiter is IDisposable disposableRateLimiter)
|
||||||
|
{
|
||||||
|
disposableRateLimiter.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
await _app.StopAsync();
|
await _app.StopAsync();
|
||||||
await _app.DisposeAsync();
|
await _app.DisposeAsync();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue