using System.Security.Cryptography;
using System.Text.Json;
using JiDangJia.Views;
namespace JiDangJia.Services;
public static class AppPrivacy
{
private static int depth;
public static void Enter(){depth++;Apply();}
public static void Leave(){depth=Math.Max(0,depth-1);Apply();}
public static void Apply()
{
#if ANDROID
var window=Platform.CurrentActivity?.Window;if(window is null)return;
if(depth>0||AppLock.Enabled||AuthClient.Current.Locked)window.AddFlags(Android.Views.WindowManagerFlags.Secure);else window.ClearFlags(Android.Views.WindowManagerFlags.Secure);
#endif
}
}
public static class AppLock
{
private sealed record LockConfig(string Salt,string Hash,bool Biometric,int Attempts=0,long Until=0,int PinLength=0);
private static string Key(string account)=>"app-unlock-"+account;
private static LockConfig? current;private static string owner="";
private static Page? covered;private static Action? after;
public static bool Enabled=>owner==AuthClient.Current.AccountId&¤t is not null;
public static bool Fingerprint=>Enabled&¤t!.Biometric;
public static bool UsesPin=>Enabled&¤t!.PinLength==6;
public static void Abandon(){covered=null;after=null;current=null;owner="";AuthClient.Current.Locked=false;BiometricUnlock.Cancel();}
public static async Task Load()
{var account=AuthClient.Current.AccountId;var json=await SecureStorage.Default.GetAsync(Key(account));if(account!=AuthClient.Current.AccountId)throw new OperationCanceledException("账户已切换");owner=account;current=json is null?null:JsonSerializer.Deserialize<LockConfig>(json);AppPrivacy.Apply();}
private static byte[] Hash(string password,byte[] salt)=>Rfc2898DeriveBytes.Pbkdf2(password,salt,210000,HashAlgorithmName.SHA256,32);
private static void Scope(){if(owner.Length==0||owner!=AuthClient.Current.AccountId)throw new InvalidOperationException("账户已切换,请重新设置");}
public static async Task Set(string password,string again,bool biometric)
{
Scope();if(password.Length!=6||password.Any(c=>c is <'0' or >'9')||password!=again)throw new ArgumentException("请设置相同的 6 位数字解锁密码");
if(biometric&&!await BiometricUnlock.Authenticate(owner))throw new InvalidOperationException("未完成设备指纹验证,请重试或先仅开启数字密码");Scope();var salt=RandomNumberGenerator.GetBytes(16);current=new(Convert.ToBase64String(salt),Convert.ToBase64String(Hash(password,salt)),biometric,PinLength:6);await Save();AppPrivacy.Apply();
}
private static Task Save(){Scope();return SecureStorage.Default.SetAsync(Key(owner),JsonSerializer.Serialize(current));}
public static async Task<bool> Check(string password)
{
Scope();if(current is null)return true;var config=current;long now=DateTimeOffset.UtcNow.ToUnixTimeSeconds();if(now<config.Until)throw new InvalidOperationException($"请在 {config.Until-now} 秒后重试");
bool valid=CryptographicOperations.FixedTimeEquals(Hash(password,Convert.FromBase64String(config.Salt)),Convert.FromBase64String(config.Hash));Scope();current=config with{Attempts=valid?0:config.Attempts+1,Until=valid?0:config.Attempts+1>=5?now+Math.Min(900,30*(config.Attempts+1-4)):0};await Save();return valid;
}
public static async Task Disable(string password){if(!await Check(password))throw new ArgumentException("解锁密码不正确");Scope();SecureStorage.Default.Remove(Key(owner));current=null;BiometricUnlock.Remove(owner);AppPrivacy.Apply();}
public static void Cover(Window window,Action? completed=null)
{
if(!Enabled||AuthClient.Current.Locked)return;AuthClient.Current.Locked=true;if((window.Page as NavigationPage)?.RootPage is MainPage root)root.Suspend();
covered=completed is null?window.Page:null;after=completed;window.Page=new NavigationPage(new UnlockPage());AppPrivacy.Apply();
}
public static async Task Unlock(string? password,bool biometric)
{
Scope();if(biometric){if(!Fingerprint||!await BiometricUnlock.Authenticate(owner))throw new InvalidOperationException("指纹未验证成功,可使用解锁密码");}
else if(!await Check(password??""))throw new ArgumentException("解锁密码不正确");Scope();AuthClient.Current.Locked=false;var window=Application.Current!.Windows[0];var previous=covered;var callback=after;covered=null;after=null;
if(previous is not null){window.Page=previous;if((previous as NavigationPage)?.RootPage is MainPage root)root.Resume();}else callback?.Invoke();AppPrivacy.Apply();
}
public static async Task Forgot(string password)
{Scope();await AuthClient.Current.VerifyPassword(password);Scope();SecureStorage.Default.Remove(Key(owner));BiometricUnlock.Remove(owner);current=null;AuthClient.Current.Locked=false;var window=Application.Current!.Windows[0];var previous=covered;var callback=after;covered=null;after=null;if(previous is not null){window.Page=previous;if((previous as NavigationPage)?.RootPage is MainPage root)root.Resume();}else callback?.Invoke();AppPrivacy.Apply();}
}
public static partial class BiometricUnlock
{
#if !ANDROID
public static Task<bool> Authenticate(string account)=>Task.FromResult(false);
public static void Remove(string account){}
public static void Cancel(){}
#endif
}
public static class AccountDataClear
{
public static bool InProgress {get;private set;}
private static string Receipt(string account)=>Path.Combine(FileSystem.AppDataDirectory,"wipe-"+account+".json");
public static string CacheFile(string name)
{var directory=Path.Combine(FileSystem.CacheDirectory,"accounts",AuthClient.Current.AccountId);Directory.CreateDirectory(directory);return Path.Combine(directory,name);}
public static void Pending()
{var account=AuthClient.Current.AccountId;if(File.Exists(Receipt(account)))Finish(account);}
public static async Task Clear(string password,string again,Action? retire=null)
{
string account=AuthClient.Current.AccountId;var receipt=new{accountId=account,clientId=Guid.NewGuid().ToString("N")};
using var result=await AuthClient.Current.AccountRequest<JsonDocument>("/data-clear",new{password,passwordAgain=again,clientId=receipt.clientId});
if(account!=AuthClient.Current.AccountId||result.RootElement.GetProperty("accountId").GetString()!=account)throw new OperationCanceledException("账户已切换");
InProgress=true;File.WriteAllText(Receipt(account),JsonSerializer.Serialize(receipt));retire?.Invoke();if((Application.Current!.Windows[0].Page as NavigationPage)?.RootPage is MainPage root)root.Suspend();Finish(account);InProgress=false;await LoginPage.EnterApp();
}
private static void DeleteAccountFolder(string root,string account)
{var parent=Path.GetFullPath(root);var target=Path.GetFullPath(Path.Combine(parent,account));if(!target.StartsWith(parent+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase)||!System.Text.RegularExpressions.Regex.IsMatch(account,"^[a-f0-9]{32}$"))throw new InvalidOperationException("账户数据路径无效");if(Directory.Exists(target))Directory.Delete(target,true);}
private static void Finish(string account)
{
AppNotifications.Stop(true);
DeleteAccountFolder(Path.Combine(FileSystem.AppDataDirectory,"accounts"),account);DeleteAccountFolder(Path.Combine(FileSystem.CacheDirectory,"accounts"),account);
foreach(var path in Directory.GetFiles(FileSystem.AppDataDirectory,"social-draft-"+account+"-*.json"))File.Delete(path);
Preferences.Default.Remove("community-city-"+account);Preferences.Default.Remove("community-city-"+account+"-address");
var quotes=Path.Combine(FileSystem.AppDataDirectory,"quote-cache.json");if(File.Exists(quotes))File.Delete(quotes);File.Delete(Receipt(account));
}
}
using System.Security.Cryptography;
using System.Text.Json;
using JiDangJia.Views;
namespace JiDangJia.Services;
public static class AppPrivacy
{
private static int depth;
public static void Enter(){depth++;Apply();}
public static void Leave(){depth=Math.Max(0,depth-1);Apply();}
public static void Apply()
{
#if ANDROID
var window=Platform.CurrentActivity?.Window;if(window is null)return;
if(depth>0||AppLock.Enabled||AuthClient.Current.Locked)window.AddFlags(Android.Views.WindowManagerFlags.Secure);else window.ClearFlags(Android.Views.WindowManagerFlags.Secure);
#endif
}
}
public static class AppLock
{
private sealed record LockConfig(string Salt,string Hash,bool Biometric,int Attempts=0,long Until=0,int PinLength=0);
private static string Key(string account)=>"app-unlock-"+account;
private static LockConfig? current;private static string owner="";
private static Page? covered;private static Action? after;
public static bool Enabled=>owner==AuthClient.Current.AccountId&¤t is not null;
public static bool Fingerprint=>Enabled&¤t!.Biometric;
public static bool UsesPin=>Enabled&¤t!.PinLength==6;
public static void Abandon(){covered=null;after=null;current=null;owner="";AuthClient.Current.Locked=false;BiometricUnlock.Cancel();}
public static async Task Load()
{var account=AuthClient.Current.AccountId;var json=await SecureStorage.Default.GetAsync(Key(account));if(account!=AuthClient.Current.AccountId)throw new OperationCanceledException("账户已切换");owner=account;current=json is null?null:JsonSerializer.Deserialize<LockConfig>(json);AppPrivacy.Apply();}
private static byte[] Hash(string password,byte[] salt)=>Rfc2898DeriveBytes.Pbkdf2(password,salt,210000,HashAlgorithmName.SHA256,32);
private static void Scope(){if(owner.Length==0||owner!=AuthClient.Current.AccountId)throw new InvalidOperationException("账户已切换,请重新设置");}
public static async Task Set(string password,string again,bool biometric)
{
Scope();if(password.Length!=6||password.Any(c=>c is <'0' or >'9')||password!=again)throw new ArgumentException("请设置相同的 6 位数字解锁密码");
if(biometric&&!await BiometricUnlock.Authenticate(owner))throw new InvalidOperationException("未完成设备指纹验证,请重试或先仅开启数字密码");Scope();var salt=RandomNumberGenerator.GetBytes(16);current=new(Convert.ToBase64String(salt),Convert.ToBase64String(Hash(password,salt)),biometric,PinLength:6);await Save();AppPrivacy.Apply();
}
private static Task Save(){Scope();return SecureStorage.Default.SetAsync(Key(owner),JsonSerializer.Serialize(current));}
public static async Task<bool> Check(string password)
{
Scope();if(current is null)return true;var config=current;long now=DateTimeOffset.UtcNow.ToUnixTimeSeconds();if(now<config.Until)throw new InvalidOperationException($"请在 {config.Until-now} 秒后重试");
bool valid=CryptographicOperations.FixedTimeEquals(Hash(password,Convert.FromBase64String(config.Salt)),Convert.FromBase64String(config.Hash));Scope();current=config with{Attempts=valid?0:config.Attempts+1,Until=valid?0:config.Attempts+1>=5?now+Math.Min(900,30*(config.Attempts+1-4)):0};await Save();return valid;
}
public static async Task Disable(string password){if(!await Check(password))throw new ArgumentException("解锁密码不正确");Scope();SecureStorage.Default.Remove(Key(owner));current=null;BiometricUnlock.Remove(owner);AppPrivacy.Apply();}
public static void Cover(Window window,Action? completed=null)
{
if(!Enabled||AuthClient.Current.Locked)return;AuthClient.Current.Locked=true;if((window.Page as NavigationPage)?.RootPage is MainPage root)root.Suspend();
covered=completed is null?window.Page:null;after=completed;window.Page=new NavigationPage(new UnlockPage());AppPrivacy.Apply();
}
public static async Task Unlock(string? password,bool biometric)
{
Scope();if(biometric){if(!Fingerprint||!await BiometricUnlock.Authenticate(owner))throw new InvalidOperationException("指纹未验证成功,可使用解锁密码");}
else if(!await Check(password??""))throw new ArgumentException("解锁密码不正确");Scope();AuthClient.Current.Locked=false;var window=Application.Current!.Windows[0];var previous=covered;var callback=after;covered=null;after=null;
if(previous is not null){window.Page=previous;if((previous as NavigationPage)?.RootPage is MainPage root)root.Resume();}else callback?.Invoke();AppPrivacy.Apply();
}
public static async Task Forgot(string password)
{Scope();await AuthClient.Current.VerifyPassword(password);Scope();SecureStorage.Default.Remove(Key(owner));BiometricUnlock.Remove(owner);current=null;AuthClient.Current.Locked=false;var window=Application.Current!.Windows[0];var previous=covered;var callback=after;covered=null;after=null;if(previous is not null){window.Page=previous;if((previous as NavigationPage)?.RootPage is MainPage root)root.Resume();}else callback?.Invoke();AppPrivacy.Apply();}
}
public static partial class BiometricUnlock
{
#if !ANDROID
public static Task<bool> Authenticate(string account)=>Task.FromResult(false);
public static void Remove(string account){}
public static void Cancel(){}
#endif
}
public static class AccountDataClear
{
public static bool InProgress {get;private set;}
private static string Receipt(string account)=>Path.Combine(FileSystem.AppDataDirectory,"wipe-"+account+".json");
public static string CacheFile(string name)
{var directory=Path.Combine(FileSystem.CacheDirectory,"accounts",AuthClient.Current.AccountId);Directory.CreateDirectory(directory);return Path.Combine(directory,name);}
public static void Pending()
{var account=AuthClient.Current.AccountId;if(File.Exists(Receipt(account)))Finish(account);}
public static async Task Clear(string password,string again,Action? retire=null)
{
string account=AuthClient.Current.AccountId;var receipt=new{accountId=account,clientId=Guid.NewGuid().ToString("N")};
using var result=await AuthClient.Current.AccountRequest<JsonDocument>("/data-clear",new{password,passwordAgain=again,clientId=receipt.clientId});
if(account!=AuthClient.Current.AccountId||result.RootElement.GetProperty("accountId").GetString()!=account)throw new OperationCanceledException("账户已切换");
InProgress=true;File.WriteAllText(Receipt(account),JsonSerializer.Serialize(receipt));retire?.Invoke();if((Application.Current!.Windows[0].Page as NavigationPage)?.RootPage is MainPage root)root.Suspend();Finish(account);InProgress=false;await LoginPage.EnterApp();
}
private static void DeleteAccountFolder(string root,string account)
{var parent=Path.GetFullPath(root);var target=Path.GetFullPath(Path.Combine(parent,account));if(!target.StartsWith(parent+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase)||!System.Text.RegularExpressions.Regex.IsMatch(account,"^[a-f0-9]{32}$"))throw new InvalidOperationException("账户数据路径无效");if(Directory.Exists(target))Directory.Delete(target,true);}
private static void Finish(string account)
{
AppNotifications.Stop(true);
DeleteAccountFolder(Path.Combine(FileSystem.AppDataDirectory,"accounts"),account);DeleteAccountFolder(Path.Combine(FileSystem.CacheDirectory,"accounts"),account);
foreach(var path in Directory.GetFiles(FileSystem.AppDataDirectory,"social-draft-"+account+"-*.json"))File.Delete(path);
Preferences.Default.Remove("community-city-"+account);Preferences.Default.Remove("community-city-"+account+"-address");
var quotes=Path.Combine(FileSystem.AppDataDirectory,"quote-cache.json");if(File.Exists(quotes))File.Delete(quotes);File.Delete(Receipt(account));
}
}