Piattaforme: istanza unica dopo lo spostamento dei dati, avvio sicuro del contenitore, rilascio con prove e immagine, accesso senza reindirizzamenti esterni (pkg-1, pkg-2, pkg-3, pkg-4, pkg-5, pkg-6, websec-2, web-8, websec-3)

Registro di casa 192.168.30.23:3000 (HTTP) nel modello Unraid, in compose e nel rilascio con buildx; profilo seccomp fuori da /dati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-14 00:59:18 +00:00
1 parent 78c92eb2a4
commit dd9320c54b
36 files changed
+1683 -152

No files matched your search

@@ -40,6 +40,13 @@ public sealed record ChromiumLaunchOptions
/// The Docker image also ships a policy file for the same purpose.
/// </summary>
public bool SeedProfilePreferences { get; init; } = true;
/// <summary>
/// Called with every browser process right after it starts (also after a restart), before it is ready. Windows: Edge
/// is tied to the life of Febe.exe, so that it never outlives a crash of Febe holding the profile and the debugging
/// port. Null: nothing.
/// </summary>
public Action<System.Diagnostics.Process>? ProcessStarted { get; init; }
}
/// <summary>
@@ -229,6 +229,8 @@ public sealed class ChromiumProcessHost : IBrowserHost
private async Task WaitReadyAndConnectAsync(Process process, CancellationToken ct)
{
// First of all, as close to the start as possible: the processes the browser opens afterwards follow it.
_launch.ProcessStarted?.Invoke(process);
var options = _options ?? throw new InvalidOperationException("Opzioni mancanti.");
var port = options.DebugPort;
var deadline = _clock.Now + _launch.StartupTimeout;
+144 -23
View File
@@ -1,20 +1,34 @@
using System.Text;
namespace Febe.Desktop.Core;
/// <summary>
/// «Avvia Febe all'accensione del computer» (spec §12): the value <c>Febe</c> under
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c>, per user, no administrator rights. Febe then starts with
/// <c>--nascosto</c>: only the icon in the notification area, the window stays closed.
/// «Avvia Febe all'accensione del computer» (spec §12): a value under <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c>,
/// per user, no administrator rights. Febe then starts with <c>--nascosto</c>: only the icon in the notification area,
/// the window stays closed. Each Febe has its own value: <c>Febe</c> for the usual one (Data folder recorded or
/// default), <c>Febe-…</c> with <c>--dati</c> for one started on a Data folder of its own (a second account), so the
/// switch of one never starts, shows or removes the other.
/// </summary>
public static class Autostart
{
/// <summary>The registry key, under HKEY_CURRENT_USER.</summary>
public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
/// <summary>The name of the value.</summary>
/// <summary>The name of the value of the usual Febe.</summary>
public const string ValueName = "Febe";
/// <summary>The command written in the value: the quoted executable and <c>--nascosto</c>.</summary>
public static string Command(string executable)
/// <summary>
/// The name of the value: <see cref="ValueName"/> without a Data folder of its own, otherwise «Febe-» and the
/// identity of the folder (the same as the single-instance guard, so the same folder always has the same value).
/// </summary>
public static string ValueNameFor(string? fixedDataFolder) =>
fixedDataFolder is null ? ValueName : InstanceIdentity.For(fixedDataFolder);
/// <summary>
/// The command written in the value: the quoted executable, <c>--nascosto</c> and, for a Febe started with
/// <c>--dati</c>, the same Data folder.
/// </summary>
public static string Command(string executable, string? fixedDataFolder = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(executable);
if (executable.Contains('"', StringComparison.Ordinal))
@@ -22,43 +36,150 @@ public static class Autostart
throw new ArgumentException("Percorso dell'eseguibile non valido.", nameof(executable));
}
return $"\"{executable}\" --nascosto";
if (fixedDataFolder is null)
{
return $"\"{executable}\" --nascosto";
}
if (string.IsNullOrWhiteSpace(fixedDataFolder) || fixedDataFolder.Contains('"', StringComparison.Ordinal))
{
throw new ArgumentException("Percorso della cartella dei dati non valido.", nameof(fixedDataFolder));
}
return $"\"{executable}\" --nascosto --dati {Quote(fixedDataFolder)}";
}
/// <summary>True when <paramref name="value"/> starts this executable (a value left by another copy of Febe is not ours).</summary>
public static bool PointsTo(string? value, string executable)
/// <summary>
/// True when <paramref name="value"/> starts this executable on this Data folder: <paramref name="fixedDataFolder"/>
/// for a Febe started with <c>--dati</c>, none for the usual one. A value left by another copy of Febe, or written
/// for another Data folder, is not ours.
/// </summary>
public static bool PointsTo(string? value, string executable, string? fixedDataFolder = null)
{
if (string.IsNullOrWhiteSpace(value) || string.IsNullOrWhiteSpace(executable))
{
return false;
}
var text = value.Trim();
string target;
if (text.StartsWith('"'))
var arguments = Split(value.Trim());
if (arguments is not [var target, .. var rest] || !SamePath(target, executable))
{
var end = text.IndexOf('"', 1);
if (end < 0)
return false;
}
string? dataFolder = null;
for (var i = 0; i < rest.Count; i++)
{
if (string.Equals(rest[i], "--dati", StringComparison.OrdinalIgnoreCase))
{
return false;
if (i + 1 >= rest.Count)
{
return false;
}
dataFolder = rest[++i];
}
}
return fixedDataFolder is null ? dataFolder is null : dataFolder is not null && SamePath(dataFolder, fixedDataFolder);
}
/// <summary>
/// The words of a command line as Windows programs read them: blanks separate, quotes group, backslashes are plain
/// except before a quote (2n backslashes and a quote: n backslashes and a quote that groups; 2n+1: n and a literal
/// quote). Null for an unfinished quote.
/// </summary>
internal static List<string>? Split(string commandLine)
{
var words = new List<string>();
var word = new StringBuilder();
var inWord = false;
var quoted = false;
for (var i = 0; i < commandLine.Length; i++)
{
var c = commandLine[i];
if (c == '\\')
{
var start = i;
while (i < commandLine.Length && commandLine[i] == '\\')
{
i++;
}
var count = i - start;
if (i < commandLine.Length && commandLine[i] == '"')
{
word.Append('\\', count / 2);
if (count % 2 == 1)
{
word.Append('"');
}
else
{
quoted = !quoted;
}
}
else
{
word.Append('\\', count);
i--;
}
inWord = true;
continue;
}
target = text[1..end];
}
else
{
var space = text.IndexOf(' ', StringComparison.Ordinal);
target = space < 0 ? text : text[..space];
if (c == '"')
{
quoted = !quoted;
inWord = true;
continue;
}
if (!quoted && char.IsWhiteSpace(c))
{
if (inWord)
{
words.Add(word.ToString());
word.Clear();
inWord = false;
}
continue;
}
word.Append(c);
inWord = true;
}
return string.Equals(Normalize(target), Normalize(executable), StringComparison.OrdinalIgnoreCase);
if (quoted)
{
return null;
}
if (inWord)
{
words.Add(word.ToString());
}
return words;
}
/// <summary>A quoted argument: backslashes before the closing quote are doubled (<c>"D:\\"</c> reads back as <c>D:\</c>).</summary>
private static string Quote(string argument)
{
var trailing = argument.Length - argument.TrimEnd('\\').Length;
return "\"" + argument + new string('\\', trailing) + "\"";
}
private static bool SamePath(string a, string b) =>
string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase);
private static string Normalize(string path)
{
try
{
return Path.GetFullPath(path);
return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
+89
View File
@@ -0,0 +1,89 @@
namespace Febe.Desktop.Core;
/// <summary>What <see cref="DataFolderLock.TryAcquire"/> found.</summary>
public enum DataFolderLockOutcome
{
/// <summary>This Febe holds the lock: no other Febe can open the Data folder until it ends.</summary>
Acquired,
/// <summary>Another Febe holds it: it is already running on this Data folder.</summary>
HeldByAnother,
/// <summary>
/// The lock file cannot be written at all (a folder that is not writable, a file in its place…): the start-up checks
/// explain that problem, and with it Febe starts neither the engine nor the browser.
/// </summary>
Unavailable,
}
/// <summary>
/// The second guard of «one Febe at a time on a Data folder» (spec §12, rule 7): the file <c>febe.lock</c> inside the
/// folder, open without sharing for the whole life of the process; Windows closes it when the process ends, even after a
/// crash. The named mutex of <see cref="InstanceIdentity"/> is derived from the path, so two spellings of the same folder
/// (a short 8.3 name, a drive letter made with <c>subst</c>, a junction) would get two names; the file is the same one.
/// </summary>
public sealed class DataFolderLock : IDisposable
{
/// <summary>The name of the lock file, inside the Data folder.</summary>
public const string FileName = "febe.lock";
// Windows: ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION. Elsewhere .NET emulates FileShare.None with flock, which
// answers EWOULDBLOCK (11 on Linux, 35 on macOS): only for the tests of this class, Febe.exe runs on Windows.
private const int SharingViolation = 32;
private const int LockViolation = 33;
private const int WouldBlockLinux = 11;
private const int WouldBlockMac = 35;
private readonly FileStream _file;
private DataFolderLock(FileStream file, string path)
{
_file = file;
Path = path;
}
/// <summary>The lock file.</summary>
public string Path { get; }
/// <summary>
/// Takes the lock of <paramref name="dataFolder"/> (creating the folder if needed). A file held by someone else is
/// tried again for <paramref name="patience"/> (an antivirus may look at it for a moment) before it counts as
/// another Febe.
/// </summary>
public static DataFolderLockOutcome TryAcquire(string dataFolder, out DataFolderLock? acquired, TimeSpan? patience = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder);
acquired = null;
var path = System.IO.Path.Combine(System.IO.Path.GetFullPath(dataFolder), FileName);
var deadline = DateTime.UtcNow + (patience ?? TimeSpan.FromSeconds(2));
while (true)
{
try
{
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);
var file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1, FileOptions.None);
acquired = new DataFolderLock(file, path);
return DataFolderLockOutcome.Acquired;
}
catch (IOException ex) when (IsHeldElsewhere(ex))
{
if (DateTime.UtcNow >= deadline)
{
return DataFolderLockOutcome.HeldByAnother;
}
Thread.Sleep(200);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or ArgumentException)
{
return DataFolderLockOutcome.Unavailable;
}
}
}
public void Dispose() => _file.Dispose();
private static bool IsHeldElsewhere(IOException ex) => OperatingSystem.IsWindows()
? (ex.HResult & 0xFFFF) is SharingViolation or LockViolation
: ex.HResult is WouldBlockLinux or WouldBlockMac;
}
+54 -2
View File
@@ -39,7 +39,15 @@ public enum DataFolderMoveOutcome
}
/// <summary>Outcome of <see cref="DataFolderMove.ApplyPending"/>, with an Italian message for the log and a notification.</summary>
public sealed record DataFolderMoveResult(DataFolderMoveOutcome Outcome, string DataFolder, string? Message);
public sealed record DataFolderMoveResult(DataFolderMoveOutcome Outcome, string DataFolder, string? Message)
{
/// <summary>
/// After a move, the single-instance guard of the new folder, taken before anything was written there: from now on
/// every launch finds the new folder recorded, and must find this Febe holding it. Null when no move happened or no
/// guard was asked for. The caller keeps it for the life of the process.
/// </summary>
public IDisposable? TargetGuard { get; init; }
}
/// <summary>Progress of the copy: files and bytes.</summary>
public sealed record DataFolderMoveProgress(int FilesDone, int FilesTotal, long BytesDone, long BytesTotal);
@@ -107,7 +115,17 @@ public static class DataFolderMove
/// <summary>
/// Applies the move asked from Impostazioni, if any. Call it before anything opens <paramref name="current"/>.
/// </summary>
public static DataFolderMoveResult ApplyPending(IDataFolderLocationStore store, string current, IProgress<DataFolderMoveProgress>? progress = null, DataFolderCheck? check = null)
/// <param name="store">Where the folder in use and the pending move are recorded.</param>
/// <param name="current">The Data folder this Febe started on (and holds the single-instance guard of).</param>
/// <param name="progress">Progress of the copy.</param>
/// <param name="check">The checks of a Data folder (local disk, writable).</param>
/// <param name="claimTarget">
/// Takes the single-instance guard of the new folder (spec §12: one Febe at a time on a Data folder). It is taken
/// before anything is written there, and before the new folder is recorded: a launch that reads the new folder must
/// find this Febe, never start a second one on it. When another Febe holds it the move does not happen. A guard
/// taken for a move that fails is given back. Null: no guard (tests of the copy alone).
/// </param>
public static DataFolderMoveResult ApplyPending(IDataFolderLocationStore store, string current, IProgress<DataFolderMoveProgress>? progress = null, DataFolderCheck? check = null, InstanceGuardFactory? claimTarget = null)
{
ArgumentNullException.ThrowIfNull(store);
ArgumentException.ThrowIfNullOrWhiteSpace(current);
@@ -124,6 +142,40 @@ public static class DataFolderMove
return new DataFolderMoveResult(DataFolderMoveOutcome.Failed, from, $"La cartella dei dati non è stata spostata in {to}: {reason} Febe usa ancora {from}.");
}
IDisposable? guard = null;
if (claimTarget is not null)
{
guard = claimTarget(to);
if (guard is null)
{
store.SetPending(null);
return new DataFolderMoveResult(
DataFolderMoveOutcome.Failed,
from,
$"La cartella dei dati non è stata spostata in {to}: un altro Febe la sta già usando. Febe usa ancora {from}.");
}
}
try
{
var result = Move(store, from, to, progress);
if (result.Outcome == DataFolderMoveOutcome.Failed)
{
guard?.Dispose();
return result;
}
return result with { TargetGuard = guard };
}
catch
{
guard?.Dispose();
throw;
}
}
private static DataFolderMoveResult Move(IDataFolderLocationStore store, string from, string to, IProgress<DataFolderMoveProgress>? progress)
{
if (!Directory.Exists(from))
{
// Nothing to copy (Febe never ran here): the new folder is simply used from now on.
+17 -1
View File
@@ -47,6 +47,13 @@ public interface IDesktopShell
/// <summary>Moves the main window of a process (Edge) out of view, still open: never minimised (S2).</summary>
Task HideProcessWindowAsync(int processId, CancellationToken ct);
/// <summary>
/// Ties a process Febe started (Edge) to the life of Febe.exe: Windows ends it, with the processes it opens, when
/// Febe ends — also after a crash or «Termina attività», so that it never stays behind holding the profile and the
/// debugging port. False when Windows refused (the process then lives on its own, as before).
/// </summary>
bool EndWithFebe(System.Diagnostics.Process process);
}
/// <summary>
@@ -160,7 +167,9 @@ public sealed class DesktopPlatform : IFebePlatform
/// <summary>
/// Edge for the last fallback of S2: the same <see cref="ChromiumProcessHost"/> as Docker, with its fixed DevTools
/// port on 127.0.0.1, a profile of its own inside <c>Dati\browser</c> (so «Scollega» deletes both), preferences
/// with password saving and autofill off, and the switches of S2.
/// with password saving and autofill off, and the switches of S2. Every Edge started is tied to the life of
/// Febe.exe (<see cref="IDesktopShell.EndWithFebe"/>): an Edge left behind by a crash would keep the port, and every
/// later start would find it «occupata».
/// </summary>
private ChromiumBrowser CreateEdge(FebePlatformContext context, string executable) => new(
new ChromiumBrowserSettings
@@ -177,6 +186,13 @@ public sealed class DesktopPlatform : IFebePlatform
ExtraArguments = BrowserArguments.ForEdge(),
SessionCookie = _options.Site.SessionCookie,
SeedProfilePreferences = true,
ProcessStarted = process =>
{
if (!_shell.EndWithFebe(process))
{
context.Log.Warn("browser", "Windows non ha legato Edge a Febe: se Febe si chiudesse all'improvviso, Edge resterebbe aperto (chiudilo dal Gestione attività).");
}
},
},
},
context.Clock,
+6
View File
@@ -27,6 +27,12 @@ public static class InstanceIdentity
public static string PipeName(string dataFolder) => For(dataFolder);
}
/// <summary>
/// Takes the single-instance guard of a Data folder (on Windows the named mutex and pipe of <see cref="InstanceIdentity"/>)
/// for this Febe; null when another Febe already holds it. Disposing the guard gives it back.
/// </summary>
public delegate IDisposable? InstanceGuardFactory(string dataFolder);
/// <summary>What a second launch asks the running Febe.</summary>
public enum InstanceRequest
{
+53 -9
View File
@@ -26,9 +26,13 @@ internal sealed class DesktopApplication : Application
private readonly DesktopFolders _folders;
private readonly IDataFolderLocationStore _locations;
private readonly bool _dataFolderFixed;
private readonly SingleInstanceGuard _instance;
// The single-instance guards this Febe holds: the one of the folder it started on (taken by Program, disposed there)
// and, after a move, the one of the new folder — which every later launch finds recorded.
private readonly List<SingleInstanceGuard> _instances;
private readonly CancellationTokenSource _lifetime = new();
private string _dataFolder;
private DataFolderLock? _dataLock;
private ImageSource? _iconImage;
private TrayIcon? _tray;
private DesktopPlatform? _platform;
@@ -44,7 +48,7 @@ internal sealed class DesktopApplication : Application
_locations = locations;
_dataFolder = dataFolder;
_dataFolderFixed = dataFolderFixed;
_instance = instance;
_instances = [instance];
ShutdownMode = ShutdownMode.OnExplicitShutdown;
DispatcherUnhandledException += OnDispatcherUnhandledException;
TaskScheduler.UnobservedTaskException += (_, e) => e.SetObserved();
@@ -85,13 +89,34 @@ internal sealed class DesktopApplication : Application
{
moved = await MoveDataFolderAsync().ConfigureAwait(true);
_dataFolder = moved.DataFolder;
if (moved.TargetGuard is SingleInstanceGuard guard)
{
_instances.Add(guard);
}
if (moved.Message is { } message)
{
_tray.Notify("Cartella dei dati", message, moved.Outcome != DataFolderMoveOutcome.Moved);
}
}
var native = new WindowsShell(Dispatcher, () => _main, () => _tray);
// The folder itself is locked too: the guards are named after its path, the lock is the folder (spec §12).
if (DataFolderLock.TryAcquire(_dataFolder, out _dataLock) == DataFolderLockOutcome.HeldByAnother)
{
if (!_options.StartHidden)
{
MessageBox.Show(
$"Febe è già aperto con questa cartella dei dati ({_dataFolder}): cercalo nell'area di notifica, accanto all'orologio.",
"Febe",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
await ExitAsync().ConfigureAwait(true);
return;
}
var native = new WindowsShell(Dispatcher, () => _main, () => _tray, _dataFolderFixed ? _dataFolder : null);
var shell = new DesktopShell(Dispatcher, _iconImage, native);
_platform = new DesktopPlatform(_options, shell, _locations, _dataFolderFixed);
_app = await FebeApp.StartAsync(_options.AppOptions(_dataFolder, _folders), _platform, new FebeAppHooks(), _lifetime.Token).ConfigureAwait(true);
@@ -124,13 +149,17 @@ internal sealed class DesktopApplication : Application
return;
}
_instance.Listen(request => Dispatcher.InvokeAsync(() =>
foreach (var instance in _instances)
{
if (request == InstanceRequest.Show)
instance.Listen(request => Dispatcher.InvokeAsync(() =>
{
ShowMain();
}
}));
if (request == InstanceRequest.Show)
{
ShowMain();
}
}));
}
_ = Task.Run(() => FollowEngineAsync(_lifetime.Token));
if (!_options.StartHidden || _app.Problems.Count > 0)
@@ -298,7 +327,7 @@ internal sealed class DesktopApplication : Application
bar.Value = p.FilesDone;
});
var current = _dataFolder;
return await Task.Run(() => DataFolderMove.ApplyPending(_locations, current, progress)).ConfigureAwait(true);
return await Task.Run(() => DataFolderMove.ApplyPending(_locations, current, progress, claimTarget: SingleInstanceGuard.TryAcquire)).ConfigureAwait(true);
}
finally
{
@@ -335,6 +364,21 @@ internal sealed class DesktopApplication : Application
_tray = null;
}
/// <summary>
/// Everything has stopped: the lock of the Data folder and the guard of a moved folder go last. The guard of the
/// folder Febe started on belongs to Program, which disposes it when the application returns.
/// </summary>
protected override void OnExit(ExitEventArgs e)
{
_dataLock?.Dispose();
foreach (var instance in _instances.Skip(1))
{
instance.Dispose();
}
base.OnExit(e);
}
/// <summary>Windows is shutting down or Alberto logs off: stop in order while the messages still flow (S3).</summary>
private void OnSessionEnding(object sender, SessionEndingCancelEventArgs e)
{
+2
View File
@@ -89,6 +89,8 @@ internal sealed class DesktopShell(Dispatcher ui, ImageSource? icon, INativeShel
Win32.SetWindowPos(window, IntPtr.Zero, x, y, 0, 0, Win32.SwpNoSize | Win32.SwpNoZOrder | Win32.SwpNoActivate);
}).Task;
public bool EndWithFebe(Process process) => ProcessJob.Add(process);
private static IntPtr? MainWindowOf(int processId)
{
try
+116
View File
@@ -0,0 +1,116 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace Febe.Desktop.Native;
/// <summary>
/// A job object of Windows with «kill on job close»: the processes put in it end when Febe.exe ends, however it ends
/// (Esci, a crash, «Termina attività»), because Windows closes the job's only handle with the process. The processes
/// they start join the job too. Used for Edge, the last fallback of S2 (spec §6.6): without it an Edge left behind keeps
/// the profile and the debugging port 9222, and every later start of Febe finds the port «occupata».
/// </summary>
internal static class ProcessJob
{
private const int JobObjectExtendedLimitInformation = 9;
private const uint JobObjectLimitKillOnJobClose = 0x00002000;
private static readonly Lazy<SafeFileHandle?> Job = new(Create, LazyThreadSafetyMode.ExecutionAndPublication);
/// <summary>Puts <paramref name="process"/> in the job; false when Windows refuses (the process then lives on its own).</summary>
public static bool Add(Process process)
{
ArgumentNullException.ThrowIfNull(process);
if (Job.Value is not { IsInvalid: false } job)
{
return false;
}
try
{
return AssignProcessToJobObject(job, process.Handle);
}
catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or NotSupportedException)
{
// The process is already gone.
return false;
}
}
/// <summary>The job, created once and never closed: closing it would end the processes inside it.</summary>
private static SafeFileHandle? Create()
{
var job = CreateJobObject(IntPtr.Zero, null);
if (job.IsInvalid)
{
job.Dispose();
return null;
}
var limits = new ExtendedLimitInformation { BasicLimitInformation = new BasicLimitInformation { LimitFlags = JobObjectLimitKillOnJobClose } };
var size = Marshal.SizeOf<ExtendedLimitInformation>();
var buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(limits, buffer, fDeleteOld: false);
if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, buffer, (uint)size))
{
job.Dispose();
return null;
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
return job;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateJobObject(IntPtr attributes, string? name);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetInformationJobObject(SafeFileHandle job, int infoClass, IntPtr info, uint length);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AssignProcessToJobObject(SafeFileHandle job, IntPtr process);
[StructLayout(LayoutKind.Sequential)]
private struct BasicLimitInformation
{
public long PerProcessUserTimeLimit;
public long PerJobUserTimeLimit;
public uint LimitFlags;
public UIntPtr MinimumWorkingSetSize;
public UIntPtr MaximumWorkingSetSize;
public uint ActiveProcessLimit;
public UIntPtr Affinity;
public uint PriorityClass;
public uint SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
private struct IoCounters
{
public ulong ReadOperationCount;
public ulong WriteOperationCount;
public ulong OtherOperationCount;
public ulong ReadTransferCount;
public ulong WriteTransferCount;
public ulong OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
private struct ExtendedLimitInformation
{
public BasicLimitInformation BasicLimitInformation;
public IoCounters IoInfo;
public UIntPtr ProcessMemoryLimit;
public UIntPtr JobMemoryLimit;
public UIntPtr PeakProcessMemoryUsed;
public UIntPtr PeakJobMemoryUsed;
}
}
+5 -11
View File
@@ -6,7 +6,9 @@ namespace Febe.Desktop;
/// <summary>
/// One Febe at a time for a Data folder (spec §12): a named mutex in the session namespace, and a named pipe (current
/// user only) through which a second launch asks the first to show its window, then exits.
/// user only) through which a second launch asks the first to show its window, then exits. What counts is that the
/// mutex exists, not which thread owns it: a guard can be taken on any thread (the move of the Data folder takes the
/// guard of the new folder on a worker thread) and lives until it is disposed or the process ends.
/// </summary>
internal sealed class SingleInstanceGuard : IDisposable
{
@@ -24,7 +26,8 @@ internal sealed class SingleInstanceGuard : IDisposable
/// <summary>The guard of the first instance, or null when another Febe already runs on this Data folder.</summary>
public static SingleInstanceGuard? TryAcquire(string dataFolder)
{
var mutex = new Mutex(initiallyOwned: true, InstanceIdentity.MutexName(dataFolder), out var created);
// Not owned: ownership belongs to a thread, while the guard belongs to the process.
var mutex = new Mutex(initiallyOwned: false, InstanceIdentity.MutexName(dataFolder), out var created);
if (!created)
{
mutex.Dispose();
@@ -69,15 +72,6 @@ internal sealed class SingleInstanceGuard : IDisposable
{
}
try
{
_mutex.ReleaseMutex();
}
catch (ApplicationException)
{
// Released on another thread already: Windows releases it when the process ends.
}
_mutex.Dispose();
_stop.Dispose();
}
+8 -6
View File
@@ -12,9 +12,11 @@ namespace Febe.Desktop;
/// «Mostra nella cartella» (<c>explorer.exe /select,"…"</c>), addresses in the default browser (shell execute), Windows
/// notifications (balloon tips of the notification-area icon: the alerts of spec §13.3 arrive here through
/// <see cref="NativeShellAlertChannel"/>, and «Invia una prova») and start with the computer
/// (<c>HKCU\…\Run</c>, value <c>Febe</c>). Paths and addresses never come from the page: the web layer resolves them.
/// (<c>HKCU\…\Run</c>, value <c>Febe</c>, or <c>Febe-…</c> with <c>--dati</c> for a Febe started on a Data folder of
/// its own: <paramref name="fixedDataFolder"/>, see <see cref="Autostart"/>). Paths and addresses never come from the
/// page: the web layer resolves them.
/// </summary>
internal sealed class WindowsShell(Dispatcher ui, Func<Window?> owner, Func<TrayIcon?> tray) : INativeShell
internal sealed class WindowsShell(Dispatcher ui, Func<Window?> owner, Func<TrayIcon?> tray, string? fixedDataFolder) : INativeShell
{
public bool CanPickFolder => true;
@@ -85,8 +87,8 @@ internal sealed class WindowsShell(Dispatcher ui, Func<Window?> owner, Func<Tray
public Task<bool> GetAutostartAsync(CancellationToken ct)
{
using var key = Registry.CurrentUser.OpenSubKey(Autostart.RunKey, writable: false);
var value = key?.GetValue(Autostart.ValueName) as string;
return Task.FromResult(Environment.ProcessPath is { } exe && Autostart.PointsTo(value, exe));
var value = key?.GetValue(Autostart.ValueNameFor(fixedDataFolder)) as string;
return Task.FromResult(Environment.ProcessPath is { } exe && Autostart.PointsTo(value, exe, fixedDataFolder));
}
public Task SetAutostartAsync(bool enabled, CancellationToken ct)
@@ -95,11 +97,11 @@ internal sealed class WindowsShell(Dispatcher ui, Func<Window?> owner, Func<Tray
if (enabled)
{
var exe = Environment.ProcessPath ?? throw new InvalidOperationException("Percorso di Febe.exe sconosciuto.");
key.SetValue(Autostart.ValueName, Autostart.Command(exe), RegistryValueKind.String);
key.SetValue(Autostart.ValueNameFor(fixedDataFolder), Autostart.Command(exe, fixedDataFolder), RegistryValueKind.String);
}
else
{
key.DeleteValue(Autostart.ValueName, throwOnMissingValue: false);
key.DeleteValue(Autostart.ValueNameFor(fixedDataFolder), throwOnMissingValue: false);
}
return Task.CompletedTask;
+10 -3
View File
@@ -38,7 +38,8 @@ public static class AccessApi
{
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Secure = context.Request.IsHttps,
// Behind the proxy with HTTPS (FEBE_PROXY_FIDATO) too: the session never travels in clear text.
Secure = RequestScheme.IsHttps(context.Request, options),
Path = "/",
IsEssential = true,
MaxAge = passwords.SessionLifetime,
@@ -54,10 +55,16 @@ public static class AccessApi
}
});
endpoints.MapPost("/api/uscita", (HttpContext context) =>
endpoints.MapPost("/api/uscita", (HttpContext context, FebeWebOptions options) =>
{
context.RequestServices.GetService<PasswordAccess>()?.Logout(context.Request.Cookies[PasswordAccess.CookieName]);
context.Response.Cookies.Delete(PasswordAccess.CookieName, new CookieOptions { Path = "/", SameSite = SameSiteMode.Strict, HttpOnly = true });
context.Response.Cookies.Delete(PasswordAccess.CookieName, new CookieOptions
{
Path = "/",
SameSite = SameSiteMode.Strict,
HttpOnly = true,
Secure = RequestScheme.IsHttps(context.Request, options),
});
return ApiHttp.Message("Sei uscito da Febe.");
});
}
+57
View File
@@ -0,0 +1,57 @@
using Microsoft.AspNetCore.Http;
namespace Febe.Web.Security;
/// <summary>
/// Where the login page goes back after the password (spec §13.1): <c>/accesso?torna=…</c>. Only a page of this
/// interface, never another site. A browser reads <c>//host</c> as an address of another site, and turns <c>/\host</c>
/// into <c>//host</c> as well (a backslash counts as a slash, tabs and new lines are dropped), so the value must be one
/// path that starts with a single slash and holds no backslash, blank or control character. The login page script
/// (<c>js/core/return-path.js</c>) applies the same rule.
/// </summary>
public static class LoginReturn
{
/// <summary>The name of the query parameter of the login page.</summary>
public const string QueryName = "torna";
/// <summary>The longest path accepted (a real page address is much shorter).</summary>
public const int MaxLength = 2048;
/// <summary><paramref name="value"/> when it is a path of this interface; null otherwise.</summary>
public static string? Sanitize(string? value) => IsSafe(value) ? value : null;
/// <summary>True when <paramref name="value"/> can only lead to a page of this interface.</summary>
public static bool IsSafe(string? value)
{
if (string.IsNullOrEmpty(value) || value.Length > MaxLength || value[0] != '/')
{
return false;
}
if (value.Length > 1 && value[1] is '/' or '\\')
{
return false;
}
foreach (var c in value)
{
if (c == '\\' || c <= ' ' || c == '\u007f' || char.IsWhiteSpace(c) || char.IsControl(c))
{
return false;
}
}
return true;
}
/// <summary>The address of the login page that goes back to <paramref name="path"/> (or just the login page).</summary>
public static string LoginAddress(string? path) =>
Sanitize(path) is { } safe ? "/accesso?" + QueryName + "=" + Uri.EscapeDataString(safe) : "/accesso";
/// <summary>True when the request carries a <c>torna</c> that is not a path of this interface.</summary>
public static bool HasUnsafeReturn(HttpRequest request)
{
ArgumentNullException.ThrowIfNull(request);
return request.Query.TryGetValue(QueryName, out var values) && values.Any(v => !IsSafe(v));
}
}
+32
View File
@@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Http;
namespace Febe.Web.Security;
/// <summary>
/// Whether a request reached Febe over HTTPS, for the <c>Secure</c> flag of its cookies (spec §11, §13.1). Febe itself
/// listens on plain HTTP; remote access goes through a proxy with HTTPS in front, which terminates TLS. Only that trusted
/// proxy (<c>FEBE_PROXY_FIDATO=1</c>) can say so, with <c>X-Forwarded-Proto: https</c>: from anyone else the header is
/// ignored.
/// </summary>
public static class RequestScheme
{
/// <summary>True when the browser talked HTTPS: directly, or to the trusted proxy in front of Febe.</summary>
public static bool IsHttps(HttpRequest request, FebeWebOptions options)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(options);
if (request.IsHttps)
{
return true;
}
if (!options.TrustForwardedHost)
{
return false;
}
// The first value is the one the proxy closest to the browser wrote.
var forwarded = request.Headers["X-Forwarded-Proto"].ToString().Split(',')[0].Trim();
return string.Equals(forwarded, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
}
}
+17 -2
View File
@@ -47,6 +47,14 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
return;
}
// The login page with a «torna» that leads out of the interface (a crafted link: «/\host», «//host»): the
// value is dropped before the page even shows, so after the password Febe goes only to its own pages.
if (IsLoginPage(request) && LoginReturn.HasUnsafeReturn(request))
{
response.Redirect("/accesso");
return;
}
switch (options.Access)
{
case AccessMode.Token:
@@ -85,7 +93,7 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
{
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Secure = request.IsHttps,
Secure = RequestScheme.IsHttps(request, options),
Path = "/",
IsEssential = true,
});
@@ -141,12 +149,19 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
}
else
{
context.Response.Redirect("/accesso?torna=" + Uri.EscapeDataString(path));
// Back to this page after the password; a path that would lead out of the interface is not carried.
context.Response.Redirect(LoginReturn.LoginAddress(path));
}
return false;
}
/// <summary>The login page: <c>/accesso</c>, or its file <c>/accesso.html</c> served as it is.</summary>
private static bool IsLoginPage(HttpRequest request) =>
(HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method))
&& (string.Equals(request.Path.Value, "/accesso", StringComparison.OrdinalIgnoreCase)
|| string.Equals(request.Path.Value, "/accesso.html", StringComparison.OrdinalIgnoreCase));
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>
+3 -2
View File
@@ -3,6 +3,7 @@
import { h, fill, brand } from './core/dom.js';
import { loadTexts, t } from './core/text.js';
import { returnAddress } from './core/return-path.js';
async function boot() {
await loadTexts('it');
@@ -31,8 +32,8 @@ async function boot() {
});
const data = await response.json().catch(() => ({}));
if (response.ok && data.ok) {
const back = new URLSearchParams(location.search).get('torna');
location.href = back && back.startsWith('/') && !back.startsWith('//') ? back : '/libreria';
// Back to the page Alberto was opening: only a page of this interface, never another site.
location.href = returnAddress(new URLSearchParams(location.search).get('torna'), location.origin);
return;
}
message.textContent = data.message || t('accesso.sbagliata');
@@ -0,0 +1,24 @@
// Where the login page goes after the password (spec §13.1): the page Alberto was opening («?torna=/account/12»),
// never another site. A link can hide another site in many ways: «//host», «/\host» (a backslash counts as a slash),
// «/%09/host» (tabs and new lines are dropped). The same rule as the server (Febe.Web.Security.LoginReturn): one path
// that starts with a single slash, without backslashes, blanks or control characters; then the address it resolves to
// must still be on this origin, and the page goes to that absolute address (nothing left to read twice).
const SAFE = /^\/(?![\/\\])[^\\\s\u0000-\u001f\u007f-\u009f]*$/;
export const DEFAULT_PAGE = '/libreria';
/** The absolute address to open after the login, on <origin> only; the library when <value> is missing or unsafe. */
export function returnAddress(value, origin) {
const fallback = new URL(DEFAULT_PAGE, origin).href;
if (typeof value !== 'string' || value.length > 2048 || !SAFE.test(value)) {
return fallback;
}
try {
const target = new URL(value, origin);
return target.origin === new URL(origin).origin ? target.href : fallback;
} catch {
return fallback;
}
}