From 10f44edbca8e04442bbd70c2ecdb7ccb32478934 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Thu, 5 Nov 2026 23:44:38 +0000 Subject: [PATCH] Reject imported cursor mappings from a different live Word session --- ...26-11-05-overnight-development-handover.md | 5 +-- PlotLine.Tests/Sql/NativeApprovedImport.sql | 11 ++++-- .../Controllers/NativeCompanionController.cs | 4 +-- .../Controllers/NativePresenceController.cs | 2 +- PlotLine/Data/NativePositionRepository.cs | 4 +-- PlotLine/Data/NativeReviewRepository.cs | 4 +-- .../Sql/234_NativeImportedSessionGuard.sql | 35 +++++++++++++++++++ 7 files changed, 53 insertions(+), 12 deletions(-) create mode 100644 PlotLine/Sql/234_NativeImportedSessionGuard.sql diff --git a/Docs/Investigations/2026-11-05-overnight-development-handover.md b/Docs/Investigations/2026-11-05-overnight-development-handover.md index c76aa7a5..4eb4b6d6 100644 --- a/Docs/Investigations/2026-11-05-overnight-development-handover.md +++ b/Docs/Investigations/2026-11-05-overnight-development-handover.md @@ -24,14 +24,15 @@ New chapters append in capture order. Existing relationships and metadata remain ## Position and multi-screen safety -Optional tray 1.0.0.11 sends the already available selection start, without additional Word COM operations. The server resolves only saved imported absolute ranges for the same authorised book, persistent document identity and observed revision. Scene/chapter changes invalidate the browser workspace; cursor heartbeats do not continuously rebuild it. After an observed edit, unmatched ranges are refused rather than guessed. This is not durable bookmark installation: revision resets between sessions and same-length dirty edits require Windows qualification; manual scene choice and existing markers remain the safer fallback. Chapter-relative paragraph indices are not saved as whole-document Word positions. +Optional tray 1.0.0.11 sends the already available selection start, without additional Word COM operations. The server resolves only saved imported absolute ranges for the same authorised book, persistent document identity, captured live session and observed revision. Scene/chapter changes invalidate the browser workspace; cursor heartbeats do not continuously rebuild it. After an observed edit, unmatched ranges are refused rather than guessed. This is not durable bookmark installation: reopened sessions are refused (SQL regression checked); same-length dirty edits still require Windows qualification; manual scene choice and existing markers remain the safer fallback. Chapter-relative paragraph indices are not saved as whole-document Word positions. ## Database and deployment -Development-only forward migrations: `232_NativeApprovedImport.sql`, `233_NativeImportedPositions.sql`. Both applied after verified COPY_ONLY/CHECKSUM backups: +Development-only forward migrations: `232_NativeApprovedImport.sql`, `233_NativeImportedPositions.sql`, `234_NativeImportedSessionGuard.sql`. Both applied after verified COPY_ONLY/CHECKSUM backups: - `/var/opt/mssql/backups/PlotDirector_Development-overnight-20261105T225822.bak` - `/var/opt/mssql/backups/PlotDirector_Development-overnight-position-20261105T232027.bak` +- `/var/opt/mssql/backups/PlotDirector_Development-overnight-session-20261105T234600.bak` SQL regression fixtures run inside rollback transactions. Tests cover initial import, exact source/summary, duplicate retry, ordered append, stale revision refusal, and failure after canonical build maps were emitted. Failure leaves no chapter, scene, receipt or fixture behind. No real manuscript import was executed by this sprint. diff --git a/PlotLine.Tests/Sql/NativeApprovedImport.sql b/PlotLine.Tests/Sql/NativeApprovedImport.sql index 946f210e..9d468917 100644 --- a/PlotLine.Tests/Sql/NativeApprovedImport.sql +++ b/PlotLine.Tests/Sql/NativeApprovedImport.sql @@ -5,10 +5,11 @@ IF @User IS NULL THROW 51000,'Fixture requires an existing identity',1; INSERT dbo.Projects(ProjectName) VALUES(N'Native import isolated fixture');DECLARE @Project int=SCOPE_IDENTITY(); INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@Project,@User,N'Owner'); INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Native import isolated book',1,1);DECLARE @Book int=SCOPE_IDENTITY(); -DECLARE @Review uniqueidentifier=NEWID(),@Doc uniqueidentifier=NEWID(),@Operation uniqueidentifier=NEWID(); +DECLARE @Review uniqueidentifier=NEWID(),@Doc uniqueidentifier=NEWID(),@Session uniqueidentifier=NEWID(),@Operation uniqueidentifier=NEWID(); DECLARE @Key nvarchar(80)=CONCAT('native:',REPLACE(CONVERT(nvarchar(36),@Doc),'-',''),':10'); INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,EncryptedSource) VALUES(@Review,@User,@Book,@Doc,10,30,'fixture-hash',N'{"DocumentRevision":2,"Scenes":[{"Start":10,"End":30}]}',N'[]',N'fixture-encrypted-source'); +UPDATE dbo.NativeChapterReviews SET ResultJson=JSON_MODIFY(ResultJson,'$.CaptureSession',CONVERT(varchar(36),@Session)) WHERE ReviewID=@Review; DECLARE @Items nvarchar(max)=(SELECT @Review ReviewID,1 Version,@Key [Key],'fixture-hash' Hash,N'Approved opening' Title,10 Start,30 [End],JSON_QUERY((SELECT CONCAT(@Key,':10') [Key],N'Approved scene' Title,N'An author-approved summary.' Summary,N'Preserved source prose.' [Text],1 StartParagraph,1 EndParagraph,3 Words FOR JSON PATH)) Scenes FOR JSON PATH); EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@OperationID=@Operation,@DocumentGuid=@Doc,@ItemsJson=@Items; IF (SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@Book AND IsArchived=0)<>1 THROW 51000,'Wrong chapter creation count',1; @@ -24,9 +25,13 @@ EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@Operat IF NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE BookID=@Book AND ChapterNumber=2 AND ChapterTitle=N'Approved continuation') THROW 51000,'Incremental chapter ordering failed',1; IF (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@Book AND s.IsArchived=0)<>2 THROW 51000,'Incremental scene count failed',1; CREATE TABLE #NativePosition(ChapterID int,SceneID int NULL); -INSERT #NativePosition EXEC dbo.NativeImportedPosition @UserID=@User,@BookID=@Book,@DocumentGuid=@Doc,@Revision=2,@Position=12; +INSERT #NativePosition EXEC dbo.NativeImportedPosition @UserID=@User,@BookID=@Book,@DocumentGuid=@Doc,@Revision=2,@Position=12,@SessionID=@Session; IF (SELECT COUNT(*) FROM #NativePosition)<>1 OR NOT EXISTS(SELECT 1 FROM #NativePosition WHERE SceneID IS NOT NULL) THROW 51000,'Imported scene cursor mapping failed',1; TRUNCATE TABLE #NativePosition; -INSERT #NativePosition EXEC dbo.NativeImportedPosition @UserID=@User,@BookID=@Book,@DocumentGuid=@Doc,@Revision=3,@Position=12; +INSERT #NativePosition EXEC dbo.NativeImportedPosition @UserID=@User,@BookID=@Book,@DocumentGuid=@Doc,@Revision=3,@Position=12,@SessionID=@Session; IF EXISTS(SELECT 1 FROM #NativePosition) THROW 51000,'Stale imported positions accepted',1; +TRUNCATE TABLE #NativePosition; +DECLARE @OtherSession uniqueidentifier=NEWID(); +INSERT #NativePosition EXEC dbo.NativeImportedPosition @UserID=@User,@BookID=@Book,@DocumentGuid=@Doc,@Revision=2,@Position=12,@SessionID=@OtherSession; +IF EXISTS(SELECT 1 FROM #NativePosition) THROW 51000,'Reopened session accepted old positions',1; SELECT 'PASS canonical native initial import, source/summary preservation, retry and incremental append'; diff --git a/PlotLine/Controllers/NativeCompanionController.cs b/PlotLine/Controllers/NativeCompanionController.cs index 977da71f..c59f36ac 100644 --- a/PlotLine/Controllers/NativeCompanionController.cs +++ b/PlotLine/Controllers/NativeCompanionController.cs @@ -33,13 +33,13 @@ public sealed class NativeCompanionController(IWordCompanionRepository repositor var retain=User.HasClaim("NativeCompanion.RetainImport","true"); var mapped=NativeChapterMapping.Build(request,Math.Clamp(configuration.GetValue("NativeCompanion:MaxChapterCharacters",120000),10000,500000)); var contentHash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{request.ChapterStart,request.ChapterEnd,request.Paragraphs}))); - if(reviews!=null){var prior=await reviews.Find(UserId,request.BookId,request.ManuscriptId,contentHash);if(prior!=null){if(retain&&prior.EncryptedSource==null&&importService!=null){prior.EncryptedSource=importService.Protect(request);prior.SourceRevision=request.Revision;await reviews.Save(prior);}var saved=JsonSerializer.Deserialize(prior.ResultJson)!;saved.SourceRetained=prior.EncryptedSource!=null;saved.RequestId=request.RequestId;saved.DocumentRevision=request.Revision;saved.ReviewPath=$"/native-companion/reviews/{prior.ReviewID}";return Ok(saved);}} + if(reviews!=null){var prior=await reviews.Find(UserId,request.BookId,request.ManuscriptId,contentHash);if(prior!=null){if(retain&&prior.EncryptedSource==null&&importService!=null){prior.EncryptedSource=importService.Protect(request);prior.SourceRevision=request.Revision;prior.SourceSession=request.SessionId;await reviews.Save(prior);}var saved=JsonSerializer.Deserialize(prior.ResultJson)!;saved.SourceRetained=prior.EncryptedSource!=null;saved.RequestId=request.RequestId;saved.DocumentRevision=request.Revision;saved.ReviewPath=$"/native-companion/reviews/{prior.ReviewID}";return Ok(saved);}} var hash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(request))); var author=UserId;var task=cache.Run(author,request.RequestId,hash,async cancellation=>{ await using var scope=scopes.CreateAsyncScope(); var result=await scope.ServiceProvider.GetRequiredService().AnalyseChapterAsync(mapped,cancellation); var mappedResult=NativeChapterMapping.Map(request,result); - if(mappedResult.State=="complete"&&reviews!=null){var row=await scope.ServiceProvider.GetRequiredService().Save(new(){ReviewID=request.RequestId,UserID=author,BookID=request.BookId,ManuscriptID=request.ManuscriptId,ChapterStart=request.ChapterStart,ChapterEnd=request.ChapterEnd,ContentHash=contentHash,ResultJson=JsonSerializer.Serialize(mappedResult),SourceRevision=request.Revision,EncryptedSource=retain?importService?.Protect(request):null});mappedResult.SourceRetained=row.EncryptedSource!=null;mappedResult.ReviewPath=$"/native-companion/reviews/{row.ReviewID}";} + if(mappedResult.State=="complete"&&reviews!=null){var row=await scope.ServiceProvider.GetRequiredService().Save(new(){ReviewID=request.RequestId,UserID=author,BookID=request.BookId,ManuscriptID=request.ManuscriptId,ChapterStart=request.ChapterStart,ChapterEnd=request.ChapterEnd,ContentHash=contentHash,ResultJson=JsonSerializer.Serialize(mappedResult),SourceRevision=request.Revision,SourceSession=request.SessionId,EncryptedSource=retain?importService?.Protect(request):null});mappedResult.SourceRetained=row.EncryptedSource!=null;mappedResult.ReviewPath=$"/native-companion/reviews/{row.ReviewID}";} return mappedResult; },request.BookId); Response.Headers.CacheControl="no-store"; diff --git a/PlotLine/Controllers/NativePresenceController.cs b/PlotLine/Controllers/NativePresenceController.cs index 2c5af7cd..d3e9af6a 100644 --- a/PlotLine/Controllers/NativePresenceController.cs +++ b/PlotLine/Controllers/NativePresenceController.cs @@ -18,7 +18,7 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC { input.Navigation=null;var book=await access.GetBookStructureAsync(input.BookId,Author);if(book==null)return Forbid(); if(input.CursorStart is <0)return BadRequest("Invalid cursor position."); - if(input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}} + if(input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}} var chapter=input.ChapterId.HasValue?book.Chapters.FirstOrDefault(c=>c.ChapterId==input.ChapterId):null; if(input.SceneId.HasValue){var parent=book.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==input.SceneId));if(parent==null||(chapter!=null&&chapter!=parent))return NotFound();chapter=parent;input.ChapterId=parent.ChapterId;} if(input.ChapterId.HasValue&&chapter==null)return NotFound(); diff --git a/PlotLine/Data/NativePositionRepository.cs b/PlotLine/Data/NativePositionRepository.cs index 807ab0b9..e1003808 100644 --- a/PlotLine/Data/NativePositionRepository.cs +++ b/PlotLine/Data/NativePositionRepository.cs @@ -2,8 +2,8 @@ using System.Data; using Dapper; namespace PlotLine.Data; public sealed class NativeSavedPosition{public int ChapterID{get;set;}public int? SceneID{get;set;}} -public interface INativePositionRepository{Task Resolve(int user,int book,Guid document,long revision,int position);} +public interface INativePositionRepository{Task Resolve(int user,int book,Guid document,Guid session,long revision,int position);} public sealed class NativePositionRepository(ISqlConnectionFactory factory):INativePositionRepository { - public async Task Resolve(int user,int book,Guid document,long revision,int position){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync("dbo.NativeImportedPosition",new{UserID=user,BookID=book,DocumentGuid=document,Revision=revision,Position=position},commandType:CommandType.StoredProcedure);} + public async Task Resolve(int user,int book,Guid document,Guid session,long revision,int position){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync("dbo.NativeImportedPosition",new{UserID=user,BookID=book,DocumentGuid=document,SessionID=session,Revision=revision,Position=position},commandType:CommandType.StoredProcedure);} } diff --git a/PlotLine/Data/NativeReviewRepository.cs b/PlotLine/Data/NativeReviewRepository.cs index 3b6d9c0a..f800570f 100644 --- a/PlotLine/Data/NativeReviewRepository.cs +++ b/PlotLine/Data/NativeReviewRepository.cs @@ -3,7 +3,7 @@ using Dapper; namespace PlotLine.Data; public sealed class NativeReview { - public long? SourceRevision{get;set;}public string? EncryptedSource{get;set;}public Guid ReviewID {get;set;}public int UserID {get;set;}public int BookID {get;set;}public Guid ManuscriptID {get;set;}public int ChapterStart {get;set;}public int ChapterEnd {get;set;}public string ContentHash {get;set;}="";public string ResultJson {get;set;}="";public string? DecisionsJson {get;set;}public int Version {get;set;}public DateTime CreatedUtc {get;set;} + public Guid? SourceSession{get;set;}public long? SourceRevision{get;set;}public string? EncryptedSource{get;set;}public Guid ReviewID {get;set;}public int UserID {get;set;}public int BookID {get;set;}public Guid ManuscriptID {get;set;}public int ChapterStart {get;set;}public int ChapterEnd {get;set;}public string ContentHash {get;set;}="";public string ResultJson {get;set;}="";public string? DecisionsJson {get;set;}public int Version {get;set;}public DateTime CreatedUtc {get;set;} } public interface INativeReviewRepository { @@ -19,6 +19,6 @@ public sealed class NativeReviewRepository(ISqlConnectionFactory factory):INativ public Task Find(int user,int book,Guid manuscript,string hash)=>Read(new{Action="Find",UserID=user,BookID=book,ManuscriptID=manuscript,ContentHash=hash}); public Task Get(int user,Guid id)=>Read(new{Action="Get",UserID=user,ReviewID=id}); public async Task> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync("dbo.NativeChapterReview_Access",new{Action="List",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} - public async Task Save(NativeReview r){var saved=await Read(new{Action="Save",r.UserID,r.BookID,r.ReviewID,r.ManuscriptID,r.ChapterStart,r.ChapterEnd,r.ContentHash,r.ResultJson})??throw new InvalidOperationException("Review was not saved.");if(!string.IsNullOrEmpty(r.EncryptedSource)){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.NativeReviewSource_Save",new{r.UserID,ReviewID=saved.ReviewID,r.EncryptedSource,ObservedRevision=r.SourceRevision},commandType:CommandType.StoredProcedure);saved.EncryptedSource??=r.EncryptedSource;}return saved;} + public async Task Save(NativeReview r){var saved=await Read(new{Action="Save",r.UserID,r.BookID,r.ReviewID,r.ManuscriptID,r.ChapterStart,r.ChapterEnd,r.ContentHash,r.ResultJson})??throw new InvalidOperationException("Review was not saved.");if(!string.IsNullOrEmpty(r.EncryptedSource)){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.NativeReviewSource_Save",new{r.UserID,ReviewID=saved.ReviewID,r.EncryptedSource,ObservedRevision=r.SourceRevision,SessionID=r.SourceSession},commandType:CommandType.StoredProcedure);saved.EncryptedSource??=r.EncryptedSource;}return saved;} public async Task Decide(int user,Guid id,int version,string json){using var db=factory.CreateConnection();return await db.ExecuteScalarAsync("dbo.NativeChapterReview_Access",new{Action="Decide",UserID=user,ReviewID=id,Version=version,DecisionsJson=json},commandType:CommandType.StoredProcedure)==1;} } diff --git a/PlotLine/Sql/234_NativeImportedSessionGuard.sql b/PlotLine/Sql/234_NativeImportedSessionGuard.sql new file mode 100644 index 00000000..a8e2349e --- /dev/null +++ b/PlotLine/Sql/234_NativeImportedSessionGuard.sql @@ -0,0 +1,35 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +IF COL_LENGTH(N'dbo.NativeReviewImports',N'ObservationSession') IS NULL ALTER TABLE dbo.NativeReviewImports ADD ObservationSession uniqueidentifier NULL; +GO +CREATE OR ALTER PROCEDURE dbo.NativeReviewSource_Save @UserID int,@ReviewID uniqueidentifier,@EncryptedSource nvarchar(max),@ObservedRevision bigint=NULL,@SessionID uniqueidentifier=NULL +AS +BEGIN + SET NOCOUNT ON; + IF DATALENGTH(@EncryptedSource)>8388608 THROW 51000,'Source capture too large',1; + UPDATE dbo.NativeChapterReviews SET EncryptedSource=@EncryptedSource,ResultJson=CASE WHEN @ObservedRevision IS NOT NULL THEN JSON_MODIFY(JSON_MODIFY(ResultJson,'$.DocumentRevision',@ObservedRevision),'$.CaptureSession',CONVERT(varchar(36),@SessionID)) ELSE ResultJson END WHERE ReviewID=@ReviewID AND UserID=@UserID AND EncryptedSource IS NULL; +END; +GO +CREATE OR ALTER TRIGGER dbo.NativeReviewImports_CapturePositions ON dbo.NativeReviewImports AFTER INSERT +AS +BEGIN + SET NOCOUNT ON; + UPDATE n SET DocumentGuid=r.ManuscriptID,ObservationSession=TRY_CONVERT(uniqueidentifier,JSON_VALUE(r.ResultJson,'$.CaptureSession')),ObservationRevision=TRY_CONVERT(bigint,JSON_VALUE(r.ResultJson,'$.DocumentRevision')),ChapterStart=r.ChapterStart,ChapterEnd=r.ChapterEnd, + ScenePositionsJson=(SELECT p.Start,p.[End],m.SceneID,n.ChapterID FROM OPENJSON(r.ResultJson,'$.Scenes') WITH(Start int,[End] int) p JOIN dbo.OnboardingManuscriptBuildSceneMap m ON m.OnboardingManuscriptBuildID=n.BuildID AND m.TemporarySceneKey=CONCAT(n.ChapterKey,':',p.Start) FOR JSON PATH) + FROM dbo.NativeReviewImports n JOIN inserted i ON i.BookID=n.BookID AND i.ChapterKey=n.ChapterKey JOIN dbo.NativeChapterReviews r ON r.ReviewID=n.ReviewID; + IF EXISTS(SELECT 1 FROM dbo.NativeReviewImports n JOIN inserted i ON i.BookID=n.BookID AND i.ChapterKey=n.ChapterKey JOIN dbo.NativeReviewImports other ON other.BookID=n.BookID AND other.DocumentGuid=n.DocumentGuid AND other.ChapterKey<>n.ChapterKey AND other.ChapterStart=s.Start AND @Position=n.ChapterStart AND @Position