Files
2026-10-12 20:10:00 -04:00

83 lines
4.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Amnesia.Services;
public sealed record Account(string Username, string Salt, string Hash);
public sealed record Session(string Username, string AccountHash, DateTime ExpiresUtc);
public sealed class Preferences
{
public string LauncherPath { get; set; } = "";
public bool MinimizeOnLaunch { get; set; } = true;
public bool ReduceMotion { get; set; }
public double Opacity { get; set; } = 1;
}
// Local launcher accounts only. This is not Minecraft or Microsoft authentication.
public sealed class LocalStore
{
public static readonly string Root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Amnesia");
private static string FilePath(string name) => Path.Combine(Root, name);
private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("Amnesia.LocalSession.v1");
public LocalStore() => Directory.CreateDirectory(Root);
private static void Write(string name, byte[] bytes)
{
string target = FilePath(name), temp = target + "." + Guid.NewGuid().ToString("N") + ".tmp";
try { File.WriteAllBytes(temp, bytes); File.Move(temp, target, true); }
finally { if (File.Exists(temp)) File.Delete(temp); }
}
private List<Account> Accounts() => File.Exists(FilePath("accounts.json"))
? JsonSerializer.Deserialize<List<Account>>(File.ReadAllText(FilePath("accounts.json"))) ?? throw new InvalidDataException("Account data could not be read.")
: new();
public Account Register(string username, string password)
{
if (!Regex.IsMatch(username, @"^[a-zA-Z0-9_]{3,24}$")) throw new ArgumentException("Use 3–24 letters, numbers, or underscores for your username.");
if (password.Length < 8 || password.Length > 128) throw new ArgumentException("Use a password between 8 and 128 characters.");
var accounts = Accounts();
if (accounts.Any(a => a.Username.Equals(username, StringComparison.OrdinalIgnoreCase))) throw new ArgumentException("That username already exists on this PC.");
byte[] salt = RandomNumberGenerator.GetBytes(32);
var account = new Account(username, Convert.ToBase64String(salt), Convert.ToBase64String(Derive(password, salt)));
accounts.Add(account);
Write("accounts.json", JsonSerializer.SerializeToUtf8Bytes(accounts));
return account;
}
private static byte[] Derive(string password, byte[] salt) => Rfc2898DeriveBytes.Pbkdf2(password, salt, 600_000, HashAlgorithmName.SHA256, 32);
public Account Login(string username, string password)
{
var account = Accounts().FirstOrDefault(a => a.Username.Equals(username, StringComparison.OrdinalIgnoreCase));
byte[] salt = account is null ? new byte[32] : Convert.FromBase64String(account.Salt);
byte[] hash = Derive(password, salt);
if (account is null || !CryptographicOperations.FixedTimeEquals(hash, Convert.FromBase64String(account.Hash)))
throw new ArgumentException("The username or password is incorrect.");
return account;
}
public void Remember(Account account)
{
var session = new Session(account.Username, account.Hash, DateTime.UtcNow.AddDays(30));
Write("session.bin", ProtectedData.Protect(JsonSerializer.SerializeToUtf8Bytes(session), Entropy, DataProtectionScope.CurrentUser));
}
public Account? Restore()
{
if (!File.Exists(FilePath("session.bin"))) return null;
try
{
var bytes = ProtectedData.Unprotect(File.ReadAllBytes(FilePath("session.bin")), Entropy, DataProtectionScope.CurrentUser);
var s = JsonSerializer.Deserialize<Session>(bytes);
if (s is null || s.ExpiresUtc <= DateTime.UtcNow) { Forget(); return null; }
return Accounts().FirstOrDefault(a => a.Username == s.Username && a.Hash == s.AccountHash);
}
catch (Exception e) when (e is CryptographicException or JsonException or FormatException) { Forget(); return null; }
}
public void Forget() { if (File.Exists(FilePath("session.bin"))) File.Delete(FilePath("session.bin")); }
public Preferences ReadPreferences()
{
if (!File.Exists(FilePath("preferences.json"))) return new();
var p = JsonSerializer.Deserialize<Preferences>(File.ReadAllText(FilePath("preferences.json"))) ?? new();
p.Opacity = double.IsFinite(p.Opacity) ? Math.Clamp(p.Opacity, .85, 1) : 1;
return p;
}
public void SavePreferences(Preferences p) => Write("preferences.json", JsonSerializer.SerializeToUtf8Bytes(p));
}