Persist revocable Companion approval and reconnect automatically
This commit is contained in:
parent
21f9eac167
commit
5316ad539c
87
Docs/WordCompanion/Persistent-Authorisation.md
Normal file
87
Docs/WordCompanion/Persistent-Authorisation.md
Normal file
@ -0,0 +1,87 @@
|
||||
# Persistent Companion authorisation and automatic reconnection
|
||||
|
||||
## Baseline and causes
|
||||
|
||||
Work started with a clean shared branch `codex/word-companion-native-phase1-20261104`, fetched the configured `origin` remote and fast-forwarded to Windows qualification commit **21f9eac**. No branch/worktree or merge commit was created. The qualified version13 setup source and evidence are preserved.
|
||||
|
||||
The reported behaviour followed the implementation rather than an expiring Windows setting:
|
||||
|
||||
- `CloudGateway` retained only a four-hour Data Protection bearer grant in memory. Only `server-url.txt` was persisted.
|
||||
- `Dispose()` called `SignOut()`, so process exit discarded authentication and revoked presence. There was no renewable installation credential or startup restore loop.
|
||||
- Window X already hid the form; it did not exit. Tray Quit stopped the process and wrote a permanent `paused` file, preventing subsequent automatic Word-triggered launches until explicit activation.
|
||||
- Session-only book association, window size and selections were memory-only. Word metadata persistence was optional, so unchecked associations disappeared with the agent.
|
||||
- Grant identity was derived from each access token's ciphertext. Simply renewing access would have changed presence routing unless connection identity was separated from access expiry.
|
||||
|
||||
## Correction
|
||||
|
||||
Existing browser-approved PKCE pairing, AppUser identities/security stamps, Data Protection tokens, Dapper and stored procedures are extended. There is no second identity provider or Windows service.
|
||||
|
||||
### Server contract
|
||||
|
||||
- New clients request persistent pairing using the existing `/api/native-companion/pair` and browser approval endpoints. Older clients keep the legacy four-hour contract; they are not silently granted permanent authority.
|
||||
- Approval creates a random installation ID and 256-bit rotating credential. SQL stores only its SHA-256 hash, previous hash/rotation ID for retry recovery, original security stamp, owner, approved retention permission and connection metadata.
|
||||
- Access tokens expire after **10 minutes** and remain memory-only. `/api/native-companion/renew` rotates the installation credential and issues new short-lived access. Approval has a **90-day sliding inactivity limit**.
|
||||
- Pending rotation is durably written on the client before renewal. The server accepts a previous credential only for the identical rotation ID, next-credential hash and connection identity. Lost responses/process crashes can finish that pending operation and acquire a new process connection without browser approval. Another operation cannot reuse the old credential.
|
||||
- Every trusted access request checks installation revocation, account/security stamp, lockout, expiry and process connection against SQL, in addition to existing user authentication. Existing book/subscription checks remain in their original endpoints.
|
||||
- Access renewal keeps the same presence grant key within an agent process. Restart acquires a new connection identity and invalidates the old process's presence/access, without discarding installation approval.
|
||||
- `/api/native-companion/revoke`, owner-only antiforgery-protected installation management, and website logout revoke trust. Website logout revokes all installations for that account. A revoked installation cannot renew or keep using an otherwise unexpired access token.
|
||||
- No authority or credentials are included in project/book backup packages. The new table is operational account authorisation, not manuscript data, and cascades when AppUser is deleted.
|
||||
|
||||
Migration: **`PlotLine/Sql/238_NativeInstallationAuthorisation.sql`**. It creates `NativeCompanionInstallations` and `NativeCompanionInstallation`. Apply it before dependent server binaries. Do not replay other migrations or modify earlier numbered scripts.
|
||||
|
||||
### Windows-protected settings
|
||||
|
||||
`%LOCALAPPDATA%\PlotDirector\Companion\installation-state.dat` holds the active installation, pending rotation, pending sign-out revocations, server/account identity, namespaced manuscript/book associations and preferences. The envelope is protected by Windows **current-user DPAPI**, with additional server/account entropy and matching encrypted scope fields. It does not use machine-wide protection or a plaintext fallback. Access tokens and passwords are never written to it.
|
||||
|
||||
Writes use a separate owner lock, protected temporary file, disk flush and atomic replacement. An interrupted write preserves the previous complete file. Credentials must be durably saved before the agent treats the account as usable. Unreadable/inaccessible protected settings produce Action required instead of silently discarding approval or opening repeated browser prompts. A second Windows session cannot concurrently rotate the same protected profile.
|
||||
|
||||
The implementation uses the documented non-interactive DPAPI path and `LocalFree` cleanup, without a new package dependency. See [Microsoft CryptProtectData documentation](https://learn.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptprotectdata) and [CryptUnprotectData documentation](https://learn.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata). Actual DPAPI/profile interoperability is a Windows qualification item, not proven by Linux encryption substitutes.
|
||||
|
||||
### Lifecycle and reconnection
|
||||
|
||||
- Startup restores protected approval and renews silently. The existing per-user startup shortcut and Word IPC-worker agent launch are reused.
|
||||
- Word's existing background IPC recovery is preserved. No HTTP/authentication, disk protection or credentials move into the Word UI/STA path.
|
||||
- Renewal is serialised. Network failures use bounded exponential backoff/jitter, up to approximately one minute. The two-second local loop does not make a network request every tick.
|
||||
- Existing presence traffic supplies liveness when Word is active. A small authenticated heartbeat handles an approved agent with no Word document. Permission/configuration checks remain periodic; automatic renewal does not resubmit a manuscript or AI request.
|
||||
- Access expiry preserves the account context, associations and user decisions. Account changes/sign-out invalidate that context and cancel obsolete work.
|
||||
- Local associations are keyed by server, existing account ID and persistent manuscript GUID. They are restored only after current book permissions are verified. Word metadata association remains optional and is not automatically rewritten.
|
||||
- Window close hides the tray form. Quit flushes preferences and reports disconnection without revoking approval. Existing Word processes respect Quit; a later new Word process or Windows logon is not permanently blocked by the old pause marker.
|
||||
- Explicit sign-out clears the active local credential before completion. Offline revocation is queued in protected storage, never used to sign in, and retried automatically. The UI distinguishes local sign-out from pending server revocation.
|
||||
|
||||
### Status
|
||||
|
||||
The Companion shows Connected, Reconnecting, Disconnected or Action required, plus account identity and independent local Word/document registration information. The website uses the existing presence area and a cookie-authorised connection-state endpoint, backed by recent authenticated installation activity. An agent-only connection explicitly says Word is not connected. Presence uses a 45-second liveness window; network recovery/expiry is not an assertion that a stopped process is still running.
|
||||
|
||||
The author can inspect/revoke only their installations at `/native-companion/installations`, linked from account settings. Secrets/security stamps are not rendered. Existing Office.js/legacy native compatibility remains; the normal import wizard is still the only automatic extraction trigger authorised by an explicit manuscript request.
|
||||
|
||||
## Verification
|
||||
|
||||
- Managed solution and Windows-targeted managed code built with zero warnings/errors. No VSTO host or Windows package was built or installed on Atlas.
|
||||
- Focused native tests cover initial approval, process disposal/restart, access expiry, offline startup/recovery, stable account context, permission loss, pending-rotation recovery, offline sign-out, account switching and revocation. They assert zero prose requests during these operations.
|
||||
- Protected-file tests cover encrypted round trips using an injected Linux test protector, wrong protection key/account scope, atomic-write failure and the absence of a production plaintext fallback. They do not claim real Windows DPAPI or ACL verification.
|
||||
- Server/service and actual HTTP tests exercise existing PKCE/antiforgery, renewable access, idempotent rotation, old-credential rejection, owner isolation, process replacement, security-stamp/lockout checks, website logout and immediate revocation of unexpired access.
|
||||
- `PlotLine.Tests/Sql/NativeInstallationAuthorisation.sql` passed against guarded synthetic database `PlotDirector_Phase2_20261103_2305`: durable hash-only records, rotation/retry, exit/restart, account isolation, password/logout revocation and account-deletion cascade. All fixtures rolled back.
|
||||
- Browser tests cover website states and independent Word liveness, alongside the existing native-workspace regression.
|
||||
- Full executable application harness: **416 checks passed**. Native foundation harness: **238 checks passed**. The serial CLI build uses `--disable-build-servers -m:1 /p:UseSharedCompilation=false`; an initial CLR build-process failure was avoided using this stable serial invocation.
|
||||
|
||||
## Windows handover
|
||||
|
||||
Source version is **1.0.0.14**, with matching VSTO assembly/file versions. Setup's qualified **1.0.0.13** baseline, packaging source and installed laptop are unchanged. Do not repeatedly rebuild/install packages to investigate persistence. Use the existing workflow once for the eventual Windows build/qualification; do not introduce another installer or direct-VSTO installation path.
|
||||
|
||||
Version13 cannot retroactively supply an installation credential: it never saved one. The new client needs **one explicit initial approval** after upgrade and matching server deployment. Thereafter normal access expiry/restarts/reconnects are automatic. Only explicit sign-out/revocation, account changes, 90 days without renewal or genuinely invalid/unreadable credentials require action.
|
||||
|
||||
On the real interactive Windows user profile, verify:
|
||||
|
||||
1. Approve once; note the account/server. Link a saved test manuscript and adjust window size/preferences.
|
||||
2. Close/reopen the window, Quit/relaunch, restart the agent and Windows, and open a new Word process. Confirm the same approved installation reconnects, without a browser or settings loss.
|
||||
3. Leave connected past ten minutes and four hours. Confirm renewal preserves document/book context and does not read/upload prose or disrupt Word.
|
||||
4. Disconnect/reconnect network/server access. Confirm Reconnecting and automatic recovery; Word remains usable. With no Word document, neither UI should claim a live Word document.
|
||||
5. Change current book permissions; confirm a denied association does not authorise a transfer.
|
||||
6. Sign out online and offline. Confirm local trust is removed, pending revocation is explicit when offline, and reconnecting the network completes revocation without restoring the signed-out account.
|
||||
7. Reapprove, then revoke in website account settings or use website logout. Confirm access is refused promptly and no automatic browser opens. Explicit sign-in is required.
|
||||
8. Switch accounts/server; confirm associations and identity never cross scopes. Verify settings come from the normal user's AppData/DPAPI context, not a Codex-private profile.
|
||||
9. Use the existing import wizard explicitly to confirm manuscript transfer still works. Startup/renewal alone must never start an import/AI analysis.
|
||||
|
||||
Native DPAPI, Windows logon startup, Word runtime behaviour and visual qualification remain for the user. No installer/system configuration or installed software was modified on Atlas; no Production changes are authorised or performed.
|
||||
|
||||
Deployment, backup and live Development verification are recorded below after delivery.
|
||||
@ -1,3 +1,9 @@
|
||||
# Persistent authorisation correction — current handover
|
||||
|
||||
Read [Persistent authorisation](../Persistent-Authorisation.md) before the older handovers below. Source version **1.0.0.14** adds protected installation approval, automatic renewal/reconnection and persistent account-scoped associations/preferences. The fetched Windows **21f9eac / 1.0.0.13** qualification and installer baseline are preserved. Windows installation and live DPAPI/Word qualification remain with the author; do not repeatedly rebuild installers, install software, or use Computer Use during an unattended pass. One first-time approval after this upgrade is required because version13 never stored installation approval.
|
||||
|
||||
---
|
||||
|
||||
# Current integration handover — 6 November
|
||||
|
||||
Read [the native integration correction report](../2026-11-06-native-integration-correction.md) first. It supersedes the historical version12 UI/workflow instructions below: current application source is **1.0.0.13**, with manuscript import owned by the existing website wizard and a simplified tray. Do not restore the duplicate tray analyser or redesign the managed UI on Windows.
|
||||
|
||||
@ -0,0 +1,91 @@
|
||||
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(){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 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;snapshot=JsonSerializer.Deserialize<CompanionState>(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))await Post<HeartbeatReply>("api/native-companion/heartbeat",new{},authenticationContext);}}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<retryAfter)throw new InvalidOperationException("Reconnecting automatically. Retry when connected.");active=saved.Active;expected=authenticationContext;if(active.Pending==null){credentialVersion++;active.Pending=new(){NextCredential=Convert.ToHexString(RandomNumberGenerator.GetBytes(32)),RotationId=Guid.NewGuid(),ConnectionId=connectionId};}pending=active.Pending;health.State="Reconnecting";}
|
||||
// Write pending rotation before sending: a crash/lost response can retry exactly the same operation.
|
||||
await FlushSettingsAsync();var result=await CredentialRequest("renew",active);
|
||||
if(result.Status==HttpStatusCode.Unauthorized){await RequireApproval(expected,active);throw new InvalidOperationException("Installation approval is invalid or revoked. Sign in again.");}
|
||||
if(result.Tokens==null)throw new HttpRequestException("Connection renewal unavailable.");var reply=result.Tokens;
|
||||
if(reply.InstallationId!=active.InstallationId||reply.AccountId!=active.AccountId||reply.ConnectionId!=pending.ConnectionId||reply.ExpiresUtc<=Now||string.IsNullOrEmpty(reply.AccessToken))throw new InvalidDataException("Renewal did not match this server/account installation.");
|
||||
lock(gate){if(disposed||authenticationContext!=expected||saved.Active!=active)throw new InvalidOperationException("Connection/account changed.");credentialVersion++;active.Credential=pending.NextCredential;active.Pending=null;active.RefreshExpiresUtc=reply.RefreshExpiresUtc;active.AccountName=reply.AccountName;saved.AccountName=reply.AccountName;}
|
||||
await FlushSettingsAsync();
|
||||
// Complete a crashed prior process's rotation, then rotate again for this process's connection identity.
|
||||
if(reply.ConnectionId!=connectionId)continue;
|
||||
lock(gate){if(disposed||authenticationContext!=expected||saved.Active!=active)throw new InvalidOperationException("Connection/account changed.");token=reply.AccessToken;accessExpires=reply.ExpiresUtc;health.ExpiresUtc=reply.ExpiresUtc.UtcDateTime;health.AccountName=reply.AccountName;health.Authentication="verified";health.Server="checking";health.State="Reconnecting";nextCheck=DateTime.MinValue;retryFailures=0;retryAfter=DateTimeOffset.MinValue;}return;
|
||||
}
|
||||
}finally{renewal.Release();}
|
||||
}
|
||||
private async Task RequireApproval(Guid context,TrustedInstallation active)
|
||||
{
|
||||
lock(gate){if(context!=authenticationContext||saved.Active!=active)return;if(saved.Revocations.Count<16)saved.Revocations.Add(active);saved.Active=null;credentialVersion++;token=null;books=[];authenticationContext=Guid.NewGuid();health.State="Action required";health.Authentication="revoked";state="Installation approval expired or was revoked. Sign in again.";health.Explanation=state;}
|
||||
await FlushSettingsAsync();
|
||||
}
|
||||
private async Task<(HttpStatusCode Status,TokenReply? Tokens)> 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<TokenReply>(buffer,Json,stop.Token));
|
||||
}
|
||||
private async Task DrainRevocations()
|
||||
{
|
||||
TrustedInstallation[] pending;lock(gate){if(Now<revocationAfter)return;pending=saved.Revocations.ToArray();revocationAfter=Now.AddSeconds(30);}foreach(var item in pending){try{var response=await CredentialRequest("revoke",item);if((int)response.Status is >=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);
|
||||
}
|
||||
@ -9,8 +9,8 @@ using PlotDirector.Companion.Protocol;
|
||||
|
||||
namespace PlotDirector.Companion.Agent;
|
||||
|
||||
// All browser launching, HTTP and credentials stay in the agent. Tokens are memory-only.
|
||||
public sealed class CloudGateway : IDisposable
|
||||
// Network/authentication stay in the agent. Access tokens are memory-only; installation credentials use Windows-protected storage.
|
||||
public sealed partial class CloudGateway : IDisposable
|
||||
{
|
||||
private readonly object gate=new();
|
||||
private readonly HttpClient http;
|
||||
@ -26,10 +26,10 @@ public sealed class CloudGateway : IDisposable
|
||||
private CompanionBook[] books=[];
|
||||
private readonly string? settingsPath;
|
||||
private static readonly JsonSerializerOptions Json=new(JsonSerializerDefaults.Web);
|
||||
public CloudGateway(HttpMessageHandler? handler=null,Action<string>? browser=null,string? settingsPath=null)
|
||||
public CloudGateway(HttpMessageHandler? handler=null,Action<string>? browser=null,string? settingsPath=null,ICompanionStateStore? stateStore=null,TimeProvider? timeProvider=null)
|
||||
{
|
||||
http=new(handler??new HttpClientHandler{AllowAutoRedirect=false}){Timeout=TimeSpan.FromMinutes(6)};
|
||||
openBrowser=browser??(url=>Process.Start(new ProcessStartInfo(url){UseShellExecute=true}));this.settingsPath=settingsPath;
|
||||
openBrowser=browser??(url=>Process.Start(new ProcessStartInfo(url){UseShellExecute=true}));this.settingsPath=settingsPath;clock=timeProvider??TimeProvider.System;storage=stateStore??(settingsPath!=null&&OperatingSystem.IsWindows()?new ProtectedCompanionStateStore(Path.Combine(Path.GetDirectoryName(settingsPath)!,"installation-state.dat"),new WindowsUserProtection()):null);RestoreState();
|
||||
}
|
||||
public static Uri ValidateOrigin(string value)
|
||||
{
|
||||
@ -39,31 +39,35 @@ public sealed class CloudGateway : IDisposable
|
||||
public Message Status()
|
||||
{
|
||||
bool refresh;Message answer;
|
||||
lock(gate){Expire();refresh=token!=null&&DateTime.UtcNow>=nextCheck;answer=new(){Status=state,Books=books,AuthenticationContext=authenticationContext,ServerUrl=origin?.AbsoluteUri??ReadOrigin(),Health=CopyHealth()};}
|
||||
lock(gate){Expire();refresh=token!=null&&Now.UtcDateTime>=nextCheck;answer=new(){Status=state,Books=books,AuthenticationContext=authenticationContext,ServerUrl=origin?.AbsoluteUri??ReadOrigin(),Health=CopyHealth()};}
|
||||
if(refresh)_=CheckConnection();return answer;
|
||||
}
|
||||
private ConnectionHealth CopyHealth()=>new(){Server=health.Server,Authentication=health.Authentication,Ai=health.Ai,Explanation=health.Explanation,VerifiedUtc=health.VerifiedUtc,ExpiresUtc=health.ExpiresUtc};
|
||||
private void Expire(){if(token!=null&&health.ExpiresUtc!=default&&DateTime.UtcNow>=health.ExpiresUtc){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";health.Ai="unknown";}}
|
||||
private ConnectionHealth CopyHealth()=>new(){State=health.State,AccountName=health.AccountName,Server=health.Server,Authentication=health.Authentication,Ai=health.Ai,Explanation=health.Explanation,VerifiedUtc=health.VerifiedUtc,ExpiresUtc=health.ExpiresUtc};
|
||||
private void Expire(){if(token!=null&&health.ExpiresUtc!=default&&Now.UtcDateTime>=health.ExpiresUtc){InvalidateAccess(authenticationContext);health.Ai="unknown";}}
|
||||
public async Task CheckConnection()
|
||||
{
|
||||
if(Interlocked.Exchange(ref checking,1)!=0)return;
|
||||
Guid context;lock(gate){context=authenticationContext;nextCheck=DateTime.UtcNow.AddMinutes(2);health.Server="checking";}
|
||||
try{var result=await Get<ConnectionHealth>("api/native-companion/connection",context);var accessible=await Get<CompanionBook[]>("api/native-companion/books",context);lock(gate)if(authenticationContext==context){books=accessible.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).ToArray();result.VerifiedUtc=DateTime.UtcNow;health=result;state="Signed in (verified)";}}
|
||||
catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException){lock(gate)if(authenticationContext==context){health.Server=token==null?"unknown":"offline";health.Explanation="Server verification failed. Check connection; local detection remains available.";}}
|
||||
Guid context;lock(gate){context=authenticationContext;nextCheck=Now.UtcDateTime.AddMinutes(2);health.Server="checking";}
|
||||
try{var result=await Get<ConnectionHealth>("api/native-companion/connection",context);var accessible=await Get<CompanionBook[]>("api/native-companion/books",context);lock(gate)if(authenticationContext==context){books=accessible.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).ToArray();result.VerifiedUtc=Now.UtcDateTime;result.State="Connected";result.AccountName=saved.AccountName;health=result;state="Signed in (verified)";retryFailures=0;retryAfter=DateTimeOffset.MinValue;}}
|
||||
catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException){lock(gate)if(authenticationContext==context){health.Server=token==null?"unknown":"offline";health.State=saved.Active!=null?"Reconnecting":"Action required";health.Explanation=saved.Active!=null?"Server unavailable. Reconnecting automatically; Word remains available.":"Sign in or check the server address.";if(e is CompanionStorageException)ConnectionFailure(e);else if(saved.Active!=null)TransientFailure();}}
|
||||
finally{Volatile.Write(ref checking,0);}
|
||||
}
|
||||
private string ReadOrigin(){try{return settingsPath!=null&&File.Exists(settingsPath)?File.ReadAllText(settingsPath):"";}catch(IOException){return "";}}
|
||||
public void Connect(string address)
|
||||
private string ReadOrigin(){try{return !string.IsNullOrEmpty(saved.Server)?saved.Server:settingsPath!=null&&File.Exists(settingsPath)?File.ReadAllText(settingsPath):"";}catch(IOException){return "";}}
|
||||
public void Connect(string address,bool forcePairing=false)
|
||||
{
|
||||
var uri=ValidateOrigin(address);DisconnectPresence();CancellationTokenSource stop;
|
||||
lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;authenticationContext=Guid.NewGuid();token=null;books=[];health=new(){Server="connecting",Authentication="pending"};state="Starting browser sign-in…";}
|
||||
var uri=ValidateOrigin(address);
|
||||
if(storage!=null&&!stateLoaded){RestoreState();if(storageUnavailable)throw new InvalidOperationException("Protected settings are unavailable or another Windows session owns the Companion. Close that Companion or fix the user profile first.");if(!stateLoaded)stateLoaded=true;}
|
||||
lock(gate){if(!forcePairing&&saved.Active!=null&&ValidateOrigin(saved.Active.Site)==uri){_=ReconnectAsync();return;}if(saved.Revocations.Count>=15)throw new InvalidOperationException("Reconnect to complete pending sign-outs before approving another account.");}
|
||||
if(saved.Active!=null){ChangeAccount(address);return;}
|
||||
DisconnectPresence();CancellationTokenSource stop;
|
||||
lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;authenticationContext=Guid.NewGuid();token=null;books=[];health=new(){Server="connecting",Authentication="pending",State="Action required"};state="Starting browser sign-in…";}
|
||||
_=Task.Run(async()=>{
|
||||
try
|
||||
{
|
||||
if(settingsPath!=null){Directory.CreateDirectory(Path.GetDirectoryName(settingsPath)!);await File.WriteAllTextAsync(settingsPath,uri.AbsoluteUri,stop.Token);}
|
||||
var verifier=Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
|
||||
using var start=await http.PostAsJsonAsync(new Uri(uri,"api/native-companion/pair"),new{challenge},stop.Token);start.EnsureSuccessStatusCode();
|
||||
using var start=await http.PostAsJsonAsync(new Uri(uri,"api/native-companion/pair"),new{challenge,persistent=storage!=null,connectionId,deviceName=Environment.MachineName},stop.Token);start.EnsureSuccessStatusCode();
|
||||
var data=await start.Content.ReadFromJsonAsync<PairStart>(Json,stop.Token)??throw new InvalidDataException();
|
||||
if(data.Code==null||data.Code.Length!=24||!data.Code.All(Uri.IsHexDigit))throw new InvalidDataException();
|
||||
lock(gate)if(pairing==stop)state="Approve in browser · code "+data.Code[^6..];
|
||||
@ -74,22 +78,29 @@ public sealed class CloudGateway : IDisposable
|
||||
using var response=await http.PostAsJsonAsync(new Uri(uri,"api/native-companion/token"),new{code=data.Code,verifier},stop.Token);
|
||||
if(response.StatusCode==HttpStatusCode.Accepted)continue;
|
||||
response.EnsureSuccessStatusCode();var grant=await response.Content.ReadFromJsonAsync<TokenReply>(Json,stop.Token)??throw new InvalidDataException();
|
||||
if(storage!=null){
|
||||
if(grant.InstallationId==Guid.Empty||grant.AccountId<=0||grant.ConnectionId!=connectionId||grant.DeviceSecret==null||grant.DeviceSecret.Length!=64||!grant.DeviceSecret.All(Uri.IsHexDigit)||string.IsNullOrEmpty(grant.AccessToken)||grant.ExpiresUtc<=Now)throw new InvalidDataException("Update PlotDirector for persistent Companion approval.");
|
||||
lock(gate){if(pairing!=stop||stop.IsCancellationRequested||disposed)return;credentialVersion++;saved.Server=uri.AbsoluteUri;saved.AccountId=grant.AccountId;saved.AccountName=grant.AccountName;saved.Active=new(){InstallationId=grant.InstallationId,AccountId=grant.AccountId,AccountName=grant.AccountName,Site=uri.AbsoluteUri,Credential=grant.DeviceSecret,RefreshExpiresUtc=grant.RefreshExpiresUtc};token=grant.AccessToken;accessExpires=grant.ExpiresUtc;health.ExpiresUtc=grant.ExpiresUtc.UtcDateTime;health.AccountName=grant.AccountName;}
|
||||
await FlushSettingsAsync();await CheckConnection();return;
|
||||
}
|
||||
using var request=new HttpRequestMessage(HttpMethod.Get,new Uri(uri,"api/native-companion/books"));request.Headers.Authorization=new("Bearer",grant.AccessToken);
|
||||
using var list=await http.SendAsync(request,stop.Token);list.EnsureSuccessStatusCode();
|
||||
var available=await list.Content.ReadFromJsonAsync<CompanionBook[]>(Json,stop.Token)??[];
|
||||
lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";health=new(){Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=DateTime.UtcNow.AddHours(4),Ai="unknown",Explanation="Book list verified; checking AI configuration."};nextCheck=DateTime.MinValue;}
|
||||
lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";health=new(){State="Connected",Server="online",Authentication="verified",VerifiedUtc=Now.UtcDateTime,ExpiresUtc=Now.UtcDateTime.AddHours(4),Ai="unknown",Explanation="Book list verified; checking AI configuration."};nextCheck=DateTime.MinValue;}
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch(Exception e)when(e is HttpRequestException or OperationCanceledException or IOException or InvalidDataException or JsonException or System.ComponentModel.Win32Exception or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
|
||||
{lock(gate)if(pairing==stop){state="Sign-in failed or expired. Check the site address and try Connect again.";health=new(){Server="unverified",Authentication="not-signed-in",Explanation=state};}}
|
||||
catch(Exception e)when(e is HttpRequestException or OperationCanceledException or IOException or InvalidDataException or JsonException or System.ComponentModel.Win32Exception or UnauthorizedAccessException or InvalidOperationException or ArgumentException or CryptographicException)
|
||||
{lock(gate)if(pairing==stop){state="Sign-in failed or expired. Check the site address and try Connect again.";health=new(){State="Action required",Server="unverified",Authentication="not-signed-in",Explanation=state};}}
|
||||
});
|
||||
}
|
||||
public void SignOut(){DisconnectPresence();lock(gate){pairing?.Cancel();pairing=null;authenticationContext=Guid.NewGuid();token=null;books=[];state="Not signed in";health=new();successful.Clear();}}
|
||||
public void SignOut(){_=ObserveSignOut(SignOutAsync());}
|
||||
private async Task ObserveSignOut(Task operation){try{await operation;}catch(Exception e)when(AuthFailure(e)){lock(gate){health.State="Action required";health.Explanation="Sign-out could not be saved securely. Check your Windows user profile and retry.";}}}
|
||||
public bool Allows(Guid context,int bookId)
|
||||
{lock(gate){Expire();return token!=null&&context==authenticationContext&&books.Any(b=>b.BookId==bookId);}}
|
||||
{lock(gate){Expire();return token!=null&&(storage==null||(health.State=="Connected"&&checking==0&&credentialVersion==durableCredentialVersion))&&context==authenticationContext&&books.Any(b=>b.BookId==bookId);}}
|
||||
public async Task<AiChapterResult> Analyse(AiChapterRequest chapter,CancellationToken cancellation,Guid expectedContext)
|
||||
{
|
||||
await EnsureAccess(expectedContext);
|
||||
var fingerprint=expectedContext+":"+chapter.BookId+":"+chapter.ManuscriptId+":"+Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{chapter.ChapterStart,chapter.ChapterEnd,chapter.Paragraphs})));
|
||||
Uri site;string access;
|
||||
lock(gate){Expire();if(successful.TryGetValue(fingerprint,out var prior)&&authenticationContext==expectedContext&&token!=null)return new(){SourceRetained=prior.SourceRetained,RequestId=chapter.RequestId,DocumentRevision=chapter.Revision,ChapterTitle=chapter.ChapterTitle,State="complete",Message="Unchanged chapter: reused saved AI suggestions without uploading prose.",ReviewPath=prior.ReviewPath,Scenes=prior.Scenes};if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");}
|
||||
@ -99,14 +110,14 @@ public sealed class CloudGateway : IDisposable
|
||||
try{responseValue=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation);}
|
||||
catch(HttpRequestException){lock(gate)if(authenticationContext==expectedContext){health.Server="offline";health.Explanation="AI request could not reach the server.";}throw;}
|
||||
using var response=responseValue;
|
||||
if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";health.Server="online";health.Ai="unknown";}throw new InvalidOperationException("Sign-in expired. Connect again.");}
|
||||
if(response.StatusCode==HttpStatusCode.Unauthorized){InvalidateAccess(expectedContext);throw new InvalidOperationException("Connection needs renewal. Retry this explicit analysis after reconnection.");}
|
||||
if(!response.IsSuccessStatusCode){lock(gate)if(authenticationContext==expectedContext){health.Server="degraded";health.Ai="request-failed";health.Explanation="AI request rejected or unavailable; see chapter results.";}throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."});}
|
||||
// Bound server response before deserializing; never log a body/provider message.
|
||||
await using var stream=await response.Content.ReadAsStreamAsync(cancellation);using var buffer=new MemoryStream();var bytes=new byte[8192];
|
||||
int count;while((count=await stream.ReadAsync(bytes,cancellation))>0){if(buffer.Length+count>1024*1024)throw new InvalidDataException("AI response too large.");buffer.Write(bytes,0,count);}
|
||||
buffer.Position=0;var result=await JsonSerializer.DeserializeAsync<AiChapterResult>(buffer,Json,cancellation)??throw new InvalidDataException();
|
||||
if(result.RequestId!=chapter.RequestId||result.State is not ("complete" or "failed" or "cancelled")||result.Message==null||result.Message.Length>2048||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Start<chapter.ChapterStart||s.End>chapter.ChapterEnd||s.End<=s.Start||s.Title==null||s.Reason==null||s.Summary==null||s.Summary.Length>600||s.Confidence==null||s.Confidence.Length>32||s.Kind!="Scene"||s.Origin!="AI"||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping.");
|
||||
lock(gate)if(authenticationContext==expectedContext){health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;health.Ai=result.State=="complete"?"last-request-succeeded":"request-failed";health.Explanation=result.Message;if(result.State=="complete"){if(successful.Count>=64||successful.Values.Sum(r=>r.Scenes.Length)+result.Scenes.Length>8192)successful.Clear();successful[fingerprint]=result;}}
|
||||
lock(gate)if(authenticationContext==expectedContext){health.Server="online";health.Authentication="verified";health.State="Connected";health.VerifiedUtc=Now.UtcDateTime;health.Ai=result.State=="complete"?"last-request-succeeded":"request-failed";health.Explanation=result.Message;if(result.State=="complete"){if(successful.Count>=64||successful.Values.Sum(r=>r.Scenes.Length)+result.Scenes.Length>8192)successful.Clear();successful[fingerprint]=result;}}
|
||||
return result;
|
||||
}
|
||||
public async Task<T> Get<T>(string path,Guid expectedContext)
|
||||
@ -117,21 +128,22 @@ public sealed class CloudGateway : IDisposable
|
||||
public async Task<NativePresence> Capture(ManuscriptCapture capture,Guid context){var result=await Send<NativePresence>(HttpMethod.Post,"api/native-companion/manuscript-capture",capture,context);if(result.CaptureRequestId!=capture.RequestId||result.Revision!=capture.Revision)throw new InvalidDataException("Server did not acknowledge this manuscript capture. Update or reconnect before retrying.");return result;}
|
||||
private async Task<T> Send<T>(HttpMethod method,string path,object? body,Guid context)
|
||||
{
|
||||
await EnsureAccess(context);
|
||||
Uri site;string access;lock(gate){Expire();if(context!=authenticationContext||token==null)throw new InvalidOperationException("Sign in again and reselect the book.");site=origin!;access=token;}
|
||||
using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(path=="api/native-companion/manuscript-capture"?120:15));using var request=new HttpRequestMessage(method,new Uri(site,path));request.Headers.Authorization=new("Bearer",access);if(body!=null)request.Content=JsonContent.Create(body,options:Json);
|
||||
try
|
||||
{
|
||||
using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,stop.Token);
|
||||
if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(authenticationContext==context){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";}throw new InvalidOperationException("Sign-in expired. Connect again.");}
|
||||
if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=DateTime.UtcNow;health.Explanation=$"PlotDirector rejected { (path.EndsWith("/presence",StringComparison.Ordinal)?"document registration":"the request") } (HTTP {(int)response.StatusCode}). Reconnect or check the selected book.";if(response.StatusCode==HttpStatusCode.Forbidden){if(body is NativePresence denied)books=books.Where(b=>b.BookId!=denied.BookId).ToArray();else if(path=="api/native-companion/books")books=[];}}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");}
|
||||
if(response.StatusCode==HttpStatusCode.Unauthorized){InvalidateAccess(context);throw new InvalidOperationException("Connection needs renewal. Retry after Companion reconnects automatically.");}
|
||||
if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=Now.UtcDateTime;health.Explanation=$"PlotDirector rejected { (path.EndsWith("/presence",StringComparison.Ordinal)?"document registration":"the request") } (HTTP {(int)response.StatusCode}). Reconnect or check the selected book.";if(response.StatusCode==HttpStatusCode.Forbidden){if(body is NativePresence denied)books=books.Where(b=>b.BookId!=denied.BookId).ToArray();else if(path=="api/native-companion/books")books=[];}}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");}
|
||||
await using var stream=await response.Content.ReadAsStreamAsync(stop.Token);using var buffer=new MemoryStream();var bytes=new byte[8192];int size;
|
||||
while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0;
|
||||
var result=await JsonSerializer.DeserializeAsync<T>(buffer,Json,stop.Token);
|
||||
lock(gate){if(context!=authenticationContext)throw new InvalidOperationException("Connection changed; discarded old response.");health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;if(path.EndsWith("/presence",StringComparison.Ordinal))health.Explanation="Document heartbeat verified by PlotDirector.";}
|
||||
lock(gate){if(context!=authenticationContext)throw new InvalidOperationException("Connection changed; discarded old response.");health.Server="online";health.Authentication="verified";health.State="Connected";health.VerifiedUtc=Now.UtcDateTime;if(path.EndsWith("/presence",StringComparison.Ordinal))health.Explanation="Document heartbeat verified by PlotDirector.";}
|
||||
return result??throw new InvalidDataException();
|
||||
}
|
||||
catch(OperationCanceledException){lock(gate)if(context==authenticationContext){health.Server="degraded";health.Explanation="Server verification timed out. Check connection before continuing.";}throw;}
|
||||
catch(HttpRequestException){lock(gate)if(context==authenticationContext){health.Server="offline";health.Explanation="Server unreachable. Saved information is not current.";}throw;}
|
||||
catch(OperationCanceledException){lock(gate)if(context==authenticationContext){health.Server="degraded";health.State=saved.Active!=null?"Reconnecting":"Disconnected";health.Explanation="Server verification timed out. Check connection before continuing.";}throw;}
|
||||
catch(HttpRequestException){lock(gate)if(context==authenticationContext){health.Server="offline";health.State=saved.Active!=null?"Reconnecting":"Disconnected";health.Explanation="Server unreachable. Saved information is not current.";}throw;}
|
||||
}
|
||||
public void OpenSavedPage(string path,Guid context)
|
||||
{
|
||||
@ -156,7 +168,7 @@ public sealed class CloudGateway : IDisposable
|
||||
}
|
||||
catch(Exception e)when(e is HttpRequestException or OperationCanceledException){ }
|
||||
}
|
||||
public void Dispose(){SignOut();http.Dispose();}
|
||||
public void Dispose(){lock(gate){disposed=true;pairing?.Cancel();lifetime.Cancel();}try{FlushSettingsAsync().GetAwaiter().GetResult();}catch(Exception e)when(StorageFailure(e)){}http.Dispose();(storage as IDisposable)?.Dispose();}
|
||||
private sealed record PairStart(string Code);
|
||||
private sealed record TokenReply(string AccessToken);
|
||||
private sealed record TokenReply(string AccessToken,DateTimeOffset ExpiresUtc=default,Guid InstallationId=default,int AccountId=0,string AccountName="",DateTimeOffset RefreshExpiresUtc=default,Guid ConnectionId=default,string? DeviceSecret=null);
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ public static class CompanionPresentation
|
||||
public static bool Dark(bool? windowsDark)=>windowsDark??false;
|
||||
public static string Connection(ConnectionHealth? health,DateTime now)
|
||||
{
|
||||
if(!string.IsNullOrEmpty(health?.State))return health.State=="Action required"?"Action required · sign in or check connection settings":health.State;
|
||||
if(health==null)return "Welcome · connect to PlotDirector";
|
||||
if(health.Authentication is "expired" or "unauthorised")return "Sign in again";
|
||||
if(health.Server=="checking")return "Checking your connection…";
|
||||
|
||||
52
PlotDirector.NativeCompanion/Agent/CompanionStateStore.cs
Normal file
52
PlotDirector.NativeCompanion/Agent/CompanionStateStore.cs
Normal file
@ -0,0 +1,52 @@
|
||||
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;}=880;public int Height {get;set;}=820;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;}}
|
||||
}
|
||||
@ -7,7 +7,7 @@ internal static class TrayApplication
|
||||
{
|
||||
public static int Run(string[] args)
|
||||
{
|
||||
var directory=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"PlotDirector","Companion");Directory.CreateDirectory(directory);
|
||||
var directory=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"PlotDirector","Companion");Directory.CreateDirectory(directory);if(File.Exists(Path.Combine(directory,"paused")))File.Delete(Path.Combine(directory,"paused"));
|
||||
var endpoint=AgentEndpoint.CurrentUserPipeName();FileStream singleton;
|
||||
try{singleton=new(Path.Combine(directory,"agent-"+System.Diagnostics.Process.GetCurrentProcess().SessionId+".lock"),FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);}
|
||||
catch(IOException){try{using var pipe=new NamedPipeClientStream(".",endpoint+".activate",PipeDirection.Out,PipeOptions.CurrentUserOnly);pipe.Connect(2000);pipe.WriteByte(1);}catch(IOException){}catch(TimeoutException){}return 0;}
|
||||
@ -17,10 +17,10 @@ internal static class TrayApplication
|
||||
using var window=new CompanionWindow(control,cloud,shutdown,directory);var handle=window.Handle;
|
||||
control.OpenRequested+=()=>{if(!window.IsDisposed)window.BeginInvoke(new Action(window.Reveal));};
|
||||
var host=new PipeHost(endpoint,sessions,log.Write,control);var serve=host.RunAsync(shutdown.Token);
|
||||
var work=control.Tick(shutdown.Token);var heartbeat=control.Heartbeat(shutdown.Token);
|
||||
var reconnect=cloud.RunConnectionLoop(shutdown.Token);var work=control.Tick(shutdown.Token);var heartbeat=control.Heartbeat(shutdown.Token);
|
||||
var activate=Task.Run(async()=>{while(!shutdown.IsCancellationRequested){await using var pipe=new NamedPipeServerStream(endpoint+".activate",PipeDirection.In,1,PipeTransmissionMode.Byte,PipeOptions.Asynchronous|PipeOptions.CurrentUserOnly);await pipe.WaitForConnectionAsync(shutdown.Token);var value=new byte[1];if(await pipe.ReadAsync(value,shutdown.Token)>0)window.BeginInvoke(new Action(window.Reveal));}});
|
||||
log.Write("tray-start publisher=Nick-Beckley");if(args.Contains("--open"))window.Reveal();
|
||||
Application.Run();shutdown.Cancel();try{Task.WhenAll(serve,work,heartbeat,activate).Wait(TimeSpan.FromSeconds(3));}catch(AggregateException){}log.Write("tray-stop");
|
||||
Application.Run();shutdown.Cancel();try{Task.WhenAll(serve,work,heartbeat,activate,reconnect).Wait(TimeSpan.FromSeconds(3));}catch(AggregateException){}cloud.StopAsync().GetAwaiter().GetResult();log.Write("tray-stop");
|
||||
}return 0;
|
||||
}
|
||||
}
|
||||
@ -45,7 +45,7 @@ internal sealed class CompanionWindow:Form
|
||||
public CompanionWindow(TrayCoordinator control,CloudGateway cloud,CancellationTokenSource shutdown,string directory)
|
||||
{
|
||||
this.control=control;this.cloud=cloud;this.shutdown=shutdown;this.directory=directory;
|
||||
Icon=brand;Text="PlotDirector Companion";Font=new("Segoe UI",10);BackColor=Color.FromArgb(249,246,240);ForeColor=Color.FromArgb(58,49,44);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new(660,640);Size=new(880,820);DoubleBuffered=true;
|
||||
Icon=brand;Text="PlotDirector Companion";Font=new("Segoe UI",10);BackColor=Color.FromArgb(249,246,240);ForeColor=Color.FromArgb(58,49,44);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new(660,640);Size=new(Math.Clamp(cloud.Preferences.Width,660,4096),Math.Clamp(cloud.Preferences.Height,640,2160));DoubleBuffered=true;remember.Checked=cloud.Preferences.RememberInDocument;ResizeEnd+=(_,_)=>SavePreferences();remember.CheckedChanged+=(_,_)=>{if(!refreshing)SavePreferences();};
|
||||
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new(24),ColumnCount=1,RowCount=8};layout.ColumnStyles.Add(new(SizeType.Percent,100));for(int i=0;i<8;i++)layout.RowStyles.Add(new(i==6?SizeType.Percent:SizeType.AutoSize,i==6?100:0));
|
||||
var header=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,WrapContents=true};
|
||||
header.Controls.Add(new Label{Text="PlotDirector",Font=new("Segoe UI",22,FontStyle.Bold),AutoSize=true,Margin=new(0,0,20,12)});
|
||||
@ -66,11 +66,11 @@ internal sealed class CompanionWindow:Form
|
||||
var settingsLayout=new TableLayoutPanel{Dock=DockStyle.Fill,ColumnCount=1,RowCount=4};settingsLayout.RowStyles.Add(new(SizeType.AutoSize));settingsLayout.RowStyles.Add(new(SizeType.AutoSize));settingsLayout.RowStyles.Add(new(SizeType.Percent,100));settingsLayout.RowStyles.Add(new(SizeType.AutoSize));settingsLayout.ColumnStyles.Add(new(SizeType.Percent,100));
|
||||
settingsLayout.Controls.Add(new Label{Text="Your PlotDirector website · enter its HTTPS address, then approve sign-in in your browser.",AutoSize=true,Dock=DockStyle.Fill});
|
||||
var connection=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2};connection.ColumnStyles.Add(new(SizeType.Percent,100));connection.ColumnStyles.Add(new(SizeType.AutoSize));connection.Controls.Add(site,0,0);connection.Controls.Add(Button("Connect / Sign in",()=>cloud.Connect(site.Text.Trim())),1,0);settingsLayout.Controls.Add(connection);settingsLayout.Controls.Add(diagnostics);
|
||||
var options=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};options.Controls.AddRange([Button("Check connection",()=>_ = cloud.CheckConnection()),Button("Sign out",()=>cloud.SignOut()),Button("Open support folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true}))]);settingsLayout.Controls.Add(options);settings.Controls.Add(settingsLayout);tabs.TabPages.Add(settings);layout.Controls.Add(tabs,0,6);
|
||||
var options=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};options.Controls.AddRange([Button("Check connection",()=>_ = cloud.ReconnectAsync()),Button("Change account",()=>cloud.ChangeAccount(site.Text.Trim())),Button("Sign out",()=>cloud.SignOut()),Button("Open support folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true}))]);settingsLayout.Controls.Add(options);settings.Controls.Add(settingsLayout);tabs.TabPages.Add(settings);layout.Controls.Add(tabs,0,6);
|
||||
layout.Controls.Add(new Label{AutoSize=true,Dock=DockStyle.Fill,Padding=new(0,12,0,0),Text="Import, analysis, Context and Intent are available in PlotDirector. Word text changes only through your own authoring actions."},0,7);Controls.Add(layout);
|
||||
tips.SetToolTip(analyse,"Choose a linked book and select chapters first. Sends prose only after you confirm.");tips.SetToolTip(review,"Open saved scene suggestions and approve them before importing.");tips.SetToolTip(detect,"Reads Heading 1 chapter boundaries without changing your words.");
|
||||
ApplyTheme();Microsoft.Win32.SystemEvents.UserPreferenceChanged+=OnPreferences;
|
||||
documents.SelectedIndexChanged+=(_,_)=>{if(!refreshing&&documents.SelectedItem is TrayDocument d){selected=d.Session;chapterKey="";RefreshState();}};
|
||||
documents.SelectedIndexChanged+=(_,_)=>{if(!refreshing&&documents.SelectedItem is TrayDocument d){selected=d.Session;chapterKey="";SavePreferences();RefreshState();}};
|
||||
chapters.DoubleClick+=(_,_)=>{if(chapters.SelectedItem is ChapterItem chapter)Safe(()=>control.Navigate(selected,chapter.Start));};
|
||||
chapters.ItemCheck+=(_,e)=>{if(refreshing||renderedSession==Guid.Empty)return;if(!selections.TryGetValue(renderedSession,out var chosen)){if(selections.Count>=64)selections.Clear();selections[renderedSession]=chosen=[];}var start=((ChapterItem)chapters.Items[e.Index]).Start;if(e.NewValue==CheckState.Checked)chosen.Add(start);else chosen.Remove(start);};
|
||||
detect.Click+=(_,_)=>Safe(()=>control.Detect(selected));cancel.Click+=(_,_)=>Safe(()=>control.Cancel(selected));
|
||||
@ -81,18 +81,19 @@ internal sealed class CompanionWindow:Form
|
||||
tray=new(){Icon=brand,Text="PlotDirector Companion",ContextMenuStrip=menu,Visible=true};tray.DoubleClick+=(_,_)=>Reveal();FormClosing+=(_,e)=>{if(!exiting){e.Cancel=true;Hide();}};timer.Tick+=(_,_)=>RefreshState();timer.Start();RefreshState();
|
||||
}
|
||||
private Button Button(string text,Action action){var button=new Button{Text=text,AutoSize=true};button.Click+=(_,_)=>Safe(action);return button;}
|
||||
private void SavePreferences(){var size=WindowState==FormWindowState.Normal?Size:RestoreBounds.Size;cloud.SavePreferences(new(){Width=size.Width,Height=size.Height,RememberInDocument=remember.Checked,LastManuscript=Current?.Manuscript??Guid.Empty});}
|
||||
private void Safe(Action action){try{error="";action();}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){error=e.Message;}RefreshState();}
|
||||
private void Open(string page){if(Current==null)cloud.OpenSite(page);else control.OpenPage(selected,page);}
|
||||
public void Reveal(){Show();WindowState=FormWindowState.Normal;Activate();}
|
||||
private void RefreshState()
|
||||
{
|
||||
var state=cloud.Status();var docs=control.PresentationDocuments;displayedDocuments=docs;var key=string.Join("|",docs.Select(d=>d.Session+":"+d.Title+":"+d.Active));refreshing=true;
|
||||
try{if(key!=documentKey){documentKey=key;documents.DataSource=docs;if(!docs.Any(d=>d.Session==selected))selected=docs.FirstOrDefault(d=>d.Active)?.Session??docs.FirstOrDefault()?.Session??Guid.Empty;documents.SelectedItem=docs.FirstOrDefault(d=>d.Session==selected);}
|
||||
try{if(key!=documentKey){documentKey=key;documents.DataSource=docs;if(!docs.Any(d=>d.Session==selected))selected=docs.FirstOrDefault(d=>d.Active)?.Session??docs.FirstOrDefault(d=>d.Manuscript==cloud.Preferences.LastManuscript)?.Session??docs.FirstOrDefault()?.Session??Guid.Empty;documents.SelectedItem=docs.FirstOrDefault(d=>d.Session==selected);}
|
||||
var bkey=state.AuthenticationContext+string.Join("|",state.Books.Select(b=>b.BookId+":"+b.Title));if(bookKey!=bkey){bookKey=bkey;books.DataSource=state.Books;books.SelectedIndex=-1;displayedBook=-1;}
|
||||
var d=Current;if(displayedSession!=selected||displayedBook!=(d?.Book??0)){displayedSession=selected;displayedBook=d?.Book??0;books.SelectedItem=state.Books.FirstOrDefault(b=>b.BookId==d?.Book);}
|
||||
if(string.IsNullOrWhiteSpace(site.Text)&&!string.IsNullOrEmpty(state.ServerUrl))site.Text=state.ServerUrl;
|
||||
var server=state.Health==null?"unknown":DateTime.UtcNow-state.Health.VerifiedUtc>TimeSpan.FromSeconds(90)&&state.Health.Server=="online"?"unverified (check connection)":state.Health.Server;
|
||||
SetText(status,CompanionPresentation.Connection(state.Health,DateTime.UtcNow)+" · "+(d==null?"Word not connected":d.Book==0?"Word available locally · link a book":!string.IsNullOrEmpty(d.LastPresenceKey)&&DateTime.UtcNow-d.LastPresenceUtc<TimeSpan.FromSeconds(45)?"Word document registered with PlotDirector":"Word available locally · document registration pending"));
|
||||
SetText(status,CompanionPresentation.Connection(state.Health,DateTime.UtcNow)+(string.IsNullOrEmpty(state.Health?.AccountName)?"":" · "+state.Health.AccountName)+" · "+(d==null?"Word not connected":d.Book==0?"Word available locally · link a book":!string.IsNullOrEmpty(d.LastPresenceKey)&&DateTime.UtcNow-d.LastPresenceUtc<TimeSpan.FromSeconds(45)?"Word document registered with PlotDirector":"Word available locally · document registration pending"));
|
||||
SetText(nextStep,d==null?"Open a manuscript in Word to begin.":d.Book==0?"Choose the PlotDirector book for this manuscript.":"Use Import manuscript in PlotDirector. Open Context and Intent from the website writing workspace.");
|
||||
SetText(progressText,string.IsNullOrEmpty(error)?(d?.Status??"Waiting for your manuscript.")+(d==null?"":"\r\n"+(d.WordSaved==true?"Word reports saved.":d.WordSaved==false?"Word has unsaved changes.":"Word save state not yet reported.")+(d.AcceptedRevision==d.Revision?" PlotDirector acknowledged this captured revision.":" This revision has not been acknowledged by PlotDirector.")):error);progress.Value=Math.Clamp(d?.Progress??0,0,100);
|
||||
detect.Enabled=d!=null&&d.Job==Guid.Empty;analyse.Enabled=d!=null&&d.Book>0&&d.Chapters.Length>0&&d.Job==Guid.Empty&&d.Pending.Count==0&&state.Health?.Authentication=="verified"&&state.Health?.Ai is not ("not-configured" or "not-entitled");cancel.Enabled=d!=null&&(d.Job!=Guid.Empty||d.Pending.Count>0);bookButton.Enabled=d!=null&&state.Books.Length>0&&d.Job==Guid.Empty;review.Enabled=d?.Book>0;contextAction.Enabled=intentAction.Enabled=d?.Book>0;
|
||||
@ -119,7 +120,7 @@ internal sealed class CompanionWindow:Form
|
||||
var working=d?.Current?.Start==item.Start&&d.Job!=Guid.Empty;
|
||||
TextRenderer.DrawText(e.Graphics,CompanionPresentation.Chapter(working,analysed,d?.FailedChapters.Contains((d.Revision,d.Book,item.Start))==true),Font,new Rectangle(e.Bounds.Left+Px(32),e.Bounds.Top+Px(28),e.Bounds.Width-Px(40),Px(22)),ink,TextFormatFlags.EndEllipsis|TextFormatFlags.SingleLine);e.DrawFocusRectangle();
|
||||
}
|
||||
private void Exit(){exiting=true;File.WriteAllText(Path.Combine(directory,"paused"),"User exited Companion");shutdown.Cancel();tray.Visible=false;Application.Exit();}
|
||||
private void Exit(){SavePreferences();exiting=true;File.WriteAllText(Path.Combine(directory,"paused"),"User exited Companion");shutdown.Cancel();tray.Visible=false;Application.Exit();}
|
||||
protected override void Dispose(bool disposing){if(disposing){Microsoft.Win32.SystemEvents.UserPreferenceChanged-=OnPreferences;timer.Dispose();tips.Dispose();tray.Dispose();brand.Dispose();}base.Dispose(disposing);}
|
||||
private static Icon CreateBrandIcon()
|
||||
{
|
||||
|
||||
@ -57,7 +57,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
public void Detect(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Completed.Clear();doc.FailedChapters.Clear();doc.Status="Reading chapters in bounded Word batches…";doc.Progress=0;Queue(doc,new(){Kind="detect"});}}
|
||||
public void SelectBook(Guid session,int book,bool remember)
|
||||
{
|
||||
lock(gate){if(!documents.TryGetValue(session,out var doc))return;var state=cloud.Status();if(!cloud.Allows(state.AuthenticationContext,book))throw new InvalidOperationException("Sign in and select an authorised book.");Cancel(doc);doc.Book=book;doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";doc.Authentication=state.AuthenticationContext;lastBook=book;lastAuthentication=doc.Authentication;doc.Status=remember?"Remember requested; save Word normally after confirmation.":"Book selected for this session.";
|
||||
lock(gate){if(!documents.TryGetValue(session,out var doc))return;var state=cloud.Status();if(!cloud.Allows(state.AuthenticationContext,book))throw new InvalidOperationException("Sign in and select an authorised book.");Cancel(doc);doc.Book=book;cloud.RememberBinding(doc.Manuscript,book,state.AuthenticationContext);doc.ChapterId=null;doc.SceneId=null;doc.LastPresenceKey="";doc.Authentication=state.AuthenticationContext;lastBook=book;lastAuthentication=doc.Authentication;doc.Status=remember?"Remember requested; save Word normally after confirmation.":"Book association saved for this Windows user and PlotDirector account.";
|
||||
Queue(doc,new(){Kind="associate",BookId=book,AuthenticationContext=doc.Authentication,Site=state.ServerUrl,Remember=remember});}
|
||||
}
|
||||
public void Analyse(Guid session,IEnumerable<int> starts)
|
||||
@ -85,7 +85,8 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
|
||||
{
|
||||
while(!cancellation.IsCancellationRequested){await Task.Delay(500,cancellation);lock(gate){var cloudState=cloud.Status();foreach(var doc in documents.Values){
|
||||
if(doc.Authentication!=cloudState.AuthenticationContext){Cancel(doc);doc.Book=0;doc.Completed.Clear();doc.FailedChapters.Clear();doc.Authentication=cloudState.AuthenticationContext;}
|
||||
if(doc.Book>0&&!cloud.Allows(doc.Authentication,doc.Book)){Cancel(doc);doc.Book=0;doc.Status="Book access is no longer verified. Reconnect and select an authorised book.";}
|
||||
if(doc.Book>0&&cloudState.Health?.Authentication=="verified"&&cloudState.Health.State=="Connected"&&!cloudState.Books.Any(b=>b.BookId==doc.Book)){Cancel(doc);doc.Book=0;doc.Status="Book access is no longer verified. Reconnect and select an authorised book.";}
|
||||
if(doc.Book==0&&cloud.RestoreBinding(doc.Manuscript) is int localBook){doc.Book=localBook;doc.Authentication=cloudState.AuthenticationContext;lastBook=localBook;lastAuthentication=doc.Authentication;}
|
||||
if(doc.Book==0&&DocumentBindingRestore(doc,cloudState)) {doc.Book=doc.RememberedBook!.Value;doc.Authentication=cloudState.AuthenticationContext;lastBook=doc.Book;lastAuthentication=doc.Authentication;}
|
||||
if(doc.Job==Guid.Empty){if(doc.Pending.Count>0&&!documents.Values.Any(other=>other.Job!=Guid.Empty))Next(doc);continue;}var result=ai.Result(doc.Session);
|
||||
if(result?.RequestId==doc.Job&&result.State is "complete" or "failed" or "cancelled"){
|
||||
|
||||
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.13</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.14</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
@ -4,6 +4,8 @@ namespace PlotDirector.Companion.Protocol;
|
||||
[DataContract]
|
||||
public sealed class ConnectionHealth
|
||||
{
|
||||
[DataMember] public string State {get;set;}="";
|
||||
[DataMember] public string AccountName {get;set;}="";
|
||||
[DataMember] public string Server {get;set;}="unknown";
|
||||
[DataMember] public string Authentication {get;set;}="signed-out";
|
||||
[DataMember] public string Ai {get;set;}="unknown";
|
||||
|
||||
@ -0,0 +1,89 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using PlotDirector.Companion.Agent;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
internal static class PersistentConnectionTests
|
||||
{
|
||||
public static async Task Run(Action<bool,string> check)
|
||||
{
|
||||
var clock=new Clock();var server=new Server(clock);var store=new MemoryStore();int approvals=0;var manuscript=Guid.NewGuid();
|
||||
using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){
|
||||
cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Health?.State=="Connected");
|
||||
cloud.RememberBinding(manuscript,3);cloud.SavePreferences(new(){Width=975,Height=725,RememberInDocument=true,LastManuscript=manuscript});await cloud.FlushSettingsAsync();
|
||||
check(approvals==1&&store.Load().Active!=null,"first pairing saves approved installation, not a four-hour-only sign-in");
|
||||
check(!JsonSerializer.Serialize(store.Load()).Contains("access:"),"short-lived access tokens are never persisted in settings");
|
||||
}
|
||||
check(!server.Revoked&&store.Load().Active!=null,"normal process disposal preserves trust and settings");
|
||||
server.Offline=true;using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){
|
||||
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;
|
||||
check(approvals==1&&cloud.RestoreBinding(manuscript)==3&&cloud.Preferences.Width==975&&cloud.Preferences.RememberInDocument,"process/network recovery restores scoped association and preferences without interaction");
|
||||
var context=cloud.Status().AuthenticationContext;clock.Advance(TimeSpan.FromMinutes(11));await cloud.ReconnectAsync();
|
||||
check(cloud.Status().AuthenticationContext==context&&cloud.Status().Health?.State=="Connected"&&approvals==1,"access expiry renews without changing account context or asking for browser approval");
|
||||
server.AllowBook=false;await cloud.CheckConnection();check(cloud.RestoreBinding(manuscript)==null,"persisted association is not restored when current book permission is missing");server.AllowBook=true;await cloud.CheckConnection();
|
||||
server.LoseRenewalResponse=true;clock.Advance(TimeSpan.FromMinutes(11));await cloud.ReconnectAsync();check(store.Load().Active?.Pending!=null,"lost renewal response retains the exact pending rotation securely for recovery");
|
||||
}
|
||||
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");
|
||||
}
|
||||
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");
|
||||
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");
|
||||
}
|
||||
check(server.ProseRequests==0,"startup, renewal, settings, reconnect and sign-out never upload manuscript prose");
|
||||
await ProtectedFiles(check);
|
||||
}
|
||||
private static async Task ProtectedFiles(Action<bool,string> check)
|
||||
{
|
||||
var root=Path.Combine(Path.GetTempPath(),"pd-protected-state-"+Guid.NewGuid().ToString("N"));Directory.CreateDirectory(root);var path=Path.Combine(root,"state.dat");var key=RandomNumberGenerator.GetBytes(32);var secret=new string('A',64);
|
||||
try{
|
||||
var state=new CompanionState{Server="https://fixture.invalid/",AccountId=7,Active=new(){Site="https://fixture.invalid/",AccountId=7,InstallationId=Guid.NewGuid(),Credential=secret}};
|
||||
using(var file=new ProtectedCompanionStateStore(path,new Protection(key))){file.Save(state);check(!Encoding.UTF8.GetString(File.ReadAllBytes(path)).Contains(secret),"credential files contain protected bytes, never clear credentials");check(file.Load().Active?.Credential==secret,"protected settings round trip through injected protection on Linux");}
|
||||
var original=await File.ReadAllBytesAsync(path);using(var other=new ProtectedCompanionStateStore(path,new Protection(RandomNumberGenerator.GetBytes(32)))){bool refused=false;try{other.Load();}catch(CryptographicException){refused=true;}check(refused,"a different user protection key cannot read saved approval");}
|
||||
var envelope=JsonSerializer.Deserialize<Dictionary<string,JsonElement>>(original)!;var tampered=Encoding.UTF8.GetString(original).Replace("\"Account\":7","\"Account\":8",StringComparison.Ordinal);await File.WriteAllTextAsync(path,tampered);
|
||||
using(var file=new ProtectedCompanionStateStore(path,new Protection(key))){bool refused=false;try{file.Load();}catch(CryptographicException){refused=true;}check(refused,"tampering with the account scope cannot decrypt or redirect an approval");}
|
||||
await File.WriteAllBytesAsync(path,original);using(var file=new ProtectedCompanionStateStore(path,new Protection(key,true))){bool failed=false;try{file.Save(state);}catch(IOException){failed=true;}var persisted=await File.ReadAllBytesAsync(path);check(failed&&original.SequenceEqual(persisted),"failed protected write preserves the previous complete settings file");}
|
||||
if(!OperatingSystem.IsWindows()){bool refused=false;try{new WindowsUserProtection().Protect([1],[2]);}catch(PlatformNotSupportedException){refused=true;}check(refused,"production protection never falls back to plaintext on non-Windows hosts");}
|
||||
}finally{Directory.Delete(root,true);}
|
||||
}
|
||||
private sealed class Protection(byte[] key,bool fail=false):IStateProtection
|
||||
{
|
||||
public byte[] Protect(byte[] clear,byte[] entropy){if(fail)throw new IOException("Synthetic write failure");var nonce=RandomNumberGenerator.GetBytes(12);var encrypted=new byte[clear.Length];var tag=new byte[16];using var aes=new AesGcm(key,16);aes.Encrypt(nonce,clear,encrypted,tag,entropy);return nonce.Concat(tag).Concat(encrypted).ToArray();}
|
||||
public byte[] Unprotect(byte[] cipher,byte[] entropy){var clear=new byte[cipher.Length-28];using var aes=new AesGcm(key,16);aes.Decrypt(cipher[..12],cipher[28..],cipher[12..28],clear,entropy);return clear;}
|
||||
}
|
||||
private sealed class MemoryStore:ICompanionStateStore{private readonly object gate=new();private CompanionState state=new();public CompanionState Load(){lock(gate)return JsonSerializer.Deserialize<CompanionState>(JsonSerializer.Serialize(state))!;}public void Save(CompanionState value){lock(gate)state=JsonSerializer.Deserialize<CompanionState>(JsonSerializer.Serialize(value))!;}}
|
||||
private sealed class Clock:TimeProvider{public DateTimeOffset Time=new(2026,11,6,12,0,0,TimeSpan.Zero);public override DateTimeOffset GetUtcNow()=>Time;public void Advance(TimeSpan elapsed)=>Time+=elapsed;}
|
||||
private sealed class Server(Clock clock):HttpMessageHandler
|
||||
{
|
||||
public bool Offline,Revoked,AllowBook=true,LoseRenewalResponse;public int Account=7,RenewAttempts,ProseRequests;private Guid installation,connection,lastRotation;private string current="",previous="";private Guid pairingConnection;
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
|
||||
{
|
||||
var action=request.RequestUri!.AbsolutePath.Split('/').Last();if(action=="renew")RenewAttempts++;if(Offline)throw new HttpRequestException("Synthetic offline");
|
||||
var payload=request.Content==null?default:JsonDocument.Parse(await request.Content.ReadAsStringAsync(cancellation)).RootElement;
|
||||
if(action is "manuscript-capture" or "analyse-chapter" or "import-preview")ProseRequests++;
|
||||
object result;
|
||||
if(action=="pair"){pairingConnection=payload.GetProperty("connectionId").GetGuid();result=new{code=new string('A',24)};}
|
||||
else if(action=="token"){installation=Guid.NewGuid();connection=pairingConnection;current=Convert.ToHexString(RandomNumberGenerator.GetBytes(32));previous="";Revoked=false;result=Tokens(true);}
|
||||
else if(action=="renew"){
|
||||
var credential=payload.GetProperty("credential").GetString()!;var next=payload.GetProperty("nextCredential").GetString()!;var rotation=payload.GetProperty("rotationId").GetGuid();var runtime=payload.GetProperty("connectionId").GetGuid();
|
||||
if(Revoked||payload.GetProperty("installationId").GetGuid()!=installation)return Reply(HttpStatusCode.Unauthorized,new{});
|
||||
if(credential==current){previous=current;current=next;lastRotation=rotation;connection=runtime;}
|
||||
else if(credential!=previous||next!=current||rotation!=lastRotation||connection!=runtime)return Reply(HttpStatusCode.Unauthorized,new{});
|
||||
if(LoseRenewalResponse){LoseRenewalResponse=false;throw new HttpRequestException("Synthetic response lost after commit");}result=Tokens(false);
|
||||
}
|
||||
else if(action=="revoke"){var credential=payload.GetProperty("credential").GetString();if(credential==current||credential==previous)Revoked=true;return new(HttpStatusCode.NoContent);}
|
||||
else if(action=="books")result=AllowBook?new[]{new CompanionBook{BookId=Account==7?3:4,Title="Allowed synthetic book"}}:[];
|
||||
else result=new ConnectionHealth{Server="online",Authentication="verified",ExpiresUtc=clock.Time.AddMinutes(10).UtcDateTime,VerifiedUtc=clock.Time.UtcDateTime};
|
||||
return Reply(HttpStatusCode.OK,result);
|
||||
}
|
||||
private object Tokens(bool secret)=>new{accessToken="access:"+Guid.NewGuid(),expiresUtc=clock.Time.AddMinutes(10),installationId=installation,accountId=Account,accountName="Synthetic account "+Account,refreshExpiresUtc=clock.Time.AddDays(90),connectionId=connection,deviceSecret=secret?current:null};
|
||||
private static HttpResponseMessage Reply(HttpStatusCode code,object body)=>new(code){Content=JsonContent.Create(body)};
|
||||
}
|
||||
private static async Task Until(Func<bool> ready){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(15));while(!ready())await Task.Delay(20,timeout.Token);}
|
||||
}
|
||||
@ -171,4 +171,5 @@ await AnalysisTests.Run(Check);
|
||||
await ChapterAiTests.Run(Check);
|
||||
await WorkflowTests.Run(Check);
|
||||
await TrayTests.Run(Check);
|
||||
await PersistentConnectionTests.Run(Check);
|
||||
Console.WriteLine($"Native foundation: {passed} checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified.");
|
||||
|
||||
@ -25,7 +25,7 @@ namespace PlotDirector.WordAddIn
|
||||
internal static void Start(bool activate)
|
||||
{
|
||||
var paused=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"PlotDirector","Companion","paused");
|
||||
if(!activate&&File.Exists(paused)){LaunchStatus="Companion exited by author; use Open Companion to resume.";return;}
|
||||
if(!activate&&File.Exists(paused)&&File.GetLastWriteTimeUtc(paused)>=Process.GetCurrentProcess().StartTime.ToUniversalTime()){LaunchStatus="Companion exited by author; use Open Companion to resume.";return;}
|
||||
if(activate&&File.Exists(paused))File.Delete(paused);
|
||||
var assembly=Assembly.GetExecutingAssembly().Location;
|
||||
var executable=Path.Combine(Path.GetDirectoryName(assembly),"Agent","PlotDirector.Companion.Agent.exe");
|
||||
|
||||
@ -3,6 +3,6 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
|
||||
[assembly: AssemblyCompany("Nick Beckley")]
|
||||
[assembly: AssemblyProduct("PlotDirector")]
|
||||
[assembly: AssemblyVersion("1.0.0.13")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.13")]
|
||||
[assembly: AssemblyVersion("1.0.0.14")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.14")]
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
15
PlotLine.Tests/Browser/native-authorisation-development.cjs
Normal file
15
PlotLine.Tests/Browser/native-authorisation-development.cjs
Normal file
@ -0,0 +1,15 @@
|
||||
// Explicit Development-only authentication test. Uses a freshly provisioned private fixture identity; no manuscripts/AI.
|
||||
const {chromium,request}=require('playwright'),fs=require('fs'),assert=require('assert/strict'),crypto=require('crypto');let step='initialise';
|
||||
(async()=>{const path=process.argv[2];assert.ok(path?.startsWith('/tmp/pd-dev-browser-'));assert.equal(fs.statSync(path).mode&0o077,0);const identity=JSON.parse(fs.readFileSync(path,'utf8'));assert.equal(identity.Database,'PlotDirector_Development');assert.match(identity.Email,/^pwa-browser-[a-f0-9]+@example\.invalid$/);const base='https://dev.plotdirector.com',browser=await chromium.launch();const contexts=[];try{
|
||||
const context=await browser.newContext();const page=await context.newPage();step='normal login';await page.goto(base+'/Account/Login');await page.locator('input[name=Email]').fill(identity.Email);await page.locator('input[name=Password]').fill(identity.Password);await Promise.all([page.waitForURL(u=>u.pathname!='/Account/Login'),page.locator('form:has(input[name=Password]) button[type=submit]').click()]);
|
||||
const bare=await request.newContext({baseURL:base});contexts.push(bare);
|
||||
async function pair(){const connectionId=crypto.randomUUID(),verifier=crypto.randomBytes(32).toString('hex'),challenge=crypto.createHash('sha256').update(verifier).digest('hex').toUpperCase();const response=await bare.post('/api/native-companion/pair',{data:{challenge,persistent:true,connectionId,deviceName:'Isolated persistent-authorisation test'}});assert.ok(response.ok());const {code}=await response.json();await page.goto(base+'/native-companion/authorize?code='+encodeURIComponent(code));assert.match(await page.locator('body').innerText(),/90 days/);const token=await page.locator('input[name=__RequestVerificationToken]').inputValue();assert.ok((await context.request.post(base+'/native-companion/authorize',{form:{code,__RequestVerificationToken:token}})).ok());const tokens=await(await bare.post('/api/native-companion/token',{data:{code,verifier}})).json();assert.equal(tokens.accountId,identity.UserID);assert.equal(tokens.connectionId,connectionId);assert.equal(tokens.deviceSecret.length,64);assert.ok(Date.parse(tokens.expiresUtc)-Date.now()<11*60*1000);return tokens;}
|
||||
async function agent(token){const client=await request.newContext({baseURL:base,extraHTTPHeaders:{Authorization:'Bearer '+token}});contexts.push(client);return client;}
|
||||
step='persistent first approval';const initial=await pair();let client=await agent(initial.accessToken);assert.ok((await client.post('/api/native-companion/heartbeat',{data:{}})).ok());
|
||||
step='permission-free agent state without Word';let state=await(await context.request.get(base+'/native-companion/connection-state')).json();assert.equal(state.state,'Connected');assert.equal(state.wordConnected,false);assert.deepEqual(await(await context.request.get(base+'/native-companion/status')).json(),[]);
|
||||
step='rotation and lost-response retry';const next=crypto.randomBytes(32).toString('hex').toUpperCase(),rotation={installationId:initial.installationId,credential:initial.deviceSecret,nextCredential:next,rotationId:crypto.randomUUID(),connectionId:initial.connectionId};let response=await bare.post('/api/native-companion/renew',{data:rotation});assert.ok(response.ok());let renewed=await response.json();assert.equal(renewed.installationId,initial.installationId);assert.equal(renewed.accountId,identity.UserID);assert.ok((await bare.post('/api/native-companion/renew',{data:rotation})).ok());assert.equal((await bare.post('/api/native-companion/renew',{data:{...rotation,rotationId:crypto.randomUUID()}})).status(),401);
|
||||
step='process restart replaces access without approval';const newest=crypto.randomBytes(32).toString('hex').toUpperCase(),restart={...rotation,credential:next,nextCredential:newest,rotationId:crypto.randomUUID(),connectionId:crypto.randomUUID()};response=await bare.post('/api/native-companion/renew',{data:restart});assert.ok(response.ok());const restarted=await response.json();assert.equal((await client.get('/api/native-companion/books')).status(),401);client=await agent(restarted.accessToken);assert.ok((await client.get('/api/native-companion/books')).ok());
|
||||
step='authorised device management and antiforgery';await page.goto(base+'/native-companion/installations');assert.match(await page.locator('main').innerText(),/Isolated persistent-authorisation test/);assert.ok(!(await page.content()).includes(initial.deviceSecret));assert.equal((await context.request.post(base+'/native-companion/installations/'+initial.installationId+'/revoke',{form:{}})).status(),400);let csrf=await page.locator('input[name=__RequestVerificationToken]').first().inputValue();assert.ok((await context.request.post(base+'/native-companion/installations/'+initial.installationId+'/revoke',{form:{__RequestVerificationToken:csrf}})).ok());assert.equal((await client.get('/api/native-companion/books')).status(),401);assert.equal((await bare.post('/api/native-companion/renew',{data:{...restart,credential:newest,nextCredential:crypto.randomBytes(32).toString('hex').toUpperCase(),rotationId:crypto.randomUUID()}})).status(),401);state=await(await context.request.get(base+'/native-companion/connection-state')).json();assert.equal(state.state,'Action required');
|
||||
step='website logout revokes approved installations';const second=await pair();client=await agent(second.accessToken);assert.ok((await client.get('/api/native-companion/books')).ok());await page.goto(base+'/native-companion/installations');csrf=await page.locator('input[name=__RequestVerificationToken]').first().inputValue();assert.ok((await context.request.post(base+'/Account/Logout',{form:{__RequestVerificationToken:csrf}})).ok());assert.equal((await client.get('/api/native-companion/books')).status(),401);assert.equal((await bare.post('/api/native-companion/renew',{data:{installationId:second.installationId,credential:second.deviceSecret,nextCredential:crypto.randomBytes(32).toString('hex').toUpperCase(),rotationId:crypto.randomUUID(),connectionId:second.connectionId}})).status(),401);
|
||||
console.log('PASS live Development persistent pairing, SQL-backed renewal/retry, process replacement, agent-only liveness, antiforgery, unexpired-access revocation and website logout. No manuscript or AI requests.');
|
||||
}finally{for(const context of contexts)await context.dispose();await browser.close();}})().catch(error=>{fs.writeFileSync('/tmp/pd-native-authorisation-error.txt',String(error.stack),{mode:0o600});console.error('FAIL authentication smoke at '+step+'; private diagnostic recorded.');process.exit(1);});
|
||||
5
PlotLine.Tests/Browser/native-authorisation-status.cjs
Normal file
5
PlotLine.Tests/Browser/native-authorisation-status.cjs
Normal file
@ -0,0 +1,5 @@
|
||||
const {chromium}=require('playwright'),fs=require('fs'),path=require('path'),assert=require('assert/strict');
|
||||
(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage();await page.setContent('<span id="native-companion-status" data-office-connected="false"><span id="native-companion-status-text"></span></span>');await page.evaluate(()=>{window.device={known:true,state:'Connected'};window.leases=[];window.setInterval=callback=>(window.tick=callback,1);window.fetch=async url=>({ok:true,json:async()=>url.includes('connection-state')?device:leases});});await page.addScriptTag({content:fs.readFileSync(path.resolve(__dirname,'../../PlotLine/wwwroot/js/native-companion-status.js'),'utf8')});await page.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='true');assert.match(await page.locator('#native-companion-status-text').textContent(),/Word not connected/);
|
||||
for(const state of ['Reconnecting','Disconnected','Action required']){await page.evaluate(state=>{device.state=state;tick();},state);await page.waitForFunction(state=>document.querySelector('#native-companion-status-text').textContent===state,state);assert.equal(await page.locator('#native-companion-status').getAttribute('data-connected'),'false');}
|
||||
await page.evaluate(()=>{device.state='Connected';leases=[{bookId:3,wordAvailable:true,active:true,documentTitle:'Synthetic manuscript',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];tick();});await page.waitForFunction(()=>document.querySelector('#native-companion-status-text').textContent==='Word connected');
|
||||
console.log('PASS website trusted-connection states, renewal/revocation and independent Word liveness');}finally{await browser.close();}})().catch(error=>{console.error(error.message);process.exit(1);});
|
||||
@ -47,7 +47,7 @@ internal static class NativeCompanionHttpTests
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IWordCompanionService>((n,a)=>n=="AnalyseManuscriptAsync"?Task.FromResult<WordCompanionManuscriptAnalyseResponse?>(new(){CanImport=true,Message="Preview eligible"}):throw new Exception("Unexpected write "+n)));
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IStoryContextService>((n,a)=>Task.FromResult<StoryContextViewModel?>(null)));
|
||||
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IWriterWorkspaceService>((n,a)=>Task.FromResult<PlotLine.ViewModels.ChapterWorkflowViewModel?>(null)));
|
||||
builder.Services.AddSingleton(users);builder.Services.AddSingleton(repo);builder.Services.AddSingleton(subscriptions);
|
||||
builder.Services.AddSingleton<INativeInstallationRepository>(new MemoryNativeInstallations(user));builder.Services.AddScoped<NativeInstallationService>();builder.Services.AddSingleton(users);builder.Services.AddSingleton(repo);builder.Services.AddSingleton(subscriptions);
|
||||
builder.Services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton<DesktopPairing>();builder.Services.AddSingleton<NativeAnalysisCache>();builder.Services.AddSingleton(NativeWorkflowTests.Proxy<INativeImportRepository>((n,a)=>n=="List"?Task.FromResult<IReadOnlyList<NativeImportedChapter>>([]):throw new Exception("Unexpected import write "+n)));builder.Services.AddScoped<NativeImportService>();builder.Services.AddSingleton<NativePresenceStore>();builder.Services.AddSingleton<INativeReviewRepository>(new MemoryNativeReviews());
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options=>{options.LoginPath="/fixture-login";options.Cookie.SecurePolicy=Microsoft.AspNetCore.Http.CookieSecurePolicy.None;})
|
||||
.AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});
|
||||
@ -117,6 +117,15 @@ internal static class NativeCompanionHttpTests
|
||||
live.Sequence=2;Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).StatusCode==HttpStatusCode.Conflict,"Late heartbeat cannot restore signed-out presence");
|
||||
request.BookId=999;Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).StatusCode==HttpStatusCode.Forbidden&&provider.Prompts.Count==1,"Foreign book rejected without provider charge");request.BookId=3;
|
||||
allowed=false;Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).StatusCode==HttpStatusCode.Forbidden,"Subscription access enforced on HTTP path");allowed=true;
|
||||
var runtime=Guid.NewGuid();var devicePair=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge,persistent=true,connectionId=runtime,deviceName="HTTP fixture installation"});var deviceCode=(await devicePair.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("code").GetString()!;
|
||||
await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary<string,string>{{"code",deviceCode},{"__RequestVerificationToken",antiforgery}}));
|
||||
var device=(await(await agent.PostAsJsonAsync("/api/native-companion/token",new{code=deviceCode,verifier})).Content.ReadFromJsonAsync<NativeDeviceTokens>())!;
|
||||
agent.DefaultRequestHeaders.Authorization=new("Bearer",device.AccessToken);Check((await agent.GetAsync("/api/native-companion/books")).IsSuccessStatusCode,"Actual HTTP trusted installation authenticates");
|
||||
var rotate=new NativeDeviceRenew(device.InstallationId,device.DeviceSecret!,new string('C',64),Guid.NewGuid(),runtime);var rotatedResponse=await agent.PostAsJsonAsync("/api/native-companion/renew",rotate);Check(rotatedResponse.IsSuccessStatusCode,"Actual HTTP access renewal does not need browser approval");
|
||||
var renewed=(await rotatedResponse.Content.ReadFromJsonAsync<NativeDeviceTokens>())!;Check((await agent.PostAsJsonAsync("/api/native-companion/renew",rotate)).IsSuccessStatusCode,"Actual HTTP rotation retry is idempotent");
|
||||
Check((await agent.PostAsJsonAsync("/api/native-companion/renew",rotate with{RotationId=Guid.NewGuid()})).StatusCode==HttpStatusCode.Unauthorized,"Actual HTTP stale credential cannot start another rotation");
|
||||
agent.DefaultRequestHeaders.Authorization=new("Bearer",renewed.AccessToken);Check((await agent.PostAsJsonAsync("/api/native-companion/revoke",rotate with{Credential=new string('C',64),NextCredential=""})).IsSuccessStatusCode,"Explicit trusted sign-out revokes installation over HTTP");Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Actual HTTP revocation invalidates unexpired access immediately");
|
||||
agent.DefaultRequestHeaders.Authorization=new("Bearer",token);
|
||||
user.SecurityStamp=Guid.NewGuid();Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Revoked grant rejected through HTTP handler");
|
||||
}
|
||||
finally{await app.StopAsync();}
|
||||
|
||||
65
PlotLine.Tests/NativeInstallationTests.cs
Normal file
65
PlotLine.Tests/NativeInstallationTests.cs
Normal file
@ -0,0 +1,65 @@
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using PlotLine.Controllers;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
internal static class NativeInstallationTests
|
||||
{
|
||||
public static async Task Run()
|
||||
{
|
||||
static void Check(bool value,string message){if(!value)throw new Exception(message);}
|
||||
var user=new AppUser{UserID=7,SecurityStamp=Guid.NewGuid(),DisplayName="Synthetic author"};var repo=new MemoryNativeInstallations(user);var protection=new EphemeralDataProtectionProvider();var pairing=new DesktopPairing(protection,TimeProvider.System);var presence=new NativePresenceStore(TimeProvider.System);var service=new NativeInstallationService(repo,pairing,presence,TimeProvider.System);
|
||||
var first=await service.Create(new(7,user.SecurityStamp,true,true,Guid.NewGuid(),"Synthetic Windows installation"));
|
||||
Check(first.ExpiresUtc<=DateTimeOffset.UtcNow.AddMinutes(10)&&first.DeviceSecret?.Length==64,"Installation approval issues a short-lived access token and separate refresh credential");
|
||||
Check(first.ToString()=="NativeDeviceTokens [redacted]","Tokens cannot be exposed by default record diagnostic formatting");
|
||||
var users=NativeWorkflowTests.Proxy<IUserRepository>((_,_)=>Task.FromResult<AppUser?>(user));var services=new ServiceCollection().AddLogging().AddSingleton(pairing).AddSingleton(users).AddSingleton<INativeInstallationRepository>(repo);services.AddAuthentication(DesktopPairing.Scheme).AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});await using var provider=services.BuildServiceProvider();
|
||||
async Task<bool> Auth(string token){await using var scope=provider.CreateAsyncScope();var context=new DefaultHttpContext{RequestServices=scope.ServiceProvider};context.Request.Headers.Authorization="Bearer "+token;return(await context.AuthenticateAsync(DesktopPairing.Scheme)).Succeeded;}
|
||||
Check(await Auth(first.AccessToken),"Trusted access requires both protected token and active installation record");
|
||||
var instance=Guid.NewGuid();var session=Guid.NewGuid();var grant=pairing.Read(first.AccessToken)!;var key=NativeInstallationService.GrantKey(first.InstallationId,first.ConnectionId);presence.Put(7,key,first.ExpiresUtc,instance,session,new(){BookId=3,ManuscriptId=Guid.NewGuid(),Sequence=1});
|
||||
var next=Convert.ToHexString(RandomNumberGenerator.GetBytes(32));var request=new NativeDeviceRenew(first.InstallationId,first.DeviceSecret!,next,Guid.NewGuid(),Guid.NewGuid());
|
||||
var renewed=await service.Renew(request)??throw new Exception("Renewal failed");Check(renewed.AccountId==7&&renewed.ConnectionId==request.ConnectionId&&renewed.DeviceSecret==null,"Renewal remains bound to its original account and carries no standing bearer token");
|
||||
Check(!await Auth(first.AccessToken)&&await Auth(renewed.AccessToken)&&presence.Read(7,3).Length==0,"Restart invalidates old process access/liveness while retaining installation trust");
|
||||
Check(await service.Renew(request)!=null,"Lost-response retry requires the identical persisted rotation and next credential");
|
||||
Check(await service.Renew(request with{RotationId=Guid.NewGuid()})==null,"Old refresh credential cannot create another renewal after rotation");
|
||||
Check(!await service.RevokeUser(8,first.InstallationId)&&await Auth(renewed.AccessToken),"Other account cannot revoke this installation");
|
||||
var current=new NativeDeviceRenew(first.InstallationId,next,new string('B',64),Guid.NewGuid(),request.ConnectionId);
|
||||
user.SecurityStamp=Guid.NewGuid();Check(!await Auth(renewed.AccessToken)&&await service.Renew(current)==null,"Account security-stamp changes invalidate access and installation renewal");user.SecurityStamp=grant.Stamp;
|
||||
user.IsLocked=true;Check(!await Auth(renewed.AccessToken)&&await service.Renew(current)==null,"Locked accounts cannot renew or use trusted installations");user.IsLocked=false;
|
||||
var recreatedPairing=new DesktopPairing(protection,TimeProvider.System);var restarted=new NativeInstallationService(repo,recreatedPairing,presence,TimeProvider.System);Check(await restarted.Renew(current)!=null,"Server process restart does not erase persisted installation approval");
|
||||
var logout=new AccountController(NativeWorkflowTests.Proxy<IAuthService>((name,_)=>name=="LogoutAsync"?Task.CompletedTask:throw new Exception(name)),service){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}};
|
||||
await logout.Logout();Check(!await Auth(renewed.AccessToken)&&await service.Renew(current)==null,"Explicit website logout revokes device approval, including future renewal");
|
||||
var second=await service.Create(new(7,user.SecurityStamp,false,true,Guid.NewGuid(),"Another fixture"));await service.RevokeSecret(new(second.InstallationId,second.DeviceSecret!,"",Guid.Empty,Guid.Empty));Check(!await Auth(second.AccessToken),"Device sign-out immediately invalidates otherwise unexpired access");
|
||||
}
|
||||
}
|
||||
internal sealed class MemoryNativeInstallations(AppUser user):INativeInstallationRepository
|
||||
{
|
||||
private sealed record Secret(NativeInstallation Row,byte[] Current,byte[]? Previous=null,Guid? Rotation=null);
|
||||
private readonly Dictionary<Guid,Secret> rows=[];private readonly object gate=new();
|
||||
private bool Valid(NativeInstallation row)=>row.SecurityStamp==user.SecurityStamp&&!user.IsLocked&&row.RevokedUtc==null&&row.RefreshExpiresUtc>DateTimeOffset.UtcNow;
|
||||
public Task<bool> Validate(Guid id,int actor,Guid stamp,Guid connection){lock(gate){if(!rows.TryGetValue(id,out var entry)||entry.Row.UserID!=actor||entry.Row.SecurityStamp!=stamp||entry.Row.ConnectionID!=connection||!Valid(entry.Row))return Task.FromResult(false);entry.Row.LastSeenUtc=DateTimeOffset.UtcNow;entry.Row.DisconnectedUtc=null;return Task.FromResult(true);}}
|
||||
public Task<IReadOnlyList<NativeInstallation>> Run(string action,Guid? id=null,int? actor=null,Guid? stamp=null,string? name=null,bool retain=false,byte[]? hash=null,byte[]? nextHash=null,Guid? rotation=null,Guid? connection=null)
|
||||
{
|
||||
lock(gate){
|
||||
if(action=="create"){if(actor!=user.UserID||stamp!=user.SecurityStamp)throw new UnauthorizedAccessException();rows[id!.Value]=new(new(){InstallationID=id.Value,UserID=actor.Value,SecurityStamp=stamp!.Value,AccountName=user.DisplayName??"Fixture",DeviceName=name!,RetainImport=retain,ConnectionID=connection!.Value,CreatedUtc=DateTimeOffset.UtcNow,RefreshExpiresUtc=DateTimeOffset.UtcNow.AddDays(90)},hash!);}
|
||||
else if(action=="rotate"){
|
||||
if(!rows.TryGetValue(id!.Value,out var entry)||!Valid(entry.Row))return Task.FromResult<IReadOnlyList<NativeInstallation>>([]);
|
||||
if(entry.Current.SequenceEqual(hash!)){entry.Row.PreviousConnectionID=entry.Row.ConnectionID;entry.Row.ConnectionID=connection!.Value;rows[id.Value]=entry with{Previous=entry.Current,Current=nextHash!,Rotation=rotation};}
|
||||
else if(entry.Previous==null||!entry.Previous.SequenceEqual(hash!)||!entry.Current.SequenceEqual(nextHash!)||entry.Rotation!=rotation||entry.Row.ConnectionID!=connection)return Task.FromResult<IReadOnlyList<NativeInstallation>>([]);
|
||||
}
|
||||
else if(action=="revoke-secret"){
|
||||
if(!rows.TryGetValue(id!.Value,out var entry)||!(entry.Current.SequenceEqual(hash!)||(entry.Previous?.SequenceEqual(hash!)==true&&entry.Rotation==rotation&&entry.Current.SequenceEqual(nextHash!))))return Task.FromResult<IReadOnlyList<NativeInstallation>>([]);entry.Row.RevokedUtc=DateTimeOffset.UtcNow;
|
||||
}
|
||||
else if(action is "revoke-user" or "revoke-all"){foreach(var entry in rows.Values.Where(s=>s.Row.UserID==actor&&(!id.HasValue||s.Row.InstallationID==id)))entry.Row.RevokedUtc=DateTimeOffset.UtcNow;}
|
||||
else if(action=="disconnect"){if(rows.TryGetValue(id!.Value,out var entry)&&entry.Row.UserID==actor&&entry.Row.ConnectionID==connection){entry.Row.DisconnectedUtc=DateTimeOffset.UtcNow;}}
|
||||
else if(action!="list")throw new InvalidOperationException(action);
|
||||
return Task.FromResult<IReadOnlyList<NativeInstallation>>(rows.Values.Select(s=>s.Row).Where(r=>(!id.HasValue||r.InstallationID==id)&&(!actor.HasValue||r.UserID==actor)).ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -125,6 +125,7 @@ if (args.Contains("--plot-lines"))
|
||||
if(args.Contains("--intent-assessment")){await IntentAssessmentTests.Run();Console.WriteLine("PASS persisted Intent evidence, exact quotes, cache, stale plans, ownership, cancellation and entitlement");return;}
|
||||
if(args.Contains("--release-sprint")){ReleaseSprintTests.Run();Console.WriteLine("PASS continuity triage and public onboarding/installer guidance");return;}
|
||||
if(args.Contains("--native-import")){await NativeImportTests.Run();Console.WriteLine("PASS approved native import preview, source preservation, ownership, version and retry");return;}
|
||||
if(args.Contains("--native-installation")){await NativeInstallationTests.Run();Console.WriteLine("PASS trusted installation access, renewal, process replacement, account isolation and revocation");return;}
|
||||
if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();await NativeManuscriptCaptureTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;}
|
||||
if(args.Contains("--native-workflow")){await NativeWorkflowTests.Run();Console.WriteLine("PASS native saved workspace and safe import preview validation");return;}
|
||||
if(args.Contains("--native-companion-http")){await NativeCompanionHttpTests.Run();return;}
|
||||
@ -135,6 +136,7 @@ var tests = new (string Name, Action Test)[]
|
||||
("Intent evidence preserves provenance and author control", () => IntentAssessmentTests.Run().GetAwaiter().GetResult()),
|
||||
("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run),
|
||||
("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()),
|
||||
("Native installation renewal and revocation remain account/security scoped", () => NativeInstallationTests.Run().GetAwaiter().GetResult()),
|
||||
("Native wizard capture is scoped, durable and independent of Word", () => NativeManuscriptCaptureTests.Run().GetAwaiter().GetResult()),
|
||||
("Native tray presence and PWA review remain scoped, expiring and non-destructive", () => NativeTrayIntegrationTests.Run().GetAwaiter().GetResult()),
|
||||
("Native saved workspace and established import eligibility remain scoped and read-only", () => NativeWorkflowTests.Run().GetAwaiter().GetResult()),
|
||||
|
||||
48
PlotLine.Tests/Sql/NativeInstallationAuthorisation.sql
Normal file
48
PlotLine.Tests/Sql/NativeInstallationAuthorisation.sql
Normal file
@ -0,0 +1,48 @@
|
||||
-- Guarded disposable database. Every synthetic user and approval is rolled back.
|
||||
SET NOCOUNT ON;
|
||||
IF DB_NAME()<>N'PlotDirector_Phase2_20261103_2305' OR NOT EXISTS(SELECT 1 FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true') THROW 51000,'Guarded synthetic database required',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @User int,@Other int,@Stamp uniqueidentifier=NEWID(),@ID uniqueidentifier=NEWID(),@Connection uniqueidentifier=NEWID(),@Restart uniqueidentifier=NEWID(),@Rotation uniqueidentifier=NEWID();
|
||||
DECLARE @Now datetimeoffset='2026-11-06T12:00:00+00:00',@A varbinary(32)=HASHBYTES('SHA2_256',REPLICATE('A',64)),@B varbinary(32)=HASHBYTES('SHA2_256',REPLICATE('B',64)),@C varbinary(32)=HASHBYTES('SHA2_256',REPLICATE('C',64));
|
||||
INSERT dbo.AppUser(Email,DisplayName,PasswordHash,SecurityStamp) VALUES(CONVERT(nvarchar(36),NEWID())+N'@native-trust.invalid',N'Installation fixture',N'not-a-credential',@Stamp);SET @User=SCOPE_IDENTITY();
|
||||
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@native-trust.invalid',N'Other installation fixture',N'not-a-credential');SET @Other=SCOPE_IDENTITY();
|
||||
CREATE TABLE #Rows(InstallationID uniqueidentifier,UserID int,SecurityStamp uniqueidentifier,DeviceName nvarchar(80),RetainImport bit,ConnectionID uniqueidentifier,RefreshExpiresUtc datetimeoffset,CreatedUtc datetimeoffset,LastRenewedUtc datetimeoffset,LastSeenUtc datetimeoffset,DisconnectedUtc datetimeoffset,RevokedUtc datetimeoffset,AccountName nvarchar(512),PreviousConnectionID uniqueidentifier);
|
||||
INSERT #Rows EXEC dbo.NativeCompanionInstallation @Action='create',@InstallationID=@ID,@UserID=@User,@Stamp=@Stamp,@DeviceName=N'Synthetic Windows',@RetainImport=1,@RefreshHash=@A,@ConnectionID=@Connection,@Now=@Now;
|
||||
IF (SELECT COUNT(*) FROM #Rows)<>1 OR NOT EXISTS(SELECT 1 FROM dbo.NativeCompanionInstallations WHERE InstallationID=@ID AND RefreshHash=@A) THROW 51000,'Approval persistence failed',1;
|
||||
CREATE TABLE #Valid(ID uniqueidentifier);
|
||||
INSERT #Valid EXEC dbo.NativeCompanionInstallation @Action='validate',@InstallationID=@ID,@UserID=@User,@Stamp=@Stamp,@ConnectionID=@Connection,@Now=@Now;
|
||||
IF (SELECT COUNT(*) FROM #Valid)<>1 THROW 51000,'Valid access rejected',1;
|
||||
TRUNCATE TABLE #Rows;
|
||||
INSERT #Rows EXEC dbo.NativeCompanionInstallation @Action='rotate',@InstallationID=@ID,@RefreshHash=@A,@NextHash=@B,@RotationID=@Rotation,@ConnectionID=@Restart,@Now=@Now;
|
||||
IF NOT EXISTS(SELECT 1 FROM #Rows WHERE ConnectionID=@Restart AND PreviousConnectionID=@Connection AND RetainImport=1 AND UserID=@User) THROW 51000,'Rotation changed account/consent or lost runtime identity',1;
|
||||
TRUNCATE TABLE #Valid;
|
||||
INSERT #Valid EXEC dbo.NativeCompanionInstallation @Action='validate',@InstallationID=@ID,@UserID=@User,@Stamp=@Stamp,@ConnectionID=@Connection,@Now=@Now;
|
||||
IF EXISTS(SELECT 1 FROM #Valid) THROW 51000,'Old process token still valid',1;
|
||||
TRUNCATE TABLE #Rows;
|
||||
INSERT #Rows EXEC dbo.NativeCompanionInstallation @Action='rotate',@InstallationID=@ID,@RefreshHash=@A,@NextHash=@B,@RotationID=@Rotation,@ConnectionID=@Restart,@Now=@Now;
|
||||
IF (SELECT COUNT(*) FROM #Rows)<>1 THROW 51000,'Exact lost-response retry failed',1;
|
||||
TRUNCATE TABLE #Rows;
|
||||
DECLARE @OtherRotation uniqueidentifier=NEWID();
|
||||
INSERT #Rows EXEC dbo.NativeCompanionInstallation @Action='rotate',@InstallationID=@ID,@RefreshHash=@A,@NextHash=@C,@RotationID=@OtherRotation,@ConnectionID=@Restart,@Now=@Now;
|
||||
IF EXISTS(SELECT 1 FROM #Rows) THROW 51000,'Old secret started another rotation',1;
|
||||
INSERT #Rows EXEC dbo.NativeCompanionInstallation @Action='revoke-user',@InstallationID=@ID,@UserID=@Other,@Now=@Now;
|
||||
IF EXISTS(SELECT 1 FROM #Rows) OR EXISTS(SELECT 1 FROM dbo.NativeCompanionInstallations WHERE InstallationID=@ID AND RevokedUtc IS NOT NULL) THROW 51000,'Cross-account revocation succeeded',1;
|
||||
EXEC dbo.NativeCompanionInstallation @Action='disconnect',@InstallationID=@ID,@UserID=@User,@ConnectionID=@Restart,@Now=@Now;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.NativeCompanionInstallations WHERE InstallationID=@ID AND ConnectionID=@Restart AND DisconnectedUtc IS NOT NULL AND RevokedUtc IS NULL) THROW 51000,'Exit discarded trust or failed to record disconnection',1;
|
||||
INSERT #Rows EXEC dbo.NativeCompanionInstallation @Action='rotate',@InstallationID=@ID,@RefreshHash=@B,@NextHash=@C,@RotationID=@OtherRotation,@ConnectionID=@Connection,@Now=@Now;
|
||||
IF NOT EXISTS(SELECT 1 FROM #Rows WHERE ConnectionID=@Connection) THROW 51000,'Restart after exit requires reapproval',1;
|
||||
DECLARE @InvalidStamp uniqueidentifier=NEWID();UPDATE dbo.AppUser SET SecurityStamp=@InvalidStamp WHERE UserID=@User;
|
||||
TRUNCATE TABLE #Valid;INSERT #Valid EXEC dbo.NativeCompanionInstallation @Action='validate',@InstallationID=@ID,@UserID=@User,@Stamp=@Stamp,@ConnectionID=@Connection,@Now=@Now;
|
||||
IF EXISTS(SELECT 1 FROM #Valid) THROW 51000,'Password change failed to invalidate access',1;
|
||||
TRUNCATE TABLE #Rows;INSERT #Rows EXEC dbo.NativeCompanionInstallation @Action='rotate',@InstallationID=@ID,@RefreshHash=@C,@NextHash=@A,@RotationID=@Rotation,@ConnectionID=@Connection,@Now=@Now;
|
||||
IF EXISTS(SELECT 1 FROM #Rows) THROW 51000,'Password change allowed renewal',1;
|
||||
UPDATE dbo.AppUser SET SecurityStamp=@Stamp WHERE UserID=@User;
|
||||
TRUNCATE TABLE #Rows;INSERT #Rows EXEC dbo.NativeCompanionInstallation @Action='revoke-all',@UserID=@User,@Now=@Now;
|
||||
TRUNCATE TABLE #Valid;INSERT #Valid EXEC dbo.NativeCompanionInstallation @Action='validate',@InstallationID=@ID,@UserID=@User,@Stamp=@Stamp,@ConnectionID=@Connection,@Now=@Now;
|
||||
IF EXISTS(SELECT 1 FROM #Valid) THROW 51000,'Logout did not invalidate access',1;
|
||||
TRUNCATE TABLE #Rows;INSERT #Rows EXEC dbo.NativeCompanionInstallation @Action='rotate',@InstallationID=@ID,@RefreshHash=@C,@NextHash=@A,@RotationID=@Rotation,@ConnectionID=@Connection,@Now=@Now;
|
||||
IF EXISTS(SELECT 1 FROM #Rows) THROW 51000,'Revoked approval renewed',1;
|
||||
DELETE dbo.AppUser WHERE UserID=@User;
|
||||
IF EXISTS(SELECT 1 FROM dbo.NativeCompanionInstallations WHERE InstallationID=@ID) THROW 51000,'Account deletion left device trust',1;
|
||||
ROLLBACK;
|
||||
PRINT 'PASS durable approval, hashed rotation, lost-response retry, process exit/restart, account isolation, password/logout revocation and account-deletion cascade; synthetic fixtures rolled back';
|
||||
@ -6,7 +6,7 @@ using PlotLine.ViewModels;
|
||||
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
public sealed class AccountController(IAuthService authService) : Controller
|
||||
public sealed class AccountController(IAuthService authService,PlotLine.Services.NativeCompanion.NativeInstallationService? nativeInstallations=null) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
[AllowAnonymous]
|
||||
@ -99,6 +99,7 @@ public sealed class AccountController(IAuthService authService) : Controller
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
if(nativeInstallations!=null&&int.TryParse(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value,out var author))await nativeInstallations.RevokeAll(author);
|
||||
await authService.LogoutAsync();
|
||||
return RedirectToAction("Index", "Home");
|
||||
}
|
||||
|
||||
@ -7,30 +7,38 @@ namespace PlotLine.Controllers;
|
||||
|
||||
[RequestSizeLimit(4096)]
|
||||
[Microsoft.AspNetCore.RateLimiting.EnableRateLimiting("native-pair")]
|
||||
public sealed class NativeCompanionAuthController(DesktopPairing pairing):Controller
|
||||
public sealed class NativeCompanionAuthController(DesktopPairing pairing,NativeInstallationService? installations=null):Controller
|
||||
{
|
||||
[AllowAnonymous,HttpPost("api/native-companion/pair")]
|
||||
public IActionResult Start([FromBody] PairStart request)
|
||||
{
|
||||
Response.Headers.CacheControl="no-store";
|
||||
if(request==null)return BadRequest();
|
||||
try{return Ok(new{code=pairing.Start(request.Challenge??"")});}
|
||||
if(request==null||(request.Persistent&&request.ConnectionId==Guid.Empty))return BadRequest();
|
||||
try{return Ok(new{code=pairing.Start(request.Challenge??"",request.Persistent,request.ConnectionId,request.DeviceName??"Windows Companion")});}
|
||||
catch(ArgumentException){return BadRequest();}catch(InvalidOperationException){return StatusCode(429);}
|
||||
}
|
||||
[Authorize,HttpGet("native-companion/authorize")]
|
||||
public IActionResult Approve(string code)
|
||||
{Response.Headers.CacheControl="no-store";Response.Headers["Referrer-Policy"]="no-referrer";return !string.IsNullOrEmpty(code)&&pairing.Exists(code)?View("Approve",code):BadRequest("This request expired. Start Connect again in Word.");}
|
||||
{Response.Headers.CacheControl="no-store";Response.Headers["Referrer-Policy"]="no-referrer";ViewData["PersistentInstallation"]=pairing.Persistent(code??"");return !string.IsNullOrEmpty(code)&&pairing.Exists(code)?View("Approve",code):BadRequest("This request expired. Start Connect again in Word.");}
|
||||
[Authorize,HttpPost("native-companion/authorize"),ValidateAntiForgeryToken]
|
||||
public IActionResult ApproveGrant(string code,bool retainImport=false)
|
||||
{
|
||||
if(string.IsNullOrEmpty(code))return BadRequest();
|
||||
if(!int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var user)||!Guid.TryParse(User.FindFirstValue("PlotLine.SecurityStamp"),out var stamp))return Forbid();
|
||||
Response.Headers.CacheControl="no-store";
|
||||
return pairing.Approve(code,user,stamp,retainImport)?Content("Word Companion connected. You may close this tab. The grant expires in four hours; signing out in Word discards it."):BadRequest("This request expired or was already approved.");
|
||||
var persistent=pairing.Persistent(code);return pairing.Approve(code,user,stamp,retainImport)?Content(persistent?"Companion installation approved. You may close this tab. Access renews automatically; sign out or revoke this installation to remove its approval.":"Word Companion connected. You may close this tab. This older Companion uses a four-hour grant; update it for automatic reconnection."):BadRequest("This request expired or was already approved.");
|
||||
}
|
||||
[AllowAnonymous,HttpPost("api/native-companion/token")]
|
||||
public IActionResult Token([FromBody] PairRedeem request)
|
||||
{Response.Headers.CacheControl="no-store";if(request==null)return BadRequest();var token=pairing.Redeem(request.Code??"",request.Verifier??"");return token==null?Accepted(new{status="pending-or-expired"}):Ok(new{accessToken=token});}
|
||||
public sealed record PairStart(string Challenge);
|
||||
public async Task<IActionResult> Token([FromBody] PairRedeem request)
|
||||
{
|
||||
Response.Headers.CacheControl="no-store";if(request==null)return BadRequest();var approval=pairing.RedeemApproval(request.Code??"",request.Verifier??"");if(approval==null)return Accepted(new{status="pending-or-expired"});
|
||||
if(approval.Persistent){if(installations==null||approval.ConnectionId==Guid.Empty)return StatusCode(503);return Ok(await installations.Create(approval));}
|
||||
return Ok(new{accessToken=pairing.Issue(new(approval.UserId,approval.Stamp,DateTimeOffset.UtcNow.AddHours(4),approval.RetainImport))});
|
||||
}
|
||||
[AllowAnonymous,HttpPost("api/native-companion/renew")]
|
||||
public async Task<IActionResult> Renew([FromBody] NativeDeviceRenew request){Response.Headers.CacheControl="no-store";if(request==null)return BadRequest();if(installations==null)return StatusCode(503);try{var tokens=await installations.Renew(request);return tokens==null?Unauthorized():Ok(tokens);}catch(ArgumentException){return BadRequest();}}
|
||||
[AllowAnonymous,HttpPost("api/native-companion/revoke")]
|
||||
public async Task<IActionResult> Revoke([FromBody] NativeDeviceRenew request){Response.Headers.CacheControl="no-store";if(request==null)return BadRequest();if(installations==null)return StatusCode(503);try{await installations.RevokeSecret(request);return NoContent();}catch(ArgumentException){return BadRequest();}}
|
||||
public sealed record PairStart(string Challenge,bool Persistent=false,Guid ConnectionId=default,string? DeviceName=null);
|
||||
public sealed record PairRedeem(string Code,string Verifier);
|
||||
}
|
||||
|
||||
31
PlotLine/Controllers/NativeInstallationController.cs
Normal file
31
PlotLine/Controllers/NativeInstallationController.cs
Normal file
@ -0,0 +1,31 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
namespace PlotLine.Controllers;
|
||||
[Authorize,Route("native-companion")]
|
||||
public sealed class NativeInstallationController(INativeInstallationRepository installations,NativeInstallationService service,TimeProvider clock):Controller
|
||||
{
|
||||
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
[HttpGet("installations")]
|
||||
public async Task<IActionResult> Index(){Response.Headers.CacheControl="no-store";return View(await installations.Run("list",user:Author));}
|
||||
[HttpPost("installations/{id:guid}/revoke"),ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Revoke(Guid id){if(!await service.RevokeUser(Author,id))return NotFound();return RedirectToAction(nameof(Index));}
|
||||
[HttpGet("connection-state")]
|
||||
public async Task<IActionResult> State()
|
||||
{
|
||||
Response.Headers.CacheControl="no-store";var all=await installations.Run("list",user:Author);var now=clock.GetUtcNow();var active=all.Where(i=>i.RevokedUtc==null&&i.RefreshExpiresUtc>now).ToArray();
|
||||
var connected=active.Any(i=>i.LastSeenUtc.HasValue&&now-i.LastSeenUtc.Value<TimeSpan.FromSeconds(45)&&(!i.DisconnectedUtc.HasValue||i.LastSeenUtc>i.DisconnectedUtc));
|
||||
var recent=active.Any(i=>i.LastSeenUtc.HasValue&&now-i.LastSeenUtc.Value<TimeSpan.FromMinutes(5)&&(!i.DisconnectedUtc.HasValue||i.LastSeenUtc>i.DisconnectedUtc));
|
||||
return Json(new{known=all.Count>0,state=connected?"Connected":recent?"Reconnecting":active.Length>0?"Disconnected":all.Count>0?"Action required":"Disconnected",wordConnected=false});
|
||||
}
|
||||
}
|
||||
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")]
|
||||
public sealed class NativeConnectionController(INativeInstallationRepository installations,NativePresenceStore presence):ControllerBase
|
||||
{
|
||||
[HttpPost("heartbeat")]
|
||||
public IActionResult Heartbeat()=>Ok(new{connected=true}); // Authentication validates live installation/security stamp.
|
||||
[HttpPost("disconnect")]
|
||||
public async Task<IActionResult> Disconnect(){if(Guid.TryParse(User.FindFirstValue("NativeCompanion.Installation"),out var id)&&Guid.TryParse(User.FindFirstValue("NativeCompanion.Connection"),out var connection)){var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);await installations.Run("disconnect",id,user,connection:connection);presence.DisconnectGrant(user,User.FindFirstValue("NativeCompanion.Grant")!);}return NoContent();}
|
||||
}
|
||||
@ -33,5 +33,5 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
|
||||
[HttpDelete("instances/{instance:guid}/documents/{session:guid}/presence")]
|
||||
public IActionResult Remove(Guid instance,Guid session,long? throughSequence=null){presence.Remove(Author,Grant,instance,session,throughSequence);return Ok(new NativePresence());}
|
||||
[HttpPost("presence/disconnect")]
|
||||
public IActionResult Disconnect(){presence.Revoke(Author,Grant,Expires);return NoContent();}
|
||||
public IActionResult Disconnect(){if(User.HasClaim(c=>c.Type=="NativeCompanion.Installation"))presence.DisconnectGrant(Author,Grant);else presence.Revoke(Author,Grant,Expires);return NoContent();}
|
||||
}
|
||||
|
||||
18
PlotLine/Data/NativeInstallationRepository.cs
Normal file
18
PlotLine/Data/NativeInstallationRepository.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using System.Data;
|
||||
using Dapper;
|
||||
namespace PlotLine.Data;
|
||||
public sealed class NativeInstallation
|
||||
{
|
||||
public Guid InstallationID {get;set;}public int UserID {get;set;}public Guid SecurityStamp {get;set;}public string DeviceName {get;set;}="";public string AccountName {get;set;}="";public bool RetainImport {get;set;}
|
||||
public Guid ConnectionID {get;set;}public Guid? PreviousConnectionID {get;set;}public DateTimeOffset RefreshExpiresUtc {get;set;}public DateTimeOffset CreatedUtc {get;set;}public DateTimeOffset LastRenewedUtc {get;set;}public DateTimeOffset? LastSeenUtc {get;set;}public DateTimeOffset? DisconnectedUtc {get;set;}public DateTimeOffset? RevokedUtc {get;set;}
|
||||
}
|
||||
public interface INativeInstallationRepository
|
||||
{
|
||||
Task<IReadOnlyList<NativeInstallation>> Run(string action,Guid? id=null,int? user=null,Guid? stamp=null,string? name=null,bool retain=false,byte[]? hash=null,byte[]? nextHash=null,Guid? rotation=null,Guid? connection=null);
|
||||
Task<bool> Validate(Guid id,int user,Guid stamp,Guid connection);
|
||||
}
|
||||
public sealed class NativeInstallationRepository(ISqlConnectionFactory factory):INativeInstallationRepository
|
||||
{
|
||||
public async Task<IReadOnlyList<NativeInstallation>> Run(string action,Guid? id=null,int? user=null,Guid? stamp=null,string? name=null,bool retain=false,byte[]? hash=null,byte[]? nextHash=null,Guid? rotation=null,Guid? connection=null){using var db=factory.CreateConnection();return(await db.QueryAsync<NativeInstallation>("dbo.NativeCompanionInstallation",new{Action=action,InstallationID=id,UserID=user,Stamp=stamp,DeviceName=name,RetainImport=retain,RefreshHash=hash,NextHash=nextHash,RotationID=rotation,ConnectionID=connection},commandType:CommandType.StoredProcedure)).AsList();}
|
||||
public async Task<bool> Validate(Guid id,int user,Guid stamp,Guid connection){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<Guid?>("dbo.NativeCompanionInstallation",new{Action="validate",InstallationID=id,UserID=user,Stamp=stamp,ConnectionID=connection},commandType:CommandType.StoredProcedure)==id;}
|
||||
}
|
||||
@ -24,7 +24,7 @@ When an approved release is published, use its verified download and close Word
|
||||
|
||||
# Connect and review
|
||||
|
||||
Open Companion, sign in through your normal PlotDirector browser session and select the authorised book. Remembering a book association is optional and requires permission to modify document metadata; it never saves or rewrites manuscript prose.
|
||||
On first connection, approve this Companion installation through your normal PlotDirector browser session and select an authorised book. In version 1.0.0.14, the approved installation reconnects automatically after normal restarts, network interruptions and short-lived access expiry. Credentials and local preferences are protected for your Windows user and scoped to the PlotDirector server/account. Book associations are remembered locally and checked against current permissions. Remembering the association inside the Word document is an additional, optional metadata change; it never saves or rewrites prose.
|
||||
|
||||
Use Heading 1 for chapter headings. In the website’s existing manuscript import wizard, choose the same book as the linked Word document, then select **Import manuscript**. This explicitly requests a bounded reading of that document and uploads a server-side capture. Wait for PlotDirector to acknowledge receipt before closing Word. Chapter and scene analysis, locations, characters, assets, summaries and the existing review stages remain in PlotDirector; the Companion does not provide a second importer.
|
||||
|
||||
@ -38,7 +38,7 @@ Save Word normally before capturing when you want live positional scene mapping.
|
||||
|
||||
The Companion provides browser-approved sign-in, the active Word document, its authorised book association, connection checks and troubleshooting. Import, analysis, Context and Intent are launched from PlotDirector. The normal tray interface no longer contains chapter selection or a separate analysis workflow.
|
||||
|
||||
The managed interface follows Windows light or dark appearance. Full PlotDirector theme synchronisation is not available. Source version **1.0.0.13** needs a new Windows build, unified installer qualification and real Word tests; Atlas has not installed or qualified it.
|
||||
The managed interface follows Windows light or dark appearance. Full PlotDirector theme synchronisation is not available. Source version **1.0.0.14** needs a new Windows build, unified installer qualification and real Word tests; Atlas has not installed or qualified it.
|
||||
|
||||
## Context and Intent beside Word
|
||||
|
||||
@ -49,3 +49,15 @@ Context shows saved scene details, nearby dated scenes, participants, thread dev
|
||||
Intent shows your saved plan and objectives. On **Evidence**, **Show saved evidence** loads an existing assessment without requesting AI. **Assess saved prose with AI** explicitly compares saved manuscript prose with your intentions and may incur AI costs. Unchanged prose and plans reuse the saved result. Evidence can be kept, dismissed or deferred; objective completion is still your decision in the scene editor. A stale assessment is labelled when the saved plan or prose changes.
|
||||
|
||||
These assessments use imported PlotDirector manuscript text, not unsaved Word edits or a scene summary. Import or otherwise update saved source through the established workflow before reassessing. No automatic prose synchronisation, silent objective ticking or Word editing is performed.
|
||||
|
||||
## Approval, closing and sign-out
|
||||
|
||||
Closing the Companion window hides it in the tray. **Quit Companion** stops its process without forgetting your account, settings or device approval. Windows sign-in or opening a new Word process can start it again. An already-running Word process respects an explicit Quit; use **Open Companion** to resume immediately.
|
||||
|
||||
Access credentials last ten minutes and renew automatically. The separate installation approval is revocable and expires after 90 days without renewal. No permanent access token is saved. Normal renewal does not open your browser or upload prose.
|
||||
|
||||
**Sign out**, **Change account**, revoking an installation under [approved Companion installations](/native-companion/installations), or signing out of PlotDirector deliberately removes approval. Website sign-out revokes all approved Companions for that account. Offline Companion sign-out clears local authorisation immediately and keeps a protected revocation request for when the server is reachable; its status says when that server confirmation is still pending.
|
||||
|
||||
The connection states are **Connected**, **Reconnecting**, **Disconnected** and **Action required**. A connected agent does not mean a Word document is connected. Check document registration separately. If access to a book is removed, its saved association cannot authorise a manuscript transfer.
|
||||
|
||||
Version 1.0.0.13 never stored installation approval. After upgrading to 1.0.0.14 and the matching server update, approve this installation once; subsequent normal reconnects do not need approval. Windows-protected storage and native startup still require qualification on your actual Windows profile. Do not use a private Codex profile as evidence of a normal-user installation.
|
||||
|
||||
@ -95,6 +95,8 @@ public class Program
|
||||
builder.Services.AddRateLimiter(options => options.AddPolicy("native-pair", context => System.Threading.RateLimiting.RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new System.Threading.RateLimiting.FixedWindowRateLimiterOptions { PermitLimit=120, Window=TimeSpan.FromMinutes(1), QueueLimit=0 })));
|
||||
builder.Services.AddSingleton(TimeProvider.System);
|
||||
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.DesktopPairing>();
|
||||
builder.Services.AddScoped<INativeInstallationRepository, NativeInstallationRepository>();
|
||||
builder.Services.AddScoped<PlotLine.Services.NativeCompanion.NativeInstallationService>();
|
||||
builder.Services.AddAuthentication().AddScheme<Microsoft.AspNetCore.Authentication.AuthenticationSchemeOptions, PlotLine.Services.NativeCompanion.DesktopAuthentication>(PlotLine.Services.NativeCompanion.DesktopPairing.Scheme, _ => { });
|
||||
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.NativeAnalysisCache>();
|
||||
builder.Services.AddScoped<PlotLine.Data.IIntentAssessmentRepository,PlotLine.Data.IntentAssessmentRepository>();
|
||||
|
||||
@ -10,14 +10,14 @@ using PlotLine.Data;
|
||||
|
||||
namespace PlotLine.Services.NativeCompanion;
|
||||
|
||||
// Short lived, browser-approved desktop grants. No password/cookie export or refresh secret.
|
||||
// Existing browser-approved pairing. Durable installation authorisation is optional and negotiated.
|
||||
public sealed class DesktopPairing(IDataProtectionProvider protection, TimeProvider clock)
|
||||
{
|
||||
public const string Scheme="NativeCompanion";
|
||||
private readonly IDataProtector protector=protection.CreateProtector("PlotDirector.NativeCompanion.Access.v1");
|
||||
private readonly object gate=new();
|
||||
private readonly Dictionary<string,Pending> pending=[];
|
||||
public string Start(string challenge)
|
||||
public string Start(string challenge,bool persistent=false,Guid connection=default,string deviceName="Windows Companion")
|
||||
{
|
||||
if(challenge.Length!=64||!challenge.All(Uri.IsHexDigit))throw new ArgumentException("Invalid pairing challenge.");
|
||||
lock(gate)
|
||||
@ -25,33 +25,34 @@ public sealed class DesktopPairing(IDataProtectionProvider protection, TimeProvi
|
||||
foreach(var key in pending.Where(p=>p.Value.Expires<clock.GetUtcNow()).Select(p=>p.Key).ToArray())pending.Remove(key);
|
||||
if(pending.Count>=100)throw new InvalidOperationException("Pairing busy. Try later.");
|
||||
var code=Convert.ToHexString(RandomNumberGenerator.GetBytes(12));
|
||||
pending[code]=new(challenge,clock.GetUtcNow().AddMinutes(5));return code;
|
||||
pending[code]=new(challenge,clock.GetUtcNow().AddMinutes(5)){Persistent=persistent,ConnectionId=connection,DeviceName=deviceName.Length>80?deviceName[..80]:deviceName};return code;
|
||||
}
|
||||
}
|
||||
public bool Exists(string code){lock(gate)return pending.TryGetValue(code,out var p)&&p.Expires>clock.GetUtcNow()&&p.UserId==null;}
|
||||
public bool Approve(string code,int userId,Guid stamp,bool retainImport=false)
|
||||
{lock(gate){if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||p.UserId!=null)return false;p.UserId=userId;p.Stamp=stamp;p.RetainImport=retainImport;return true;}}
|
||||
public string? Redeem(string code,string verifier)
|
||||
public bool Persistent(string code){lock(gate)return pending.TryGetValue(code,out var p)&&p.Persistent;}
|
||||
public sealed record Approval(int UserId,Guid Stamp,bool RetainImport,bool Persistent,Guid ConnectionId,string DeviceName);
|
||||
public Approval? RedeemApproval(string code,string verifier)
|
||||
{
|
||||
if(verifier.Length<43||verifier.Length>128)return null;
|
||||
lock(gate)
|
||||
{
|
||||
lock(gate){
|
||||
if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(p.Challenge),Encoding.ASCII.GetBytes(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier))))))return null;
|
||||
if(p.UserId is not int user)return null;
|
||||
pending.Remove(code);
|
||||
return protector.Protect(JsonSerializer.Serialize(new Grant(user,p.Stamp,clock.GetUtcNow().AddHours(4),p.RetainImport)));
|
||||
if(p.UserId is not int user)return null;pending.Remove(code);return new(user,p.Stamp,p.RetainImport,p.Persistent,p.ConnectionId,p.DeviceName);
|
||||
}
|
||||
}
|
||||
public string Issue(Grant grant)=>protector.Protect(JsonSerializer.Serialize(grant));
|
||||
public string? Redeem(string code,string verifier){var approval=RedeemApproval(code,verifier);return approval==null?null:Issue(new(approval.UserId,approval.Stamp,clock.GetUtcNow().AddHours(4),approval.RetainImport));}
|
||||
public Grant? Read(string token)
|
||||
{
|
||||
try{var grant=JsonSerializer.Deserialize<Grant>(protector.Unprotect(token));return grant?.Expires>clock.GetUtcNow()?grant:null;}
|
||||
catch(Exception e)when(e is CryptographicException or JsonException or FormatException){return null;}
|
||||
}
|
||||
public sealed record Grant(int UserId,Guid Stamp,DateTimeOffset Expires,bool RetainImport=false);
|
||||
private sealed class Pending(string challenge,DateTimeOffset expires){public string Challenge=challenge;public DateTimeOffset Expires=expires;public int? UserId;public Guid Stamp;public bool RetainImport;}
|
||||
public sealed record Grant(int UserId,Guid Stamp,DateTimeOffset Expires,bool RetainImport=false,Guid? InstallationId=null,Guid? ConnectionId=null);
|
||||
private sealed class Pending(string challenge,DateTimeOffset expires){public string Challenge=challenge;public DateTimeOffset Expires=expires;public int? UserId;public Guid Stamp;public bool RetainImport;public bool Persistent;public Guid ConnectionId;public string DeviceName="Windows Companion";}
|
||||
}
|
||||
|
||||
public sealed class DesktopAuthentication(IOptionsMonitor<AuthenticationSchemeOptions> options,ILoggerFactory logger,UrlEncoder encoder,DesktopPairing pairing,IUserRepository users)
|
||||
public sealed class DesktopAuthentication(IOptionsMonitor<AuthenticationSchemeOptions> options,ILoggerFactory logger,UrlEncoder encoder,DesktopPairing pairing,IUserRepository users,INativeInstallationRepository? installations=null)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options,logger,encoder)
|
||||
{
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
@ -62,7 +63,10 @@ public sealed class DesktopAuthentication(IOptionsMonitor<AuthenticationSchemeOp
|
||||
var grant=pairing.Read(header[7..]);if(grant==null)return AuthenticateResult.Fail("Sign in again.");
|
||||
var user=await users.GetByIdAsync(grant.UserId);
|
||||
if(user==null||user.SecurityStamp!=grant.Stamp||(user.IsLocked&&(!user.LockoutEndUtc.HasValue||user.LockoutEndUtc>DateTime.UtcNow)))return AuthenticateResult.Fail("Sign in again.");
|
||||
var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString()),new("NativeCompanion.RetainImport",grant.RetainImport?"true":"false"),new("NativeCompanion.Expires",grant.Expires.UtcDateTime.ToString("O")),new("NativeCompanion.Grant",Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(header[7..]))))],DesktopPairing.Scheme);
|
||||
if(grant.InstallationId.HasValue&&(grant.ConnectionId==null||installations==null||!await installations.Validate(grant.InstallationId.Value,grant.UserId,grant.Stamp,grant.ConnectionId.Value)))return AuthenticateResult.Fail("Installation approval expired or revoked.");
|
||||
var key=grant.InstallationId.HasValue?NativeInstallationService.GrantKey(grant.InstallationId.Value,grant.ConnectionId!.Value):Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(header[7..])));
|
||||
var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString()),new("NativeCompanion.RetainImport",grant.RetainImport?"true":"false"),new("NativeCompanion.Expires",grant.Expires.UtcDateTime.ToString("O")),new("NativeCompanion.Grant",key)],DesktopPairing.Scheme);
|
||||
if(grant.InstallationId.HasValue){identity.AddClaim(new("NativeCompanion.Installation",grant.InstallationId.Value.ToString("D")));identity.AddClaim(new("NativeCompanion.Connection",grant.ConnectionId!.Value.ToString("D")));}
|
||||
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity),DesktopPairing.Scheme));
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,30 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Hubs;
|
||||
namespace PlotLine.Services.NativeCompanion;
|
||||
public sealed record NativeDeviceTokens(string AccessToken,DateTimeOffset ExpiresUtc,Guid InstallationId,int AccountId,string AccountName,DateTimeOffset RefreshExpiresUtc,Guid ConnectionId,string? DeviceSecret=null){public override string ToString()=>"NativeDeviceTokens [redacted]";}
|
||||
public sealed record NativeDeviceRenew(Guid InstallationId,string Credential,string NextCredential,Guid RotationId,Guid ConnectionId){public override string ToString()=>"NativeDeviceRenew [redacted]";}
|
||||
public sealed class NativeInstallationService(INativeInstallationRepository repository,DesktopPairing pairing,NativePresenceStore presence,TimeProvider clock,IHubContext<NativeCompanionPresenceHub>? live=null)
|
||||
{
|
||||
public static string GrantKey(Guid installation,Guid connection)=>$"installation:{installation:D}:session:{connection:D}";
|
||||
public static byte[] Hash(string secret){if(secret==null||secret.Length!=64||!secret.All(Uri.IsHexDigit))throw new ArgumentException("Invalid installation credential.");return SHA256.HashData(Encoding.ASCII.GetBytes(secret));}
|
||||
public async Task<NativeDeviceTokens> Create(DesktopPairing.Approval approval)
|
||||
{
|
||||
var secret=Convert.ToHexString(RandomNumberGenerator.GetBytes(32));var id=Guid.NewGuid();
|
||||
var row=(await repository.Run("create",id,approval.UserId,approval.Stamp,approval.DeviceName,approval.RetainImport,Hash(secret),connection:approval.ConnectionId)).Single();return Tokens(row,secret);
|
||||
}
|
||||
public async Task<NativeDeviceTokens?> Renew(NativeDeviceRenew request)
|
||||
{
|
||||
if(request.InstallationId==Guid.Empty||request.RotationId==Guid.Empty||request.ConnectionId==Guid.Empty)return null;
|
||||
var row=(await repository.Run("rotate",request.InstallationId,hash:Hash(request.Credential),nextHash:Hash(request.NextCredential),rotation:request.RotationId,connection:request.ConnectionId)).SingleOrDefault();if(row==null)return null;
|
||||
if(row.PreviousConnectionID.HasValue&&row.PreviousConnectionID!=row.ConnectionID)presence.Revoke(row.UserID,GrantKey(row.InstallationID,row.PreviousConnectionID.Value),clock.GetUtcNow().AddMinutes(15));
|
||||
return Tokens(row);
|
||||
}
|
||||
private NativeDeviceTokens Tokens(NativeInstallation row,string? secret=null){var expires=clock.GetUtcNow().AddMinutes(10);return new(pairing.Issue(new(row.UserID,row.SecurityStamp,expires,row.RetainImport,row.InstallationID,row.ConnectionID)),expires,row.InstallationID,row.UserID,row.AccountName,row.RefreshExpiresUtc,row.ConnectionID,secret);}
|
||||
public async Task RevokeSecret(NativeDeviceRenew request){var rows=await repository.Run("revoke-secret",request.InstallationId,hash:Hash(request.Credential),nextHash:string.IsNullOrEmpty(request.NextCredential)?null:Hash(request.NextCredential),rotation:request.RotationId);await Invalidate(rows);}
|
||||
public async Task<bool> RevokeUser(int user,Guid id){var rows=await repository.Run("revoke-user",id,user);await Invalidate(rows);return rows.Count>0;}
|
||||
public async Task RevokeAll(int user)=>await Invalidate(await repository.Run("revoke-all",user:user));
|
||||
private async Task Invalidate(IReadOnlyList<NativeInstallation> rows){foreach(var row in rows)presence.Revoke(row.UserID,GrantKey(row.InstallationID,row.ConnectionID),clock.GetUtcNow().AddMinutes(15));if(live!=null)foreach(var user in rows.Select(r=>r.UserID).Distinct())await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync("NativePresenceChanged",new{bookId=0});}
|
||||
}
|
||||
@ -25,5 +25,6 @@ public sealed class NativePresenceStore(TimeProvider clock)
|
||||
public AdapterCommand? TakeNavigation(int user,string grant,Guid instance,Guid session)
|
||||
{lock(gate){Prune();var key=(user,instance,session);return leases.TryGetValue(key,out var lease)&&lease.Grant==grant&&navigation.Remove(key,out var command)?command:null;}}
|
||||
public void Remove(int user,string grant,Guid instance,Guid session,long? throughSequence=null){lock(gate)if(leases.TryGetValue((user,instance,session),out var prior)&&prior.Grant==grant&&(!throughSequence.HasValue||prior.Position.Sequence<=throughSequence.Value)){leases.Remove((user,instance,session));navigation.Remove((user,instance,session));}}
|
||||
public void DisconnectGrant(int user,string grant){lock(gate)foreach(var key in leases.Where(p=>p.Value.User==user&&p.Value.Grant==grant).Select(p=>p.Key).ToArray()){leases.Remove(key);navigation.Remove(key);}}
|
||||
public void Revoke(int user,string grant,DateTimeOffset expiry){lock(gate){Prune();if(revoked.Count<8192)revoked[grant]=expiry;foreach(var key in leases.Where(p=>p.Value.User==user&&p.Value.Grant==grant).Select(p=>p.Key).ToArray())leases.Remove(key);}}
|
||||
}
|
||||
|
||||
93
PlotLine/Sql/238_NativeInstallationAuthorisation.sql
Normal file
93
PlotLine/Sql/238_NativeInstallationAuthorisation.sql
Normal file
@ -0,0 +1,93 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF OBJECT_ID('dbo.NativeCompanionInstallations','U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.NativeCompanionInstallations(
|
||||
InstallationID uniqueidentifier NOT NULL PRIMARY KEY,UserID int NOT NULL,
|
||||
SecurityStamp uniqueidentifier NOT NULL,DeviceName nvarchar(80) NOT NULL,RetainImport bit NOT NULL,
|
||||
RefreshHash binary(32) NOT NULL,PreviousHash binary(32) NULL,RotationID uniqueidentifier NULL,
|
||||
ConnectionID uniqueidentifier NOT NULL,RefreshExpiresUtc datetimeoffset NOT NULL,
|
||||
CreatedUtc datetimeoffset NOT NULL,LastRenewedUtc datetimeoffset NOT NULL,LastSeenUtc datetimeoffset NULL,
|
||||
DisconnectedUtc datetimeoffset NULL,RevokedUtc datetimeoffset NULL,
|
||||
CONSTRAINT FK_NativeCompanionInstallations_User FOREIGN KEY(UserID) REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE);
|
||||
CREATE INDEX IX_NativeCompanionInstallations_User ON dbo.NativeCompanionInstallations(UserID,CreatedUtc DESC);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.NativeCompanionInstallation
|
||||
@Action varchar(16),@InstallationID uniqueidentifier=NULL,@UserID int=NULL,@Stamp uniqueidentifier=NULL,
|
||||
@DeviceName nvarchar(80)=NULL,@RetainImport bit=0,@RefreshHash varbinary(32)=NULL,@NextHash varbinary(32)=NULL,
|
||||
@RotationID uniqueidentifier=NULL,@ConnectionID uniqueidentifier=NULL,@Now datetimeoffset=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
IF @Now IS NULL SET @Now=TODATETIMEOFFSET(SYSUTCDATETIME(),'+00:00');
|
||||
DECLARE @PriorConnection uniqueidentifier=NULL;
|
||||
IF @Action='create'
|
||||
BEGIN
|
||||
IF DATALENGTH(@RefreshHash)<>32 OR @RefreshHash IS NULL OR @InstallationID IS NULL OR @ConnectionID IS NULL THROW 51000,'Invalid installation',1;
|
||||
BEGIN TRANSACTION;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.AppUser WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND SecurityStamp=@Stamp AND (IsLocked=0 OR LockoutEndUtc<=@Now)) THROW 51000,'Account approval changed',1;
|
||||
IF (SELECT COUNT(*) FROM dbo.NativeCompanionInstallations WHERE UserID=@UserID AND RevokedUtc IS NULL AND RefreshExpiresUtc>@Now)>=10 THROW 51000,'Revoke an unused Companion installation before approving another',1;
|
||||
INSERT dbo.NativeCompanionInstallations(InstallationID,UserID,SecurityStamp,DeviceName,RetainImport,RefreshHash,ConnectionID,RefreshExpiresUtc,CreatedUtc,LastRenewedUtc)
|
||||
VALUES(@InstallationID,@UserID,@Stamp,LEFT(COALESCE(@DeviceName,N'Windows Companion'),80),@RetainImport,@RefreshHash,@ConnectionID,DATEADD(day,90,@Now),@Now,@Now);
|
||||
COMMIT;
|
||||
END
|
||||
ELSE IF @Action='rotate'
|
||||
BEGIN
|
||||
IF @ConnectionID IS NULL OR @RotationID IS NULL OR @RefreshHash IS NULL OR @NextHash IS NULL OR DATALENGTH(@RefreshHash)<>32 OR DATALENGTH(@NextHash)<>32 RETURN;
|
||||
BEGIN TRANSACTION;
|
||||
SELECT @PriorConnection=i.ConnectionID FROM dbo.NativeCompanionInstallations i WITH(UPDLOCK,HOLDLOCK)
|
||||
JOIN dbo.AppUser u ON u.UserID=i.UserID AND u.SecurityStamp=i.SecurityStamp
|
||||
WHERE i.InstallationID=@InstallationID AND i.RevokedUtc IS NULL AND i.RefreshExpiresUtc>@Now AND (u.IsLocked=0 OR u.LockoutEndUtc<=@Now)
|
||||
AND (i.RefreshHash=@RefreshHash OR (i.PreviousHash=@RefreshHash AND i.RotationID=@RotationID AND i.RefreshHash=@NextHash AND i.ConnectionID=@ConnectionID));
|
||||
IF @PriorConnection IS NULL BEGIN COMMIT;RETURN;END;
|
||||
-- A retry must prove possession of the same pending next secret, not merely an old token.
|
||||
IF EXISTS(SELECT 1 FROM dbo.NativeCompanionInstallations WHERE InstallationID=@InstallationID AND RefreshHash=@RefreshHash)
|
||||
BEGIN
|
||||
IF @RefreshHash=@NextHash BEGIN COMMIT;RETURN;END;
|
||||
UPDATE dbo.NativeCompanionInstallations SET PreviousHash=RefreshHash,RefreshHash=@NextHash,RotationID=@RotationID,ConnectionID=@ConnectionID,
|
||||
RefreshExpiresUtc=DATEADD(day,90,@Now),LastRenewedUtc=@Now WHERE InstallationID=@InstallationID;
|
||||
END;
|
||||
COMMIT;
|
||||
END
|
||||
ELSE IF @Action='validate'
|
||||
BEGIN
|
||||
UPDATE i SET LastSeenUtc=CASE WHEN DisconnectedUtc IS NOT NULL OR LastSeenUtc IS NULL OR LastSeenUtc<DATEADD(second,-15,@Now) THEN @Now ELSE LastSeenUtc END,DisconnectedUtc=NULL
|
||||
FROM dbo.NativeCompanionInstallations i JOIN dbo.AppUser u ON u.UserID=i.UserID AND u.SecurityStamp=i.SecurityStamp
|
||||
WHERE i.InstallationID=@InstallationID AND i.UserID=@UserID AND i.SecurityStamp=@Stamp AND i.ConnectionID=@ConnectionID AND i.RevokedUtc IS NULL
|
||||
AND i.RefreshExpiresUtc>@Now AND (u.IsLocked=0 OR u.LockoutEndUtc<=@Now)
|
||||
AND (i.LastSeenUtc IS NULL OR i.LastSeenUtc<DATEADD(second,-15,@Now) OR i.DisconnectedUtc IS NOT NULL);
|
||||
IF @@ROWCOUNT=1 SELECT @InstallationID;
|
||||
ELSE SELECT i.InstallationID FROM dbo.NativeCompanionInstallations i JOIN dbo.AppUser u ON u.UserID=i.UserID AND u.SecurityStamp=i.SecurityStamp
|
||||
WHERE i.InstallationID=@InstallationID AND i.UserID=@UserID AND i.SecurityStamp=@Stamp AND i.ConnectionID=@ConnectionID AND i.RevokedUtc IS NULL AND i.RefreshExpiresUtc>@Now AND (u.IsLocked=0 OR u.LockoutEndUtc<=@Now);
|
||||
RETURN;
|
||||
END
|
||||
ELSE IF @Action='revoke-secret'
|
||||
BEGIN
|
||||
UPDATE dbo.NativeCompanionInstallations SET RevokedUtc=COALESCE(RevokedUtc,@Now) WHERE InstallationID=@InstallationID
|
||||
AND (RefreshHash=@RefreshHash OR (PreviousHash=@RefreshHash AND RotationID=@RotationID AND RefreshHash=@NextHash));
|
||||
IF @@ROWCOUNT=0 RETURN;
|
||||
END
|
||||
ELSE IF @Action='revoke-user'
|
||||
BEGIN
|
||||
UPDATE dbo.NativeCompanionInstallations SET RevokedUtc=COALESCE(RevokedUtc,@Now) WHERE InstallationID=@InstallationID AND UserID=@UserID;
|
||||
IF @@ROWCOUNT=0 RETURN;
|
||||
END
|
||||
ELSE IF @Action='revoke-all'
|
||||
BEGIN
|
||||
UPDATE dbo.NativeCompanionInstallations SET RevokedUtc=COALESCE(RevokedUtc,@Now) WHERE UserID=@UserID;
|
||||
END
|
||||
ELSE IF @Action='disconnect'
|
||||
BEGIN
|
||||
UPDATE dbo.NativeCompanionInstallations SET DisconnectedUtc=@Now WHERE InstallationID=@InstallationID AND UserID=@UserID AND ConnectionID=@ConnectionID;
|
||||
RETURN;
|
||||
END
|
||||
ELSE IF @Action<>'list' THROW 51000,'Unknown installation operation',1;
|
||||
SELECT i.InstallationID,i.UserID,i.SecurityStamp,i.DeviceName,i.RetainImport,i.ConnectionID,i.RefreshExpiresUtc,i.CreatedUtc,i.LastRenewedUtc,i.LastSeenUtc,i.DisconnectedUtc,i.RevokedUtc,
|
||||
COALESCE(NULLIF(u.DisplayName,N''),u.Email) AccountName,@PriorConnection PreviousConnectionID
|
||||
FROM dbo.NativeCompanionInstallations i JOIN dbo.AppUser u ON u.UserID=i.UserID
|
||||
WHERE (@InstallationID IS NULL OR i.InstallationID=@InstallationID) AND (@UserID IS NULL OR i.UserID=@UserID)
|
||||
ORDER BY i.CreatedUtc DESC;
|
||||
END;
|
||||
GO
|
||||
@ -228,3 +228,5 @@
|
||||
</script>
|
||||
}
|
||||
}
|
||||
|
||||
<div class="mt-3"><a href="/native-companion/installations">Manage approved Companion installations</a></div>
|
||||
|
||||
@ -3,13 +3,14 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Connect Word Companion</title><link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css"/></head><body>
|
||||
<div class="container py-4" style="max-width:45rem">
|
||||
<h1>Connect Word Companion</h1>
|
||||
<p>Account: <strong>@(User.Identity?.Name??"Your signed-in PlotDirector account")</strong>. To connect a different account, sign in to that account before approving.</p>
|
||||
<p>Approve only if you just chose Connect in your own Word Companion. This grants access to your available books and allows chapter text you explicitly submit to use PlotDirector's configured AI provider.</p>
|
||||
<p>Request code: <strong>@Model.Substring(Math.Max(0, Model.Length - 6))</strong>. Compare this with the Companion request before approving.</p>
|
||||
<p>No manuscript is uploaded by signing in. The connection expires after four hours.</p>
|
||||
<p>@(ViewData["PersistentInstallation"] is true?"No manuscript is uploaded by signing in. This installation stays approved across restarts, using short-lived access that renews automatically. Approval expires after 90 days without renewal, or when you sign out, change your account security, or revoke it in PlotDirector.":"No manuscript is uploaded by signing in. This older Companion uses a four-hour connection; update it for automatic reconnection.")</p>
|
||||
<form method="post" action="/native-companion/authorize">
|
||||
@Html.AntiForgeryToken()
|
||||
<input type="hidden" name="code" value="@Model" />
|
||||
<label class="form-check mb-3"><input class="form-check-input" type="checkbox" name="retainImport" value="true" /><span class="form-check-label">For this connection, retain encrypted copies of chapters I explicitly submit, so I can review and import them. Captures expire after 30 days; confirmed imports become my saved book data. This does not upload anything automatically.</span></label>
|
||||
<label class="form-check mb-3"><input class="form-check-input" type="checkbox" name="retainImport" value="true" /><span class="form-check-label">For this approved installation, retain encrypted copies of chapters I explicitly submit, so I can review and import them. Captures expire after 30 days; confirmed imports become my saved book data. This does not upload anything automatically.</span></label>
|
||||
<button type="submit" class="btn btn-primary">Approve this Word Companion connection</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
9
PlotLine/Views/NativeInstallation/Index.cshtml
Normal file
9
PlotLine/Views/NativeInstallation/Index.cshtml
Normal file
@ -0,0 +1,9 @@
|
||||
@model IReadOnlyList<PlotLine.Data.NativeInstallation>
|
||||
@{ViewData["Title"]="Approved Companion installations";}
|
||||
<div class="container py-4"><h1>Approved Companion installations</h1>
|
||||
<p>These installations can renew short-lived access automatically. Revoking approval disconnects that installation; its next sign-in requires your browser approval. No manuscript is uploaded by approving or renewing a connection.</p>
|
||||
@if(Model.Count==0){<p>No Companion installation has been approved yet.</p>}
|
||||
@foreach(var installation in Model){<section class="card mb-3"><div class="card-body"><h2 class="h5">@installation.DeviceName</h2><p>@installation.AccountName · Approved @installation.CreatedUtc.ToString("d") · @(installation.RevokedUtc.HasValue?"Revoked":installation.RefreshExpiresUtc<=DateTimeOffset.UtcNow?"Approval expired":"Approved")</p>
|
||||
@if(installation.RevokedUtc==null){<form method="post" action="/native-companion/installations/@installation.InstallationID/revoke">@Html.AntiForgeryToken()<button class="btn btn-outline-danger">Revoke approval</button></form>}
|
||||
</div></section>}
|
||||
<a asp-controller="ManageAccount" asp-action="Index">Back to account settings</a></div>
|
||||
@ -4,8 +4,13 @@
|
||||
function offline(message){root.dataset.nativeAuthority=root.dataset.officeConnected==='true'?'false':'true';root.dataset.connected='false';root.classList.remove('is-connected');root.classList.add('is-offline');text.textContent=message;root.title=message+' · saved PlotDirector information remains available.';}
|
||||
async function update(){if(pending||document.hidden)return;pending=true;try{
|
||||
const response=await fetch('/native-companion/status',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error();const leases=(await response.json()).filter(l=>Date.parse(l.expires)>Date.now());const active=leases.filter(l=>l.active&&l.wordAvailable),words=leases.filter(l=>l.wordAvailable);const lease=active.length===1?active[0]:words.length===1?words[0]:words.length===0?leases[0]:null;if(words.length>1&&active.length!==1){seen=true;offline('Choose an active Word document');}
|
||||
if(lease){seen=true;root.dataset.nativeAuthority='true';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');text.textContent=lease.wordAvailable?'Word connected':'Companion connected';root.title=lease.wordAvailable?lease.documentTitle+' · verified document heartbeat · last update '+new Date(lease.updated).toLocaleTimeString():'Companion connected; open a linked manuscript in Word.';}
|
||||
else if(seen){offline('Word disconnected or stale');}window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases}));
|
||||
if(lease){seen=true;root.dataset.nativeAuthority='true';root.dataset.connectionState='Connected';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');text.textContent=lease.wordAvailable?'Word connected':'Companion connected';root.title=lease.wordAvailable?lease.documentTitle+' · verified document heartbeat · last update '+new Date(lease.updated).toLocaleTimeString():'Companion connected; open a linked manuscript in Word.';}
|
||||
else {
|
||||
const stateResponse=await fetch('/native-companion/connection-state',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});
|
||||
const device=stateResponse.ok?await stateResponse.json():null;
|
||||
if(device?.known){seen=true;const label=device.state==='Connected'?'Companion connected · Word not connected':device.state;offline(label);root.dataset.connectionState=device.state;if(device.state==='Connected'){root.dataset.nativeAuthority='true';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');root.title='Approved Companion is connected. No live Word document is registered.';}}
|
||||
else if(seen)offline('Word disconnected or stale');
|
||||
}window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases}));
|
||||
}catch{if(seen){offline('Companion status unavailable');}window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[]}));}finally{pending=false;}}
|
||||
void update();const timer=setInterval(()=>void update(),15000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer));
|
||||
if(window.signalR){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',()=>{clearTimeout(refresh);refresh=setTimeout(()=>void update(),250);});connection.onreconnected(()=>void update());void connection.start().then(()=>void update()).catch(()=>{});window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user