This commit is contained in:
tyuXX 2026-10-24 15:19:21 +03:00
parent 68e6fa2353
commit 4714d25724
6 changed files with 86 additions and 20 deletions

View file

@ -9,6 +9,7 @@ using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using GsDChat.Client.State;
using GsDChat.Core.Models;
using GsDChat.Core.Protocol;
@ -42,6 +43,30 @@ public class ChatClientConnection : IDisposable
};
}
private async Task<string> FetchCsrfTokenAsync()
{
try
{
var res = await _httpClient.GetAsync("/api/csrf-token");
if (res.IsSuccessStatusCode)
{
var json = await res.Content.ReadAsStringAsync();
var tokenData = JsonSerializer.Deserialize<Dictionary<string, string>>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (tokenData != null && tokenData.TryGetValue("token", out var token))
{
return token;
}
}
}
catch (Exception ex)
{
_state.SetStatus($"Failed to fetch CSRF token: {ex.Message}");
}
// Fallback to empty string if CSRF token fetch fails
return string.Empty;
}
public async Task<ServerInfoResponse?> GetServerInfoAsync()
{
try
@ -104,13 +129,15 @@ public class ChatClientConnection : IDisposable
try
{
// Fetch CSRF token from server
string csrfToken = await FetchCsrfTokenAsync();
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);
@ -160,13 +187,15 @@ public class ChatClientConnection : IDisposable
try
{
// Fetch CSRF token from server
string csrfToken = await FetchCsrfTokenAsync();
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);

View file

@ -321,7 +321,14 @@ public class Program
};
var ui = new ConsoleUi(state, connection);
await ui.RunAsync(cts.Token);
try
{
await ui.RunAsync(cts.Token);
}
catch (TaskCanceledException)
{
// Expected on shutdown
}
break;
}
}

View file

@ -66,9 +66,29 @@ public class ConsoleUi
_state.NeedsRedraw = false;
}
if (Console.KeyAvailable)
bool keyAvailable;
try
{
var key = Console.ReadKey(intercept: true);
keyAvailable = Console.KeyAvailable;
}
catch (InvalidOperationException)
{
// Console input stream closed during shutdown
break;
}
if (keyAvailable)
{
ConsoleKeyInfo key;
try
{
key = Console.ReadKey(intercept: true);
}
catch (InvalidOperationException)
{
// Console input stream closed during shutdown
break;
}
if (key.Key == ConsoleKey.C && (key.Modifiers & ConsoleModifiers.Control) != 0)
{
@ -113,7 +133,15 @@ public class ConsoleUi
}
else
{
await Task.Delay(30, cancellationToken);
try
{
await Task.Delay(30, cancellationToken);
}
catch (TaskCanceledException)
{
// Expected on shutdown
break;
}
}
}
}

View file

@ -185,6 +185,12 @@ string? ExtractBearerToken(HttpRequest request)
}
// REST Endpoints
app.MapGet("/api/csrf-token", (CsrfProtectionService csrf) =>
{
var token = csrf.GenerateToken();
return Results.Ok(new { token });
});
app.MapGet("/api/info", (ServerOptions opt, IAuthService auth, HttpRequest req) =>
{
if (opt.RequireAuthForServerInfo)

View file

@ -665,10 +665,10 @@
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('');
// Fetch CSRF token from server
const csrfRes = await fetch('/api/csrf-token');
const csrfData = await csrfRes.json();
const csrfToken = csrfData.token || '';
const res = await fetch(endpoint, {
method: 'POST',

View file

@ -87,6 +87,12 @@ public class EndToEndChatTests : IAsyncLifetime
return null;
}
_app.MapGet("/api/csrf-token", (CsrfProtectionService csrf) =>
{
var token = csrf.GenerateToken();
return Results.Ok(new { token });
});
_app.MapGet("/api/info", (ServerOptions opt) => Results.Ok(new ServerInfoResponse
{
ServerName = opt.ServerName,
@ -103,11 +109,6 @@ public class EndToEndChatTests : IAsyncLifetime
_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" });
@ -120,11 +121,6 @@ public class EndToEndChatTests : IAsyncLifetime
_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" });