14 KiB
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:
CloudGatewayretained only a four-hour Data Protection bearer grant in memory. Onlyserver-url.txtwas persisted.Dispose()calledSignOut(), 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
pausedfile, 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/pairand 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/renewrotates 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 and CryptUnprotectData documentation. 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.sqlpassed against guarded synthetic databasePlotDirector_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:
- Approve once; note the account/server. Link a saved test manuscript and adjust window size/preferences.
- 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.
- Leave connected past ten minutes and four hours. Confirm renewal preserves document/book context and does not read/upload prose or disrupt Word.
- 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.
- Change current book permissions; confirm a denied association does not authorise a transfer.
- 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.
- 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.
- 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.
- 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.
Delivery evidence
Implementation commit 5316ad539c was pushed on the existing shared branch and deployed to Development. Documentation-only follow-up commits descend from that implementation. Source version14, qualified version13 installer files and the installed Windows laptop were not built/reinstalled on Atlas.
- SQL238 applied after copy-only, checksummed backup and
RESTORE VERIFYONLY:/var/opt/mssql/backup/PlotDirector_Development_before_installation_auth_20261107T000508Z.bak. - Release:
/srv/apps/plotdirector-dev/releases/5316ad5-20261107T001259Z. - Previous application retained:
/srv/apps/plotdirector-dev/current-before-5316ad5-20261107T001259Z. - Published/deployed
PlotLine.dllSHA-256 both 0924407f7fa678887e527d8dae47a9f1b66b813e357099cac06be12425c16960. - Idle import/Story Intelligence guards passed before replacement; service active and local/public Development GETs returned 200. Existing configuration, data-protection keys, uploads and logs were preserved.
The actual Development HTTP/browser pass used a dedicated normally created/signed-in account and the real SQL-backed installation repository. It passed first-time persistent approval, short-lived access issuance, renewal without browser interaction, identical-rotation retry, rejection of another old-credential operation, new-process identity replacement, refusal of the prior process token, agent-only state without Word, owner-device management and antiforgery, revocation of unexpired access, and website-logout revocation of both access and future renewal. No manuscript or AI requests were made. The fixture account/device rows and private credential file were removed through the normal account-deletion path; the new AppUser cascade was exercised.
Repeat the explicit live authentication check on Development only:
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --dev-browser-identity create /tmp/pd-dev-browser-auth-qualification.json
node PlotLine.Tests/Browser/native-authorisation-development.cjs /tmp/pd-dev-browser-auth-qualification.json
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --dev-browser-identity cleanup /tmp/pd-dev-browser-auth-qualification.json
Provisioning verifies the effective Development database and creates its own pre-fixture backup. The browser test refuses non-fixture credentials and does not test real Windows protected storage. Private diagnostics/credential files must not be printed or committed.
Ready for the user's Windows qualification, not a claim that DPAPI, Windows restart or Word has been exercised on Atlas. No Production deployment or Windows installation was performed.