From a369e7dcd21cee86aed4954c20f72332ce46f3a1 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sun, 15 Nov 2026 00:33:57 +0000 Subject: [PATCH] Harden activity retries, downgrade protection and bounded word comparisons --- .../Agent/CloudGateway.Authorization.cs | 2 +- .../Agent/CloudGateway.WritingActivity.cs | 18 ++++++++++++------ .../Agent/CompanionStateStore.cs | 2 +- .../Tests/PersistentConnectionTests.cs | 6 ++++-- .../WritingActivity/WritingChangeCalculator.cs | 15 +++++++++------ 5 files changed, 27 insertions(+), 16 deletions(-) diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.Authorization.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.Authorization.cs index 92c90869..34ff5c18 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.Authorization.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.Authorization.cs @@ -23,7 +23,7 @@ public sealed partial class CloudGateway 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;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();} + 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() diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.WritingActivity.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.WritingActivity.cs index 08b4a6dd..8e8265f1 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.WritingActivity.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.WritingActivity.cs @@ -6,6 +6,7 @@ public sealed class QueuedWritingObservation { public string Site { get; set; } = ""; public int Account { get; set; } + public DateTimeOffset RetryAfterUtc { get; set; } public WritingObservation Observation { get; set; } = new(); } public sealed partial class CloudGateway @@ -20,9 +21,9 @@ public sealed partial class CloudGateway { if(storage==null||!stateLoaded||saved.Active==null||authenticationContext!=context||book<=0||manuscript==Guid.Empty||chapter<=0)return false; var hash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes($"{manuscript:D}|{chapter}|{session:D}|{revision}"))); - if(saved.WritingObservations.Any(q=>q.Site==saved.Active.Site&&q.Account==saved.Active.AccountId&&q.Observation.PayloadHash==hash))return true; - if(saved.WritingObservations.Count>=128){health.Explanation="Activity observation queue is full. Manuscript synchronisation remains available; some observation coverage is unavailable.";return false;} - saved.WritingObservations.Add(new(){Site=saved.Active.Site,Account=saved.Active.AccountId,Observation=new(){BookID=book,ManuscriptID=manuscript,ChapterID=chapter,ObservedUtc=Now.UtcDateTime,PayloadHash=hash}}); + var duplicate=saved.WritingObservations.Any(q=>q.Site==saved.Active.Site&&q.Account==saved.Active.AccountId&&q.Observation.PayloadHash==hash); + if(!duplicate&&saved.WritingObservations.Count>=128){health.Explanation="Activity observation queue is full. Manuscript synchronisation remains available; some observation coverage is unavailable.";return false;} + if(!duplicate)saved.WritingObservations.Add(new(){Site=saved.Active.Site,Account=saved.Active.AccountId,Observation=new(){BookID=book,ManuscriptID=manuscript,ChapterID=chapter,ObservedUtc=Now.UtcDateTime,PayloadHash=hash}}); } await FlushSettingsAsync();return true; } @@ -31,17 +32,22 @@ public sealed partial class CloudGateway public async Task DrainWritingObservations() { if(!await activityDelivery.WaitAsync(0))return; + QueuedWritingObservation? attempted=null; try { QueuedWritingObservation? item;Guid context; - lock(gate){if(Nowq.Site==saved.Active.Site&&q.Account==saved.Active.AccountId);} - if(item==null)return; + lock(gate){if(Nowq.Site==saved.Active.Site&&q.Account==saved.Active.AccountId&&q.RetryAfterUtc<=Now);} + if(item==null)return;attempted=item; var receipt=await Post("api/native-companion/writing-activity",item.Observation,context); if(receipt.RequestID!=item.Observation.RequestID)throw new InvalidDataException("Activity acknowledgement identity differs."); lock(gate){if(context!=authenticationContext)return;saved.WritingObservations.Remove(item);} await FlushSettingsAsync(); } - catch(Exception e)when(AuthFailure(e)){lock(gate){activityRetryUtc=Now.AddMinutes(1);health.Explanation="Activity observations are waiting for delivery. Manuscript synchronisation remains independent.";}} + catch(Exception e)when(AuthFailure(e)) + { + lock(gate){activityRetryUtc=Now.AddSeconds(5);if(attempted!=null)attempted.RetryAfterUtc=Now.AddMinutes(1);health.Explanation="Activity observations are waiting for delivery. Manuscript synchronisation remains independent.";} + await PersistSafely(); + } finally{activityDelivery.Release();} } } diff --git a/PlotDirector.NativeCompanion/Agent/CompanionStateStore.cs b/PlotDirector.NativeCompanion/Agent/CompanionStateStore.cs index 406bc568..a9a26e00 100644 --- a/PlotDirector.NativeCompanion/Agent/CompanionStateStore.cs +++ b/PlotDirector.NativeCompanion/Agent/CompanionStateStore.cs @@ -47,7 +47,7 @@ public sealed class ProtectedCompanionStateStore(string path,IStateProtection pr 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(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(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||state.WritingObservations==null||state.WritingObservations.Count>128)throw new CryptographicException("Settings scope mismatch.");return state;}finally{CryptographicOperations.ZeroMemory(clear);}}} + 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(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(clear)??throw new CryptographicException("Invalid protected settings.");if(state.Version is not (1 or 2)||state.Server!=envelope.Site||state.AccountId!=envelope.Account||state.Revocations.Count>16||state.Bindings.Count>2048||state.WritingObservations==null||state.WritingObservations.Count>128)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;}} } diff --git a/PlotDirector.NativeCompanion/Tests/PersistentConnectionTests.cs b/PlotDirector.NativeCompanion/Tests/PersistentConnectionTests.cs index 2dda836a..79ae8b16 100644 --- a/PlotDirector.NativeCompanion/Tests/PersistentConnectionTests.cs +++ b/PlotDirector.NativeCompanion/Tests/PersistentConnectionTests.cs @@ -17,6 +17,7 @@ internal static class PersistentConnectionTests server.Offline=true; check(await cloud.QueueWritingObservation(3,manuscript,10,manuscript,1,cloud.Status().AuthenticationContext),"native activity observation persists before offline delivery"); var queuedID=store.Load().WritingObservations.Single().Observation.RequestID; + check(store.Load().Version==2,"pending outbox uses a protected state version that older agents refuse instead of discarding observations"); await cloud.QueueWritingObservation(3,manuscript,10,manuscript,1,cloud.Status().AuthenticationContext); await cloud.DrainWritingObservations();check(store.Load().WritingObservations.Count==1&&store.Load().WritingObservations[0].Observation.RequestID==queuedID,"offline retries preserve immutable identity without duplicate queue entries"); check(!JsonSerializer.Serialize(store.Load()).Contains("access:"),"short-lived access tokens are never persisted in settings"); @@ -26,6 +27,7 @@ internal static class PersistentConnectionTests using var stop=new CancellationTokenSource();var loop=cloud.RunConnectionLoop(stop.Token);await Until(()=>cloud.Status().Health?.State=="Reconnecting");await Task.Delay(200);check(server.RenewAttempts==1,"offline startup makes a bounded renewal attempt without browser approval"); server.Offline=false;clock.Advance(TimeSpan.FromMinutes(1));await Until(()=>cloud.Status().Health?.State=="Connected");stop.Cancel();await loop; await Until(()=>store.Load().WritingObservations.Count==0); + check(store.Load().Version==1,"drained outbox restores the older compatible settings version"); check(server.ActivityIDs.Count==1,"native restart recovers and acknowledges durable observation without prose upload"); check(approvals==1&&cloud.RestoreBinding(manuscript)==3&&cloud.Preferences.Width==975&&cloud.Preferences.RememberInDocument&&cloud.Preferences.AdvancedMode,"process/network recovery restores scoped association and preferences without interaction"); var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai); @@ -49,11 +51,11 @@ internal static class PersistentConnectionTests } using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){ await cloud.ReconnectAsync();check(cloud.Status().Health?.State=="Connected"&&store.Load().Active?.Pending==null&&approvals==1,"restart recovers committed rotation and acquires a fresh process connection without re-pairing"); - server.Offline=true;await cloud.SignOutAsync();check(store.Load().Active==null&&store.Load().Revocations.Count==1,"offline explicit sign-out disables local trust and durably queues server revocation"); + server.Offline=true;await cloud.QueueWritingObservation(3,manuscript,10,manuscript,2,cloud.Status().AuthenticationContext);await cloud.SignOutAsync();check(store.Load().Active==null&&store.Load().Revocations.Count==1,"offline explicit sign-out disables local trust and durably queues server revocation"); } using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){ await cloud.ReconnectAsync();check(cloud.Status().Health?.State=="Action required"&&approvals==1,"signed-out process restart never silently resumes the old account");server.Offline=false;await cloud.SignOutAsync();check(server.Revoked&&store.Load().Revocations.Count==0,"queued sign-out revokes server approval after connectivity returns"); - cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Health?.State=="Connected");server.Account=8;cloud.ChangeAccount("https://fixture.invalid/");await Until(()=>store.Load().Active?.AccountId==8&&cloud.Status().Health?.State=="Connected"); + cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Health?.State=="Connected");server.Account=8;cloud.ChangeAccount("https://fixture.invalid/");await Until(()=>store.Load().Active?.AccountId==8&&cloud.Status().Health?.State=="Connected");await cloud.DrainWritingObservations();check(store.Load().WritingObservations.All(q=>q.Account==7)&&server.ActivityIDs.Count==1,"account switching never delivers the previous account's queued activity under new credentials"); check(approvals==3&&cloud.RestoreBinding(manuscript)==null,"account change requires explicit approval and cannot reuse another account's manuscript association"); server.Revoked=true;clock.Advance(TimeSpan.FromMinutes(11));await cloud.ReconnectAsync();check(cloud.Status().Health?.State=="Action required"&&store.Load().Active==null,"server revocation stops renewal and requires a genuine new approval"); } diff --git a/PlotLine/Services/WritingActivity/WritingChangeCalculator.cs b/PlotLine/Services/WritingActivity/WritingChangeCalculator.cs index d5eb7463..73319175 100644 --- a/PlotLine/Services/WritingActivity/WritingChangeCalculator.cs +++ b/PlotLine/Services/WritingActivity/WritingChangeCalculator.cs @@ -7,9 +7,10 @@ public static class WritingChangeCalculator public static string[] Tokens(string text) => text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); public static WritingChange Compare(ParagraphManuscript? before, ParagraphManuscript after) { + if(before==null)return new(0,after.Paragraphs.Sum(p=>Tokens(p.Occurrence.Text).Length),0,0,"Baseline; earlier activity unavailable",[]); var old = before?.Paragraphs.ToDictionary(p => p.Occurrence.Id) ?? []; var next = after.Paragraphs.ToDictionary(p => p.Occurrence.Id); - var added = 0; var removed = 0; var exact = true; + var added = 0; var removed = 0; var exact = true; long workBudget = 8_000_000; var scopes = new List(); var unmatchedOld = new List(); var unmatchedNew = new List(); foreach (var row in after.Paragraphs) @@ -18,32 +19,34 @@ public static class WritingChangeCalculator { if (prior.Occurrence.Text == row.Occurrence.Text) continue; var a = Tokens(prior.Occurrence.Text); var b = Tokens(row.Occurrence.Text); - var common = Common(a, b, ref exact); added += b.Length - common; removed += a.Length - common; + var common = Common(a, b, ref exact, ref workBudget); added += b.Length - common; removed += a.Length - common; scopes.Add(new(row.Occurrence.Id, prior.ChapterId, row.ChapterId, prior.SceneId, row.SceneId)); } else { unmatchedNew.AddRange(Tokens(row.Occurrence.Text)); scopes.Add(new(row.Occurrence.Id, null, row.ChapterId, null, row.SceneId)); } } foreach (var row in before?.Paragraphs ?? []) if (!next.ContainsKey(row.Occurrence.Id)) { unmatchedOld.AddRange(Tokens(row.Occurrence.Text)); scopes.Add(new(row.Occurrence.Id, row.ChapterId, null, row.SceneId, null)); } - var shared = Common(unmatchedOld.ToArray(), unmatchedNew.ToArray(), ref exact); + var shared = Common(unmatchedOld.ToArray(), unmatchedNew.ToArray(), ref exact, ref workBudget); added += unmatchedNew.Count - shared; removed += unmatchedOld.Count - shared; var beforeWords = before?.Paragraphs.Sum(p => Tokens(p.Occurrence.Text).Length) ?? 0; var afterWords = after.Paragraphs.Sum(p => Tokens(p.Occurrence.Text).Length); return new(beforeWords, afterWords, before == null ? 0 : added, before == null ? 0 : removed, - before == null ? "Baseline; earlier activity unavailable" : exact ? "Accepted snapshot difference; whitespace-v1/paragraph-lcs; writing time unknown" : "Partial: minimum token-balance difference for large replacement; writing time unknown", scopes); + before == null ? "Baseline; earlier activity unavailable" : exact ? "Accepted snapshot difference; whitespace-v1/paragraph-lcs; writing time unknown" : "Partial: minimum token-balance difference for bounded comparison; writing time unknown", scopes); } - private static int Common(string[] a, string[] b, ref bool exact) + private static int Common(string[] a, string[] b, ref bool exact, ref long workBudget) { var start = 0; while (start < a.Length && start < b.Length && a[start] == b[start]) start++; var ae = a.Length; var be = b.Length; while (ae > start && be > start && a[ae - 1] == b[be - 1]) { ae--; be--; } - if ((long)(ae - start) * (be - start) > 2_000_000) + var work=(long)(ae-start)*(be-start); + if (work > 2_000_000 || work > workBudget) { exact = false; var counts = a[start..ae].GroupBy(t => t, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal); var common = 0; foreach (var token in b[start..be]) if (counts.TryGetValue(token, out var n) && n > 0) { common++; counts[token] = n - 1; } return start + a.Length - ae + common; } + workBudget-=work; var row = new int[be - start + 1]; for (var i = start; i < ae; i++) { var diagonal = 0; for (var j = start; j < be; j++) { var previous = row[j - start + 1]; row[j - start + 1] = a[i] == b[j] ? diagonal + 1 : Math.Max(row[j - start + 1], row[j - start]); diagonal = previous; } } return start + a.Length - ae + row[^1];