Phase 1 completed on top of the library foundations: - Server: startup state machine (config, first run, database down, schema, identity, ready) with an error page that retries by itself; the configured database is the only one ever opened, and a vanished SQLite file is never recreated. REST API and status WebSocket; session cookie auth, CSRF on every form and write call; desktop and demo answer only the computer itself. - Interface: static Blazor rendering with plain forms (no interactive runtime), menu, top bar and phone bottom bar as in the mockups, light and dark themes with appendix C tokens and a contrast test, Panoramica, Diario, Rischio, Impostazioni; service pages for sign-in, first access, desktop first run and the database error page with its choices. - Demo mode (tasks seed-demo): appendix F in a database of its own under the temp folder, frozen clock, never touches the configured installation. - Docker: entrypoint gives /data to PUID:PGID and drops root with setpriv, HEALTHCHECK through bash /dev/tcp; proven with SQLite, PostgreSQL, a wrong configuration and a database that goes away and comes back. - tasks screenshots drives the installed Edge/Chrome through DevTools for exact 1440 and 390 pixel shots; anubis db export|import on the command line. Fixes from the independent review: return paths without control characters, Host check against DNS rebinding, attempt limit counted before the check and also on the error-page password, one-use TOTP codes and a code to switch the second factor off, error-page choices serialized with the startup loop, identity checked before migrating, restore restarts with "Ferma tutto" on, damaged archives reported instead of crashing. Running the server tests on PostgreSQL exposed pages rendered before their data arrived; data-loading components now load first (LoadedComponent). Decisions in ADR 0007. Tests: 100 on SQLite and on PostgreSQL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
178 lines
6.2 KiB
C#
178 lines
6.2 KiB
C#
using System.Diagnostics;
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
|
|
/// <summary>
|
|
/// Screenshots through the DevTools protocol of the Edge or Chrome already installed (ADR 0007). The protocol sets the
|
|
/// exact width: a headless window cannot be narrower than about 500 pixels, too wide for the 390-pixel phone.
|
|
/// </summary>
|
|
internal sealed class Shots : IDisposable
|
|
{
|
|
private readonly Process _browser;
|
|
private readonly ClientWebSocket _socket = new();
|
|
private readonly string _profile;
|
|
private int _id;
|
|
|
|
private Shots(Process browser, string profile)
|
|
{
|
|
_browser = browser;
|
|
_profile = profile;
|
|
}
|
|
|
|
public static Shots Start(string browserPath)
|
|
{
|
|
var profile = Path.Combine(Path.GetTempPath(), "anubis-shots-" + Guid.NewGuid().ToString("N"));
|
|
var info = new ProcessStartInfo(browserPath)
|
|
{
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
};
|
|
foreach (var argument in new[] { "--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check",
|
|
"--remote-debugging-port=0", "--user-data-dir=" + profile, "about:blank" })
|
|
{
|
|
info.ArgumentList.Add(argument);
|
|
}
|
|
|
|
var process = Process.Start(info)!;
|
|
process.OutputDataReceived += (_, _) => { };
|
|
process.ErrorDataReceived += (_, _) => { };
|
|
process.BeginOutputReadLine();
|
|
process.BeginErrorReadLine();
|
|
var shots = new Shots(process, profile);
|
|
try
|
|
{
|
|
shots.Connect();
|
|
return shots;
|
|
}
|
|
catch
|
|
{
|
|
shots.Dispose();
|
|
throw;
|
|
}
|
|
}
|
|
|
|
// The browser writes its port into DevToolsActivePort; the page target is found through /json/list.
|
|
private void Connect()
|
|
{
|
|
var portFile = Path.Combine(_profile, "DevToolsActivePort");
|
|
for (var i = 0; i < 60 && !File.Exists(portFile); i++)
|
|
{
|
|
Thread.Sleep(250);
|
|
}
|
|
|
|
var port = File.ReadAllLines(portFile)[0].Trim();
|
|
using var http = new HttpClient();
|
|
string? target = null;
|
|
for (var i = 0; i < 40 && target is null; i++)
|
|
{
|
|
var list = JsonNode.Parse(http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list")).GetAwaiter().GetResult())!.AsArray();
|
|
target = list.FirstOrDefault(t => (string?)t!["type"] == "page")?["webSocketDebuggerUrl"]?.GetValue<string>();
|
|
if (target is null)
|
|
{
|
|
Thread.Sleep(250);
|
|
}
|
|
}
|
|
|
|
_socket.ConnectAsync(new Uri(target ?? throw new InvalidOperationException("Nessuna pagina nel browser.")), CancellationToken.None).GetAwaiter().GetResult();
|
|
Send("Page.enable", new JsonObject());
|
|
}
|
|
|
|
/// <summary>Opens <paramref name="url"/> at the given size and theme and saves the visible part as PNG.</summary>
|
|
public void Take(string url, int width, int height, bool dark, string file)
|
|
{
|
|
Send("Emulation.setDeviceMetricsOverride", new JsonObject
|
|
{
|
|
["width"] = width,
|
|
["height"] = height,
|
|
["deviceScaleFactor"] = 2,
|
|
["mobile"] = width < 768,
|
|
});
|
|
Send("Emulation.setEmulatedMedia", new JsonObject
|
|
{
|
|
["features"] = new JsonArray(new JsonObject { ["name"] = "prefers-color-scheme", ["value"] = dark ? "dark" : "light" }),
|
|
});
|
|
Send("Page.navigate", new JsonObject { ["url"] = url }, waitForEvent: "Page.loadEventFired");
|
|
Thread.Sleep(500);
|
|
var result = Send("Page.captureScreenshot", new JsonObject { ["format"] = "png" });
|
|
File.WriteAllBytes(file, Convert.FromBase64String(result["data"]!.GetValue<string>()));
|
|
}
|
|
|
|
// Sends one command and waits for its answer (and, if asked, for an event), skipping everything else.
|
|
private JsonNode Send(string method, JsonObject parameters, string? waitForEvent = null)
|
|
{
|
|
var id = ++_id;
|
|
var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters };
|
|
_socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, true, CancellationToken.None).GetAwaiter().GetResult();
|
|
JsonNode? answer = null;
|
|
var eventSeen = waitForEvent is null;
|
|
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
|
while (answer is null || !eventSeen)
|
|
{
|
|
var received = Receive(limit.Token);
|
|
if ((int?)received["id"] == id)
|
|
{
|
|
if (received["error"] is { } error)
|
|
{
|
|
throw new InvalidOperationException(method + ": " + error.ToJsonString());
|
|
}
|
|
|
|
answer = received["result"] ?? new JsonObject();
|
|
}
|
|
else if ((string?)received["method"] == waitForEvent)
|
|
{
|
|
eventSeen = true;
|
|
}
|
|
}
|
|
|
|
return answer;
|
|
}
|
|
|
|
private JsonNode Receive(CancellationToken cancellationToken)
|
|
{
|
|
var buffer = new byte[64 * 1024];
|
|
using var all = new MemoryStream();
|
|
WebSocketReceiveResult result;
|
|
do
|
|
{
|
|
result = _socket.ReceiveAsync(buffer, cancellationToken).GetAwaiter().GetResult();
|
|
all.Write(buffer, 0, result.Count);
|
|
}
|
|
while (!result.EndOfMessage);
|
|
|
|
return JsonNode.Parse(all.ToArray(), documentOptions: new JsonDocumentOptions { MaxDepth = 64 })!;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_socket.Dispose();
|
|
try
|
|
{
|
|
_browser.Kill(entireProcessTree: true);
|
|
_browser.WaitForExit(5000);
|
|
}
|
|
catch (InvalidOperationException)
|
|
{
|
|
}
|
|
|
|
_browser.Dispose();
|
|
for (var i = 0; i < 10 && Directory.Exists(_profile); i++)
|
|
{
|
|
try
|
|
{
|
|
Directory.Delete(_profile, recursive: true);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
Thread.Sleep(300);
|
|
}
|
|
catch (UnauthorizedAccessException)
|
|
{
|
|
Thread.Sleep(300);
|
|
}
|
|
}
|
|
}
|
|
}
|