From 2235f4a5b55c13a7e79691733e38b0558f6e686a Mon Sep 17 00:00:00 2001 From: James Maes Date: Sun, 1 Nov 2026 11:03:21 -0600 Subject: [PATCH 1/8] chore(standards): enforce owned C# copyright headers Add the repository's existing James Maes/MIT notice to127owned C# files and correct one SPDX marker. Preserve all94existing copyright lines and all vendor/generated material. Enforce future headers with native IDE0073 under the existing warnings-as-errors build; sort only three adjacent import pairs. Roslyn tokens and original suffixes prove the comment-only edits; separate import multiset/remaining-text proofs cover the import corrections. Release solution and layout host build with zero warnings/errors. A deliberate missing header fails the build, restoration passes, and the targeted header formatter verification passes. No runtime behavior or workflow changes. Co-Authored-By: Codex (GPT-6) Signed-off-by: James Maes --- .editorconfig | 4 ++ docs/SOURCE-HEADER-COMPLIANCE.md | 38 +++++++++++++++++++ .../Authentication/OwnedPrintingSocket.cs | 5 +++ .../QqqSessionClient.Realtime.cs | 5 +++ .../Printing/DeviceControlCommand.cs | 5 +++ .../Printing/DeviceControlPoll.cs | 5 +++ .../Printing/DeviceControlReceipt.cs | 5 +++ .../Printing/DeviceDesiredState.cs | 5 +++ .../Printing/DownloadedDocument.cs | 5 +++ .../Printing/IFilePrinterBackend.cs | 5 +++ .../Printing/PrintApiClient.Controls.cs | 5 +++ .../Printing/PrintApiClient.Download.cs | 5 +++ .../Printing/PrintApiClient.Realtime.cs | 5 +++ .../Printing/PrintApiClient.Session.cs | 5 +++ .../Printing/PrintWorkerOptions.cs | 5 +++ .../Printing/PrintingRealtimeChannel.cs | 5 +++ .../Printing/RealtimeEnvelope.cs | 5 +++ .../Printing/RealtimeSettings.cs | 5 +++ .../Printing/TestPrintDefaults.cs | 5 +++ .../Transport/ApplicationTrafficMeter.cs | 5 +++ .../Transport/ApplicationTrafficSnapshot.cs | 5 +++ .../Transport/TrafficHttpContent.cs | 5 +++ .../Transport/TrafficStream.cs | 5 +++ .../AgentActivityLog.Settings.cs | 5 +++ .../AgentAuthentication.cs | 5 +++ .../AgentAuthenticationStatus.cs | 5 +++ .../AgentControlLabels.cs | 5 +++ .../AgentControlState.cs | 5 +++ .../AgentRuntime.Authentication.cs | 5 +++ .../AgentRuntime.ControlCommands.cs | 5 +++ .../AgentRuntime.ControlStatus.cs | 5 +++ .../AgentRuntime.Controls.cs | 7 +++- .../AgentRuntime.Enrollment.cs | 5 +++ .../AgentRuntime.Jobs.cs | 5 +++ .../AgentRuntime.Pipeline.cs | 5 +++ .../AgentRuntime.Realtime.cs | 5 +++ .../AgentRuntime.RealtimeQueue.cs | 5 +++ .../AgentRuntime.RealtimeStatus.cs | 7 +++- .../AgentRuntime.SignIn.cs | 5 +++ .../AgentRuntime.Transport.cs | 5 +++ .../AgentStore.Authentication.cs | 5 +++ .../AgentStore.Controls.cs | 5 +++ .../AgentStore.CreationTime.cs | 5 +++ src/Qqq.PrintAgent.Windows/AgentStore.Jobs.cs | 5 +++ .../AgentStore.Metadata.cs | 5 +++ .../AgentStore.Realtime.cs | 5 +++ .../AgentTransportSnapshot.cs | 5 +++ .../IPrinterJobControl.cs | 2 +- .../JobDetailsSnapshot.cs | 5 +++ .../JobEventSnapshot.cs | 5 +++ src/Qqq.PrintAgent.Windows/JobLabels.cs | 5 +++ src/Qqq.PrintAgent.Windows/JobPage.cs | 5 +++ src/Qqq.PrintAgent.Windows/JobQuery.cs | 5 +++ src/Qqq.PrintAgent.Windows/JobSorting.cs | 5 +++ src/Qqq.PrintAgent.Windows/LogSettings.cs | 5 +++ src/Qqq.PrintAgent.Windows/PrinterProfile.cs | 5 +++ .../QqqBrowserCallback.Paths.cs | 5 +++ .../QqqBrowserCallback.cs | 5 +++ .../SpoolCancellationException.cs | 5 +++ .../WindowsPrinters.Files.cs | 5 +++ .../WindowsSpoolerJobs.cs | 5 +++ src/Qqq.PrintAgent/JobDetailsView.cs | 5 +++ src/Qqq.PrintAgent/JobRowView.cs | 5 +++ .../MainWindow.Authentication.cs | 5 +++ src/Qqq.PrintAgent/MainWindow.Details.cs | 5 +++ src/Qqq.PrintAgent/MainWindow.JobExpansion.cs | 5 +++ src/Qqq.PrintAgent/MainWindow.LogSettings.cs | 5 +++ src/Qqq.PrintAgent/MainWindow.Metadata.cs | 5 +++ src/Qqq.PrintAgent/MainWindow.Sorting.cs | 5 +++ src/Qqq.PrintAgent/MainWindow.Transport.cs | 5 +++ src/Qqq.PrintAgent/PrinterDetailsView.cs | 5 +++ src/Qqq.PrintAgent/ProfileEditor.cs | 5 +++ src/Qqq.PrintAgent/TestPrintEditor.cs | 5 +++ src/Qqq.PrintAgent/TransportFormatting.cs | 5 +++ src/Qqq.PrintAgent/UiExceptionPolicy.cs | 5 +++ .../AgentControlConcurrencyTests.cs | 5 +++ .../AgentJobPageTests.cs | 5 +++ .../AgentLogSettingsTests.cs | 5 +++ .../AgentNewPairingTests.cs | 5 +++ .../AgentPipeFramingTests.cs | 5 +++ .../AgentPipeSecurityTests.cs | 5 +++ .../AgentRealtimeBandwidthTests.cs | 5 +++ .../AgentRealtimeGenerationTests.cs | 5 +++ .../AgentRealtimeOrderingTests.cs | 5 +++ .../AgentRealtimeRecoveryTests.cs | 5 +++ .../AgentRealtimeStartupTests.cs | 5 +++ .../AgentRealtimeStatusTests.cs | 5 +++ .../AgentRealtimeTests.cs | 5 +++ .../AgentRealtimeTransitionTests.cs | 5 +++ .../AgentRemoteControlTests.cs | 5 +++ .../AgentRuntimeBacklogTests.cs | 5 +++ .../AgentRuntimePipeResponseTests.cs | 5 +++ .../AgentRuntimeProfileTests.cs | 5 +++ .../AgentRuntimeTests.cs | 5 +++ .../AgentSessionIntegrationTests.cs | 5 +++ .../AgentSessionRecoveryTests.cs | 5 +++ .../AgentStoreScaleTests.cs | 5 +++ .../AgentStoreTests.cs | 5 +++ .../AgentTransportTests.cs | 5 +++ .../BrowserCallbackTests.cs | 5 +++ .../ControlFixture.cs | 5 +++ .../InstallerPreflightTests.cs | 5 +++ .../JobCreationTimeTests.cs | 5 +++ .../JobSortingTests.cs | 5 +++ .../Qqq.PrintAgent.Cli.Tests/MetadataTests.cs | 5 +++ .../MsiUpdateInstallerTests.cs | 5 +++ .../NativeCliRoutingTests.cs | 5 +++ .../PrinterExposureTests.cs | 5 +++ .../PrinterWorkerIsolationTests.cs | 2 +- .../Qqq.PrintAgent.Cli.Tests/ProgramTests.cs | 5 +++ .../RealtimeRuntimeFixture.cs | 5 +++ .../SessionFixture.cs | 5 +++ .../TestPrintPipeTests.cs | 5 +++ .../WindowsPrintersTests.cs | 5 +++ .../ApplicationTrafficMeterTests.cs | 5 +++ .../ApplicationTrafficTransportTests.cs | 5 +++ .../DeviceControlApiTests.cs | 5 +++ .../LoopbackWebSocketPeer.cs | 5 +++ .../MachineStateDirectoryTests.cs | 5 +++ .../PrintApiBoundsTests.cs | 5 +++ .../PrintWorkerTests.cs | 5 +++ .../ProtocolFixtureTests.cs | 5 +++ .../QqqSessionAuthenticationTests.cs | 5 +++ .../RealtimeSettingsTests.cs | 5 +++ .../RealtimeTransportTests.cs | 5 +++ .../TestPrintProfileTests.cs | 5 +++ tests/Qqq.PrintAgent.LayoutTests/App.xaml.cs | 5 +++ .../LayoutScenario.cs | 5 +++ tests/Qqq.PrintAgent.LayoutTests/Program.cs | 5 +++ .../SyntheticService.cs | 5 +++ .../TransportFormattingTests.cs | 5 +++ 131 files changed, 681 insertions(+), 4 deletions(-) create mode 100644 docs/SOURCE-HEADER-COMPLIANCE.md diff --git a/.editorconfig b/.editorconfig index 1351117..2800593 100644 --- a/.editorconfig +++ b/.editorconfig @@ -29,6 +29,10 @@ trim_trailing_whitespace = false end_of_line = crlf [*.cs] +# Repository-owned C# sources retain the MIT notice in LICENSE; enforced by the existing build. +file_header_template = Copyright (c) 2026 James Maes\nSPDX-License-Identifier: MIT +dotnet_diagnostic.IDE0073.severity = warning + #### Formatting (IDE0055 makes every rule below a build error) #### dotnet_diagnostic.IDE0055.severity = warning dotnet_sort_system_directives_first = true diff --git a/docs/SOURCE-HEADER-COMPLIANCE.md b/docs/SOURCE-HEADER-COMPLIANCE.md new file mode 100644 index 0000000..d95ec0c --- /dev/null +++ b/docs/SOURCE-HEADER-COMPLIANCE.md @@ -0,0 +1,38 @@ +# C# source header checkpoint + +The 2026-11-01 review of baseline `268f951b6728b0e69fedaf46769785c3f5ae55f4` +identified 127 of 221 tracked, repository-owned C# files without a copyright +header. Those files now carry the existing `Copyright (c) 2026 James Maes` and +`SPDX-License-Identifier: MIT` notice from this repository's LICENSE. Existing +copyright notices were preserved; one existing SPDX marker's casing was corrected. +Vendor notices and generated files were not rewritten. + +This addresses KofTwentyTwo K22-CODE-24, which recommends source license headers +outside Java. The native .NET IDE0073 analyzer now enforces this repository's +header through `.editorconfig` and the existing warnings-as-errors build. No +workflow, dependency or application behavior was changed. Three existing pairs +of namespace imports were also reordered to satisfy the targeted formatter. + +Validation: + +- All 221 tracked C# files have the canonical header. +- Roslyn token kind, original token text and value text are identical for all + 128 header/marker edits, before the separate import corrections. Each of the 127 additions also preserves the original + source text exactly after the prepended comment. This is source-token + equivalence, not a claim of byte-identical PDBs or assemblies. +- Release solution build passed with zero warnings and errors. +- The separate layout-test host also compiled with zero warnings and errors; + it was not launched. +- A deliberate missing-header case failed with IDE0073; restoring the exact + source made the build pass. No application or printer operations were run. +- `git diff --check` passed. + +The read-only `dotnet format style --diagnostics IDE0073 --verify-no-changes` +command also checks imports. It initially reported three existing import-order +differences in `AgentRuntime.Controls.cs`, `AgentRuntime.RealtimeStatus.cs`, and +`PrinterWorkerIsolationTests.cs`. Each correction swaps only two adjacent, +ordinary namespace imports. A separate comparison confirms the same import +multiset and identical remaining source text. The targeted command then exited +successfully; it emitted a workspace-loading warning. This filtered check does +not claim full formatter coverage. The full solution was rebuilt after the +import corrections. diff --git a/src/Qqq.PrintAgent.Core/Authentication/OwnedPrintingSocket.cs b/src/Qqq.PrintAgent.Core/Authentication/OwnedPrintingSocket.cs index ea413d4..0549fcf 100644 --- a/src/Qqq.PrintAgent.Core/Authentication/OwnedPrintingSocket.cs +++ b/src/Qqq.PrintAgent.Core/Authentication/OwnedPrintingSocket.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net.WebSockets; namespace Qqq.PrintAgent.Core.Authentication; diff --git a/src/Qqq.PrintAgent.Core/Authentication/QqqSessionClient.Realtime.cs b/src/Qqq.PrintAgent.Core/Authentication/QqqSessionClient.Realtime.cs index 9d45b36..d8ddf20 100644 --- a/src/Qqq.PrintAgent.Core/Authentication/QqqSessionClient.Realtime.cs +++ b/src/Qqq.PrintAgent.Core/Authentication/QqqSessionClient.Realtime.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net.WebSockets; namespace Qqq.PrintAgent.Core.Authentication; diff --git a/src/Qqq.PrintAgent.Core/Printing/DeviceControlCommand.cs b/src/Qqq.PrintAgent.Core/Printing/DeviceControlCommand.cs index c5fecaa..b03c4e9 100644 --- a/src/Qqq.PrintAgent.Core/Printing/DeviceControlCommand.cs +++ b/src/Qqq.PrintAgent.Core/Printing/DeviceControlCommand.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Printing; public sealed record DeviceControlCommand(string CommandId, string RequestId, string Action, string CreatedAt, string ExpiresAt, string? JobId = null); diff --git a/src/Qqq.PrintAgent.Core/Printing/DeviceControlPoll.cs b/src/Qqq.PrintAgent.Core/Printing/DeviceControlPoll.cs index d70c779..ae046ce 100644 --- a/src/Qqq.PrintAgent.Core/Printing/DeviceControlPoll.cs +++ b/src/Qqq.PrintAgent.Core/Printing/DeviceControlPoll.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Printing; public sealed record DeviceControlPoll(int ControlVersion, string ServerTime, int PollIntervalSeconds, DeviceDesiredState DesiredState, IReadOnlyList Commands); diff --git a/src/Qqq.PrintAgent.Core/Printing/DeviceControlReceipt.cs b/src/Qqq.PrintAgent.Core/Printing/DeviceControlReceipt.cs index ec25a78..e74b403 100644 --- a/src/Qqq.PrintAgent.Core/Printing/DeviceControlReceipt.cs +++ b/src/Qqq.PrintAgent.Core/Printing/DeviceControlReceipt.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Printing; public sealed record DeviceControlReceipt(string ReceiptId, string Outcome, string CompletedAt, string? Message = null); diff --git a/src/Qqq.PrintAgent.Core/Printing/DeviceDesiredState.cs b/src/Qqq.PrintAgent.Core/Printing/DeviceDesiredState.cs index f5aa765..b0257af 100644 --- a/src/Qqq.PrintAgent.Core/Printing/DeviceDesiredState.cs +++ b/src/Qqq.PrintAgent.Core/Printing/DeviceDesiredState.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json.Serialization; namespace Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Core/Printing/DownloadedDocument.cs b/src/Qqq.PrintAgent.Core/Printing/DownloadedDocument.cs index 7742e9a..b3809db 100644 --- a/src/Qqq.PrintAgent.Core/Printing/DownloadedDocument.cs +++ b/src/Qqq.PrintAgent.Core/Printing/DownloadedDocument.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Printing; /// Owns a verified staging file and prevents replacement until the native worker finishes. diff --git a/src/Qqq.PrintAgent.Core/Printing/IFilePrinterBackend.cs b/src/Qqq.PrintAgent.Core/Printing/IFilePrinterBackend.cs index 8c7e86d..11a4125 100644 --- a/src/Qqq.PrintAgent.Core/Printing/IFilePrinterBackend.cs +++ b/src/Qqq.PrintAgent.Core/Printing/IFilePrinterBackend.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Printing; /// Consumes a verified file while its owner retains the read-only lease; no document travels in a control message. diff --git a/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Controls.cs b/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Controls.cs index 90dc1a6..9977cb5 100644 --- a/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Controls.cs +++ b/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Controls.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using System.Net; using System.Net.Http.Json; diff --git a/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Download.cs b/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Download.cs index 0fd584e..60df52d 100644 --- a/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Download.cs +++ b/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Download.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Diagnostics; using System.Security.Cryptography; diff --git a/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Realtime.cs b/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Realtime.cs index 836f0f1..9ec59e3 100644 --- a/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Realtime.cs +++ b/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Realtime.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Printing; public sealed partial class PrintApiClient diff --git a/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Session.cs b/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Session.cs index ab45d31..bb7e6ac 100644 --- a/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Session.cs +++ b/src/Qqq.PrintAgent.Core/Printing/PrintApiClient.Session.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Authentication; namespace Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Core/Printing/PrintWorkerOptions.cs b/src/Qqq.PrintAgent.Core/Printing/PrintWorkerOptions.cs index 1ffd8d1..6e8b787 100644 --- a/src/Qqq.PrintAgent.Core/Printing/PrintWorkerOptions.cs +++ b/src/Qqq.PrintAgent.Core/Printing/PrintWorkerOptions.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Printing; public sealed record PrintWorkerOptions diff --git a/src/Qqq.PrintAgent.Core/Printing/PrintingRealtimeChannel.cs b/src/Qqq.PrintAgent.Core/Printing/PrintingRealtimeChannel.cs index 42f3c9e..f3b7949 100644 --- a/src/Qqq.PrintAgent.Core/Printing/PrintingRealtimeChannel.cs +++ b/src/Qqq.PrintAgent.Core/Printing/PrintingRealtimeChannel.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Collections.Concurrent; using System.Net.WebSockets; using System.Text.Json; diff --git a/src/Qqq.PrintAgent.Core/Printing/RealtimeEnvelope.cs b/src/Qqq.PrintAgent.Core/Printing/RealtimeEnvelope.cs index ff49cb2..122d833 100644 --- a/src/Qqq.PrintAgent.Core/Printing/RealtimeEnvelope.cs +++ b/src/Qqq.PrintAgent.Core/Printing/RealtimeEnvelope.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; namespace Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Core/Printing/RealtimeSettings.cs b/src/Qqq.PrintAgent.Core/Printing/RealtimeSettings.cs index a57ecd9..f118c2f 100644 --- a/src/Qqq.PrintAgent.Core/Printing/RealtimeSettings.cs +++ b/src/Qqq.PrintAgent.Core/Printing/RealtimeSettings.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; namespace Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Core/Printing/TestPrintDefaults.cs b/src/Qqq.PrintAgent.Core/Printing/TestPrintDefaults.cs index 715ff68..6a71f91 100644 --- a/src/Qqq.PrintAgent.Core/Printing/TestPrintDefaults.cs +++ b/src/Qqq.PrintAgent.Core/Printing/TestPrintDefaults.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Printing; /// Suggested diagnostic defaults; the operator must still verify installed stock and resolution. diff --git a/src/Qqq.PrintAgent.Core/Transport/ApplicationTrafficMeter.cs b/src/Qqq.PrintAgent.Core/Transport/ApplicationTrafficMeter.cs index e805b3c..5fb6ee8 100644 --- a/src/Qqq.PrintAgent.Core/Transport/ApplicationTrafficMeter.cs +++ b/src/Qqq.PrintAgent.Core/Transport/ApplicationTrafficMeter.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Transport; /// Application payload bytes only: no headers, framing, TLS, credentials or document contents. diff --git a/src/Qqq.PrintAgent.Core/Transport/ApplicationTrafficSnapshot.cs b/src/Qqq.PrintAgent.Core/Transport/ApplicationTrafficSnapshot.cs index 1ef6e65..4f7cde3 100644 --- a/src/Qqq.PrintAgent.Core/Transport/ApplicationTrafficSnapshot.cs +++ b/src/Qqq.PrintAgent.Core/Transport/ApplicationTrafficSnapshot.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Transport; public sealed record ApplicationTrafficSnapshot(long UploadedBytes, long DownloadedBytes, double UploadBytesPerSecond, double DownloadBytesPerSecond, DateTimeOffset TotalsSinceUtc); diff --git a/src/Qqq.PrintAgent.Core/Transport/TrafficHttpContent.cs b/src/Qqq.PrintAgent.Core/Transport/TrafficHttpContent.cs index 1cf73a5..014a1ce 100644 --- a/src/Qqq.PrintAgent.Core/Transport/TrafficHttpContent.cs +++ b/src/Qqq.PrintAgent.Core/Transport/TrafficHttpContent.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; namespace Qqq.PrintAgent.Core.Transport; diff --git a/src/Qqq.PrintAgent.Core/Transport/TrafficStream.cs b/src/Qqq.PrintAgent.Core/Transport/TrafficStream.cs index f2bff60..a61885b 100644 --- a/src/Qqq.PrintAgent.Core/Transport/TrafficStream.cs +++ b/src/Qqq.PrintAgent.Core/Transport/TrafficStream.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Core.Transport; /// Counts completed payload reads or writes without buffering or retaining their contents. diff --git a/src/Qqq.PrintAgent.Windows/AgentActivityLog.Settings.cs b/src/Qqq.PrintAgent.Windows/AgentActivityLog.Settings.cs index a68277a..b5ec2eb 100644 --- a/src/Qqq.PrintAgent.Windows/AgentActivityLog.Settings.cs +++ b/src/Qqq.PrintAgent.Windows/AgentActivityLog.Settings.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Diagnostics; using System.Globalization; using System.Text; diff --git a/src/Qqq.PrintAgent.Windows/AgentAuthentication.cs b/src/Qqq.PrintAgent.Windows/AgentAuthentication.cs index c5d252d..207f04a 100644 --- a/src/Qqq.PrintAgent.Windows/AgentAuthentication.cs +++ b/src/Qqq.PrintAgent.Windows/AgentAuthentication.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Authentication; namespace Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent.Windows/AgentAuthenticationStatus.cs b/src/Qqq.PrintAgent.Windows/AgentAuthenticationStatus.cs index 51016ab..e0e0b78 100644 --- a/src/Qqq.PrintAgent.Windows/AgentAuthenticationStatus.cs +++ b/src/Qqq.PrintAgent.Windows/AgentAuthenticationStatus.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; /// Safe companion status, with no cookie, password or device proof. diff --git a/src/Qqq.PrintAgent.Windows/AgentControlLabels.cs b/src/Qqq.PrintAgent.Windows/AgentControlLabels.cs index 6f5923d..2bac844 100644 --- a/src/Qqq.PrintAgent.Windows/AgentControlLabels.cs +++ b/src/Qqq.PrintAgent.Windows/AgentControlLabels.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; public static class AgentControlLabels diff --git a/src/Qqq.PrintAgent.Windows/AgentControlState.cs b/src/Qqq.PrintAgent.Windows/AgentControlState.cs index abdf8a2..ce3a7e5 100644 --- a/src/Qqq.PrintAgent.Windows/AgentControlState.cs +++ b/src/Qqq.PrintAgent.Windows/AgentControlState.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Printing; namespace Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.Authentication.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.Authentication.cs index 3bea017..2adef90 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.Authentication.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.Authentication.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Authentication; using Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.ControlCommands.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.ControlCommands.cs index 7994655..0ee7977 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.ControlCommands.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.ControlCommands.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.ControlStatus.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.ControlStatus.cs index a8fc0ef..38cceb2 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.ControlStatus.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.ControlStatus.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; public sealed partial class AgentRuntime diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.Controls.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.Controls.cs index f3ba419..dedb0e8 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.Controls.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.Controls.cs @@ -1,8 +1,13 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Diagnostics; using System.Globalization; using System.Net; -using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Core.Authentication; +using Qqq.PrintAgent.Core.Printing; namespace Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.Enrollment.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.Enrollment.cs index 6cf7968..0bcb846 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.Enrollment.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.Enrollment.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Authentication; using Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.Jobs.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.Jobs.cs index 6392586..94bab08 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.Jobs.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.Jobs.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.Pipeline.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.Pipeline.cs index 36ccf59..6742ead 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.Pipeline.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.Pipeline.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Printing; namespace Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.Realtime.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.Realtime.cs index 9aafbbb..ab7c3b1 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.Realtime.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.Realtime.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net.WebSockets; using System.Text.Json; using System.Threading.Channels; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.RealtimeQueue.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.RealtimeQueue.cs index 4e21124..a954642 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.RealtimeQueue.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.RealtimeQueue.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Printing; namespace Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.RealtimeStatus.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.RealtimeStatus.cs index c75301a..b05e628 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.RealtimeStatus.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.RealtimeStatus.cs @@ -1,5 +1,10 @@ -using System.Threading.Channels; +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; +using System.Threading.Channels; using Qqq.PrintAgent.Core.Printing; namespace Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.SignIn.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.SignIn.cs index e02c7ee..e412285 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.SignIn.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.SignIn.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Authentication; using Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.Transport.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.Transport.cs index 3d5068a..484e0bf 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.Transport.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.Transport.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Transport; namespace Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent.Windows/AgentStore.Authentication.cs b/src/Qqq.PrintAgent.Windows/AgentStore.Authentication.cs index 4b3c215..ac6b961 100644 --- a/src/Qqq.PrintAgent.Windows/AgentStore.Authentication.cs +++ b/src/Qqq.PrintAgent.Windows/AgentStore.Authentication.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Security.Cryptography; using System.Text.Json; using Qqq.PrintAgent.Core.Authentication; diff --git a/src/Qqq.PrintAgent.Windows/AgentStore.Controls.cs b/src/Qqq.PrintAgent.Windows/AgentStore.Controls.cs index ec12ff9..394d0fd 100644 --- a/src/Qqq.PrintAgent.Windows/AgentStore.Controls.cs +++ b/src/Qqq.PrintAgent.Windows/AgentStore.Controls.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using System.Text.Json; using Microsoft.Data.Sqlite; diff --git a/src/Qqq.PrintAgent.Windows/AgentStore.CreationTime.cs b/src/Qqq.PrintAgent.Windows/AgentStore.CreationTime.cs index 90ceedf..63222ca 100644 --- a/src/Qqq.PrintAgent.Windows/AgentStore.CreationTime.cs +++ b/src/Qqq.PrintAgent.Windows/AgentStore.CreationTime.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using Microsoft.Data.Sqlite; diff --git a/src/Qqq.PrintAgent.Windows/AgentStore.Jobs.cs b/src/Qqq.PrintAgent.Windows/AgentStore.Jobs.cs index 180d196..c9039ef 100644 --- a/src/Qqq.PrintAgent.Windows/AgentStore.Jobs.cs +++ b/src/Qqq.PrintAgent.Windows/AgentStore.Jobs.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using Microsoft.Data.Sqlite; diff --git a/src/Qqq.PrintAgent.Windows/AgentStore.Metadata.cs b/src/Qqq.PrintAgent.Windows/AgentStore.Metadata.cs index bbcff76..c1d3883 100644 --- a/src/Qqq.PrintAgent.Windows/AgentStore.Metadata.cs +++ b/src/Qqq.PrintAgent.Windows/AgentStore.Metadata.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using Microsoft.Data.Sqlite; using Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Windows/AgentStore.Realtime.cs b/src/Qqq.PrintAgent.Windows/AgentStore.Realtime.cs index e318378..6c9ab48 100644 --- a/src/Qqq.PrintAgent.Windows/AgentStore.Realtime.cs +++ b/src/Qqq.PrintAgent.Windows/AgentStore.Realtime.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using Microsoft.Data.Sqlite; using Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent.Windows/AgentTransportSnapshot.cs b/src/Qqq.PrintAgent.Windows/AgentTransportSnapshot.cs index 6ae31e2..c95db3d 100644 --- a/src/Qqq.PrintAgent.Windows/AgentTransportSnapshot.cs +++ b/src/Qqq.PrintAgent.Windows/AgentTransportSnapshot.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; /// Local observations of the cloud transport. Totals span this service lifetime, including reconnects. diff --git a/src/Qqq.PrintAgent.Windows/IPrinterJobControl.cs b/src/Qqq.PrintAgent.Windows/IPrinterJobControl.cs index 31b0409..bf7acc7 100644 --- a/src/Qqq.PrintAgent.Windows/IPrinterJobControl.cs +++ b/src/Qqq.PrintAgent.Windows/IPrinterJobControl.cs @@ -1,6 +1,6 @@ /* * Copyright (c) 2026 James Maes - * SPDX-license-Identifier: MIT + * SPDX-License-Identifier: MIT */ namespace Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent.Windows/JobDetailsSnapshot.cs b/src/Qqq.PrintAgent.Windows/JobDetailsSnapshot.cs index d4be514..f038fcc 100644 --- a/src/Qqq.PrintAgent.Windows/JobDetailsSnapshot.cs +++ b/src/Qqq.PrintAgent.Windows/JobDetailsSnapshot.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; /// Retained local evidence for a job, independent of physical output confirmation. diff --git a/src/Qqq.PrintAgent.Windows/JobEventSnapshot.cs b/src/Qqq.PrintAgent.Windows/JobEventSnapshot.cs index 9d6fe18..22767c0 100644 --- a/src/Qqq.PrintAgent.Windows/JobEventSnapshot.cs +++ b/src/Qqq.PrintAgent.Windows/JobEventSnapshot.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; public sealed record JobEventSnapshot(string EventId, string Status, string RecordedAt, string? Message, string? SpoolerJobId, bool Delivered); diff --git a/src/Qqq.PrintAgent.Windows/JobLabels.cs b/src/Qqq.PrintAgent.Windows/JobLabels.cs index adc5840..9e6eb92 100644 --- a/src/Qqq.PrintAgent.Windows/JobLabels.cs +++ b/src/Qqq.PrintAgent.Windows/JobLabels.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; /// Shared visible job labels used by the companion and server-side local sorting. diff --git a/src/Qqq.PrintAgent.Windows/JobPage.cs b/src/Qqq.PrintAgent.Windows/JobPage.cs index 1b29beb..1afec71 100644 --- a/src/Qqq.PrintAgent.Windows/JobPage.cs +++ b/src/Qqq.PrintAgent.Windows/JobPage.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; public sealed record JobPage(IReadOnlyList Jobs, int TotalCount, int Offset, int PageSize, bool ServerQueueLimited = false); diff --git a/src/Qqq.PrintAgent.Windows/JobQuery.cs b/src/Qqq.PrintAgent.Windows/JobQuery.cs index 1a7254d..836b6a9 100644 --- a/src/Qqq.PrintAgent.Windows/JobQuery.cs +++ b/src/Qqq.PrintAgent.Windows/JobQuery.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; /// Queries durable local history; search matches the start of a job ID, title or printer name. diff --git a/src/Qqq.PrintAgent.Windows/JobSorting.cs b/src/Qqq.PrintAgent.Windows/JobSorting.cs index 95b7908..8299212 100644 --- a/src/Qqq.PrintAgent.Windows/JobSorting.cs +++ b/src/Qqq.PrintAgent.Windows/JobSorting.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using System.Text; diff --git a/src/Qqq.PrintAgent.Windows/LogSettings.cs b/src/Qqq.PrintAgent.Windows/LogSettings.cs index 5731a71..fda0dad 100644 --- a/src/Qqq.PrintAgent.Windows/LogSettings.cs +++ b/src/Qqq.PrintAgent.Windows/LogSettings.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; /// Machine-wide diagnostic limits. Daily rotation is always enabled. diff --git a/src/Qqq.PrintAgent.Windows/PrinterProfile.cs b/src/Qqq.PrintAgent.Windows/PrinterProfile.cs index 1df5ca2..897a175 100644 --- a/src/Qqq.PrintAgent.Windows/PrinterProfile.cs +++ b/src/Qqq.PrintAgent.Windows/PrinterProfile.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; /// Customer-facing queue metadata; the Windows queue name and printer ID remain unchanged. diff --git a/src/Qqq.PrintAgent.Windows/QqqBrowserCallback.Paths.cs b/src/Qqq.PrintAgent.Windows/QqqBrowserCallback.Paths.cs index 3bcfd36..0b328cf 100644 --- a/src/Qqq.PrintAgent.Windows/QqqBrowserCallback.Paths.cs +++ b/src/Qqq.PrintAgent.Windows/QqqBrowserCallback.Paths.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Security.AccessControl; namespace Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent.Windows/QqqBrowserCallback.cs b/src/Qqq.PrintAgent.Windows/QqqBrowserCallback.cs index 4c200c4..694e8f0 100644 --- a/src/Qqq.PrintAgent.Windows/QqqBrowserCallback.cs +++ b/src/Qqq.PrintAgent.Windows/QqqBrowserCallback.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Diagnostics; using System.IO.Pipes; using System.Runtime.InteropServices; diff --git a/src/Qqq.PrintAgent.Windows/SpoolCancellationException.cs b/src/Qqq.PrintAgent.Windows/SpoolCancellationException.cs index 2a02562..0893e3f 100644 --- a/src/Qqq.PrintAgent.Windows/SpoolCancellationException.cs +++ b/src/Qqq.PrintAgent.Windows/SpoolCancellationException.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Windows; /// A verified refusal that must survive the isolated worker boundary. diff --git a/src/Qqq.PrintAgent.Windows/WindowsPrinters.Files.cs b/src/Qqq.PrintAgent.Windows/WindowsPrinters.Files.cs index f96b430..b6b496a 100644 --- a/src/Qqq.PrintAgent.Windows/WindowsPrinters.Files.cs +++ b/src/Qqq.PrintAgent.Windows/WindowsPrinters.Files.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.ComponentModel; using System.Runtime.InteropServices; using System.Security.Cryptography; diff --git a/src/Qqq.PrintAgent.Windows/WindowsSpoolerJobs.cs b/src/Qqq.PrintAgent.Windows/WindowsSpoolerJobs.cs index 8a48389..8a01a71 100644 --- a/src/Qqq.PrintAgent.Windows/WindowsSpoolerJobs.cs +++ b/src/Qqq.PrintAgent.Windows/WindowsSpoolerJobs.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; diff --git a/src/Qqq.PrintAgent/JobDetailsView.cs b/src/Qqq.PrintAgent/JobDetailsView.cs index c7724ea..a3e7a30 100644 --- a/src/Qqq.PrintAgent/JobDetailsView.cs +++ b/src/Qqq.PrintAgent/JobDetailsView.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent/JobRowView.cs b/src/Qqq.PrintAgent/JobRowView.cs index 5da9db1..48b514e 100644 --- a/src/Qqq.PrintAgent/JobRowView.cs +++ b/src/Qqq.PrintAgent/JobRowView.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using CommunityToolkit.Mvvm.Input; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Automation; diff --git a/src/Qqq.PrintAgent/MainWindow.Authentication.cs b/src/Qqq.PrintAgent/MainWindow.Authentication.cs index 7d0e56f..4503443 100644 --- a/src/Qqq.PrintAgent/MainWindow.Authentication.cs +++ b/src/Qqq.PrintAgent/MainWindow.Authentication.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Diagnostics; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; diff --git a/src/Qqq.PrintAgent/MainWindow.Details.cs b/src/Qqq.PrintAgent/MainWindow.Details.cs index 69b0577..2038759 100644 --- a/src/Qqq.PrintAgent/MainWindow.Details.cs +++ b/src/Qqq.PrintAgent/MainWindow.Details.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; diff --git a/src/Qqq.PrintAgent/MainWindow.JobExpansion.cs b/src/Qqq.PrintAgent/MainWindow.JobExpansion.cs index 3e7c498..fffe01f 100644 --- a/src/Qqq.PrintAgent/MainWindow.JobExpansion.cs +++ b/src/Qqq.PrintAgent/MainWindow.JobExpansion.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; diff --git a/src/Qqq.PrintAgent/MainWindow.LogSettings.cs b/src/Qqq.PrintAgent/MainWindow.LogSettings.cs index c072ce7..60df557 100644 --- a/src/Qqq.PrintAgent/MainWindow.LogSettings.cs +++ b/src/Qqq.PrintAgent/MainWindow.LogSettings.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using KofTwentyTwo.AppKit.WinUI; using Microsoft.UI.Xaml; diff --git a/src/Qqq.PrintAgent/MainWindow.Metadata.cs b/src/Qqq.PrintAgent/MainWindow.Metadata.cs index 12f07e3..775c006 100644 --- a/src/Qqq.PrintAgent/MainWindow.Metadata.cs +++ b/src/Qqq.PrintAgent/MainWindow.Metadata.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using KofTwentyTwo.AppKit.WinUI; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; diff --git a/src/Qqq.PrintAgent/MainWindow.Sorting.cs b/src/Qqq.PrintAgent/MainWindow.Sorting.cs index 8a87333..0fa3d66 100644 --- a/src/Qqq.PrintAgent/MainWindow.Sorting.cs +++ b/src/Qqq.PrintAgent/MainWindow.Sorting.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Automation; using Microsoft.UI.Xaml.Controls; diff --git a/src/Qqq.PrintAgent/MainWindow.Transport.cs b/src/Qqq.PrintAgent/MainWindow.Transport.cs index d604f5a..d88a58f 100644 --- a/src/Qqq.PrintAgent/MainWindow.Transport.cs +++ b/src/Qqq.PrintAgent/MainWindow.Transport.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using System.Text.Json; using Microsoft.UI.Xaml; diff --git a/src/Qqq.PrintAgent/PrinterDetailsView.cs b/src/Qqq.PrintAgent/PrinterDetailsView.cs index 32b826f..bc82578 100644 --- a/src/Qqq.PrintAgent/PrinterDetailsView.cs +++ b/src/Qqq.PrintAgent/PrinterDetailsView.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Qqq.PrintAgent.Windows; diff --git a/src/Qqq.PrintAgent/ProfileEditor.cs b/src/Qqq.PrintAgent/ProfileEditor.cs index 24c79b1..c57be01 100644 --- a/src/Qqq.PrintAgent/ProfileEditor.cs +++ b/src/Qqq.PrintAgent/ProfileEditor.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; diff --git a/src/Qqq.PrintAgent/TestPrintEditor.cs b/src/Qqq.PrintAgent/TestPrintEditor.cs index a8c0ec0..a1c2ca0 100644 --- a/src/Qqq.PrintAgent/TestPrintEditor.cs +++ b/src/Qqq.PrintAgent/TestPrintEditor.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Qqq.PrintAgent.Core.Printing; diff --git a/src/Qqq.PrintAgent/TransportFormatting.cs b/src/Qqq.PrintAgent/TransportFormatting.cs index 9115092..e9feb8a 100644 --- a/src/Qqq.PrintAgent/TransportFormatting.cs +++ b/src/Qqq.PrintAgent/TransportFormatting.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; namespace Qqq.PrintAgent; diff --git a/src/Qqq.PrintAgent/UiExceptionPolicy.cs b/src/Qqq.PrintAgent/UiExceptionPolicy.cs index b4a131b..a2d032c 100644 --- a/src/Qqq.PrintAgent/UiExceptionPolicy.cs +++ b/src/Qqq.PrintAgent/UiExceptionPolicy.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent; /// Leaves a failed native layout unhandled after AppKit has recorded it. diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentControlConcurrencyTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentControlConcurrencyTests.cs index 9ea6dc5..1e99d5a 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentControlConcurrencyTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentControlConcurrencyTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentJobPageTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentJobPageTests.cs index 5da641d..93d09dd 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentJobPageTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentJobPageTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Microsoft.Data.Sqlite; using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentLogSettingsTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentLogSettingsTests.cs index a2d8846..4676a55 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentLogSettingsTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentLogSettingsTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using KofTwentyTwo.AppKit.Logging; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentNewPairingTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentNewPairingTests.cs index 3135713..a71824a 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentNewPairingTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentNewPairingTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using Qqq.PrintAgent.Core.Authentication; using Qqq.PrintAgent.Core.Printing; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentPipeFramingTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentPipeFramingTests.cs index 52320dc..342f8f7 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentPipeFramingTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentPipeFramingTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.IO.Pipes; using System.Text; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentPipeSecurityTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentPipeSecurityTests.cs index e0a200d..0aae1e8 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentPipeSecurityTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentPipeSecurityTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.IO.Pipes; using System.Security.AccessControl; using System.Security.Principal; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeBandwidthTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeBandwidthTests.cs index bd04165..dc42876 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeBandwidthTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeBandwidthTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Diagnostics; using System.Security.Cryptography; using System.Text; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeGenerationTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeGenerationTests.cs index 51077fe..172ef30 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeGenerationTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeGenerationTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.IO.Pipes; using Qqq.PrintAgent.Core.Authentication; using Qqq.PrintAgent.Core.Printing; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeOrderingTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeOrderingTests.cs index 7a51c87..18aa98e 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeOrderingTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeOrderingTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text; namespace Qqq.PrintAgent.Cli.Tests; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeRecoveryTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeRecoveryTests.cs index 3219a59..c1a94a1 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeRecoveryTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeRecoveryTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.IO.Pipes; using System.Text.Json; using Qqq.PrintAgent.Core.Printing; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeStartupTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeStartupTests.cs index 57badb2..e31308b 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeStartupTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeStartupTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Printing; namespace Qqq.PrintAgent.Cli.Tests; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeStatusTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeStatusTests.cs index 016edb6..6b440bc 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeStatusTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeStatusTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Printing; namespace Qqq.PrintAgent.Cli.Tests; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeTests.cs index 8aa6490..0cc0a21 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using Qqq.PrintAgent.Core.Printing; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeTransitionTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeTransitionTests.cs index 5cb4254..3ec8579 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeTransitionTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeTransitionTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRemoteControlTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRemoteControlTests.cs index 582a82f..310f426 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRemoteControlTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRemoteControlTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using System.Text.Json; using Qqq.PrintAgent.Core.Printing; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeBacklogTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeBacklogTests.cs index efe1356..0a2073b 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeBacklogTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeBacklogTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.IO.Pipes; using System.Net; using System.Text.Json; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimePipeResponseTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimePipeResponseTests.cs index 0d169c7..5cccd49 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimePipeResponseTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimePipeResponseTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.ComponentModel; using System.IO.Pipes; using System.Runtime.InteropServices; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeProfileTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeProfileTests.cs index 727e8de..a9b5976 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeProfileTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeProfileTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.IO.Pipes; using System.Net; using System.Text; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeTests.cs index 7f98d21..2678fd5 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRuntimeTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.IO.Pipes; using System.Net; using System.Text; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentSessionIntegrationTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentSessionIntegrationTests.cs index c5cd656..004b763 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentSessionIntegrationTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentSessionIntegrationTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using System.Text; using System.Text.Json; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentSessionRecoveryTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentSessionRecoveryTests.cs index 284dc88..91f41e2 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentSessionRecoveryTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentSessionRecoveryTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Security.Cryptography; using System.Text; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentStoreScaleTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentStoreScaleTests.cs index c83db79..5da80df 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentStoreScaleTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentStoreScaleTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Diagnostics; using System.Globalization; using System.Net; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentStoreTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentStoreTests.cs index ad4b2c2..f8bd2fc 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentStoreTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentStoreTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentTransportTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentTransportTests.cs index b797e1a..cbb30d0 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentTransportTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentTransportTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.IO.Pipes; using System.Text.Json; using Qqq.PrintAgent.Core.Printing; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/BrowserCallbackTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/BrowserCallbackTests.cs index 93e3a4a..f42756e 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/BrowserCallbackTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/BrowserCallbackTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Windows; namespace Qqq.PrintAgent.Cli.Tests; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/ControlFixture.cs b/tests/Qqq.PrintAgent.Cli.Tests/ControlFixture.cs index 013fc38..d5d2387 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/ControlFixture.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/ControlFixture.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using System.IO.Pipes; using System.Net; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/InstallerPreflightTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/InstallerPreflightTests.cs index e5f8cdf..7a608cf 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/InstallerPreflightTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/InstallerPreflightTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Diagnostics; using System.Xml.Linq; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/JobCreationTimeTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/JobCreationTimeTests.cs index 61bf5b7..c65c177 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/JobCreationTimeTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/JobCreationTimeTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Microsoft.Data.Sqlite; using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/JobSortingTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/JobSortingTests.cs index 715ddab..810e13b 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/JobSortingTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/JobSortingTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Globalization; using Microsoft.Data.Sqlite; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/MetadataTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/MetadataTests.cs index 16ea484..51ebd86 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/MetadataTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/MetadataTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Microsoft.Data.Sqlite; using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateInstallerTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateInstallerTests.cs index b783c1b..ee249f9 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateInstallerTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateInstallerTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Security.AccessControl; using System.Security.Cryptography; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs index ebcfc94..777cec9 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Windows; namespace Qqq.PrintAgent.Cli.Tests; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/PrinterExposureTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/PrinterExposureTests.cs index 3081847..b5af345 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/PrinterExposureTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/PrinterExposureTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/PrinterWorkerIsolationTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/PrinterWorkerIsolationTests.cs index 23e08e3..d954f80 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/PrinterWorkerIsolationTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/PrinterWorkerIsolationTests.cs @@ -5,8 +5,8 @@ using System.Diagnostics; using System.Globalization; -using Qqq.PrintAgent.Windows; using Qqq.PrintAgent.Core.Printing; +using Qqq.PrintAgent.Windows; namespace Qqq.PrintAgent.Cli.Tests; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs index 72bed6c..3aef2d0 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.Cli.Tests; public sealed class ProgramTests diff --git a/tests/Qqq.PrintAgent.Cli.Tests/RealtimeRuntimeFixture.cs b/tests/Qqq.PrintAgent.Cli.Tests/RealtimeRuntimeFixture.cs index 416343e..761d113 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/RealtimeRuntimeFixture.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/RealtimeRuntimeFixture.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Collections.Concurrent; using System.Globalization; using System.IO.Pipes; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/SessionFixture.cs b/tests/Qqq.PrintAgent.Cli.Tests/SessionFixture.cs index ae123a9..d1e4bdc 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/SessionFixture.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/SessionFixture.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using System.Text; using System.Text.Json; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/TestPrintPipeTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/TestPrintPipeTests.cs index f28804e..38e9dc8 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/TestPrintPipeTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/TestPrintPipeTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Cli.Tests/WindowsPrintersTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/WindowsPrintersTests.cs index a2c5759..abdc59d 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/WindowsPrintersTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/WindowsPrintersTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.ComponentModel; using Qqq.PrintAgent.Windows; diff --git a/tests/Qqq.PrintAgent.Core.Tests/ApplicationTrafficMeterTests.cs b/tests/Qqq.PrintAgent.Core.Tests/ApplicationTrafficMeterTests.cs index a2db436..74f8afe 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/ApplicationTrafficMeterTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/ApplicationTrafficMeterTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Qqq.PrintAgent.Core.Transport; namespace Qqq.PrintAgent.Core.Tests; diff --git a/tests/Qqq.PrintAgent.Core.Tests/ApplicationTrafficTransportTests.cs b/tests/Qqq.PrintAgent.Core.Tests/ApplicationTrafficTransportTests.cs index 47430ea..9b2857e 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/ApplicationTrafficTransportTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/ApplicationTrafficTransportTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using System.Net.WebSockets; using System.Security.Cryptography; diff --git a/tests/Qqq.PrintAgent.Core.Tests/DeviceControlApiTests.cs b/tests/Qqq.PrintAgent.Core.Tests/DeviceControlApiTests.cs index 92e66d9..4ff2cb7 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/DeviceControlApiTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/DeviceControlApiTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using System.Text; using System.Text.Json; diff --git a/tests/Qqq.PrintAgent.Core.Tests/LoopbackWebSocketPeer.cs b/tests/Qqq.PrintAgent.Core.Tests/LoopbackWebSocketPeer.cs index d742c04..27500ab 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/LoopbackWebSocketPeer.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/LoopbackWebSocketPeer.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using System.Net.Sockets; using System.Net.WebSockets; diff --git a/tests/Qqq.PrintAgent.Core.Tests/MachineStateDirectoryTests.cs b/tests/Qqq.PrintAgent.Core.Tests/MachineStateDirectoryTests.cs index 88ff71d..192eb06 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/MachineStateDirectoryTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/MachineStateDirectoryTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Runtime.Versioning; using System.Security.AccessControl; using System.Security.Principal; diff --git a/tests/Qqq.PrintAgent.Core.Tests/PrintApiBoundsTests.cs b/tests/Qqq.PrintAgent.Core.Tests/PrintApiBoundsTests.cs index c8cab75..e854c39 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/PrintApiBoundsTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/PrintApiBoundsTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using Qqq.PrintAgent.Core.Printing; diff --git a/tests/Qqq.PrintAgent.Core.Tests/PrintWorkerTests.cs b/tests/Qqq.PrintAgent.Core.Tests/PrintWorkerTests.cs index d1a272a..4478d31 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/PrintWorkerTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/PrintWorkerTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using System.Text; using System.Text.Json; diff --git a/tests/Qqq.PrintAgent.Core.Tests/ProtocolFixtureTests.cs b/tests/Qqq.PrintAgent.Core.Tests/ProtocolFixtureTests.cs index e11cad3..8e7a0b7 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/ProtocolFixtureTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/ProtocolFixtureTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using Qqq.PrintAgent.Core.Printing; diff --git a/tests/Qqq.PrintAgent.Core.Tests/QqqSessionAuthenticationTests.cs b/tests/Qqq.PrintAgent.Core.Tests/QqqSessionAuthenticationTests.cs index c7aa4a5..da900a7 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/QqqSessionAuthenticationTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/QqqSessionAuthenticationTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using System.Security.Cryptography; using System.Text; diff --git a/tests/Qqq.PrintAgent.Core.Tests/RealtimeSettingsTests.cs b/tests/Qqq.PrintAgent.Core.Tests/RealtimeSettingsTests.cs index e45b3f5..8f11cd8 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/RealtimeSettingsTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/RealtimeSettingsTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using System.Text.Json.Nodes; using Qqq.PrintAgent.Core.Printing; diff --git a/tests/Qqq.PrintAgent.Core.Tests/RealtimeTransportTests.cs b/tests/Qqq.PrintAgent.Core.Tests/RealtimeTransportTests.cs index bca7433..9057a07 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/RealtimeTransportTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/RealtimeTransportTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using System.Net.WebSockets; using System.Security.Cryptography; diff --git a/tests/Qqq.PrintAgent.Core.Tests/TestPrintProfileTests.cs b/tests/Qqq.PrintAgent.Core.Tests/TestPrintProfileTests.cs index 9a71f6a..b91f213 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/TestPrintProfileTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/TestPrintProfileTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Net; using System.Text.Json; using Qqq.PrintAgent.Core.Printing; diff --git a/tests/Qqq.PrintAgent.LayoutTests/App.xaml.cs b/tests/Qqq.PrintAgent.LayoutTests/App.xaml.cs index cfca8ed..e7a315d 100644 --- a/tests/Qqq.PrintAgent.LayoutTests/App.xaml.cs +++ b/tests/Qqq.PrintAgent.LayoutTests/App.xaml.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using KofTwentyTwo.AppKit.Logging; using Microsoft.UI.Xaml; diff --git a/tests/Qqq.PrintAgent.LayoutTests/LayoutScenario.cs b/tests/Qqq.PrintAgent.LayoutTests/LayoutScenario.cs index 349eafd..8d73c38 100644 --- a/tests/Qqq.PrintAgent.LayoutTests/LayoutScenario.cs +++ b/tests/Qqq.PrintAgent.LayoutTests/LayoutScenario.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Automation; diff --git a/tests/Qqq.PrintAgent.LayoutTests/Program.cs b/tests/Qqq.PrintAgent.LayoutTests/Program.cs index 37743bf..0669906 100644 --- a/tests/Qqq.PrintAgent.LayoutTests/Program.cs +++ b/tests/Qqq.PrintAgent.LayoutTests/Program.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using Microsoft.UI.Dispatching; namespace Qqq.PrintAgent; diff --git a/tests/Qqq.PrintAgent.LayoutTests/SyntheticService.cs b/tests/Qqq.PrintAgent.LayoutTests/SyntheticService.cs index 5883a18..8870d9f 100644 --- a/tests/Qqq.PrintAgent.LayoutTests/SyntheticService.cs +++ b/tests/Qqq.PrintAgent.LayoutTests/SyntheticService.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + using System.Text.Json; using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Core.Transport; diff --git a/tests/Qqq.PrintAgent.UiTests/TransportFormattingTests.cs b/tests/Qqq.PrintAgent.UiTests/TransportFormattingTests.cs index e1f08fc..29d8b6b 100644 --- a/tests/Qqq.PrintAgent.UiTests/TransportFormattingTests.cs +++ b/tests/Qqq.PrintAgent.UiTests/TransportFormattingTests.cs @@ -1,3 +1,8 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + namespace Qqq.PrintAgent.UiTests; public sealed class TransportFormattingTests -- 2.54.0 From fcd4d54d479a0f6eb9e149893749fa0953248bba Mon Sep 17 00:00:00 2001 From: James Maes Date: Sun, 1 Nov 2026 11:11:07 -0600 Subject: [PATCH 2/8] fix(dev): enforce virtual agent origin and version boundaries Supply the exact configured Origin for unsafe cookie-authenticated requests, reject foreign or credential-bearing targets before sending headers, and preserve redirect refusal. Validate canonical stable three-part printing versions and compare components without numeric rounding. The two regressions fail before the fix; all seven Node tests pass afterward. The owned loopback fixture proves missing and foreign Origin refusal and zero foreign credential requests. Add the dependency-free tests to tooling CI using the protocol repository's pinned Node setup. Actionlint and zizmor pass; no production app or physical printer operations. Co-Authored-By: Codex (GPT-6) Signed-off-by: James Maes --- .github/workflows/scripts.yml | 19 +++++ docs/security/threat-model.md | 10 +++ tools/virtual-agent/README.md | 5 ++ .../virtual-agent/test/virtual-agent.test.mjs | 80 ++++++++++++++++++- tools/virtual-agent/virtual-agent.mjs | 27 +++++-- 5 files changed, 132 insertions(+), 9 deletions(-) diff --git a/.github/workflows/scripts.yml b/.github/workflows/scripts.yml index ae7d126..81a2321 100644 --- a/.github/workflows/scripts.yml +++ b/.github/workflows/scripts.yml @@ -10,6 +10,25 @@ on: permissions: {} jobs: + virtual-agent: + name: virtual-agent + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Node + uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0 + with: + node-version: '24' + package-manager-cache: false + - name: Verify virtual-agent protocol and HTTP boundaries + run: node --test tools/virtual-agent/test/virtual-agent.test.mjs + powershell: name: powershell runs-on: windows-latest diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index fc17e22..3392af1 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -113,3 +113,13 @@ Direct MSI and branded installation enforce this invariant before using persiste Unreadable session ciphertext is quarantined only on explicit sign-out or after fresh sign-in and authoritative binding succeed. Unreadable device proof remains in place until explicit enrollment replaces it; old journal scopes and local printer exposure are retained. Recovery never invents device authority or retries old print submissions. A missing readable session cannot be remotely revoked by local sign-out; the UI reports the separate QQQ revocation requirement. Background traffic remains fail closed. Replacement pairing requires an explicit local setup choice and fresh standard QQQ authentication. Its persisted unbound identity prevents restoration from presenting old, revoked device proof. New claims remain gated until successful enrollment, binding and control synchronization. Default sign-in still requires the saved pairing's authoritative binding. Failed setup preserves old configuration; successful replacement changes journal scope without replaying prior-device work. + +### Virtual development agent HTTP boundary + +The virtual agent's native HTTP request helper rejects foreign origins before +attaching session or device credentials, refuses redirects, and sends the exact +configured Origin on unsafe cookie-authenticated requests. This preserves the +server's missing/foreign-Origin rejection. Discovery accepts canonical stable +three-part printing versions in major 2, matching the protocol fixtures. +Synthetic loopback HTTP tests cover these boundaries; they do not establish +production authentication, durable spooling or physical printing acceptance. diff --git a/tools/virtual-agent/README.md b/tools/virtual-agent/README.md index c584ff2..59486c8 100644 --- a/tools/virtual-agent/README.md +++ b/tools/virtual-agent/README.md @@ -35,3 +35,8 @@ OAuth2 is not supported. Credentials, device tokens and enrollment codes are nev Supported commands: `REFRESH_INVENTORY` (answers `INVENTORY_REFRESHED`); others are `UNSUPPORTED`. Tests: `node --test tools/virtual-agent/test/virtual-agent.test.mjs`. +The scripts workflow runs these tests with Node 24. HTTP tests use disposable +loopback servers and synthetic cookies, without a QQQ deployment or printer. +Discovery accepts only canonical stable three-part printing versions in major 2. +Authenticated native HTTP requests remain on the configured origin; unsafe +cookie requests include its exact Origin, and redirects are refused. diff --git a/tools/virtual-agent/test/virtual-agent.test.mjs b/tools/virtual-agent/test/virtual-agent.test.mjs index c8d8e2c..d0a827d 100644 --- a/tools/virtual-agent/test/virtual-agent.test.mjs +++ b/tools/virtual-agent/test/virtual-agent.test.mjs @@ -1,10 +1,86 @@ /* * Copyright 2026 QRun.IO, Inc. Licensed under the MIT License (see LICENSE). + * SPDX-License-Identifier: MIT */ import assert from 'node:assert/strict' import { createHash } from 'node:crypto' +import { mkdtempSync, rmSync } from 'node:fs' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { test } from 'node:test' -import { LIMITS, backoff, checkTransport, compareVersions, frame, outputName, parseArgs, requirePrinting, sessionCookie, verifyDocument } from '../virtual-agent.mjs' +import { Agent, LIMITS, backoff, checkTransport, compareVersions, frame, outputName, parseArgs, requirePrinting, sessionCookie, verifyDocument } from '../virtual-agent.mjs' + +// Stable native-major boundary from qqq-print-protocol/tools/verify-realtime.mjs. +test('discovery accepts stable compatible minors and rejects noncanonical versions', () => { + for (const version of ['2.0.0', '2.1.0', '2.7.3', '2.10.0']) { + assert.equal(requirePrinting({ extensions: [{ name: 'printing', version }] }).version, version) + } + for (const version of ['1.0.0', '1.1.0', '3.0.0', '2.0', '2', '2.01.0', '02.0.0', '2.0.00', '2.0.0-rc.1', '2.0.0+build', '2junk.0.0', '2.0.0.1', ' 2.0.0', '2.0.0\n', '', null, undefined, 2]) { + assert.throws(() => requirePrinting({ extensions: [{ name: 'printing', version }] }), undefined, String(version)) + } + assert.ok(compareVersions('2.9007199254740993.0', '2.9007199254740992.0') > 0) +}) + +/** Own only ephemeral loopback fixtures; no QQQ server, spooler or account is used. */ +async function listen(t, handler) { + const server = createServer(handler) + t.after(() => new Promise((resolve, reject) => { + server.close((error) => error ? reject(error) : resolve()) + server.closeAllConnections() + })) + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', resolve) + }) + return `http://127.0.0.1:${server.address().port}` +} + +/** Match the native localhost cookie/Origin boundary without changing its policy. */ +test('native cookie POSTs carry exact Origin; foreign targets and redirects receive no credentials', { timeout: 10000 }, async (t) => { + let foreignRequests = 0 + const foreign = await listen(t, (_request, response) => { + foreignRequests++ + response.end('{}') + }) + let accepted = 0 + let origin + origin = await listen(t, (request, response) => { + if (request.url === '/redirect') { + response.writeHead(302, { location: `${foreign}/capture` }) + response.end() + return + } + if (request.headers.cookie && !['GET', 'HEAD', 'OPTIONS'].includes(request.method) && request.headers.origin !== origin) { + response.writeHead(403) + response.end('{}') + return + } + assert.equal(request.headers.cookie, 'sessionUUID=synthetic-only') + if (request.method === 'POST') assert.equal(request.headers.origin, origin) + accepted++ + response.end('{}') + }) + const directory = mkdtempSync(join(tmpdir(), 'qqq-virtual-http-')) + t.after(() => rmSync(directory, { recursive: true, force: true })) + const agent = new Agent(parseArgs(['--server', origin, '--out', directory], {}), () => {}) + agent.cookie = 'sessionUUID=synthetic-only' + for (const badOrigin of [undefined, foreign]) { + const headers = { Cookie: agent.cookie } + if (badOrigin) headers.Origin = badOrigin + const response = await fetch(`${origin}/native`, { method: 'POST', headers, redirect: 'error' }) + assert.equal(response.status, 403) + await response.text() + } + for (const path of ['/qqq/v1/processes/fixture', '/qqq/v1/qbit/printing/devices/enroll', '/qqq/v1/qbit/printing/device/jobs/claim']) { + await agent.request('POST', path, { body: {} }) + } + assert.equal(accepted, 3) + await assert.rejects(agent.request('POST', `${foreign}/capture`, { body: {} }), /origin/i) + await assert.rejects(agent.request('POST', `//127.0.0.1:${new URL(foreign).port}/capture`, { body: {} }), /origin/i) + await assert.rejects(agent.request('GET', '/redirect')) + assert.equal(foreignRequests, 0) +}) test('requires printing >=2.0.0 <3.0.0', () => { assert.equal(requirePrinting({ extensions: [{ name: 'printing', version: '2.0.0' }] }).version, '2.0.0') @@ -47,7 +123,7 @@ test('frames, cookies, backoff, limits and arguments', () => { assert.equal(LIMITS.maxConcurrentPrints, 1) const o = parseArgs(['--server', 'http://localhost:8078/x', '--out', '/tmp/out', '--enroll', '--formats', 'pdf'], {}) assert.equal(o.server, 'http://localhost:8078') - assert.equal(o.state, '/tmp/out/.agent-state.json') + assert.equal(o.state, join(o.out, '.agent-state.json')) assert.deepEqual(o.formats, ['PDF']) assert.ok(o.enroll && !o.approve) assert.throws(() => parseArgs(['--formats', 'PS'], {}), /PDF/) diff --git a/tools/virtual-agent/virtual-agent.mjs b/tools/virtual-agent/virtual-agent.mjs index 881f209..07416ec 100644 --- a/tools/virtual-agent/virtual-agent.mjs +++ b/tools/virtual-agent/virtual-agent.mjs @@ -1,6 +1,7 @@ #!/usr/bin/env node /* * Copyright 2026 QRun.IO, Inc. Licensed under the MIT License (see LICENSE). + * SPDX-License-Identifier: MIT */ /** @@ -102,14 +103,21 @@ export function checkTransport(server) { throw new Error(`${server}: use https (plain http is accepted only for a loopback server)`) } -/** Compares dotted versions: negative, zero or positive. */ +/** Compare canonical stable SemVer without rounding large numeric components. */ export function compareVersions(a, b) { - const pa = String(a).split(/[.-]/).map((x) => Number.parseInt(x, 10) || 0) - const pb = String(b).split(/[.-]/).map((x) => Number.parseInt(x, 10) || 0) - for (let i = 0; i < 3; i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) - (pb[i] ?? 0) + const pa = stableVersionParts(a) + const pb = stableVersionParts(b) + for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] < pb[i] ? -1 : 1 return 0 } +/** Match the protocol's stable three-part version boundary, including exact end of input. */ +function stableVersionParts(version) { + const match = typeof version === 'string' && /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.exec(version) + if (!match || match[0] !== version) throw new Error('printing version is not supported: expected a canonical stable three-part version') + return match.slice(1).map((part) => BigInt(part)) +} + /** The realtime contract: printing >=2.0.0 <3.0.0 must be listed by GET /version. */ export function requirePrinting(version) { const printing = (version?.extensions ?? []).find((e) => e.name === 'printing') @@ -156,7 +164,7 @@ export function backoff(attempt, settings = {}, random = Math.random) { return Math.round(Math.min(max, Math.max(min, base * (1 - jitter + 2 * jitter * random())))) } -class Agent { +export class Agent { constructor(options, log = (line) => console.log(`${new Date().toISOString()} ${line}`)) { this.o = options this.log = log @@ -190,7 +198,12 @@ class Agent { } async request(method, path, { body, device = false, raw = false, form } = {}) { - const init = { method, headers: this.headers(device), redirect: 'error' } + const origin = new URL(this.o.server).origin + const url = new URL(path, origin) + if (url.origin !== origin || url.username || url.password) throw new Error('request target must remain on the configured server origin') + const verb = method.toUpperCase() + const init = { method: verb, headers: this.headers(device), redirect: 'error' } + if (this.cookie && !['GET', 'HEAD', 'OPTIONS'].includes(verb)) init.headers.Origin = origin if (form) { const data = new FormData() for (const [k, v] of Object.entries(form)) data.append(k, v) @@ -199,7 +212,7 @@ class Agent { init.headers['content-type'] = 'application/json' init.body = JSON.stringify(body) } - const response = await fetch(new URL(path, this.o.server), init) + const response = await fetch(url, init) if (!response.ok) { const text = await response.text().catch(() => '') let message = text -- 2.54.0 From 04bf345b94666d975ffab790bf550b3c42a54516 Mon Sep 17 00:00:00 2001 From: James Maes Date: Sun, 1 Nov 2026 11:35:28 -0600 Subject: [PATCH 3/8] chore(standards): preserve owned-source copyright notices Add accurate repository copyright and license comments to 49 owned source/build/configuration files. Preserve existing holders, upstream wrappers, legal payloads and schema/data exemptions. Exact inverse-byte reconstruction and applicable parser/token/AST checks prove comment-only changes; existing relevant regressions pass. Co-Authored-By: Codex (GPT-6) Signed-off-by: James Maes --- .github/ISSUE_TEMPLATE/bug_report.yml | 3 +++ .github/ISSUE_TEMPLATE/config.yml | 3 +++ .github/ISSUE_TEMPLATE/feature_request.yml | 3 +++ .github/dependabot.yml | 3 +++ .github/release.yml | 3 +++ .github/scripts/check-codeql-sarif.py | 3 +++ .github/scripts/check-dependency-inventory.py | 3 +++ .github/scripts/test-scan-gates.py | 3 +++ .github/workflows/ci.yml | 3 +++ .github/workflows/codeql-analysis.yml | 3 +++ .github/workflows/codeql.yml | 3 +++ .github/workflows/pr-gates.yml | 3 +++ .github/workflows/release.yml | 3 +++ .github/workflows/scorecard.yml | 3 +++ .github/workflows/scripts.yml | 3 +++ .github/workflows/security-analysis.yml | 3 +++ .github/workflows/security.yml | 3 +++ .pre-commit-config.yaml | 3 +++ Directory.Build.props | 5 +++++ Directory.Packages.props | 5 +++++ PSScriptAnalyzerSettings.psd1 | 3 +++ build/Analyze-Scripts.Tests.ps1 | 3 +++ build/Analyze-Scripts.ps1 | 3 +++ build/Assert-Coverage.ps1 | 3 +++ build/Build-Installer.ps1 | 3 +++ build/Generate-Icons.ps1 | 3 +++ build/Install-Branded.Tests.ps1 | 3 +++ build/Install-Branded.ps1 | 3 +++ build/Test-BrandedInstaller.ps1 | 3 +++ build/Test-PackagingInputs.ps1 | 3 +++ build/Test-WindowsSdkInventory.Tests.ps1 | 3 +++ build/Test-WindowsSdkInventory.ps1 | 3 +++ build/Verify.ps1 | 3 +++ installer/Directory.Build.props | 5 +++++ installer/Package.wxs | 5 +++++ installer/Qqq.PrintAgent.Installer.wixproj | 5 +++++ src/Qqq.PrintAgent.Cli/Qqq.PrintAgent.Cli.csproj | 5 +++++ src/Qqq.PrintAgent.Core/Qqq.PrintAgent.Core.csproj | 5 +++++ src/Qqq.PrintAgent.Service/Qqq.PrintAgent.Service.csproj | 5 +++++ src/Qqq.PrintAgent.Windows/Qqq.PrintAgent.Windows.csproj | 5 +++++ src/Qqq.PrintAgent/App.xaml | 5 +++++ src/Qqq.PrintAgent/MainWindow.xaml | 5 +++++ src/Qqq.PrintAgent/Qqq.PrintAgent.csproj | 5 +++++ .../Qqq.PrintAgent.Cli.Tests/Qqq.PrintAgent.Cli.Tests.csproj | 5 +++++ .../Qqq.PrintAgent.Core.Tests.csproj | 5 +++++ .../Qqq.PrintAgent.LayoutTests.csproj | 5 +++++ tests/Qqq.PrintAgent.LayoutTests/Run.ps1 | 3 +++ tests/Qqq.PrintAgent.UiTests/Qqq.PrintAgent.UiTests.csproj | 5 +++++ .../Qqq.PrintAgent.WorkerFixture.csproj | 5 +++++ 49 files changed, 181 insertions(+) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index ba52248..5b6634c 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + name: Bug report description: Something is broken labels: [bug] diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 547d8b9..546a077 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + blank_issues_enabled: false contact_links: - name: Report a security vulnerability diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 213a1e3..fda907b 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + name: Feature request description: Suggest an improvement labels: [enhancement] diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 70ef038..ad55b99 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + # Dependabot for a KofTwentyTwo repository: copy to .github/dependabot.yml and keep # the ecosystems the repository uses. Updates are grouped weekly. A 7-day cooldown # lets the community catch a compromised release before it reaches us; security diff --git a/.github/release.yml b/.github/release.yml index e99370b..31f14f2 100644 --- a/.github/release.yml +++ b/.github/release.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + # Categories for GitHub's auto-generated release notes (uses issue/PR labels). changelog: exclude: diff --git a/.github/scripts/check-codeql-sarif.py b/.github/scripts/check-codeql-sarif.py index cf44763..389be1a 100644 --- a/.github/scripts/check-codeql-sarif.py +++ b/.github/scripts/check-codeql-sarif.py @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + """Reject missing/malformed CodeQL evidence before enforcing the severity gate.""" import json import math diff --git a/.github/scripts/check-dependency-inventory.py b/.github/scripts/check-dependency-inventory.py index a5d3c7e..8bda5c2 100644 --- a/.github/scripts/check-dependency-inventory.py +++ b/.github/scripts/check-dependency-inventory.py @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + """Require scanner evidence for every resolved NuGet lock-file dependency.""" import json from pathlib import Path diff --git a/.github/scripts/test-scan-gates.py b/.github/scripts/test-scan-gates.py index b8c846a..d377840 100644 --- a/.github/scripts/test-scan-gates.py +++ b/.github/scripts/test-scan-gates.py @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + """Exercise the exact CI guards using synthetic evidence only.""" import contextlib import copy diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 64db90c..fd5f434 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + name: ci on: diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index e22af6e..6a59d04 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + # Local copy of KofTwentyTwo/standards at fdf5ed029603c938615a32b1beca3628b8787945 (v0.1.2). # Pins, inputs and analysis checks preserved; report validation now fails closed. # Static analysis (K22-CI-22): CodeQL with the security-extended suite, failing on diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index d20ade5..e1265ed 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + # CodeQL static analysis (K22-CI-22): security-extended queries for C# (a manual x64 # build of the solution) and for the workflows themselves, blocking high severity. name: codeql diff --git a/.github/workflows/pr-gates.yml b/.github/workflows/pr-gates.yml index c118623..d57f92d 100644 --- a/.github/workflows/pr-gates.yml +++ b/.github/workflows/pr-gates.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + # Pull request gates (K22-CI-01): Conventional Commit title, DCO sign-off, and # dependency review, from the shared KofTwentyTwo/standards workflow pinned by SHA # (K22-CI-11). Dependabot's github-actions ecosystem keeps the pin current. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 24df54e..1ccf66a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + name: prerelease on: diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index ed80dc2..030d434 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + # OpenSSF Scorecard (K22-CI-24). Scorecard's publishing API only accepts results # from a workflow shaped exactly like this one: a single job, read-only top-level # permissions, no top-level env or defaults, and only the allowed steps. diff --git a/.github/workflows/scripts.yml b/.github/workflows/scripts.yml index 81a2321..026c23b 100644 --- a/.github/workflows/scripts.yml +++ b/.github/workflows/scripts.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + # K22-CODE-SH: check repository tooling before merges and releases. name: scripts diff --git a/.github/workflows/security-analysis.yml b/.github/workflows/security-analysis.yml index 5993875..a98f8e9 100644 --- a/.github/workflows/security-analysis.yml +++ b/.github/workflows/security-analysis.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + # Local copy of KofTwentyTwo/standards at fdf5ed029603c938615a32b1beca3628b8787945 (v0.1.2). # Scanner pins/checks retained; NuGet inventory and OSV evidence now fail closed. # Security scanning (K22-CI-20, K22-CI-21, K22-CI-23): secrets over full history, diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 7e96a30..2621dcd 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + # Security scans (K22-CI-20, K22-CI-21, K22-CI-23): gitleaks over full history, # Trivy + OSV-Scanner over the lock files, zizmor + actionlint over the workflows. # Runs on every pull request, every push to main, and weekly. diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7de635c..ec62e9b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + # KofTwentyTwo pre-commit configuration. Works with pre-commit and prek. # Copy to the repository root as .pre-commit-config.yaml, then install both hook # types once per clone: diff --git a/Directory.Build.props b/Directory.Build.props index 7063c1a..837d9c1 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,3 +1,8 @@ + + + + diff --git a/installer/Package.wxs b/installer/Package.wxs index 3f839ad..e0d87f5 100644 --- a/installer/Package.wxs +++ b/installer/Package.wxs @@ -1,3 +1,8 @@ + + diff --git a/installer/Qqq.PrintAgent.Installer.wixproj b/installer/Qqq.PrintAgent.Installer.wixproj index 07eabc6..e3ecf6c 100644 --- a/installer/Qqq.PrintAgent.Installer.wixproj +++ b/installer/Qqq.PrintAgent.Installer.wixproj @@ -1,3 +1,8 @@ + + Package diff --git a/src/Qqq.PrintAgent.Cli/Qqq.PrintAgent.Cli.csproj b/src/Qqq.PrintAgent.Cli/Qqq.PrintAgent.Cli.csproj index d0f4d41..e141157 100644 --- a/src/Qqq.PrintAgent.Cli/Qqq.PrintAgent.Cli.csproj +++ b/src/Qqq.PrintAgent.Cli/Qqq.PrintAgent.Cli.csproj @@ -1,3 +1,8 @@ + + + + net10.0-windows10.0.19041.0Exe diff --git a/src/Qqq.PrintAgent.Windows/Qqq.PrintAgent.Windows.csproj b/src/Qqq.PrintAgent.Windows/Qqq.PrintAgent.Windows.csproj index 9b17547..fb1ca62 100644 --- a/src/Qqq.PrintAgent.Windows/Qqq.PrintAgent.Windows.csproj +++ b/src/Qqq.PrintAgent.Windows/Qqq.PrintAgent.Windows.csproj @@ -1,3 +1,8 @@ + + net10.0-windows10.0.19041.0true diff --git a/src/Qqq.PrintAgent/App.xaml b/src/Qqq.PrintAgent/App.xaml index cc4c611..28e9e87 100644 --- a/src/Qqq.PrintAgent/App.xaml +++ b/src/Qqq.PrintAgent/App.xaml @@ -1,4 +1,9 @@ + + + + diff --git a/src/Qqq.PrintAgent/Qqq.PrintAgent.csproj b/src/Qqq.PrintAgent/Qqq.PrintAgent.csproj index 0032b01..e33bb7b 100644 --- a/src/Qqq.PrintAgent/Qqq.PrintAgent.csproj +++ b/src/Qqq.PrintAgent/Qqq.PrintAgent.csproj @@ -1,3 +1,8 @@ + + + diff --git a/tests/Qqq.PrintAgent.Core.Tests/Qqq.PrintAgent.Core.Tests.csproj b/tests/Qqq.PrintAgent.Core.Tests/Qqq.PrintAgent.Core.Tests.csproj index 44bb963..e6e86bf 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/Qqq.PrintAgent.Core.Tests.csproj +++ b/tests/Qqq.PrintAgent.Core.Tests/Qqq.PrintAgent.Core.Tests.csproj @@ -1,3 +1,8 @@ + + diff --git a/tests/Qqq.PrintAgent.LayoutTests/Qqq.PrintAgent.LayoutTests.csproj b/tests/Qqq.PrintAgent.LayoutTests/Qqq.PrintAgent.LayoutTests.csproj index 04849b5..a854ae6 100644 --- a/tests/Qqq.PrintAgent.LayoutTests/Qqq.PrintAgent.LayoutTests.csproj +++ b/tests/Qqq.PrintAgent.LayoutTests/Qqq.PrintAgent.LayoutTests.csproj @@ -1,3 +1,8 @@ + + WinExe diff --git a/tests/Qqq.PrintAgent.LayoutTests/Run.ps1 b/tests/Qqq.PrintAgent.LayoutTests/Run.ps1 index 86fd9de..c016ab8 100644 --- a/tests/Qqq.PrintAgent.LayoutTests/Run.ps1 +++ b/tests/Qqq.PrintAgent.LayoutTests/Run.ps1 @@ -1,3 +1,6 @@ +# Copyright (c) 2026 James Maes +# SPDX-License-Identifier: MIT + <# .SYNOPSIS Builds and runs the isolated native WinUI regression host without printing. diff --git a/tests/Qqq.PrintAgent.UiTests/Qqq.PrintAgent.UiTests.csproj b/tests/Qqq.PrintAgent.UiTests/Qqq.PrintAgent.UiTests.csproj index d828891..b0872b3 100644 --- a/tests/Qqq.PrintAgent.UiTests/Qqq.PrintAgent.UiTests.csproj +++ b/tests/Qqq.PrintAgent.UiTests/Qqq.PrintAgent.UiTests.csproj @@ -1,3 +1,8 @@ + + + Exe -- 2.54.0 From 82b19523ba81114dcb8a518f80a42b68c467ad7a Mon Sep 17 00:00:00 2001 From: James Maes Date: Sun, 1 Nov 2026 13:05:52 -0600 Subject: [PATCH 4/8] feat: enforce discovered printer media through realtime reconnects Report configured machine defaults and bind jobs to exact revisions. Normalize supported driver copies and scale, validate effective PDF device context before spooling, and negotiate media support from fresh standard discovery on each WebSocket connection. Co-Authored-By: Codex GPT-6 Signed-off-by: James Maes --- docs/PRINTER-MEDIA.md | 86 +++++ docs/SESSION-STATE.md | 36 ++ docs/TODO.md | 11 + .../Authentication/QqqApiDiscovery.cs | 10 + .../QqqSessionClient.Realtime.cs | 23 +- .../Printing/PrintOptions.cs | 2 +- .../Printing/PrintWorker.cs | 6 +- .../Printing/PrinterInfo.cs | 3 +- .../Printing/PrinterMediaMismatchException.cs | 9 + .../Printing/PrinterMediaProfile.cs | 40 +++ .../Printing/PrinterMediaSelection.cs | 9 + .../AgentRuntime.Realtime.cs | 16 +- src/Qqq.PrintAgent.Windows/AgentRuntime.cs | 2 +- .../IsolatedPrinterBackend.cs | 15 +- src/Qqq.PrintAgent.Windows/PrinterSnapshot.cs | 3 +- .../PrinterWorkerHost.cs | 2 +- .../WindowsPrinters.Files.cs | 9 +- .../WindowsPrinters.Media.cs | 316 ++++++++++++++++++ .../WindowsPrinters.PdfMedia.cs | 115 +++++++ src/Qqq.PrintAgent.Windows/WindowsPrinters.cs | 28 +- .../AgentRealtimeMediaCapabilitiesTests.cs | 77 +++++ .../PrinterMediaTests.cs | 311 +++++++++++++++++ .../PrinterWorkerIsolationTests.cs | 15 + .../RealtimeRuntimeFixture.cs | 31 +- .../SessionFixture.cs | 2 +- .../PrintWorkerTests.cs | 40 ++- .../PrinterMediaContractTests.cs | 98 ++++++ tests/Qqq.PrintAgent.WorkerFixture/Program.cs | 6 +- 28 files changed, 1275 insertions(+), 46 deletions(-) create mode 100644 docs/PRINTER-MEDIA.md create mode 100644 src/Qqq.PrintAgent.Core/Printing/PrinterMediaMismatchException.cs create mode 100644 src/Qqq.PrintAgent.Core/Printing/PrinterMediaProfile.cs create mode 100644 src/Qqq.PrintAgent.Core/Printing/PrinterMediaSelection.cs create mode 100644 src/Qqq.PrintAgent.Windows/WindowsPrinters.Media.cs create mode 100644 src/Qqq.PrintAgent.Windows/WindowsPrinters.PdfMedia.cs create mode 100644 tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeMediaCapabilitiesTests.cs create mode 100644 tests/Qqq.PrintAgent.Cli.Tests/PrinterMediaTests.cs create mode 100644 tests/Qqq.PrintAgent.Core.Tests/PrinterMediaContractTests.cs diff --git a/docs/PRINTER-MEDIA.md b/docs/PRINTER-MEDIA.md new file mode 100644 index 0000000..c664ae5 --- /dev/null +++ b/docs/PRINTER-MEDIA.md @@ -0,0 +1,86 @@ +# Windows queue-default media profiles + +The candidate client advertises `printer-media-v1` only when standard discovery +reports a stable printing extension version of at least 2.2.0 within major two. +Printing 2.0/2.1 servers retain the original three realtime capabilities and +legacy unselected jobs. Each WebSocket establishment refreshes standard discovery +once under the authenticated session gate, then uses that refreshed snapshot +for HELLO. This handles same-session server upgrades and downgrades without an +HTTP polling schedule. An unverified test or +custom transport does not claim media support. + +The client includes optional `mediaProfiles` in exposed-printer inventory. It reports at most one profile per +queue: the machine-wide Windows driver default. It does not enumerate stock that +an operator might have available, infer dimensions from document pages, or claim +that the configured stock is physically loaded. + +Discovery reads `GetPrinter` level 8, rather than the current user's level 9 +preferences. Custom paper dimensions come from both valid DEVMODE width/length +fields, converted from tenths of a millimeter to integer microns. Otherwise, a +single matching paper ID in the driver's `DeviceCapabilities` paper/size arrays +is required. Landscape defaults swap the effective page axes. Positive explicit +DEVMODE resolutions are retained; symbolic quality values require resolution +from a driver DC created with that exact machine DEVMODE. Unknown, incomplete, +ambiguous or out-of-contract values produce no profile, without guessing. + +Each profile has a stable opaque queue/default ID, a lowercase SHA-256 revision, +a display name, width/height in microns, horizontal/vertical DPI, +`source: WINDOWS_QUEUE_DEFAULT` and `applyMode: DRIVER_DEFAULT`. The revision +includes driver identity, resolved dimensions/resolution, and the complete +returned public/private DEVMODE bytes. This is deliberately conservative: even a +driver-private setting change invalidates an old selection. Drivers returning +volatile private bytes may require reselection; the client does not guess which +vendor fields can be ignored. The fingerprint is not a credential. + +Consumers submit `options.mediaProfile: {id, revision}` exactly as advertised. +It cannot be combined with `paperWidthMm` or `paperHeightMm`. The worker checks +the current selection after download and before its submission state. The +native helper checks again immediately before opening a spool document. A known +media refusal is propagated across the helper boundary and recorded as FAILED +with no document submitted; arbitrary native failures and timeouts retain their +existing uncertain-outcome handling and are not retried automatically. + +For selected PDF jobs, the captured machine DEVMODE remains the selection +fingerprint. A separate job-only copy requests one driver copy and 100% driver +scale, only for fields supported by the captured defaults, through +`DocumentProperties(DM_IN_BUFFER | DM_OUT_BUFFER)`. Unsupported fields remain +absent; drivers without native scale support use the software renderer's scale. +This allows +the driver to reconcile its private settings without prompting or changing +queue defaults. Software remains responsible for requested copies and +ACTUAL_SIZE/FIT rendering. The normalized result must confirm these overrides +and preserve the original support flags and selected geometry/DPI; otherwise +submission is refused. A previously supported override cannot silently disappear. +`CreateDC` receives those normalized bytes, never a null/current-user default. +Before `StartDoc`, the effective DC must also report matching physical page +dimensions and exact horizontal/vertical DPI. Dimension tolerance is one device +pixel plus 50 microns (half the DEVMODE 0.1 mm form unit), including landscape +axes. Unknown or substituted dimensions/DPI are refused before spooling. +RAW ZPL has no DEVMODE application mechanism: the helper rechecks the current +profile immediately before `StartDocPrinter`, but cannot lock loaded stock or +prevent a physical/device-setting change afterward. `DRIVER_DEFAULT` never +changes queue settings, calibrates hardware or loads stock. Such changes require +operator verification and fresh discovery. Legacy jobs without a media selection +retain their existing path. + +The candidate's actual read-only probe reported the configured label default as +101,600 × 152,400 microns at 300 × 300 DPI, with an identical fingerprint across +three separate helper launches. Synthetic tests also cover 101,600 × 25,400 and +101,600 × 50,800 microns; these are not advertised as current configuration. +Physical queue names, driver selectors and inventory evidence remain private. +No print, installation, queue change or service operation was performed for this +feature's discovery qualification. End-to-end server acceptance and physical +printing of a profile-selected job remain separate gates. + +A subsequent read-only probe of the compiled corrected adapter successfully +normalized the configured label driver's supported copy field while retaining +its absent native scale field. The resulting DC reported 1,200 × 1,800 physical +pixels at 300 × 300 DPI. It invoked no StartDoc and changed no queue defaults. +All 24 focused adapter regression cases pass; this does not resolve the separate +Core test-assembly quarantine or qualify a physical profile-selected print. + +Native references: [machine-wide PRINTER_INFO_8 defaults](https://learn.microsoft.com/en-us/windows/win32/printdocs/printer-info-8), +[DEVMODE dimensions and resolution](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-devmodew), +and [driver paper capabilities](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-devicecapabilitiesw). +Job-only driver normalization follows [DocumentProperties](https://learn.microsoft.com/en-us/windows/win32/printdocs/documentproperties); +effective page checks use [GetDeviceCaps](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getdevicecaps). diff --git a/docs/SESSION-STATE.md b/docs/SESSION-STATE.md index 92c0b5c..f24c127 100644 --- a/docs/SESSION-STATE.md +++ b/docs/SESSION-STATE.md @@ -1,5 +1,41 @@ # Session state — 2026-10-31 +## Candidate Echo media discovery — 2026-11-01 + +The isolated candidate implements `printer-media-v1`, machine-wide queue-default +profiles, immutable media selection and pre-spool drift refusal. Selected PDFs +use a driver-normalized job-only copy of the captured DEVMODE; RAW's physical-stock limitation is explicit +in `docs/PRINTER-MEDIA.md`. Read-only native discovery produced a stable configured +4 × 6 inch, 300 × 300 DPI profile across three helper launches. No live component +was changed and no physical output was submitted. + +Core/Windows/CLI and synthetic test projects compile without warnings. Seven +initial adapter cases and one isolated-worker refusal case passed. Review added +driver-normalized copies/scale overrides and effective DC geometry/DPI validation +before StartDoc; all 24 focused Windows adapter cases now pass with zero build +warnings. The original queue fingerprint remains unchanged, and the driver may +update private settings only in the job's in-memory buffer. Unsupported override +fields stay absent. A read-only probe of the corrected production adapter passed +on the configured label driver, including its absent native-scale flag and an +effective 1,200 × 1,800 pixel DC at 300 DPI, without StartDoc or queue changes. +A Core run executed +150 cases, with 147 passing (including the new media/worker cases) and three +failing because the new worktree's linked fixtures were missing. The subsequent +full rerun is blocked by local Defender quarantine of the Core test assembly; +no protection changes, exclusions or quarantine restoration were performed. +This is not a clean full-suite or release qualification. Parent review owns the +security provenance investigation and the remaining server/hardware gates. +The shared selection validator also enforces protocol IDs of at most 128 ASCII +URL-safe characters, profile names of 1–512 characters and at most 32 profiles. +New Core boundary regressions are present for hosted validation and were not +locally compiled or run after the quarantine. +Capability negotiation requires discovered stable printing 2.2+ within major +two; older 2.0/2.1 servers retain the original three-capability HELLO. The real +session/loopback-WebSocket compatibility tests cover same-session upgrade and +downgrade, refreshing discovery once per socket (separate from initial sign-in +discovery), with zero forbidden HTTP polls. The combined focused Windows gate +passed 40 cases with zero build warnings/errors. + ## Installed 0.3.1 and 0.3.2 qualification — 2026-11-01 The published 0.3.1 MSI was installed with exit 0 and no reboot. App, service and diff --git a/docs/TODO.md b/docs/TODO.md index 48f3b14..3142867 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -1,5 +1,16 @@ # TODO +## Candidate Echo printer media + +- [x] Discover truthful machine-default dimensions/DPI and expose an opaque, revision-bound profile. +- [x] Reject stale/unknown selection before spool; pass captured validated defaults to selected PDF DCs. +- [x] Normalize supported job-only driver copies/scale and verify effective DC dimensions/DPI before StartDoc (24 focused Windows tests plus read-only actual driver/DC probe). +- [x] Verify synthetic 4 × 1 / 4 × 2 / 4 × 6 profiles, driver-private drift, unknown DPI and isolated-worker refusal. +- [x] Verify configured 4 × 6 / 300 DPI fingerprint stability across three read-only helper launches. +- [ ] Resolve the local Core test-assembly quarantine through the normal security review; obtain a complete clean gate without disabling protections. +- [ ] Qualify the matching server/consumer catalog, immutable selection and authorized retained-document submission. +- [ ] Perform separately authorized installed/profile-selected physical acceptance; available alternative stock is not current queue configuration. + ## Companion layout, live transport status and startup follow-up - [x] Install the attested published 0.3.1 MSI; verify all three exact component versions, automatic WebSocket restoration and preserved local receipts, pairing and profiles. diff --git a/src/Qqq.PrintAgent.Core/Authentication/QqqApiDiscovery.cs b/src/Qqq.PrintAgent.Core/Authentication/QqqApiDiscovery.cs index 345435d..40391a5 100644 --- a/src/Qqq.PrintAgent.Core/Authentication/QqqApiDiscovery.cs +++ b/src/Qqq.PrintAgent.Core/Authentication/QqqApiDiscovery.cs @@ -15,6 +15,16 @@ public sealed class QqqApiDiscovery public IReadOnlyList ClientChannels { get; init; } = []; public IReadOnlyList Extensions { get; init; } = []; + + + /// Enables additive media negotiation only for one standard-path stable printing 2.2-or-newer extension within major two. + public bool SupportsPrinterMedia() => Extensions is not null + && Extensions.Count(extension => extension is not null && string.Equals(extension.Name, "printing", StringComparison.Ordinal)) == 1 + && Extensions.Any(extension => extension is not null && string.Equals(extension.Name, "printing", StringComparison.Ordinal) + && string.Equals(extension.PathPrefix, "/qbit/printing", StringComparison.Ordinal) && SupportedVersion(extension.Version, 2, "2")); + + + public sealed record Extension(string Name, string Version, string PathPrefix); internal void Validate(bool nativeSession = false) diff --git a/src/Qqq.PrintAgent.Core/Authentication/QqqSessionClient.Realtime.cs b/src/Qqq.PrintAgent.Core/Authentication/QqqSessionClient.Realtime.cs index d8ddf20..d728076 100644 --- a/src/Qqq.PrintAgent.Core/Authentication/QqqSessionClient.Realtime.cs +++ b/src/Qqq.PrintAgent.Core/Authentication/QqqSessionClient.Realtime.cs @@ -9,7 +9,7 @@ namespace Qqq.PrintAgent.Core.Authentication; public sealed partial class QqqSessionClient { - /// Connects only to the discovered origin, using the current native session and approved device proof. + /// Refreshes standard discovery once per socket establishment, then connects only to that origin with the current session and approved device proof. public async Task ConnectPrintingAsync(TimeSpan heartbeatInterval, TimeSpan heartbeatTimeout, CancellationToken cancellationToken = default) { var invoker = new HttpMessageInvoker(new SocketsHttpHandler { AllowAutoRedirect = false, UseCookies = false }); @@ -21,12 +21,7 @@ public sealed partial class QqqSessionClient try { RequireAuthenticated(); - QqqApiDiscovery discovery = _discovery ?? throw QqqApiDiscovery.Configuration(); - QqqApiDiscovery.Extension extension = discovery.Extensions.Single(item => string.Equals(item.Name, "printing", StringComparison.Ordinal)); - if(!Version.TryParse(extension.Version, out Version? version) || version.Major != 2) - { - throw new QqqSessionException(QqqSessionException.FailureKind.ConfigurationRequired, "Upgrade the server to printing extension 2.x for realtime printing."); - } + await RefreshPrintingDiscoveryAsync(cancellationToken).ConfigureAwait(false); if(_device is null || _binding?.HasApprovedDevice != true) { throw new QqqSessionException(QqqSessionException.FailureKind.PermissionDenied, "An approved device binding is required."); @@ -71,4 +66,18 @@ public sealed partial class QqqSessionClient throw; } } + + + + /// Refreshes discovery under the caller-held session gate and rejects incompatible printing majors before sending any WebSocket credentials. + private async Task RefreshPrintingDiscoveryAsync(CancellationToken token) + { + _discovery = null; + QqqApiDiscovery discovery = await DiscoverCoreAsync(token).ConfigureAwait(false); + QqqApiDiscovery.Extension extension = discovery.Extensions.Single(item => string.Equals(item.Name, "printing", StringComparison.Ordinal)); + if(!Version.TryParse(extension.Version, out Version? version) || version.Major != 2) + { + throw new QqqSessionException(QqqSessionException.FailureKind.ConfigurationRequired, "Upgrade the server to printing extension 2.x for realtime printing."); + } + } } diff --git a/src/Qqq.PrintAgent.Core/Printing/PrintOptions.cs b/src/Qqq.PrintAgent.Core/Printing/PrintOptions.cs index ffd57ff..25e8a05 100644 --- a/src/Qqq.PrintAgent.Core/Printing/PrintOptions.cs +++ b/src/Qqq.PrintAgent.Core/Printing/PrintOptions.cs @@ -5,6 +5,6 @@ namespace Qqq.PrintAgent.Core.Printing; -public sealed record PrintOptions(int Copies = 1, string Scale = "ACTUAL_SIZE", double? PaperWidthMm = null, double? PaperHeightMm = null); +public sealed record PrintOptions(int Copies = 1, string Scale = "ACTUAL_SIZE", double? PaperWidthMm = null, double? PaperHeightMm = null, PrinterMediaSelection? MediaProfile = null); diff --git a/src/Qqq.PrintAgent.Core/Printing/PrintWorker.cs b/src/Qqq.PrintAgent.Core/Printing/PrintWorker.cs index df08958..c381d5f 100644 --- a/src/Qqq.PrintAgent.Core/Printing/PrintWorker.cs +++ b/src/Qqq.PrintAgent.Core/Printing/PrintWorker.cs @@ -106,10 +106,12 @@ public sealed class PrintWorker(PrintApiClient api, IPrinterBackend printers, IJ await using IAsyncDisposable? reservation = options?.ReserveDocumentAsync is null ? null : await options.ReserveDocumentAsync(job, token).ConfigureAwait(false); using DownloadedDocument? file = options?.StagingDirectory is null ? null : await api.DownloadFileAsync(job, options.StagingDirectory, options.Settings, token, options.ThrottleDownloadAsync).ConfigureAwait(false); byte[]? content = file is null ? await api.DownloadAsync(job, token).ConfigureAwait(false) : null; - if(!printers.Discover().Any(p => string.Equals(p.PrinterId, job.PrinterId, StringComparison.Ordinal) && p.Formats.Contains(job.Format, StringComparer.Ordinal))) + PrinterInfo? currentPrinter = printers.Discover().SingleOrDefault(p => string.Equals(p.PrinterId, job.PrinterId, StringComparison.Ordinal) && p.Formats.Contains(job.Format, StringComparer.Ordinal)); + if(currentPrinter is null) { throw new InvalidOperationException("Assigned printer or document format is unavailable."); } + PrinterMediaProfile.RequireMatch(job.Options, currentPrinter.MediaProfiles); await using IAsyncDisposable? submission = options?.AcquireSubmissionAsync is null ? null : await options.AcquireSubmissionAsync(job, token).ConfigureAwait(false); if((options?.CanSubmit ?? canDispatch)?.Invoke() == false) @@ -131,7 +133,7 @@ public sealed class PrintWorker(PrintApiClient api, IPrinterBackend printers, IJ } catch(Exception exception) { - Record(job, submitting ? "OUTCOME_UNKNOWN" : "FAILED", exception.Message); + Record(job, submitting && exception is not PrinterMediaMismatchException ? "OUTCOME_UNKNOWN" : "FAILED", exception.Message); } if(!token.IsCancellationRequested) { await FlushAsync(token).ConfigureAwait(false); } diff --git a/src/Qqq.PrintAgent.Core/Printing/PrinterInfo.cs b/src/Qqq.PrintAgent.Core/Printing/PrinterInfo.cs index f240216..89fe0d9 100644 --- a/src/Qqq.PrintAgent.Core/Printing/PrinterInfo.cs +++ b/src/Qqq.PrintAgent.Core/Printing/PrinterInfo.cs @@ -5,6 +5,7 @@ namespace Qqq.PrintAgent.Core.Printing; -public sealed record PrinterInfo(string PrinterId, string Name, string DriverName, string PortName, string Status, string[] Formats, string? DisplayName = null, string? Description = null, string? Location = null); +public sealed record PrinterInfo(string PrinterId, string Name, string DriverName, string PortName, string Status, string[] Formats, string? DisplayName = null, string? Description = null, string? Location = null, + IReadOnlyList? MediaProfiles = null); diff --git a/src/Qqq.PrintAgent.Core/Printing/PrinterMediaMismatchException.cs b/src/Qqq.PrintAgent.Core/Printing/PrinterMediaMismatchException.cs new file mode 100644 index 0000000..f9a118b --- /dev/null +++ b/src/Qqq.PrintAgent.Core/Printing/PrinterMediaMismatchException.cs @@ -0,0 +1,9 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Core.Printing; + +/// A media validation refusal made before StartDoc/StartDocPrinter; no document bytes were submitted. +public sealed class PrinterMediaMismatchException(string message) : InvalidOperationException(message); diff --git a/src/Qqq.PrintAgent.Core/Printing/PrinterMediaProfile.cs b/src/Qqq.PrintAgent.Core/Printing/PrinterMediaProfile.cs new file mode 100644 index 0000000..14cdb38 --- /dev/null +++ b/src/Qqq.PrintAgent.Core/Printing/PrinterMediaProfile.cs @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Core.Printing; + +/// A measured Windows machine queue default, not a claim about physically loaded stock. +public sealed record PrinterMediaProfile(string Id, string Revision, string Name, int WidthMicrons, int HeightMicrons, + int DpiX, int DpiY, string Source = "WINDOWS_QUEUE_DEFAULT", string ApplyMode = "DRIVER_DEFAULT") +{ + /// Refuse stale, ambiguous or unavailable selected defaults before any native submission. + public static void RequireMatch(PrintOptions options, IReadOnlyList? profiles) + { + PrinterMediaSelection? selection = options.MediaProfile; + if(selection is null) + { return; } + if(options.PaperWidthMm is not null || options.PaperHeightMm is not null || !ValidId(selection.Id) + || profiles is { Count: > 32 } + || selection.Revision is not { Length: 64 } || selection.Revision.Any(character => character is not (>= '0' and <= '9' or >= 'a' and <= 'f'))) + { throw new PrinterMediaMismatchException("The selected printer media profile is invalid or conflicts with explicit paper dimensions."); } + PrinterMediaProfile[] matches = profiles?.Where(profile => string.Equals(profile.Id, selection.Id, StringComparison.Ordinal)).ToArray() ?? []; + if(matches.Length != 1 || !string.Equals(matches[0].Revision, selection.Revision, StringComparison.Ordinal) + || matches[0].Name is not { Length: >= 1 and <= 512 } + || matches[0].WidthMicrons is < 1 or > 2_000_000 || matches[0].HeightMicrons is < 1 or > 2_000_000 + || matches[0].DpiX is < 1 or > 9600 || matches[0].DpiY is < 1 or > 9600 + || !string.Equals(matches[0].Source, "WINDOWS_QUEUE_DEFAULT", StringComparison.Ordinal) + || !string.Equals(matches[0].ApplyMode, "DRIVER_DEFAULT", StringComparison.Ordinal)) + { throw new PrinterMediaMismatchException("The selected printer media profile changed or is unavailable. Refresh the printer and select its current default."); } + } + + + + /// + /// Matches the shared opaque-ID alphabet and length before profile lookup, preventing malformed selectors from reaching native submission. + /// + private static bool ValidId(string? id) + => id is { Length: >= 1 and <= 128 } + && id.All(character => character is >= 'A' and <= 'Z' or >= 'a' and <= 'z' or >= '0' and <= '9' or '.' or '_' or '-'); +} diff --git a/src/Qqq.PrintAgent.Core/Printing/PrinterMediaSelection.cs b/src/Qqq.PrintAgent.Core/Printing/PrinterMediaSelection.cs new file mode 100644 index 0000000..b9a9035 --- /dev/null +++ b/src/Qqq.PrintAgent.Core/Printing/PrinterMediaSelection.cs @@ -0,0 +1,9 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Core.Printing; + +/// An immutable reference to the exact queue default selected when the server created the job. +public sealed record PrinterMediaSelection(string Id, string Revision); diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.Realtime.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.Realtime.cs index ab7c3b1..deba1e5 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.Realtime.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.Realtime.cs @@ -119,7 +119,7 @@ public sealed partial class AgentRuntime RealtimeSettings settings = _realtimeSettings; using var handshake = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); handshake.CancelAfter(settings.WebSocketHandshakeTimeoutMillis); - WebSocket socket = await ConnectRealtimeSocketAsync(settings, lifetime, handshake.Token).ConfigureAwait(false); + (WebSocket socket, bool supportsMedia) = await ConnectRealtimeSocketAsync(settings, lifetime, handshake.Token).ConfigureAwait(false); using var channel = new PrintingRealtimeChannel(socket, settings, _traffic); var updates = Channel.CreateBounded(4096); var commands = Channel.CreateBounded(4096); @@ -147,7 +147,7 @@ public sealed partial class AgentRuntime await channel.SendAsync("HELLO", new { agentVersion = PrintApiClient.AgentVersion, - capabilities = RealtimeCapabilities, + capabilities = supportsMedia ? [.. RealtimeCapabilities, "printer-media-v1"] : RealtimeCapabilities, lastAppliedRevision = _controlState.DesiredState.Revision, lastSettingsRevision = settings.Revision, limits = RealtimeSettings.ClientLimits, @@ -168,12 +168,20 @@ public sealed partial class AgentRuntime } } - private async Task ConnectRealtimeSocketAsync(RealtimeSettings settings, CancellationTokenSource lifetime, CancellationToken token) + /// Reads the discovery refreshed by this socket establishment, so server upgrades and downgrades change capabilities on reconnect without polling. + private async Task<(WebSocket Socket, bool SupportsMedia)> ConnectRealtimeSocketAsync(RealtimeSettings settings, CancellationTokenSource lifetime, CancellationToken token) { try { - return await (_sessionClient ?? throw new InvalidOperationException("Sign in is required.")).ConnectPrintingAsync( + IQqqSessionClient session = _sessionClient ?? throw new InvalidOperationException("Sign in is required."); + WebSocket socket = await session.ConnectPrintingAsync( TimeSpan.FromSeconds(settings.HeartbeatIntervalSeconds), TimeSpan.FromSeconds(settings.HeartbeatTimeoutSeconds), token).ConfigureAwait(false); + try + { + QqqApiDiscovery discovery = await session.DiscoverAsync(token).ConfigureAwait(false); + return (socket, discovery.SupportsPrinterMedia()); + } + catch { socket.Dispose(); throw; } } catch { diff --git a/src/Qqq.PrintAgent.Windows/AgentRuntime.cs b/src/Qqq.PrintAgent.Windows/AgentRuntime.cs index cacacaf..d3f9e94 100644 --- a/src/Qqq.PrintAgent.Windows/AgentRuntime.cs +++ b/src/Qqq.PrintAgent.Windows/AgentRuntime.cs @@ -202,7 +202,7 @@ public sealed partial class AgentRuntime(string directory, Action log, I using AgentStore store = new(directory, recoverUnreadableConfiguration: true); AgentConfiguration? configuration = store.LoadConfiguration(); IReadOnlySet exposed = store.GetExposedPrinterIds(); - var printers = new ProfiledPrinterBackend(_printers, store).Discover().Select(printer => new PrinterSnapshot(printer.PrinterId, printer.Name, printer.DriverName, printer.PortName, printer.Status, printer.Formats, exposed.Contains(printer.PrinterId), printer.DisplayName, printer.Description, printer.Location)).ToList(); + var printers = new ProfiledPrinterBackend(_printers, store).Discover().Select(printer => new PrinterSnapshot(printer.PrinterId, printer.Name, printer.DriverName, printer.PortName, printer.Status, printer.Formats, exposed.Contains(printer.PrinterId), printer.DisplayName, printer.Description, printer.Location, printer.MediaProfiles)).ToList(); foreach(string missing in exposed.Where(id => !printers.Any(printer => string.Equals(printer.PrinterId, id, StringComparison.Ordinal)))) { PrinterProfile profile = store.GetPrinterProfile(missing); diff --git a/src/Qqq.PrintAgent.Windows/IsolatedPrinterBackend.cs b/src/Qqq.PrintAgent.Windows/IsolatedPrinterBackend.cs index 7cb264c..3f46697 100644 --- a/src/Qqq.PrintAgent.Windows/IsolatedPrinterBackend.cs +++ b/src/Qqq.PrintAgent.Windows/IsolatedPrinterBackend.cs @@ -76,11 +76,7 @@ public sealed class IsolatedPrinterBackend(string helperExecutable) : IFilePrint PrinterWorkerHost.Response response = JsonSerializer.Deserialize(text, PrintApiClient.JsonOptions) ?? throw new InvalidDataException("Printer worker returned no response."); if(child.ExitCode != 0 || !response.Success) { - if(response.ErrorCode is "ALREADY_ABSENT" or "OWNERSHIP_MISMATCH") - { - throw new SpoolCancellationException(response.ErrorCode, response.Error ?? "Verified spool cancellation was refused."); - } - throw new IOException(response.Error ?? "The printer worker stopped unexpectedly. Inspect the printer before retrying."); + ThrowWorkerFailure(response); } return response; } @@ -105,4 +101,13 @@ public sealed class IsolatedPrinterBackend(string helperExecutable) : IFilePrint } } } + + private static void ThrowWorkerFailure(PrinterWorkerHost.Response response) + { + if(string.Equals(response.ErrorCode, "MEDIA_PROFILE_MISMATCH", StringComparison.Ordinal)) + { throw new PrinterMediaMismatchException(response.Error ?? "The selected printer default changed before submission."); } + if(response.ErrorCode is "ALREADY_ABSENT" or "OWNERSHIP_MISMATCH") + { throw new SpoolCancellationException(response.ErrorCode, response.Error ?? "Verified spool cancellation was refused."); } + throw new IOException(response.Error ?? "The printer worker stopped unexpectedly. Inspect the printer before retrying."); + } } diff --git a/src/Qqq.PrintAgent.Windows/PrinterSnapshot.cs b/src/Qqq.PrintAgent.Windows/PrinterSnapshot.cs index c033436..276c1c3 100644 --- a/src/Qqq.PrintAgent.Windows/PrinterSnapshot.cs +++ b/src/Qqq.PrintAgent.Windows/PrinterSnapshot.cs @@ -7,5 +7,6 @@ namespace Qqq.PrintAgent.Windows; /// A locally discovered queue and whether its owner has exposed it to QQQ. public sealed record PrinterSnapshot(string PrinterId, string Name, string DriverName, string PortName, string Status, string[] Formats, bool Exposed, - string? DisplayName = null, string? Description = null, string? Location = null); + string? DisplayName = null, string? Description = null, string? Location = null, + IReadOnlyList? MediaProfiles = null); diff --git a/src/Qqq.PrintAgent.Windows/PrinterWorkerHost.cs b/src/Qqq.PrintAgent.Windows/PrinterWorkerHost.cs index 1e4f3c8..8a58d00 100644 --- a/src/Qqq.PrintAgent.Windows/PrinterWorkerHost.cs +++ b/src/Qqq.PrintAgent.Windows/PrinterWorkerHost.cs @@ -70,7 +70,7 @@ public static class PrinterWorkerHost } catch(Exception exception) { - await Console.Out.WriteLineAsync(JsonSerializer.Serialize(new Response(false, Error: AgentActivityLog.Redact(exception.Message), ErrorCode: (exception as SpoolCancellationException)?.Outcome), PrintApiClient.JsonOptions)).ConfigureAwait(false); + await Console.Out.WriteLineAsync(JsonSerializer.Serialize(new Response(false, Error: AgentActivityLog.Redact(exception.Message), ErrorCode: exception is PrinterMediaMismatchException ? "MEDIA_PROFILE_MISMATCH" : (exception as SpoolCancellationException)?.Outcome), PrintApiClient.JsonOptions)).ConfigureAwait(false); return 1; } finally diff --git a/src/Qqq.PrintAgent.Windows/WindowsPrinters.Files.cs b/src/Qqq.PrintAgent.Windows/WindowsPrinters.Files.cs index b6b496a..1c28f2a 100644 --- a/src/Qqq.PrintAgent.Windows/WindowsPrinters.Files.cs +++ b/src/Qqq.PrintAgent.Windows/WindowsPrinters.Files.cs @@ -33,18 +33,19 @@ public sealed partial class WindowsPrinters } if(string.Equals(job.Format, "ZPL", StringComparison.Ordinal)) { - return PrintRawStream(printer.Name, job, input, cancellationToken); + return PrintRawStream(printer, job, input, cancellationToken); } using global::Windows.Storage.Streams.IRandomAccessStream random = input.AsRandomAccessStream(); PdfDocument document = await PdfDocument.LoadFromStreamAsync(random).AsTask(cancellationToken).ConfigureAwait(false); - return await PrintPdfDocumentAsync(printer.Name, job, document, cancellationToken).ConfigureAwait(false); + return await PrintPdfDocumentAsync(printer, job, document, cancellationToken).ConfigureAwait(false); } - private static string PrintRawStream(string printerName, PrintJob job, Stream input, CancellationToken token) + private static string PrintRawStream(PrinterInfo selectedPrinter, PrintJob job, Stream input, CancellationToken token) { - Check(Native.OpenPrinter(printerName, out IntPtr printer, IntPtr.Zero)); + Check(Native.OpenPrinter(selectedPrinter.Name, out IntPtr printer, IntPtr.Zero)); try { + _ = RequireCurrentMedia(selectedPrinter, job); Native.DocInfo1 info = new() { DocumentName = $"QQQ {job.JobId}", DataType = "RAW" }; uint id = Native.StartDocPrinter(printer, 1, ref info); if(id == 0) diff --git a/src/Qqq.PrintAgent.Windows/WindowsPrinters.Media.cs b/src/Qqq.PrintAgent.Windows/WindowsPrinters.Media.cs new file mode 100644 index 0000000..8e7f176 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/WindowsPrinters.Media.cs @@ -0,0 +1,316 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Buffers.Binary; +using System.ComponentModel; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using Qqq.PrintAgent.Core.Printing; + +namespace Qqq.PrintAgent.Windows; + +/// +/// Reads machine queue defaults and verifies selected media before native submission, without inferring loaded stock. +/// +public sealed partial class WindowsPrinters +{ + /// + /// Keeps the complete driver bytes beside their resolved profile so validation and submission use the same captured defaults. + /// + private sealed record QueueDefaultMedia(byte[] DevMode, PrinterMediaProfile? Profile); + + + + /// + /// Resolves bounded machine defaults into a selectable profile; unreadable queues remain discoverable without a media claim. + /// + private static QueueDefaultMedia? ReadQueueMedia(string id, string name, string driver, string port) + { + try + { + byte[]? mode = ReadMachineDevMode(name); + if(mode is null) + { return null; } + var pinned = GCHandle.Alloc(mode, GCHandleType.Pinned); + try + { + IntPtr pointer = pinned.AddrOfPinnedObject(); + (int width, int height) = ResolvePaperDimensions(name, port, mode, pointer); + (int dpiX, int dpiY) = ResolveResolution(name, mode, pointer); + return new QueueDefaultMedia(mode, BuildMediaProfile(id, driver, mode, width, height, dpiX, dpiY)); + } + finally { pinned.Free(); } + } + catch(Win32Exception) + { + // A queue without readable machine defaults has no selectable media profile. + return null; + } + } + + + + /// + /// Copies level-eight machine defaults only after checking native pointer and length bounds, avoiding per-user preferences. + /// + private static byte[]? ReadMachineDevMode(string name) + { + Check(Native.OpenPrinter(name, out IntPtr printer, IntPtr.Zero)); + try + { + _ = Native.GetPrinter(printer, 8, IntPtr.Zero, 0, out uint needed); + if(needed < IntPtr.Size + 102 || needed > 1_048_576) + { return null; } + IntPtr buffer = Marshal.AllocHGlobal(checked((int)needed)); + try + { + Check(Native.GetPrinter(printer, 8, buffer, needed, out _)); + IntPtr mode = Marshal.ReadIntPtr(buffer); + long offset = mode.ToInt64() - buffer.ToInt64(); + if(mode == IntPtr.Zero || offset < IntPtr.Size || offset > needed - 102) + { return null; } + int size = (ushort)Marshal.ReadInt16(mode, 68); + int extra = (ushort)Marshal.ReadInt16(mode, 70); + if(size < 102 || size + extra > needed - offset) + { return null; } + byte[] bytes = new byte[size + extra]; + Marshal.Copy(mode, bytes, 0, bytes.Length); + return bytes; + } + finally { Marshal.FreeHGlobal(buffer); } + } + finally { _ = Native.ClosePrinter(printer); } + } + + + + /// + /// Uses both explicit form dimensions or an unambiguous driver paper-ID mapping, because partial dimensions are not reliable stock data. + /// + private static (int Width, int Height) ResolvePaperDimensions(string name, string port, byte[] mode, IntPtr pointer) + { + uint fields = BinaryPrimitives.ReadUInt32LittleEndian(mode.AsSpan(72)); + if((fields & 12) != 0) + { + // Both explicit fields are required; a half-specified custom form is ambiguous. + return ReadExplicitDimensions(mode); + } + if((fields & 2) == 0) + { return (0, 0); } + return ReadDriverPaperSize(name, port, pointer, ReadModeShort(mode, 78)); + } + + + + /// + /// Pairs the driver's paper identifiers and size arrays and accepts exactly one bounded match, rather than guessing a standard form. + /// + private static (int Width, int Height) ReadDriverPaperSize(string name, string port, IntPtr mode, short paperId) + { + int count = Native.DeviceCapabilities(name, port, 2, IntPtr.Zero, mode); + if(count is < 1 or > ushort.MaxValue || Native.DeviceCapabilities(name, port, 3, IntPtr.Zero, mode) != count) + { return (0, 0); } + IntPtr identifiers = Marshal.AllocHGlobal(count * sizeof(short)); + IntPtr dimensions = Marshal.AllocHGlobal(count * 2 * sizeof(int)); + try + { + if(Native.DeviceCapabilities(name, port, 2, identifiers, mode) != count || Native.DeviceCapabilities(name, port, 3, dimensions, mode) != count) + { return (0, 0); } + List<(int Width, int Height)> matches = []; + for(int index = 0; index < count; index++) + { + if(Marshal.ReadInt16(identifiers, index * 2) == paperId) + { + int width = Marshal.ReadInt32(dimensions, index * 8); + int height = Marshal.ReadInt32(dimensions, index * 8 + 4); + if(width is < 1 or > 20_000 || height is < 1 or > 20_000) + { return (0, 0); } + matches.Add((width * 100, height * 100)); + } + } + return matches.Count == 1 ? matches[0] : (0, 0); + } + finally { Marshal.FreeHGlobal(identifiers); Marshal.FreeHGlobal(dimensions); } + } + + + + /// + /// Uses positive explicit DPI or a DC built from the captured defaults; symbolic quality values are not treated as resolution. + /// + private static (int X, int Y) ResolveResolution(string name, byte[] mode, IntPtr pointer) + { + uint fields = BinaryPrimitives.ReadUInt32LittleEndian(mode.AsSpan(72)); + if((fields & 0x2400) == 0x2400 && ReadModeShort(mode, 90) > 0 && ReadModeShort(mode, 96) > 0) + { return (ReadModeShort(mode, 90), ReadModeShort(mode, 96)); } + // Symbolic quality values are not DPI. Ask this driver with this exact machine DEVMODE. + IntPtr dc = Native.CreateDC("WINSPOOL", name, null, pointer); + if(dc == IntPtr.Zero) + { return (0, 0); } + try + { return (Native.GetDeviceCaps(dc, 88), Native.GetDeviceCaps(dc, 90)); } + finally { _ = Native.DeleteDC(dc); } + } + + + + /// + /// Validates dimensions, orientation and resolution, then fingerprints all public/private defaults so driver changes invalidate stale selections. + /// + internal static PrinterMediaProfile? BuildMediaProfile(string printerId, string driver, byte[] mode, int width, int height, int dpiX, int dpiY) + { + if(mode.Length < 102 || BinaryPrimitives.ReadUInt16LittleEndian(mode.AsSpan(68)) < 102 + || BinaryPrimitives.ReadUInt16LittleEndian(mode.AsSpan(68)) + BinaryPrimitives.ReadUInt16LittleEndian(mode.AsSpan(70)) != mode.Length + || width is < 1 or > 2_000_000 || height is < 1 or > 2_000_000 || dpiX is < 1 or > 9600 || dpiY is < 1 or > 9600) + { return null; } + uint fields = BinaryPrimitives.ReadUInt32LittleEndian(mode.AsSpan(72)); + if((fields & 1) == 0 || ReadModeShort(mode, 76) is not (1 or 2)) + { return null; } + if(ReadModeShort(mode, 76) == 2) + { (width, height) = (height, width); } + string id = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(printerId + ":machine-default"))).ToLowerInvariant()[..24]; + string canonical = string.Create(CultureInfo.InvariantCulture, $"{printerId}\n{driver}\n{width}\n{height}\n{dpiX}\n{dpiY}\n"); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + hash.AppendData(Encoding.UTF8.GetBytes(canonical)); + hash.AppendData(mode); + string revision = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant(); + string label = string.Create(CultureInfo.InvariantCulture, $"Windows queue default ({width / 1000m} × {height / 1000m} mm, {dpiX} × {dpiY} DPI)"); + return new PrinterMediaProfile(id, revision, label, width, height, dpiX, dpiY); + } + + + + /// + /// Reads a validated DEVMODE short at its native little-endian offset without interpreting driver-private bytes. + /// + private static short ReadModeShort(byte[] mode, int offset) => BinaryPrimitives.ReadInt16LittleEndian(mode.AsSpan(offset)); + + + + /// + /// Converts complete DEVMODE form dimensions from tenths of a millimeter to microns; missing fields return unknown geometry. + /// + internal static (int Width, int Height) ReadExplicitDimensions(byte[] mode) + => mode.Length >= 84 && (BinaryPrimitives.ReadUInt32LittleEndian(mode.AsSpan(72)) & 12) == 12 + ? (ReadModeShort(mode, 82) * 100, ReadModeShort(mode, 80) * 100) : (0, 0); + + + + /// + /// Re-reads and matches selected defaults at the native submission boundary, while leaving legacy unselected jobs on their existing path. + /// + private static QueueDefaultMedia? RequireCurrentMedia(PrinterInfo printer, PrintJob job) + { + if(job.Options.MediaProfile is null) + { return null; } + QueueDefaultMedia? media = ReadQueueMedia(printer.PrinterId, printer.Name, printer.DriverName, printer.PortName); + PrinterMediaProfile.RequireMatch(job.Options, media?.Profile is null ? [] : [media.Profile]); + return media; + } + + + + /// + /// Passes the pinned captured or normalized job settings to GDI so selected jobs do not silently request current-user defaults. + /// + private static IntPtr CreateDocumentContext(string printerName, byte[]? mode) + => WithPinnedMode(mode, pointer => Native.CreateDC("WINSPOOL", printerName, null, pointer)); + + + + /// + /// Checks active overrides and the effective DC's physical dimensions/DPI before invoking StartDoc, so substituted defaults cannot open a spool document. + /// + internal static int StartValidatedPdfDocument(byte[]? mode, PrinterMediaProfile? profile, Func deviceCaps, Func startDocument) + { + if(profile is not null) + { + RequirePdfDefaults(mode); + int dpiX = deviceCaps(88); + int dpiY = deviceCaps(90); + if(dpiX != profile.DpiX || dpiY != profile.DpiY + || !MatchesPhysicalDimension(deviceCaps(110), dpiX, profile.WidthMicrons) + || !MatchesPhysicalDimension(deviceCaps(111), dpiY, profile.HeightMicrons)) + { + throw new PrinterMediaMismatchException("The printer device context does not match the selected media dimensions and resolution."); + } + } + return startDocument(); + } + + + + /// + /// Rejects active driver copy or scale settings that would multiply or resize the renderer's output; unsupported fields remain ignored. + /// + private static void RequirePdfDefaults(byte[]? mode) + { + if(mode is null || mode.Length < 102) + { + throw new PrinterMediaMismatchException("The selected PDF media has no complete machine defaults."); + } + uint fields = BinaryPrimitives.ReadUInt32LittleEndian(mode.AsSpan(72)); + // The renderer owns copies and scaling. Do not patch vendor-private DEVMODE data. + if(((fields & 0x100) != 0 && ReadModeShort(mode, 86) != 1) + || ((fields & 0x10) != 0 && ReadModeShort(mode, 84) != 100)) + { + throw new PrinterMediaMismatchException("Selected PDF media requires Windows queue defaults of one copy and 100 percent scale."); + } + } + + + + /// + /// Compares physical pixels with selected microns using only device-pixel and form-unit rounding tolerance, never printable-area dimensions. + /// + private static bool MatchesPhysicalDimension(int pixels, int dpi, int microns) + { + if(pixels <= 0 || dpi <= 0) + { return false; } + // Allow one device pixel plus half the DEVMODE form unit (0.1 mm). + double pixelMicrons = 25_400d / dpi; + return Math.Abs(pixels * pixelMicrons - microns) <= pixelMicrons + 50; + } + + + + /// + /// Pins the complete settings buffer for the synchronous native call and always releases it; null is reserved for the legacy path. + /// + internal static IntPtr WithPinnedMode(byte[]? mode, Func create) + { + if(mode is null) + { return create(IntPtr.Zero); } + var pinned = GCHandle.Alloc(mode, GCHandleType.Pinned); + try + { return create(pinned.AddrOfPinnedObject()); } + finally { pinned.Free(); } + } + + + + /// + /// Contains read-only Winspool entry points used to obtain machine defaults and driver form capabilities. + /// + private static partial class Native + { + /// + /// Reads printer information into a caller-sized buffer; level eight supplies machine-wide DEVMODE defaults. + /// + [DllImport("winspool.drv", EntryPoint = "GetPrinterW", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool GetPrinter(IntPtr printer, uint level, IntPtr buffer, uint size, out uint needed); + + + + /// + /// Queries driver capabilities against the supplied DEVMODE so paper IDs and sizes refer to the same captured configuration. + /// + [DllImport("winspool.drv", EntryPoint = "DeviceCapabilitiesW", CharSet = CharSet.Unicode)] + internal static extern int DeviceCapabilities(string device, string port, ushort capability, IntPtr output, IntPtr devMode); + } +} diff --git a/src/Qqq.PrintAgent.Windows/WindowsPrinters.PdfMedia.cs b/src/Qqq.PrintAgent.Windows/WindowsPrinters.PdfMedia.cs new file mode 100644 index 0000000..504a8db --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/WindowsPrinters.PdfMedia.cs @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using Qqq.PrintAgent.Core.Printing; + +namespace Qqq.PrintAgent.Windows; + +/// +/// Prepares job-local PDF settings through the driver while preserving the queue-default fingerprint and leaving persistent settings untouched. +/// +public sealed partial class WindowsPrinters +{ + /// + /// Normalizes a selected PDF job and resolves the returned driver settings again, refusing any geometry or DPI change. + /// + private static byte[] PreparePdfMode(PrinterInfo printer, QueueDefaultMedia media) + => NormalizePdfMode(media.DevMode, media.Profile!, mode => MergeDriverMode(printer.Name, mode), mode => + { + var pinned = GCHandle.Alloc(mode, GCHandleType.Pinned); + try + { + IntPtr pointer = pinned.AddrOfPinnedObject(); + (int width, int height) = ResolvePaperDimensions(printer.Name, printer.PortName, mode, pointer); + (int dpiX, int dpiY) = ResolveResolution(printer.Name, mode, pointer); + return BuildMediaProfile(printer.PrinterId, printer.DriverName, mode, width, height, dpiX, dpiY); + } + finally { pinned.Free(); } + }); + + + + /// + /// Clones captured defaults, overrides only supported copy/scale fields, and verifies driver output without altering the selection fingerprint. + /// + internal static byte[] NormalizePdfMode(byte[] captured, PrinterMediaProfile selected, + Func normalize, Func resolve) + { + byte[] input = captured.ToArray(); + uint fields = BinaryPrimitives.ReadUInt32LittleEndian(input.AsSpan(72)); + uint overrides = fields & 0x110; + if((overrides & 0x10) != 0) + { BinaryPrimitives.WriteInt16LittleEndian(input.AsSpan(84), 100); } + if((overrides & 0x100) != 0) + { BinaryPrimitives.WriteInt16LittleEndian(input.AsSpan(86), 1); } + byte[] output = normalize(input); + RequirePdfDefaults(output); + if((BinaryPrimitives.ReadUInt32LittleEndian(output.AsSpan(72)) & 0x110) != overrides) + { + throw new PrinterMediaMismatchException("The driver changed support for job-level copies or scale."); + } + PrinterMediaProfile? effective = resolve(output); + if(effective is null || effective.WidthMicrons != selected.WidthMicrons || effective.HeightMicrons != selected.HeightMicrons + || effective.DpiX != selected.DpiX || effective.DpiY != selected.DpiY) + { + throw new PrinterMediaMismatchException("The driver changed selected media while applying job-level copies and scale."); + } + return output; + } + + + + /// + /// Lets DocumentProperties reconcile private settings in bounded buffers using input/output flags only, with no prompt or queue update. + /// + private static byte[] MergeDriverMode(string printerName, byte[] input) + { + Check(Native.OpenPrinter(printerName, out IntPtr printer, IntPtr.Zero)); + try + { + int required = Native.DocumentProperties(IntPtr.Zero, printer, printerName, IntPtr.Zero, IntPtr.Zero, 0); + if(required is < 102 or > 1_048_576) + { + throw new PrinterMediaMismatchException("The driver did not provide a bounded document-settings buffer."); + } + byte[] output = new byte[required]; + var source = GCHandle.Alloc(input, GCHandleType.Pinned); + var destination = GCHandle.Alloc(output, GCHandleType.Pinned); + try + { + // DM_IN_BUFFER | DM_OUT_BUFFER only: no prompt and no queue-default update. + if(Native.DocumentProperties(IntPtr.Zero, printer, printerName, destination.AddrOfPinnedObject(), source.AddrOfPinnedObject(), 10) != 1) + { + throw new PrinterMediaMismatchException("The driver refused job-level document settings."); + } + } + finally { destination.Free(); source.Free(); } + int size = BinaryPrimitives.ReadUInt16LittleEndian(output.AsSpan(68)); + int extra = BinaryPrimitives.ReadUInt16LittleEndian(output.AsSpan(70)); + if(size < 102 || size + extra > output.Length) + { + throw new PrinterMediaMismatchException("The driver returned incomplete document settings."); + } + return output[..(size + extra)]; + } + finally { _ = Native.ClosePrinter(printer); } + } + + + + /// + /// Contains the driver-normalization call used to create application-local DEVMODE settings. + /// + private static partial class Native + { + /// + /// Queries required buffer size or merges job settings; callers deliberately omit prompt and persistent-update flags. + /// + [DllImport("winspool.drv", EntryPoint = "DocumentPropertiesW", CharSet = CharSet.Unicode)] + internal static extern int DocumentProperties(IntPtr window, IntPtr printer, string device, IntPtr output, IntPtr input, uint mode); + } +} diff --git a/src/Qqq.PrintAgent.Windows/WindowsPrinters.cs b/src/Qqq.PrintAgent.Windows/WindowsPrinters.cs index 195bba4..c4a5cdd 100644 --- a/src/Qqq.PrintAgent.Windows/WindowsPrinters.cs +++ b/src/Qqq.PrintAgent.Windows/WindowsPrinters.cs @@ -45,7 +45,9 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend string port = Marshal.PtrToStringUni(info.PortName) ?? ""; bool interactive = RequiresInteractiveOutput(port, driver); string id = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(name))).ToLowerInvariant()[..24]; - printers.Add(new PrinterInfo(id, name, driver, port, interactive ? "UNKNOWN" : status, interactive ? [] : zebra ? ["PDF", "ZPL"] : ["PDF"])); + QueueDefaultMedia? media = interactive ? null : ReadQueueMedia(id, name, driver, port); + printers.Add(new PrinterInfo(id, name, driver, port, interactive ? "UNKNOWN" : status, interactive ? [] : zebra ? ["PDF", "ZPL"] : ["PDF"], + MediaProfiles: media?.Profile is null ? [] : [media.Profile])); } return printers; } @@ -118,18 +120,19 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend cancellationToken.ThrowIfCancellationRequested(); return job.Format switch { - "ZPL" => PrintRaw(printer.Name, job, content), - "PDF" => await PrintPdfAsync(printer.Name, job, content, cancellationToken).ConfigureAwait(false), + "ZPL" => PrintRaw(printer, job, content), + "PDF" => await PrintPdfAsync(printer, job, content, cancellationToken).ConfigureAwait(false), _ => throw new InvalidDataException("Unsupported document format."), }; } /// Send printer-ready ZPL bytes, handling partial spooler writes. - private static string PrintRaw(string printerName, PrintJob job, byte[] content) + private static string PrintRaw(PrinterInfo selectedPrinter, PrintJob job, byte[] content) { - Check(Native.OpenPrinter(printerName, out IntPtr printer, IntPtr.Zero)); + Check(Native.OpenPrinter(selectedPrinter.Name, out IntPtr printer, IntPtr.Zero)); try { + _ = RequireCurrentMedia(selectedPrinter, job); Native.DocInfo1 info = new() { DocumentName = $"QQQ {job.JobId}", DataType = "RAW" }; uint id = Native.StartDocPrinter(printer, 1, ref info); if(id == 0) @@ -163,7 +166,7 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend } /// Own the native document lifecycle while rendering its PDF pages. - private static async Task PrintPdfAsync(string printerName, PrintJob job, byte[] content, CancellationToken cancellationToken) + private static async Task PrintPdfAsync(PrinterInfo printer, PrintJob job, byte[] content, CancellationToken cancellationToken) { using InMemoryRandomAccessStream pdfStream = new(); using(DataWriter writer = new(pdfStream)) @@ -174,12 +177,14 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend } pdfStream.Seek(0); PdfDocument document = await PdfDocument.LoadFromStreamAsync(pdfStream); - return await PrintPdfDocumentAsync(printerName, job, document, cancellationToken).ConfigureAwait(false); + return await PrintPdfDocumentAsync(printer, job, document, cancellationToken).ConfigureAwait(false); } - private static async Task PrintPdfDocumentAsync(string printerName, PrintJob job, PdfDocument document, CancellationToken cancellationToken) + private static async Task PrintPdfDocumentAsync(PrinterInfo printer, PrintJob job, PdfDocument document, CancellationToken cancellationToken) { - IntPtr dc = Native.CreateDC("WINSPOOL", printerName, null, IntPtr.Zero); + QueueDefaultMedia? media = RequireCurrentMedia(printer, job); + byte[]? documentMode = media is null ? null : PreparePdfMode(printer, media); + IntPtr dc = CreateDocumentContext(printer.Name, documentMode); if(dc == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error()); @@ -188,7 +193,8 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend try { Native.DocInfo info = new() { Size = Marshal.SizeOf(), DocumentName = $"QQQ {job.JobId}" }; - int jobId = Native.StartDoc(dc, ref info); + int jobId = StartValidatedPdfDocument(documentMode, media?.Profile, + capability => Native.GetDeviceCaps(dc, capability), () => Native.StartDoc(dc, ref info)); if(jobId <= 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); @@ -272,7 +278,7 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend } } - private static class Native + private static partial class Native { [StructLayout(LayoutKind.Sequential)] internal struct PrinterInfo2 diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeMediaCapabilitiesTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeMediaCapabilitiesTests.cs new file mode 100644 index 0000000..fff1369 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentRealtimeMediaCapabilitiesTests.cs @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Core.Authentication; +using Qqq.PrintAgent.Core.Printing; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// Checks the real session/realtime handshake against controlled discovery so additive media support cannot disconnect older servers. +public sealed class AgentRealtimeMediaCapabilitiesTests +{ + /// Reads actual HELLO frames before and after reconnect, proving each socket refreshes discovery once without HTTP polling. + [Theory] + [InlineData("2.0.0", false)] + [InlineData("2.1.9", false)] + [InlineData("2.2.0", true)] + [InlineData("2.3.0", true)] + public async Task HelloAdvertisesMediaOnlyAfterStandardDiscoveryConfirmsSupport(string version, bool media) + { + await using var fixture = new RealtimeRuntimeFixture(printingVersion: version); + RealtimeRuntimeFixture.Connection first = await fixture.ConnectAsync(); + string[] expected = media ? ["realtime-v1", "REFRESH_INVENTORY", "CANCEL_SPOOL", "printer-media-v1"] + : ["realtime-v1", "REFRESH_INVENTORY", "CANCEL_SPOOL"]; + Assert.Equal(expected, fixture.LastHelloCapabilities); + // One initial authentication discovery, then one fresh discovery per socket. + Assert.Equal(2, fixture.DiscoveryRequests); + first.Abort(); + _ = await fixture.ConnectAsync(); + Assert.Equal(expected, fixture.LastHelloCapabilities); + Assert.Equal(3, fixture.DiscoveryRequests); + Assert.Equal(0, fixture.ForbiddenPolls); + Assert.Equal(0, fixture.Printer.Prints); + } + + + + /// Changes a running server's version and proves capabilities change only on the next socket, with the existing session retained. + [Theory] + [InlineData("2.0.0", "2.2.0", true)] + [InlineData("2.2.0", "2.1.0", false)] + public async Task SameSessionReconnectTracksServerUpgradeAndDowngrade(string initial, string replacement, bool mediaAfter) + { + await using var fixture = new RealtimeRuntimeFixture(printingVersion: initial); + RealtimeRuntimeFixture.Connection first = await fixture.ConnectAsync(); + Assert.Equal(!mediaAfter, fixture.LastHelloCapabilities.Contains("printer-media-v1", StringComparer.Ordinal)); + Assert.Equal(2, fixture.DiscoveryRequests); + fixture.PrintingVersion = replacement; + await first.SendAsync("DESIRED_STATE", new DeviceDesiredState(2, true, "CONNECTED")); + await fixture.WaitAsync(() => fixture.Runtime.GetSnapshot().Control!.DesiredState.Revision == 2); + Assert.Equal(2, fixture.DiscoveryRequests); + first.Abort(); + _ = await fixture.ConnectAsync(desiredState: new DeviceDesiredState(2, true, "CONNECTED")); + Assert.Equal(mediaAfter, fixture.LastHelloCapabilities.Contains("printer-media-v1", StringComparer.Ordinal)); + Assert.Equal(3, fixture.DiscoveryRequests); + Assert.Equal(0, fixture.ForbiddenPolls); + Assert.Equal(0, fixture.Printer.Prints); + } + + + + /// Rejects ambiguous or nonstable discovery claims even when a test transport bypasses the production discovery validator. + [Theory] + [InlineData("2.2.0-rc.1")] + [InlineData("2.2")] + [InlineData("2.2.0.1")] + [InlineData("02.2.0")] + [InlineData("3.0.0")] + public void UnverifiedSemanticVersionsCannotClaimMedia(string version) + { + var discovery = new QqqApiDiscovery { Extensions = [new("printing", version, "/qbit/printing")] }; + Assert.False(discovery.SupportsPrinterMedia()); + Assert.False(new QqqApiDiscovery().SupportsPrinterMedia()); + Assert.False(new QqqApiDiscovery { Extensions = [new("printing", "2.2.0", "/wrong")] }.SupportsPrinterMedia()); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/PrinterMediaTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/PrinterMediaTests.cs new file mode 100644 index 0000000..3db04c4 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/PrinterMediaTests.cs @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using Qqq.PrintAgent.Core.Printing; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// Tests native-media decisions with synthetic DEVMODE bytes and injected driver/DC results; no test opens a real spool document. +/// +public sealed class PrinterMediaTests +{ + /// + /// Checks 4-by-1, 4-by-2 and 4-by-6 form conversion using queue bytes rather than PDF dimensions or assumptions about loaded labels. + /// + [Theory] + [InlineData(254, 25400)] + [InlineData(508, 50800)] + [InlineData(1524, 152400)] + public void ConfiguredLabelDimensionsComeFromMachineDevMode(int length, int expectedHeight) + { + byte[] mode = Mode((short)length); + (int width, int height) = WindowsPrinters.ReadExplicitDimensions(mode); + PrinterMediaProfile profile = Assert.IsType(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, width, height, 300, 300)); + Assert.Equal(101600, profile.WidthMicrons); + Assert.Equal(expectedHeight, profile.HeightMicrons); + Assert.Equal(300, profile.DpiX); + Assert.Equal(300, profile.DpiY); + Assert.Equal("WINDOWS_QUEUE_DEFAULT", profile.Source); + Assert.Equal("DRIVER_DEFAULT", profile.ApplyMode); + } + + + + /// + /// Ensures incomplete geometry, unknown DPI and out-of-range dimensions cannot produce a selectable profile. + /// + [Fact] + public void PartialDimensionsAndUnknownDpiCannotAdvertiseSupportedStock() + { + byte[] mode = Mode(1524); + BinaryPrimitives.WriteUInt32LittleEndian(mode.AsSpan(72), 5); + Assert.Equal((0, 0), WindowsPrinters.ReadExplicitDimensions(mode)); + Assert.Null(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, 101600, 152400, 0, 300)); + Assert.Null(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, 101600, 152400, 300, -4)); + Assert.Null(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, 2_000_001, 152400, 300, 300)); + } + + + + /// + /// Checks repeatable fingerprints and invalidation by private defaults or driver identity, including landscape axis resolution. + /// + [Fact] + public void RevisionIsStableButPrivateConfigurationAndDriverChangesInvalidateIt() + { + byte[] mode = Mode(1524); + PrinterMediaProfile first = Profile(mode); + Assert.Equal(first, Profile(mode.ToArray())); + mode[^1] = 1; + PrinterMediaProfile changed = Profile(mode); + Assert.Equal(first.Id, changed.Id); + Assert.NotEqual(first.Revision, changed.Revision, StringComparer.Ordinal); + Assert.NotEqual(first.Revision, WindowsPrinters.BuildMediaProfile("fixture", "different driver", Mode(1524), 101600, 152400, 300, 300)!.Revision, StringComparer.Ordinal); + BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(76), 2); + Assert.Equal(152400, Profile(mode).WidthMicrons); + Assert.Equal(101600, Profile(mode).HeightMicrons); + } + + + + /// + /// Reads the actual pinned callback buffer to prove selected bytes are passed intact and the legacy null path remains distinct. + /// + [Fact] + public void PdfFactoryReceivesTheCapturedDefaultBytesRatherThanCurrentUserDefaults() + { + byte[] captured = Mode(508); + IntPtr result = WindowsPrinters.WithPinnedMode(captured, pointer => + { + Assert.NotEqual(IntPtr.Zero, pointer); + byte[] actual = new byte[captured.Length]; + Marshal.Copy(pointer, actual, 0, actual.Length); + Assert.Equal(captured, actual); + return new IntPtr(42); + }); + Assert.Equal(new IntPtr(42), result); + Assert.Equal(IntPtr.Zero, WindowsPrinters.WithPinnedMode(null, pointer => pointer)); + } + + + + /// + /// Rejects invalid orientation and incomplete private settings instead of advertising unverifiable media. + /// + [Fact] + public void UnknownOrientationAndTruncatedDriverDataDoNotProduceProfiles() + { + byte[] mode = Mode(1524); + BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(76), 0); + Assert.Null(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, 101600, 152400, 300, 300)); + Assert.Null(WindowsPrinters.BuildMediaProfile("fixture", "driver", Mode(1524)[..^1], 101600, 152400, 300, 300)); + } + + + + /// + /// Builds a synthetic 300-DPI profile from supplied driver bytes, allowing tests to isolate normalization and fingerprint changes. + /// + private static PrinterMediaProfile Profile(byte[] mode) + => Assert.IsType(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, 101600, 152400, 300, 300)); + + + + /// + /// Verifies conflicting active driver settings fail before the injected StartDoc callback and leave captured bytes untouched. + /// + [Theory] + [InlineData(2, 100)] + [InlineData(1, 50)] + [InlineData(0, 100)] + public void DriverCopiesOrScalingCannotMultiplyOrResizeSelectedPdf(int copies, int scale) + { + byte[] mode = Mode(1524); + BinaryPrimitives.WriteUInt32LittleEndian(mode.AsSpan(72), 0x11d); + BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(86), (short)copies); + BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(84), (short)scale); + byte[] original = mode.ToArray(); + int submissions = 0; + Assert.Throws(() => WindowsPrinters.StartValidatedPdfDocument(mode, Profile(mode), + capability => Caps(capability, 1200, 1800, 300, 300), () => ++submissions)); + Assert.Equal(0, submissions); + Assert.Equal(original, mode); + } + + + + /// + /// Simulates wrong physical size, orientation, resolution and unknown caps to prove effective-DC mismatches make zero submissions. + /// + [Theory] + [InlineData(1200, 600, 300, 300)] + [InlineData(1800, 1200, 300, 300)] + [InlineData(1200, 1800, 203, 300)] + [InlineData(1200, 1800, 300, 600)] + [InlineData(0, 1800, 300, 300)] + public void RejectedOrSubstitutedDeviceContextNeverStartsDocument(int width, int height, int dpiX, int dpiY) + { + byte[] mode = Mode(1524); + int submissions = 0; + Assert.Throws(() => WindowsPrinters.StartValidatedPdfDocument(mode, Profile(mode), + capability => Caps(capability, width, height, dpiX, dpiY), () => ++submissions)); + Assert.Equal(0, submissions); + } + + + + /// + /// Accepts matching portrait/landscape device contexts within one-pixel rounding and invokes the document callback exactly once. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MatchingEffectiveContextAllowsOneDocumentWithDevicePixelRounding(bool landscape) + { + byte[] mode = Mode(1524); + BinaryPrimitives.WriteUInt32LittleEndian(mode.AsSpan(72), 0x11d); + BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(86), 1); + BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(84), 100); + BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(76), (short)(landscape ? 2 : 1)); + int submissions = 0; + int result = WindowsPrinters.StartValidatedPdfDocument(mode, Profile(mode), + capability => Caps(capability, landscape ? 1801 : 1201, landscape ? 1200 : 1800, 300, 300), () => ++submissions); + Assert.Equal(1, result); + Assert.Equal(1, submissions); + } + + + + /// + /// Maps only the physical-size and DPI capability indices used by validation, making accidental reliance on other driver values fail the test. + /// + private static int Caps(int capability, int width, int height, int dpiX, int dpiY) => capability switch + { + 110 => width, + 111 => height, + 88 => dpiX, + 90 => dpiY, + _ => throw new ArgumentOutOfRangeException(nameof(capability)), + }; + + + + /// + /// Simulates a driver's private copy-count mirror update and proves job-only normalization preserves original queue bytes and revision. + /// + [Fact] + public void JobOverridesAreMergedByDriverWithoutChangingQueueFingerprintOrPrivateInput() + { + byte[] captured = Mode(1524); + BinaryPrimitives.WriteUInt32LittleEndian(captured.AsSpan(72), 0x11d); + BinaryPrimitives.WriteInt16LittleEndian(captured.AsSpan(86), 3); + BinaryPrimitives.WriteInt16LittleEndian(captured.AsSpan(84), 50); + captured[^1] = 3; + byte[] original = captured.ToArray(); + PrinterMediaProfile selected = Profile(captured); + int merges = 0; + byte[] result = WindowsPrinters.NormalizePdfMode(captured, selected, input => + { + merges++; + Assert.Equal(1, BinaryPrimitives.ReadInt16LittleEndian(input.AsSpan(86))); + Assert.Equal(100, BinaryPrimitives.ReadInt16LittleEndian(input.AsSpan(84))); + Assert.Equal(3, input[^1]); + byte[] merged = input.ToArray(); + merged[^1] = 1; // A driver updates its private copy-count mirror during normalization. + return merged; + }, Profile); + Assert.Equal(1, merges); + Assert.Equal(1, result[^1]); + Assert.Equal(original, captured); + Assert.Equal(selected.Revision, Profile(captured).Revision); + int submissions = 0; + Assert.Equal(1, WindowsPrinters.StartValidatedPdfDocument(result, selected, + capability => Caps(capability, 1200, 1800, 300, 300), () => ++submissions)); + } + + + + /// + /// Simulates ignored overrides, stripped flags and changed geometry/DPI, asserting refusal before the document callback. + /// + [Theory] + [InlineData("copies")] + [InlineData("scale")] + [InlineData("flags")] + [InlineData("geometry")] + [InlineData("dpi")] + public void UnverifiableDriverNormalizationCannotReachSpoolBoundary(string change) + { + byte[] captured = Mode(1524); + BinaryPrimitives.WriteUInt32LittleEndian(captured.AsSpan(72), 0x11d); + int submissions = 0; + Assert.Throws(() => + { + byte[] result = WindowsPrinters.NormalizePdfMode(captured, Profile(captured), input => + { + if(string.Equals(change, "copies", StringComparison.Ordinal)) + { BinaryPrimitives.WriteInt16LittleEndian(input.AsSpan(86), 2); } + if(string.Equals(change, "scale", StringComparison.Ordinal)) + { BinaryPrimitives.WriteInt16LittleEndian(input.AsSpan(84), 50); } + if(string.Equals(change, "flags", StringComparison.Ordinal)) + { BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(72), 13); } + return input; + }, output => Profile(output) with + { + HeightMicrons = string.Equals(change, "geometry", StringComparison.Ordinal) ? 50800 : 152400, + DpiX = string.Equals(change, "dpi", StringComparison.Ordinal) ? 203 : 300, + }); + WindowsPrinters.StartValidatedPdfDocument(result, Profile(captured), + capability => Caps(capability, 1200, 1800, 300, 300), () => ++submissions); + }); + Assert.Equal(0, submissions); + } + + + + /// + /// Covers the observed label-driver field mask so absent native scaling does not exclude a valid selected PDF configuration. + /// + [Fact] + public void QueueWithoutNativeScaleSupportKeepsThatFieldAbsentAndUsesSoftwareScaling() + { + byte[] captured = Mode(1524); + BinaryPrimitives.WriteUInt32LittleEndian(captured.AsSpan(72), 290573); + BinaryPrimitives.WriteInt16LittleEndian(captured.AsSpan(86), 3); + byte[] original = captured.ToArray(); + byte[] normalized = WindowsPrinters.NormalizePdfMode(captured, Profile(captured), input => + { + Assert.Equal(290573u, BinaryPrimitives.ReadUInt32LittleEndian(input.AsSpan(72))); + Assert.Equal(0, BinaryPrimitives.ReadInt16LittleEndian(input.AsSpan(84))); + Assert.Equal(1, BinaryPrimitives.ReadInt16LittleEndian(input.AsSpan(86))); + return input; + }, Profile); + int submissions = 0; + Assert.Equal(1, WindowsPrinters.StartValidatedPdfDocument(normalized, Profile(captured), + capability => Caps(capability, 1200, 1800, 300, 300), () => ++submissions)); + Assert.Equal(original, captured); + } + + + + /// + /// Creates a bounded synthetic DEVMODE with explicit form fields and private bytes for deterministic tests without native driver calls. + /// + private static byte[] Mode(short height) + { + byte[] mode = new byte[224]; + BinaryPrimitives.WriteUInt16LittleEndian(mode.AsSpan(68), 220); + BinaryPrimitives.WriteUInt16LittleEndian(mode.AsSpan(70), 4); + BinaryPrimitives.WriteUInt32LittleEndian(mode.AsSpan(72), 13); + BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(76), 1); + BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(80), height); + BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(82), 1016); + return mode; + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/PrinterWorkerIsolationTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/PrinterWorkerIsolationTests.cs index d954f80..4a29a83 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/PrinterWorkerIsolationTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/PrinterWorkerIsolationTests.cs @@ -15,6 +15,21 @@ public sealed class PrinterWorkerIsolationTests { private static string FixtureExecutable => Path.ChangeExtension(typeof(WorkerFixture.Program).Assembly.Location, ".exe"); + [Fact] + public async Task VerifiedMediaRefusalSurvivesTheWorkerBoundaryWithoutAnUncertainOutcome() + { + var backend = new IsolatedPrinterBackend(FixtureExecutable) + { + StartProcess = start => + { + start.ArgumentList.Add("--media-drift"); + return Process.Start(start) ?? throw new InvalidOperationException("Fixture failed."); + }, + }; + PrintJob job = new("fixture", "fixture", "Not printed", "PDF", new string('0', 64), 1, new PrintOptions(), "", "RECEIVED"); + await Assert.ThrowsAsync(() => backend.PrintFileAsync(job, Path.Combine(Path.GetTempPath(), "unused-media-fixture.pdf"), CancellationToken.None)); + } + [Fact] public async Task FileSubmissionUsesConfiguredWatchdogInsteadOfFixedTwoMinuteTimeout() { diff --git a/tests/Qqq.PrintAgent.Cli.Tests/RealtimeRuntimeFixture.cs b/tests/Qqq.PrintAgent.Cli.Tests/RealtimeRuntimeFixture.cs index 761d113..2585b54 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/RealtimeRuntimeFixture.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/RealtimeRuntimeFixture.cs @@ -37,14 +37,30 @@ internal sealed class RealtimeRuntimeFixture : IAsyncDisposable internal TaskCompletionSource? StateAppliedRelease { get; set; } internal Func? BeforeAcknowledgement { get; set; } internal long LastHelloSettingsRevision; + + + + /// Captures the actual HELLO payload so compatibility tests observe the wire rather than duplicating capability selection. + internal string[] LastHelloCapabilities { get; private set; } = []; + + + + /// Counts discovery requests to distinguish reconnect reuse from an added HTTP polling schedule. + internal int DiscoveryRequests; + + + + /// Controls advertised discovery across a server upgrade or downgrade while retaining the same authenticated client session. + internal string PrintingVersion { get; set; } private readonly Lock _claimLock = new(); private PrintJob? _claimed; private readonly CancellationTokenSource _stopping = new(TimeSpan.FromSeconds(30)); private readonly Task _run; private readonly List _connections = []; - internal RealtimeRuntimeFixture(int downloads = 1, RealtimeSettings? settings = null, TimeProvider? timeProvider = null, bool cacheSettings = false) + internal RealtimeRuntimeFixture(int downloads = 1, RealtimeSettings? settings = null, TimeProvider? timeProvider = null, bool cacheSettings = false, string printingVersion = "2.0.0") { + PrintingVersion = printingVersion; Settings = (settings ?? Settings) with { MaxConcurrentDownloads = downloads }; using(var store = new AgentStore(DirectoryPath)) { @@ -73,6 +89,7 @@ internal sealed class RealtimeRuntimeFixture : IAsyncDisposable RealtimeEnvelope hello = await LoopbackWebSocketPeer.ReceiveAsync(socket, _stopping.Token); Assert.Equal("HELLO", hello.Type); LastHelloSettingsRevision = hello.Payload.GetProperty("lastSettingsRevision").GetInt64(); + LastHelloCapabilities = hello.Payload.GetProperty("capabilities").EnumerateArray().Select(item => item.GetString()!).ToArray(); await connection.SendAsync("WELCOME", new { connectionId = Guid.NewGuid().ToString("N"), serverTime = Now(), desiredState = desiredState ?? new DeviceDesiredState(1, false, "CONNECTED"), settings = Settings }); connection.Start(); await WaitAsync(() => @@ -217,6 +234,17 @@ internal sealed class RealtimeRuntimeFixture : IAsyncDisposable protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string path = request.RequestUri!.AbsolutePath; + if(string.Equals(path, "/qqq/v1/version", StringComparison.Ordinal)) + { + Interlocked.Increment(ref fixture.DiscoveryRequests); + return Response(JsonSerializer.Serialize(new + { + apiVersion = "1.9.0", + features = new[] { "version", "metaData", "processes", "processCancel", "extensions", "widgets", "nativeSessionLogin" }, + clientChannels = new[] { "api" }, + extensions = new[] { new { name = "printing", version = fixture.PrintingVersion, pathPrefix = "/qbit/printing" } }, + })); + } if(path.EndsWith("/content", StringComparison.Ordinal)) { string id = path.Split('/')[^2]; @@ -246,7 +274,6 @@ internal sealed class RealtimeRuntimeFixture : IAsyncDisposable } return Response(path switch { - "/qqq/v1/version" => """{"apiVersion":"1.9.0","features":["version","metaData","processes","processCancel","extensions","widgets","nativeSessionLogin"],"clientChannels":["api"],"extensions":[{"name":"printing","version":"2.0.0","pathPrefix":"/qbit/printing"}]}""", "/qqq/v1/manageSession" => """{"uuid":"synthetic-session"}""", "/qqq/v1/metaData/authentication" => """{"name":"local","type":"TABLE_BASED"}""", "/qqq/v1/qbit/printing/session" => """{"principalId":"user","tenantId":"tenant","deviceId":"device"}""", diff --git a/tests/Qqq.PrintAgent.Cli.Tests/SessionFixture.cs b/tests/Qqq.PrintAgent.Cli.Tests/SessionFixture.cs index d1e4bdc..4218115 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/SessionFixture.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/SessionFixture.cs @@ -103,7 +103,7 @@ internal sealed class SessionFixture : IDisposable object body = new DeviceControlPoll(1, DateTime.UtcNow.ToString("O", System.Globalization.CultureInfo.InvariantCulture), 5, new DeviceDesiredState(1, false, "CONNECTED"), []); return new HttpResponseMessage(Status) { Content = new StringContent(JsonSerializer.Serialize(body, PrintApiClient.JsonOptions), Encoding.UTF8, "application/json") }; } - public Task DiscoverAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); + public Task DiscoverAsync(CancellationToken cancellationToken = default) => Task.FromResult(new QqqApiDiscovery()); public Task GetAuthenticationMetadataAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task SignInWithPasswordAsync(string username, string password, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task BeginBrowserLoginAsync(Uri redirectUri, CancellationToken cancellationToken = default) => throw new NotSupportedException(); diff --git a/tests/Qqq.PrintAgent.Core.Tests/PrintWorkerTests.cs b/tests/Qqq.PrintAgent.Core.Tests/PrintWorkerTests.cs index 4478d31..871c4a7 100644 --- a/tests/Qqq.PrintAgent.Core.Tests/PrintWorkerTests.cs +++ b/tests/Qqq.PrintAgent.Core.Tests/PrintWorkerTests.cs @@ -12,6 +12,27 @@ namespace Qqq.PrintAgent.Core.Tests; public sealed class PrintWorkerTests { + [Theory] + [InlineData(true, false, "FAILED", 0)] + [InlineData(false, true, "FAILED", 0)] + [InlineData(false, false, "SPOOLED", 1)] + public async Task SelectedMediaDriftCannotSpoolAndKnownNativeRefusalIsNotUncertain(bool discoveryDrift, bool nativeDrift, string expected, int spoolCount) + { + byte[] content = [1]; + PrinterMediaProfile profile = new("default-id", new string('a', 64), "Default", 101600, 152400, 300, 300); + PrintOptions options = new(MediaProfile: new(profile.Id, profile.Revision)); + PrintJob job = new("job1", "printer1", "Test", "ZPL", Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(content)), 1, options, "", "CLAIMED"); + using FixtureHandler handler = new(job, content); + using PrintApiClient api = new("http://localhost", "fixture", handler); + MemoryJournal journal = new(); + FakePrinter printer = new(profile: profile, discoveryDrift: discoveryDrift, nativeDrift: nativeDrift); + await new PrintWorker(api, printer, journal).RunOnceAsync(); + Assert.Equal(spoolCount, printer.PrintCount); + Assert.Equal(expected, journal.GetState(job.JobId)); + if(discoveryDrift) + { Assert.DoesNotContain("SUBMITTING", handler.Events, StringComparer.Ordinal); } + } + [Theory] [InlineData(true)] [InlineData(false)] @@ -185,11 +206,24 @@ public sealed class PrintWorkerTests } } - private sealed class FakePrinter(string? displayName = null) : IPrinterBackend + private sealed class FakePrinter(string? displayName = null, PrinterMediaProfile? profile = null, bool discoveryDrift = false, bool nativeDrift = false) : IPrinterBackend { + private int _discoveries; public int PrintCount { get; private set; } - public IReadOnlyList Discover() => [new("printer1", "Test", "Zebra", "USB", "READY", ["ZPL"], DisplayName: displayName)]; - public Task PrintAsync(PrintJob job, byte[] content, CancellationToken cancellationToken) { PrintCount++; return Task.FromResult("123"); } + public IReadOnlyList Discover() + { + PrinterMediaProfile? current = profile; + if(discoveryDrift && _discoveries++ > 0 && current is not null) + { current = current with { Revision = new string('b', 64) }; } + return [new("printer1", "Test", "Zebra", "USB", "READY", ["ZPL"], DisplayName: displayName, MediaProfiles: current is null ? null : [current])]; + } + public Task PrintAsync(PrintJob job, byte[] content, CancellationToken cancellationToken) + { + if(nativeDrift) + { throw new PrinterMediaMismatchException("Fixture default changed before native submission."); } + PrintCount++; + return Task.FromResult("123"); + } } private sealed class MemoryJournal : IJobJournal diff --git a/tests/Qqq.PrintAgent.Core.Tests/PrinterMediaContractTests.cs b/tests/Qqq.PrintAgent.Core.Tests/PrinterMediaContractTests.cs new file mode 100644 index 0000000..87a5797 --- /dev/null +++ b/tests/Qqq.PrintAgent.Core.Tests/PrinterMediaContractTests.cs @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Text.Json; +using Qqq.PrintAgent.Core.Printing; + +namespace Qqq.PrintAgent.Core.Tests; + +/// +/// Checks additive media wire compatibility and rejection boundaries before any operating-system adapter is involved. +/// +public sealed class PrinterMediaContractTests +{ + /// + /// Provides a bounded synthetic queue default so contract tests do not depend on installed printers or physical stock. + /// + private static readonly PrinterMediaProfile Profile = new("opaque-default", new string('a', 64), "Default", 101600, 152400, 300, 300); + + + + /// + /// Round-trips inventory and selection while verifying that legacy options still omit the optional media field. + /// + [Fact] + public void OptionalMediaSelectionAndInventoryRoundTripWithoutChangingLegacyOptions() + { + var printer = new PrinterInfo("p", "Queue", "Driver", "Port", "READY", ["PDF", "ZPL"], MediaProfiles: [Profile]); + string json = JsonSerializer.Serialize(printer, PrintApiClient.JsonOptions); + PrinterInfo restored = JsonSerializer.Deserialize(json, PrintApiClient.JsonOptions)!; + Assert.Equal(Profile, Assert.Single(restored.MediaProfiles!)); + Assert.DoesNotContain("mediaProfile", JsonSerializer.Serialize(new PrintOptions(), PrintApiClient.JsonOptions), StringComparison.Ordinal); + PrintOptions options = new(MediaProfile: new(Profile.Id, Profile.Revision)); + Assert.Equal(options, JsonSerializer.Deserialize(JsonSerializer.Serialize(options, PrintApiClient.JsonOptions), PrintApiClient.JsonOptions)); + PrinterMediaProfile.RequireMatch(options, [Profile]); + } + + + + /// + /// Exercises unavailable, stale and ambiguous selections plus dimension conflicts, while preserving the unselected legacy path. + /// + [Fact] + public void MissingChangedDuplicateAndConflictingMediaSelectionsAreRejected() + { + PrintOptions options = new(MediaProfile: new(Profile.Id, Profile.Revision)); + Assert.Throws(() => PrinterMediaProfile.RequireMatch(options, null)); + Assert.Throws(() => PrinterMediaProfile.RequireMatch(options, [Profile with { Revision = new string('b', 64) }])); + Assert.Throws(() => PrinterMediaProfile.RequireMatch(options, [Profile, Profile])); + Assert.Throws(() => PrinterMediaProfile.RequireMatch(options with { PaperWidthMm = 101.6 }, [Profile])); + Assert.Throws(() => PrinterMediaProfile.RequireMatch(options with { PaperHeightMm = 152.4 }, [Profile])); + Assert.Throws(() => PrinterMediaProfile.RequireMatch(options with { MediaProfile = new(Profile.Id, new string('A', 64)) }, [Profile])); + PrinterMediaProfile.RequireMatch(new PrintOptions(), null); + } + + + + /// + /// Checks the exact 128-character boundary and forbidden slash against matching inventory, so lookup success cannot hide malformed IDs. + /// + [Theory] + [InlineData(128, false, true)] + [InlineData(129, false, false)] + [InlineData(128, true, false)] + public void SelectionIdsRespectTheSharedOpaqueIdBoundary(int length, bool slash, bool accepted) + { + string id = new string('a', length - 4) + (slash ? "A9_/" : "A9_."); + PrinterMediaProfile current = Profile with { Id = id }; + PrintOptions options = new(MediaProfile: new(id, current.Revision)); + if(accepted) + { + PrinterMediaProfile.RequireMatch(options, [current]); + } + else + { + Assert.Throws(() => PrinterMediaProfile.RequireMatch(options, [current])); + } + } + + + + /// + /// Accepts maximum legal names and inventory sizes, then rejects single-step overflows and empty names. + /// + [Fact] + public void CurrentProfileNamesAndInventoryHaveBoundedContractSizes() + { + PrinterMediaProfile current = Profile with { Name = new string('a', 512) }; + PrintOptions options = new(MediaProfile: new(current.Id, current.Revision)); + PrinterMediaProfile[] profiles = Enumerable.Range(0, 32).Select(index => current with { Id = $"p-{index}" }).ToArray(); + profiles[0] = current; + PrinterMediaProfile.RequireMatch(options, profiles); + Assert.Throws(() => PrinterMediaProfile.RequireMatch(options, [.. profiles, current with { Id = "overflow" }])); + Assert.Throws(() => PrinterMediaProfile.RequireMatch(options, [current with { Name = new string('a', 513) }])); + Assert.Throws(() => PrinterMediaProfile.RequireMatch(options, [current with { Name = "" }])); + } +} diff --git a/tests/Qqq.PrintAgent.WorkerFixture/Program.cs b/tests/Qqq.PrintAgent.WorkerFixture/Program.cs index cc50e0e..807fb1d 100644 --- a/tests/Qqq.PrintAgent.WorkerFixture/Program.cs +++ b/tests/Qqq.PrintAgent.WorkerFixture/Program.cs @@ -31,10 +31,10 @@ public static class Program Console.WriteLine(child.Id.ToString(CultureInfo.InvariantCulture)); return 0; } - return await PrinterWorkerHost.RunAsync(new FakePrinters(args.Contains("--hang", StringComparer.Ordinal))).ConfigureAwait(false); + return await PrinterWorkerHost.RunAsync(new FakePrinters(args.Contains("--hang", StringComparer.Ordinal), args.Contains("--media-drift", StringComparer.Ordinal))).ConfigureAwait(false); } - private sealed class FakePrinters(bool hang) : IFilePrinterBackend + private sealed class FakePrinters(bool hang, bool mediaDrift) : IFilePrinterBackend { public IReadOnlyList Discover() { @@ -52,6 +52,8 @@ public static class Program public Task PrintFileAsync(PrintJob job, string path, CancellationToken cancellationToken) { + if(mediaDrift) + { throw new PrinterMediaMismatchException("The fixture changed its default before submission."); } if(hang) { Thread.Sleep(Timeout.Infinite); } throw new InvalidOperationException("This fixture never opens documents or prints."); -- 2.54.0 From 35ed93c7d5cad707a59d174ad533f3a234f7b5d8 Mon Sep 17 00:00:00 2001 From: James Maes Date: Sun, 1 Nov 2026 13:10:23 -0600 Subject: [PATCH 5/8] ci: pin the reviewed media protocol contract Use protected protocol source a26c18c for compatible consumer verification. Fail local Windows verification early when required shared fixtures are missing instead of building a test assembly with incomplete inputs. Co-Authored-By: Codex GPT-6 Signed-off-by: James Maes --- .github/workflows/ci.yml | 2 +- build/Verify.ps1 | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fd5f434..c34e057 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,7 +42,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: QRun-IO/qqq-print-protocol - ref: f3cbc02e9b0fb4fdfefaa59d976c04df747cc589 + ref: a26c18c90c7d6102bbe26eb50cbb90fcd1bd46e3 path: qqq-print-protocol persist-credentials: false - name: Set up .NET diff --git a/build/Verify.ps1 b/build/Verify.ps1 index f4e72dd..b272027 100644 --- a/build/Verify.ps1 +++ b/build/Verify.ps1 @@ -14,6 +14,13 @@ if(-not (Test-Path -LiteralPath $protocolFixtures)) { throw 'Check out the pinned qqq-print-protocol repository beside qqq-print-agent before running verification.' } +foreach($fixture in @('claim.response.json', 'enroll.response.json', 'control-poll.response.json', 'printing-session.response.json', 'printing-session-bound.response.json')) +{ + if(-not (Test-Path -LiteralPath (Join-Path $ProtocolFixtures $fixture) -PathType Leaf)) + { + throw "Required protocol fixture is missing: $fixture. Use the protocol revision pinned in .github/workflows/ci.yml, or pass its fixtures directory with -ProtocolFixtures." + } +} Push-Location $projectRoot try { -- 2.54.0 From c4c663aa385776e839a17ab7114a9b21eab86e44 Mon Sep 17 00:00:00 2001 From: James Maes Date: Sun, 1 Nov 2026 13:33:00 -0600 Subject: [PATCH 6/8] feat(tools): virtual agent writes to ~/Downloads by default; identity in ~/.qqq-print-agent (#17) The virtual file printer writes PDFs to ~/Downloads when neither --out nor QQQ_PRINT_OUT is set, and keeps its device identity in ~/.qqq-print-agent/state.json (an identity left next to an earlier output folder is still honoured). Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.1 --- tools/virtual-agent/README.md | 10 ++++--- .../virtual-agent/test/virtual-agent.test.mjs | 27 +++++++++++++++---- tools/virtual-agent/virtual-agent.mjs | 19 ++++++++++--- 3 files changed, 44 insertions(+), 12 deletions(-) diff --git a/tools/virtual-agent/README.md b/tools/virtual-agent/README.md index 59486c8..75539e4 100644 --- a/tools/virtual-agent/README.md +++ b/tools/virtual-agent/README.md @@ -14,16 +14,18 @@ and does not qualify the Windows service. A written file is `SPOOLED` and then ```sh # first run: enroll through the native "Enroll a print device" process and approve the printer -node tools/virtual-agent/virtual-agent.mjs --server http://localhost:8078 --out ./printed --enroll --approve -# later runs reuse the identity in ./printed/.agent-state.json +node tools/virtual-agent/virtual-agent.mjs --server http://localhost:8078 --enroll --approve +# later runs reuse the identity in ~/.qqq-print-agent/state.json; printed PDFs land in ~/Downloads +node tools/virtual-agent/virtual-agent.mjs --server http://localhost:8078 +# or somewhere else node tools/virtual-agent/virtual-agent.mjs --server http://localhost:8078 --out ./printed ``` | Option | Meaning | |---|---| | `--server ` | QQQ server (`QQQ_PRINT_SERVER`); plain http only for loopback | -| `--out ` | where printed documents go (`QQQ_PRINT_OUT`); each job writes `