Server reale e veste Docker (M5): composizione, collegamento, vista remota, salute, immagine e modello Unraid
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
35 files changed
+6124
-10
No files matched your search
@@ -0,0 +1,69 @@
|
||||
using Febe.Web.Api;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
namespace Febe.Web.Connection;
|
||||
|
||||
/// <summary>
|
||||
/// <c>GET /salute</c> (PROTOCOLLO.md, spec §11): <c>200 {"stato":"ok"}</c> or <c>503 {"stato":"problema"}</c> and
|
||||
/// nothing else, without authentication, for the Docker health check. It says no more than that on purpose.
|
||||
/// </summary>
|
||||
public static class HealthEndpoint
|
||||
{
|
||||
public const string Path = "/salute";
|
||||
|
||||
public const string Ok = """{"stato":"ok"}""";
|
||||
|
||||
public const string Problem = """{"stato":"problema"}""";
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoints);
|
||||
endpoints.MapMethods(Path, [HttpMethods.Get, HttpMethods.Head], (HttpContext context, IConfigurationProblems problems) =>
|
||||
{
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
var healthy = problems.Current.Count == 0;
|
||||
return Results.Text(healthy ? Ok : Problem, "application/json; charset=utf-8", statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>True for the health check request, which needs neither a session nor an allowed Host.</summary>
|
||||
public static bool IsHealthRequest(HttpRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method))
|
||||
&& string.Equals(request.Path.Value, Path, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// While a configuration problem keeps the engine from starting (spec §8.2, §11), the interface shows only the page
|
||||
/// that explains it: the API answers only what that page and the frame around it need, everything else (library,
|
||||
/// accounts, connection, remote view) gets 503 with the problem in Italian.
|
||||
/// </summary>
|
||||
public sealed class ConfigurationGateMiddleware(RequestDelegate next, IConfigurationProblems problems)
|
||||
{
|
||||
/// <summary>API addresses still answered while there is a problem.</summary>
|
||||
public static readonly IReadOnlyList<string> AllowedApi =
|
||||
["/api/capabilities", "/api/preferences", "/api/accesso", "/api/uscita", "/api/engine", "/api/eventi"];
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var current = problems.Current;
|
||||
var path = context.Request.Path;
|
||||
if (current.Count == 0
|
||||
|| !path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)
|
||||
|| AllowedApi.Any(a => string.Equals(path.Value, a, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
await next(context).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
await context.Response.WriteAsJsonAsync(
|
||||
new ProblemDto($"{current[0].Title}. Il motore non è partito: {current[0].Remedy}"),
|
||||
FebeJsonContext.Default.ProblemDto).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
namespace Febe.Web.Connection;
|
||||
|
||||
/// <summary>
|
||||
/// The browser seen through the interface (Docker only, spec §4.1, §11, mockup 10). Implemented by the server
|
||||
/// composition over the real Chromium; the web layer only speaks the protocol of <c>PROTOCOLLO.md</c> over a WebSocket.
|
||||
/// </summary>
|
||||
public interface IRemoteViewHost
|
||||
{
|
||||
/// <summary>
|
||||
/// Opens a remote view: Alberto is now driving (the engine is still) and frames start. A view opened earlier
|
||||
/// (another tab) is closed with <see cref="RemoteViewEnd.Replaced"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="RemoteViewUnavailableException">The browser is not running: nothing to show.</exception>
|
||||
Task<IRemoteViewConnection> OpenAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>One open remote view. Disposing it stops the frames and ends «Alberto is driving».</summary>
|
||||
public interface IRemoteViewConnection : IAsyncDisposable
|
||||
{
|
||||
/// <summary>What goes to the page, in order: meta first, then frames (the oldest dropped when the page is slow).</summary>
|
||||
IAsyncEnumerable<RemoteViewOutput> ReadAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Why the view ended on the server side (null while it is open).</summary>
|
||||
RemoteViewEnd? Ended { get; }
|
||||
|
||||
Task MouseAsync(RemoteViewMouse input, CancellationToken ct);
|
||||
|
||||
Task KeyAsync(RemoteViewKey input, CancellationToken ct);
|
||||
|
||||
Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Why a remote view ended without Alberto closing it.</summary>
|
||||
public enum RemoteViewEnd
|
||||
{
|
||||
/// <summary>Opened again in another tab or window: the newest wins.</summary>
|
||||
Replaced,
|
||||
|
||||
/// <summary>The browser stopped or is restarting.</summary>
|
||||
BrowserStopped,
|
||||
|
||||
/// <summary>The server is shutting down.</summary>
|
||||
ShuttingDown,
|
||||
}
|
||||
|
||||
/// <summary>A message for the page: a JPEG frame, or a meta message (address and size).</summary>
|
||||
public abstract record RemoteViewOutput;
|
||||
|
||||
/// <summary>A frame of the screencast, sent as one binary WebSocket message.</summary>
|
||||
/// <param name="Jpeg">The JPEG bytes.</param>
|
||||
public sealed record RemoteViewFrame(ReadOnlyMemory<byte> Jpeg) : RemoteViewOutput;
|
||||
|
||||
/// <summary>Sent at the start and whenever the address or the size changes.</summary>
|
||||
/// <param name="Width">Page width in CSS pixels the frames represent.</param>
|
||||
/// <param name="Height">Page height in CSS pixels the frames represent.</param>
|
||||
/// <param name="Url">Address of the page without query string or fragment.</param>
|
||||
public sealed record RemoteViewMeta(int Width, int Height, string Url) : RemoteViewOutput;
|
||||
|
||||
public enum RemoteViewMouseAction
|
||||
{
|
||||
Move,
|
||||
Down,
|
||||
Up,
|
||||
Wheel,
|
||||
}
|
||||
|
||||
public enum RemoteViewButton
|
||||
{
|
||||
None,
|
||||
Left,
|
||||
Middle,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// <summary>A mouse event; <paramref name="X"/> and <paramref name="Y"/> are 0–1 of the frame.</summary>
|
||||
public sealed record RemoteViewMouse(
|
||||
RemoteViewMouseAction Action,
|
||||
double X,
|
||||
double Y,
|
||||
RemoteViewButton Button,
|
||||
int ClickCount,
|
||||
double DeltaX,
|
||||
double DeltaY);
|
||||
|
||||
public enum RemoteViewKeyAction
|
||||
{
|
||||
/// <summary>Key pressed; when it has <see cref="RemoteViewKey.Text"/> the text is inserted.</summary>
|
||||
Down,
|
||||
|
||||
Up,
|
||||
|
||||
/// <summary>Text only (composed characters): inserted without key codes.</summary>
|
||||
Char,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A key from the page. Contains what Alberto types, passwords included: never logged, never stored, never shown
|
||||
/// (spec §13.2). <see cref="ToString"/> hides everything on purpose.
|
||||
/// </summary>
|
||||
/// <param name="Action">Down, up or char.</param>
|
||||
/// <param name="Key">DOM <c>key</c>.</param>
|
||||
/// <param name="Code">DOM <c>code</c>.</param>
|
||||
/// <param name="Text">Text the key produces, if any.</param>
|
||||
/// <param name="Modifiers">Bit mask of <c>Input.dispatchKeyEvent</c>: Alt 1, Ctrl 2, Meta 4, Shift 8.</param>
|
||||
public sealed record RemoteViewKey(RemoteViewKeyAction Action, string Key, string Code, string? Text, int Modifiers)
|
||||
{
|
||||
public override string ToString() => "RemoteViewKey(…)";
|
||||
}
|
||||
|
||||
public enum RemoteViewNavigation
|
||||
{
|
||||
/// <summary>Back to the previous address of this view.</summary>
|
||||
Back,
|
||||
|
||||
/// <summary>Reload the current page.</summary>
|
||||
Reload,
|
||||
}
|
||||
|
||||
/// <summary>The browser is not available (starting, restarting, missing, or Febe stopped by a configuration problem).</summary>
|
||||
public sealed class RemoteViewUnavailableException : Exception
|
||||
{
|
||||
public RemoteViewUnavailableException()
|
||||
: base("Il browser di Febe non è disponibile in questo momento.")
|
||||
{
|
||||
}
|
||||
|
||||
public RemoteViewUnavailableException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public RemoteViewUnavailableException(string message, Exception? inner)
|
||||
: base(message, inner)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
using System.Buffers;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using Febe.Web.Api;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Web.Connection;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/vista</c>: the remote view over a WebSocket (PROTOCOLLO.md, spec §4.1, §11). The security middleware has
|
||||
/// already checked the session and the <c>Origin</c> (spec §13.1) before this runs. Frames go out as binary messages,
|
||||
/// meta as text; mouse, keys and back/reload come in as small JSON text messages and go to the browser. Nothing that
|
||||
/// comes in is ever logged: it contains what Alberto types.
|
||||
/// </summary>
|
||||
public static class RemoteViewSocket
|
||||
{
|
||||
public const string Path = "/api/vista";
|
||||
|
||||
/// <summary>Largest message accepted from the page; larger ones close the view.</summary>
|
||||
public const int MaxMessageBytes = 4096;
|
||||
|
||||
/// <summary>Close code when the view was opened again elsewhere (the newest wins).</summary>
|
||||
public const int CloseReplaced = 4001;
|
||||
|
||||
/// <summary>Close code when the browser stopped or is restarting.</summary>
|
||||
public const int CloseBrowserStopped = 4002;
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoints);
|
||||
endpoints.Map(Path, HandleAsync);
|
||||
}
|
||||
|
||||
public static async Task HandleAsync(HttpContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var options = context.RequestServices.GetRequiredService<FebeWebOptions>();
|
||||
if (options.Edition == FebeEdition.Desktop && !options.Demo)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status404NotFound, "Sul desktop il browser di Febe ha la sua finestra: la vista remota c'è solo nel contenitore.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!context.WebSockets.IsWebSocketRequest)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status400BadRequest, "La vista remota si apre solo con una connessione WebSocket.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.RequestServices.GetService<IRemoteViewHost>() is not { } host)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, "La vista remota non è disponibile: il browser di Febe non è in funzione.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
IRemoteViewConnection connection;
|
||||
try
|
||||
{
|
||||
connection = await host.OpenAsync(context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
catch (RemoteViewUnavailableException ex)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, ex.Message).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await using (connection.ConfigureAwait(false))
|
||||
{
|
||||
using var socket = await context.WebSockets.AcceptWebSocketAsync(new WebSocketAcceptContext
|
||||
{
|
||||
KeepAliveInterval = TimeSpan.FromSeconds(20),
|
||||
DangerousEnableCompression = false,
|
||||
}).ConfigureAwait(false);
|
||||
await RunAsync(socket, connection, context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pumps one view until either side closes it.</summary>
|
||||
internal static async Task RunAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken aborted)
|
||||
{
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(aborted);
|
||||
var sender = Task.Run(() => SendLoopAsync(socket, connection, stop.Token), CancellationToken.None);
|
||||
var closeStatus = WebSocketCloseStatus.NormalClosure;
|
||||
var closeText = "Vista chiusa";
|
||||
try
|
||||
{
|
||||
if (!await ReceiveLoopAsync(socket, connection, stop.Token).ConfigureAwait(false))
|
||||
{
|
||||
closeStatus = WebSocketCloseStatus.MessageTooBig;
|
||||
closeText = "Messaggio troppo lungo";
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException)
|
||||
{
|
||||
// The page went away.
|
||||
}
|
||||
finally
|
||||
{
|
||||
await stop.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await sender.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
||||
try
|
||||
{
|
||||
await socket.CloseOutputAsync(closeStatus, closeText, timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task SendLoopAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken ct)
|
||||
{
|
||||
await foreach (var output in connection.ReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
switch (output)
|
||||
{
|
||||
case RemoteViewMeta meta:
|
||||
await socket.SendAsync(MetaJson(meta), WebSocketMessageType.Text, endOfMessage: true, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case RemoteViewFrame frame:
|
||||
await socket.SendAsync(frame.Jpeg, WebSocketMessageType.Binary, endOfMessage: true, ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// The server ended the view (another tab, browser stopped, shutdown): tell the page why.
|
||||
if (!ct.IsCancellationRequested && socket.State == WebSocketState.Open)
|
||||
{
|
||||
var (status, text) = connection.Ended switch
|
||||
{
|
||||
RemoteViewEnd.Replaced => ((WebSocketCloseStatus)CloseReplaced, "Vista aperta in un'altra finestra"),
|
||||
RemoteViewEnd.ShuttingDown => (WebSocketCloseStatus.EndpointUnavailable, "Febe si sta fermando"),
|
||||
_ => ((WebSocketCloseStatus)CloseBrowserStopped, "Il browser si è fermato"),
|
||||
};
|
||||
await socket.CloseOutputAsync(status, text, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the page's messages until it closes. Returns false when a message was too long: the caller closes the
|
||||
/// view (only one task may send at a time, and the frames are being sent by another).
|
||||
/// </summary>
|
||||
private static async Task<bool> ReceiveLoopAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken ct)
|
||||
{
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(MaxMessageBytes + 1);
|
||||
try
|
||||
{
|
||||
while (socket.State == WebSocketState.Open && !ct.IsCancellationRequested)
|
||||
{
|
||||
var length = 0;
|
||||
ValueWebSocketReceiveResult result;
|
||||
do
|
||||
{
|
||||
if (length >= MaxMessageBytes + 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
result = await socket.ReceiveAsync(buffer.AsMemory(length, MaxMessageBytes + 1 - length), ct).ConfigureAwait(false);
|
||||
if (result.MessageType == WebSocketMessageType.Close)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
length += result.Count;
|
||||
}
|
||||
while (!result.EndOfMessage);
|
||||
|
||||
if (length > MaxMessageBytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (result.MessageType != WebSocketMessageType.Text)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await DispatchAsync(buffer.AsMemory(0, length), connection, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Parses one message of the page and forwards it. Unknown or malformed messages are dropped silently.</summary>
|
||||
internal static async Task DispatchAsync(ReadOnlyMemory<byte> message, IRemoteViewConnection connection, CancellationToken ct)
|
||||
{
|
||||
object? input;
|
||||
try
|
||||
{
|
||||
input = Parse(message);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
switch (input)
|
||||
{
|
||||
case RemoteViewMouse mouse:
|
||||
await connection.MouseAsync(mouse, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case RemoteViewKey key:
|
||||
await connection.KeyAsync(key, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case RemoteViewNavigation navigation:
|
||||
await connection.NavigateAsync(navigation, ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException && ex is not OutOfMemoryException)
|
||||
{
|
||||
// A lost gesture (no frame yet, browser restarting): the page simply tries again. Never logged: it may
|
||||
// be a key of a password.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The input messages of PROTOCOLLO.md: <c>mouse</c>, <c>key</c>, <c>navigate</c>. Returns null for anything else
|
||||
/// (unknown type or action, missing fields, values out of range).
|
||||
/// </summary>
|
||||
internal static object? Parse(ReadOnlyMemory<byte> message)
|
||||
{
|
||||
using var document = JsonDocument.Parse(message, new JsonDocumentOptions { MaxDepth = 3 });
|
||||
var root = document.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object || Text(root, "type", 16) is not { } type)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var action = Text(root, "action", 16);
|
||||
switch (type)
|
||||
{
|
||||
case "mouse":
|
||||
{
|
||||
RemoteViewMouseAction? kind = action switch
|
||||
{
|
||||
"move" => RemoteViewMouseAction.Move,
|
||||
"down" => RemoteViewMouseAction.Down,
|
||||
"up" => RemoteViewMouseAction.Up,
|
||||
"wheel" => RemoteViewMouseAction.Wheel,
|
||||
_ => null,
|
||||
};
|
||||
if (kind is null || Number(root, "x") is not { } x || Number(root, "y") is not { } y || x is < 0 or > 1 || y is < 0 or > 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var button = Text(root, "button", 16) switch
|
||||
{
|
||||
"left" => RemoteViewButton.Left,
|
||||
"middle" => RemoteViewButton.Middle,
|
||||
"right" => RemoteViewButton.Right,
|
||||
_ => kind is RemoteViewMouseAction.Down or RemoteViewMouseAction.Up ? RemoteViewButton.Left : RemoteViewButton.None,
|
||||
};
|
||||
var clicks = (int)Math.Clamp(Number(root, "clickCount") ?? 1, 1, 3);
|
||||
var dx = Math.Clamp(Number(root, "deltaX") ?? 0, -5000, 5000);
|
||||
var dy = Math.Clamp(Number(root, "deltaY") ?? 0, -5000, 5000);
|
||||
return new RemoteViewMouse(kind.Value, x, y, button, clicks, dx, dy);
|
||||
}
|
||||
|
||||
case "key":
|
||||
{
|
||||
RemoteViewKeyAction? kind = action switch
|
||||
{
|
||||
"down" => RemoteViewKeyAction.Down,
|
||||
"up" => RemoteViewKeyAction.Up,
|
||||
"char" => RemoteViewKeyAction.Char,
|
||||
_ => null,
|
||||
};
|
||||
var key = Text(root, "key", 64) ?? string.Empty;
|
||||
var code = Text(root, "code", 64) ?? string.Empty;
|
||||
var text = Text(root, "text", 32);
|
||||
var modifiers = (int)Math.Clamp(Number(root, "modifiers") ?? 0, 0, 15);
|
||||
if (kind is null || (kind == RemoteViewKeyAction.Char ? string.IsNullOrEmpty(text) : key.Length == 0))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new RemoteViewKey(kind.Value, key, code, string.IsNullOrEmpty(text) ? null : text, modifiers);
|
||||
}
|
||||
|
||||
case "navigate":
|
||||
return action switch
|
||||
{
|
||||
"back" => RemoteViewNavigation.Back,
|
||||
"reload" => RemoteViewNavigation.Reload,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The meta message as UTF-8 JSON.</summary>
|
||||
internal static ReadOnlyMemory<byte> MetaJson(RemoteViewMeta meta)
|
||||
{
|
||||
var buffer = new ArrayBufferWriter<byte>(256);
|
||||
using (var writer = new Utf8JsonWriter(buffer))
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
writer.WriteString("type", "meta");
|
||||
writer.WriteNumber("width", meta.Width);
|
||||
writer.WriteNumber("height", meta.Height);
|
||||
writer.WriteString("url", meta.Url);
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
return buffer.WrittenMemory;
|
||||
}
|
||||
|
||||
private static string? Text(JsonElement root, string name, int maxLength) =>
|
||||
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.GetString() is { } s && s.Length <= maxLength
|
||||
? s
|
||||
: null;
|
||||
|
||||
private static double? Number(JsonElement root, string name) =>
|
||||
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var d) && double.IsFinite(d)
|
||||
? d
|
||||
: null;
|
||||
|
||||
private static Task RefuseAsync(HttpContext context, int status, string message)
|
||||
{
|
||||
context.Response.StatusCode = status;
|
||||
return context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using System.Net;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Web.Api;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Demo;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Hosting;
|
||||
@@ -58,6 +59,7 @@ public static class FebeWeb
|
||||
services.TryAddSingleton<OfflineEngine>();
|
||||
services.TryAddSingleton<IEngineMonitor>(sp => sp.GetRequiredService<OfflineEngine>());
|
||||
services.TryAddSingleton<IEngineControl>(sp => sp.GetRequiredService<OfflineEngine>());
|
||||
services.TryAddSingleton<IConfigurationProblems, NoConfigurationProblems>();
|
||||
services.AddHttpContextAccessor();
|
||||
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
|
||||
{
|
||||
@@ -86,6 +88,10 @@ public static class FebeWeb
|
||||
}
|
||||
|
||||
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";
|
||||
@@ -111,6 +117,8 @@ public static class FebeWeb
|
||||
LibraryApi.Map(endpoints);
|
||||
AccountsApi.Map(endpoints);
|
||||
AccessApi.Map(endpoints);
|
||||
RemoteViewSocket.Map(endpoints);
|
||||
HealthEndpoint.Map(endpoints);
|
||||
|
||||
endpoints.Map("/api/{**rest}", static context =>
|
||||
{
|
||||
|
||||
+27
-1
@@ -51,7 +51,7 @@ var address = FebeWebHost.BoundAddress(app);
|
||||
|
||||
| Veste | Opzioni | Effetto |
|
||||
|---|---|---|
|
||||
| Docker | `Edition = Docker`, `Access = Password`, `Password = FEBE_PASSWORD`, `AllowedHosts` = nomi con cui si raggiunge il server (anche `nome:*`), `FebeListen.Any(8480)` | Pagina `/accesso`, cookie `febe_sessione` HttpOnly SameSite=Strict, blocco dopo 5 errori per client e 20 in tutto in 15 minuti. Senza password risponde 503 e non si apre |
|
||||
| Docker | `Edition = Docker`, `Access = Password`, `Password = FEBE_PASSWORD`, `AllowedHosts` = nomi con cui si raggiunge il server (anche `nome:*`), `FebeListen.Any(8480)` | Pagina `/accesso`, cookie `febe_sessione` HttpOnly SameSite=Strict, blocco dopo 5 errori per client e 20 in tutto in 15 minuti. Senza password risponde solo alla pagina dell'errore (indirizzi delle pagine, file dell'interfaccia, `GET /api/capabilities` e `/api/preferences`, `/salute`); tutto il resto, vista remota compresa, 503 |
|
||||
| Windows | `Edition = Desktop`, `Access = Token`, `AccessToken = AccessToken.Create()`, `AllowedHosts = FebeWebOptions.LoopbackHosts(porta)`, `FebeListen.Loopback(0)` | La finestra apre `/?gettone=…` una volta: il gettone diventa un cookie HttpOnly Strict e sparisce dall'indirizzo. Anche l'intestazione `X-Febe-Gettone` vale |
|
||||
| Prove e dimostrazione | `Access = None` | Solo su 127.0.0.1 |
|
||||
|
||||
@@ -88,6 +88,32 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
|
||||
|
||||
Ogni altro indirizzo senza estensione risponde con `index.html`; `/api/…` sconosciuto risponde 404 in JSON.
|
||||
|
||||
## Collegamento, vista remota, salute (veste Docker)
|
||||
|
||||
Il contratto con l'interfaccia è `Connection/PROTOCOLLO.md`. Lato server:
|
||||
|
||||
- `IConnectionService` lo registra la composizione (`Febe.Server/ServerConnectionService`, sul Chromium vero; con un
|
||||
problema di configurazione `UnavailableConnectionService`). Gli endpoint `/api/connection/*` lo usano.
|
||||
- `IRemoteViewHost` (`Connection/RemoteView.cs`) apre una vista: `IRemoteViewConnection.ReadAsync` dà prima `meta` poi
|
||||
fotogrammi (i vecchi si scartano se la pagina è lenta), `MouseAsync`/`KeyAsync`/`NavigateAsync` portano i gesti al
|
||||
browser. Una vista alla volta: aprirne un'altra chiude la precedente. Senza `IRemoteViewHost` registrato,
|
||||
`/api/vista` risponde 503.
|
||||
- `/api/vista` (`Connection/RemoteViewSocket.cs`): WebSocket dietro il controllo di sessione e di `Origin` del
|
||||
`SecurityMiddleware`; 404 sulla veste desktop (fuori dalla dimostrazione), 400 se non è un WebSocket, 503 senza
|
||||
browser. Messaggi in arrivo solo testo, al massimo 4 KB (oltre: chiusura 1009); quelli sconosciuti, malformati o con
|
||||
valori fuori intervallo (x e y fuori da 0–1) si scartano in silenzio. Mai registrati.
|
||||
- `modifiers` dei tasti: la maschera di `Input.dispatchKeyEvent` (Alt 1, Ctrl 2, Meta 4, Shift 8).
|
||||
- `key` con `action: "down"` e `text` inserisce il testo; `action: "char"` (con il solo `text`) inserisce un carattere
|
||||
composto senza codici tasto. Per un tasto normale si manda `down` (con `text`) e poi `up`, non anche `char`.
|
||||
- `navigate`: `back` torna all'indirizzo precedente di questa vista (con `Page.navigate`: fra i comandi ammessi di
|
||||
§6.1 non c'è la cronologia del browser), `reload` ricarica l'indirizzo attuale.
|
||||
- Chiusure dal server: 4001 «Vista aperta in un'altra finestra», 4002 «Il browser si è fermato», 1001 «Febe si sta
|
||||
fermando», 1000 normale.
|
||||
- `GET /salute` (`Connection/ConfigurationGate.cs`): senza sessione e con qualunque Host, `200 {"stato":"ok"}` o
|
||||
`503 {"stato":"problema"}` quando `IConfigurationProblems.Current` non è vuoto.
|
||||
- `ConfigurationGateMiddleware`: con un problema di configurazione l'API risponde solo a `capabilities`, `preferences`,
|
||||
`accesso`, `uscita`, `engine` (GET, motore spento) ed `eventi`; il resto 503 con il problema in italiano.
|
||||
|
||||
## Interfaccia (`wwwroot/`)
|
||||
|
||||
Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da disco:
|
||||
|
||||
@@ -14,6 +14,13 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
|
||||
public static readonly IReadOnlyList<string> PublicPrefixes =
|
||||
["/accesso", "/api/accesso", "/css/", "/caratteri/", "/img/", "/testi/", "/js/", "/favicon.ico"];
|
||||
|
||||
/// <summary>
|
||||
/// Without a password (FEBE_PASSWORD missing) only these answer, so that the interface can show the page that
|
||||
/// explains the problem (spec §11): the application page, its files, the capabilities with the problems, the
|
||||
/// preferences (theme). Everything else, the remote view first, gets 503.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> WithoutPasswordApi = ["/api/capabilities", "/api/preferences"];
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
@@ -21,6 +28,13 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
|
||||
var response = context.Response;
|
||||
SetHeaders(response);
|
||||
|
||||
// The Docker health check: no session, any Host (it comes from inside the container), «ok» or «problema» only.
|
||||
if (Connection.HealthEndpoint.IsHealthRequest(request))
|
||||
{
|
||||
await next(context).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!HostOriginGuard.HostAllowed(request, options))
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status400BadRequest, "Indirizzo non ammesso: apri Febe dal suo indirizzo.").ConfigureAwait(false);
|
||||
@@ -99,13 +113,18 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
|
||||
|
||||
private async Task<bool> PasswordAsync(HttpContext context)
|
||||
{
|
||||
var path = context.Request.Path.Value ?? "/";
|
||||
if (passwords is null)
|
||||
{
|
||||
if (OpenWithoutPassword(context.Request, path))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -130,6 +149,25 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
|
||||
|
||||
private static bool IsApi(HttpRequest request) => request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>What may be read without a password: the error page and what it needs, never a command.</summary>
|
||||
private static bool OpenWithoutPassword(HttpRequest request, string path)
|
||||
{
|
||||
if (!HttpMethods.IsGet(request.Method) && !HttpMethods.IsHead(request.Method))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (IsApi(request))
|
||||
{
|
||||
return WithoutPasswordApi.Any(a => string.Equals(path, a, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
// Interface files, and page addresses (no extension) that answer with the application page.
|
||||
return PublicPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase))
|
||||
|| path.StartsWith("/icone/", StringComparison.OrdinalIgnoreCase)
|
||||
|| !Path.HasExtension(path);
|
||||
}
|
||||
|
||||
private static async Task RefuseAsync(HttpContext context, int status, string message)
|
||||
{
|
||||
context.Response.StatusCode = status;
|
||||
|
||||
Reference in new issue
Block a user