refactor(cli)!: manage the installed service only; remove the legacy mode; cover every line #28

Merged
james.maes merged 13 commits from refactor/2.0-cli-cleanup-on-release-20261110 into release/2.0 2026-11-10 21:52:13 +00:00
25 changed files with 1710 additions and 394 deletions

No files matched your search

+34
View File
@@ -13,6 +13,40 @@ capability gets the ordinary logout, and the log says the provider session was n
`sign-out` cannot open the companion's callback inbox, so it still ends only the QQQ session and says so.
No change to pairing, history or the printing protocol.
Command line (2.0, breaking). `qqq-print-agent.exe` now only manages the installed service over its pipe.
- The `--legacy-compat` mode is removed with everything that existed for it: the separate per-user data directory
(`--data-dir`), the command line's worker lock, the run-once claim pass (`run --once`), the isolated enroll and
expose paths, and the `--service` flag. It was the last path the shipped programs could reach that sent a device
token outside a QQQ session. A command line that uses one of the four options is refused with a sentence saying
they were removed in 2.0. State the mode left in `%LOCALAPPDATA%\QqqPrintAgent` is no longer read; see
[Administrator operations](docs/ADMINISTRATION.md#command-line).
- The executable is no longer a printer worker: `--printer-worker` is an unknown command. Only the removed mode
ever started it that way; the service starts its own executable as the worker, in 1.x as now. Its two remaining
internal roles (MSI update helper, browser sign-in callback) are unchanged.
- Help: `--help` and `-h` print the usage on standard output and exit 0 (they used to exit 1), as `help` and no
arguments already did, and so does `--help` or `-h` after a command (`printers --help`). The usage text is new:
one line per command, where the enrollment code comes from, and the exit codes. It is written with the
platform's line ends.
- Refusals: an unknown command, and any command line a command does not accept, exits 1 with one line saying what
is wrong followed by the usage, on standard error (an unknown command used to print the old usage on standard
output). The reasons are new and fixed: for example `--server is required.`, `--printer needs a value.`,
`--exposed may be given only once.`, `'run' takes no arguments.`. A refusal never repeats what was typed.
- Arguments are strict. A command accepts exactly its own options, each once, each with a value that is not blank
and does not begin with `--`; extra words used to be ignored. `--exposed` takes `true` or `false` in any letter
case and nothing else (padded values used to be accepted). Nothing is sent, and no enrollment code is asked
for, when a command line is refused.
- Enrollment code: there is a prompt only when the code is typed at a Windows console. It is written to standard
error, not standard output, the code is not shown while it is typed, and the prompt line is ended afterwards.
When the code is piped in or comes from `QQQ_PRINT_ENROLLMENT_CODE` nothing is prompted: standard output holds
only the service's reply and a successful enrollment writes nothing to standard error. A terminal that gives
programs a pipe instead of a console (the default Git Bash window) is read as redirected input and may echo
what is typed; an unattended caller whose console nobody types at must set the variable or redirect input.
White space around the code and a leading byte-order mark are dropped, whether it comes from the variable or
standard input.
- `service-status` and `snapshot` exit 1 when the service replies with `Error:`, as the other commands already
did. The reply itself is still printed on standard output.
## 1.2.1
Release-pipeline fix only; same source as 1.2.0 otherwise. The stable release workflow's per-edition
+2 -2
View File
@@ -71,7 +71,7 @@ Five projects, strict layering (Core → Windows → Service/UI/CLI). Business l
| `Qqq.PrintAgent.Windows` | Spooler/PDF/ZPL backends, SQLite + DPAPI store, named-pipe IPC, the long-running runtime | `AgentRuntime.*.cs` (partial class split by concern), `AgentPipe*`, `AgentStore` |
| `Qqq.PrintAgent.Service` | Windows Service host only | `PrintService.cs` |
| `Qqq.PrintAgent` | WinUI/AppKit companion: tray, Printers/Jobs/Logs/Settings views, MSI update UX | `MainWindow.*.cs` (partial class split by concern) |
| `Qqq.PrintAgent.Cli` | Authenticated service management over the pipe; isolated legacy diagnostics | `Program.cs` |
| `Qqq.PrintAgent.Cli` | Service management over the pipe, nothing else; the same executable is also the MSI update helper and the browser sign-in callback forwarder | `CommandLine.cs` (`Program.cs` only binds the real console, pipe and helpers) |
Large classes are deliberately split into partial files by concern (`AgentRuntime.Realtime.cs`, `AgentRuntime.Jobs.cs`, `MainWindow.Updates.cs`, ...). Add new behavior to the matching partial rather than growing `AgentRuntime.cs` / `MainWindow.xaml.cs`.
@@ -86,7 +86,7 @@ Large classes are deliberately split into partial files by concern (`AgentRuntim
## Test layout
- `tests/Qqq.PrintAgent.Core.Tests`: protocol fixtures (`ProtocolFixtureTests`), loopback WebSocket peer, worker state machine, media contracts. New Core tests are written here (see the host note under Commands for where it builds).
- `tests/Qqq.PrintAgent.Cli.Tests`: despite the name, this is the Windows runtime suite (`AgentRuntime*`, `AgentRealtime*`, `AgentPipe*`, `AgentStore*`). Put Windows-layer tests here.
- `tests/Qqq.PrintAgent.Cli.Tests`: despite the name, this is mostly the Windows runtime suite (`AgentRuntime*`, `AgentRealtime*`, `AgentPipe*`, `AgentStore*`). Put Windows-layer tests here. The command-line tests are its `Cli*Tests.cs` files: they drive `CommandLine` through `CliFixture` (fakes for console, environment, pipe and helpers), and `CliProcessTests` starts the built executable.
- `tests/Qqq.PrintAgent.WorkerFixture`: child-process fixture used by runtime tests.
## Conventions worth knowing
+1 -1
View File
@@ -26,7 +26,7 @@ Publish ordinary branches and pull requests to the [primary Gitea repository](ht
- Do not include secrets, document contents, customer labels or local journals in issues, fixtures or commits.
- Disclose substantial AI assistance in the PR and include a model-naming Co-Authored-By trailer when appropriate.
Line coverage is gated per assembly ([ADR-0003](docs/adr/0003-version-2.md)). `build/Verify.ps1` merges the suites' reports and fails when an assembly is below its minimum in `build/minimum-coverage.json`. The minimums are a floor that only moves up: when a change adds tests, raise the entry in the same change to the measured percentage rounded down, less one point (a few timing-dependent lines differ between runs); never lower one to make a change pass. The release bar is 100% for Core and the CLI and 90% for the Windows layer, so a green gate today means "within a point of the recorded baseline", not "fully covered". Code a test cannot reach (native calls, process hooks) goes in a thin adapter marked `[ExcludeFromCodeCoverage(Justification = "...")]`, with the decisions around it kept in covered code. Elevated desktop tests are separate from hosted CI because they need an interactive administrator session.
Line coverage is gated per assembly ([ADR-0003](docs/adr/0003-version-2.md)). `build/Verify.ps1` merges the suites' reports and fails when an assembly is below its minimum in `build/minimum-coverage.json`. The minimums are a floor that only moves up: when a change adds tests, raise the entry in the same change to the measured percentage rounded down, less one point (a few timing-dependent lines differ between runs); never lower one to make a change pass. An assembly that has reached its release bar is recorded at the bar, with no point of slack: that is why the CLI stands at 100. The release bar is 100% for Core and the CLI and 90% for the Windows layer, so for an assembly still below its bar a green gate means "within a point of the recorded baseline", not "fully covered". Code a test cannot reach (native calls, process hooks) goes in a thin adapter marked `[ExcludeFromCodeCoverage(Justification = "...")]`, with the decisions around it kept in covered code. Elevated desktop tests are separate from hosted CI because they need an interactive administrator session.
## UI and hardware tests
+1 -1
View File
@@ -1,5 +1,5 @@
{
"Qqq.PrintAgent.Core": 86,
"Qqq.PrintAgent.Windows": 69,
"qqq-print-agent": 37
"qqq-print-agent": 100
}
+26 -1
View File
@@ -24,10 +24,35 @@ Get-Service QqqPrintAgent, Spooler
& 'C:\Program Files\QQQ Print Agent\Cli\qqq-print-agent.exe' service-status
```
Use the actual install path if it differs. Normal CLI commands and the companion use the authenticated installed service. Its printer list reflects the service identity; explicit isolated legacy diagnostics may see different queues under their invoking account.
Use the actual install path if it differs. CLI commands and the companion use the authenticated installed service, so the printer list reflects the service identity, not the account that runs the command.
Use the built-in AppKit activity log for shared service and companion events, with source labels and severity filtering. Windows Event Viewer can also help diagnose service-host startup failures. Record relevant timestamps, job IDs and error text without customer document contents.
## Command line
`qqq-print-agent.exe` manages the installed service and nothing else. Each command is one request over the administrator-only pipe, so run it from an elevated prompt with the service running. Sign in through the companion first: enrollment and the connection commands act on the service's QQQ session.
| Command | What the service does |
| --- | --- |
| `printers` | Lists the printers it can see, as JSON |
| `enroll --server URL` | Pairs this computer with a QQQ server using a one-time enrollment code |
| `expose --printer ID --exposed true\|false` | Shares a printer with QQQ, or stops sharing it |
| `run` | Refreshes its connection to QQQ |
| `sign-out` | Ends its QQQ session (the identity provider's browser session is ended only by Sign out in the companion) |
| `service-status` | Reports its connection status |
| `snapshot` | Reports its state as JSON: connection, printers, recent jobs and logs |
| `help`, `--help`, `-h`, or no arguments; `--help` or `-h` after a command | Nothing; the usage is printed |
The enrollment code is read from the `QQQ_PRINT_ENROLLMENT_CODE` environment variable. When the variable is not set it is read from standard input, in one of two ways. When input is redirected, one line is read with no prompt, so a script can pipe the code in: standard output holds only the service's reply and, on success, standard error stays empty (when a script redirects or captures standard error, with `2>&1`, a file, the ISE or remoting, Windows PowerShell turns each line a native program writes there into an error). When input is a Windows console, the prompt `Enrollment code: ` is written to standard error and the code is typed without being shown (Backspace corrects, Enter ends). White space around the code is dropped, and so is a leading byte-order mark, which Windows PowerShell 5.1 puts in front of piped text when the console code page is UTF-8. The code is never accepted as an argument and never printed.
Two limits of that rule. "Not shown" holds at a Windows console. A terminal that gives native programs a pipe instead of a console (the default Git Bash window, for example) counts as redirected input: there is no prompt, the tool cannot stop the terminal echoing what is typed, and the line may stay on the screen; use the variable there. And an unattended caller that has a console nobody can type at (a scheduled task, for example) must set the variable or redirect input, or the command waits at the prompt for a key that never comes.
The exit code is 0 on success and 1 otherwise: wrong arguments, a service that cannot be reached or is not the installed one, a timeout, or a reply from the service that begins with `Error:`. Standard output carries what the service replied, including an `Error:` reply (the exit code, not the stream, tells a script it failed), and usage that was asked for. Standard error carries the command line's own failures (the service unreachable, a timeout, no enrollment code), the enrollment prompt when the code is typed at a console, and the reason and usage for a refused command line; a command that succeeds without that prompt writes nothing to it.
A command accepts exactly the options shown, each once, in any order, each with a value that is not blank and does not begin with `--`. `--exposed` takes the word `true` or `false` in any letter case. Anything else is refused before the service is contacted and before a code is asked for, with one line saying what is wrong (`--server is required.`, `--printer needs a value.`, `'run' takes no arguments.` and so on) followed by the usage. The refusal names only the tool's own commands and options and never repeats what was typed, because a mistyped command line can contain an enrollment code.
Version 2.0 removed `--legacy-compat` and the options that existed for it (`--data-dir`, `--once`, `--service`); a command line that uses one is refused with a sentence saying so. The executable is also no longer a printer worker (`--printer-worker`): the service starts its own executable for that. If that mode was ever used on a machine, its separate per-user state is still in `%LOCALAPPDATA%\QqqPrintAgent` (`connection.dpapi`, `journal.db`, `worker.lock`). Nothing reads it any more; delete it once the device it enrolled has been revoked in QQQ. Leave `auth-callback.log` in that folder: the browser sign-in helper still writes it.
## Credentials and network
Sign in through standard QQQ authentication, then associate an existing unbound pairing or enroll a new device explicitly. Every normal printing request requires the current QQQ user session and secondary device proof; server user, tenant and record permissions still apply. Session renewal does not change the journal's device identity. Revoke the device in QQQ when decommissioning a machine. Revocation cannot recall a job already accepted by the Windows spooler.
+3 -3
View File
@@ -12,7 +12,7 @@ and reconnect rules. The service never falls back from WSS to job/control pollin
| Qqq.PrintAgent.Windows | Native spooler/PDF adapter, SQLite/DPAPI store and local management runtime |
| Qqq.PrintAgent.Service | .NET Windows Service host |
| Qqq.PrintAgent | AppKit/WinUI setup, details and tray companion |
| Qqq.PrintAgent.Cli | Authenticated service management and explicit isolated legacy diagnostics |
| Qqq.PrintAgent.Cli | Management of the installed service over its pipe; also the MSI update helper and browser sign-in callback forwarder |
The service owns the credential, journal and print operations. The UI is optional at runtime and sees only credential-free snapshots. Service IPC uses the `QqqPrintAgent` named pipe and accepts administrator clients. `snapshot` returns connection health, all locally discovered printers with exposure state, the latest 50 jobs and the latest 100 in-memory log entries. `set-exposure` persists a selected queue and returns a fresh snapshot. Legacy `status`, `printers` and `enroll` operations remain available.
@@ -51,9 +51,9 @@ $agent = '.\src\Qqq.PrintAgent.Cli\bin\x64\Debug\net10.0-windows10.0.19041.0\qqq
& $agent run
```
`run` requests a connection refresh through the authenticated service; it does not start a second foreground worker. Device setup and explicit printer exposure use that same service. Submit a physical test only when authorized, after approving the selected exposed queue in QQQ.
`run` requests a connection refresh through the authenticated service; the command line never claims or prints a job itself. Device setup and explicit printer exposure use that same service. Submit a physical test only when authorized, after approving the selected exposed queue in QQQ.
Direct bearer diagnostics require explicit `--legacy-compat` and a separate private `--data-dir`; they cannot use `--service` and are never an automatic fallback. The exclusive `worker.lock` prevents simultaneous workers on one journal. Do not point a development worker at installed state.
The command line has no state and no server transport of its own: every command is one request to the service. The `--legacy-compat` bearer diagnostics and their `--data-dir`, `--once` and `--service` options were removed in 2.0. The service holds an exclusive `worker.lock` in its data directory, so a second service host cannot run against the same journal; do not point a development service at installed state. `CommandLine` takes the console, the environment, the pipe and the helper entry points as injected functions, so its tests need none of them.
## Virtual file printer (macOS/Linux)
+2
View File
@@ -43,6 +43,8 @@ The audit originally found backend liveness defects and missing day-to-day contr
| Poll interval was ignored and CLI timeouts exited successfully. | Runtime honors a 1–20 second bounded interval; foreground Ctrl+C is the only successful cancellation path. Other CLI cancellations/timeouts exit 1. | Timeout regression passes; reconnect wakes the interval early. |
| Arbitrary branding accents could make white AppKit text unreadable. | JSON load and direct application enforce unrounded white-text contrast of at least 4.5:1; lighter accents fall back to default teal. Main heading follows the active theme. | Tests include the #767676 pass / #777777 fail boundary. See [branding policy](BRANDING.md). Theme, scaling and assistive-technology acceptance remain separate. |
Note added 2026-11-10, for version 2.0. Three rows above record the command line as it was on the audit date and no longer describe the product: "CLI enrollment could overwrite service credentials under the wrong Windows identity", "Native driver calls could block the service indefinitely" (where it says the CLI uses a disposable child) and "Poll interval was ignored and CLI timeouts exited successfully" (where it speaks of foreground Ctrl+C). Version 2.0 removed the command line's foreground mode (`--legacy-compat`, its per-user data directory and worker lock, and `run --once` with its Ctrl+C path) and its printer-worker role. The default-directory, shared-directory rejection and lock-contention tests the first row cites were deleted with that mode. What still holds from those rows: service commands use the pipe, which is now all the command line does; the service starts the disposable printer child, and only the service; and a command-line timeout or cancellation exits 1, now held by `CliServiceCommandTests`. The rows themselves are left as written.
## Boundaries retained
- Device connections are outbound HTTPS; HTTP is only a loopback development exception. No inbound firewall rule or local HTTP management endpoint is added.
+3 -3
View File
@@ -18,7 +18,7 @@ Run the MSI as an administrator. Windows Installer deploys one coherent applicat
- The `QqqPrintAgent` automatic Windows service, running as LocalSystem and depending on the Windows Spooler.
- The native **QQQ Print Agent** setup/status app and Start-menu entry.
- The `qqq-print-agent.exe` diagnostic CLI.
- The `qqq-print-agent.exe` command-line tool, which manages the service.
- A restricted `%ProgramData%\QqqPrintAgent` directory for enrollment and the job journal.
There is no inbound firewall rule or local HTTP server. The client requires outbound WSS upgrades and HTTPS to the QQQ server; update checks/downloads use HTTPS to GitHub release services. Use the matching qbit-printing 1.0.0 server with native printing API 2.3. There is no job/control polling fallback. The UI requests administrator elevation because its management pipe permits only SYSTEM and local administrators.
@@ -49,7 +49,7 @@ Full uninstall removes only tasks whose name, current-user SID, interactive prin
## Isolated native printer operations
Discovery, submission and cancellation run in a short-lived child of the service or explicit diagnostic CLI. Control requests use anonymous standard-input/output pipes. Realtime documents stream to protected owned staging files; their content is not placed in command arguments or logs. Discovery and cancellation have bounded helper deadlines. Realtime printing uses the server's `nativeSubmissionTimeoutMillis`, default 120 seconds, rather than a fixed submission deadline. A timed-out child is terminated, with bounded cleanup, and also watches its parent. The child still runs with service privileges; isolation limits a blocked driver, not its authority.
Discovery, submission and cancellation run in a short-lived child of the service. Control requests use anonymous standard-input/output pipes. Realtime documents stream to protected owned staging files; their content is not placed in command arguments or logs. Discovery and cancellation have bounded helper deadlines. Realtime printing uses the server's `nativeSubmissionTimeoutMillis`, default 120 seconds, rather than a fixed submission deadline. A timed-out child is terminated, with bounded cleanup, and also watches its parent. The child still runs with service privileges; isolation limits a blocked driver, not its authority.
This bounds a blocked printer driver without stopping cloud connectivity permanently. It cannot retract bytes already accepted by a printer: timeout, crash or cancellation after submission begins is an uncertain outcome and requires inspection before reprinting. Existing spooler receipt cancellation verifies the exact QQQ document identity before requesting cancellation; it does not prove that no paper or label has already emerged. Synthetic subprocess tests use a fake backend and never access a printer.
@@ -65,7 +65,7 @@ Use qbit-printing 1.0.0 on QQQ 4.1.0-RC.21 or a compatible newer server; the rel
For an existing unbound installation, choose **Associate the existing pairing with my account**; preserve its device record and history. For a new installation, complete sign-in and enter a single-use enrollment code created in QQQ. Enrollment runs in the service, protecting its device proof and QQQ session under the service identity. The desktop does not retain the password or device token. **Set up a new pairing** is an explicit replacement flow, not routine upgrade migration.
Normal CLI setup, printer exposure and connection commands use the authenticated installed service. Sign in through the companion first; `run` requests a connection refresh. Explicit `--legacy-compat` diagnostics require a separate `--data-dir` and cannot use `--service`. Do not copy a user-protected DPAPI credential into ProgramData: credentials are bound to the account that created them. The service owns unattended discovery and printing.
CLI setup, printer exposure and connection commands are requests to the authenticated installed service; see [Administrator operations](ADMINISTRATION.md#command-line). Sign in through the companion first; `run` requests a connection refresh. The command line keeps no credentials or data of its own. Do not copy a user-protected DPAPI credential into ProgramData: credentials are bound to the account that created them. The service owns unattended discovery and printing.
## Updates
+1 -1
View File
@@ -12,7 +12,7 @@ The installed browser callback is exactly `io.qrun.qqq-print-agent:/oauth/callba
**Shared server with the Android scanner.** One QQQ host and one OAuth2 provider/`clientId` can serve both clients. The native grant's `redirectUris` must contain both exact callbacks, `io.qrun.qqq-print-agent:/oauth/callback` (print agent) and `io.qrun.mobile.scanner.oauth://callback/oauth2redirect` (scanner), and the provider must allow both exactly (no wildcards). The host must also advertise the `api` and `android` client channels and both the `printing` and `mobile-scanners` extensions. Nonce handling is negotiated per server: when the grant descriptor has `nonceValidation: REQUIRED` (which the scanner demands) or `OPTIONAL`, or when discovery advertises the `nativeSessionNonceValidation` capability, the agent sends that attempt's own authorization nonce as `expectedNonce` in the `manageSession` exchange. When neither is present (older servers) the exchange body is unchanged. Any other non-empty policy value is refused as a server configuration problem before a browser opens. The nonce is never taken from the callback, regenerated or logged. Human permissions (`printing_admin` versus the scanner's `mobile.*`) and device credentials stay separate. Validation against a real shared Authentik host is pending; this is not released.
Normal CLI `printers`, `enroll`, `expose`, `run` and `sign-out` commands use the installed authenticated service. `run` requests a connection refresh; the service owns unattended printing. Direct bearer-based foreground diagnostics require explicit `--legacy-compat` and a separate user data directory; they cannot use `--service`. They are a compatibility diagnostic, not the app's sign-in or fallback path.
The CLI `printers`, `enroll`, `expose`, `run` and `sign-out` commands use the installed authenticated service. `run` requests a connection refresh; the service owns unattended printing. The command line has no sign-in or transport of its own: the bearer-based `--legacy-compat` diagnostics were removed in 2.0.
The server and its identity provider govern session lifetime, renewal and current permissions. Unattended service operation does not promise an indefinite authorization lifetime: expiration, revocation or a policy change can require a new sign-in. Configure the advertised native session grant and approved callback for each deployment.
+2 -2
View File
@@ -2,7 +2,7 @@
| Symptom | Check |
| --- | --- |
| Companion cannot connect to service | Confirm the MSI is installed, `QqqPrintAgent` is running, and the companion is elevated. A development CLI worker does not host the installed service pipe. |
| Companion cannot connect to service | Confirm the MSI is installed, `QqqPrintAgent` is running, and the companion is elevated. The command-line tool is only a client of that pipe; it does not host it. |
| Sign-in or discovery fails | Open **View logs**: every step (discovery, authentication metadata, native grant validation, provider discovery, browser callback, session verification by the service, device binding, identity check) is logged with the reason it stopped, and the dialog shows the same reason. Turn on **Debug logging** in Log settings for request routes, status codes, timings and realtime frames. |
| Sign-in works in the companion but "Service authorization not completed" | The service verifies the session itself as LocalSystem. A self-signed or private-authority certificate (for example a local Caddy root) that your user account trusts is not in the machine store, so the service's TLS check fails; the log shows `TLS certificate for host rejected: RemoteCertificateChainErrors`. Install the issuing root in **Local Machine → Trusted Root Certification Authorities**, or enter the server address and enable **Allow untrusted server certificate for this server** in Connection settings for a development server (the exception is bound to that one server). |
| Enrollment fails | Complete standard QQQ sign-in, then check the server URL, fresh/unconsumed code, device/facility configuration and server logs. Remote endpoints require HTTPS. The log records each enrollment step and the server's answer. |
@@ -17,7 +17,7 @@
| PDF clipped or wrong size | Select actual size versus fit deliberately. Match the machine default, advertised media profile or explicit per-job PDF dimensions to the loaded stock; see [Printer media](PRINTER-MEDIA.md). |
| Zebra prints text or blank labels | Confirm ZPL-capable hardware/driver, DPI, stock dimensions and actual printer mode. Inspect the specific document; previously confirmed output does not qualify every format/driver combination. |
| Protected configuration cannot be opened | It belongs to another Windows identity, or the service account changed. Re-enroll through the service after resolving old jobs; do not copy a user-enrolled DPAPI file. |
| Another worker owns the directory | Stop the duplicate CLI worker. Only one worker may own a given journal/data directory. |
| Another worker owns the directory | A second copy of the service host (for example a development build started by hand) holds `worker.lock`. Stop it. Only one service may own a given journal/data directory. |
| MSI publisher warning | Stable 1.0.1 is signed. Verify the exact official release checksum and Authenticode signature as described in [Installation](INSTALLATION.md). Earlier prereleases may be unsigned. |
## ZPL prints but PDF does not
+1 -1
View File
@@ -20,7 +20,7 @@ A baseline audit on 2026-11-10 measured merged line coverage of 87% for Core, 69
**The management pipe gets a versioned contract.** Requests name the server they address, replies are typed instead of matched by text prefix, and a client or service that does not understand the other's version says so.
**Coverage is gated.** `build/Verify.ps1` fails when an assembly falls below its minimum in `build/minimum-coverage.json`. Each minimum is the measured percentage rounded down to a whole number, less one point: a few lines in timing-dependent waits are reached on some runs and not others (five lines of the Windows layer moved between two runs of the same commit), and a minimum set at the measured value would fail at random. Minimums only move up, by the same rule, in the change that adds the tests. The release bar is 100% for Core, the view-model assembly and the CLI, and 90% for the Windows layer, where the remainder is native printing, installer and service-control code behind thin adapters marked `[ExcludeFromCodeCoverage]` with a written reason. The 90% figure deviates from K22-TEST-10; an exception record for it is to be proposed to the standards register and is not yet filed. K22-TEST-10 also asks for 80% coverage of changed lines; nothing measures that yet, and it is open work for this release.
**Coverage is gated.** `build/Verify.ps1` fails when an assembly falls below its minimum in `build/minimum-coverage.json`. Each minimum is the measured percentage rounded down to a whole number, less one point: a few lines in timing-dependent waits are reached on some runs and not others (five lines of the Windows layer moved between two runs of the same commit), and a minimum set at the measured value would fail at random. Minimums only move up, by the same rule, in the change that adds the tests. An assembly that has reached its release bar is recorded at the bar, not a point under it: the command line is at 100, where every line is reached by tests that do not depend on timing, and a point of slack would only hide a regression. The release bar is 100% for Core, the view-model assembly and the CLI, and 90% for the Windows layer, where the remainder is native printing, installer and service-control code behind thin adapters marked `[ExcludeFromCodeCoverage]` with a written reason. The 90% figure deviates from K22-TEST-10; an exception record for it is to be proposed to the standards register and is not yet filed. K22-TEST-10 also asks for 80% coverage of changed lines; nothing measures that yet, and it is open work for this release.
**Test doubles are hand-written fakes at boundaries.** No mocking library is added. The polling path that only tests reach is removed once its tests run against the realtime path.
+2 -2
View File
@@ -8,9 +8,9 @@ The signed 1.0.1 release uses the realtime and native-authentication boundaries
The remote-control adapter accepts only inventory refresh and cancellation of one locally journaled spooler job. Desired pause/disconnect state is revisioned and persists by canonical server URL and device identity; older or conflicting revisions cannot resume a device. An independently processed authenticated WSS channel carries controls and receipts while documents stream over separate same-origin HTTPS requests. There is no job/control polling fallback. A paused device claims no new work. A disconnected device retains control traffic and in-flight receipts; already-submitted printing is not recalled. Reconnect is a transport refresh, never an OS or service restart. See [the realtime contract and operational limits](../REALTIME.md).
The native QQQ session adapter requires discovery before credentials and never treats a native control 404 as legacy permission. After support is negotiated, 404 does not remove restrictions. Authorization denial becomes authorization-required, without inferring that every 401/403 proves revocation. New claims wait for an authenticated, bound QQQ user and valid control state. Existing installations without a protected QQQ session wait for explicit sign-in; device proof alone cannot authorize normal service printing. Explicit isolated CLI diagnostics may use the compatibility bearer adapter with `--legacy-compat`; it is not a fallback from native authentication.
The native QQQ session adapter requires discovery before credentials and never treats a native control 404 as legacy permission. After support is negotiated, 404 does not remove restrictions. Authorization denial becomes authorization-required, without inferring that every 401/403 proves revocation. New claims wait for an authenticated, bound QQQ user and valid control state. Existing installations without a protected QQQ session wait for explicit sign-in; device proof alone cannot authorize normal service printing. The command line has no server transport: the `--legacy-compat` bearer diagnostics were removed in 2.0, so no path the shipped programs can reach sends the device token outside a native session (the bearer constructor that mode used still ships in Core until it is deleted), and the command line keeps no credentials or journal of its own.
The service stores only the QQQ session cookie and stable authoritative identity under service-identity DPAPI, and periodically resumes the standard session. Passwords stay in the companion; provider refresh/access tokens remain server-side. Normal CLI operations use the existing authenticated service pipe. The private browser callback is fixed and MSI-owned, forwarding bounded data only into an active same-user/session companion inbox after executable verification. It carries a short-lived authorization code, never a session cookie or PKCE verifier. Core validates exact advertised redirect, random state, PKCE and single-use expiry; when the server advertises `nonceValidation: REQUIRED` it also sends only that attempt's own authorization nonce as `expectedNonce` (never a callback-supplied or regenerated value) and refuses any other non-empty nonce policy; no callback creates an authentication attempt. Provider registration, installed callback delivery and long-duration renewal remain deployment qualifications.
The service stores only the QQQ session cookie and stable authoritative identity under service-identity DPAPI, and periodically resumes the standard session. Passwords stay in the companion; provider refresh/access tokens remain server-side. CLI operations use the existing authenticated service pipe. The enrollment code reaches the CLI only through an environment variable or standard input, never as an argument, and the CLI prints it nowhere. Typed at a Windows console it is read without echo; redirected input is read as a line, and that includes a terminal that hands native programs a pipe instead of a console (the default Git Bash window, for example), where the terminal itself may echo what is typed and the variable should be used instead. An unattended caller with a console nobody types at must set the variable or redirect input, or the command waits. A command line the CLI refuses is never echoed, because it can carry a misplaced enrollment code or a sign-in callback address. The private browser callback is fixed and MSI-owned, forwarding bounded data only into an active same-user/session companion inbox after executable verification. It carries a short-lived authorization code, never a session cookie or PKCE verifier. Core validates exact advertised redirect, random state, PKCE and single-use expiry; when the server advertises `nonceValidation: REQUIRED` it also sends only that attempt's own authorization nonce as `expectedNonce` (never a callback-supplied or regenerated value) and refuses any other non-empty nonce policy; no callback creates an authentication attempt. Provider registration, installed callback delivery and long-duration renewal remain deployment qualifications.
Sign-out also ends the identity provider's browser session. The companion sends only the fixed registered callback with `sign-out`; the service refuses any other value, asks QQQ to log out with `nativeLogout.postLogoutRedirectUri`, and returns the provider end-session request to the companion over the administrator-only pipe. That request carries the provider's ID token hint (sensitive, bounded to 32 KiB, no whitespace or control characters), so it is never logged, the record prints redacted, and only the provider host is logged. Core refuses the data unless the issuer equals the one QQQ advertises, the end-session endpoint is HTTPS on the issuer's origin and identical to the provider's own discovery, and the callback is the one requested. The browser return is accepted only on the exact callback with the state this sign-out generated. Browser sign-in also sends `max_age=0` beside `prompt=login`.
+305
View File
@@ -0,0 +1,305 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using System.Text;
using Qqq.PrintAgent.Windows;
namespace Qqq.PrintAgent.Cli;
/// <summary>
/// Everything qqq-print-agent.exe decides: which role an argument list selects, which request an operator command becomes,
/// what is printed where, and the exit code a script sees. The command line holds no state of its own and never talks to a
/// QQQ server: an operator command is one request to the installed service over its administrator pipe, because the service
/// owns the sign-in, the pairing and all printing. The outside world is reached only through the host, so tests run this
/// class against fakes.
/// </summary>
internal sealed class CommandLine(CommandLineHost host)
{
/// <summary>The environment variable that supplies the one-time enrollment code to a script.</summary>
internal const string EnrollmentCodeVariable = "QQQ_PRINT_ENROLLMENT_CODE";
/// <summary>
/// The help text: printed on standard output when asked for, and on standard error after a refused command line. Its
/// line ends are made the platform's here, because the literal carries whatever this source file was checked out
/// with and a console or a captured file should not get a mixture.
/// </summary>
internal static readonly string Usage = """
Usage: qqq-print-agent <command>
Commands:
printers List the printers the service can see, as JSON.
enroll --server URL Pair this computer with a QQQ server using a one-time enrollment code.
expose --printer ID --exposed true|false Share a printer with QQQ, or stop sharing it.
run Ask the service to refresh its connection to QQQ.
sign-out End the service's QQQ session.
service-status Show the service's connection status.
snapshot Show the service's state as JSON: connection, printers, recent jobs and logs.
help Show this text (also --help or -h, alone or after a command).
Every command is carried out by the installed print service, which owns the sign-in, the pairing and all printing.
Run from an administrator prompt, and sign in through the companion app first.
The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or else from standard input:
at a Windows console it is prompted for and not shown; redirected input is read as one line, without a prompt.
An unattended caller must set the variable or redirect input, or the prompt waits for a key.
The code is never accepted on the command line.
Exit code: 0 on success; 1 when the arguments are wrong, the service cannot be reached or the service reports an error.
""".ReplaceLineEndings();
/// <summary>Each operator command, with the pipe operation it becomes and the options it requires. Every listed option is mandatory, and nothing else is accepted.</summary>
private static readonly Dictionary<string, (string Operation, string[] Options)> s_commands = new(StringComparer.Ordinal)
{
["printers"] = ("printers", []),
["enroll"] = ("enroll", ["--server"]),
["expose"] = ("set-exposure", ["--printer", "--exposed"]),
["run"] = ("reconnect", []),
["sign-out"] = ("sign-out", []),
["service-status"] = ("status", []),
["snapshot"] = ("snapshot", []),
};
/// <summary>What a command line is told when it uses an option of the legacy mode that 2.0 removed, so a script written for 1.x learns why it fails.</summary>
internal const string RemovedOptionsReason = "The options --service, --legacy-compat, --data-dir and --once were removed in 2.0: the command line only manages the installed service.";
/// <summary>The options of the removed legacy mode. They are recognized only to explain the refusal.</summary>
private static readonly HashSet<string> s_removedOptions = new(StringComparer.Ordinal) { "--service", "--legacy-compat", "--data-dir", "--once" };
/// <summary>The names of the operator commands, exposed so a test can hold the help text to the commands that really exist.</summary>
internal static IReadOnlyCollection<string> CommandNames => s_commands.Keys;
/// <summary>
/// Runs one invocation and returns the process exit code. Two argument shapes are internal and fixed: the MSI update
/// helper and the browser sign-in callback forwarder, each started by another part of the product with exactly these
/// arguments. Everything else is an operator command. This executable is not a printer worker: the service starts its
/// own executable for that. A failure becomes one line on standard error and exit code 1; a timeout or cancellation
/// does too, so a script never mistakes an operation that did not finish for one that succeeded.
/// </summary>
internal async Task<int> RunAsync(string[] args)
{
try
{
return args switch
{
["--apply-update", string request] => await host.ApplyUpdateAsync(request),
["--auth-callback", string callback] => await ForwardSignInCallbackAsync(callback),
_ => await ManageServiceAsync(args),
};
}
catch(OperationCanceledException)
{
host.Error.WriteLine("The operation timed out or was canceled before completion.");
return 1;
}
catch(Exception exception)
{
host.Error.WriteLine(exception.Message);
return 1;
}
}
/// <summary>Hands the browser's callback address to the companion that is waiting for it. Success is exit code 0; a refusal is thrown and reported by the caller.</summary>
private async Task<int> ForwardSignInCallbackAsync(string callback)
{
await host.ForwardSignInCallbackAsync(callback, CancellationToken.None);
return 0;
}
/// <summary>
/// Carries out an operator command: help is printed here, and any other command is checked against the table, turned into
/// one pipe request and sent to the service. The reply is printed on standard output as the service wrote it, also when
/// it is a refusal. A reply that starts with "Error:" is the service refusing or failing the request, so it exits 1
/// for every command.
/// </summary>
private async Task<int> ManageServiceAsync(string[] args)
{
if(AsksForHelp(args))
{
host.Output.WriteLine(Usage);
return 0;
}
Dictionary<string, string> options = new(StringComparer.Ordinal);
string? problem = FindProblem(args, options);
if(problem is not null)
{
return RefuseArguments(problem);
}
////////////////////////////////////////////////////////////////////////////
// the enrollment code is asked for last, once the command line is known //
// to be valid, so a mistyped command never prompts for a single-use code //
////////////////////////////////////////////////////////////////////////////
PipeRequest request = new(s_commands[args[0]].Operation, options.GetValueOrDefault("--server"), args[0] is "enroll" ? ReadEnrollmentCode() : null,
options.GetValueOrDefault("--printer"), options.TryGetValue("--exposed", out string? choice) ? IsWord(choice, "true") : null);
string response = await host.SendAsync(request);
host.Output.WriteLine(response);
bool failed = response.StartsWith("Error:", StringComparison.Ordinal);
if(args[0] is "sign-out" && !failed)
{
host.Output.WriteLine("The identity provider's browser session is not ended from the command line; use Sign out in the QQQ Print Agent app to end it too.");
}
return failed ? 1 : 0;
}
/// <summary>
/// Says whether the command line is a request for help: no arguments, a help word in first place whatever follows
/// ("help enroll" is a person asking how to enroll), or a help flag in last place after a real command
/// ("printers --help"). Answering costs nothing and sends nothing.
/// </summary>
private static bool AsksForHelp(string[] args)
=> args is [] or ["help" or "--help" or "-h", ..] || (s_commands.ContainsKey(args[0]) && args[^1] is "--help" or "-h");
/// <summary>
/// Refuses a command line: the reason and the help text go to standard error and the exit code is 1. The reason never
/// repeats what was typed. A refused command line can hold a secret in the wrong place (an enrollment code given as an
/// argument, a sign-in callback address), and standard error is routinely captured into logs.
/// </summary>
private int RefuseArguments(string reason)
{
host.Error.WriteLine(reason);
host.Error.WriteLine(Usage);
return 1;
}
/// <summary>
/// Checks the command line and reads the "--name value" pairs that follow the command, in any order, into the given
/// dictionary. It returns null when the command line is acceptable, and otherwise the reason it is not, which the
/// caller refuses with rather than guess what was meant. Every option of a command is required exactly once, with a
/// value that is not blank and is not itself an option name, so a forgotten value cannot swallow the next option.
/// Each reason is assembled only from this class's own command and option names, never from an argument that did not
/// match one of them, so it cannot repeat a secret that was typed in the wrong place.
/// </summary>
private static string? FindProblem(string[] args, Dictionary<string, string> options)
{
if(args.Any(s_removedOptions.Contains))
{
return RemovedOptionsReason;
}
if(!s_commands.TryGetValue(args[0], out (string Operation, string[] Options) command))
{
return "Unknown command.";
}
for(int index = 1; index < args.Length; index += 2)
{
string name = args[index];
if(!command.Options.Contains(name, StringComparer.Ordinal))
{
return command.Options.Length == 0 ? $"'{args[0]}' takes no arguments." : $"'{args[0]}' accepts only {string.Join(" and ", command.Options)}.";
}
if(options.ContainsKey(name))
{
return $"{name} may be given only once.";
}
if(index + 1 == args.Length || string.IsNullOrWhiteSpace(args[index + 1]) || args[index + 1].StartsWith("--", StringComparison.Ordinal))
{
return $"{name} needs a value.";
}
options[name] = args[index + 1];
}
string? missing = command.Options.FirstOrDefault(option => !options.ContainsKey(option));
if(missing is not null)
{
return $"{missing} is required.";
}
return options.TryGetValue("--exposed", out string? choice) && !IsWord(choice, "true") && !IsWord(choice, "false") ? "--exposed must be true or false." : null;
}
/// <summary>Compares an option value with a fixed word, ignoring letter case and nothing else: "TRUE" is true, " true" is not.</summary>
private static bool IsWord(string text, string word) => string.Equals(text, word, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Reads the one-time enrollment code from the environment, or else from standard input, so the code never appears in
/// the command line or shell history. It is passed to the service and nowhere else: this class never prints it. With
/// the variable or redirected input nothing is written, so standard error stays empty unless something fails.
/// What a shell adds around the code is dropped whichever way it arrives, and a source that holds nothing else counts
/// as holding no code.
/// </summary>
private string ReadEnrollmentCode()
{
string code = WithoutShellAdditions(host.ReadEnvironmentVariable(EnrollmentCodeVariable));
if(code.Length == 0)
{
//////////////////////////////////////////////////////////////////////////////
// redirected input is read silently. a prompt would be the only thing on //
// standard error in a successful scripted enrollment. when a script //
// redirects or captures standard error (2>&1, 2>file, the ISE, remoting), //
// Windows PowerShell turns each line a native program writes there into an //
// error record, which with ErrorActionPreference Stop ends the script //
// after the single-use code has already been spent //
//////////////////////////////////////////////////////////////////////////////
code = WithoutShellAdditions(host.IsInputRedirected() ? host.ReadLine() : PromptWithoutEcho());
}
return code.Length > 0 ? code : throw new InvalidOperationException("Enrollment code is required.");
}
/// <summary>
/// Drops what a shell can put around a code that never has any of it: surrounding white space (cmd's "echo CODE | ..."
/// pipes a trailing space) and a leading byte-order mark (Windows PowerShell 5.1 puts one in front of piped text when
/// the console code page is UTF-8). The mark is not white space, so it is removed between two trims; left in, the
/// code would pass the blank check and the server would reject it as unknown. Nothing at all returns an empty string.
/// </summary>
private static string WithoutShellAdditions(string? text) => (text ?? "").Trim().TrimStart('\uFEFF').Trim();
/// <summary>
/// Prompts at the console and reads one line key by key without showing it, so a typed code is not left on the screen
/// or in a terminal recording. The prompt goes to standard error, so it appears even when standard output is captured.
/// Enter ends the line, and so does a key that carries a carriage return or line feed without being the Enter key
/// (Ctrl+M, or a line end pasted by a terminal). Backspace removes the last character typed, and keys that produce no
/// printable character (arrows, function keys) are ignored. The line end that ended the read was not shown either, so
/// the prompt line is ended here, also when reading fails, before anything else is written.
/// </summary>
private string PromptWithoutEcho()
{
host.Error.Write("Enrollment code: ");
try
{
StringBuilder typed = new();
for(ConsoleKeyInfo key = host.ReadKey(true); key.Key != ConsoleKey.Enter && key.KeyChar is not ('\r' or '\n'); key = host.ReadKey(true))
{
if(key.Key == ConsoleKey.Backspace)
{
typed.Length = Math.Max(0, typed.Length - 1);
}
else if(!char.IsControl(key.KeyChar))
{
typed.Append(key.KeyChar);
}
}
return typed.ToString();
}
finally
{
host.Error.WriteLine();
}
}
}
+32
View File
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using Qqq.PrintAgent.Windows;
namespace Qqq.PrintAgent.Cli;
/// <summary>
/// Everything outside the process that the command line touches, each as a replaceable function, so <see cref="CommandLine"/>
/// runs in a test without the real console, the installed service or its pipe. <see cref="Program"/> supplies the real ones.
/// </summary>
/// <param name="Output">Standard output: service replies, and usage that was asked for.</param>
/// <param name="Error">Standard error: failures, usage shown because the arguments were wrong, and the enrollment prompt when the code is typed at a console. A command that succeeds without that prompt writes nothing here.</param>
/// <param name="ReadEnvironmentVariable">Reads one environment variable; the enrollment code arrives this way so it stays out of the command line and shell history.</param>
/// <param name="IsInputRedirected">Says whether standard input is a file or a pipe instead of a console, which decides how the enrollment code is read and whether it is prompted for.</param>
/// <param name="ReadLine">Reads one line of redirected standard input, for an enrollment code that is piped in; null at end of input.</param>
/// <param name="ReadKey">Reads one key from the console, for an enrollment code that is typed; the argument says whether to keep the key off the screen.</param>
/// <param name="SendAsync">Sends one request to the installed service over its administrator pipe and returns the reply text.</param>
/// <param name="ApplyUpdateAsync">Applies the prepared MSI update named by a request file and returns the exit code.</param>
/// <param name="ForwardSignInCallbackAsync">Forwards a browser sign-in callback address to the running companion.</param>
internal sealed record CommandLineHost(
TextWriter Output,
TextWriter Error,
Func<string, string?> ReadEnvironmentVariable,
Func<bool> IsInputRedirected,
Func<string?> ReadLine,
Func<bool, ConsoleKeyInfo> ReadKey,
Func<PipeRequest, Task<string>> SendAsync,
Func<string, Task<int>> ApplyUpdateAsync,
Func<string, CancellationToken, Task> ForwardSignInCallbackAsync);
+11 -261
View File
@@ -3,276 +3,26 @@
* SPDX-License-Identifier: MIT
*/
using System.Text.Json;
using Qqq.PrintAgent.Core.Printing;
using Qqq.PrintAgent.Windows;
namespace Qqq.PrintAgent.Cli;
/// <summary>Scriptable setup, printer selection and foreground diagnostics.</summary>
/// <summary>
/// Process entry point of qqq-print-agent.exe. It decides nothing: it hands the real console, environment, service pipe and
/// helper entry points to <see cref="CommandLine"/>, which holds every decision and is tested against fakes.
/// </summary>
public static class Program
{
/// <summary>
/// Entry point. Three argument shapes are internal and fixed: the isolated printer worker (a child process the service
/// starts for each native printer call), the MSI update helper, and the browser sign-in callback forwarder. Everything
/// else is an operator command.
/// Binds the outside world and runs the arguments. Each boundary is passed as a method reference, not a wrapper, so there
/// is no code here that a test cannot reach: asking for help exercises this whole composition without touching the service.
/// </summary>
public static Task<int> Main(string[] args) => args switch
{
["--printer-worker"] => PrinterWorkerHost.RunAsync(),
["--apply-update", string request] => ExecuteAsync(() => MsiUpdateInstaller.ApplyAsync(request)),
["--auth-callback", string callback] => ExecuteAsync(async () =>
{
await QqqBrowserCallback.ForwardFromHandlerAsync(callback);
return 0;
}),
_ => ExecuteAsync(() => DispatchAsync(args)),
};
public static Task<int> Main(string[] args)
=> new CommandLine(new CommandLineHost(Console.Out, Console.Error, Environment.GetEnvironmentVariable, IsInputRedirected, Console.ReadLine, Console.ReadKey,
AgentPipeClient.SendAsync, MsiUpdateInstaller.ApplyAsync, QqqBrowserCallback.ForwardFromHandlerAsync)).RunAsync(args);
/// <summary>
/// Runs a command and turns failures into a one-line message on standard error and exit code 1. A timeout or cancellation
/// also exits 1, so a script never mistakes an operation that did not finish for one that succeeded.
/// </summary>
internal static async Task<int> ExecuteAsync(Func<Task<int>> command)
{
try
{
return await command();
}
catch(OperationCanceledException)
{
Console.Error.WriteLine("The operation timed out or was canceled before completion.");
return 1;
}
catch(Exception exception) { Console.Error.WriteLine(exception.Message); return 1; }
}
/// <summary>
/// Routes an operator command. Without the explicit legacy flag, printing commands go to the installed service over its
/// authenticated pipe, because the service owns the signed-in session; only with the flag do they use a separate
/// per-user data directory and the old device-token transport, and that is announced on every run.
/// </summary>
internal static async Task<int> DispatchAsync(string[] args, Func<PipeRequest, Task<string>>? serviceCommand = null)
{
string command = args.FirstOrDefault() ?? "help";
bool legacy = UseLegacyCompatibility(args);
if(legacy)
{
Console.Error.WriteLine("Explicit legacy compatibility diagnostics: private device bearer transport, separate local state. This is not QQQ user sign-in.");
}
if(!legacy && command is "printers" or "enroll" or "expose" or "run" or "sign-out")
{
return await DispatchServiceAsync(args, serviceCommand ?? AgentPipeClient.SendAsync);
}
string directory = ResolveDataDirectory(args);
switch(command)
{
case "printers":
Console.WriteLine(JsonSerializer.Serialize(CreatePrinterBackend().Discover(), PrintApiClient.JsonOptions));
return 0;
case "service-status":
case "snapshot":
Console.WriteLine(await AgentPipeClient.SendAsync(new PipeRequest(command is "snapshot" ? "snapshot" : "status")));
return 0;
case "enroll":
return await EnrollAsync(args, directory);
case "expose":
return await SetExposureAsync(args, directory);
case "run":
return await RunAsync(args, directory);
default:
Console.WriteLine("printers | enroll --server URL | expose --printer ID --exposed true|false | run | sign-out | service-status | snapshot\nNormal commands use the authenticated installed service. Sign in through the companion first. run requests a connection refresh; the Windows service owns unattended printing.\nExplicit isolated legacy diagnostics only: add --legacy-compat and a separate --data-dir; legacy run accepts --once. Enrollment code is read from QQQ_PRINT_ENROLLMENT_CODE or an interactive prompt.");
return command is "help" ? 0 : 1;
}
}
/// <summary>Reports whether the legacy flag was given, and refuses it combined with --service, because legacy mode must never touch the installed service's state.</summary>
internal static bool UseLegacyCompatibility(string[] args)
{
bool legacy = args.Contains("--legacy-compat", StringComparer.Ordinal);
if(legacy && args.Contains("--service", StringComparer.Ordinal))
{
throw new ArgumentException("Legacy compatibility cannot access the installed service's state.", nameof(args));
}
return legacy;
}
/// <summary>
/// Sends a normal command to the installed service and prints its reply, exiting 1 when the reply is an error. Options
/// that only make sense for the isolated legacy mode (a data directory, run once) are refused here with an explanation,
/// so a script cannot silently run against the wrong state.
/// </summary>
private static async Task<int> DispatchServiceAsync(string[] args, Func<PipeRequest, Task<string>> send)
{
if(args.Contains("--data-dir", StringComparer.Ordinal) || args.Contains("--once", StringComparer.Ordinal))
{
throw new ArgumentException("Foreground diagnostic options require explicit --legacy-compat. Normal printing is owned by the signed-in Windows service.", nameof(args));
}
PipeRequest request = args[0] switch
{
"run" => new("reconnect"),
"enroll" => new("enroll", Option(args, "--server") ?? throw new ArgumentException("--server is required.", nameof(args)), ReadEnrollmentCode()),
"expose" => new("set-exposure", PrinterId: Option(args, "--printer") ?? throw new ArgumentException("--printer is required.", nameof(args)),
Exposed: bool.TryParse(Option(args, "--exposed"), out bool exposed) ? exposed : throw new ArgumentException("--exposed must be true or false.", nameof(args))),
_ => new(args[0]),
};
string response = await send(request);
Console.WriteLine(response);
if(args[0] is "sign-out" && !response.StartsWith("Error:", StringComparison.Ordinal))
{
Console.WriteLine("The identity provider's browser session is not ended from the command line; use Sign out in the QQQ Print Agent app to end it too.");
}
return response.StartsWith("Error:", StringComparison.Ordinal) ? 1 : 0;
}
/// <summary>Reads the one-time enrollment code from the environment, or prompts for it, so the code never appears in the command line or shell history.</summary>
private static string ReadEnrollmentCode()
{
string? code = Environment.GetEnvironmentVariable("QQQ_PRINT_ENROLLMENT_CODE");
if(string.IsNullOrWhiteSpace(code))
{
Console.Write("Enrollment code: ");
code = Console.ReadLine();
}
return !string.IsNullOrWhiteSpace(code) ? code : throw new InvalidOperationException("Enrollment code is required.");
}
/// <summary>Returns the value following a named option, or null when the option is absent or has no value.</summary>
private static string? Option(string[] args, string key)
{
int index = Array.IndexOf(args, key);
return index >= 0 && index + 1 < args.Length ? args[index + 1] : null;
}
/// <summary>
/// Chooses the data directory. --service selects the installed machine directory; otherwise a per-user directory is used,
/// and the machine directory is refused there, so a foreground command can never overwrite the service's credentials by accident.
/// </summary>
internal static string ResolveDataDirectory(string[] args)
{
if(args.Contains("--service", StringComparer.Ordinal))
{
return AgentStore.DefaultDirectory;
}
string directory = Path.GetFullPath(Option(args, "--data-dir") ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QqqPrintAgent"));
if(string.Equals(Path.TrimEndingDirectorySeparator(directory), Path.TrimEndingDirectorySeparator(AgentStore.DefaultDirectory), StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Use --service to manage the installed service. Foreground commands require a separate per-user data directory.");
}
return directory;
}
/// <summary>Takes the exclusive lock on a data directory so two foreground commands (or one beside the service) cannot write the same journal at once.</summary>
internal static FileStream AcquireWorkerLock(string directory)
{
Directory.CreateDirectory(directory);
return new FileStream(Path.Combine(directory, "worker.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
/// <summary>Creates the isolated printer backend that runs each native call in a child copy of this executable, bounding any blocking driver call.</summary>
private static IsolatedPrinterBackend CreatePrinterBackend() => new(Environment.ProcessPath ?? throw new InvalidOperationException("Cannot locate the printer helper executable."));
/// <summary>
/// Runs one legacy diagnostic claim pass. Continuous legacy polling is gone, so only --once is accepted. Ctrl+C ends the
/// pass cleanly (exit 0); any other cancellation is a failure. It uses a separate data directory and the device token.
/// </summary>
private static async Task<int> RunAsync(string[] args, string directory)
{
if(!args.Contains("--once", StringComparer.Ordinal))
{
throw new InvalidOperationException("Continuous legacy polling is no longer supported. Sign in to the installed native-session service for realtime printing. --once is a legacy diagnostic only.");
}
using FileStream instance = AcquireWorkerLock(directory);
using AgentStore journal = new(directory);
AgentConfiguration config = journal.LoadConfiguration() ?? throw new InvalidOperationException("Enroll this account first.");
using PrintApiClient client = new(config.ServerUrl, config.DeviceToken);
ExposedPrinterBackend printers = new(CreatePrinterBackend(), journal.GetExposedPrinterIds);
PrintWorker worker = new(client, printers, journal, Console.WriteLine);
using CancellationTokenSource stopping = new();
ConsoleCancelEventHandler cancelHandler = (_, e) => { e.Cancel = true; stopping.Cancel(); };
Console.CancelKeyPress += cancelHandler;
try
{ await worker.RunOnceAsync(stopping.Token); }
catch(OperationCanceledException) when(stopping.IsCancellationRequested) { return 0; }
finally { Console.CancelKeyPress -= cancelHandler; }
return 0;
}
/// <summary>Shares or hides one printer, through the service when --service is given and otherwise in the separate legacy directory after validating against current discovery.</summary>
private static async Task<int> SetExposureAsync(string[] args, string directory)
{
string id = Option(args, "--printer") ?? throw new ArgumentException("--printer is required.", nameof(args));
if(!bool.TryParse(Option(args, "--exposed"), out bool exposed))
{
throw new ArgumentException("--exposed must be true or false.", nameof(args));
}
if(args.Contains("--service", StringComparer.Ordinal))
{
string response = await AgentPipeClient.SendAsync(new PipeRequest("set-exposure", PrinterId: id, Exposed: exposed));
Console.WriteLine(response);
return response.StartsWith("Error:", StringComparison.Ordinal) ? 1 : 0;
}
using FileStream instance = AcquireWorkerLock(directory);
using AgentStore store = new(directory);
store.SetExposure(id, exposed, CreatePrinterBackend().Discover());
Console.WriteLine(exposed ? "Printer exposed to QQQ." : "Printer hidden from QQQ.");
return 0;
}
/// <summary>
/// Enrolls this computer with a one-time code read from the environment or a prompt, never from the command line. With
/// --service the installed service does it; otherwise the legacy path enrolls into a separate directory and saves the
/// device connection protected for the current user.
/// </summary>
private static async Task<int> EnrollAsync(string[] args, string directory)
{
string server = Option(args, "--server") ?? throw new ArgumentException("--server is required.", nameof(args));
string? code = Environment.GetEnvironmentVariable("QQQ_PRINT_ENROLLMENT_CODE");
if(string.IsNullOrWhiteSpace(code))
{
Console.Write("Enrollment code: ");
code = Console.ReadLine();
}
if(string.IsNullOrWhiteSpace(code))
{
throw new InvalidOperationException("Enrollment code is required.");
}
if(args.Contains("--service", StringComparer.Ordinal))
{
string response = await AgentPipeClient.SendAsync(new PipeRequest("enroll", server, code));
Console.WriteLine(response);
return response.StartsWith("Error:", StringComparison.Ordinal) ? 1 : 0;
}
using FileStream instance = AcquireWorkerLock(directory);
using AgentStore store = new(directory, recoverUnreadableConfiguration: true);
using PrintApiClient api = new(server);
EnrollmentResponse result = await api.EnrollAsync(new EnrollmentRequest(code, Environment.MachineName, "0.1.0"));
store.SaveConfiguration(new AgentConfiguration(server, result.DeviceId, result.DeviceToken, result.PollIntervalSeconds));
Console.WriteLine($"Enrolled device {result.DeviceId}.");
return 0;
}
/// <summary>Says whether standard input is a file or a pipe instead of a console. It exists only because a property cannot be passed as a method reference.</summary>
internal static bool IsInputRedirected() => Console.IsInputRedirected;
}
@@ -5,9 +5,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- The scriptable head over the same Core as the window. Ships as a self-contained
single-file exe named after the app id (qqq-print-agent.exe), so the coverage package
name is the assembly name, not the project name. -->
<!-- The command-line client of the installed service. It reaches the service through the
Windows layer's pipe client and holds no protocol or printing logic of its own, so it
references only that layer. The executable is named after the app id
(qqq-print-agent.exe), so the coverage package name is the assembly name, not the
project name. The installer publishes it self-contained for win-x64. -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
@@ -18,20 +20,11 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Qqq.PrintAgent.Core\Qqq.PrintAgent.Core.csproj" />
<ProjectReference Include="..\Qqq.PrintAgent.Windows\Qqq.PrintAgent.Windows.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Qqq.PrintAgent.Cli.Tests" />
</ItemGroup>
<ItemGroup>
<!-- The app's own namespaces are global usings: their sort position against other
usings depends on the app's name, which the template replaces. -->
<Using Include="Qqq.PrintAgent.Core" />
</ItemGroup>
<ItemGroup><ProjectReference Include="../Qqq.PrintAgent.Windows/Qqq.PrintAgent.Windows.csproj" /></ItemGroup></Project>
</Project>
@@ -0,0 +1,199 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
namespace Qqq.PrintAgent.Cli.Tests;
/// <summary>
/// Malformed command lines. A command accepts exactly its own options, each once and each with a value, and nothing else.
/// Anything different is refused before the service is contacted and before the enrollment code is asked for: one line
/// that says what is wrong, then the usage, on standard error; nothing on standard output; exit code 1. The reason names
/// only the tool's own commands and options, never what was typed, and the tool never guesses what was meant.
/// </summary>
public sealed class CliArgumentRefusalTests
{
private const string Server = "https://qqq.example.test";
private const string Printer = "synthetic-queue-1";
/// <summary>A command that takes no options says so when anything follows it.</summary>
[Theory]
[InlineData("printers", "extra")]
[InlineData("printers", "--server", Server)]
[InlineData("run", "now")]
[InlineData("sign-out", "now")]
[InlineData("service-status", "--verbose")]
[InlineData("snapshot", "")]
[InlineData("snapshot", "--help", "extra")]
public async Task CommandWithoutOptions_RefusesAnythingAfterIt(params string[] args)
{
await AssertRefusedAsync($"'{args[0]}' takes no arguments.", args);
}
/// <summary>An argument in an option's place that is not one of the command's options is refused with the options the command does accept: a positional value, a misspelled or differently cased option, another command's option, or a trailing word.</summary>
[Theory]
[InlineData("'enroll' accepts only --server.", "enroll", Server)]
[InlineData("'enroll' accepts only --server.", "enroll", Server, "--server")]
[InlineData("'enroll' accepts only --server.", "enroll", "--Server", Server)]
[InlineData("'enroll' accepts only --server.", "enroll", "--printer", Printer)]
[InlineData("'enroll' accepts only --server.", "enroll", "--server", Server, "extra")]
[InlineData("'enroll' accepts only --server.", "enroll", "--code", "synthetic-code-4471", "--server", Server)]
[InlineData("'expose' accepts only --printer and --exposed.", "expose", Printer, "true")]
[InlineData("'expose' accepts only --printer and --exposed.", "expose", "--printer", Printer, "--server", Server)]
[InlineData("'expose' accepts only --printer and --exposed.", "expose", "--printer", Printer, "--exposed", "true", "extra")]
[InlineData("'expose' accepts only --printer and --exposed.", "expose", "--Exposed", "true", "--printer", Printer)]
public async Task UnexpectedArgument_IsRefusedWithTheOptionsTheCommandAccepts(string reason, params string[] args)
{
await AssertRefusedAsync(reason, args);
}
/// <summary>A required option that is absent is named.</summary>
[Theory]
[InlineData("--server is required.", "enroll")]
[InlineData("--printer is required.", "expose")]
[InlineData("--printer is required.", "expose", "--exposed", "true")]
[InlineData("--exposed is required.", "expose", "--printer", Printer)]
public async Task MissingOption_IsNamed(string reason, params string[] args)
{
await AssertRefusedAsync(reason, args);
}
/// <summary>An option with nothing after it, with a blank value, or followed by another option name is refused as needing a value. An option name is never taken as a value, so a forgotten value cannot make the next option disappear into it.</summary>
[Theory]
[InlineData("--server needs a value.", "enroll", "--server")]
[InlineData("--server needs a value.", "enroll", "--server", "")]
[InlineData("--server needs a value.", "enroll", "--server", " ")]
[InlineData("--server needs a value.", "enroll", "--server", "--server")]
[InlineData("--server needs a value.", "enroll", "--server", "--anything")]
[InlineData("--printer needs a value.", "expose", "--printer", "--exposed", "true")]
[InlineData("--printer needs a value.", "expose", "--printer", "--exposed", "--exposed", "true")]
[InlineData("--printer needs a value.", "expose", "--printer", "", "--exposed", "true")]
[InlineData("--exposed needs a value.", "expose", "--printer", Printer, "--exposed")]
[InlineData("--exposed needs a value.", "expose", "--printer", Printer, "--exposed", " ")]
[InlineData("--exposed needs a value.", "expose", "--exposed", "--printer", Printer)]
public async Task OptionWithoutAValue_IsRefused(string reason, params string[] args)
{
await AssertRefusedAsync(reason, args);
}
/// <summary>An option given twice is refused, whether or not the two values agree; the tool does not pick one.</summary>
[Theory]
[InlineData("--server may be given only once.", "enroll", "--server", Server, "--server", "https://other.example.test")]
[InlineData("--server may be given only once.", "enroll", "--server", Server, "--server", Server)]
[InlineData("--printer may be given only once.", "expose", "--printer", Printer, "--printer", "synthetic-queue-2")]
[InlineData("--exposed may be given only once.", "expose", "--exposed", "true", "--exposed", "false", "--printer", Printer)]
public async Task RepeatedOption_IsRefused(string reason, params string[] args)
{
await AssertRefusedAsync(reason, args);
}
/// <summary>The choice must be the word true or false, in any letter case and with nothing around it. A number, yes or no, any other word, and true or false padded with white space are refused with a message that says so, wherever the option stands.</summary>
[Theory]
[InlineData("yes")]
[InlineData("no")]
[InlineData("1")]
[InlineData("0")]
[InlineData("on")]
[InlineData("truee")]
[InlineData(" true")]
[InlineData("true ")]
[InlineData("\tfalse")]
public async Task Expose_RefusesAChoiceThatIsNotTrueOrFalse(string choice)
{
await AssertRefusedAsync("--exposed must be true or false.", "expose", "--printer", Printer, "--exposed", choice);
await AssertRefusedAsync("--exposed must be true or false.", "expose", "--exposed", choice, "--printer", Printer);
}
/// <summary>Every option of the legacy mode removed in 2.0 is refused with one fixed sentence that names all four and says they are gone, wherever it appears and whatever else is on the command line, so a script written for 1.x learns why it no longer runs.</summary>
[Theory]
[InlineData("--legacy-compat")]
[InlineData("--service")]
[InlineData("--legacy-compat", "run", "--once")]
[InlineData("run", "--once")]
[InlineData("run", "--legacy-compat", "--once", "--data-dir", "C:\\synthetic")]
[InlineData("printers", "--data-dir", "C:\\synthetic")]
[InlineData("sign-out", "--service")]
[InlineData("service-status", "--service")]
[InlineData("enroll", "--service", "--server", Server)]
[InlineData("enroll", "--server", Server, "--legacy-compat")]
[InlineData("enroll", "--server", "--service")]
[InlineData("expose", "--printer", Printer, "--exposed", "true", "--service")]
[InlineData("unknown-word", "--once")]
public async Task RemovedLegacyOption_IsRefusedWithTheReasonItIsGone(params string[] args)
{
await AssertRefusedAsync("The options --service, --legacy-compat, --data-dir and --once were removed in 2.0: the command line only manages the installed service.", args);
}
/// <summary>A help flag in last place after a real command is a request for help, not a mistake: the usage goes to standard output, the exit code is 0, nothing is sent and no enrollment code is asked for, even when the rest of the command line would have been refused.</summary>
[Theory]
[InlineData("printers", "--help")]
[InlineData("printers", "-h")]
[InlineData("enroll", "--help")]
[InlineData("enroll", "--server", Server, "-h")]
[InlineData("enroll", "--server", "--help")]
[InlineData("expose", "--printer", Printer, "--exposed", "maybe", "--help")]
[InlineData("run", "--once", "--help")]
public async Task HelpFlagAfterACommand_PrintsTheUsageAndSucceeds(params string[] args)
{
using CliFixture cli = new();
cli.TypedLines.Enqueue("synthetic-code-4471");
int exitCode = await cli.RunAsync(args);
Assert.Equal(0, exitCode);
Assert.Equal(CommandLine.Usage.ReplaceLineEndings("\n") + "\n", cli.Output.ReplaceLineEndings("\n"));
Assert.Equal("", cli.Error);
Assert.Empty(cli.Sent);
Assert.Empty(cli.VariablesRead);
Assert.Equal(0, cli.LinesRead);
}
/// <summary>A help flag helps only in last place after a real command. After a word that is not a command it does not turn the refusal into a success, and in the middle of a command line it is an argument like any other.</summary>
[Theory]
[InlineData("Unknown command.", "unknown-word", "--help")]
[InlineData("Unknown command.", "--printer-worker", "-h")]
[InlineData("'printers' takes no arguments.", "printers", "--help", "extra")]
[InlineData("'enroll' accepts only --server.", "enroll", "-h", "--server", Server)]
public async Task HelpFlagElsewhere_DoesNotRescueABadCommandLine(string reason, params string[] args)
{
await AssertRefusedAsync(reason, args);
}
/// <summary>Runs the arguments against a command line whose enrollment code is available every way it could be asked for, and requires a complete refusal: exit code 1, the reason and the usage on standard error, nothing on standard output, nothing sent, and the environment, standard input and the console all left unread.</summary>
private static async Task AssertRefusedAsync(string reason, params string[] args)
{
using CliFixture cli = new();
cli.Variables[CommandLine.EnrollmentCodeVariable] = "synthetic-code-4471";
cli.TypedLines.Enqueue("synthetic-code-4471");
int exitCode = await cli.RunAsync(args);
Assert.Equal(1, exitCode);
Assert.Equal("", cli.Output);
Assert.Equal(reason + "\n" + CommandLine.Usage.ReplaceLineEndings("\n") + "\n", cli.Error.ReplaceLineEndings("\n"));
Assert.Empty(cli.Sent);
Assert.Empty(cli.VariablesRead);
Assert.Equal(0, cli.LinesRead);
Assert.Equal(0, cli.KeysRead);
}
}
@@ -0,0 +1,309 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using Qqq.PrintAgent.Windows;
namespace Qqq.PrintAgent.Cli.Tests;
/// <summary>
/// The one-time enrollment code is a secret. It comes from an environment variable or from standard input (piped in
/// without a prompt, or typed at a console prompt without being shown), never from the command line; it goes to the
/// service in the enrollment request and nowhere else; and nothing the tool prints ever contains it, whether the
/// enrollment works, is refused or cannot be sent.
/// </summary>
public sealed class CliEnrollmentCodeTests
{
private const string Code = "synthetic-code-4471";
private const string Server = "https://qqq.example.test";
private const string Prompt = "Enrollment code: \n";
/// <summary>With the variable set, the code is taken from QQQ_PRINT_ENROLLMENT_CODE: no prompt is written, no line and no key is read, so an unattended script never blocks.</summary>
[Fact]
public async Task CodeInTheEnvironment_IsUsedWithoutPrompting()
{
using CliFixture cli = new() { Reply = "Enrolled." };
cli.Variables["QQQ_PRINT_ENROLLMENT_CODE"] = Code;
int exitCode = await cli.RunAsync("enroll", "--server", Server);
Assert.Equal(0, exitCode);
Assert.Equal("QQQ_PRINT_ENROLLMENT_CODE", Assert.Single(cli.VariablesRead));
Assert.Equal(0, cli.LinesRead);
Assert.Equal(0, cli.KeysRead);
Assert.Equal(Code, Assert.Single(cli.Sent).EnrollmentCode);
Assert.Equal("Enrolled.\n", cli.Output);
Assert.Equal("", cli.Error);
}
/// <summary>With the variable missing or blank and standard input redirected, the code is the line that is piped in, read without a prompt: standard output holds the service's reply and nothing else, standard error stays empty, and no key is read from a console that is not there.</summary>
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task CodePipedIn_IsReadAsALineWithoutAPrompt(string? variable)
{
using CliFixture cli = new() { Reply = "Enrolled." };
cli.Variables["QQQ_PRINT_ENROLLMENT_CODE"] = variable;
cli.TypedLines.Enqueue(Code);
int exitCode = await cli.RunAsync("enroll", "--server", Server);
Assert.Equal(0, exitCode);
Assert.Equal(1, cli.LinesRead);
Assert.Equal(0, cli.KeysRead);
Assert.Equal(new PipeRequest("enroll", Server, Code), Assert.Single(cli.Sent));
Assert.Equal("Enrolled.\n", cli.Output);
Assert.Equal("", cli.Error);
}
/// <summary>A scripted enrollment that succeeds writes nothing at all to standard error, whether the code came from the variable or was piped in. When a script redirects or captures standard error (2>&amp;1, a file, the ISE, remoting), Windows PowerShell turns each line a native program writes there into an error record, and with ErrorActionPreference set to Stop that would end the script after the single-use code was already spent.</summary>
[Theory]
[InlineData("variable")]
[InlineData("piped")]
public async Task SuccessfulScriptedEnrollment_WritesNothingToStandardError(string source)
{
using CliFixture cli = new() { Reply = "Enrolled device synthetic-device-7." };
Supply(cli, source, Code);
int exitCode = await cli.RunAsync("enroll", "--server", Server);
Assert.Equal(0, exitCode);
Assert.Equal(0, cli.Error.Length);
Assert.Equal("Enrolled device synthetic-device-7.\n", cli.Output);
}
/// <summary>At a console the operator is prompted on standard error and the code is read key by key up to Enter, every key without being shown. Standard input is not read as a line, and the prompt line is ended on standard error because the Enter was not shown either.</summary>
[Fact]
public async Task CodeTypedAtTheConsole_IsReadWithoutBeingShown()
{
using CliFixture cli = new() { Reply = "Enrolled.", InputRedirected = false };
cli.Type(Code);
cli.Press(ConsoleKey.Enter, '\r');
int exitCode = await cli.RunAsync("enroll", "--server", Server);
Assert.Equal(0, exitCode);
Assert.Equal(Code.Length + 1, cli.KeysRead);
Assert.Equal(0, cli.KeysShown);
Assert.Equal(0, cli.LinesRead);
Assert.Equal(new PipeRequest("enroll", Server, Code), Assert.Single(cli.Sent));
Assert.Equal("Enrolled.\n", cli.Output);
Assert.Equal(Prompt, cli.Error);
}
/// <summary>While typing, Backspace removes the last character and does nothing on an empty line, and keys that produce no printable character (arrows, function keys, Tab, Ctrl combinations) are ignored, so the code sent is what the operator meant to type.</summary>
[Fact]
public async Task TypingAtTheConsole_HonorsBackspaceAndIgnoresKeysWithoutACharacter()
{
using CliFixture cli = new() { InputRedirected = false };
cli.Press(ConsoleKey.Backspace, '\b');
cli.Type("synthetic-cods");
cli.Press(ConsoleKey.Backspace, '\b');
cli.Press(ConsoleKey.Backspace, '\b');
cli.Press(ConsoleKey.LeftArrow);
cli.Press(ConsoleKey.F5);
cli.Press(ConsoleKey.Tab, '\t');
cli.Press(ConsoleKey.A, '\u0001');
cli.Type("de-4471");
cli.Press(ConsoleKey.Enter, '\r');
cli.Type("typed-after-enter");
int exitCode = await cli.RunAsync("enroll", "--server", Server);
Assert.Equal(0, exitCode);
Assert.Equal(Code, Assert.Single(cli.Sent).EnrollmentCode);
Assert.Equal(0, cli.KeysShown);
Assert.Equal("typed-after-enter".Length, cli.Keys.Count);
}
/// <summary>The typed line also ends on a key that carries a line-end character without being the Enter key: Ctrl+M, which a console reports as the M key with a carriage return, and a bare carriage return or line feed delivered by a terminal that pastes or forwards text. Keys after it are left unread.</summary>
[Theory]
[InlineData(ConsoleKey.M, '\r')]
[InlineData(ConsoleKey.None, '\r')]
[InlineData(ConsoleKey.None, '\n')]
[InlineData(ConsoleKey.J, '\n')]
public async Task TypingAtTheConsole_EndsOnALineEndCharacterWithoutTheEnterKey(ConsoleKey key, char character)
{
using CliFixture cli = new() { Reply = "Enrolled.", InputRedirected = false };
cli.Type(Code);
cli.Press(key, character);
cli.Type("typed-after-the-line-end");
int exitCode = await cli.RunAsync("enroll", "--server", Server);
Assert.Equal(0, exitCode);
Assert.Equal(Code, Assert.Single(cli.Sent).EnrollmentCode);
Assert.Equal("typed-after-the-line-end".Length, cli.Keys.Count);
Assert.Equal(Prompt, cli.Error);
}
/// <summary>When reading keys fails, the prompt line is ended before the failure is reported, so the message starts on its own line instead of running on from "Enrollment code: ". Nothing is sent.</summary>
[Fact]
public async Task KeyReadFailure_EndsThePromptLineBeforeTheMessage()
{
using CliFixture cli = new() { InputRedirected = false };
cli.Type("synthetic-co");
int exitCode = await cli.RunAsync("enroll", "--server", Server);
Assert.Equal(1, exitCode);
Assert.Empty(cli.Sent);
Assert.Equal("", cli.Output);
Assert.Equal(Prompt + "The fixture has no more keys to press.\n", cli.Error);
}
/// <summary>What a shell puts around the code is dropped, whichever way it arrives, and white space inside it is kept. A code never begins or ends with white space or a byte-order mark, but a shell can add them: cmd's "echo CODE | ..." pipes a trailing space, and Windows PowerShell 5.1 with a UTF-8 console code page pipes a leading byte-order mark, which is not white space and would otherwise reach the server as part of the code.</summary>
[Theory]
[InlineData("variable", " synthetic-code-4471 ", "synthetic-code-4471")]
[InlineData("piped", "synthetic-code-4471 ", "synthetic-code-4471")]
[InlineData("piped", "\tsynthetic code 4471\t", "synthetic code 4471")]
[InlineData("typed", " synthetic-code-4471 ", "synthetic-code-4471")]
[InlineData("piped", "\uFEFFsynthetic-code-4471", "synthetic-code-4471")]
[InlineData("piped", " \uFEFF synthetic-code-4471 ", "synthetic-code-4471")]
[InlineData("variable", "\uFEFFsynthetic-code-4471", "synthetic-code-4471")]
[InlineData("typed", "\uFEFFsynthetic-code-4471", "synthetic-code-4471")]
public async Task WhiteSpaceAroundTheCode_IsDropped(string source, string given, string sent)
{
using CliFixture cli = new();
Supply(cli, source, given);
int exitCode = await cli.RunAsync("enroll", "--server", Server);
Assert.Equal(0, exitCode);
Assert.Equal(new PipeRequest("enroll", Server, sent), Assert.Single(cli.Sent));
}
/// <summary>When no code is available, enrollment fails with one line on standard error that says why, exit code 1, nothing on standard output and no request to the service. With redirected input (at its end, or holding a blank line) that line is all standard error gets; at a console (only Enter or spaces pressed) it follows the ended prompt line. A source that holds only a byte-order mark, with or without white space, holds no code either: a mark alone is never sent as a code.</summary>
[Theory]
[InlineData("piped", null, "")]
[InlineData("piped", "", "")]
[InlineData("piped", " ", "")]
[InlineData("typed", "", Prompt)]
[InlineData("typed", " ", Prompt)]
[InlineData("piped", "\uFEFF", "")]
[InlineData("piped", " \uFEFF ", "")]
[InlineData("variable", "\uFEFF", "")]
[InlineData("typed", "\uFEFF ", Prompt)]
public async Task NoCodeAtAll_FailsWithoutContactingTheService(string source, string? given, string prompt)
{
using CliFixture cli = new();
if(given is not null)
{
Supply(cli, source, given);
}
int exitCode = await cli.RunAsync("enroll", "--server", Server);
Assert.Equal(1, exitCode);
Assert.Empty(cli.Sent);
Assert.Equal("", cli.Output);
Assert.Equal(prompt + "Enrollment code is required.\n", cli.Error);
}
/// <summary>
/// The code is never printed, whichever way it arrived and however the enrollment ends: accepted, refused by the service,
/// timed out, or failed to send. The fake service's replies do not contain the code, and the real service's cannot: its
/// reply to an enrollment is the new device's identifier, or "Error:" followed by its own description of the failure,
/// and it copies neither the request nor the server's response body into either. So the reply is printed as it comes,
/// with no filtering to test.
/// </summary>
[Theory]
[InlineData("variable", "accepted")]
[InlineData("piped", "accepted")]
[InlineData("typed", "accepted")]
[InlineData("variable", "refused")]
[InlineData("piped", "refused")]
[InlineData("typed", "refused")]
[InlineData("variable", "timeout")]
[InlineData("piped", "timeout")]
[InlineData("typed", "timeout")]
[InlineData("variable", "failure")]
[InlineData("piped", "failure")]
[InlineData("typed", "failure")]
public async Task Code_NeverAppearsInOutput(string source, string outcome)
{
using CliFixture cli = new()
{
Reply = outcome is "refused" ? "Error: The synthetic service refused the enrollment." : "Enrolled.",
SendFailure = outcome switch
{
"timeout" => new TaskCanceledException("Synthetic request timeout."),
"failure" => new IOException("Service connection closed before a complete response was received."),
_ => null,
},
};
Supply(cli, source, Code);
int exitCode = await cli.RunAsync("enroll", "--server", Server);
Assert.Equal(outcome is "accepted" ? 0 : 1, exitCode);
Assert.Equal(Code, Assert.Single(cli.Sent).EnrollmentCode);
Assert.DoesNotContain(Code, cli.Everything, StringComparison.Ordinal);
}
/// <summary>A code put on the command line is refused, not used: nothing is sent, nothing is read, and the refusal does not repeat the code, so a mistake does not also copy the secret into captured error output.</summary>
[Theory]
[InlineData("enroll", "--server", Server, Code)]
[InlineData("enroll", "--server", Server, "--code", Code)]
[InlineData("enroll", "--code", Code)]
[InlineData("enroll", Code)]
[InlineData("enrol", "--server", Server, "--code", Code)]
public async Task CodeOnTheCommandLine_IsRefusedAndNotEchoed(params string[] args)
{
using CliFixture cli = new();
int exitCode = await cli.RunAsync(args);
Assert.Equal(1, exitCode);
Assert.Empty(cli.Sent);
Assert.Equal("", cli.Output);
Assert.DoesNotContain(Code, cli.Error, StringComparison.Ordinal);
Assert.Equal(0, cli.LinesRead);
Assert.Equal(0, cli.KeysRead);
}
/// <summary>Makes the given text arrive the named way: in the variable, as the line redirected standard input holds, or as keys typed at a console and ended with Enter.</summary>
private static void Supply(CliFixture cli, string source, string text)
{
switch(source)
{
case "variable":
cli.Variables["QQQ_PRINT_ENROLLMENT_CODE"] = text;
break;
case "piped":
cli.TypedLines.Enqueue(text);
break;
default:
cli.InputRedirected = false;
cli.Type(text);
cli.Press(ConsoleKey.Enter, '\r');
break;
}
}
}
@@ -0,0 +1,197 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using Qqq.PrintAgent.Windows;
namespace Qqq.PrintAgent.Cli.Tests;
/// <summary>
/// Shared harness for the command-line tests: the real <see cref="CommandLine"/> wired to hand-written fakes for the console,
/// the environment, the service pipe and the two helper entry points. A test scripts what the outside world answers, runs
/// an argument list, then reads exactly what was written, sent and started. Nothing here touches the real console, the
/// installed service or a printer. Captured output uses "\n" line endings so expected text reads the same on every machine.
/// </summary>
internal sealed class CliFixture : IDisposable
{
private readonly StringWriter _output = new() { NewLine = "\n" };
private readonly StringWriter _error = new() { NewLine = "\n" };
/// <summary>Everything written to standard output so far.</summary>
internal string Output => _output.ToString();
/// <summary>Everything written to standard error so far.</summary>
internal string Error => _error.ToString();
/// <summary>The environment the command line sees; a name that is absent reads as not set.</summary>
internal Dictionary<string, string?> Variables { get; } = new(StringComparer.Ordinal);
/// <summary>The names of the environment variables that were read, in order.</summary>
internal List<string> VariablesRead { get; } = [];
/// <summary>Whether standard input is a file or a pipe (the default here, as in a script) or a console an operator types at.</summary>
internal bool InputRedirected { get; set; } = true;
/// <summary>The lines redirected standard input holds, in order; when they run out, standard input is at its end.</summary>
internal Queue<string?> TypedLines { get; } = new();
/// <summary>How many times a line was asked for from standard input.</summary>
internal int LinesRead { get; private set; }
/// <summary>The keys an operator presses at the console, in order.</summary>
internal Queue<ConsoleKeyInfo> Keys { get; } = new();
/// <summary>How many keys were read from the console.</summary>
internal int KeysRead { get; private set; }
/// <summary>How many of those keys were read in a way that would have shown them on the screen.</summary>
internal int KeysShown { get; private set; }
/// <summary>The reply the fake service gives to every request.</summary>
internal string Reply { get; set; } = "Synthetic service reply.";
/// <summary>When set, the fake pipe fails with this instead of replying, after recording the request.</summary>
internal Exception? SendFailure { get; set; }
/// <summary>Every request sent to the fake service, in order.</summary>
internal List<PipeRequest> Sent { get; } = [];
/// <summary>The exit code the fake update helper reports.</summary>
internal int HelperExitCode { get; set; }
/// <summary>When set, whichever helper entry point is started fails with this.</summary>
internal Exception? HelperFailure { get; set; }
/// <summary>The request-file paths handed to the update helper, in order.</summary>
internal List<string> UpdateRequests { get; } = [];
/// <summary>The sign-in callback addresses handed to the forwarder, each with the cancellation token it was given.</summary>
internal List<(string Callback, CancellationToken Token)> Callbacks { get; } = [];
/// <summary>Everything the command line wrote, to either stream; a secret must never appear in it.</summary>
internal string Everything => Output + Error;
/// <summary>Runs one invocation of the command line against the fakes and returns its exit code.</summary>
internal Task<int> RunAsync(params string[] args)
=> new CommandLine(new CommandLineHost(_output, _error, ReadVariable, () => InputRedirected, ReadLine, ReadKey, SendAsync, ApplyUpdateAsync, ForwardCallbackAsync)).RunAsync(args);
/// <summary>Queues the keys for typing the given text at the console, without the Enter that ends the line.</summary>
internal void Type(string text)
{
foreach(char character in text)
{
Keys.Enqueue(new ConsoleKeyInfo(character, ConsoleKey.None, shift: false, alt: false, control: false));
}
}
/// <summary>Queues one key that produces the given character, such as Enter ('\r') or Backspace ('\b'), or none ('\0') for an arrow or function key.</summary>
internal void Press(ConsoleKey key, char character = '\0')
=> Keys.Enqueue(new ConsoleKeyInfo(character, key, shift: false, alt: false, control: false));
/// <summary>Records which variable was asked for and answers from the scripted variables.</summary>
private string? ReadVariable(string name)
{
VariablesRead.Add(name);
return Variables.GetValueOrDefault(name);
}
/// <summary>Hands out the next typed line, or null once the operator has nothing more to type.</summary>
private string? ReadLine()
{
LinesRead++;
return TypedLines.Count > 0 ? TypedLines.Dequeue() : null;
}
/// <summary>Hands out the next pressed key and notes whether it was asked for without echo. Running out of keys is a failure, so a read loop that never sees Enter fails the test instead of hanging it.</summary>
private ConsoleKeyInfo ReadKey(bool intercept)
{
KeysRead++;
KeysShown += intercept ? 0 : 1;
return Keys.Count > 0 ? Keys.Dequeue() : throw new InvalidOperationException("The fixture has no more keys to press.");
}
/// <summary>Records the request, then replies or fails as scripted.</summary>
private Task<string> SendAsync(PipeRequest request)
{
Sent.Add(request);
return SendFailure is null ? Task.FromResult(Reply) : Task.FromException<string>(SendFailure);
}
/// <summary>Records the update request path and reports the scripted exit code or failure.</summary>
private Task<int> ApplyUpdateAsync(string requestPath)
{
UpdateRequests.Add(requestPath);
return HelperFailure is null ? Task.FromResult(HelperExitCode) : Task.FromException<int>(HelperFailure);
}
/// <summary>Records the callback address and token, then succeeds or fails as scripted.</summary>
private Task ForwardCallbackAsync(string callback, CancellationToken token)
{
Callbacks.Add((callback, token));
return HelperFailure is null ? Task.CompletedTask : Task.FromException(HelperFailure);
}
/// <summary>Releases the two capture writers.</summary>
public void Dispose()
{
_output.Dispose();
_error.Dispose();
}
}
@@ -0,0 +1,124 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
namespace Qqq.PrintAgent.Cli.Tests;
/// <summary>
/// The two roles other parts of the product start this executable in, each with fixed arguments: the MSI update helper
/// and the browser sign-in callback forwarder. These tests pin which arguments select each role, what is passed on, and
/// how a failure is reported, with fakes standing in for the installer and the companion. The executable is not a printer
/// worker; the service starts its own executable for that, and CliUsageTests holds --printer-worker to an unknown command.
/// </summary>
public sealed class CliHelperRoleTests
{
private const string Callback = "io.qrun.qqq-print-agent:/oauth/callback?code=synthetic-code-91&state=synthetic-state-17";
/// <summary>The update helper receives exactly the request path it was started with and its exit code is returned unchanged; the command line prints nothing of its own.</summary>
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1603)]
public async Task ApplyUpdate_PassesTheRequestPathAndReturnsTheExitCode(int helperExitCode)
{
using CliFixture cli = new() { HelperExitCode = helperExitCode };
int exitCode = await cli.RunAsync("--apply-update", "C:\\synthetic\\updates\\request.json");
Assert.Equal(helperExitCode, exitCode);
Assert.Equal("C:\\synthetic\\updates\\request.json", Assert.Single(cli.UpdateRequests));
Assert.Equal("", cli.Everything);
Assert.Empty(cli.Sent);
}
/// <summary>An update helper that throws is reported as one line on standard error and exit code 1.</summary>
[Fact]
public async Task ApplyUpdate_FailureIsOneLineOnStandardErrorAndFails()
{
using CliFixture cli = new() { HelperFailure = new UnauthorizedAccessException("Synthetic update refusal.") };
int exitCode = await cli.RunAsync("--apply-update", "C:\\synthetic\\updates\\request.json");
Assert.Equal(1, exitCode);
Assert.Equal("", cli.Output);
Assert.Equal("Synthetic update refusal.\n", cli.Error);
}
/// <summary>The sign-in callback address is forwarded exactly as the browser supplied it, without a cancellation deadline of the command line's own, and a delivered callback exits 0 with nothing printed.</summary>
[Fact]
public async Task AuthCallback_ForwardsTheAddressUnchangedAndSucceeds()
{
using CliFixture cli = new();
int exitCode = await cli.RunAsync("--auth-callback", Callback);
Assert.Equal(0, exitCode);
(string forwarded, CancellationToken token) = Assert.Single(cli.Callbacks);
Assert.Equal(Callback, forwarded);
Assert.False(token.CanBeCanceled);
Assert.Equal("", cli.Everything);
Assert.Empty(cli.Sent);
}
/// <summary>A callback that cannot be delivered exits 1 with the forwarder's reason on standard error, and the address, which carries a one-time authorization code, is not printed.</summary>
[Fact]
public async Task AuthCallback_FailureIsReportedWithoutTheAddress()
{
using CliFixture cli = new() { HelperFailure = new UnauthorizedAccessException("Browser callbacks require the installed CLI location.") };
int exitCode = await cli.RunAsync("--auth-callback", Callback);
Assert.Equal(1, exitCode);
Assert.Equal("", cli.Output);
Assert.Equal("Browser callbacks require the installed CLI location.\n", cli.Error);
Assert.DoesNotContain("synthetic-code-91", cli.Everything, StringComparison.Ordinal);
}
/// <summary>A callback hand-off that is canceled or times out exits 1 with the fixed timeout sentence.</summary>
[Fact]
public async Task AuthCallback_TimeoutFailsWithTheFixedMessage()
{
using CliFixture cli = new() { HelperFailure = new OperationCanceledException("Synthetic hand-off timeout.") };
int exitCode = await cli.RunAsync("--auth-callback", Callback);
Assert.Equal(1, exitCode);
Assert.Equal("The operation timed out or was canceled before completion.\n", cli.Error);
}
/// <summary>The role arguments are exact. One argument too many or too few does not start a helper: the command line is refused as an unknown command, and what was typed, which may be a callback address, is not repeated.</summary>
[Theory]
[InlineData("--apply-update")]
[InlineData("--apply-update", "C:\\synthetic\\updates\\request.json", "extra")]
[InlineData("--Apply-Update", "C:\\synthetic\\updates\\request.json")]
[InlineData("--auth-callback")]
[InlineData("--auth-callback", Callback, "extra")]
[InlineData("run", "--apply-update", "C:\\synthetic\\updates\\request.json")]
public async Task InexactRoleArguments_StartNoHelperAndAreRefused(params string[] args)
{
using CliFixture cli = new();
int exitCode = await cli.RunAsync(args);
Assert.Equal(1, exitCode);
Assert.Empty(cli.UpdateRequests);
Assert.Empty(cli.Callbacks);
Assert.Empty(cli.Sent);
Assert.Equal("", cli.Output);
Assert.EndsWith(CommandLine.Usage.ReplaceLineEndings("\n") + "\n", cli.Error.ReplaceLineEndings("\n"), StringComparison.Ordinal);
Assert.DoesNotContain("synthetic-code-91", cli.Error, StringComparison.Ordinal);
}
}
@@ -0,0 +1,165 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using System.Diagnostics;
namespace Qqq.PrintAgent.Cli.Tests;
/// <summary>
/// The built qqq-print-agent.exe, started as a real process. The other command-line tests drive the logic against fakes;
/// these prove the shipped entry point is wired to it: real exit codes, real standard output and standard error. None of
/// them needs the installed service: every command line here is answered or refused before the service would be contacted.
/// </summary>
public sealed class CliProcessTests
{
/// <summary>The executable built beside this test assembly.</summary>
private static string Executable => Path.ChangeExtension(typeof(Program).Assembly.Location, ".exe");
/// <summary>Asking the real executable for help exits 0 with the usage on standard output and nothing on standard error.</summary>
[Theory]
[InlineData("--help")]
[InlineData("-h")]
[InlineData("help")]
public async Task Help_ExitsZeroWithUsageOnStandardOutput(string argument)
{
(int exitCode, string output, string error) = await RunAsync(input: null, argument);
Assert.Equal(0, exitCode);
Assert.Equal(CommandLine.Usage + Environment.NewLine, output);
Assert.Equal("", error);
}
/// <summary>Every line of the usage the real executable writes, to either stream, ends the way this platform ends lines. The help text is a multi-line literal whose line ends follow the source checkout, so without care a Windows console would get bare line feeds with one carriage return at the very end.</summary>
[Theory]
[InlineData("--help")]
[InlineData("status")]
public async Task Usage_IsWrittenWithThePlatformLineEnds(string argument)
{
(_, string output, string error) = await RunAsync(input: null, argument);
string written = output + error;
Assert.True(written.Split(Environment.NewLine).Length > 15, "The usage should span many lines.");
string withoutLineEnds = written.Replace(Environment.NewLine, "", StringComparison.Ordinal);
Assert.DoesNotContain('\n', withoutLineEnds);
Assert.DoesNotContain('\r', withoutLineEnds);
}
/// <summary>With no arguments at all the real executable also prints the usage and exits 0.</summary>
[Fact]
public async Task NoArguments_ExitsZeroWithUsageOnStandardOutput()
{
(int exitCode, string output, string error) = await RunAsync(input: null);
Assert.Equal(0, exitCode);
Assert.Equal(CommandLine.Usage + Environment.NewLine, output);
Assert.Equal("", error);
}
/// <summary>An unknown command makes the real executable exit 1 with the reason and the usage on standard error and nothing on standard output.</summary>
[Fact]
public async Task UnknownCommand_ExitsOneWithUsageOnStandardError()
{
(int exitCode, string output, string error) = await RunAsync(input: null, "status");
Assert.Equal(1, exitCode);
Assert.Equal("", output);
Assert.Equal("Unknown command." + Environment.NewLine + CommandLine.Usage + Environment.NewLine, error);
}
/// <summary>The real executable is not a printer worker. Given the worker's argument and a worker request on standard input, it answers nothing on standard output, where a parent would expect the worker's reply, and refuses the argument as an unknown command.</summary>
[Fact]
public async Task PrinterWorkerArgument_IsAnUnknownCommand()
{
(int exitCode, string output, string error) = await RunAsync("{\"operation\":\"discover\"}", "--printer-worker");
Assert.Equal(1, exitCode);
Assert.Equal("", output);
Assert.Equal("Unknown command." + Environment.NewLine + CommandLine.Usage + Environment.NewLine, error);
}
/// <summary>The real executable, with no enrollment code in its environment and standard input closed, sees that input is redirected, reads it as a line without prompting, finds none, and stops there: the reason is the only thing on standard error, standard output is empty and the exit code is 1. It fails before any request would be sent, so the service is not contacted. A binding that took redirected input for a console would prompt and then fail reading a key, which this output excludes.</summary>
[Fact]
public async Task Enroll_WithNoCodeAndClosedInput_FailsBeforeContactingTheService()
{
(int exitCode, string output, string error) = await RunAsync(input: null, "enroll", "--server", "https://qqq.example.test");
Assert.Equal(1, exitCode);
Assert.Equal("", output);
Assert.Equal("Enrollment code is required." + Environment.NewLine, error);
}
/// <summary>
/// Executes the real binding for "is standard input redirected" in this process, and nothing more: it compares the
/// binding with the property it should read, so it would not notice most wrong bindings. What proves the two branches
/// is elsewhere. The redirected branch is proved by Enroll_WithNoCodeAndClosedInput_FailsBeforeContactingTheService,
/// which runs the real executable with redirected input. The console branch is proved against fake keys in
/// CliEnrollmentCodeTests; no test here has a real console to type at.
/// </summary>
[Fact]
public void InputRedirectionBinding_ReportsTheConsoleState()
{
Assert.Equal(Console.IsInputRedirected, Program.IsInputRedirected());
}
/// <summary>
/// Starts the executable with the given arguments and waits for it to end, returning its exit code and exactly what it
/// wrote, line ends included. Standard input carries the given line, if any, and is then closed. The enrollment code
/// variable is removed from the child's environment, so the result does not depend on the machine running the test. A
/// process that has not finished within a minute is killed, so a hang fails the test instead of blocking the run.
/// </summary>
private static async Task<(int ExitCode, string Output, string Error)> RunAsync(string? input, params string[] args)
{
ProcessStartInfo start = new(Executable)
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach(string argument in args)
{
start.ArgumentList.Add(argument);
}
start.Environment.Remove(CommandLine.EnrollmentCodeVariable);
using Process process = Process.Start(start) ?? throw new InvalidOperationException("The command-line executable did not start.");
using CancellationTokenSource limit = new(TimeSpan.FromMinutes(1));
try
{
Task<string> output = process.StandardOutput.ReadToEndAsync(limit.Token);
Task<string> error = process.StandardError.ReadToEndAsync(limit.Token);
if(input is not null)
{
await process.StandardInput.WriteLineAsync(input.AsMemory(), limit.Token);
}
process.StandardInput.Close();
await process.WaitForExitAsync(limit.Token);
return (process.ExitCode, await output, await error);
}
finally
{
if(!process.HasExited)
{
process.Kill(entireProcessTree: true);
}
}
}
}
@@ -0,0 +1,166 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using Qqq.PrintAgent.Windows;
namespace Qqq.PrintAgent.Cli.Tests;
/// <summary>
/// Operator commands. Each one becomes exactly one request to the installed service over its pipe; the reply is printed as
/// the service wrote it; and the exit code tells a script whether the service did what was asked. The pipe is a fake here,
/// so these tests need no installed service.
/// </summary>
public sealed class CliServiceCommandTests
{
private const string SignOutNote = "The identity provider's browser session is not ended from the command line; use Sign out in the QQQ Print Agent app to end it too.";
/// <summary>A command without options sends one request that carries only its operation name (run asks for a reconnect, service-status for the status), prints the reply on standard output and exits 0.</summary>
[Theory]
[InlineData("printers", "printers")]
[InlineData("run", "reconnect")]
[InlineData("service-status", "status")]
[InlineData("snapshot", "snapshot")]
public async Task CommandWithoutOptions_SendsItsOperationAndPrintsTheReply(string command, string operation)
{
using CliFixture cli = new() { Reply = "Synthetic service accepted the request." };
int exitCode = await cli.RunAsync(command);
Assert.Equal(0, exitCode);
Assert.Equal(new PipeRequest(operation), Assert.Single(cli.Sent));
Assert.Equal("Synthetic service accepted the request.\n", cli.Output);
Assert.Equal("", cli.Error);
}
/// <summary>Signing out sends the sign-out operation and, when the service accepts it, adds one line saying the identity provider's browser session is still open, because only the companion can end that.</summary>
[Fact]
public async Task SignOut_SendsTheOperationAndSaysTheProviderSessionRemains()
{
using CliFixture cli = new() { Reply = "Signed out." };
int exitCode = await cli.RunAsync("sign-out");
Assert.Equal(0, exitCode);
Assert.Equal(new PipeRequest("sign-out"), Assert.Single(cli.Sent));
Assert.Equal("Signed out.\n" + SignOutNote + "\n", cli.Output);
Assert.Equal("", cli.Error);
}
/// <summary>Sharing or hiding a printer sends the printer and the choice, and nothing else. The two options may come in either order, and true or false is accepted in any letter case (PowerShell writes $true as "True").</summary>
[Theory]
[InlineData(true, "expose", "--printer", "synthetic-queue-1", "--exposed", "true")]
[InlineData(false, "expose", "--printer", "synthetic-queue-1", "--exposed", "false")]
[InlineData(true, "expose", "--printer", "synthetic-queue-1", "--exposed", "True")]
[InlineData(false, "expose", "--printer", "synthetic-queue-1", "--exposed", "FALSE")]
[InlineData(true, "expose", "--exposed", "TRUE", "--printer", "synthetic-queue-1")]
[InlineData(false, "expose", "--exposed", "False", "--printer", "synthetic-queue-1")]
public async Task Expose_SendsThePrinterAndTheChoice(bool exposed, params string[] args)
{
using CliFixture cli = new() { Reply = "{\"status\":\"Connected\"}" };
int exitCode = await cli.RunAsync(args);
Assert.Equal(0, exitCode);
Assert.Equal(new PipeRequest("set-exposure", PrinterId: "synthetic-queue-1", Exposed: exposed), Assert.Single(cli.Sent));
Assert.Equal("{\"status\":\"Connected\"}\n", cli.Output);
Assert.Equal("", cli.Error);
}
/// <summary>Enrolling sends the server address and the enrollment code together in one request, and nothing else.</summary>
[Fact]
public async Task Enroll_SendsTheServerAndTheCode()
{
using CliFixture cli = new() { Reply = "Enrolled." };
cli.Variables[CommandLine.EnrollmentCodeVariable] = "synthetic-code-4471";
int exitCode = await cli.RunAsync("enroll", "--server", "https://qqq.example.test");
Assert.Equal(0, exitCode);
Assert.Equal(new PipeRequest("enroll", "https://qqq.example.test", "synthetic-code-4471"), Assert.Single(cli.Sent));
Assert.Equal("Enrolled.\n", cli.Output);
Assert.Equal("", cli.Error);
}
/// <summary>A reply that begins with "Error:" means the service refused or failed the request. It is still printed on standard output as the service wrote it, and every command then exits 1, so a script cannot take a refusal for success. Signing out adds no note when it did not happen.</summary>
[Theory]
[InlineData("printers")]
[InlineData("run")]
[InlineData("sign-out")]
[InlineData("service-status")]
[InlineData("snapshot")]
[InlineData("expose", "--printer", "synthetic-queue-1", "--exposed", "true")]
[InlineData("enroll", "--server", "https://qqq.example.test")]
public async Task ErrorReply_IsPrintedAndFailsTheCommand(params string[] args)
{
using CliFixture cli = new() { Reply = "Error: The synthetic service refused." };
cli.Variables[CommandLine.EnrollmentCodeVariable] = "synthetic-code-4471";
int exitCode = await cli.RunAsync(args);
Assert.Equal(1, exitCode);
Assert.Single(cli.Sent);
Assert.Equal("Error: The synthetic service refused.\n", cli.Output);
Assert.Equal("", cli.Error);
}
/// <summary>Only a reply that starts with "Error:" in exactly that form is a failure; the word appearing later in a reply, or in another letter case, is ordinary text.</summary>
[Theory]
[InlineData("Last error: none.")]
[InlineData("error: lower case is not the service's refusal form")]
[InlineData("")]
public async Task ReplyThatOnlyMentionsAnError_IsNotAFailure(string reply)
{
using CliFixture cli = new() { Reply = reply };
int exitCode = await cli.RunAsync("service-status");
Assert.Equal(0, exitCode);
Assert.Equal(reply + "\n", cli.Output);
}
/// <summary>When the service cannot be reached or is not the installed service, the reason is one line on standard error, standard output stays empty and the exit code is 1.</summary>
[Fact]
public async Task PipeFailure_IsOneLineOnStandardErrorAndFails()
{
using CliFixture cli = new() { SendFailure = new UnauthorizedAccessException("The local endpoint is not the installed Windows print service. No request was sent.") };
int exitCode = await cli.RunAsync("snapshot");
Assert.Equal(1, exitCode);
Assert.Equal("", cli.Output);
Assert.Equal("The local endpoint is not the installed Windows print service. No request was sent.\n", cli.Error);
}
/// <summary>A request that times out or is canceled exits 1 with a fixed sentence, never 0 and never an unhandled exception, so an operation that did not finish is not mistaken for one that succeeded.</summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task TimeoutOrCancellation_FailsWithAFixedMessage(bool taskCanceled)
{
using CliFixture cli = new() { SendFailure = taskCanceled ? new TaskCanceledException("Synthetic request timeout.") : new OperationCanceledException("Synthetic cancellation.") };
int exitCode = await cli.RunAsync("run");
Assert.Equal(1, exitCode);
Assert.Equal("", cli.Output);
Assert.Equal("The operation timed out or was canceled before completion.\n", cli.Error);
}
}
@@ -0,0 +1,117 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
namespace Qqq.PrintAgent.Cli.Tests;
/// <summary>
/// Help and unknown commands. Asking for help is a success and prints the usage on standard output; a command the tool does
/// not know is a failure and prints the usage on standard error, so a script that captures output never mistakes help text
/// for a result. Neither contacts the service.
/// </summary>
public sealed class CliUsageTests
{
/// <summary>The exact help text an operator sees. It is repeated here on purpose: changing what the tool tells operators should be a deliberate edit in two places, not a side effect.</summary>
private const string ExpectedUsage = """
Usage: qqq-print-agent <command>
Commands:
printers List the printers the service can see, as JSON.
enroll --server URL Pair this computer with a QQQ server using a one-time enrollment code.
expose --printer ID --exposed true|false Share a printer with QQQ, or stop sharing it.
run Ask the service to refresh its connection to QQQ.
sign-out End the service's QQQ session.
service-status Show the service's connection status.
snapshot Show the service's state as JSON: connection, printers, recent jobs and logs.
help Show this text (also --help or -h, alone or after a command).
Every command is carried out by the installed print service, which owns the sign-in, the pairing and all printing.
Run from an administrator prompt, and sign in through the companion app first.
The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or else from standard input:
at a Windows console it is prompted for and not shown; redirected input is read as one line, without a prompt.
An unattended caller must set the variable or redirect input, or the prompt waits for a key.
The code is never accepted on the command line.
Exit code: 0 on success; 1 when the arguments are wrong, the service cannot be reached or the service reports an error.
""";
/// <summary>No arguments, help, --help and -h all print exactly the usage on standard output, write nothing to standard error, send nothing to the service and exit 0. Words after the help word do not change that.</summary>
[Theory]
[InlineData]
[InlineData("help")]
[InlineData("--help")]
[InlineData("-h")]
[InlineData("help", "enroll")]
[InlineData("--help", "--anything")]
public async Task AskingForHelp_PrintsUsageOnStandardOutputAndSucceeds(params string[] args)
{
using CliFixture cli = new();
int exitCode = await cli.RunAsync(args);
Assert.Equal(0, exitCode);
Assert.Equal(ExpectedUsage.ReplaceLineEndings("\n") + "\n", cli.Output.ReplaceLineEndings("\n"));
Assert.Equal("", cli.Error);
Assert.Empty(cli.Sent);
}
/// <summary>A first word that is not a command is refused: standard error gets the reason and the usage, standard output stays empty, nothing is sent and the exit code is 1. Command names are case-sensitive, the service's own operation names are not commands, and --printer-worker is not a role of this executable: the service starts its own executable as the printer worker.</summary>
[Theory]
[InlineData("status")]
[InlineData("Printers")]
[InlineData("--printer-worker")]
[InlineData("--printer-worker", "extra")]
[InlineData("--version")]
[InlineData("")]
public async Task UnknownCommand_PrintsUsageOnStandardErrorAndFails(params string[] args)
{
using CliFixture cli = new();
int exitCode = await cli.RunAsync(args);
Assert.Equal(1, exitCode);
Assert.Equal("", cli.Output);
Assert.Equal("Unknown command.\n" + ExpectedUsage.ReplaceLineEndings("\n") + "\n", cli.Error.ReplaceLineEndings("\n"));
Assert.Empty(cli.Sent);
}
/// <summary>The refusal never repeats what was typed. A mistyped command line can carry a secret (an enrollment code, a sign-in callback address) and standard error is often captured into logs.</summary>
[Fact]
public async Task UnknownCommand_IsNotEchoed()
{
using CliFixture cli = new();
int exitCode = await cli.RunAsync("frobnicate-7Q2", "synthetic-secret-91");
Assert.Equal(1, exitCode);
Assert.DoesNotContain("frobnicate-7Q2", cli.Everything, StringComparison.Ordinal);
Assert.DoesNotContain("synthetic-secret-91", cli.Everything, StringComparison.Ordinal);
}
/// <summary>The usage lists every command the tool accepts, each at the start of its own line, so help cannot fall behind the commands that exist.</summary>
[Fact]
public void Usage_ListsEveryCommand()
{
string[] lines = CommandLine.Usage.ReplaceLineEndings("\n").Split('\n');
Assert.Equal(7, CommandLine.CommandNames.Count);
Assert.All(CommandLine.CommandNames, name => Assert.Contains(lines, line => line.StartsWith(" " + name + " ", StringComparison.Ordinal)));
}
/// <summary>The real entry point, with the real console and pipe client bound, answers help with exit code 0 and never needs the service for it. This is the only test that runs the production composition in this process.</summary>
[Fact]
public async Task RealEntryPoint_AnswersHelpWithoutTheService()
{
Assert.Equal(0, await Program.Main(["--help"]));
}
}
@@ -1,41 +0,0 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using Qqq.PrintAgent.Windows;
namespace Qqq.PrintAgent.Cli.Tests;
/// <summary>With the signed-in service installed, the command-line tool sends its commands to the service over the management pipe instead of using a private device token, and refuses foreground options unless legacy mode is explicitly requested.</summary>
public sealed class NativeCliRoutingTests
{
/// <summary>The printers, run and sign-out commands are each translated into the matching service request (printers, reconnect, sign-out) and succeed with exit code 0, so normal use goes through the service that owns the signed-in session.</summary>
[Theory]
[InlineData("printers", "printers")]
[InlineData("run", "reconnect")]
[InlineData("sign-out", "sign-out")]
public async Task NormalCommandsUseServiceRatherThanPrivateBearerTransport(string command, string expected)
{
PipeRequest? sent = null;
int result = await Program.DispatchAsync([command], request =>
{
sent = request;
return Task.FromResult("Synthetic service accepted request.");
});
Assert.Equal(0, result);
Assert.Equal(expected, sent!.Operation);
}
/// <summary>Foreground-only options such as running once are refused before any service call unless legacy compatibility is named, and legacy mode cannot be combined with the service flag. The compatibility check itself is true only when the legacy flag is present.</summary>
[Fact]
public async Task ForegroundOptionsRequireExplicitCompatibilityBeforeAnyServiceCall()
{
await Assert.ThrowsAsync<ArgumentException>(() => Program.DispatchAsync(["run", "--once"], _ => throw new InvalidOperationException("Must not contact service.")));
Assert.Throws<ArgumentException>(() => Program.UseLegacyCompatibility(["run", "--legacy-compat", "--service"]));
Assert.True(Program.UseLegacyCompatibility(["run", "--legacy-compat"]));
Assert.False(Program.UseLegacyCompatibility(["run"]));
}
}
@@ -1,61 +0,0 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
namespace Qqq.PrintAgent.Cli.Tests;
/// <summary>Command-line entry point behavior: which data folder foreground runs may use, single-worker locking, and exit codes for help and failures.</summary>
public sealed class ProgramTests
{
/// <summary>A foreground run defaults to the current user's own data folder and may not be pointed at the service's protected machine folder, where it could overwrite the service's credentials; only the explicit service mode resolves to that folder.</summary>
[Fact]
public void ForegroundData_UsesCurrentUserAndCannotOverwriteServiceCredentials()
{
Assert.Equal(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QqqPrintAgent"), Program.ResolveDataDirectory([]));
Assert.Throws<InvalidOperationException>(() => Program.ResolveDataDirectory(["--data-dir", Qqq.PrintAgent.Windows.AgentStore.DefaultDirectory]));
Assert.Equal(Qqq.PrintAgent.Windows.AgentStore.DefaultDirectory, Program.ResolveDataDirectory(["--service"]));
}
/// <summary>The worker lock is exclusive per data folder: while one worker holds it, a second attempt fails, so a foreground command cannot modify state under an active worker.</summary>
[Fact]
public void ForegroundMutation_CannotAcquireActiveWorkerDirectory()
{
string directory = Path.Combine(Path.GetTempPath(), "qqq-cli-lock-" + Guid.NewGuid().ToString("N"));
try
{
using FileStream worker = Program.AcquireWorkerLock(directory);
Assert.Throws<IOException>(() => Program.AcquireWorkerLock(directory));
}
finally { Directory.Delete(directory, recursive: true); }
}
/// <summary>Asking for help prints usage and exits with code 0.</summary>
[Fact]
public async Task Help_ExitsSuccessfully()
{
Assert.Equal(0, await Program.Main(["help"]));
}
/// <summary>Enrolling without the required server address fails with exit code 1 instead of prompting or guessing.</summary>
[Fact]
public async Task Enroll_MissingServerFails()
{
Assert.Equal(1, await Program.Main(["enroll"]));
}
/// <summary>A request that times out ends the command with exit code 1 rather than an unhandled exception.</summary>
[Fact]
public async Task RequestTimeout_ExitsWithFailure()
{
Assert.Equal(1, await Program.ExecuteAsync(() => Task.FromException<int>(new TaskCanceledException("Request timeout."))));
}
}