53 lines
6.3 KiB
C#

using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace PlotDirector.Companion.Agent;
public sealed class TrustedInstallation
{
public Guid InstallationId {get;set;}public int AccountId {get;set;}public string AccountName {get;set;}="";public string Site {get;set;}="";public string Credential {get;set;}="";public DateTimeOffset RefreshExpiresUtc {get;set;}public CredentialRotation? Pending {get;set;}
}
public sealed class CredentialRotation
{
public string NextCredential {get;set;}="";public Guid RotationId {get;set;}public Guid ConnectionId {get;set;}
}
public sealed class CompanionPreferences
{
public int Width {get;set;}=410;public int Height {get;set;}=540;public bool CompactLayoutApplied {get;set;}public bool AdvancedMode {get;set;}public bool RememberInDocument {get;set;}public Guid LastManuscript {get;set;}
}
public sealed class CompanionState
{
public int Version {get;set;}=1;public string Server {get;set;}="";public int AccountId {get;set;}public string AccountName {get;set;}="";public TrustedInstallation? Active {get;set;}public List<TrustedInstallation> Revocations {get;set;}=[];public Dictionary<string,int> Bindings {get;set;}=[];public CompanionPreferences Preferences {get;set;}=new();
}
public sealed class CompanionStorageException(string message,Exception? inner=null):IOException(message,inner);
public interface ICompanionStateStore {CompanionState Load();void Save(CompanionState state);}
public interface IStateProtection {byte[] Protect(byte[] clear,byte[] entropy);byte[] Unprotect(byte[] encrypted,byte[] entropy);}
// No plaintext or machine-wide fallback. DPAPI uses the current Windows user; entropy also binds server/account.
public sealed class WindowsUserProtection:IStateProtection
{
[StructLayout(LayoutKind.Sequential)]private struct Blob{public int Size;public IntPtr Data;}
[DllImport("crypt32.dll",EntryPoint="CryptProtectData",ExactSpelling=true,SetLastError=true,CharSet=CharSet.Unicode)]private static extern bool CryptProtectData(ref Blob input,string? description,ref Blob entropy,IntPtr reserved,IntPtr prompt,int flags,out Blob output);
[DllImport("crypt32.dll",EntryPoint="CryptUnprotectData",ExactSpelling=true,SetLastError=true)]private static extern bool CryptUnprotectData(ref Blob input,IntPtr description,ref Blob entropy,IntPtr reserved,IntPtr prompt,int flags,out Blob output);
[DllImport("kernel32.dll")]private static extern IntPtr LocalFree(IntPtr memory);
public byte[] Protect(byte[] clear,byte[] entropy)=>Transform(clear,entropy,true);
public byte[] Unprotect(byte[] encrypted,byte[] entropy)=>Transform(encrypted,entropy,false);
private static byte[] Transform(byte[] bytes,byte[] entropy,bool protect)
{
if(!OperatingSystem.IsWindows())throw new PlatformNotSupportedException("Windows user-protected storage is required.");
var input=new Blob{Size=bytes.Length,Data=Marshal.AllocHGlobal(bytes.Length)};var extra=new Blob{Size=entropy.Length,Data=Marshal.AllocHGlobal(entropy.Length)};Blob output=default;
try{Marshal.Copy(bytes,0,input.Data,bytes.Length);Marshal.Copy(entropy,0,extra.Data,entropy.Length);var ok=protect?CryptProtectData(ref input,"PlotDirector Companion",ref extra,IntPtr.Zero,IntPtr.Zero,1,out output):CryptUnprotectData(ref input,IntPtr.Zero,ref extra,IntPtr.Zero,IntPtr.Zero,1,out output);if(!ok)throw new CryptographicException("Windows could not read or write this user's protected Companion approval.",new Win32Exception(Marshal.GetLastWin32Error()));if(output.Size<=0||output.Size>2*1024*1024)throw new CryptographicException("Invalid protected settings size.");var result=new byte[output.Size];Marshal.Copy(output.Data,result,0,result.Length);return result;}
finally{if(input.Data!=IntPtr.Zero){Marshal.Copy(new byte[input.Size],0,input.Data,input.Size);Marshal.FreeHGlobal(input.Data);}if(extra.Data!=IntPtr.Zero)Marshal.FreeHGlobal(extra.Data);if(output.Data!=IntPtr.Zero){Marshal.Copy(new byte[output.Size],0,output.Data,output.Size);LocalFree(output.Data);}}
}
}
public sealed class ProtectedCompanionStateStore(string path,IStateProtection protection):ICompanionStateStore,IDisposable
{
private sealed record Envelope(int Version,string Site,int Account,byte[] Protected);
private readonly object gate=new();private FileStream? owner;
private void Own(){if(owner!=null)return;Directory.CreateDirectory(Path.GetDirectoryName(path)!);owner=new(path+".lock",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);}
private static byte[] Entropy(string site,int account)=>SHA256.HashData(Encoding.UTF8.GetBytes("PlotDirector.Companion.State.v1|"+site+"|"+account));
public CompanionState Load(){lock(gate){Own();if(!File.Exists(path))return new();if(new FileInfo(path).Length>2*1024*1024)throw new CryptographicException("Invalid Companion settings size.");var envelope=JsonSerializer.Deserialize<Envelope>(File.ReadAllBytes(path))??throw new CryptographicException("Invalid protected settings.");if(envelope.Version!=1||envelope.Protected==null)throw new CryptographicException("Unsupported protected settings.");var clear=protection.Unprotect(envelope.Protected,Entropy(envelope.Site,envelope.Account));try{var state=JsonSerializer.Deserialize<CompanionState>(clear)??throw new CryptographicException("Invalid protected settings.");if(state.Version!=1||state.Server!=envelope.Site||state.AccountId!=envelope.Account||state.Revocations.Count>16||state.Bindings.Count>2048)throw new CryptographicException("Settings scope mismatch.");return state;}finally{CryptographicOperations.ZeroMemory(clear);}}}
public void Save(CompanionState state){lock(gate){Own();var clear=JsonSerializer.SerializeToUtf8Bytes(state);try{if(clear.Length>1024*1024)throw new IOException("Companion settings capacity exceeded.");var bytes=JsonSerializer.SerializeToUtf8Bytes(new Envelope(1,state.Server,state.AccountId,protection.Protect(clear,Entropy(state.Server,state.AccountId))));var temp=path+"."+Guid.NewGuid().ToString("N")+".tmp";try{using(var file=new FileStream(temp,FileMode.CreateNew,FileAccess.Write,FileShare.None,4096,FileOptions.WriteThrough)){file.Write(bytes);file.Flush(true);}File.Move(temp,path,true);}finally{if(File.Exists(temp))File.Delete(temp);}}finally{CryptographicOperations.ZeroMemory(clear);}}}
public void Dispose(){lock(gate){owner?.Dispose();owner=null;}}
}