Interfaccia web, parte 1: ospite, sicurezza, API, modalità dimostrativa, libreria, visualizzatore e account
Febe.Web: AddFebeWeb/UseFebe/FebeWebHost per le due vesti, interfaccia incorporata con IFileProvider proprio, indirizzi italiani, API JSON con contesto generato, eventi SSE, controlli di Host/Origin, gettone del desktop e password con blocco (§13.1), INativeShell e capacità per veste. Modalità --demo con 38 account e circa 18.000 elementi finti e scene del motore. Pagine Libreria, Visualizzatore, Account, Aggiungi account e Scheda account (contenuti, impostazioni con piano, cronologia); schermate in docs/schermate con le differenze dai mockup; prove delle API, della sicurezza, dell'esportazione CSV e dei dati dimostrativi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
76 files changed
+12503
-17
No files matched your search
@@ -0,0 +1,157 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Web.Security;
|
||||
|
||||
/// <summary>Outcome of a login attempt.</summary>
|
||||
public enum LoginStatus
|
||||
{
|
||||
Accepted,
|
||||
WrongPassword,
|
||||
|
||||
/// <summary>Too many wrong attempts: no attempt is checked until <see cref="LoginResult.LockedUntil"/>.</summary>
|
||||
Locked,
|
||||
}
|
||||
|
||||
/// <summary>Result of <see cref="PasswordAccess.TryLogin"/>.</summary>
|
||||
public sealed record LoginResult(LoginStatus Status, string? SessionId = null, DateTimeOffset? LockedUntil = null);
|
||||
|
||||
/// <summary>
|
||||
/// Docker access (spec §13.1): one password (FEBE_PASSWORD), sessions in memory identified by a random value kept in an
|
||||
/// HttpOnly SameSite=Strict cookie, and a lockout after repeated failures — per client and overall, so that guessing
|
||||
/// from many addresses is slowed down too. A restart closes every session. Nothing here is ever logged.
|
||||
/// </summary>
|
||||
public sealed class PasswordAccess
|
||||
{
|
||||
/// <summary>Session cookie name.</summary>
|
||||
public const string CookieName = "febe_sessione";
|
||||
|
||||
private readonly byte[] _passwordHash;
|
||||
private readonly LockoutOptions _options;
|
||||
private readonly Func<DateTimeOffset> _now;
|
||||
private readonly ConcurrentDictionary<string, DateTimeOffset> _sessions = new(StringComparer.Ordinal);
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<string, List<DateTimeOffset>> _failures = new(StringComparer.Ordinal);
|
||||
private readonly List<DateTimeOffset> _allFailures = [];
|
||||
private readonly Dictionary<string, DateTimeOffset> _lockedClients = new(StringComparer.Ordinal);
|
||||
private DateTimeOffset _lockedAll = DateTimeOffset.MinValue;
|
||||
|
||||
public PasswordAccess(string password, LockoutOptions? options = null, Func<DateTimeOffset>? now = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(password);
|
||||
_passwordHash = Hash(password);
|
||||
_options = options ?? new LockoutOptions();
|
||||
_now = now ?? (() => DateTimeOffset.UtcNow);
|
||||
}
|
||||
|
||||
public TimeSpan SessionLifetime => _options.SessionLifetime;
|
||||
|
||||
/// <summary>Checks a password from a client (its address, or another stable key).</summary>
|
||||
public LoginResult TryLogin(string? password, string client)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(client);
|
||||
var now = _now();
|
||||
lock (_gate)
|
||||
{
|
||||
var locked = LockedUntilLocked(client, now);
|
||||
if (locked is not null)
|
||||
{
|
||||
return new LoginResult(LoginStatus.Locked, LockedUntil: locked);
|
||||
}
|
||||
}
|
||||
|
||||
var accepted = password is not null && CryptographicOperations.FixedTimeEquals(Hash(password), _passwordHash);
|
||||
if (accepted)
|
||||
{
|
||||
var id = AccessToken.Base64Url(RandomNumberGenerator.GetBytes(32));
|
||||
_sessions[id] = now + _options.SessionLifetime;
|
||||
lock (_gate)
|
||||
{
|
||||
_failures.Remove(client);
|
||||
}
|
||||
|
||||
return new LoginResult(LoginStatus.Accepted, id);
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
var since = now - _options.Window;
|
||||
if (!_failures.TryGetValue(client, out var list))
|
||||
{
|
||||
list = [];
|
||||
_failures[client] = list;
|
||||
}
|
||||
|
||||
list.RemoveAll(t => t < since);
|
||||
list.Add(now);
|
||||
_allFailures.RemoveAll(t => t < since);
|
||||
_allFailures.Add(now);
|
||||
if (list.Count >= _options.AttemptsPerClient)
|
||||
{
|
||||
_lockedClients[client] = now + _options.LockFor;
|
||||
list.Clear();
|
||||
}
|
||||
|
||||
if (_allFailures.Count >= _options.AttemptsOverall)
|
||||
{
|
||||
_lockedAll = now + _options.LockFor;
|
||||
_allFailures.Clear();
|
||||
}
|
||||
|
||||
var locked = LockedUntilLocked(client, now);
|
||||
return locked is null ? new LoginResult(LoginStatus.WrongPassword) : new LoginResult(LoginStatus.Locked, LockedUntil: locked);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when the session exists and has not expired.</summary>
|
||||
public bool IsValid(string? sessionId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sessionId) || !_sessions.TryGetValue(sessionId, out var expires))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (expires > _now())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
_sessions.TryRemove(sessionId, out _);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>«Esci»: closes a session.</summary>
|
||||
public void Logout(string? sessionId)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(sessionId))
|
||||
{
|
||||
_sessions.TryRemove(sessionId, out _);
|
||||
}
|
||||
}
|
||||
|
||||
private DateTimeOffset? LockedUntilLocked(string client, DateTimeOffset now)
|
||||
{
|
||||
DateTimeOffset? until = null;
|
||||
if (_lockedClients.TryGetValue(client, out var c))
|
||||
{
|
||||
if (c > now)
|
||||
{
|
||||
until = c;
|
||||
}
|
||||
else
|
||||
{
|
||||
_lockedClients.Remove(client);
|
||||
}
|
||||
}
|
||||
|
||||
if (_lockedAll > now && (until is null || _lockedAll > until))
|
||||
{
|
||||
until = _lockedAll;
|
||||
}
|
||||
|
||||
return until;
|
||||
}
|
||||
|
||||
private static byte[] Hash(string text) => SHA256.HashData(Encoding.UTF8.GetBytes(text));
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Febe.Web.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Spec §13.1, first line of defence: the Host header must be one of the allowed names (desktop and demo: loopback with
|
||||
/// the port, against DNS rebinding), and every request that changes something — plus the server-sent events and
|
||||
/// WebSocket openings — must come from the interface itself: <c>Origin</c> equal to the interface, or, for browsers
|
||||
/// that do not send it on same-origin requests, <c>Sec-Fetch-Site: same-origin</c>. Another page open in Alberto's
|
||||
/// browser cannot command Febe or the remote view.
|
||||
/// </summary>
|
||||
public static class HostOriginGuard
|
||||
{
|
||||
/// <summary>Paths opened with GET that still count as commands (long-lived channels).</summary>
|
||||
public static readonly IReadOnlyList<string> ChannelPaths = ["/api/eventi", "/api/vista"];
|
||||
|
||||
/// <summary>True when the Host header is acceptable.</summary>
|
||||
public static bool HostAllowed(HttpRequest request, FebeWebOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (!request.Host.HasValue)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.AllowedHosts.Count == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var host = request.Host.Value;
|
||||
return options.AllowedHosts.Any(a => string.Equals(a, host, StringComparison.OrdinalIgnoreCase)
|
||||
|| (a.EndsWith(":*", StringComparison.Ordinal) && request.Host.Port is not null
|
||||
&& string.Equals(a[..^2], request.Host.Host, StringComparison.OrdinalIgnoreCase)));
|
||||
}
|
||||
|
||||
/// <summary>True for requests that must pass the Origin check.</summary>
|
||||
public static bool NeedsOriginCheck(HttpRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!HttpMethods.IsGet(request.Method) && !HttpMethods.IsHead(request.Method) && !HttpMethods.IsOptions(request.Method))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (request.Headers.Upgrade.Count > 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var path = request.Path.Value ?? string.Empty;
|
||||
return ChannelPaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Origin check. A present Origin must name the interface; without it, a present <c>Sec-Fetch-Site</c> must be
|
||||
/// <c>same-origin</c>. Requests with neither come from programs, not from a web page, and are left to the access
|
||||
/// check (token or password).
|
||||
/// </summary>
|
||||
public static bool OriginAllowed(HttpRequest request, FebeWebOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var origin = request.Headers.Origin.ToString();
|
||||
if (!string.IsNullOrEmpty(origin))
|
||||
{
|
||||
if (string.Equals(origin, "null", StringComparison.Ordinal)
|
||||
|| !Uri.TryCreate(origin, UriKind.Absolute, out var uri)
|
||||
|| (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var expected = ExpectedAuthority(request, options);
|
||||
return expected is not null && string.Equals(Authority(uri), expected, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
var site = request.Headers["Sec-Fetch-Site"].ToString();
|
||||
return string.IsNullOrEmpty(site) || string.Equals(site, "same-origin", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string? ExpectedAuthority(HttpRequest request, FebeWebOptions options)
|
||||
{
|
||||
if (options.TrustForwardedHost && request.Headers["X-Forwarded-Host"].ToString() is { Length: > 0 } forwarded)
|
||||
{
|
||||
return NormalizeAuthority(forwarded.Split(',')[0].Trim(), request.Headers["X-Forwarded-Proto"].ToString().Split(',')[0].Trim() is { Length: > 0 } p ? p : request.Scheme);
|
||||
}
|
||||
|
||||
return request.Host.HasValue ? NormalizeAuthority(request.Host.Value, request.Scheme) : null;
|
||||
}
|
||||
|
||||
private static string Authority(Uri uri) => uri.IsDefaultPort ? uri.Host : $"{uri.Host}:{uri.Port}";
|
||||
|
||||
private static string NormalizeAuthority(string hostAndPort, string scheme)
|
||||
{
|
||||
if (Uri.TryCreate($"{scheme}://{hostAndPort}", UriKind.Absolute, out var uri))
|
||||
{
|
||||
return Authority(uri);
|
||||
}
|
||||
|
||||
return hostAndPort;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The per-start token of the desktop (spec §13.1, Windows).</summary>
|
||||
public static class AccessToken
|
||||
{
|
||||
/// <summary>Cookie set when the window opens the interface with the token; HttpOnly, SameSite=Strict.</summary>
|
||||
public const string CookieName = "febe_gettone";
|
||||
|
||||
/// <summary>Query parameter the window uses once: <c>http://127.0.0.1:port/?gettone=…</c>.</summary>
|
||||
public const string QueryName = "gettone";
|
||||
|
||||
/// <summary>Header accepted instead of the cookie (programs, tests).</summary>
|
||||
public const string HeaderName = "X-Febe-Gettone";
|
||||
|
||||
/// <summary>A new random token (256 bits, URL-safe).</summary>
|
||||
public static string Create() => Base64Url(RandomNumberGenerator.GetBytes(32));
|
||||
|
||||
public static bool Matches(string? candidate, string? expected)
|
||||
{
|
||||
if (string.IsNullOrEmpty(candidate) || string.IsNullOrEmpty(expected))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(candidate)), SHA256.HashData(Encoding.UTF8.GetBytes(expected)));
|
||||
}
|
||||
|
||||
internal static string Base64Url(byte[] bytes) =>
|
||||
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
using Febe.Web.Api;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Febe.Web.Security;
|
||||
|
||||
/// <summary>
|
||||
/// The pluggable access points of spec §13.1, in order: Host, Origin, then the access mode (none for the demo, token
|
||||
/// for the desktop, password for Docker). Also sets the security headers of every response. Requests that fail get a
|
||||
/// short Italian answer and are never logged with their query (the token travels there once).
|
||||
/// </summary>
|
||||
public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions options, PasswordAccess? passwords = null)
|
||||
{
|
||||
/// <summary>Paths reachable without a session in password mode: the login page and what it needs.</summary>
|
||||
public static readonly IReadOnlyList<string> PublicPrefixes =
|
||||
["/accesso", "/api/accesso", "/css/", "/caratteri/", "/img/", "/testi/", "/js/", "/favicon.ico"];
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var request = context.Request;
|
||||
var response = context.Response;
|
||||
SetHeaders(response);
|
||||
|
||||
if (!HostOriginGuard.HostAllowed(request, options))
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status400BadRequest, "Indirizzo non ammesso: apri Febe dal suo indirizzo.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (HostOriginGuard.NeedsOriginCheck(request) && !HostOriginGuard.OriginAllowed(request, options))
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status403Forbidden, "Richiesta rifiutata: non arriva dall'interfaccia di Febe.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (options.Access)
|
||||
{
|
||||
case AccessMode.Token:
|
||||
if (await TokenAsync(context).ConfigureAwait(false))
|
||||
{
|
||||
await next(context).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return;
|
||||
case AccessMode.Password:
|
||||
if (await PasswordAsync(context).ConfigureAwait(false))
|
||||
{
|
||||
await next(context).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return;
|
||||
default:
|
||||
await next(context).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> TokenAsync(HttpContext context)
|
||||
{
|
||||
var request = context.Request;
|
||||
var query = request.Query[AccessToken.QueryName].ToString();
|
||||
if (query.Length > 0)
|
||||
{
|
||||
if (!AccessToken.Matches(query, options.AccessToken))
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status401Unauthorized, "Gettone non valido: apri Febe dalla sua finestra.").ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
context.Response.Cookies.Append(AccessToken.CookieName, query, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Secure = request.IsHttps,
|
||||
Path = "/",
|
||||
IsEssential = true,
|
||||
});
|
||||
|
||||
// The token leaves the address at once: it must not stay in the history or in a bookmark.
|
||||
var rest = QueryString.Create(request.Query.Where(q => !string.Equals(q.Key, AccessToken.QueryName, StringComparison.Ordinal)));
|
||||
context.Response.Redirect(request.PathBase + request.Path + rest);
|
||||
return false;
|
||||
}
|
||||
|
||||
var presented = request.Headers[AccessToken.HeaderName].ToString();
|
||||
if (presented.Length == 0)
|
||||
{
|
||||
presented = request.Cookies[AccessToken.CookieName] ?? string.Empty;
|
||||
}
|
||||
|
||||
if (AccessToken.Matches(presented, options.AccessToken))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
await RefuseAsync(context, StatusCodes.Status401Unauthorized, "Questa pagina si apre solo dalla finestra di Febe.").ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
private async Task<bool> PasswordAsync(HttpContext context)
|
||||
{
|
||||
if (passwords is null)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, "Manca la password dell'interfaccia (FEBE_PASSWORD): Febe non si apre senza.").ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
var path = context.Request.Path.Value ?? "/";
|
||||
if (PublicPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (passwords.IsValid(context.Request.Cookies[PasswordAccess.CookieName]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (IsApi(context.Request) || !HttpMethods.IsGet(context.Request.Method))
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status401Unauthorized, "Sessione scaduta: accedi di nuovo.").ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
context.Response.Redirect("/accesso?torna=" + Uri.EscapeDataString(path));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsApi(HttpRequest request) => request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static async Task RefuseAsync(HttpContext context, int status, string message)
|
||||
{
|
||||
context.Response.StatusCode = status;
|
||||
if (IsApi(context.Request))
|
||||
{
|
||||
await context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
context.Response.ContentType = "text/plain; charset=utf-8";
|
||||
await context.Response.WriteAsync(message).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetHeaders(HttpResponse response)
|
||||
{
|
||||
var headers = response.Headers;
|
||||
headers["X-Content-Type-Options"] = "nosniff";
|
||||
headers["Referrer-Policy"] = "no-referrer";
|
||||
headers["X-Frame-Options"] = "DENY";
|
||||
headers["Cross-Origin-Opener-Policy"] = "same-origin";
|
||||
headers["Content-Security-Policy"] =
|
||||
"default-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; "
|
||||
+ "script-src 'self'; connect-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user