namespace Febe.Core.Security;
///
/// Encrypts the saved session before it touches the disk (issue #36, S4, spec ยง13.2): DPAPI for the current user on
/// Windows (in Febe.Desktop, the only project with ProtectedData and no package), AES-256-GCM with a key of its
/// own in Docker (). The text it protects never reaches a log or an exception.
///
public interface ISessionProtector
{
/// The scheme, for the log: dpapi or aes-gcm.
string Scheme { get; }
/// The encrypted form of , starting with 's header.
byte[] Protect(ReadOnlySpan plain);
/// The plain text of .
/// Another key or user, a damaged file, another scheme or format.
byte[] Unprotect(ReadOnlySpan blob);
}
///
/// The header every protected session starts with: FEBS, the format version, the scheme. It says only what the
/// file is, never what it holds; the AES scheme authenticates it.
///
public static class SessionBlob
{
/// The scheme byte of DPAPI.
public const byte Dpapi = 1;
/// The scheme byte of AES-256-GCM.
public const byte AesGcm = 2;
/// The format version.
public const byte Version = 1;
/// The length of the header.
public const int HeaderLength = 6;
/// The header for .
public static byte[] Header(byte scheme) => [(byte)'F', (byte)'E', (byte)'B', (byte)'S', Version, scheme];
/// True when starts with the header of .
public static bool HasHeader(ReadOnlySpan blob, byte scheme) =>
blob.Length >= HeaderLength && blob[..HeaderLength].SequenceEqual(Header(scheme));
}
///
/// The saved session cannot be read: another key or user, a damaged file, another format. Its message is fixed and
/// carries no inner text: Febe treats it as no session and asks for a new login.
///
public sealed class SessionUnreadableException : Exception
{
/// The fixed message.
public const string Text = "La sessione salvata non si legge (cifratura o formato): serve un nuovo accesso.";
public SessionUnreadableException()
: base(Text)
{
}
public SessionUnreadableException(string message)
: base(message)
{
}
public SessionUnreadableException(string message, Exception innerException)
: base(message, innerException)
{
}
}