using System.Net; using System.Net.Http.Json; using System.Security.Cryptography; using System.Text.Json; namespace PlotDirector.Companion.Agent; public sealed partial class CloudGateway { private readonly ICompanionStateStore? storage; private readonly TimeProvider clock; private CompanionState saved=new(); private readonly Guid connectionId=Guid.NewGuid(); private readonly SemaphoreSlim renewal=new(1,1),disk=new(1,1); private readonly CancellationTokenSource lifetime=new(); private DateTimeOffset retryAfter;private int retryFailures;private bool disposed;private bool stateLoaded=true,storageUnavailable;private long credentialVersion,durableCredentialVersion; private DateTimeOffset Now=>clock.GetUtcNow(); private DateTimeOffset accessExpires;private DateTimeOffset revocationAfter; public CompanionPreferences Preferences {get{lock(gate)return new(){AdvancedMode=saved.Preferences.AdvancedMode,CompactLayoutApplied=saved.Preferences.CompactLayoutApplied,Width=saved.Preferences.Width,Height=saved.Preferences.Height,RememberInDocument=saved.Preferences.RememberInDocument,LastManuscript=saved.Preferences.LastManuscript};}} public void SavePreferences(CompanionPreferences preferences){lock(gate)saved.Preferences=preferences;_ = PersistSafely();} private static string BindingKey(string site,int account,Guid manuscript)=>$"{site}|{account}|{manuscript:D}"; public void ForgetBinding(Guid manuscript,Guid expectedContext){lock(gate){if(authenticationContext==expectedContext&&saved.Active!=null)saved.Bindings.Remove(BindingKey(saved.Active.Site,saved.Active.AccountId,manuscript));}_=PersistSafely();} public void RememberBinding(Guid manuscript,int book,Guid expectedContext=default){lock(gate){if(saved.Active==null)return;if((expectedContext!=Guid.Empty&&expectedContext!=authenticationContext)||!books.Any(b=>b.BookId==book))throw new InvalidOperationException("Account or book access changed; select the book again.");if(saved.Bindings.Count>=2048&&!saved.Bindings.ContainsKey(BindingKey(saved.Active.Site,saved.Active.AccountId,manuscript)))throw new InvalidOperationException("Saved manuscript association limit reached.");saved.Bindings[BindingKey(saved.Active.Site,saved.Active.AccountId,manuscript)]=book;}_=PersistSafely();} public int? RestoreBinding(Guid manuscript){lock(gate){var active=saved.Active;if(active==null||health.Authentication!="verified"||health.State!="Connected"||checking!=0||token==null)return null;return saved.Bindings.TryGetValue(BindingKey(active.Site,active.AccountId,manuscript),out var book)&&books.Any(b=>b.BookId==book)?book:null;}} private async Task PersistSafely(){try{await FlushSettingsAsync();}catch(Exception e)when(StorageFailure(e)){lock(gate){health.State="Action required";health.Explanation="Windows could not save Companion settings securely. Check access to your user profile before restarting.";}}} public async Task FlushSettingsAsync() { if(storage==null)return;await disk.WaitAsync();try{CompanionState snapshot;long version;lock(gate){if(!stateLoaded)throw new CompanionStorageException("Protected settings have not been loaded safely.");version=credentialVersion;saved.Version=saved.WritingObservations.Count>0?2:1;snapshot=JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(saved))!;}try{await Task.Run(()=>storage.Save(snapshot));}catch(Exception e)when(StorageFailure(e)){throw new CompanionStorageException("Companion settings could not be saved securely.",e);}lock(gate)if(version==credentialVersion)durableCredentialVersion=version;}finally{disk.Release();} } private static bool StorageFailure(Exception e)=>e is IOException or UnauthorizedAccessException or CryptographicException or JsonException or PlatformNotSupportedException; private void RestoreState() { if(storage==null)return; try{saved=storage.Load();stateLoaded=true;storageUnavailable=false;if(!string.IsNullOrEmpty(saved.Server))origin=ValidateOrigin(saved.Server);if(saved.Active!=null){if(ValidateOrigin(saved.Active.Site)!=origin||saved.Active.AccountId!=saved.AccountId||saved.Active.InstallationId==Guid.Empty||saved.Active.Credential.Length!=64)throw new CryptographicException("Settings scope invalid.");health.State="Reconnecting";health.Authentication="renewing";state="Restoring approved installation…";health.AccountName=saved.Active.AccountName;}else{health.State="Action required";state="Sign in to approve this installation.";}} catch(Exception e)when(StorageFailure(e)||e is ArgumentException){stateLoaded=false;storageUnavailable=e is IOException or UnauthorizedAccessException;health.State="Action required";health.Authentication="unavailable";state="Stored approval is unavailable. Check the Windows user/profile or explicitly sign in again.";health.Explanation=state;} } public async Task RunConnectionLoop(CancellationToken cancellation) { using var stop=CancellationTokenSource.CreateLinkedTokenSource(cancellation,lifetime.Token); try{while(!stop.IsCancellationRequested){try{await DrainRevocations();bool approved;lock(gate)approved=saved.Active!=null;if(approved&&Now>=retryAfter){await EnsureAccess(authenticationContext);if(health.State!="Connected"||Now.UtcDateTime>=nextCheck)await CheckConnection();else if(health.State=="Connected"&&Now.UtcDateTime-health.VerifiedUtc>=TimeSpan.FromSeconds(25)){var context=authenticationContext;var beat=await Post("api/native-companion/heartbeat",new{},context);await ObserveCatalog(beat.CatalogVersion,context);}if(health.State=="Connected")_ = DrainWritingObservations();}}catch(Exception e)when(AuthFailure(e)){ConnectionFailure(e);}await Task.Delay(TimeSpan.FromSeconds(2),stop.Token);}} catch(OperationCanceledException)when(stop.IsCancellationRequested){} } public async Task ReconnectAsync(){if(storageUnavailable)RestoreState();lock(gate){retryAfter=DateTimeOffset.MinValue;nextCheck=DateTime.MinValue;}try{await EnsureAccess(authenticationContext);await CheckConnection();}catch(Exception e)when(AuthFailure(e)){ConnectionFailure(e);}} private static bool AuthFailure(Exception e)=>e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException or CryptographicException or UnauthorizedAccessException; private void ConnectionFailure(Exception error){if(error is CompanionStorageException or CryptographicException){lock(gate){health.State="Action required";health.Explanation="Windows cannot save or read protected Companion settings. Check your user profile; approval will not be discarded.";retryAfter=Now.AddMinutes(1);}}else TransientFailure();} private void TransientFailure(){lock(gate){if(disposed||saved.Active==null)return;health.Server="offline";health.State="Reconnecting";health.Explanation="Connection interrupted. Companion will reconnect automatically; no manuscript will be uploaded.";state="Reconnecting automatically…";retryAfter=Now.AddSeconds(Math.Min(60,Math.Pow(2,Math.Min(++retryFailures,6)))+Random.Shared.NextDouble());}} private void InvalidateAccess(Guid context) { lock(gate){if(context!=authenticationContext)return;token=null;if(saved.Active!=null){health.Authentication="renewing";health.State="Reconnecting";retryAfter=DateTimeOffset.MinValue;state="Renewing connection automatically…";}else{authenticationContext=Guid.NewGuid();books=[];health.Authentication="expired";health.State="Action required";state="Sign in required.";}} } private async Task EnsureAccess(Guid context) { if(storage==null)return; await renewal.WaitAsync(lifetime.Token);try{ while(true){bool dirty;lock(gate)dirty=credentialVersion!=durableCredentialVersion;if(dirty)await FlushSettingsAsync();TrustedInstallation active;Guid expected;CredentialRotation pending; lock(gate){if(disposed||context!=authenticationContext)throw new InvalidOperationException("Connection/account changed.");if(token!=null&&accessExpires>Now.AddMinutes(2))return;if(saved.Active==null)throw new InvalidOperationException("Sign in to approve this installation.");if(Now CredentialRequest(string action,TrustedInstallation active) { var site=ValidateOrigin(active.Site);using var stop=CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);stop.CancelAfter(TimeSpan.FromSeconds(15)); using var response=await http.PostAsJsonAsync(new Uri(site,"api/native-companion/"+action),new{active.InstallationId,credential=active.Credential,nextCredential=active.Pending?.NextCredential??"",rotationId=active.Pending?.RotationId??Guid.Empty,connectionId=active.Pending?.ConnectionId??connectionId},Json,stop.Token); if(action=="revoke")return(response.StatusCode,null);if(response.StatusCode==HttpStatusCode.Unauthorized)return(response.StatusCode,null);response.EnsureSuccessStatusCode();await using var stream=await response.Content.ReadAsStreamAsync(stop.Token);using var buffer=new MemoryStream();var bytes=new byte[4096];int size;while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>65536)throw new InvalidDataException("Invalid credential response size.");buffer.Write(bytes,0,size);}buffer.Position=0;return(response.StatusCode,await JsonSerializer.DeserializeAsync(buffer,Json,stop.Token)); } private async Task DrainRevocations() { TrustedInstallation[] pending;lock(gate){if(Now=200 and <300){lock(gate){saved.Revocations.Remove(item);if(saved.Revocations.Count==0&&saved.Active==null&&health.Authentication=="signed-out"){state="Signed out. Sign in to approve this installation again.";health.Explanation=state;}}await FlushSettingsAsync();}}catch(Exception e)when(AuthFailure(e)){return;}} } public async Task SignOutAsync() { DisconnectPresence();lock(gate){pairing?.Cancel();pairing=null;if(saved.Active!=null){if(saved.Revocations.Count>=16)throw new InvalidOperationException("Connect to finish pending sign-outs before changing accounts.");saved.Revocations.Add(saved.Active);saved.Active=null;credentialVersion++;}authenticationContext=Guid.NewGuid();token=null;books=[];state="Signed out. Sign in to approve this installation again.";health=new(){State="Action required",Authentication="signed-out",AccountName=saved.AccountName,Explanation=state};successful.Clear();} await FlushSettingsAsync();await DrainRevocations();lock(gate)if(saved.Revocations.Count>0){state="Signed out locally · server revocation pending until online.";health.Explanation=state;} } public void ChangeAccount(string address){ValidateOrigin(address);_=CompleteAccountChange(SignOutAsync(),address);} private async Task CompleteAccountChange(Task signout,string address){try{await signout;Connect(address,true);}catch(Exception e)when(AuthFailure(e)){lock(gate){health.State="Action required";health.Explanation="Could not safely change account. Check protected settings and retry.";}}} public async Task StopAsync(){try{Guid context;lock(gate)context=authenticationContext;if(token!=null&&saved.Active!=null){using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(origin!,"api/native-companion/disconnect"));request.Headers.Authorization=new("Bearer",token);using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(3));using var response=await http.SendAsync(request,stop.Token);}else DisconnectPresence();}catch(Exception e)when(AuthFailure(e)){}try{await FlushSettingsAsync();}catch(Exception e)when(StorageFailure(e)){ConnectionFailure(e);}} private sealed record HeartbeatReply(bool Connected,Guid CatalogVersion); }