Dopo una prova dal vivo andata male, Alberto deve poter mandare un solo file che spieghi perché, senza che nessuno veda dati di altre persone. Attività ha ora il pulsante «Diagnostica», che scarica il rapporto delle sessioni degli ultimi 14 giorni: pagine aperte e forma degli indirizzi, risposte per tipo, stato e dimensione con ciò che i lettori ne hanno fatto, struttura stretta delle forme sconosciute, ricette, segnali, permessi negati, file in coda e scaricati, e il motivo di ogni arresto. Nel rapporto entrano solo valori da elenchi chiusi, numeri, orari e forme: mai nomi, indirizzi completi, codici, cursori, cookie o pezzi di risposte. Le forme degli indirizzi e la regola delle chiavi-dato passano dalla sonda a Core, e la sonda le richiama. Il registratore non lancia mai eccezioni verso la raccolta e tiene i file in Dati/diagnostica per 14 giorni. Prova che il rapporto non contiene valori, con controlli di mutazione; tre giri di revisione avversaria (25 difetti confermati, tutti corretti). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
223 lines
10 KiB
C#
223 lines
10 KiB
C#
using System.Net;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Alerts;
|
|
using Febe.Core.Engine;
|
|
using Febe.Core.Import;
|
|
using Febe.Core.Storage;
|
|
using Febe.Web.Api;
|
|
using Febe.Web.Connection;
|
|
using Febe.Web.Demo;
|
|
using Febe.Web.Engine;
|
|
using Febe.Web.Hosting;
|
|
using Febe.Web.Import;
|
|
using Febe.Web.Library;
|
|
using Febe.Web.Native;
|
|
using Febe.Web.Security;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Hosting.Server;
|
|
using Microsoft.AspNetCore.Hosting.Server.Features;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Routing;
|
|
using Microsoft.AspNetCore.StaticFiles;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Febe.Web;
|
|
|
|
/// <summary>
|
|
/// The web application of Febe, the same for both shells (spec §5): API under <c>/api</c>, server-sent events at
|
|
/// <c>/api/eventi</c>, the interface files embedded in this assembly, and the Italian page addresses
|
|
/// (<c>/libreria</c>, <c>/account/12</c>, <c>/impostazioni/generali</c> …) answered with the application page.
|
|
/// <code>
|
|
/// var app = FebeWebHost.Build(options, FebeListen.Loopback(port), services =>
|
|
/// {
|
|
/// services.AddSingleton<IFebeStorage>(db);
|
|
/// services.AddSingleton(library); // FebeLibrary
|
|
/// services.AddSingleton<IClock>(clock);
|
|
/// services.AddSingleton(engine.Monitor); // IEngineMonitor (optional)
|
|
/// services.AddSingleton<IEngineControl>(new EngineHostControl(engine)); // optional
|
|
/// services.AddSingleton<INativeShell>(shell); // desktop only
|
|
/// });
|
|
/// await app.StartAsync();
|
|
/// </code>
|
|
/// </summary>
|
|
public static class FebeWeb
|
|
{
|
|
/// <summary>
|
|
/// Registers the web layer. Register <c>IFebeStorage</c>, <see cref="FebeLibrary"/> and <see cref="IClock"/> as
|
|
/// well; everything else has a default (no engine, no native functions, files from the library layout) that a
|
|
/// registration made before this call replaces.
|
|
/// </summary>
|
|
public static IServiceCollection AddFebeWeb(this IServiceCollection services, FebeWebOptions options)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(services);
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
services.AddSingleton(options);
|
|
services.TryAddSingleton<INativeShell>(BrowserShell.Instance);
|
|
services.TryAddSingleton<IBrowserWindow, NoBrowserWindow>();
|
|
services.TryAddSingleton<IMediaFileResolver, LibraryFileResolver>();
|
|
services.TryAddSingleton<LibraryChanges>();
|
|
services.TryAddSingleton<BrowserUseTracker>();
|
|
services.TryAddSingleton<OfflineEngine>();
|
|
services.TryAddSingleton<IEngineMonitor>(sp => sp.GetRequiredService<OfflineEngine>());
|
|
services.TryAddSingleton<IEngineControl>(sp => sp.GetRequiredService<OfflineEngine>());
|
|
services.TryAddSingleton<IEngineSettingsControl>(sp => new StoredEngineSettingsControl(sp.GetRequiredService<IFebeStorage>()));
|
|
services.TryAddSingleton<IConfigurationProblems, NoConfigurationProblems>();
|
|
services.TryAddSingleton<IConnectionService, UnavailableConnectionService>();
|
|
services.TryAddSingleton<IBrowserPreview, NoBrowserPreview>();
|
|
services.TryAddSingleton<IDiagnosticSource, NoDiagnosticSource>();
|
|
services.TryAddSingleton<IIncidentHistory>(sp => new StoredIncidentHistory(sp.GetRequiredService<IFebeStorage>()));
|
|
services.TryAddSingleton<IAlertTestSender, NoTelegramSender>();
|
|
services.TryAddSingleton<IDataFolderChange, FixedDataFolder>();
|
|
services.TryAddSingleton<FolderSizes>();
|
|
services.TryAddSingleton<RebuildJob>();
|
|
services.TryAddSingleton(sp => sp.GetService<ImportService>() is { } import
|
|
? new ImportHub(import, sp.GetRequiredService<IClock>(), sp.GetRequiredService<LibraryChanges>())
|
|
: new ImportHub(sp.GetRequiredService<IFebeStorage>(), sp.GetRequiredService<FebeLibrary>(), sp.GetRequiredService<IClock>(), options, sp.GetRequiredService<LibraryChanges>()));
|
|
services.AddHttpContextAccessor();
|
|
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
|
|
{
|
|
services.TryAddSingleton(sp => new PasswordAccess(options.Password, options.Lockout, () => sp.GetRequiredService<IClock>().Now));
|
|
}
|
|
|
|
services.ConfigureHttpJsonOptions(json =>
|
|
{
|
|
json.SerializerOptions.TypeInfoResolverChain.Clear();
|
|
json.SerializerOptions.TypeInfoResolverChain.Add(FebeJsonContext.Default);
|
|
});
|
|
return services;
|
|
}
|
|
|
|
/// <summary>Middleware (security, errors, static files) and every endpoint.</summary>
|
|
public static WebApplication UseFebe(this WebApplication app)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(app);
|
|
var options = app.Services.GetRequiredService<FebeWebOptions>();
|
|
var files = options.InterfaceFolder is { Length: > 0 } folder ? new EmbeddedWwwroot(folder) : new EmbeddedWwwroot();
|
|
|
|
app.UseMiddleware<SecurityMiddleware>();
|
|
if (options.Demo)
|
|
{
|
|
app.UseMiddleware<DemoRequestMiddleware>();
|
|
}
|
|
|
|
app.UseMiddleware<ApiErrorMiddleware>();
|
|
app.UseMiddleware<ConfigurationGateMiddleware>();
|
|
|
|
// The remote view (/api/vista). Origin and session are checked by the security middleware above.
|
|
app.UseWebSockets();
|
|
var types = new FileExtensionContentTypeProvider();
|
|
types.Mappings[".json"] = "application/json; charset=utf-8";
|
|
types.Mappings[".js"] = "text/javascript; charset=utf-8";
|
|
types.Mappings[".css"] = "text/css; charset=utf-8";
|
|
app.UseStaticFiles(new StaticFileOptions
|
|
{
|
|
FileProvider = files,
|
|
ContentTypeProvider = types,
|
|
OnPrepareResponse = ctx => ctx.Context.Response.Headers.CacheControl = "no-cache",
|
|
});
|
|
|
|
app.MapFebeApi(files);
|
|
return app;
|
|
}
|
|
|
|
/// <summary>The endpoints alone (API, events, icons, application page).</summary>
|
|
public static IEndpointRouteBuilder MapFebeApi(this IEndpointRouteBuilder endpoints, EmbeddedWwwroot files)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(endpoints);
|
|
ArgumentNullException.ThrowIfNull(files);
|
|
SystemApi.Map(endpoints, files);
|
|
EngineApi.Map(endpoints);
|
|
LibraryApi.Map(endpoints);
|
|
AccountsApi.Map(endpoints);
|
|
AccessApi.Map(endpoints);
|
|
ConnectionApi.Map(endpoints);
|
|
ActivityApi.Map(endpoints);
|
|
SettingsApi.Map(endpoints);
|
|
ImportApi.Map(endpoints);
|
|
DuplicatesApi.Map(endpoints);
|
|
RemoteViewSocket.Map(endpoints);
|
|
HealthEndpoint.Map(endpoints);
|
|
|
|
endpoints.Map("/api/{**rest}", static context =>
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
|
return context.Response.WriteAsJsonAsync(new ProblemDto("Indirizzo dell'API sconosciuto."), FebeJsonContext.Default.ProblemDto);
|
|
});
|
|
|
|
// Every page address without an extension answers with the application page; the router of the page
|
|
// decides what to show (and says «Pagina non trovata» for unknown addresses).
|
|
var embeddedIndex = files.ReadText("index.html") ?? throw new InvalidOperationException("index.html non è incorporato.");
|
|
endpoints.MapFallback("{*path:nonfile}", context =>
|
|
{
|
|
if (!HttpMethods.IsGet(context.Request.Method) && !HttpMethods.IsHead(context.Request.Method))
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
context.Response.ContentType = "text/html; charset=utf-8";
|
|
context.Response.Headers.CacheControl = "no-cache";
|
|
return context.Response.WriteAsync(files.FromDisk ? files.ReadText("index.html") ?? embeddedIndex : embeddedIndex);
|
|
});
|
|
return endpoints;
|
|
}
|
|
}
|
|
|
|
/// <summary>Builds and starts the web application for either shell.</summary>
|
|
public static class FebeWebHost
|
|
{
|
|
/// <summary>
|
|
/// A web application listening on <paramref name="listen"/> (Kestrel only, no other server), with the web layer
|
|
/// registered and mapped. ASP.NET Core request logs are kept at warnings: the desktop token travels once in a
|
|
/// query string and must never reach a log.
|
|
/// </summary>
|
|
public static WebApplication Build(FebeWebOptions options, FebeListen listen, Action<IServiceCollection> configureServices, Action<ILoggingBuilder>? configureLogging = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
ArgumentNullException.ThrowIfNull(listen);
|
|
ArgumentNullException.ThrowIfNull(configureServices);
|
|
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions
|
|
{
|
|
ApplicationName = typeof(FebeWeb).Assembly.GetName().Name,
|
|
ContentRootPath = AppContext.BaseDirectory,
|
|
});
|
|
builder.WebHost.ConfigureKestrel(kestrel =>
|
|
{
|
|
kestrel.AddServerHeader = false;
|
|
kestrel.Listen(listen.Address, listen.Port);
|
|
});
|
|
builder.Logging.ClearProviders();
|
|
builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning);
|
|
builder.Logging.AddFilter("Microsoft.Hosting", LogLevel.Warning);
|
|
if (configureLogging is not null)
|
|
{
|
|
configureLogging(builder.Logging);
|
|
}
|
|
|
|
configureServices(builder.Services);
|
|
builder.Services.AddFebeWeb(options);
|
|
var app = builder.Build();
|
|
app.UseFebe();
|
|
return app;
|
|
}
|
|
|
|
/// <summary>The address Kestrel actually listens on (after <c>StartAsync</c>; useful with port 0).</summary>
|
|
public static Uri BoundAddress(WebApplication app)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(app);
|
|
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()?.Addresses
|
|
?? throw new InvalidOperationException("Il server non ha indirizzi.");
|
|
var first = addresses.First();
|
|
return new Uri(first.Replace("[::]", "127.0.0.1", StringComparison.Ordinal).Replace("0.0.0.0", "127.0.0.1", StringComparison.Ordinal));
|
|
}
|
|
|
|
/// <summary>The port Kestrel listens on.</summary>
|
|
public static int BoundPort(WebApplication app) => BoundAddress(app).Port;
|
|
|
|
/// <summary>True for an address that only this computer can reach.</summary>
|
|
public static bool IsLoopback(IPAddress address) => IPAddress.IsLoopback(address);
|
|
}
|