From d9cc789e27dc82462ad1473f25de4ecfb6418cb5 Mon Sep 17 00:00:00 2001 From: RMANOV <96174405+RMANOV@users.noreply.github.com> Date: Fri, 9 Oct 2026 00:53:36 +0300 Subject: [PATCH 1/9] Deliver standalone Windows setup and correct TSF text actions --- .github/workflows/ci.yml | 92 ++++- crates/smartkey-win/Cargo.toml | 1 + .../packaging/Disable-SmartKey.cmd | 16 + .../packaging/Enable-SmartKey.cmd | 16 + .../packaging/Install-SmartKey.cmd | 16 + .../smartkey-win/packaging/README-WINDOWS.md | 20 ++ .../packaging/Status-SmartKey.cmd | 16 + .../packaging/Uninstall-SmartKey.cmd | 33 ++ crates/smartkey-win/packaging/smoke-user.ps1 | 150 ++++++++ crates/smartkey-win/packaging/user_setup.rs | 137 ++++++++ crates/smartkey-win/src/display.rs | 6 + crates/smartkey-win/src/edit_session.rs | 299 ++++++++-------- crates/smartkey-win/src/lib.rs | 2 + crates/smartkey-win/src/register.rs | 332 ++++++++++++++---- crates/smartkey-win/src/registration.rs | 220 +++++++----- crates/smartkey-win/src/text_contract.rs | 107 ++++++ crates/smartkey-win/src/tsf.rs | 177 ++++------ .../windows-runtime-manifest.json | 123 +++++++ 18 files changed, 1349 insertions(+), 414 deletions(-) create mode 100644 crates/smartkey-win/packaging/Disable-SmartKey.cmd create mode 100644 crates/smartkey-win/packaging/Enable-SmartKey.cmd create mode 100644 crates/smartkey-win/packaging/Install-SmartKey.cmd create mode 100644 crates/smartkey-win/packaging/README-WINDOWS.md create mode 100644 crates/smartkey-win/packaging/Status-SmartKey.cmd create mode 100644 crates/smartkey-win/packaging/Uninstall-SmartKey.cmd create mode 100644 crates/smartkey-win/packaging/smoke-user.ps1 create mode 100644 crates/smartkey-win/packaging/user_setup.rs create mode 100644 crates/smartkey-win/src/text_contract.rs create mode 100644 crates/smartkey-win/windows-runtime-manifest.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5b139ba..73e4bb7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,6 +95,9 @@ jobs: build-windows: name: Build (Windows) runs-on: windows-latest + env: + # Keep the deliverable independent of a separately installed VC runtime. + RUSTFLAGS: -Dwarnings -C target-feature=+crt-static steps: - uses: actions/checkout@v5 - uses: dtolnay/rust-toolchain@stable @@ -106,13 +109,28 @@ jobs: - run: cargo check -p smartkey-win - run: cargo check -p smartkey-playground - run: cargo clippy -p smartkey-win -- -D warnings - - name: Build Windows pilot payload + - name: Build Windows standalone payload run: cargo build --locked -p smartkey-win --release - - name: Stage complete Windows pilot payload + - name: Verify standalone binary dependencies shell: pwsh run: | $ErrorActionPreference = 'Stop' - $stage = Join-Path $env:RUNNER_TEMP "smartkey-windows-pilot-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" + $dumpbin = & $vswhere -latest -products '*' -find 'VC\Tools\MSVC\**\bin\Hostx64\x64\dumpbin.exe' | Select-Object -First 1 + if (-not $dumpbin) { throw 'dumpbin was not found' } + foreach ($binary in @('smartkey-register.exe', 'smartkey_win.dll')) { + $imports = & $dumpbin /DEPENDENTS "target/release/$binary" + if ($LASTEXITCODE -ne 0) { throw "Cannot inspect $binary" } + $imports + if ($imports -match '(?i)(VCRUNTIME[0-9_]*|MSVCP[0-9_]*|ucrtbase)\.dll') { + throw "$binary still depends on a separately installed C/C++ runtime" + } + } + - name: Stage complete Windows standalone payload + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $stage = Join-Path $env:RUNNER_TEMP "smartkey-windows-standalone-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" if (Test-Path -LiteralPath $stage) { throw "Refusing to reuse staging directory: $stage" } @@ -121,12 +139,17 @@ jobs: $payload = @( @{ Source = 'target/release/smartkey-register.exe'; Name = 'smartkey-register.exe' }, @{ Source = 'target/release/smartkey_win.dll'; Name = 'smartkey_win.dll' }, - @{ Source = 'crates/smartkey-win/pilot-runtime-manifest.json'; Name = 'pilot-runtime-manifest.json' }, + @{ Source = 'crates/smartkey-win/windows-runtime-manifest.json'; Name = 'windows-runtime-manifest.json' }, @{ Source = 'config/smartkey.json'; Name = 'smartkey.json' }, @{ Source = 'corpus/corpus_en.json'; Name = 'corpus_en.json' }, @{ Source = 'corpus/corpus_bg.json'; Name = 'corpus_bg.json' }, @{ Source = 'corpus/corpus_tech.json'; Name = 'corpus_tech.json' }, - @{ Source = 'crates/smartkey-win/tests/windows_pilot_manual.md'; Name = 'PILOT_README.md' }, + @{ Source = 'crates/smartkey-win/packaging/Install-SmartKey.cmd'; Name = 'Install-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Status-SmartKey.cmd'; Name = 'Status-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Enable-SmartKey.cmd'; Name = 'Enable-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Disable-SmartKey.cmd'; Name = 'Disable-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Uninstall-SmartKey.cmd'; Name = 'Uninstall-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/README-WINDOWS.md'; Name = 'README-WINDOWS.md' }, @{ Source = 'LICENSE'; Name = 'LICENSE' }, @{ Source = 'LICENSE-GPL'; Name = 'LICENSE-GPL' }, @{ Source = 'LICENSE-APACHE'; Name = 'LICENSE-APACHE' } @@ -158,14 +181,67 @@ jobs: if (Compare-Object -ReferenceObject $expected -DifferenceObject $actual) { throw 'Staged payload differs from the exact allowlist.' } - - name: Upload Windows pilot payload + - name: Upload Windows standalone payload uses: actions/upload-artifact@v4 with: - name: smartkey-windows-pilot - path: ${{ runner.temp }}/smartkey-windows-pilot-${{ github.run_id }}-${{ github.run_attempt }} + name: smartkey-windows-standalone + path: ${{ runner.temp }}/smartkey-windows-standalone-${{ github.run_id }}-${{ github.run_attempt }} if-no-files-found: error retention-days: 14 + - name: Check install and reversal as a standard Windows user + timeout-minutes: 5 + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $root = "C:\Users\Public\SmartKeySmoke-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + $name = "SKSmoke$env:GITHUB_RUN_ATTEMPT" + if (Get-LocalUser -Name $name -ErrorAction SilentlyContinue) { throw 'Smoke account already exists' } + $secret = ConvertTo-SecureString ([Guid]::NewGuid().ToString('N') + 'aA!4') -AsPlainText -Force + $credential = [PSCredential]::new("$env:COMPUTERNAME\$name", $secret) + $created = $false + try { + New-LocalUser -Name $name -Password $secret -AccountNeverExpires | Out-Null + $created = $true + Add-LocalGroupMember -Group (Get-LocalGroup -SID 'S-1-5-32-545').Name -Member $name + New-Item -ItemType Directory -Path $root | Out-Null + $stage = Join-Path $env:RUNNER_TEMP "smartkey-windows-standalone-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + Copy-Item -LiteralPath $stage -Destination (Join-Path $root 'bundle') -Recurse + Copy-Item -LiteralPath 'crates/smartkey-win/packaging/smoke-user.ps1' -Destination $root + & icacls $root /grant "${name}:(OI)(CI)M" /T /Q + if ($LASTEXITCODE -ne 0) { throw 'Cannot grant disposable account its smoke directory' } + $script = Join-Path $root 'smoke-user.ps1' + $bundle = Join-Path $root 'bundle' + $output = Join-Path $root 'user-smoke' + $arguments = "-NoProfile -NonInteractive -File `"$script`" -Bundle `"$bundle`" -OutDir `"$output`"" + $child = Start-Process -FilePath 'powershell.exe' -ArgumentList $arguments -Credential $credential -LoadUserProfile -UseNewEnvironment -PassThru -RedirectStandardOutput (Join-Path $root 'launcher.stdout.txt') -RedirectStandardError (Join-Path $root 'launcher.stderr.txt') + if (-not $child.WaitForExit(180000)) { + & taskkill /PID $child.Id /T /F + throw 'Standard-user smoke exceeded three minutes' + } + $child.Refresh() + Get-Content -LiteralPath (Join-Path $root 'launcher.stdout.txt') + Get-Content -LiteralPath (Join-Path $root 'launcher.stderr.txt') + if (Test-Path -LiteralPath $output) { + Get-ChildItem -LiteralPath $output -File | ForEach-Object { Get-Content -LiteralPath $_.FullName } + } + if ($child.ExitCode -ne 0) { throw "Standard-user smoke failed: $($child.ExitCode)" } + $receipt = Get-Content -LiteralPath (Join-Path $output 'smoke-result.json') -Raw | ConvertFrom-Json + if ($receipt.status -ne 'PASS_NATIVE_STANDARD_USER_MAINTENANCE' -or -not $receipt.standard_nonadmin) { + throw 'Missing successful standard-user receipt' + } + } finally { + if ($created) { Remove-LocalUser -Name $name } + } + - name: Retain native standard-user result + if: always() + uses: actions/upload-artifact@v4 + with: + name: smartkey-windows-standard-user-result + path: C:/Users/Public/SmartKeySmoke-${{ github.run_id }}-${{ github.run_attempt }} + if-no-files-found: warn + retention-days: 14 + build-macos: name: Build (macOS) runs-on: macos-latest diff --git a/crates/smartkey-win/Cargo.toml b/crates/smartkey-win/Cargo.toml index b08aa64..a8485aa 100644 --- a/crates/smartkey-win/Cargo.toml +++ b/crates/smartkey-win/Cargo.toml @@ -17,6 +17,7 @@ log = { workspace = true } windows-core = "0.58" windows = { version = "0.58", features = [ "Win32_UI_TextServices", + "Win32_UI_WindowsAndMessaging", "Win32_System_Com", "Win32_Foundation", "Win32_UI_Input_KeyboardAndMouse", diff --git a/crates/smartkey-win/packaging/Disable-SmartKey.cmd b/crates/smartkey-win/packaging/Disable-SmartKey.cmd new file mode 100644 index 0000000..26c6938 --- /dev/null +++ b/crates/smartkey-win/packaging/Disable-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%LOCALAPPDATA%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" ( + echo SmartKey helper is missing. Extract the whole SmartKey archive first. + pause + exit /b 1 +) +"%SMARTKEY_HELPER%" --disable +if errorlevel 1 ( + echo SmartKey could not complete the action. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/Enable-SmartKey.cmd b/crates/smartkey-win/packaging/Enable-SmartKey.cmd new file mode 100644 index 0000000..c8b5da6 --- /dev/null +++ b/crates/smartkey-win/packaging/Enable-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%LOCALAPPDATA%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" ( + echo SmartKey helper is missing. Extract the whole SmartKey archive first. + pause + exit /b 1 +) +"%SMARTKEY_HELPER%" --enable +if errorlevel 1 ( + echo SmartKey could not complete the action. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/Install-SmartKey.cmd b/crates/smartkey-win/packaging/Install-SmartKey.cmd new file mode 100644 index 0000000..e612f3b --- /dev/null +++ b/crates/smartkey-win/packaging/Install-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%LOCALAPPDATA%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" ( + echo SmartKey helper is missing. Extract the whole SmartKey archive first. + pause + exit /b 1 +) +"%SMARTKEY_HELPER%" --install +if errorlevel 1 ( + echo SmartKey could not complete the action. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/README-WINDOWS.md b/crates/smartkey-win/packaging/README-WINDOWS.md new file mode 100644 index 0000000..462711c --- /dev/null +++ b/crates/smartkey-win/packaging/README-WINDOWS.md @@ -0,0 +1,20 @@ +# SmartKey for Windows + +This folder contains the Windows application and public English/Bulgarian dictionaries. You do not need Git, Python, Rust or a repository checkout. Use the x64 bundle on Windows 10/11 x64 on a machine where you are allowed to install software. + +Extract the entire ZIP, then double-click **Install-SmartKey.cmd**. The visible result window reports success or the exact failed operation. Installation uses your account and does not request administrator elevation. If Windows or workplace policy refuses installation, the error remains visible; ask your administrator rather than bypassing that policy. + +The installer copies the program to `%LOCALAPPDATA%\SmartKey`, and copies missing public dictionaries and starter configuration to `%APPDATA%\smartkey`. It preserves existing configuration, customized dictionaries and personal data. Keep the whole ZIP for repair or installation on another permitted machine. + +After installation, press **Win+Space** and choose **SmartKey**. Press **Win+Space** again to return to your normal keyboard whenever you want. Installation does not replace your existing layouts or change your default keyboard. Open a new text application if an application already running does not show the new choice. + +SmartKey availability is enabled at Windows login through one current-user login entry. Start menu → **SmartKey** has: + +- **Status-SmartKey** — checks the installed profile and binary location. +- **Disable-SmartKey** — disables SmartKey and removes its login entry; your ordinary keyboards and personal data remain. +- **Enable-SmartKey** — enables SmartKey and its login entry again; select it with Win+Space. +- **Uninstall-SmartKey** — removes SmartKey registration and its login entry, then deletes the installed EXE/DLL. Personal data remains in `%APPDATA%\smartkey`. + +Close applications using SmartKey before updating or uninstalling. If a file is still in use, removal reports the remaining file instead of claiming that it was deleted. After registration is removed you may delete the remaining `%LOCALAPPDATA%\SmartKey` support folder. Personal data is kept separately. + +No telemetry, network download, scheduled task or Windows service is installed. This package's build/registration checks do not replace validation of actual typing in your target applications. diff --git a/crates/smartkey-win/packaging/Status-SmartKey.cmd b/crates/smartkey-win/packaging/Status-SmartKey.cmd new file mode 100644 index 0000000..a77052f --- /dev/null +++ b/crates/smartkey-win/packaging/Status-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%LOCALAPPDATA%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" ( + echo SmartKey helper is missing. Extract the whole SmartKey archive first. + pause + exit /b 1 +) +"%SMARTKEY_HELPER%" --status +if errorlevel 1 ( + echo SmartKey could not complete the action. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/Uninstall-SmartKey.cmd b/crates/smartkey-win/packaging/Uninstall-SmartKey.cmd new file mode 100644 index 0000000..d61a362 --- /dev/null +++ b/crates/smartkey-win/packaging/Uninstall-SmartKey.cmd @@ -0,0 +1,33 @@ +@echo off +setlocal +set "SMARTKEY_HELPER=%LOCALAPPDATA%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" ( + echo SmartKey helper is missing; registration removal was not attempted. + pause + exit /b 1 +) +"%SMARTKEY_HELPER%" --uninstall +if errorlevel 1 ( + echo Removal was incomplete. Staged files have been retained so you can retry. + pause + exit /b 1 +) +rem Delete only the installed SmartKey binaries, after the helper has exited. +del /q "%LOCALAPPDATA%\SmartKey\smartkey_win.dll" "%LOCALAPPDATA%\SmartKey\smartkey-register.exe" 2>nul +if exist "%LOCALAPPDATA%\SmartKey\smartkey_win.dll" ( + echo Registration removed. Close apps using SmartKey before deleting the remaining DLL. + pause + exit /b 1 +) +if exist "%LOCALAPPDATA%\SmartKey\smartkey-register.exe" ( + echo Registration removed. The helper file could not be deleted; remove it after closing it. + pause + exit /b 1 +) +echo SmartKey removed. Your keyboards and AppData\smartkey personal data were preserved. +rem The final parsed block can remove this Start menu command after all work. +( + del /q "%APPDATA%\Microsoft\Windows\Start Menu\Programs\SmartKey\Uninstall-SmartKey.cmd" 2>nul + exit /b 0 +) diff --git a/crates/smartkey-win/packaging/smoke-user.ps1 b/crates/smartkey-win/packaging/smoke-user.ps1 new file mode 100644 index 0000000..5415326 --- /dev/null +++ b/crates/smartkey-win/packaging/smoke-user.ps1 @@ -0,0 +1,150 @@ +# One bounded native maintenance smoke. Run ONLY in an ephemeral standard account. +# The parent CI job supplies/loads that user's profile; this script never elevates. +[CmdletBinding()] +param( + [Parameter(Mandatory=$true)][string]$Bundle, + [Parameter(Mandatory=$true)][string]$OutDir +) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +$identity = [Security.Principal.WindowsIdentity]::GetCurrent() +$principal = New-Object Security.Principal.WindowsPrincipal($identity) +$adminSid = 'S-1-5-32-544' +if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -or + @($identity.Groups | Where-Object { $_.Value -eq $adminSid }).Count -ne 0) { + throw 'Refusing smoke: this must be a standard NONADMIN account, not an elevated or split-token administrator.' +} +if (-not $env:LOCALAPPDATA -or -not $env:APPDATA -or -not $env:USERPROFILE) { + throw 'The standard user profile must be loaded (APPDATA, LOCALAPPDATA, USERPROFILE required).' +} +# Credential launchers can inherit the administrator's environment even when +# the token/profile is correct. Cross-check actual SID profile + shell folders +# before constructing any destination, and fail rather than touching that home. +$profileKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey( + 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\' + $identity.User.Value) +if ($null -eq $profileKey) { throw 'No loaded Windows profile is registered for the current standard-user SID.' } +try { $actualProfile = [Environment]::ExpandEnvironmentVariables([string]$profileKey.GetValue('ProfileImagePath', $null)) } +finally { $profileKey.Dispose() } +$actualLocal = [Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData) +$actualRoaming = [Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData) +foreach ($pair in @(@($env:USERPROFILE, $actualProfile), @($env:LOCALAPPDATA, $actualLocal), @($env:APPDATA, $actualRoaming))) { + if (-not $pair[1] -or -not [string]::Equals( + [IO.Path]::GetFullPath($pair[0]).TrimEnd('\'), + [IO.Path]::GetFullPath($pair[1]).TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase)) { + throw 'Inherited USERPROFILE/APPDATA/LOCALAPPDATA does not match the actual standard-user profile. The parent must supply the correct user environment.' + } +} +$bundlePath = (Resolve-Path -LiteralPath $Bundle).Path +$install = Join-Path $env:LOCALAPPDATA 'SmartKey' +$data = Join-Path $env:APPDATA 'smartkey' +$run = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' +$clsid = 'HKCU:\SOFTWARE\Classes\CLSID\{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' +$tip = 'HKCU:\Software\Microsoft\CTF\TIP\{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' +$menu = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\SmartKey' +New-Item -ItemType Directory -Path $OutDir -Force | Out-Null + +function Assert-True([bool]$condition, [string]$message) { + if (-not $condition) { throw $message } +} +function Get-Login { + if (-not (Test-Path -LiteralPath $run)) { return $null } + return (Get-Item -LiteralPath $run).GetValue('SmartKey', $null) +} +function Keyboard-Snapshot { + # Only the ephemeral account is read. The receipt reports equality, not values. + $snapshot = [ordered]@{} + foreach ($name in @('Keyboard Layout\Preload', 'Keyboard Layout\Substitutes')) { + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($name) + $values = [ordered]@{} + if ($null -ne $key) { + try { foreach ($value in @($key.GetValueNames() | Sort-Object)) { $values[$value] = $key.GetValue($value) } } + finally { $key.Dispose() } + } + $snapshot[$name] = $values + } + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Control Panel\International\User Profile') + try { + $snapshot['InputMethodOverride'] = if ($null -ne $key) { $key.GetValue('InputMethodOverride', $null) } else { $null } + $snapshot['DefaultInputMethodOverride'] = if ($null -ne $key) { $key.GetValue('DefaultInputMethodOverride', $null) } else { $null } + } + finally { if ($null -ne $key) { $key.Dispose() } } + $default = Get-WinDefaultInputMethodOverride + $snapshot['WindowsDefaultInputTip'] = if ($null -ne $default) { $default.InputTip } else { $null } + return ($snapshot | ConvertTo-Json -Depth 4 -Compress) +} +$steps = New-Object System.Collections.Generic.List[object] +function Invoke-Helper([string]$exe, [string]$action) { + $stem = $action.TrimStart('-') + $stdout = Join-Path $OutDir "$stem.stdout.txt" + $stderr = Join-Path $OutDir "$stem.stderr.txt" + $process = Start-Process -FilePath $exe -ArgumentList @($action, '--no-dialog') -PassThru -NoNewWindow -RedirectStandardOutput $stdout -RedirectStandardError $stderr + if (-not $process.WaitForExit(45000)) { + $process.Kill() + $process.WaitForExit() + throw "$action exceeded 45 seconds; the smoke stopped." + } + $process.Refresh() + $steps.Add([ordered]@{ action=$action; exit_code=$process.ExitCode }) + if ($process.ExitCode -ne 0) { + # Exact helper HRESULT/error is retained as the failed native evidence. + throw "$action failed (exit $($process.ExitCode)); see $stderr." + } +} +$receipt = [ordered]@{ + status='NOT_RUN'; standard_nonadmin=$true; current_user_profile_confirmed=$true; no_dialog=$true + typing_exercised=$false; logon_exercised=$false + steps=$steps; keyboard_defaults_preserved=$false; personal_sentinel_preserved=$false +} +$before = Keyboard-Snapshot +try { + # Never use a daily account or delete a prior installation for this smoke. + Assert-True (-not (Test-Path -LiteralPath $install)) 'The ephemeral user already has a SmartKey install folder.' + Assert-True (-not (Test-Path -LiteralPath $data)) 'The ephemeral user already has SmartKey data.' + Assert-True (-not (Test-Path -LiteralPath $clsid)) 'The ephemeral user already has SmartKey COM registration.' + Assert-True ($null -eq (Get-Login)) 'An existing SmartKey Run value must not be overwritten by this smoke.' + New-Item -ItemType Directory -Path $data | Out-Null + $personal = Join-Path $data 'personal.json' + [IO.File]::WriteAllText($personal, '{"synthetic_smoke_sentinel":true}') + $personalHash = (Get-FileHash -LiteralPath $personal -Algorithm SHA256).Hash + + Invoke-Helper (Join-Path $bundlePath 'smartkey-register.exe') '--install' + $helper = Join-Path $install 'smartkey-register.exe' + foreach ($name in @('smartkey-register.exe','smartkey_win.dll','Install-SmartKey.cmd','Status-SmartKey.cmd','Enable-SmartKey.cmd','Disable-SmartKey.cmd','Uninstall-SmartKey.cmd')) { + Assert-True (Test-Path -LiteralPath (Join-Path $install $name) -PathType Leaf) "Missing staged file: $name" + } + foreach ($name in @('smartkey.json','corpus_en.json','corpus_bg.json','corpus_tech.json')) { + Assert-True (Test-Path -LiteralPath (Join-Path $data $name) -PathType Leaf) "Missing runtime data: $name" + } + foreach ($name in @('Status-SmartKey.cmd','Enable-SmartKey.cmd','Disable-SmartKey.cmd','Uninstall-SmartKey.cmd')) { + Assert-True (Test-Path -LiteralPath (Join-Path $menu $name) -PathType Leaf) "Missing Start menu command: $name" + } + Assert-True ((Get-Login) -eq ('"' + $helper + '" --login')) 'Login entry does not identify the stable installed helper.' + Assert-True ((Keyboard-Snapshot) -eq $before) 'Installation changed existing keyboard/default settings.' + Invoke-Helper $helper '--status' + Invoke-Helper $helper '--disable' + Assert-True ($null -eq (Get-Login)) 'Disable left the owned login entry.' + Assert-True ((Keyboard-Snapshot) -eq $before) 'Disable changed existing keyboard/default settings.' + Invoke-Helper $helper '--enable' + Assert-True ((Get-Login) -eq ('"' + $helper + '" --login')) 'Enable did not restore the exact owned login entry.' + Invoke-Helper $helper '--uninstall' + Assert-True ($null -eq (Get-Login)) 'Uninstall left the owned login entry.' + Assert-True (-not (Test-Path -LiteralPath $clsid)) 'Uninstall left own HKCU COM registration.' + Assert-True (-not (Test-Path -LiteralPath $tip)) 'Uninstall left own HKCU TIP registration.' + Assert-True ((Keyboard-Snapshot) -eq $before) 'Maintenance changed existing keyboard/default settings.' + Assert-True ((Get-FileHash -LiteralPath $personal -Algorithm SHA256).Hash -eq $personalHash) 'Maintenance changed the synthetic personal file.' + # The EXE API uninstalls integration; the user-facing CMD performs file + # removal afterwards. Mirror only that exact binary deletion here. + Remove-Item -LiteralPath (Join-Path $install 'smartkey_win.dll'), $helper + Assert-True (-not (Test-Path -LiteralPath $helper)) 'Helper binary remains.' + Assert-True (-not (Test-Path -LiteralPath (Join-Path $install 'smartkey_win.dll'))) 'DLL remains.' + $receipt['keyboard_defaults_preserved']=$true + $receipt['personal_sentinel_preserved']=$true + $receipt['status']='PASS_NATIVE_STANDARD_USER_MAINTENANCE' +} catch { + $receipt['status']='FAIL_NATIVE_STANDARD_USER_MAINTENANCE' + $receipt['error']=$_.Exception.Message + throw +} finally { + $receipt | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $OutDir 'smoke-result.json') -Encoding UTF8 +} diff --git a/crates/smartkey-win/packaging/user_setup.rs b/crates/smartkey-win/packaging/user_setup.rs new file mode 100644 index 0000000..73d7a93 --- /dev/null +++ b/crates/smartkey-win/packaging/user_setup.rs @@ -0,0 +1,137 @@ +//! Filesystem-only staging, shared by the installer and portable tests. +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +pub const BINARIES: &[&str] = &["smartkey-register.exe", "smartkey_win.dll"]; +pub const DATA: &[&str] = &[ + "smartkey.json", + "corpus_en.json", + "corpus_bg.json", + "corpus_tech.json", +]; +pub const SUPPORT: &[&str] = &[ + "Install-SmartKey.cmd", + "Status-SmartKey.cmd", + "Enable-SmartKey.cmd", + "Disable-SmartKey.cmd", + "Uninstall-SmartKey.cmd", + "README-WINDOWS.md", + "LICENSE", + "LICENSE-GPL", + "LICENSE-APACHE", +]; + +/// Validate the entire distribution before touching the destination. Existing +/// configuration, public corpus customizations and personal files are retained. +pub fn stage(bundle: &Path, install: &Path, data: &Path) -> io::Result { + for name in BINARIES.iter().chain(DATA).chain(SUPPORT) { + let path = bundle.join(name); + if !path.is_file() || fs::metadata(&path)?.len() == 0 { + return Err(io::Error::new( + io::ErrorKind::NotFound, + format!("Incomplete SmartKey bundle: {name}. Extract the whole archive first."), + )); + } + } + fs::create_dir_all(install)?; + fs::create_dir_all(data)?; + for name in BINARIES.iter().chain(SUPPORT).chain(DATA) { + let from = bundle.join(name); + let to = install.join(name); + // Running the installed helper again must not overwrite itself. + if from.canonicalize()? != to.canonicalize().unwrap_or_else(|_| to.clone()) { + fs::copy(from, to)?; + } + } + for name in DATA { + let to = data.join(name); + if !to.exists() { + // create_new prevents racing another installer or user editor. + let mut destination = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(to)?; + let mut source = fs::File::open(bundle.join(name))?; + io::copy(&mut source, &mut destination)?; + } + } + Ok(install.join("smartkey-register.exe")) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + static SEQUENCE: AtomicUsize = AtomicUsize::new(0); + struct Scratch(PathBuf); + impl Scratch { + fn new() -> Self { + let p = std::env::temp_dir().join(format!( + "smartkey-stage-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&p).unwrap(); + Self(p) + } + fn bundle(&self) -> PathBuf { + let p = self.0.join("bundle with spaces"); + fs::create_dir(&p).unwrap(); + for name in BINARIES.iter().chain(DATA).chain(SUPPORT) { + fs::write(p.join(name), format!("public bundle {name}")).unwrap(); + } + p + } + } + impl Drop for Scratch { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } + } + #[test] + fn stages_binaries_and_missing_data_but_preserves_user_files() { + let s = Scratch::new(); + let bundle = s.bundle(); + let install = s.0.join("Local/SmartKey"); + let data = s.0.join("Roaming/smartkey"); + fs::create_dir_all(&data).unwrap(); + fs::write(data.join("smartkey.json"), "existing user config").unwrap(); + fs::write(data.join("personal.json"), "existing personal data").unwrap(); + fs::write(data.join("corpus_en.json"), "custom corpus").unwrap(); + assert_eq!( + stage(&bundle, &install, &data).unwrap(), + install.join("smartkey-register.exe") + ); + assert_eq!( + fs::read(data.join("smartkey.json")).unwrap(), + b"existing user config" + ); + assert_eq!( + fs::read(data.join("personal.json")).unwrap(), + b"existing personal data" + ); + assert_eq!( + fs::read(data.join("corpus_en.json")).unwrap(), + b"custom corpus" + ); + assert_eq!( + fs::read(install.join("smartkey_win.dll")).unwrap(), + fs::read(bundle.join("smartkey_win.dll")).unwrap() + ); + assert!(data.join("corpus_bg.json").is_file()); + // Reinstall is allowed from both distribution and installed location. + stage(&bundle, &install, &data).unwrap(); + stage(&install, &install, &data).unwrap(); + } + #[test] + fn missing_payload_refuses_before_destination_changes() { + let s = Scratch::new(); + let bundle = s.bundle(); + fs::remove_file(bundle.join("smartkey_win.dll")).unwrap(); + let install = s.0.join("install"); + let data = s.0.join("data"); + assert!(stage(&bundle, &install, &data).is_err()); + assert!(!install.exists() && !data.exists()); + } +} diff --git a/crates/smartkey-win/src/display.rs b/crates/smartkey-win/src/display.rs index 60273ec..cf2cd78 100644 --- a/crates/smartkey-win/src/display.rs +++ b/crates/smartkey-win/src/display.rs @@ -76,6 +76,12 @@ pub struct SingleItemEnum { yielded: std::cell::Cell, } +impl Default for SingleItemEnum { + fn default() -> Self { + Self::new() + } +} + impl SingleItemEnum { pub fn new() -> Self { Self { diff --git a/crates/smartkey-win/src/edit_session.rs b/crates/smartkey-win/src/edit_session.rs index a753bd4..c79ea1a 100644 --- a/crates/smartkey-win/src/edit_session.rs +++ b/crates/smartkey-win/src/edit_session.rs @@ -1,11 +1,4 @@ -// TSF Edit Session — executes text operations within a granted edit cookie. -// -// TSF requires all text modifications to go through ITfEditSession::DoEditSession(). -// The framework calls back with an `ec` (edit cookie) that grants write access. -// -// Architecture: Single SmartKeyEditSession with EditOp enum instead of 3 COM classes. -// Rationale: 3 operations don't justify 3 COM classes; one struct reduces COM lifetime bugs. - +// Text operations run only inside the edit cookie granted by TSF. use std::cell::RefCell; use std::mem::ManuallyDrop; use std::rc::Rc; @@ -14,203 +7,235 @@ use windows::core::*; use windows::Win32::Foundation::*; use windows::Win32::UI::TextServices::*; -/// The operation to perform inside the edit session. pub enum EditOp { - /// Display ghost text as a TSF composition. ShowGhost { text: String, + /// Zero for a suffix-only ghost; typed-prefix UTF-16 length for preedit. + typed_units: usize, composition: Rc>>, - /// Composition sink to receive OnCompositionTerminated callbacks. comp_sink: ITfCompositionSink, - /// TfGuidAtom for ghost display attribute (grey styling). 0 = no styling. ghost_attr_atom: u32, }, - /// Remove ghost text and end the composition. HideGhost { composition: Rc>>, }, - /// Commit (finalize) text into the document. CommitText { text: String, composition: Rc>>, }, + ReplaceWord { + replace_len: usize, + text: String, + composition: Rc>>, + }, } -/// A one-shot edit session that executes a single EditOp. #[implement(ITfEditSession)] pub struct SmartKeyEditSession { context: ITfContext, - #[allow(dead_code)] // reserved for display attribute operations - client_id: u32, op: EditOp, } -impl SmartKeyEditSession { - pub fn new(context: ITfContext, client_id: u32, op: EditOp) -> Self { - Self { - context, - client_id, - op, - } - } -} - impl ITfEditSession_Impl for SmartKeyEditSession_Impl { fn DoEditSession(&self, ec: u32) -> Result<()> { match &self.op { EditOp::ShowGhost { text, + typed_units, composition, comp_sink, ghost_attr_atom, - } => self.do_show_ghost(ec, text, composition, comp_sink, *ghost_attr_atom), - EditOp::HideGhost { composition } => self.do_hide_ghost(ec, composition), - EditOp::CommitText { text, composition } => self.do_commit_text(ec, text, composition), + } => self.show( + ec, + text, + *typed_units, + composition, + comp_sink, + *ghost_attr_atom, + ), + EditOp::HideGhost { composition } => self.hide(ec, composition), + EditOp::CommitText { text, composition } => { + // CommitText is an exact insertion, including partial Right acceptance. + self.hide(ec, composition)?; + self.insert(ec, text) + } + EditOp::ReplaceWord { + replace_len, + text, + composition, + } => { + self.hide(ec, composition)?; + self.replace(ec, *replace_len, text) + } } } } impl SmartKeyEditSession_Impl { - /// Show or update ghost text via a TSF composition. - /// - /// After inserting/updating ghost text, the selection (caret) is moved to the - /// START of the ghost range so that forwarded keys are inserted before the ghost. - fn do_show_ghost( + fn own_range(&self, active: &ITfComposition) -> Result { + unsafe { + let range = active.GetRange()?; + if range.GetContext()? != self.context { + return Err(Error::from_hresult(E_INVALIDARG)); + } + Ok(range) + } + } + + fn show( &self, ec: u32, text: &str, + typed_units: usize, composition: &Rc>>, comp_sink: &ITfCompositionSink, - ghost_attr_atom: u32, + atom: u32, ) -> Result<()> { - let text_utf16: Vec = text.encode_utf16().collect(); - let mut comp = composition.borrow_mut(); - - if let Some(ref active) = *comp { - // Update existing composition range. - unsafe { - let range = active.GetRange()?; - range.SetText(ec, 0, &text_utf16)?; - // Re-apply attribute after SetText (SetText clears properties). - self.apply_ghost_attr(ec, &range, ghost_attr_atom)?; - self.set_caret_to_range_start(ec, &range)?; - } - } else { - // Start a new composition. - unsafe { + let utf16: Vec = text.encode_utf16().collect(); + let offset = i32::try_from(typed_units).map_err(|_| Error::from_hresult(E_INVALIDARG))?; + if typed_units > utf16.len() { + return Err(Error::from_hresult(E_INVALIDARG)); + } + // Never retain a RefCell borrow across COM: callbacks can reenter the sink. + let active = composition.borrow().clone(); + unsafe { + let range = if let Some(active) = active { + let range = self.own_range(&active)?; + range.SetText(ec, 0, &utf16)?; + range + } else { let insert: ITfInsertAtSelection = self.context.cast()?; - let range = insert.InsertTextAtSelection(ec, TF_IAS_NOQUERY, &text_utf16)?; - + let range = insert.InsertTextAtSelection(ec, TF_IAS_NOQUERY, &utf16)?; let ctx_comp: ITfContextComposition = self.context.cast()?; let new_comp = ctx_comp.StartComposition(ec, &range, Some(comp_sink))?; - *comp = Some(new_comp); + *composition.borrow_mut() = Some(new_comp); + range + }; + let prop = self.context.GetProperty(&GUID_PROP_ATTRIBUTE)?; + prop.Clear(ec, &range)?; + if atom != 0 && typed_units < utf16.len() { + let ghost = range.Clone()?; + let mut shifted = 0; + ghost.ShiftStart(ec, offset, &mut shifted, std::ptr::null())?; + if shifted != offset { + return Err(Error::from_hresult(E_FAIL)); + } + prop.SetValue(ec, &ghost, &VARIANT::from(atom as i32))?; + } + let caret = range.Clone()?; + caret.Collapse(ec, TF_ANCHOR_START)?; + let mut shifted = 0; + caret.ShiftEnd(ec, offset, &mut shifted, std::ptr::null())?; + if shifted != offset { + return Err(Error::from_hresult(E_FAIL)); + } + caret.Collapse(ec, TF_ANCHOR_END)?; + self.select(ec, caret) + } + } - self.apply_ghost_attr(ec, &range, ghost_attr_atom)?; - self.set_caret_to_range_start(ec, &range)?; + fn hide(&self, ec: u32, composition: &Rc>>) -> Result<()> { + let active = composition.borrow().clone(); + if let Some(active) = active { + let range = self.own_range(&active)?; + // Clear the slot before EndComposition so our own callback cannot reset + // the core state that has already generated the remaining action batch. + unsafe { + // A refused deletion must keep ownership of the surviving preedit. + range.SetText(ec, 0, &[])?; + composition.borrow_mut().take(); + if let Err(error) = active.EndComposition(ec) { + *composition.borrow_mut() = Some(active); + return Err(error); + } } } Ok(()) } - /// Set GUID_PROP_ATTRIBUTE on a range to apply ghost text styling (grey). - /// - /// The atom is a TfGuidAtom obtained from ITfCategoryMgr::RegisterGUID. - /// TSF resolves it back through our ITfDisplayAttributeProvider to get - /// the actual TF_DISPLAYATTRIBUTE (grey foreground). - fn apply_ghost_attr(&self, ec: u32, range: &ITfRange, atom: u32) -> Result<()> { - if atom == 0 { + fn insert(&self, ec: u32, text: &str) -> Result<()> { + if text.is_empty() { return Ok(()); } unsafe { - let prop = self.context.GetProperty(&GUID_PROP_ATTRIBUTE)?; - let variant = VARIANT::from(atom as i32); - prop.SetValue(ec, range, &variant)?; + let insert: ITfInsertAtSelection = self.context.cast()?; + let range = insert.InsertTextAtSelection( + ec, + TF_IAS_NOQUERY, + &text.encode_utf16().collect::>(), + )?; + let caret = range.Clone()?; + caret.Collapse(ec, TF_ANCHOR_END)?; + self.select(ec, caret) } - Ok(()) } - /// Remove ghost text and end the active composition. - fn do_hide_ghost( - &self, - ec: u32, - composition: &Rc>>, - ) -> Result<()> { - let mut comp = composition.borrow_mut(); - if let Some(active) = comp.take() { - unsafe { - // Clear the composition text before ending. - let range = active.GetRange()?; - range.SetText(ec, 0, &[])?; - active.EndComposition(ec)?; - } - } - Ok(()) - } - - /// Commit text: end the ghost composition so the suffix becomes permanent. - /// - /// When a ghost composition is active, the typed prefix is already in the - /// document (via ForwardKey) and the ghost suffix is in the composition range. - /// EndComposition makes the suffix permanent — no text replacement needed. - /// The `text` parameter is only used when there's no active composition - /// (e.g. direct commit without prior ghost). - fn do_commit_text( - &self, - ec: u32, - text: &str, - composition: &Rc>>, - ) -> Result<()> { - let mut comp = composition.borrow_mut(); - if let Some(active) = comp.take() { - unsafe { - // Ghost suffix is already in the document. Just finalize it. - active.EndComposition(ec)?; + fn replace(&self, ec: u32, count: usize, text: &str) -> Result<()> { + let lookback = count + .checked_mul(2) + .and_then(|n| i32::try_from(n).ok()) + .ok_or_else(|| Error::from_hresult(E_INVALIDARG))?; + unsafe { + let mut selection = [TF_SELECTION::default()]; + let mut fetched = 0; + let result = + self.context + .GetSelection(ec, TF_DEFAULT_SELECTION, &mut selection, &mut fetched); + let caret = ManuallyDrop::take(&mut selection[0].range); + result?; + let caret = caret + .filter(|_| fetched == 1) + .ok_or_else(|| Error::from_hresult(E_FAIL))?; + if !caret.IsEmpty(ec)?.as_bool() { + return Err(Error::from_hresult(E_INVALIDARG)); } - } else { - // No active composition — insert the full text at selection. - let text_utf16: Vec = text.encode_utf16().collect(); - unsafe { - let insert: ITfInsertAtSelection = self.context.cast()?; - insert.InsertTextAtSelection(ec, TF_IAS_NOQUERY, &text_utf16)?; + let previous = caret.Clone()?; + let mut shifted = 0; + previous.ShiftStart(ec, -lookback, &mut shifted, std::ptr::null())?; + let mut buffer = vec![0u16; lookback as usize]; + let mut read = 0; + previous.GetText(ec, 0, &mut buffer, &mut read)?; + buffer.truncate(read as usize); + let units = crate::text_contract::suffix_units(&buffer, count) + .ok_or_else(|| Error::from_hresult(E_INVALIDARG))?; + let replacement = caret.Clone()?; + let requested = -(units as i32); + replacement.ShiftStart(ec, requested, &mut shifted, std::ptr::null())?; + if shifted != requested { + return Err(Error::from_hresult(E_FAIL)); } + replacement.SetText(ec, 0, &text.encode_utf16().collect::>())?; + replacement.Collapse(ec, TF_ANCHOR_END)?; + self.select(ec, replacement) } - Ok(()) } - /// Move the caret (selection) to the start of the given range. - /// - /// This ensures forwarded keys are inserted before the ghost text, not after. - unsafe fn set_caret_to_range_start(&self, ec: u32, range: &ITfRange) -> Result<()> { - let caret = range.Clone()?; - caret.Collapse(ec, TF_ANCHOR_START)?; - - let selection = TF_SELECTION { + fn select(&self, ec: u32, caret: ITfRange) -> Result<()> { + let mut selection = [TF_SELECTION { range: ManuallyDrop::new(Some(caret)), style: TF_SELECTIONSTYLE { ase: TF_AE_END, fInterimChar: BOOL(0), }, - }; - self.context.SetSelection(ec, &[selection])?; - Ok(()) + }]; + unsafe { + let result = self.context.SetSelection(ec, &selection); + ManuallyDrop::drop(&mut selection[0].range); + result + } } } -// -- Public helper to request an edit session from outside --------------- - -/// Request a synchronous edit session on the given context. -/// -/// Creates a `SmartKeyEditSession` with the specified operation and asks TSF -/// to execute it. Returns Ok(()) if the session completed successfully. -/// -/// # Safety -/// Must be called from a TSF key event handler (OnKeyDown) for TF_ES_SYNC -/// to succeed — TSF only grants synchronous sessions during key callbacks. +/// Synchronous write sessions are requested only from TSF key callbacks. pub fn request_edit_session(context: &ITfContext, client_id: u32, op: EditOp) -> Result<()> { - let session: ITfEditSession = SmartKeyEditSession::new(context.clone(), client_id, op).into(); - - let hr = - unsafe { context.RequestEditSession(client_id, &session, TF_ES_READWRITE | TF_ES_SYNC)? }; - - hr.ok() + let session: ITfEditSession = SmartKeyEditSession { + context: context.clone(), + op, + } + .into(); + unsafe { + context + .RequestEditSession(client_id, &session, TF_ES_READWRITE | TF_ES_SYNC)? + .ok() + } } diff --git a/crates/smartkey-win/src/lib.rs b/crates/smartkey-win/src/lib.rs index fed2a0e..7b590f6 100644 --- a/crates/smartkey-win/src/lib.rs +++ b/crates/smartkey-win/src/lib.rs @@ -19,6 +19,8 @@ pub mod dll; mod edit_session; #[cfg(windows)] pub mod registration; +#[cfg(any(windows, test))] +mod text_contract; #[cfg(windows)] mod tsf; diff --git a/crates/smartkey-win/src/register.rs b/crates/smartkey-win/src/register.rs index fc68a37..4ee05c0 100644 --- a/crates/smartkey-win/src/register.rs +++ b/crates/smartkey-win/src/register.rs @@ -1,95 +1,291 @@ -// COM/TSF registration helper for SmartKey Windows IME. -// -// Usage: -// smartkey-register.exe --install Register as a TSF Text Input Processor -// smartkey-register.exe --uninstall Remove registration +//! Visible current-user setup and maintenance for a self-contained bundle. +#[cfg(windows)] +#[path = "../packaging/user_setup.rs"] +mod user_setup; fn main() { - let args: Vec = std::env::args().collect(); - - match args.get(1).map(|s| s.as_str()) { - Some("--install") => { - println!("SmartKey IME registration"); - println!("CLSID: {{{}}}", smartkey_win::config::CLSID_SMARTKEY_STR); - - #[cfg(windows)] - { - let dll_path = find_dll_path(); - println!("DLL: {dll_path}"); - - init_com(); - match smartkey_win::registration::register(&dll_path) { - Ok(system_wide) => { - if system_wide { - println!("SmartKey IME registered system-wide (HKLM)."); - } else { - println!("SmartKey IME registered per-user (HKCU)."); - } - } - Err(e) => { - log::error!("Registration failed: {e}"); - uninit_com(); - std::process::exit(1); - } + #[cfg(windows)] + { + let arguments: Vec = std::env::args().skip(1).collect(); + let no_dialog = arguments.iter().any(|argument| argument == "--no-dialog"); + let actions: Vec<_> = arguments + .iter() + .filter(|argument| argument.as_str() != "--no-dialog") + .collect(); + let action = actions + .first() + .map_or("--install", |argument| argument.as_str()); + let quiet = no_dialog || action == "--login" || action == "--verify"; + let result = if actions.len() > 1 { + Err("Specify one SmartKey action, optionally followed by --no-dialog.".into()) + } else { + run(action) + }; + match result { + Ok(message) => { + println!("{message}"); + if !quiet { + show(&message, false); } - uninit_com(); } - - #[cfg(not(windows))] - println!("(dry run — not on Windows)"); + Err(message) => { + eprintln!("SmartKey: {message}"); + // Login failures are visible too; a broken install must not + // appear silently successful just because it ran at login. + if !no_dialog && action != "--verify" { + show(&message, true); + } + std::process::exit(1); + } } - Some("--uninstall") => { - println!("Unregistering SmartKey IME..."); + } + #[cfg(not(windows))] + { + eprintln!("SmartKey Windows setup requires Windows 10/11 x64."); + std::process::exit(1); + } +} - #[cfg(windows)] - { - init_com(); - match smartkey_win::registration::unregister() { - Ok(()) => println!("SmartKey IME unregistered successfully."), - Err(e) => { - log::error!("Unregistration failed: {e}"); - uninit_com(); - std::process::exit(1); - } +#[cfg(windows)] +fn run(action: &str) -> Result { + use smartkey_win::registration; + use std::path::PathBuf; + let local = + PathBuf::from(std::env::var_os("LOCALAPPDATA").ok_or("LOCALAPPDATA is unavailable")?); + let roaming = PathBuf::from(std::env::var_os("APPDATA").ok_or("APPDATA is unavailable")?); + let install = local.join("SmartKey"); + let installed_exe = install.join("smartkey-register.exe"); + let expected_dll = install.join("smartkey_win.dll"); + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + let bundle = exe.parent().ok_or("Cannot locate SmartKey bundle")?; + let _com = Com::new()?; + let api_error = |e: windows::core::Error| { + format!("{} (HRESULT 0x{:08X}).\nNo administrator fallback was attempted. Existing keyboards remain available through Win+Space.", e, e.code().0 as u32) + }; + match action { + "--install" => { + user_setup::stage(bundle, &install, &roaming.join("smartkey")) + .map_err(|e| format!("Cannot stage the SmartKey bundle: {e}. Close apps using SmartKey before updating."))?; + let dll = expected_dll + .to_str() + .ok_or("DLL path is not valid Unicode")?; + registration::register(dll).map_err(api_error)?; + // A separate process queries the actual persisted TSF profile. + // A process-local registration cannot pass this check. + let verification = std::process::Command::new(&installed_exe) + .arg("--verify") + .output() + .map_err(|e| format!("Cannot verify in a fresh process: {e}"))?; + if !verification.status.success() { + return Err(format!("Fresh-process SmartKey verification failed.\n{}\nRun Uninstall-SmartKey.cmd to remove any partial registration.", String::from_utf8_lossy(&verification.stderr))); + } + set_login(true, &installed_exe).map_err(api_error)?; + let menu = roaming.join("Microsoft/Windows/Start Menu/Programs/SmartKey"); + std::fs::create_dir_all(&menu).map_err(|e| e.to_string())?; + for name in [ + "Status-SmartKey.cmd", + "Enable-SmartKey.cmd", + "Disable-SmartKey.cmd", + "Uninstall-SmartKey.cmd", + ] { + std::fs::copy(install.join(name), menu.join(name)).map_err(|e| e.to_string())?; + } + Ok("SmartKey installed for this user.\n\nPress Win+Space and select SmartKey. Press Win+Space again to return to your usual keyboard. Your existing layouts and default choice were preserved.\n\nSmartKey is available again at Windows login. Start menu > SmartKey provides Status, Enable, Disable and Uninstall. Existing personal data/configuration were preserved.\n\nOpen a new text app to begin.".into()) + } + "--verify" | "--status" => { + verify_com_path(&expected_dll).map_err(api_error)?; + let enabled = registration::profile_enabled().map_err(api_error)?; + if action == "--verify" && !enabled { + return Err("SmartKey profile exists but is disabled".into()); + } + Ok(format!("SmartKey current-user COM path verified.\nTSF profile: {}.\nBinary folder: {}\nData folder: {}\nUse Win+Space to choose SmartKey or an existing ordinary keyboard.", if enabled { "enabled" } else { "disabled" }, install.display(), roaming.join("smartkey").display())) + } + "--enable" | "--login" => { + verify_com_path(&expected_dll).map_err(api_error)?; + registration::set_user_enabled(true).map_err(api_error)?; + if !registration::profile_enabled().map_err(api_error)? { + return Err("Windows did not enable the SmartKey profile".into()); + } + if action == "--enable" { + set_login(true, &installed_exe).map_err(api_error)?; + } + Ok("SmartKey enabled for this user and available at login. Select it with Win+Space; your default keyboard was preserved.".into()) + } + "--disable" => { + verify_com_path(&expected_dll).map_err(api_error)?; + registration::set_user_enabled(false).map_err(api_error)?; + set_login(false, &installed_exe).map_err(api_error)?; + if registration::profile_enabled().map_err(api_error)? { + return Err("Windows still reports SmartKey enabled".into()); + } + Ok("SmartKey disabled and its login entry removed. Use Win+Space to select your usual keyboard. Enable-SmartKey restores it; personal data is unchanged.".into()) + } + "--uninstall" => { + // Remove only this helper's exact Run value, even if TSF cleanup fails. + let login = set_login(false, &installed_exe).map_err(api_error); + let removal = registration::unregister().map_err(api_error); + login?; + removal?; + let menu = roaming.join("Microsoft/Windows/Start Menu/Programs/SmartKey"); + // Keep the currently running uninstall CMD until its final block. + for name in [ + "Status-SmartKey.cmd", + "Enable-SmartKey.cmd", + "Disable-SmartKey.cmd", + ] { + let path = menu.join(name); + if path.exists() { + std::fs::remove_file(path).map_err(|e| e.to_string())?; } - uninit_com(); } + Ok("SmartKey registration and its login entry were removed. Your ordinary keyboards and personal data remain.\n\nThe Uninstall command removes staged binaries after this window closes. If an app still holds the DLL, close that app and repeat file cleanup. Data/configuration under AppData\\smartkey are preserved.".into()) + } + _ => Err("Use --install, --status, --enable, --disable or --uninstall.".into()), + } +} - #[cfg(not(windows))] - println!("(dry run — not on Windows)"); +#[cfg(windows)] +struct Com; +#[cfg(windows)] +impl Com { + fn new() -> Result { + unsafe { + windows::Win32::System::Com::CoInitializeEx( + None, + windows::Win32::System::Com::COINIT_APARTMENTTHREADED, + ) } - _ => { - log::error!("Usage: smartkey-register [--install | --uninstall]"); - std::process::exit(1); + .ok() + .map_err(|e| format!("COM initialization failed: {e}"))?; + Ok(Self) + } +} +#[cfg(windows)] +impl Drop for Com { + fn drop(&mut self) { + unsafe { + windows::Win32::System::Com::CoUninitialize(); } } } -/// Find the DLL in the same directory as this executable. #[cfg(windows)] -fn find_dll_path() -> String { - let exe = std::env::current_exe().expect("cannot determine exe path"); - let dir = exe.parent().expect("exe has no parent directory"); - dir.join("smartkey_win.dll").to_string_lossy().into_owned() +fn show(message: &str, failed: bool) { + use windows::core::*; + use windows::Win32::UI::WindowsAndMessaging::*; + let text: Vec = message.encode_utf16().chain(Some(0)).collect(); + unsafe { + MessageBoxW( + None, + PCWSTR(text.as_ptr()), + w!("SmartKey"), + MB_OK + | if failed { + MB_ICONERROR + } else { + MB_ICONINFORMATION + }, + ); + } } #[cfg(windows)] -fn init_com() { - let hr = unsafe { - windows::Win32::System::Com::CoInitializeEx( +fn read_value(key: &str, name: Option<&str>) -> windows::core::Result> { + use windows::core::*; + use windows::Win32::Foundation::ERROR_FILE_NOT_FOUND; + use windows::Win32::System::Registry::*; + let key: Vec = key.encode_utf16().chain(Some(0)).collect(); + let name: Option> = name.map(|s| s.encode_utf16().chain(Some(0)).collect()); + let name = name.as_ref().map_or(PCWSTR::null(), |s| PCWSTR(s.as_ptr())); + let mut data = vec![0u16; 32768]; + let mut size = (data.len() * 2) as u32; + let result = unsafe { + RegGetValueW( + HKEY_CURRENT_USER, + PCWSTR(key.as_ptr()), + name, + RRF_RT_REG_SZ, None, - windows::Win32::System::Com::COINIT_APARTMENTTHREADED, + Some(data.as_mut_ptr().cast()), + Some(&mut size), ) }; - if hr.is_err() { - log::error!("COM initialization failed: {hr:?}"); - std::process::exit(1); + if result == ERROR_FILE_NOT_FOUND { + return Ok(None); + } + if result.0 != 0 { + return Err(Error::from(HRESULT::from_win32(result.0))); } + let length = data.iter().position(|&v| v == 0).unwrap_or(data.len()); + Ok(Some(String::from_utf16_lossy(&data[..length]))) } #[cfg(windows)] -fn uninit_com() { - unsafe { - windows::Win32::System::Com::CoUninitialize(); +fn verify_com_path(expected: &std::path::Path) -> windows::core::Result<()> { + use windows::core::Error; + use windows::Win32::Foundation::E_FAIL; + let key = format!( + "SOFTWARE\\Classes\\CLSID\\{{{}}}\\InProcServer32", + smartkey_win::config::CLSID_SMARTKEY_STR + ); + let value = read_value(&key, None)? + .ok_or_else(|| Error::new(E_FAIL, "SmartKey HKCU registration is missing"))?; + if std::path::Path::new(&value) != expected || !expected.is_file() { + return Err(Error::new( + E_FAIL, + "SmartKey registration does not point to the installed DLL", + )); + } + Ok(()) +} + +#[cfg(windows)] +fn set_login(enabled: bool, exe: &std::path::Path) -> windows::core::Result<()> { + use windows::core::*; + use windows::Win32::Foundation::{ERROR_FILE_NOT_FOUND, E_FAIL}; + use windows::Win32::System::Registry::*; + const KEY: &str = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"; + const NAME: &str = "SmartKey"; + let expected = format!("\"{}\" --login", exe.display()); + let existing = read_value(KEY, Some(NAME))?; + if existing.as_ref().is_some_and(|value| value != &expected) { + return Err(Error::new( + E_FAIL, + "An unrelated SmartKey login value already exists; it was preserved", + )); + } + if !enabled && existing.is_none() { + return Ok(()); + } + let key: Vec = KEY.encode_utf16().chain(Some(0)).collect(); + let mut handle = HKEY::default(); + let opened = unsafe { RegCreateKeyW(HKEY_CURRENT_USER, PCWSTR(key.as_ptr()), &mut handle) }; + if opened.0 != 0 { + return Err(Error::from(HRESULT::from_win32(opened.0))); + } + let value: Vec = expected.encode_utf16().chain(Some(0)).collect(); + let result = unsafe { + if enabled { + RegSetValueExW( + handle, + w!("SmartKey"), + 0, + REG_SZ, + Some(std::slice::from_raw_parts( + value.as_ptr().cast(), + value.len() * 2, + )), + ) + } else { + RegDeleteValueW(handle, w!("SmartKey")) + } + }; + let close = unsafe { RegCloseKey(handle) }; + if result.0 != 0 && result != ERROR_FILE_NOT_FOUND { + return Err(Error::from(HRESULT::from_win32(result.0))); + } + if close.0 != 0 { + return Err(Error::from(HRESULT::from_win32(close.0))); } + Ok(()) } diff --git a/crates/smartkey-win/src/registration.rs b/crates/smartkey-win/src/registration.rs index 023de12..168a0da 100644 --- a/crates/smartkey-win/src/registration.rs +++ b/crates/smartkey-win/src/registration.rs @@ -4,10 +4,10 @@ //! the standalone smartkey-register.exe binary. //! //! Registration creates: -//! 1. HKLM\SOFTWARE\Classes\CLSID\{CLSID}\InProcServer32 → DLL path + Apartment -//! (or HKCU equivalent when the current user lacks admin privileges) +//! 1. HKCU\SOFTWARE\Classes\CLSID\{CLSID}\InProcServer32 → DLL path + Apartment //! 2. TSF TIP profile via ITfInputProcessorProfileMgr::RegisterProfile -//! 3. TSF keyboard category via ITfCategoryMgr::RegisterCategory +//! 3. TSF keyboard/display categories via ITfCategoryMgr::RegisterCategory +//! 4. Current-user availability via input.dll InstallLayoutOrTipUserReg //! //! Precondition: COM must be initialized (CoInitializeEx) before calling. @@ -26,94 +26,131 @@ const LANGID_BG: u16 = 0x0402; /// Display name shown in Windows language settings. const DISPLAY_NAME: &str = "SmartKey"; -/// TSF flag: register profile as process-local only (required for HKCU installs). -const TF_RP_LOCALPROCESS: u32 = 0x4; +// Persistent registration uses flags 0. TF_RP_LOCALPROCESS is NOT per-user: +// it vanishes with the installer process. User availability is configured by +// the documented input.dll InstallLayoutOrTipUserReg API below. -// -- Public API --------------------------------------------------------- - -/// Register the SmartKey IME. `dll_path` is the absolute path to the DLL. -/// -/// Attempts HKLM (system-wide) first; falls back to HKCU (per-user) if -/// the current user lacks admin privileges. -/// -/// Returns `true` if registered system-wide (HKLM), `false` for per-user (HKCU). +/// Register COM only in HKCU, then the persistent TSF profile/categories and +/// enable exactly this profile for the current user. No elevation fallback. +/// Returns false for compatibility with DllRegisterServer's existing caller. +/// Any denied TSF operation is a real installation failure, not a skipped step. pub fn register(dll_path: &str) -> Result { - if is_hklm_writable() { - register_com_server(dll_path)?; - register_tip_profile(dll_path, 0)?; - register_categories()?; - Ok(true) - } else { - register_com_server_hkcu(dll_path).map_err(|e| { - log::error!(" [FAIL] COM server (HKCU): {e}"); - e - })?; - log::info!(" [OK] COM server registered (HKCU)"); - register_tip_profile(dll_path, TF_RP_LOCALPROCESS).map_err(|e| { - log::error!(" [FAIL] TIP profile: {e}"); - e - })?; - log::info!(" [OK] TIP profile registered"); - match register_categories() { - Ok(()) => log::info!(" [OK] Categories registered"), - Err(e) => log::warn!(" [SKIP] Categories (needs admin): {e}"), - } - Ok(false) - } + register_com_server_hkcu(dll_path).map_err(|e| step_error("HKCU COM registration", e))?; + register_tip_profile(dll_path, 0).map_err(|e| step_error("Persistent TSF profile", e))?; + register_categories().map_err(|e| step_error("TSF categories", e))?; + set_user_enabled(true)?; + Ok(false) } -/// Unregister the SmartKey IME. Errors are non-fatal (best-effort cleanup). +/// Attempt each own-identity cleanup and return failures rather than claiming +/// success after partial removal. Never deletes HKLM or another keyboard. pub fn unregister() -> Result<()> { - let _ = unregister_categories(); - let _ = unregister_tip_profile(); - // Clean both hives (best-effort). - let _ = unregister_com_server_hklm(); - let _ = unregister_com_server_hkcu(); + let operations = [ + ("Current-user profile removal", install_layout_or_tip(1)), + ("Categories", unregister_categories()), + ("TSF profile", unregister_tip_profile()), + ("HKCU COM", unregister_com_server_hkcu()), + ]; + let errors: Vec<_> = operations + .into_iter() + .filter_map(|(name, result)| result.err().map(|e| (e.code(), format!("{name}: {e}")))) + .collect(); + if let Some((code, _)) = errors.first() { + return Err(Error::new( + *code, + errors + .iter() + .map(|(_, text)| text.as_str()) + .collect::>() + .join("; "), + )); + } Ok(()) } -// -- COM server registration (registry) -------------------------------- +fn step_error(step: &str, error: Error) -> Error { + Error::new(error.code(), format!("{step}: {error}")) +} -fn is_hklm_writable() -> bool { - let subkey = "SOFTWARE\\Classes"; - let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); - let mut hkey = HKEY::default(); - let result = unsafe { - RegOpenKeyExW( - HKEY_LOCAL_MACHINE, - PCWSTR(subkey_w.as_ptr()), - 0, - KEY_WRITE, - &mut hkey, - ) +/// Microsoft documents NULL user path as HKCU. No DEFPROFILE/CLEANINSTALL flag: +/// existing layouts and default selection remain under the user's control. +pub fn set_user_enabled(enabled: bool) -> Result<()> { + install_layout_or_tip(if enabled { 0 } else { 0x80 }) +} + +fn install_layout_or_tip(flags: u32) -> Result<()> { + use windows::Win32::Foundation::{FreeLibrary, BOOL, E_FAIL, HANDLE}; + use windows::Win32::System::LibraryLoader::{ + GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32, }; - if result.0 == 0 { - let _ = unsafe { RegCloseKey(hkey) }; - true - } else { - false + type Install = unsafe extern "system" fn(PCWSTR, PCWSTR, PCWSTR, PCWSTR, u32) -> BOOL; + // Restrict resolution to the Windows system directory; do not load input.dll + // from the portable bundle/current working directory. + let module = unsafe { + LoadLibraryExW( + w!("input.dll"), + HANDLE::default(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + )? + }; + let result = (|| { + let pointer = unsafe { GetProcAddress(module, s!("InstallLayoutOrTipUserReg")) } + .ok_or_else(|| { + Error::new( + E_FAIL, + "input.dll does not export InstallLayoutOrTipUserReg", + ) + })?; + let install: Install = unsafe { std::mem::transmute(pointer) }; + let profile = format!( + "0x0402:{{{}}}{{{}}}", + CLSID_SMARTKEY_STR, + crate::config::GUID_PROFILE_STR + ); + let profile_w: Vec = profile.encode_utf16().chain(Some(0)).collect(); + let ok = unsafe { + install( + PCWSTR::null(), + PCWSTR::null(), + PCWSTR::null(), + PCWSTR(profile_w.as_ptr()), + flags, + ) + }; + if ok.as_bool() { + Ok(()) + } else { + // Documented BOOL failure has no guaranteed last-error contract. + Err(Error::new(E_FAIL, "InstallLayoutOrTipUserReg returned FALSE; current-user availability was not applied")) + } + })(); + unsafe { + FreeLibrary(module)?; } + result } -fn register_com_server(dll_path: &str) -> Result<()> { - let subkey = format!( - "SOFTWARE\\Classes\\CLSID\\{{{}}}\\InProcServer32", - CLSID_SMARTKEY_STR - ); - let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); - - let mut hkey = HKEY::default(); - check_win32(unsafe { - RegCreateKeyW(HKEY_LOCAL_MACHINE, PCWSTR(subkey_w.as_ptr()), &mut hkey) - })?; - - set_reg_sz(hkey, None, dll_path)?; - set_reg_sz(hkey, Some("ThreadingModel"), "Apartment")?; - - let _ = unsafe { RegCloseKey(hkey) }; - Ok(()) +/// Fresh-process verification must use this query after the installer exits. +/// It observes the actual TSF profile rather than a local registration flag. +pub fn profile_enabled() -> Result { + let mgr: ITfInputProcessorProfileMgr = + unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER)? }; + let mut profile = TF_INPUTPROCESSORPROFILE::default(); + unsafe { + mgr.GetProfile( + TF_PROFILETYPE_INPUTPROCESSOR, + LANGID_BG, + &CLSID_SMARTKEY, + &GUID_PROFILE, + HKL::default(), + &mut profile, + )?; + } + Ok(profile.dwFlags & TF_IPP_FLAG_ENABLED != 0) } +// -- COM server registration (registry) -------------------------------- + fn register_com_server_hkcu(dll_path: &str) -> Result<()> { let subkey = format!( "SOFTWARE\\Classes\\CLSID\\{{{}}}\\InProcServer32", @@ -124,25 +161,21 @@ fn register_com_server_hkcu(dll_path: &str) -> Result<()> { let mut hkey = HKEY::default(); check_win32(unsafe { RegCreateKeyW(HKEY_CURRENT_USER, PCWSTR(subkey_w.as_ptr()), &mut hkey) })?; - set_reg_sz(hkey, None, dll_path)?; - set_reg_sz(hkey, Some("ThreadingModel"), "Apartment")?; - - let _ = unsafe { RegCloseKey(hkey) }; - Ok(()) -} - -fn unregister_com_server_hklm() -> Result<()> { - let subkey = format!("SOFTWARE\\Classes\\CLSID\\{{{}}}", CLSID_SMARTKEY_STR); - let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); - let _ = unsafe { RegDeleteTreeW(HKEY_LOCAL_MACHINE, PCWSTR(subkey_w.as_ptr())) }; - Ok(()) + let result = set_reg_sz(hkey, None, dll_path) + .and_then(|_| set_reg_sz(hkey, Some("ThreadingModel"), "Apartment")); + let closed = check_win32(unsafe { RegCloseKey(hkey) }); + result.and(closed) } fn unregister_com_server_hkcu() -> Result<()> { let subkey = format!("SOFTWARE\\Classes\\CLSID\\{{{}}}", CLSID_SMARTKEY_STR); let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); - let _ = unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, PCWSTR(subkey_w.as_ptr())) }; - Ok(()) + let result = unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, PCWSTR(subkey_w.as_ptr())) }; + if result == windows::Win32::Foundation::ERROR_FILE_NOT_FOUND { + Ok(()) + } else { + check_win32(result) + } } // -- TSF TIP profile registration -------------------------------------- @@ -206,12 +239,15 @@ fn unregister_categories() -> Result<()> { unsafe { CoCreateInstance(&CLSID_TF_CategoryMgr, None, CLSCTX_INPROC_SERVER)? }; unsafe { - cat_mgr.UnregisterCategory(&CLSID_SMARTKEY, &GUID_TFCAT_TIP_KEYBOARD, &CLSID_SMARTKEY)?; - let _ = cat_mgr.UnregisterCategory( + let keyboard = + cat_mgr.UnregisterCategory(&CLSID_SMARTKEY, &GUID_TFCAT_TIP_KEYBOARD, &CLSID_SMARTKEY); + let display = cat_mgr.UnregisterCategory( &CLSID_SMARTKEY, &GUID_TFCAT_DISPLAYATTRIBUTEPROVIDER, &CLSID_SMARTKEY, ); + keyboard?; + display?; } Ok(()) diff --git a/crates/smartkey-win/src/text_contract.rs b/crates/smartkey-win/src/text_contract.rs new file mode 100644 index 0000000..f42209a --- /dev/null +++ b/crates/smartkey-win/src/text_contract.rs @@ -0,0 +1,107 @@ +//! Platform-independent parts of the core-to-TSF text contract. + +use smartkey_core::input::{Action, Key, Modifiers}; + +/// TSF offsets count UTF-16 units; ReplaceWord counts Unicode scalar values. +/// Validate only the requested suffix: a bounded lookback can start mid-pair. +pub fn suffix_units(text: &[u16], scalars: usize) -> Option { + let mut start = text.len(); + for _ in 0..scalars { + start = start.checked_sub(1)?; + match text[start] { + 0xDC00..=0xDFFF => { + start = start.checked_sub(1)?; + if !(0xD800..=0xDBFF).contains(&text[start]) { + return None; + } + } + 0xD800..=0xDBFF => return None, + _ => {} + } + } + Some(text.len() - start) +} + +pub fn consumes_key(actions: &[Action]) -> bool { + !actions.is_empty() + && !actions + .iter() + .any(|action| matches!(action, Action::ForwardKey)) +} + +pub fn claims_key(key: &Key, mods: Modifiers, enabled: bool, pending: bool) -> bool { + if matches!(key, Key::Escape) && mods.contains(Modifiers::SUPER) { + return true; + } + if !enabled { + return false; + } + match key { + Key::Tab + | Key::Right + | Key::Escape + | Key::Left + | Key::Up + | Key::Down + | Key::Home + | Key::End + | Key::PageUp + | Key::PageDown => pending, + Key::Space | Key::Return | Key::Backspace | Key::Char(_) | Key::RawCode(_) => true, + Key::Other(_) => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn replaces_scalar_suffix_without_splitting_surrogates() { + let text: Vec = "old здра😀в".encode_utf16().collect(); + assert_eq!(suffix_units(&text, 2), Some(3)); + assert_eq!(suffix_units(&text, 6), Some(7)); + assert_eq!(suffix_units(&text, 0), Some(0)); + assert_eq!(suffix_units(&text, 11), None); + } + + #[test] + fn bounded_prefix_may_be_split_but_replaced_suffix_must_be_valid() { + assert_eq!(suffix_units(&[0xDC00, 0x0061], 1), Some(1)); + assert_eq!(suffix_units(&[0xDC00, 0x0061], 2), None); + assert_eq!(suffix_units(&[0x0061, 0xD800], 1), None); + assert_eq!(suffix_units(&[0xD800, 0xDC00], 1), Some(2)); + } + + #[test] + fn post_commit_correction_does_not_swallow_delimiter() { + let actions = [ + Action::HideGhost, + Action::ForwardKey, + Action::ReplaceWord { + replace_len: 4, + text: "Word".into(), + }, + ]; + assert!(!consumes_key(&actions)); + assert!(consumes_key(&[Action::CommitText("a".into())])); + assert!(!consumes_key(&[])); + } + + #[test] + fn reversible_switch_and_navigation_reach_core_without_prediction() { + for enabled in [true, false] { + assert!(claims_key(&Key::Escape, Modifiers::SUPER, enabled, false)); + } + for key in [Key::Tab, Key::Right, Key::Left, Key::Home, Key::Escape] { + assert!(claims_key(&key, Modifiers::empty(), true, true)); + assert!(!claims_key(&key, Modifiers::empty(), true, false)); + } + assert!(!claims_key( + &Key::Char('a'), + Modifiers::empty(), + false, + true + )); + } +} diff --git a/crates/smartkey-win/src/tsf.rs b/crates/smartkey-win/src/tsf.rs index 76a766c..163fcaa 100644 --- a/crates/smartkey-win/src/tsf.rs +++ b/crates/smartkey-win/src/tsf.rs @@ -82,6 +82,13 @@ impl SmartKeyTextService { VK_TAB => return Key::Tab, VK_ESCAPE => return Key::Escape, VK_RIGHT => return Key::Right, + VK_LEFT => return Key::Left, + VK_UP => return Key::Up, + VK_DOWN => return Key::Down, + VK_HOME => return Key::Home, + VK_END => return Key::End, + VK_PRIOR => return Key::PageUp, + VK_NEXT => return Key::PageDown, VK_BACK => return Key::Backspace, VK_SPACE => return Key::Space, VK_RETURN => return Key::Return, @@ -133,97 +140,54 @@ impl SmartKeyTextService { /// Execute actions returned by InputMethodCore. fn execute_actions(&self, actions: &[Action], context: &ITfContext) -> bool { - let mut consumed = false; + let consumed = crate::text_contract::consumes_key(actions); let cid = self.client_id.get(); - for action in actions { - match action { - Action::ShowGhost(text) => { + let op = match action { + Action::ForwardKey => continue, + Action::ShowGhost(text) | Action::ShowComposing { typed: text, .. } => { let sink: Result = unsafe { self.cast() }; - match sink { - Ok(comp_sink) => { - let op = EditOp::ShowGhost { - text: text.clone(), - composition: self.composition.clone(), - comp_sink, - ghost_attr_atom: self.ghost_attr_atom.get(), - }; - if let Err(e) = edit_session::request_edit_session(context, cid, op) { - log::error!("smartkey: ShowGhost failed: {e}"); - } + let comp_sink = match sink { + Ok(sink) => sink, + Err(error) => { + log::error!("smartkey: composition sink failed: {error}"); + let _ = self.core.borrow_mut().reset(); + return true; } - Err(e) => log::error!("smartkey: failed to get composition sink: {e}"), - } - consumed = true; - } - Action::HideGhost => { - let op = EditOp::HideGhost { - composition: self.composition.clone(), }; - if let Err(e) = edit_session::request_edit_session(context, cid, op) { - log::error!("smartkey: HideGhost failed: {e}"); - } - consumed = true; - } - Action::CommitText(text) => { - let op = EditOp::CommitText { - text: text.clone(), - composition: self.composition.clone(), + let (full, typed_units) = match action { + Action::ShowComposing { typed, ghost } => { + (format!("{typed}{ghost}"), typed.encode_utf16().count()) + } + _ => (text.clone(), 0), }; - if let Err(e) = edit_session::request_edit_session(context, cid, op) { - log::error!("smartkey: CommitText failed: {e}"); - } - consumed = true; - } - Action::ForwardKey => { - // Key must reach the application — override any prior consumption. - consumed = false; - } - Action::ReplaceWord { - replace_len: _, - text, - } => { - // LIMITATION: Proper ITfRange-based replacement not yet implemented. - // This falls back to CommitText which replaces the entire composition - // rather than just the last `replace_len` characters. As a result, - // transliteration on Windows may produce incorrect behavior when - // partially through a word. Full implementation requires: - // 1. Get composition range via ITfComposition::GetRange - // 2. Create a sub-range covering the last `replace_len` chars - // 3. Set text on that sub-range via ITfRange::SetText - let op = EditOp::CommitText { - text: text.clone(), + EditOp::ShowGhost { + text: full, + typed_units, composition: self.composition.clone(), - }; - if let Err(e) = edit_session::request_edit_session(context, cid, op) { - log::error!("smartkey: ReplaceWord failed: {e}"); + comp_sink, + ghost_attr_atom: self.ghost_attr_atom.get(), } - consumed = true; - } - Action::ShowComposing { - ref typed, - ref ghost, - } => { - // Fallback: treat as regular ghost with full text. - // TODO: implement styled composing for Windows TSF. - let full = format!("{}{}", typed, ghost); - let sink: Result = unsafe { self.cast() }; - match sink { - Ok(comp_sink) => { - let op = EditOp::ShowGhost { - text: full, - composition: self.composition.clone(), - comp_sink, - ghost_attr_atom: self.ghost_attr_atom.get(), - }; - if let Err(e) = edit_session::request_edit_session(context, cid, op) { - log::error!("smartkey: ShowComposing failed: {e}"); - } - } - Err(e) => log::error!("smartkey: failed to get composition sink: {e}"), - } - consumed = true; } + Action::HideGhost => EditOp::HideGhost { + composition: self.composition.clone(), + }, + Action::CommitText(text) => EditOp::CommitText { + text: text.clone(), + composition: self.composition.clone(), + }, + Action::ReplaceWord { replace_len, text } => EditOp::ReplaceWord { + replace_len: *replace_len, + text: text.clone(), + composition: self.composition.clone(), + }, + }; + if let Err(error) = edit_session::request_edit_session(context, cid, op) { + log::error!("smartkey: text edit failed; stopping dependent actions: {error}"); + let _ = self.core.borrow_mut().reset(); + // Some edits may already have succeeded. Replaying the raw key can + // duplicate committed text, so do not forward a partially applied batch. + return true; } } consumed @@ -339,29 +303,15 @@ impl ITfKeyEventSink_Impl for SmartKeyTextService_Impl { let key = SmartKeyTextService::vk_to_key(wparam.0 as u32, scan_code); let core = self.core.borrow(); - if !core.is_enabled() { - // Only claim Super+Escape (kill switch to re-enable). - if matches!(key, Key::Escape) - && SmartKeyTextService::get_modifiers().contains(Modifiers::SUPER) - { - return Ok(BOOL::from(true)); - } - return Ok(BOOL::from(false)); - } - - let has_ghost = core.has_ghost(); - let should_claim = match &key { - Key::Tab | Key::Right | Key::Escape => has_ghost, - Key::Left - | Key::Up - | Key::Down - | Key::Home - | Key::End - | Key::PageUp - | Key::PageDown => false, - Key::Space | Key::Return | Key::Backspace | Key::Char(_) | Key::RawCode(_) => true, - Key::Other(_) => false, - }; + let pending = core.has_ghost() + || !core.current_word().is_empty() + || self.composition.borrow().is_some(); + let should_claim = crate::text_contract::claims_key( + &key, + SmartKeyTextService::get_modifiers(), + core.is_enabled(), + pending, + ); Ok(BOOL::from(should_claim)) } @@ -425,11 +375,20 @@ impl ITfCompositionSink_Impl for SmartKeyTextService_Impl { fn OnCompositionTerminated( &self, _ecwrite: u32, - _pcomposition: Option<&ITfComposition>, + pcomposition: Option<&ITfComposition>, ) -> Result<()> { - // External termination (e.g. application or another TIP ended our composition). - // Clean up our state to stay in sync. - *self.composition.borrow_mut() = None; + let matches_active = { + let active = self.composition.borrow(); + active + .as_ref() + .is_some_and(|current| Some(current) == pcomposition) + }; + if matches_active { + self.composition.borrow_mut().take(); + // An external termination finalized the range; discard stale predictions. + // Own Hide/Commit removes the slot before its termination callback. + let _ = self.core.borrow_mut().reset(); + } Ok(()) } } diff --git a/crates/smartkey-win/windows-runtime-manifest.json b/crates/smartkey-win/windows-runtime-manifest.json new file mode 100644 index 0000000..1e99cd1 --- /dev/null +++ b/crates/smartkey-win/windows-runtime-manifest.json @@ -0,0 +1,123 @@ +{ + "schema_version": 1, + "package_name": "smartkey-windows-standalone", + "status": "candidate_native_acceptance_pending", + "native_artifact_layout": "Extract complete ZIP; Install-SmartKey.cmd stages the per-user application in %LOCALAPPDATA%\\SmartKey.", + "runtime_data_destination_directory": "%APPDATA%\\smartkey", + "native_files": [ + { + "name": "smartkey-register.exe", + "repository_source": "target/release/smartkey-register.exe", + "purpose": "Visible current-user setup, status, enable, disable and removal; fresh-process profile verification." + }, + { + "name": "smartkey_win.dll", + "repository_source": "target/release/smartkey_win.dll", + "purpose": "Windows TSF COM server." + } + ], + "runtime_data_files": [ + { + "name": "smartkey.json", + "repository_source": "config/smartkey.json", + "destination": "%APPDATA%\\smartkey\\smartkey.json", + "optional": true, + "provenance": "Tracked, reviewed non-personal starter configuration; GPL-3.0 under repository LICENSE." + }, + { + "name": "corpus_en.json", + "repository_source": "corpus/corpus_en.json", + "destination": "%APPDATA%\\smartkey\\corpus_en.json", + "optional": false, + "provenance": "Tracked public repository corpus; GPL-3.0 under repository LICENSE." + }, + { + "name": "corpus_bg.json", + "repository_source": "corpus/corpus_bg.json", + "destination": "%APPDATA%\\smartkey\\corpus_bg.json", + "optional": false, + "provenance": "Tracked public repository corpus; GPL-3.0 under repository LICENSE." + }, + { + "name": "corpus_tech.json", + "repository_source": "corpus/corpus_tech.json", + "destination": "%APPDATA%\\smartkey\\corpus_tech.json", + "optional": false, + "provenance": "Tracked public repository corpus; GPL-3.0 under repository LICENSE." + } + ], + "artifact_ancillary_files": [ + { + "name": "LICENSE", + "repository_source": "LICENSE", + "purpose": "Repository dual-license notice." + }, + { + "name": "LICENSE-GPL", + "repository_source": "LICENSE-GPL", + "purpose": "GPL-3.0 license text for application and corpus payload." + }, + { + "name": "LICENSE-APACHE", + "repository_source": "LICENSE-APACHE", + "purpose": "Apache-2.0 license text for smartkey-core." + }, + { + "name": "artifact-source-manifest.json", + "repository_source": null, + "purpose": "CI-generated source SHA, source URL, and per-file SHA-256 receipt for every other archive file." + }, + { + "name": "Install-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Install-SmartKey.cmd", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "Status-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Status-SmartKey.cmd", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "Enable-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Enable-SmartKey.cmd", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "Disable-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Disable-SmartKey.cmd", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "Uninstall-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Uninstall-SmartKey.cmd", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "README-WINDOWS.md", + "repository_source": "crates/smartkey-win/packaging/README-WINDOWS.md", + "purpose": "Current-user standalone setup and maintenance" + } + ], + "excluded_files": [ + { + "name": "personal.json", + "reason": "Optional user-specific profile; never packaged." + }, + { + "pattern": "corpus_*.bin", + "reason": "Runtime-generated caches are not source payload." + } + ], + "runtime_contract": { + "network_required": false, + "autostart_created": "One owned HKCU Run value after successful setup; removed by Disable/Uninstall", + "automatic_registration": "Only on explicit installer launch; no elevation fallback", + "automatic_appdata_mutation": "Setup copies only missing public starter data; preserves personal files", + "missing_public_corpus_is_package_failure": true + }, + "uninstall_boundary": "Uninstall-SmartKey removes exact SmartKey registrations, its Run value and installed EXE/DLL. Existing keyboards/default and personal data remain. Locked files are reported.", + "dependency_evidence": { + "build_assumption": "x64 MSVC static CRT; CI inspects both PE import lists", + "runtime_dll_completeness": "Requires successful CI dependency check; Windows 10/11 system DLLs supplied by OS" + } +} From 5a6e4354ca71b47516463404dee9a4463315b1df Mon Sep 17 00:00:00 2001 From: RMANOV <96174405+RMANOV@users.noreply.github.com> Date: Fri, 9 Oct 2026 01:05:44 +0300 Subject: [PATCH 2/9] Capture native registration phases and standard-user process exits --- .github/workflows/ci.yml | 34 +++++++++++++++ crates/smartkey-win/packaging/smoke-user.ps1 | 46 +++++++++++++++----- crates/smartkey-win/src/registration.rs | 29 ++++++------ 3 files changed, 84 insertions(+), 25 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 73e4bb7..d8403c3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -190,6 +190,7 @@ jobs: retention-days: 14 - name: Check install and reversal as a standard Windows user + id: user-smoke timeout-minutes: 5 shell: pwsh run: | @@ -233,6 +234,39 @@ jobs: } finally { if ($created) { Remove-LocalUser -Name $name } } + - name: Diagnose registration in the existing runner profile + if: failure() && steps.user-smoke.outcome == 'failure' + timeout-minutes: 2 + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $PSNativeCommandUseErrorActionPreference = $false + $root = "C:\Users\Public\SmartKeySmoke-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + $helper = Join-Path $root 'bundle/smartkey-register.exe' + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = [Security.Principal.WindowsPrincipal]::new($identity) + $elevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + if (-not $elevated) { throw 'Runner-profile diagnostic requires an actual elevated token' } + if (Test-Path -LiteralPath (Join-Path $env:LOCALAPPDATA 'SmartKey')) { + throw 'Refusing to alter a preexisting runner-profile SmartKey installation' + } + $result = [ordered]@{ + diagnostic_only=$true; standard_user_acceptance=$false + elevated_token=$elevated; existing_runner_profile=$true + privilege_vs_profile_history='NOT_DISTINGUISHED' + install_exit=$null; cleanup_exit=$null + } + try { + & $helper --install --no-dialog 1> (Join-Path $root 'control-install.stdout.txt') 2> (Join-Path $root 'control-install.stderr.txt') + $result.install_exit = $LASTEXITCODE + } finally { + # Exact SmartKey identifiers only; no installer elevation fallback. + & $helper --uninstall --no-dialog 1> (Join-Path $root 'control-cleanup.stdout.txt') 2> (Join-Path $root 'control-cleanup.stderr.txt') + $result.cleanup_exit = $LASTEXITCODE + $result | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $root 'control-result.json') -Encoding utf8 + Get-Content -LiteralPath (Join-Path $root 'control-install.stderr.txt') + Get-Content -LiteralPath (Join-Path $root 'control-result.json') + } - name: Retain native standard-user result if: always() uses: actions/upload-artifact@v4 diff --git a/crates/smartkey-win/packaging/smoke-user.ps1 b/crates/smartkey-win/packaging/smoke-user.ps1 index 5415326..be3099f 100644 --- a/crates/smartkey-win/packaging/smoke-user.ps1 +++ b/crates/smartkey-win/packaging/smoke-user.ps1 @@ -78,18 +78,40 @@ function Invoke-Helper([string]$exe, [string]$action) { $stem = $action.TrimStart('-') $stdout = Join-Path $OutDir "$stem.stdout.txt" $stderr = Join-Path $OutDir "$stem.stderr.txt" - $process = Start-Process -FilePath $exe -ArgumentList @($action, '--no-dialog') -PassThru -NoNewWindow -RedirectStandardOutput $stdout -RedirectStandardError $stderr - if (-not $process.WaitForExit(45000)) { - $process.Kill() - $process.WaitForExit() - throw "$action exceeded 45 seconds; the smoke stopped." - } - $process.Refresh() - $steps.Add([ordered]@{ action=$action; exit_code=$process.ExitCode }) - if ($process.ExitCode -ne 0) { - # Exact helper HRESULT/error is retained as the failed native evidence. - throw "$action failed (exit $($process.ExitCode)); see $stderr." - } + # Keep our own .NET Process/handle from Start through ExitCode. Windows + # PowerShell Start-Process -PassThru can yield a null cached ExitCode even + # after WaitForExit/Refresh; null must never be recorded as native success. + $process = New-Object System.Diagnostics.Process + $process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo + $process.StartInfo.FileName = $exe + $process.StartInfo.Arguments = "$action --no-dialog" + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.CreateNoWindow = $true + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + try { + if (-not $process.Start()) { throw "Cannot start $action." } + # Drain both streams asynchronously before waiting, avoiding pipe + # deadlocks while preserving the real helper HRESULT/error output. + $stdoutTask = $process.StandardOutput.ReadToEndAsync() + $stderrTask = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(45000)) { + $process.Kill() + if (-not $process.WaitForExit(5000)) { throw "$action timed out and did not exit after termination." } + [IO.File]::WriteAllText($stdout, $stdoutTask.GetAwaiter().GetResult()) + [IO.File]::WriteAllText($stderr, $stderrTask.GetAwaiter().GetResult()) + throw "$action exceeded 45 seconds; the smoke stopped." + } + $exitCode = $process.ExitCode + if ($null -eq $exitCode) { throw "$action exited but its real exit code was unavailable; refusing an inferred result." } + [IO.File]::WriteAllText($stdout, $stdoutTask.GetAwaiter().GetResult()) + [IO.File]::WriteAllText($stderr, $stderrTask.GetAwaiter().GetResult()) + $steps.Add([ordered]@{ action=$action; exit_code=[int]$exitCode }) + if ($exitCode -ne 0) { + throw "$action failed (exit $exitCode); see $stderr." + } + } finally { $process.Dispose() } + } $receipt = [ordered]@{ status='NOT_RUN'; standard_nonadmin=$true; current_user_profile_confirmed=$true; no_dialog=$true diff --git a/crates/smartkey-win/src/registration.rs b/crates/smartkey-win/src/registration.rs index 168a0da..a0aaadc 100644 --- a/crates/smartkey-win/src/registration.rs +++ b/crates/smartkey-win/src/registration.rs @@ -182,24 +182,27 @@ fn unregister_com_server_hkcu() -> Result<()> { fn register_tip_profile(dll_path: &str, flags: u32) -> Result<()> { let profile_mgr: ITfInputProcessorProfileMgr = - unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER)? }; + unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER) } + .map_err(|e| step_error("CoCreateInstance(ITfInputProcessorProfileMgr)", e))?; let name_w: Vec = DISPLAY_NAME.encode_utf16().collect(); let icon_w: Vec = dll_path.encode_utf16().collect(); unsafe { - profile_mgr.RegisterProfile( - &CLSID_SMARTKEY, - LANGID_BG, - &GUID_PROFILE, - &name_w, - &icon_w, - 0, // icon index - HKL::default(), // no substitute layout - 0, // no preferred layout - true, // enable by default - flags, - )?; + profile_mgr + .RegisterProfile( + &CLSID_SMARTKEY, + LANGID_BG, + &GUID_PROFILE, + &name_w, + &icon_w, + 0, // icon index + HKL::default(), // no substitute layout + 0, // no preferred layout + true, // enable by default + flags, + ) + .map_err(|e| step_error("ITfInputProcessorProfileMgr::RegisterProfile", e))?; } Ok(()) From 1b0c17c09afc546588d580e292aee4f92b8ab39d Mon Sep 17 00:00:00 2001 From: RMANOV <96174405+RMANOV@users.noreply.github.com> Date: Fri, 9 Oct 2026 01:20:11 +0300 Subject: [PATCH 3/9] Distinguish profile query failures and retain owned registry evidence --- .github/workflows/ci.yml | 20 ++++++++++++++++++ crates/smartkey-win/src/register.rs | 28 ++++++++++++++++++++++--- crates/smartkey-win/src/registration.rs | 10 +++++++-- 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d8403c3..e3e1745 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -259,6 +259,26 @@ jobs: try { & $helper --install --no-dialog 1> (Join-Path $root 'control-install.stdout.txt') 2> (Join-Path $root 'control-install.stderr.txt') $result.install_exit = $LASTEXITCODE + # Read only this candidate's identities before its cleanup. + $guid = '{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' + $snapshots = foreach ($path in @( + "HKCU:\Software\Microsoft\CTF\TIP\$guid", + "HKLM:\Software\Microsoft\CTF\TIP\$guid", + "HKCU:\Software\Classes\CLSID\$guid", + "HKLM:\Software\Classes\CLSID\$guid" + )) { + if (-not (Test-Path -LiteralPath $path)) { + [ordered]@{ path=$path; present=$false } + continue + } + $keys = @((Get-Item -LiteralPath $path)) + @(Get-ChildItem -LiteralPath $path -Recurse) + foreach ($key in $keys) { + $values = [ordered]@{} + foreach ($name in $key.GetValueNames()) { $values[$name] = $key.GetValue($name) } + [ordered]@{ path=$key.Name; present=$true; values=$values } + } + } + @($snapshots) | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $root 'control-owned-registry.json') -Encoding utf8 } finally { # Exact SmartKey identifiers only; no installer elevation fallback. & $helper --uninstall --no-dialog 1> (Join-Path $root 'control-cleanup.stdout.txt') 2> (Join-Path $root 'control-cleanup.stderr.txt') diff --git a/crates/smartkey-win/src/register.rs b/crates/smartkey-win/src/register.rs index 4ee05c0..40aaabf 100644 --- a/crates/smartkey-win/src/register.rs +++ b/crates/smartkey-win/src/register.rs @@ -70,6 +70,17 @@ fn run(action: &str) -> Result { .to_str() .ok_or("DLL path is not valid Unicode")?; registration::register(dll).map_err(api_error)?; + // Diagnostic only: the fresh child below remains the acceptance check, + // including when this same query fails in the installing process. + match registration::profile_enabled() { + Ok(enabled) => println!( + "SmartKey diagnostic: in-process TSF profile query succeeded; enabled={enabled}" + ), + Err(error) => eprintln!( + "SmartKey diagnostic: in-process TSF profile query failed: {}", + api_error(error) + ), + } // A separate process queries the actual persisted TSF profile. // A process-local registration cannot pass this check. let verification = std::process::Command::new(&installed_exe) @@ -228,12 +239,23 @@ fn verify_com_path(expected: &std::path::Path) -> windows::core::Result<()> { "SOFTWARE\\Classes\\CLSID\\{{{}}}\\InProcServer32", smartkey_win::config::CLSID_SMARTKEY_STR ); - let value = read_value(&key, None)? - .ok_or_else(|| Error::new(E_FAIL, "SmartKey HKCU registration is missing"))?; + let value = read_value(&key, None) + .map_err(|e| { + Error::new( + e.code(), + format!("Verification HKCU COM path / RegGetValueW: {e}"), + ) + })? + .ok_or_else(|| { + Error::new( + E_FAIL, + "Verification HKCU COM path: SmartKey registration is missing", + ) + })?; if std::path::Path::new(&value) != expected || !expected.is_file() { return Err(Error::new( E_FAIL, - "SmartKey registration does not point to the installed DLL", + "Verification HKCU COM path: registration does not point to the installed DLL", )); } Ok(()) diff --git a/crates/smartkey-win/src/registration.rs b/crates/smartkey-win/src/registration.rs index a0aaadc..c3be261 100644 --- a/crates/smartkey-win/src/registration.rs +++ b/crates/smartkey-win/src/registration.rs @@ -134,7 +134,13 @@ fn install_layout_or_tip(flags: u32) -> Result<()> { /// It observes the actual TSF profile rather than a local registration flag. pub fn profile_enabled() -> Result { let mgr: ITfInputProcessorProfileMgr = - unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER)? }; + unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER) } + .map_err(|e| { + step_error( + "Verification CoCreateInstance(ITfInputProcessorProfileMgr)", + e, + ) + })?; let mut profile = TF_INPUTPROCESSORPROFILE::default(); unsafe { mgr.GetProfile( @@ -144,7 +150,7 @@ pub fn profile_enabled() -> Result { &GUID_PROFILE, HKL::default(), &mut profile, - )?; + ).map_err(|e| step_error("Verification ITfInputProcessorProfileMgr::GetProfile(type=INPUTPROCESSOR, langid=0x0402, hkl=NULL)", e))?; } Ok(profile.dwFlags & TF_IPP_FLAG_ENABLED != 0) } From b8275a6d3bcc1eb9f3326581406e5f5deebb29f8 Mon Sep 17 00:00:00 2001 From: RMANOV <96174405+RMANOV@users.noreply.github.com> Date: Fri, 9 Oct 2026 01:34:18 +0300 Subject: [PATCH 4/9] Isolate elevated COM visibility in the native installer diagnostic --- .github/workflows/ci.yml | 99 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 93 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e3e1745..23de659 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -255,12 +255,20 @@ jobs: elevated_token=$elevated; existing_runner_profile=$true privilege_vs_profile_history='NOT_DISTINGUISHED' install_exit=$null; cleanup_exit=$null + token_integrity_sid=$null; enable_lua=$null + machine_com_control='NOT_RUN'; machine_verify_exit=$null + copied_dll_sha256=$null; diagnostic_error=$null; cleanup_errors=@() + machine_class_removed=$null; machine_directory_removed=$null } + $machineClassCreated = $false + $machineDirectoryCreated = $false + $guid = '{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' + $machineClass = "HKLM:\Software\Classes\CLSID\$guid" + $machineDirectory = Join-Path $env:ProgramFiles "SmartKey-COM-Diagnostic-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" try { & $helper --install --no-dialog 1> (Join-Path $root 'control-install.stdout.txt') 2> (Join-Path $root 'control-install.stderr.txt') $result.install_exit = $LASTEXITCODE # Read only this candidate's identities before its cleanup. - $guid = '{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' $snapshots = foreach ($path in @( "HKCU:\Software\Microsoft\CTF\TIP\$guid", "HKLM:\Software\Microsoft\CTF\TIP\$guid", @@ -279,12 +287,91 @@ jobs: } } @($snapshots) | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $root 'control-owned-registry.json') -Encoding utf8 + # One diagnostic for elevated COM visibility; baseline evidence above + # is retained, and this cannot accept a standard-user installation. + if ($result.install_exit -ne 0) { + $groups = & "$env:SystemRoot\System32\whoami.exe" /groups /fo csv /nh + if ($LASTEXITCODE -ne 0) { throw 'Cannot read diagnostic token integrity' } + $integrity = [regex]::Match(($groups -join "`n"), 'S-1-16-[0-9]+') + if (-not $integrity.Success) { throw 'Diagnostic token integrity SID was not reported' } + $result.token_integrity_sid = $integrity.Value + $result.enable_lua = (Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name EnableLUA).EnableLUA + if (Test-Path -LiteralPath $machineClass) { + throw 'Refusing preexisting exact SmartKey machine COM class' + } + if (Test-Path -LiteralPath $machineDirectory) { + throw 'Refusing preexisting diagnostic Program Files directory' + } + New-Item -ItemType Directory -Path $machineDirectory | Out-Null + $machineDirectoryCreated = $true + $machineDll = Join-Path $machineDirectory 'smartkey_win.dll' + $sourceDll = Join-Path $env:LOCALAPPDATA 'SmartKey/smartkey_win.dll' + Copy-Item -LiteralPath $sourceDll -Destination $machineDll + $sourceHash = (Get-FileHash -LiteralPath $sourceDll -Algorithm SHA256).Hash + $result.copied_dll_sha256 = (Get-FileHash -LiteralPath $machineDll -Algorithm SHA256).Hash + if ($result.copied_dll_sha256 -ne $sourceHash) { throw 'Diagnostic DLL copy differs from installed DLL' } + # No TSF catalog or profile parameters are changed here. + New-Item -Path $machineClass | Out-Null + $machineClassCreated = $true + $serverKey = Join-Path $machineClass 'InProcServer32' + New-Item -Path $serverKey | Out-Null + Set-Item -LiteralPath $serverKey -Value $machineDll + New-ItemProperty -LiteralPath $serverKey -Name ThreadingModel -Value Apartment -PropertyType String | Out-Null + $process = [Diagnostics.Process]::new() + try { + $process.StartInfo = [Diagnostics.ProcessStartInfo]::new($helper, '--verify --no-dialog') + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.CreateNoWindow = $true + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + if (-not $process.Start()) { throw 'Cannot start machine COM verification child' } + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(45000)) { + $process.Kill($true) + if (-not $process.WaitForExit(5000)) { throw 'Machine COM verification child did not stop after timeout' } + $result.machine_com_control = 'TIMEOUT' + } + $stdout.GetAwaiter().GetResult() | Set-Content -LiteralPath (Join-Path $root 'control-machine-com.stdout.txt') -Encoding utf8 + $stderr.GetAwaiter().GetResult() | Set-Content -LiteralPath (Join-Path $root 'control-machine-com.stderr.txt') -Encoding utf8 + $result.machine_verify_exit = $process.ExitCode + if ($result.machine_com_control -ne 'TIMEOUT') { + $result.machine_com_control = if ($process.ExitCode -eq 0) { 'QUERY_SUCCEEDED_DIAGNOSTIC_ONLY' } else { 'QUERY_FAILED' } + } + } finally { $process.Dispose() } + } + } catch { + $result.diagnostic_error = $_.Exception.Message + if ($result.machine_com_control -eq 'NOT_RUN') { $result.machine_com_control = 'CONTROL_ERROR' } } finally { - # Exact SmartKey identifiers only; no installer elevation fallback. - & $helper --uninstall --no-dialog 1> (Join-Path $root 'control-cleanup.stdout.txt') 2> (Join-Path $root 'control-cleanup.stderr.txt') - $result.cleanup_exit = $LASTEXITCODE - $result | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $root 'control-result.json') -Encoding utf8 - Get-Content -LiteralPath (Join-Path $root 'control-install.stderr.txt') + # Remove only objects this diagnostic created, even if query failed. + if ($machineClassCreated) { + try { + Remove-Item -LiteralPath $machineClass -Recurse -Force + $result.machine_class_removed = -not (Test-Path -LiteralPath $machineClass) + if (-not $result.machine_class_removed) { throw 'Created machine COM class remains' } + } catch { $result.cleanup_errors += "Machine COM class: $($_.Exception.Message)" } + } + if ($machineDirectoryCreated) { + try { + Remove-Item -LiteralPath $machineDirectory -Recurse -Force + $result.machine_directory_removed = -not (Test-Path -LiteralPath $machineDirectory) + if (-not $result.machine_directory_removed) { throw 'Created diagnostic directory remains' } + } catch { $result.cleanup_errors += "Diagnostic directory: $($_.Exception.Message)" } + } + # Existing exact SmartKey helper cleanup remains unconditional. + try { + & $helper --uninstall --no-dialog 1> (Join-Path $root 'control-cleanup.stdout.txt') 2> (Join-Path $root 'control-cleanup.stderr.txt') + $result.cleanup_exit = $LASTEXITCODE + if ($result.cleanup_exit -ne 0) { $result.cleanup_errors += "Helper cleanup exit: $($result.cleanup_exit)" } + } catch { $result.cleanup_errors += "Helper cleanup: $($_.Exception.Message)" } + $result | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $root 'control-result.json') -Encoding utf8 + if (Test-Path -LiteralPath (Join-Path $root 'control-install.stderr.txt')) { + Get-Content -LiteralPath (Join-Path $root 'control-install.stderr.txt') + } + if (Test-Path -LiteralPath (Join-Path $root 'control-machine-com.stderr.txt')) { + Get-Content -LiteralPath (Join-Path $root 'control-machine-com.stderr.txt') + } Get-Content -LiteralPath (Join-Path $root 'control-result.json') } - name: Retain native standard-user result From 3ba974400b54f7d50f9eccf80edf0bb8f738e1b9 Mon Sep 17 00:00:00 2001 From: RMANOV <96174405+RMANOV@users.noreply.github.com> Date: Fri, 9 Oct 2026 02:01:56 +0300 Subject: [PATCH 5/9] Separate protected Windows installation from normal-user keyboard setup --- .github/workflows/ci.yml | 280 +++++------ crates/smartkey-win/Cargo.toml | 4 + .../packaging/Disable-SmartKey.cmd | 4 +- .../packaging/Enable-SmartKey.cmd | 4 +- .../packaging/Install-Machine-SmartKey.cmd | 16 + .../packaging/Install-SmartKey.cmd | 4 +- .../smartkey-win/packaging/README-WINDOWS.md | 71 ++- .../packaging/Status-SmartKey.cmd | 4 +- .../packaging/Uninstall-Machine-SmartKey.cmd | 16 + .../packaging/Uninstall-SmartKey.cmd | 23 +- crates/smartkey-win/packaging/smoke-user.ps1 | 107 ++++- crates/smartkey-win/packaging/user_setup.rs | 234 ++++++++-- crates/smartkey-win/src/register.rs | 440 ++++++++++++++---- crates/smartkey-win/src/registration.rs | 57 ++- crates/smartkey-win/src/tsf.rs | 84 +++- .../windows-runtime-manifest.json | 21 +- 16 files changed, 1003 insertions(+), 366 deletions(-) create mode 100644 crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd create mode 100644 crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 23de659..3fe8e55 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,6 +144,8 @@ jobs: @{ Source = 'corpus/corpus_en.json'; Name = 'corpus_en.json' }, @{ Source = 'corpus/corpus_bg.json'; Name = 'corpus_bg.json' }, @{ Source = 'corpus/corpus_tech.json'; Name = 'corpus_tech.json' }, + @{ Source = 'crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd'; Name = 'Install-Machine-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd'; Name = 'Uninstall-Machine-SmartKey.cmd' }, @{ Source = 'crates/smartkey-win/packaging/Install-SmartKey.cmd'; Name = 'Install-SmartKey.cmd' }, @{ Source = 'crates/smartkey-win/packaging/Status-SmartKey.cmd'; Name = 'Status-SmartKey.cmd' }, @{ Source = 'crates/smartkey-win/packaging/Enable-SmartKey.cmd'; Name = 'Enable-SmartKey.cmd' }, @@ -189,191 +191,161 @@ jobs: if-no-files-found: error retention-days: 14 - - name: Check install and reversal as a standard Windows user + - name: Check machine setup and standard-user install and reversal id: user-smoke - timeout-minutes: 5 + timeout-minutes: 8 shell: pwsh run: | $ErrorActionPreference = 'Stop' $root = "C:\Users\Public\SmartKeySmoke-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" $name = "SKSmoke$env:GITHUB_RUN_ATTEMPT" + $stage = Join-Path $env:RUNNER_TEMP "smartkey-windows-standalone-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + $stageHelper = Join-Path $stage 'smartkey-register.exe' + $machineDirectory = Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::ProgramFiles)) 'SmartKey' + $machineHelper = Join-Path $machineDirectory 'smartkey-register.exe' + $guid = '{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' + $machineClass = "HKLM:\Software\Classes\CLSID\$guid" + $machineTip = "HKLM:\Software\Microsoft\CTF\TIP\$guid" + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = [Security.Principal.WindowsPrincipal]::new($identity) + if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + throw 'The disposable runner must provide an actual elevated token for machine setup.' + } if (Get-LocalUser -Name $name -ErrorAction SilentlyContinue) { throw 'Smoke account already exists' } + foreach ($path in @($root, $machineDirectory, $machineClass, $machineTip)) { + if (Test-Path -LiteralPath $path) { throw "Refusing preexisting smoke/machine state: $path" } + } $secret = ConvertTo-SecureString ([Guid]::NewGuid().ToString('N') + 'aA!4') -AsPlainText -Force $credential = [PSCredential]::new("$env:COMPUTERNAME\$name", $secret) $created = $false + $machineAttempted = $false + $failure = $null + $result = [ordered]@{ + status='NOT_RUN'; elevated_machine_token=$true + standard_user_prerequisite=$false; standard_user_lifecycle=$false + machine_install_exit=$null; machine_verify_exit=$null; machine_cleanup_exit=$null + frozen_bundle_matches=$false; machine_state_removed=$false + typing_exercised=$false; logon_exercised=$false; cleanup_errors=@() + } + function Invoke-MachineHelper([string]$helper, [string]$action, [string]$exitField) { + $process = [Diagnostics.Process]::new() + try { + $process.StartInfo = [Diagnostics.ProcessStartInfo]::new($helper, "$action --no-dialog") + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.CreateNoWindow = $true + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + if (-not $process.Start()) { throw "Cannot start $action" } + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + $timedOut = -not $process.WaitForExit(45000) + if ($timedOut) { + $process.Kill($true) + if (-not $process.WaitForExit(5000)) { throw "$action did not exit after timeout/termination" } + } + $stem = $action.TrimStart('-') + [IO.File]::WriteAllText((Join-Path $root "$stem.stdout.txt"), $stdout.GetAwaiter().GetResult()) + [IO.File]::WriteAllText((Join-Path $root "$stem.stderr.txt"), $stderr.GetAwaiter().GetResult()) + $exitCode = $process.ExitCode + if ($null -eq $exitCode) { throw "$action has no real exit code; inferred success is refused" } + $result[$exitField] = [int]$exitCode + if ($timedOut) { throw "$action exceeded 45 seconds" } + if ($exitCode -ne 0) { throw "$action failed with exit $exitCode" } + } finally { $process.Dispose() } + } + function Invoke-UserSmoke([string]$phase, [string]$expectedStatus, [int]$timeout) { + $output = Join-Path $root "user-$($phase.ToLowerInvariant())" + $arguments = "-NoProfile -NonInteractive -File `"$script`" -Bundle `"$bundle`" -OutDir `"$output`" -Phase $phase" + $child = Start-Process -FilePath 'powershell.exe' -ArgumentList $arguments -Credential $credential -LoadUserProfile -UseNewEnvironment -PassThru -RedirectStandardOutput (Join-Path $root "$phase.launcher.stdout.txt") -RedirectStandardError (Join-Path $root "$phase.launcher.stderr.txt") + try { + if (-not $child.WaitForExit($timeout)) { + & taskkill /PID $child.Id /T /F + throw "Standard-user $phase exceeded its bounded timeout" + } + $child.Refresh() + if ($null -eq $child.ExitCode -or $child.ExitCode -ne 0) { + throw "Standard-user $phase failed or its real exit code is unavailable: $($child.ExitCode)" + } + } finally { $child.Dispose() } + $receipt = Get-Content -LiteralPath (Join-Path $output 'smoke-result.json') -Raw | ConvertFrom-Json + if ($receipt.status -ne $expectedStatus -or $receipt.phase -ne $phase -or + -not $receipt.standard_nonadmin -or -not $receipt.current_user_profile_confirmed -or + -not $receipt.keyboard_defaults_preserved) { + throw "Missing successful standard-user $phase receipt" + } + if ($phase -eq 'Prerequisite' -and -not $receipt.machine_prerequisite_refused) { + throw 'Missing explicit machine-prerequisite refusal' + } + if ($phase -eq 'Lifecycle' -and (-not $receipt.machine_install_preserved -or -not $receipt.personal_sentinel_preserved)) { + throw 'Lifecycle did not preserve the machine install and personal sentinel' + } + } try { + New-Item -ItemType Directory -Path $root | Out-Null New-LocalUser -Name $name -Password $secret -AccountNeverExpires | Out-Null $created = $true Add-LocalGroupMember -Group (Get-LocalGroup -SID 'S-1-5-32-545').Name -Member $name - New-Item -ItemType Directory -Path $root | Out-Null - $stage = Join-Path $env:RUNNER_TEMP "smartkey-windows-standalone-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" Copy-Item -LiteralPath $stage -Destination (Join-Path $root 'bundle') -Recurse Copy-Item -LiteralPath 'crates/smartkey-win/packaging/smoke-user.ps1' -Destination $root & icacls $root /grant "${name}:(OI)(CI)M" /T /Q if ($LASTEXITCODE -ne 0) { throw 'Cannot grant disposable account its smoke directory' } $script = Join-Path $root 'smoke-user.ps1' $bundle = Join-Path $root 'bundle' - $output = Join-Path $root 'user-smoke' - $arguments = "-NoProfile -NonInteractive -File `"$script`" -Bundle `"$bundle`" -OutDir `"$output`"" - $child = Start-Process -FilePath 'powershell.exe' -ArgumentList $arguments -Credential $credential -LoadUserProfile -UseNewEnvironment -PassThru -RedirectStandardOutput (Join-Path $root 'launcher.stdout.txt') -RedirectStandardError (Join-Path $root 'launcher.stderr.txt') - if (-not $child.WaitForExit(180000)) { - & taskkill /PID $child.Id /T /F - throw 'Standard-user smoke exceeded three minutes' - } - $child.Refresh() - Get-Content -LiteralPath (Join-Path $root 'launcher.stdout.txt') - Get-Content -LiteralPath (Join-Path $root 'launcher.stderr.txt') - if (Test-Path -LiteralPath $output) { - Get-ChildItem -LiteralPath $output -File | ForEach-Object { Get-Content -LiteralPath $_.FullName } - } - if ($child.ExitCode -ne 0) { throw "Standard-user smoke failed: $($child.ExitCode)" } - $receipt = Get-Content -LiteralPath (Join-Path $output 'smoke-result.json') -Raw | ConvertFrom-Json - if ($receipt.status -ne 'PASS_NATIVE_STANDARD_USER_MAINTENANCE' -or -not $receipt.standard_nonadmin) { - throw 'Missing successful standard-user receipt' - } - } finally { - if ($created) { Remove-LocalUser -Name $name } - } - - name: Diagnose registration in the existing runner profile - if: failure() && steps.user-smoke.outcome == 'failure' - timeout-minutes: 2 - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $PSNativeCommandUseErrorActionPreference = $false - $root = "C:\Users\Public\SmartKeySmoke-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" - $helper = Join-Path $root 'bundle/smartkey-register.exe' - $identity = [Security.Principal.WindowsIdentity]::GetCurrent() - $principal = [Security.Principal.WindowsPrincipal]::new($identity) - $elevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) - if (-not $elevated) { throw 'Runner-profile diagnostic requires an actual elevated token' } - if (Test-Path -LiteralPath (Join-Path $env:LOCALAPPDATA 'SmartKey')) { - throw 'Refusing to alter a preexisting runner-profile SmartKey installation' - } - $result = [ordered]@{ - diagnostic_only=$true; standard_user_acceptance=$false - elevated_token=$elevated; existing_runner_profile=$true - privilege_vs_profile_history='NOT_DISTINGUISHED' - install_exit=$null; cleanup_exit=$null - token_integrity_sid=$null; enable_lua=$null - machine_com_control='NOT_RUN'; machine_verify_exit=$null - copied_dll_sha256=$null; diagnostic_error=$null; cleanup_errors=@() - machine_class_removed=$null; machine_directory_removed=$null - } - $machineClassCreated = $false - $machineDirectoryCreated = $false - $guid = '{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' - $machineClass = "HKLM:\Software\Classes\CLSID\$guid" - $machineDirectory = Join-Path $env:ProgramFiles "SmartKey-COM-Diagnostic-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" - try { - & $helper --install --no-dialog 1> (Join-Path $root 'control-install.stdout.txt') 2> (Join-Path $root 'control-install.stderr.txt') - $result.install_exit = $LASTEXITCODE - # Read only this candidate's identities before its cleanup. - $snapshots = foreach ($path in @( - "HKCU:\Software\Microsoft\CTF\TIP\$guid", - "HKLM:\Software\Microsoft\CTF\TIP\$guid", - "HKCU:\Software\Classes\CLSID\$guid", - "HKLM:\Software\Classes\CLSID\$guid" - )) { - if (-not (Test-Path -LiteralPath $path)) { - [ordered]@{ path=$path; present=$false } - continue - } - $keys = @((Get-Item -LiteralPath $path)) + @(Get-ChildItem -LiteralPath $path -Recurse) - foreach ($key in $keys) { - $values = [ordered]@{} - foreach ($name in $key.GetValueNames()) { $values[$name] = $key.GetValue($name) } - [ordered]@{ path=$key.Name; present=$true; values=$values } - } + Invoke-UserSmoke 'Prerequisite' 'PASS_NATIVE_STANDARD_USER_PREREQUISITE' 60000 + $result.standard_user_prerequisite = $true + + # Elevation uses the original frozen stage, never the user-writable copy. + # Set ownership before the attempt so partial installation is cleaned too. + $machineAttempted = $true + Invoke-MachineHelper $stageHelper '--install-machine' 'machine_install_exit' + $expected = @(Get-ChildItem -LiteralPath $stage -Force | ForEach-Object Name | Sort-Object) + $actual = @(Get-ChildItem -LiteralPath $machineDirectory -Force | ForEach-Object Name | Sort-Object) + if (Compare-Object -ReferenceObject $expected -DifferenceObject $actual) { + throw 'Protected machine directory differs from the exact frozen bundle' } - @($snapshots) | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $root 'control-owned-registry.json') -Encoding utf8 - # One diagnostic for elevated COM visibility; baseline evidence above - # is retained, and this cannot accept a standard-user installation. - if ($result.install_exit -ne 0) { - $groups = & "$env:SystemRoot\System32\whoami.exe" /groups /fo csv /nh - if ($LASTEXITCODE -ne 0) { throw 'Cannot read diagnostic token integrity' } - $integrity = [regex]::Match(($groups -join "`n"), 'S-1-16-[0-9]+') - if (-not $integrity.Success) { throw 'Diagnostic token integrity SID was not reported' } - $result.token_integrity_sid = $integrity.Value - $result.enable_lua = (Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name EnableLUA).EnableLUA - if (Test-Path -LiteralPath $machineClass) { - throw 'Refusing preexisting exact SmartKey machine COM class' - } - if (Test-Path -LiteralPath $machineDirectory) { - throw 'Refusing preexisting diagnostic Program Files directory' + foreach ($file in $expected) { + if ((Get-FileHash -LiteralPath (Join-Path $stage $file) -Algorithm SHA256).Hash -ne + (Get-FileHash -LiteralPath (Join-Path $machineDirectory $file) -Algorithm SHA256).Hash) { + throw "Protected machine file differs from frozen source: $file" } - New-Item -ItemType Directory -Path $machineDirectory | Out-Null - $machineDirectoryCreated = $true - $machineDll = Join-Path $machineDirectory 'smartkey_win.dll' - $sourceDll = Join-Path $env:LOCALAPPDATA 'SmartKey/smartkey_win.dll' - Copy-Item -LiteralPath $sourceDll -Destination $machineDll - $sourceHash = (Get-FileHash -LiteralPath $sourceDll -Algorithm SHA256).Hash - $result.copied_dll_sha256 = (Get-FileHash -LiteralPath $machineDll -Algorithm SHA256).Hash - if ($result.copied_dll_sha256 -ne $sourceHash) { throw 'Diagnostic DLL copy differs from installed DLL' } - # No TSF catalog or profile parameters are changed here. - New-Item -Path $machineClass | Out-Null - $machineClassCreated = $true - $serverKey = Join-Path $machineClass 'InProcServer32' - New-Item -Path $serverKey | Out-Null - Set-Item -LiteralPath $serverKey -Value $machineDll - New-ItemProperty -LiteralPath $serverKey -Name ThreadingModel -Value Apartment -PropertyType String | Out-Null - $process = [Diagnostics.Process]::new() - try { - $process.StartInfo = [Diagnostics.ProcessStartInfo]::new($helper, '--verify --no-dialog') - $process.StartInfo.UseShellExecute = $false - $process.StartInfo.CreateNoWindow = $true - $process.StartInfo.RedirectStandardOutput = $true - $process.StartInfo.RedirectStandardError = $true - if (-not $process.Start()) { throw 'Cannot start machine COM verification child' } - $stdout = $process.StandardOutput.ReadToEndAsync() - $stderr = $process.StandardError.ReadToEndAsync() - if (-not $process.WaitForExit(45000)) { - $process.Kill($true) - if (-not $process.WaitForExit(5000)) { throw 'Machine COM verification child did not stop after timeout' } - $result.machine_com_control = 'TIMEOUT' - } - $stdout.GetAwaiter().GetResult() | Set-Content -LiteralPath (Join-Path $root 'control-machine-com.stdout.txt') -Encoding utf8 - $stderr.GetAwaiter().GetResult() | Set-Content -LiteralPath (Join-Path $root 'control-machine-com.stderr.txt') -Encoding utf8 - $result.machine_verify_exit = $process.ExitCode - if ($result.machine_com_control -ne 'TIMEOUT') { - $result.machine_com_control = if ($process.ExitCode -eq 0) { 'QUERY_SUCCEEDED_DIAGNOSTIC_ONLY' } else { 'QUERY_FAILED' } - } - } finally { $process.Dispose() } } + $result.frozen_bundle_matches = $true + Invoke-MachineHelper $machineHelper '--verify-machine' 'machine_verify_exit' + Invoke-UserSmoke 'Lifecycle' 'PASS_NATIVE_STANDARD_USER_MAINTENANCE' 180000 + $result.standard_user_lifecycle = $true + $result.status = 'PASS_NATIVE_MACHINE_AND_STANDARD_USER_MAINTENANCE' } catch { - $result.diagnostic_error = $_.Exception.Message - if ($result.machine_com_control -eq 'NOT_RUN') { $result.machine_com_control = 'CONTROL_ERROR' } + $failure = $_.Exception.Message + $result.status = 'FAIL_NATIVE_MACHINE_AND_STANDARD_USER_MAINTENANCE' + $result['error'] = $failure } finally { - # Remove only objects this diagnostic created, even if query failed. - if ($machineClassCreated) { + if ($machineAttempted) { try { - Remove-Item -LiteralPath $machineClass -Recurse -Force - $result.machine_class_removed = -not (Test-Path -LiteralPath $machineClass) - if (-not $result.machine_class_removed) { throw 'Created machine COM class remains' } - } catch { $result.cleanup_errors += "Machine COM class: $($_.Exception.Message)" } + # The original archive helper can remove the installed EXE; + # the product deliberately refuses to delete its running self. + Invoke-MachineHelper $stageHelper '--uninstall-machine' 'machine_cleanup_exit' + foreach ($path in @($machineClass, $machineTip, $machineDirectory)) { + if (Test-Path -LiteralPath $path) { throw "Owned machine state remains after cleanup: $path" } + } + $result.machine_state_removed = $true + } catch { $result.cleanup_errors += "Machine cleanup: $($_.Exception.Message)" } } - if ($machineDirectoryCreated) { - try { - Remove-Item -LiteralPath $machineDirectory -Recurse -Force - $result.machine_directory_removed = -not (Test-Path -LiteralPath $machineDirectory) - if (-not $result.machine_directory_removed) { throw 'Created diagnostic directory remains' } - } catch { $result.cleanup_errors += "Diagnostic directory: $($_.Exception.Message)" } + if ($created) { + try { Remove-LocalUser -Name $name } + catch { $result.cleanup_errors += "Disposable account cleanup: $($_.Exception.Message)" } } - # Existing exact SmartKey helper cleanup remains unconditional. - try { - & $helper --uninstall --no-dialog 1> (Join-Path $root 'control-cleanup.stdout.txt') 2> (Join-Path $root 'control-cleanup.stderr.txt') - $result.cleanup_exit = $LASTEXITCODE - if ($result.cleanup_exit -ne 0) { $result.cleanup_errors += "Helper cleanup exit: $($result.cleanup_exit)" } - } catch { $result.cleanup_errors += "Helper cleanup: $($_.Exception.Message)" } - $result | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $root 'control-result.json') -Encoding utf8 - if (Test-Path -LiteralPath (Join-Path $root 'control-install.stderr.txt')) { - Get-Content -LiteralPath (Join-Path $root 'control-install.stderr.txt') + if ($result.cleanup_errors.Count -ne 0) { + $result.status = 'FAIL_NATIVE_MACHINE_AND_STANDARD_USER_MAINTENANCE' } - if (Test-Path -LiteralPath (Join-Path $root 'control-machine-com.stderr.txt')) { - Get-Content -LiteralPath (Join-Path $root 'control-machine-com.stderr.txt') + if (Test-Path -LiteralPath $root) { + $result | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $root 'machine-and-user-result.json') -Encoding utf8 + Get-ChildItem -LiteralPath $root -Recurse -File | Where-Object { + $_.Name -like '*.stdout.txt' -or $_.Name -like '*.stderr.txt' -or $_.Name -like '*result.json' + } | Sort-Object FullName | ForEach-Object { Get-Content -LiteralPath $_.FullName } } - Get-Content -LiteralPath (Join-Path $root 'control-result.json') } + if ($null -ne $failure) { throw $failure } + if ($result.cleanup_errors.Count -ne 0) { throw ($result.cleanup_errors -join '; ') } - name: Retain native standard-user result if: always() uses: actions/upload-artifact@v4 diff --git a/crates/smartkey-win/Cargo.toml b/crates/smartkey-win/Cargo.toml index a8485aa..7e8099f 100644 --- a/crates/smartkey-win/Cargo.toml +++ b/crates/smartkey-win/Cargo.toml @@ -23,6 +23,10 @@ windows = { version = "0.58", features = [ "Win32_UI_Input_KeyboardAndMouse", "Win32_System_Registry", "Win32_System_LibraryLoader", + "Win32_UI_Shell", + "Win32_Security", + "Win32_Security_Authorization", + "Win32_Storage_FileSystem", "implement", ] } diff --git a/crates/smartkey-win/packaging/Disable-SmartKey.cmd b/crates/smartkey-win/packaging/Disable-SmartKey.cmd index 26c6938..b9c496f 100644 --- a/crates/smartkey-win/packaging/Disable-SmartKey.cmd +++ b/crates/smartkey-win/packaging/Disable-SmartKey.cmd @@ -1,9 +1,9 @@ @echo off setlocal set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" -if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%LOCALAPPDATA%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%ProgramFiles%\SmartKey\smartkey-register.exe" if not exist "%SMARTKEY_HELPER%" ( - echo SmartKey helper is missing. Extract the whole SmartKey archive first. + echo SmartKey helper is missing. Extract the whole archive, then install the machine package once. pause exit /b 1 ) diff --git a/crates/smartkey-win/packaging/Enable-SmartKey.cmd b/crates/smartkey-win/packaging/Enable-SmartKey.cmd index c8b5da6..b44aa4e 100644 --- a/crates/smartkey-win/packaging/Enable-SmartKey.cmd +++ b/crates/smartkey-win/packaging/Enable-SmartKey.cmd @@ -1,9 +1,9 @@ @echo off setlocal set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" -if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%LOCALAPPDATA%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%ProgramFiles%\SmartKey\smartkey-register.exe" if not exist "%SMARTKEY_HELPER%" ( - echo SmartKey helper is missing. Extract the whole SmartKey archive first. + echo SmartKey helper is missing. Extract the whole archive, then install the machine package once. pause exit /b 1 ) diff --git a/crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd b/crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd new file mode 100644 index 0000000..0a24031 --- /dev/null +++ b/crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +rem Explicit machine action. Right-click this command in the extracted archive +rem and choose Run as administrator. No automatic elevation is attempted. +if not exist "%~dp0smartkey-register.exe" ( + echo Extract the whole original SmartKey archive before this machine action. + pause + exit /b 1 +) +"%~dp0smartkey-register.exe" --install-machine +if errorlevel 1 ( + echo Machine action was incomplete. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/Install-SmartKey.cmd b/crates/smartkey-win/packaging/Install-SmartKey.cmd index e612f3b..bec8598 100644 --- a/crates/smartkey-win/packaging/Install-SmartKey.cmd +++ b/crates/smartkey-win/packaging/Install-SmartKey.cmd @@ -1,9 +1,9 @@ @echo off setlocal set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" -if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%LOCALAPPDATA%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%ProgramFiles%\SmartKey\smartkey-register.exe" if not exist "%SMARTKEY_HELPER%" ( - echo SmartKey helper is missing. Extract the whole SmartKey archive first. + echo SmartKey helper is missing. Extract the whole archive, then install the machine package once. pause exit /b 1 ) diff --git a/crates/smartkey-win/packaging/README-WINDOWS.md b/crates/smartkey-win/packaging/README-WINDOWS.md index 462711c..b2452cf 100644 --- a/crates/smartkey-win/packaging/README-WINDOWS.md +++ b/crates/smartkey-win/packaging/README-WINDOWS.md @@ -1,20 +1,67 @@ -# SmartKey for Windows +# SmartKey for Windows 10/11 x64 -This folder contains the Windows application and public English/Bulgarian dictionaries. You do not need Git, Python, Rust or a repository checkout. Use the x64 bundle on Windows 10/11 x64 on a machine where you are allowed to install software. +This archive contains the complete application and public starter data. No Git, +Rust, Python or Visual C++ installer is required. Extract the whole archive; +keep it available for machine removal. Source/native acceptance status is +recorded separately in the supplied manifests; actual typing still needs a +Windows desktop check. -Extract the entire ZIP, then double-click **Install-SmartKey.cmd**. The visible result window reports success or the exact failed operation. Installation uses your account and does not request administrator elevation. If Windows or workplace policy refuses installation, the error remains visible; ask your administrator rather than bypassing that policy. +## Install once on a permitted computer -The installer copies the program to `%LOCALAPPDATA%\SmartKey`, and copies missing public dictionaries and starter configuration to `%APPDATA%\smartkey`. It preserves existing configuration, customized dictionaries and personal data. Keep the whole ZIP for repair or installation on another permitted machine. +If an older SmartKey Windows version is installed, remove that version before +installing this shared machine package. If this package is already installed and +user setup reports an old per-user COM conflict, ask an administrator to review +that exact registration. Do not blindly run the legacy uninstaller at that point: +it may remove the shared TSF catalog. Setup preserves the conflict rather than +deleting an unknown registration. -After installation, press **Win+Space** and choose **SmartKey**. Press **Win+Space** again to return to your normal keyboard whenever you want. Installation does not replace your existing layouts or change your default keyboard. Open a new text application if an application already running does not show the new choice. +An administrator is needed once to register the shared Windows text service. +Right-click **Install-Machine-SmartKey.cmd** in the extracted archive and choose +**Run as administrator**. It copies the complete bundle to the Windows Program +Files known folder, in **SmartKey**, and registers the machine COM/TSF catalog. +This phase does not enable SmartKey for the administrator, edit their AppData, +change their keyboards, or add a login entry. It refuses an existing machine +installation; remove it explicitly before replacing it. -SmartKey availability is enabled at Windows login through one current-user login entry. Start menu → **SmartKey** has: +Then close the administrator window. As the person who will type, double-click +**Install-SmartKey.cmd normally**. This enables SmartKey for that account, copies +only missing starter data to that user's **AppData\Roaming\smartkey**, verifies +it in a separate process, and adds one user login entry and Start menu commands. +Existing configuration, public corpus changes and personal files are preserved. +If machine installation is missing, this step stops with instructions before +changing user data or keyboard settings. It never triggers automatic elevation. +Each additional permitted user runs this normal step in their own account. -- **Status-SmartKey** — checks the installed profile and binary location. -- **Disable-SmartKey** — disables SmartKey and removes its login entry; your ordinary keyboards and personal data remain. -- **Enable-SmartKey** — enables SmartKey and its login entry again; select it with Win+Space. -- **Uninstall-SmartKey** — removes SmartKey registration and its login entry, then deletes the installed EXE/DLL. Personal data remains in `%APPDATA%\smartkey`. +## Use and return to your ordinary keyboard -Close applications using SmartKey before updating or uninstalling. If a file is still in use, removal reports the remaining file instead of claiming that it was deleted. After registration is removed you may delete the remaining `%LOCALAPPDATA%\SmartKey` support folder. Personal data is kept separately. +Press **Win+Space** and choose SmartKey. Press **Win+Space** again to select your +ordinary keyboard. Existing layouts and your default choice remain available. +Open a new text app after installation. SmartKey is available at the user's next +Windows login; it does not force itself to become the default keyboard. -No telemetry, network download, scheduled task or Windows service is installed. This package's build/registration checks do not replace validation of actual typing in your target applications. +Start menu > SmartKey provides **Status**, **Enable**, **Disable** and **Uninstall**. +Disable removes this user's SmartKey login entry. Enable restores availability +and login. Run these commands normally, without administrator elevation. + +## Remove + +**Uninstall-SmartKey.cmd** removes only the current user's availability, login +entry and menu commands. It preserves personal data and the shared machine files. + +When no one needs the shared installation, close apps using SmartKey. Right-click +**Uninstall-Machine-SmartKey.cmd in the original extracted archive** and choose +**Run as administrator**. It removes the exact shared catalog/COM registration and +allowlisted Program Files bundle. Run it from the archive, not the installed +Program Files directory, so the running helper can delete every machine file. +Other keyboards and all users' personal data are preserved. Machine removal does +not access other users' profiles; each configured user can remove their own login +entry using Uninstall-SmartKey.cmd from the archive. Locked files or failed +registration operations produce an error and can be retried; no success is claimed +for a partial removal. + +## Files and privacy + +The archive contains EXE/DLL, seven visible CMD commands, two manifests, public +JSON starter data, this README and license notices. It never includes personal.json. +User data stays in the user's AppData; no network connection is needed for setup +or typing. No service, scheduled task or PowerShell policy bypass is installed. diff --git a/crates/smartkey-win/packaging/Status-SmartKey.cmd b/crates/smartkey-win/packaging/Status-SmartKey.cmd index a77052f..47d7a4f 100644 --- a/crates/smartkey-win/packaging/Status-SmartKey.cmd +++ b/crates/smartkey-win/packaging/Status-SmartKey.cmd @@ -1,9 +1,9 @@ @echo off setlocal set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" -if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%LOCALAPPDATA%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%ProgramFiles%\SmartKey\smartkey-register.exe" if not exist "%SMARTKEY_HELPER%" ( - echo SmartKey helper is missing. Extract the whole SmartKey archive first. + echo SmartKey helper is missing. Extract the whole archive, then install the machine package once. pause exit /b 1 ) diff --git a/crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd b/crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd new file mode 100644 index 0000000..1375fa5 --- /dev/null +++ b/crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +rem Explicit machine action. Right-click this command in the extracted archive +rem and choose Run as administrator. No automatic elevation is attempted. +if not exist "%~dp0smartkey-register.exe" ( + echo Extract the whole original SmartKey archive before this machine action. + pause + exit /b 1 +) +"%~dp0smartkey-register.exe" --uninstall-machine +if errorlevel 1 ( + echo Machine action was incomplete. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/Uninstall-SmartKey.cmd b/crates/smartkey-win/packaging/Uninstall-SmartKey.cmd index d61a362..6507bea 100644 --- a/crates/smartkey-win/packaging/Uninstall-SmartKey.cmd +++ b/crates/smartkey-win/packaging/Uninstall-SmartKey.cmd @@ -1,32 +1,19 @@ @echo off setlocal -set "SMARTKEY_HELPER=%LOCALAPPDATA%\SmartKey\smartkey-register.exe" -if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%ProgramFiles%\SmartKey\smartkey-register.exe" if not exist "%SMARTKEY_HELPER%" ( - echo SmartKey helper is missing; registration removal was not attempted. + echo SmartKey helper is missing. Extract the whole archive, then install the machine package once. pause exit /b 1 ) "%SMARTKEY_HELPER%" --uninstall if errorlevel 1 ( - echo Removal was incomplete. Staged files have been retained so you can retry. + echo SmartKey could not complete the action. The error window describes the failure. pause exit /b 1 ) -rem Delete only the installed SmartKey binaries, after the helper has exited. -del /q "%LOCALAPPDATA%\SmartKey\smartkey_win.dll" "%LOCALAPPDATA%\SmartKey\smartkey-register.exe" 2>nul -if exist "%LOCALAPPDATA%\SmartKey\smartkey_win.dll" ( - echo Registration removed. Close apps using SmartKey before deleting the remaining DLL. - pause - exit /b 1 -) -if exist "%LOCALAPPDATA%\SmartKey\smartkey-register.exe" ( - echo Registration removed. The helper file could not be deleted; remove it after closing it. - pause - exit /b 1 -) -echo SmartKey removed. Your keyboards and AppData\smartkey personal data were preserved. -rem The final parsed block can remove this Start menu command after all work. +rem Remove this currently running user menu command only in the final block. ( del /q "%APPDATA%\Microsoft\Windows\Start Menu\Programs\SmartKey\Uninstall-SmartKey.cmd" 2>nul exit /b 0 diff --git a/crates/smartkey-win/packaging/smoke-user.ps1 b/crates/smartkey-win/packaging/smoke-user.ps1 index be3099f..d0e3314 100644 --- a/crates/smartkey-win/packaging/smoke-user.ps1 +++ b/crates/smartkey-win/packaging/smoke-user.ps1 @@ -3,7 +3,8 @@ [CmdletBinding()] param( [Parameter(Mandatory=$true)][string]$Bundle, - [Parameter(Mandatory=$true)][string]$OutDir + [Parameter(Mandatory=$true)][string]$OutDir, + [ValidateSet('Prerequisite', 'Lifecycle')][string]$Phase = 'Lifecycle' ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest @@ -36,11 +37,14 @@ foreach ($pair in @(@($env:USERPROFILE, $actualProfile), @($env:LOCALAPPDATA, $a } } $bundlePath = (Resolve-Path -LiteralPath $Bundle).Path -$install = Join-Path $env:LOCALAPPDATA 'SmartKey' +$install = Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::ProgramFiles)) 'SmartKey' +$localInstall = Join-Path $env:LOCALAPPDATA 'SmartKey' $data = Join-Path $env:APPDATA 'smartkey' $run = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' $clsid = 'HKCU:\SOFTWARE\Classes\CLSID\{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' $tip = 'HKCU:\Software\Microsoft\CTF\TIP\{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' +$machineClass = 'HKLM:\SOFTWARE\Classes\CLSID\{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' +$machineTip = 'HKLM:\Software\Microsoft\CTF\TIP\{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' $menu = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\SmartKey' New-Item -ItemType Directory -Path $OutDir -Force | Out-Null @@ -73,9 +77,25 @@ function Keyboard-Snapshot { $snapshot['WindowsDefaultInputTip'] = if ($null -ne $default) { $default.InputTip } else { $null } return ($snapshot | ConvertTo-Json -Depth 4 -Compress) } +function Machine-Snapshot { + # Only this product's protected files and exact machine identities are read. + $files = @(Get-ChildItem -LiteralPath $install -File -Force | Sort-Object Name | ForEach-Object { + [ordered]@{ name=$_.Name; sha256=(Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash } + }) + $registry = foreach ($path in @($machineClass, $machineTip)) { + Assert-True (Test-Path -LiteralPath $path) "Missing machine registration: $path" + $keys = @((Get-Item -LiteralPath $path)) + @(Get-ChildItem -LiteralPath $path -Recurse | Sort-Object Name) + foreach ($key in $keys) { + $values = [ordered]@{} + foreach ($name in @($key.GetValueNames() | Sort-Object)) { $values[$name] = $key.GetValue($name) } + [ordered]@{ path=$key.Name; values=$values } + } + } + return ([ordered]@{ files=$files; registry=@($registry) } | ConvertTo-Json -Depth 8 -Compress) +} $steps = New-Object System.Collections.Generic.List[object] -function Invoke-Helper([string]$exe, [string]$action) { - $stem = $action.TrimStart('-') +function Invoke-Helper([string]$exe, [string]$action, [int]$expectedExit = 0) { + $stem = '{0:D2}-{1}' -f $steps.Count, $action.TrimStart('-') $stdout = Join-Path $OutDir "$stem.stdout.txt" $stderr = Join-Path $OutDir "$stem.stderr.txt" # Keep our own .NET Process/handle from Start through ExitCode. Windows @@ -104,34 +124,68 @@ function Invoke-Helper([string]$exe, [string]$action) { } $exitCode = $process.ExitCode if ($null -eq $exitCode) { throw "$action exited but its real exit code was unavailable; refusing an inferred result." } - [IO.File]::WriteAllText($stdout, $stdoutTask.GetAwaiter().GetResult()) - [IO.File]::WriteAllText($stderr, $stderrTask.GetAwaiter().GetResult()) - $steps.Add([ordered]@{ action=$action; exit_code=[int]$exitCode }) - if ($exitCode -ne 0) { - throw "$action failed (exit $exitCode); see $stderr." + $stdoutText = $stdoutTask.GetAwaiter().GetResult() + $stderrText = $stderrTask.GetAwaiter().GetResult() + [IO.File]::WriteAllText($stdout, $stdoutText) + [IO.File]::WriteAllText($stderr, $stderrText) + $steps.Add([ordered]@{ action=$action; exit_code=[int]$exitCode; expected_exit=$expectedExit }) + if ($exitCode -ne $expectedExit) { + throw "$action returned exit $exitCode (required $expectedExit); see $stderr." } + return [pscustomobject]@{ stdout=$stdoutText; stderr=$stderrText } } finally { $process.Dispose() } } $receipt = [ordered]@{ status='NOT_RUN'; standard_nonadmin=$true; current_user_profile_confirmed=$true; no_dialog=$true - typing_exercised=$false; logon_exercised=$false + phase=$Phase; typing_exercised=$false; logon_exercised=$false steps=$steps; keyboard_defaults_preserved=$false; personal_sentinel_preserved=$false + machine_prerequisite_refused=$false; machine_install_preserved=$false } $before = Keyboard-Snapshot try { # Never use a daily account or delete a prior installation for this smoke. - Assert-True (-not (Test-Path -LiteralPath $install)) 'The ephemeral user already has a SmartKey install folder.' + Assert-True (-not (Test-Path -LiteralPath $localInstall)) 'The ephemeral user already has a SmartKey install folder.' Assert-True (-not (Test-Path -LiteralPath $data)) 'The ephemeral user already has SmartKey data.' Assert-True (-not (Test-Path -LiteralPath $clsid)) 'The ephemeral user already has SmartKey COM registration.' + Assert-True (-not (Test-Path -LiteralPath $tip)) 'The ephemeral user already has SmartKey user enablement.' + Assert-True (-not (Test-Path -LiteralPath $menu)) 'The ephemeral user already has a SmartKey Start menu folder.' Assert-True ($null -eq (Get-Login)) 'An existing SmartKey Run value must not be overwritten by this smoke.' + if ($Phase -eq 'Prerequisite') { + foreach ($path in @($install, $machineClass, $machineTip)) { + Assert-True (-not (Test-Path -LiteralPath $path)) 'The prerequisite refusal requires a fresh machine without SmartKey.' + } + $refusal = Invoke-Helper (Join-Path $bundlePath 'smartkey-register.exe') '--install' 1 + Assert-True ($refusal.stderr.Contains('SmartKey machine installation is missing.') -and + $refusal.stderr.Contains('Install-Machine-SmartKey.cmd')) 'Missing-machine refusal did not explain the supported administrator setup.' + foreach ($path in @($data, $menu, $localInstall, $clsid, $tip, $install, $machineClass, $machineTip)) { + Assert-True (-not (Test-Path -LiteralPath $path)) "Prerequisite refusal created unexpected state: $path" + } + Assert-True ($null -eq (Get-Login)) 'Prerequisite refusal created a login entry.' + Assert-True ((Keyboard-Snapshot) -eq $before) 'Prerequisite refusal changed keyboard/default settings.' + $receipt['machine_prerequisite_refused']=$true + $receipt['keyboard_defaults_preserved']=$true + $receipt['status']='PASS_NATIVE_STANDARD_USER_PREREQUISITE' + return + } + + $expectedFiles = @(Get-ChildItem -LiteralPath $bundlePath -Force | ForEach-Object Name | Sort-Object) + $actualFiles = @(Get-ChildItem -LiteralPath $install -Force | ForEach-Object Name | Sort-Object) + Assert-True (-not (Compare-Object -ReferenceObject $expectedFiles -DifferenceObject $actualFiles)) 'Protected install does not contain the exact frozen bundle.' + foreach ($name in $expectedFiles) { + Assert-True ((Get-FileHash -LiteralPath (Join-Path $bundlePath $name) -Algorithm SHA256).Hash -eq + (Get-FileHash -LiteralPath (Join-Path $install $name) -Algorithm SHA256).Hash) "Protected file differs from frozen bundle: $name" + } + $machineBefore = Machine-Snapshot + $helper = Join-Path $install 'smartkey-register.exe' + $initialStatus = Invoke-Helper $helper '--status' + Assert-True ($initialStatus.stdout -match '(?m)^TSF profile: disabled\.') 'Machine registration enabled SmartKey before this user opted in.' New-Item -ItemType Directory -Path $data | Out-Null $personal = Join-Path $data 'personal.json' [IO.File]::WriteAllText($personal, '{"synthetic_smoke_sentinel":true}') $personalHash = (Get-FileHash -LiteralPath $personal -Algorithm SHA256).Hash - Invoke-Helper (Join-Path $bundlePath 'smartkey-register.exe') '--install' - $helper = Join-Path $install 'smartkey-register.exe' + Invoke-Helper (Join-Path $bundlePath 'smartkey-register.exe') '--install' | Out-Null foreach ($name in @('smartkey-register.exe','smartkey_win.dll','Install-SmartKey.cmd','Status-SmartKey.cmd','Enable-SmartKey.cmd','Disable-SmartKey.cmd','Uninstall-SmartKey.cmd')) { Assert-True (Test-Path -LiteralPath (Join-Path $install $name) -PathType Leaf) "Missing staged file: $name" } @@ -143,28 +197,33 @@ try { } Assert-True ((Get-Login) -eq ('"' + $helper + '" --login')) 'Login entry does not identify the stable installed helper.' Assert-True ((Keyboard-Snapshot) -eq $before) 'Installation changed existing keyboard/default settings.' - Invoke-Helper $helper '--status' - Invoke-Helper $helper '--disable' + Invoke-Helper $helper '--status' | Out-Null + Invoke-Helper $helper '--disable' | Out-Null Assert-True ($null -eq (Get-Login)) 'Disable left the owned login entry.' Assert-True ((Keyboard-Snapshot) -eq $before) 'Disable changed existing keyboard/default settings.' - Invoke-Helper $helper '--enable' + Invoke-Helper $helper '--enable' | Out-Null Assert-True ((Get-Login) -eq ('"' + $helper + '" --login')) 'Enable did not restore the exact owned login entry.' - Invoke-Helper $helper '--uninstall' + Invoke-Helper $helper '--uninstall' | Out-Null Assert-True ($null -eq (Get-Login)) 'Uninstall left the owned login entry.' Assert-True (-not (Test-Path -LiteralPath $clsid)) 'Uninstall left own HKCU COM registration.' - Assert-True (-not (Test-Path -LiteralPath $tip)) 'Uninstall left own HKCU TIP registration.' + # Windows may retain an explicit per-user disabled marker. Verify the API + # state in a fresh process instead of deleting that supported state by hand. + $status = Invoke-Helper $helper '--status' + Assert-True ($status.stdout -match '(?m)^TSF profile: disabled\.') 'Fresh process did not report the uninstalled user profile disabled.' + Invoke-Helper $helper '--verify-machine' | Out-Null + foreach ($name in @('Status-SmartKey.cmd','Enable-SmartKey.cmd','Disable-SmartKey.cmd')) { + Assert-True (-not (Test-Path -LiteralPath (Join-Path $menu $name))) "Uninstall left a user maintenance command: $name" + } Assert-True ((Keyboard-Snapshot) -eq $before) 'Maintenance changed existing keyboard/default settings.' Assert-True ((Get-FileHash -LiteralPath $personal -Algorithm SHA256).Hash -eq $personalHash) 'Maintenance changed the synthetic personal file.' - # The EXE API uninstalls integration; the user-facing CMD performs file - # removal afterwards. Mirror only that exact binary deletion here. - Remove-Item -LiteralPath (Join-Path $install 'smartkey_win.dll'), $helper - Assert-True (-not (Test-Path -LiteralPath $helper)) 'Helper binary remains.' - Assert-True (-not (Test-Path -LiteralPath (Join-Path $install 'smartkey_win.dll'))) 'DLL remains.' + Assert-True (-not (Test-Path -LiteralPath $localInstall)) 'User setup created an unprotected local binary folder.' + Assert-True ((Machine-Snapshot) -eq $machineBefore) 'User maintenance changed the protected bundle or machine registration.' $receipt['keyboard_defaults_preserved']=$true $receipt['personal_sentinel_preserved']=$true + $receipt['machine_install_preserved']=$true $receipt['status']='PASS_NATIVE_STANDARD_USER_MAINTENANCE' } catch { - $receipt['status']='FAIL_NATIVE_STANDARD_USER_MAINTENANCE' + $receipt['status']='FAIL_NATIVE_STANDARD_USER_' + $Phase.ToUpperInvariant() $receipt['error']=$_.Exception.Message throw } finally { diff --git a/crates/smartkey-win/packaging/user_setup.rs b/crates/smartkey-win/packaging/user_setup.rs index 73d7a93..f5a2c86 100644 --- a/crates/smartkey-win/packaging/user_setup.rs +++ b/crates/smartkey-win/packaging/user_setup.rs @@ -12,6 +12,10 @@ pub const DATA: &[&str] = &[ ]; pub const SUPPORT: &[&str] = &[ "Install-SmartKey.cmd", + "Install-Machine-SmartKey.cmd", + "Uninstall-Machine-SmartKey.cmd", + "windows-runtime-manifest.json", + "artifact-source-manifest.json", "Status-SmartKey.cmd", "Enable-SmartKey.cmd", "Disable-SmartKey.cmd", @@ -22,32 +26,128 @@ pub const SUPPORT: &[&str] = &[ "LICENSE-APACHE", ]; -/// Validate the entire distribution before touching the destination. Existing -/// configuration, public corpus customizations and personal files are retained. -pub fn stage(bundle: &Path, install: &Path, data: &Path) -> io::Result { +/// Validate every required payload before touching any destination. +pub fn validate_bundle(bundle: &Path) -> io::Result<()> { for name in BINARIES.iter().chain(DATA).chain(SUPPORT) { let path = bundle.join(name); - if !path.is_file() || fs::metadata(&path)?.len() == 0 { + let metadata = fs::symlink_metadata(&path)?; + if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() == 0 { return Err(io::Error::new( - io::ErrorKind::NotFound, - format!("Incomplete SmartKey bundle: {name}. Extract the whole archive first."), + io::ErrorKind::InvalidData, + format!("Incomplete or redirected SmartKey bundle: {name}. Extract the whole archive first."), )); } } - fs::create_dir_all(install)?; - fs::create_dir_all(data)?; - for name in BINARIES.iter().chain(SUPPORT).chain(DATA) { - let from = bundle.join(name); - let to = install.join(name); - // Running the installed helper again must not overwrite itself. - if from.canonicalize()? != to.canonicalize().unwrap_or_else(|_| to.clone()) { - fs::copy(from, to)?; - } + Ok(()) +} + +/// Machine phase: destination must be new, with a protected parent validated +/// by the Windows caller. It never creates or reads any user's data folder. +pub fn stage_machine(bundle: &Path, install: &Path) -> io::Result { + validate_bundle(bundle)?; + create_machine_directory(install)?; + for name in BINARIES.iter().chain(DATA).chain(SUPPORT) { + let mut source = fs::File::open(bundle.join(name))?; + let mut destination = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(install.join(name))?; + set_machine_file_owner(&install.join(name))?; + io::copy(&mut source, &mut destination)?; + } + Ok(install.join("smartkey-register.exe")) +} + +#[cfg(not(windows))] +fn set_machine_file_owner(_path: &Path) -> io::Result<()> { + Ok(()) +} + +#[cfg(windows)] +fn set_machine_file_owner(path: &Path) -> io::Result<()> { + use windows::core::*; + use windows::Win32::Security::Authorization::{SetNamedSecurityInfoW, SE_FILE_OBJECT}; + use windows::Win32::Security::{ + CreateWellKnownSid, WinBuiltinAdministratorsSid, OWNER_SECURITY_INFORMATION, PSID, + }; + let mut storage = [0u32; 17]; + let sid = PSID(storage.as_mut_ptr().cast()); + let mut size = std::mem::size_of_val(&storage) as u32; + unsafe { CreateWellKnownSid(WinBuiltinAdministratorsSid, PSID::default(), sid, &mut size) } + .map_err(io::Error::other)?; + let name: Vec = path + .as_os_str() + .to_string_lossy() + .encode_utf16() + .chain(Some(0)) + .collect(); + let status = unsafe { + SetNamedSecurityInfoW( + PCWSTR(name.as_ptr()), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION, + sid, + PSID::default(), + None, + None, + ) + }; + if status.0 != 0 { + return Err(io::Error::other(Error::from(HRESULT::from_win32(status.0)))); + } + Ok(()) +} + +#[cfg(not(windows))] +fn create_machine_directory(path: &Path) -> io::Result<()> { + fs::create_dir(path) +} + +#[cfg(windows)] +fn create_machine_directory(path: &Path) -> io::Result<()> { + use windows::core::*; + use windows::Win32::Foundation::{LocalFree, HLOCAL}; + use windows::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW; + use windows::Win32::Security::{PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES}; + use windows::Win32::Storage::FileSystem::CreateDirectoryW; + let mut descriptor = PSECURITY_DESCRIPTOR::default(); + unsafe { + // Administrators own the directory. Only SYSTEM/Administrators can + // write; users can read/execute. Children inherit the same grants. + ConvertStringSecurityDescriptorToSecurityDescriptorW( + w!("O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FRFX;;;BU)"), + 1, + &mut descriptor, + None, + ) + } + .map_err(io::Error::other)?; + let attributes = SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: descriptor.0, + bInheritHandle: false.into(), + }; + let name: Vec = path + .as_os_str() + .to_string_lossy() + .encode_utf16() + .chain(Some(0)) + .collect(); + let result = unsafe { CreateDirectoryW(PCWSTR(name.as_ptr()), Some(&attributes)) }; + unsafe { + LocalFree(HLOCAL(descriptor.0)); } + result.map_err(io::Error::other) +} + +/// Normal-user phase: copy only missing starter data from the verified machine +/// bundle. It never stages DLLs/EXEs and preserves existing personal files. +pub fn stage_user_data(bundle: &Path, data: &Path) -> io::Result<()> { + validate_bundle(bundle)?; + fs::create_dir_all(data)?; for name in DATA { let to = data.join(name); if !to.exists() { - // create_new prevents racing another installer or user editor. let mut destination = fs::OpenOptions::new() .write(true) .create_new(true) @@ -56,7 +156,40 @@ pub fn stage(bundle: &Path, install: &Path, data: &Path) -> io::Result io::copy(&mut source, &mut destination)?; } } - Ok(install.join("smartkey-register.exe")) + Ok(()) +} + +/// Remove only allowlisted files in the exact verified machine directory. +/// Refuse unknown objects before deleting anything; never recursive-delete. +pub fn remove_machine_files(install: &Path) -> io::Result<()> { + if !install.exists() { + return Ok(()); + } + let expected: Vec<_> = BINARIES + .iter() + .chain(DATA) + .chain(SUPPORT) + .copied() + .collect(); + for entry in fs::read_dir(install)? { + let entry = entry?; + if !entry.file_type()?.is_file() + || !expected + .iter() + .any(|name| entry.file_name() == std::ffi::OsStr::new(name)) + { + return Err(io::Error::other( + "Unexpected object in SmartKey machine directory; it was preserved", + )); + } + } + for name in expected { + let path = install.join(name); + if path.exists() { + fs::remove_file(path)?; + } + } + fs::remove_dir(install) } #[cfg(test)] @@ -90,48 +223,73 @@ mod tests { } } #[test] - fn stages_binaries_and_missing_data_but_preserves_user_files() { + fn machine_stage_does_not_create_user_data_and_refuses_existing_destination() { let s = Scratch::new(); let bundle = s.bundle(); - let install = s.0.join("Local/SmartKey"); - let data = s.0.join("Roaming/smartkey"); - fs::create_dir_all(&data).unwrap(); - fs::write(data.join("smartkey.json"), "existing user config").unwrap(); - fs::write(data.join("personal.json"), "existing personal data").unwrap(); - fs::write(data.join("corpus_en.json"), "custom corpus").unwrap(); + let install = s.0.join("ProgramFiles-SmartKey"); + let personal = s.0.join("Roaming-smartkey"); + stage_machine(&bundle, &install).unwrap(); + assert!(!personal.exists()); + fs::write(install.join("smartkey_win.dll"), "existing machine binary").unwrap(); + assert!(stage_machine(&bundle, &install).is_err()); assert_eq!( - stage(&bundle, &install, &data).unwrap(), - install.join("smartkey-register.exe") + fs::read(install.join("smartkey_win.dll")).unwrap(), + b"existing machine binary" ); + } + + #[test] + fn user_stage_preserves_personal_data_and_never_stages_binaries() { + let s = Scratch::new(); + let bundle = s.bundle(); + let data = s.0.join("Roaming-smartkey"); + fs::create_dir(&data).unwrap(); + fs::write(data.join("smartkey.json"), "existing config").unwrap(); + fs::write(data.join("personal.json"), "private sentinel").unwrap(); + fs::write(data.join("corpus_en.json"), "custom corpus").unwrap(); + stage_user_data(&bundle, &data).unwrap(); + stage_user_data(&bundle, &data).unwrap(); assert_eq!( fs::read(data.join("smartkey.json")).unwrap(), - b"existing user config" + b"existing config" ); assert_eq!( fs::read(data.join("personal.json")).unwrap(), - b"existing personal data" + b"private sentinel" ); assert_eq!( fs::read(data.join("corpus_en.json")).unwrap(), b"custom corpus" ); - assert_eq!( - fs::read(install.join("smartkey_win.dll")).unwrap(), - fs::read(bundle.join("smartkey_win.dll")).unwrap() - ); assert!(data.join("corpus_bg.json").is_file()); - // Reinstall is allowed from both distribution and installed location. - stage(&bundle, &install, &data).unwrap(); - stage(&install, &install, &data).unwrap(); + assert!(!data.join("smartkey_win.dll").exists()); + assert!(!data.join("smartkey-register.exe").exists()); } + #[test] - fn missing_payload_refuses_before_destination_changes() { + fn incomplete_bundle_refuses_machine_and_user_destinations() { let s = Scratch::new(); let bundle = s.bundle(); fs::remove_file(bundle.join("smartkey_win.dll")).unwrap(); let install = s.0.join("install"); let data = s.0.join("data"); - assert!(stage(&bundle, &install, &data).is_err()); - assert!(!install.exists() && !data.exists()); + assert!(stage_machine(&bundle, &install).is_err()); + assert!(stage_user_data(&bundle, &data).is_err()); + assert!(!install.exists()); + assert!(!data.exists()); + } + + #[test] + fn machine_removal_refuses_unknown_objects_before_deleting_known_files() { + let s = Scratch::new(); + let bundle = s.bundle(); + let install = s.0.join("install"); + stage_machine(&bundle, &install).unwrap(); + fs::write(install.join("unexpected.txt"), "preserved").unwrap(); + assert!(remove_machine_files(&install).is_err()); + assert!(install.join("smartkey_win.dll").is_file()); + fs::remove_file(install.join("unexpected.txt")).unwrap(); + remove_machine_files(&install).unwrap(); + assert!(!install.exists()); } } diff --git a/crates/smartkey-win/src/register.rs b/crates/smartkey-win/src/register.rs index 40aaabf..4d6a69d 100644 --- a/crates/smartkey-win/src/register.rs +++ b/crates/smartkey-win/src/register.rs @@ -49,110 +49,342 @@ fn main() { #[cfg(windows)] fn run(action: &str) -> Result { use smartkey_win::registration; - use std::path::PathBuf; - let local = - PathBuf::from(std::env::var_os("LOCALAPPDATA").ok_or("LOCALAPPDATA is unavailable")?); - let roaming = PathBuf::from(std::env::var_os("APPDATA").ok_or("APPDATA is unavailable")?); - let install = local.join("SmartKey"); + let install = machine_install_dir()?; let installed_exe = install.join("smartkey-register.exe"); let expected_dll = install.join("smartkey_win.dll"); let exe = std::env::current_exe().map_err(|e| e.to_string())?; let bundle = exe.parent().ok_or("Cannot locate SmartKey bundle")?; let _com = Com::new()?; - let api_error = |e: windows::core::Error| { - format!("{} (HRESULT 0x{:08X}).\nNo administrator fallback was attempted. Existing keyboards remain available through Win+Space.", e, e.code().0 as u32) - }; match action { - "--install" => { - user_setup::stage(bundle, &install, &roaming.join("smartkey")) - .map_err(|e| format!("Cannot stage the SmartKey bundle: {e}. Close apps using SmartKey before updating."))?; - let dll = expected_dll - .to_str() - .ok_or("DLL path is not valid Unicode")?; - registration::register(dll).map_err(api_error)?; - // Diagnostic only: the fresh child below remains the acceptance check, - // including when this same query fails in the installing process. - match registration::profile_enabled() { - Ok(enabled) => println!( - "SmartKey diagnostic: in-process TSF profile query succeeded; enabled={enabled}" - ), - Err(error) => eprintln!( - "SmartKey diagnostic: in-process TSF profile query failed: {}", - api_error(error) - ), + "--install-machine" => { + require_elevation(true)?; + let parent = install.parent().ok_or("Cannot locate Program Files")?; + validate_protected_path(parent)?; + if registry_class_exists(windows::Win32::System::Registry::HKEY_LOCAL_MACHINE) + .map_err(api_error)? || install.exists() { + return Err("A SmartKey machine installation or destination already exists. It was preserved. Run Uninstall-Machine-SmartKey.cmd from the extracted archive before installing a replacement.".into()); + } + user_setup::stage_machine(bundle, &install) + .map_err(|e| format!("Cannot stage protected machine bundle: {e}. Any partial destination was retained for explicit machine removal."))?; + validate_machine_objects(&install)?; + registration::register_machine(expected_dll.to_str().ok_or("DLL path is not Unicode")?) + .map_err(api_error)?; + fresh_verification(&installed_exe, "--verify-machine")?; + Ok("SmartKey machine files and TSF catalog installed. No user's data, keyboard availability or login entry was configured.\n\nClose this administrator window, then double-click Install-SmartKey.cmd normally as each user who wants SmartKey.".into()) + } + "--verify-machine" => { + verify_machine_install(&install)?; + registration::profile_present().map_err(api_error)?; + Ok("SmartKey protected machine COM path and persistent TSF profile verified. User enablement was not required or changed.".into()) + } + "--uninstall-machine" => { + require_elevation(true)?; + if exe.starts_with(&install) { + return Err("Run Uninstall-Machine-SmartKey.cmd from the extracted original archive, outside Program Files\\SmartKey, so the running helper can remove all machine files.".into()); } - // A separate process queries the actual persisted TSF profile. - // A process-local registration cannot pass this check. - let verification = std::process::Command::new(&installed_exe) - .arg("--verify") - .output() - .map_err(|e| format!("Cannot verify in a fresh process: {e}"))?; - if !verification.status.success() { - return Err(format!("Fresh-process SmartKey verification failed.\n{}\nRun Uninstall-SmartKey.cmd to remove any partial registration.", String::from_utf8_lossy(&verification.stderr))); + validate_protected_path(install.parent().ok_or("Cannot locate Program Files")?)?; + if install.exists() { validate_machine_objects(&install)?; } + if registry_class_exists(windows::Win32::System::Registry::HKEY_LOCAL_MACHINE).map_err(api_error)? { + verify_com_path(&expected_dll).map_err(api_error)?; } - set_login(true, &installed_exe).map_err(api_error)?; + registration::unregister_machine().map_err(api_error)?; + user_setup::remove_machine_files(&install) + .map_err(|e| format!("Machine registration removed, but machine file removal failed: {e}. Close apps using SmartKey and retry this command from the extracted archive."))?; + Ok("SmartKey machine catalog, COM registration and protected files removed. User data, other keyboards and user login entries were preserved. Each configured user can run Uninstall-SmartKey.cmd to remove their own login/menu entries.".into()) + } + "--install" | "--enable" | "--disable" | "--login" | "--uninstall" => { + require_elevation(false)?; + refuse_user_com_override()?; + if action != "--uninstall" { verify_machine_install(&install)?; } + let roaming = known_folder(&windows::Win32::UI::Shell::FOLDERID_RoamingAppData)?; let menu = roaming.join("Microsoft/Windows/Start Menu/Programs/SmartKey"); - std::fs::create_dir_all(&menu).map_err(|e| e.to_string())?; - for name in [ - "Status-SmartKey.cmd", - "Enable-SmartKey.cmd", - "Disable-SmartKey.cmd", - "Uninstall-SmartKey.cmd", - ] { - std::fs::copy(install.join(name), menu.join(name)).map_err(|e| e.to_string())?; + match action { + "--install" => { + // Machine prerequisite above precedes every user mutation. + registration::profile_present().map_err(api_error)?; + user_setup::stage_user_data(&install, &roaming.join("smartkey")) + .map_err(|e| format!("Cannot stage missing user data: {e}"))?; + registration::set_user_enabled(true).map_err(api_error)?; + fresh_verification(&installed_exe, "--verify")?; + set_login(true, &installed_exe).map_err(api_error)?; + std::fs::create_dir_all(&menu).map_err(|e| e.to_string())?; + for name in ["Status-SmartKey.cmd", "Enable-SmartKey.cmd", "Disable-SmartKey.cmd", "Uninstall-SmartKey.cmd"] { + std::fs::copy(install.join(name), menu.join(name)).map_err(|e| e.to_string())?; + } + Ok("SmartKey enabled for this user.\n\nPress Win+Space and select SmartKey; press Win+Space again to return to your ordinary keyboard. Existing layouts and default choice were preserved.\n\nSmartKey is available at Windows login. Start menu > SmartKey provides Status, Enable, Disable and Uninstall. Existing personal data/configuration were preserved. Open a new text app to begin.".into()) + } + "--enable" | "--login" => { + registration::set_user_enabled(true).map_err(api_error)?; + if !registration::profile_enabled().map_err(api_error)? { return Err("Windows did not enable the SmartKey profile".into()); } + if action == "--enable" { set_login(true, &installed_exe).map_err(api_error)?; } + Ok("SmartKey enabled for this user and available at login. Select it with Win+Space; your default keyboard was preserved.".into()) + } + "--disable" => { + registration::set_user_enabled(false).map_err(api_error)?; + set_login(false, &installed_exe).map_err(api_error)?; + if registration::profile_enabled().map_err(api_error)? { return Err("Windows still reports SmartKey enabled".into()); } + Ok("SmartKey disabled and its login entry removed. Use Win+Space to select your ordinary keyboard. Enable-SmartKey restores it; personal data is unchanged.".into()) + } + "--uninstall" => { + // User removal remains usable after the machine package is removed. + set_login(false, &installed_exe).map_err(api_error)?; + if install.exists() { + verify_machine_install(&install)?; + registration::unregister_user().map_err(api_error)?; + if registration::profile_enabled().map_err(api_error)? { return Err("Windows still reports this user's SmartKey profile enabled after removal".into()); } + } + for name in ["Status-SmartKey.cmd", "Enable-SmartKey.cmd", "Disable-SmartKey.cmd"] { + let path = menu.join(name); + if path.exists() { std::fs::remove_file(path).map_err(|e| e.to_string())?; } + } + Ok("SmartKey removed for this user. Its login entry was removed; ordinary keyboards, personal data and shared machine files were preserved. Use Uninstall-Machine-SmartKey.cmd from the extracted archive as administrator only when shared machine removal is wanted.".into()) + } + _ => unreachable!(), } - Ok("SmartKey installed for this user.\n\nPress Win+Space and select SmartKey. Press Win+Space again to return to your usual keyboard. Your existing layouts and default choice were preserved.\n\nSmartKey is available again at Windows login. Start menu > SmartKey provides Status, Enable, Disable and Uninstall. Existing personal data/configuration were preserved.\n\nOpen a new text app to begin.".into()) } "--verify" | "--status" => { - verify_com_path(&expected_dll).map_err(api_error)?; + refuse_user_com_override()?; + verify_machine_install(&install)?; let enabled = registration::profile_enabled().map_err(api_error)?; - if action == "--verify" && !enabled { - return Err("SmartKey profile exists but is disabled".into()); - } - Ok(format!("SmartKey current-user COM path verified.\nTSF profile: {}.\nBinary folder: {}\nData folder: {}\nUse Win+Space to choose SmartKey or an existing ordinary keyboard.", if enabled { "enabled" } else { "disabled" }, install.display(), roaming.join("smartkey").display())) + if action == "--verify" && !enabled { return Err("SmartKey profile exists but is disabled".into()); } + Ok(format!("SmartKey protected machine COM path verified.\nTSF profile: {}.\nUse Win+Space to choose SmartKey or an existing ordinary keyboard.", if enabled { "enabled" } else { "disabled" })) } - "--enable" | "--login" => { - verify_com_path(&expected_dll).map_err(api_error)?; - registration::set_user_enabled(true).map_err(api_error)?; - if !registration::profile_enabled().map_err(api_error)? { - return Err("Windows did not enable the SmartKey profile".into()); - } - if action == "--enable" { - set_login(true, &installed_exe).map_err(api_error)?; - } - Ok("SmartKey enabled for this user and available at login. Select it with Win+Space; your default keyboard was preserved.".into()) + _ => Err("Use --install, --status, --enable, --disable, --uninstall, --install-machine or --uninstall-machine.".into()), + } +} + +#[cfg(windows)] +fn api_error(error: windows::core::Error) -> String { + format!( + "{} (HRESULT 0x{:08X}). Existing keyboards remain available through Win+Space.", + error, + error.code().0 as u32 + ) +} + +#[cfg(windows)] +fn fresh_verification(helper: &std::path::Path, action: &str) -> Result<(), String> { + let result = std::process::Command::new(helper) + .arg(action) + .arg("--no-dialog") + .output() + .map_err(|e| format!("Cannot verify in a fresh process: {e}"))?; + if !result.status.success() { + return Err(format!( + "Fresh-process SmartKey verification failed.\n{}", + String::from_utf8_lossy(&result.stderr) + )); + } + Ok(()) +} + +#[cfg(windows)] +fn machine_install_dir() -> Result { + Ok(known_folder(&windows::Win32::UI::Shell::FOLDERID_ProgramFiles)?.join("SmartKey")) +} + +#[cfg(windows)] +fn known_folder(id: &windows::core::GUID) -> Result { + use windows::Win32::UI::Shell::{SHGetKnownFolderPath, KF_FLAG_DEFAULT}; + let raw = unsafe { SHGetKnownFolderPath(id, KF_FLAG_DEFAULT, None) }.map_err(api_error)?; + let result = unsafe { raw.to_string() }.map_err(|e| e.to_string()); + unsafe { + windows::Win32::System::Com::CoTaskMemFree(Some(raw.0.cast())); + } + Ok(std::path::PathBuf::from(result?)) +} + +#[cfg(windows)] +fn require_elevation(required: bool) -> Result<(), String> { + use windows::Win32::Foundation::BOOL; + use windows::Win32::Security::{ + CheckTokenMembership, CreateWellKnownSid, WinBuiltinAdministratorsSid, PSID, + }; + let mut storage = [0u32; 17]; + let sid = PSID(storage.as_mut_ptr().cast()); + let mut size = std::mem::size_of_val(&storage) as u32; + unsafe { CreateWellKnownSid(WinBuiltinAdministratorsSid, PSID::default(), sid, &mut size) } + .map_err(api_error)?; + let mut elevated = BOOL::default(); + unsafe { CheckTokenMembership(None, sid, &mut elevated) }.map_err(api_error)?; + if elevated.as_bool() != required { + return Err(if required { + "This explicit machine action requires administrator rights. Right-click the matching Machine-SmartKey.cmd in the extracted archive and choose Run as administrator." + } else { + "Run this user action normally, without Run as administrator, in the account that will use SmartKey." + }.into()); + } + Ok(()) +} + +#[cfg(windows)] +fn missing_machine_error() -> String { + "SmartKey machine installation is missing. Ask an administrator to right-click Install-Machine-SmartKey.cmd and choose Run as administrator, then run Install-SmartKey.cmd normally.".into() +} + +#[cfg(windows)] +fn verify_machine_install(install: &std::path::Path) -> Result<(), String> { + if !install.is_dir() { + return Err(missing_machine_error()); + } + validate_protected_path(install.parent().ok_or("Cannot locate Program Files")?)?; + validate_machine_objects(install)?; + user_setup::validate_bundle(install) + .map_err(|e| format!("SmartKey machine installation is incomplete: {e}"))?; + verify_com_path(&install.join("smartkey_win.dll")).map_err(api_error) +} + +#[cfg(windows)] +fn validate_machine_objects(install: &std::path::Path) -> Result<(), String> { + validate_protected_path(install)?; + let allowed: Vec<_> = user_setup::BINARIES + .iter() + .chain(user_setup::DATA) + .chain(user_setup::SUPPORT) + .copied() + .collect(); + for entry in std::fs::read_dir(install).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + if !allowed + .iter() + .any(|name| entry.file_name() == std::ffi::OsStr::new(name)) + { + return Err("Unexpected object in machine destination; it was preserved".into()); + } + validate_protected_path(&entry.path())?; + if !entry.file_type().map_err(|e| e.to_string())?.is_file() { + return Err("Machine payload contains a non-file object".into()); + } + } + Ok(()) +} + +#[cfg(windows)] +fn validate_protected_path(path: &std::path::Path) -> Result<(), String> { + use std::os::windows::fs::MetadataExt; + use windows::core::*; + use windows::Win32::Foundation::{LocalFree, HLOCAL}; + use windows::Win32::Security::Authorization::*; + use windows::Win32::Security::*; + // Reject junctions/symlinks anywhere in the path before copying/loading. + for ancestor in path.ancestors().filter(|p| !p.as_os_str().is_empty()) { + let metadata = std::fs::symlink_metadata(ancestor).map_err(|e| e.to_string())?; + if metadata.file_attributes() & 0x400 != 0 { + return Err("Refusing a reparse point in the machine destination".into()); } - "--disable" => { - verify_com_path(&expected_dll).map_err(api_error)?; - registration::set_user_enabled(false).map_err(api_error)?; - set_login(false, &installed_exe).map_err(api_error)?; - if registration::profile_enabled().map_err(api_error)? { - return Err("Windows still reports SmartKey enabled".into()); + } + let text: Vec = path + .as_os_str() + .to_string_lossy() + .encode_utf16() + .chain(Some(0)) + .collect(); + let mut owner = PSID::default(); + let mut dacl = std::ptr::null_mut(); + let mut descriptor = PSECURITY_DESCRIPTOR::default(); + let status = unsafe { + GetNamedSecurityInfoW( + PCWSTR(text.as_ptr()), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + Some(&mut owner), + None, + Some(&mut dacl), + None, + &mut descriptor, + ) + }; + if status.0 != 0 { + return Err(api_error(Error::from(HRESULT::from_win32(status.0)))); + } + let checked = (|| { + let trusted_sid = |sid: PSID| -> std::result::Result { + let mut string = PWSTR::null(); + unsafe { ConvertSidToStringSidW(sid, &mut string) }.map_err(api_error)?; + let sid_text = unsafe { string.to_string() }.map_err(|e| e.to_string()); + unsafe { + LocalFree(HLOCAL(string.0.cast())); } - Ok("SmartKey disabled and its login entry removed. Use Win+Space to select your usual keyboard. Enable-SmartKey restores it; personal data is unchanged.".into()) + Ok(matches!( + sid_text?.as_str(), + "S-1-5-18" + | "S-1-5-32-544" + | "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464" + )) + }; + if !trusted_sid(owner)? { + return Err( + "Machine object is not owned by SYSTEM, Administrators or TrustedInstaller".into(), + ); } - "--uninstall" => { - // Remove only this helper's exact Run value, even if TSF cleanup fails. - let login = set_login(false, &installed_exe).map_err(api_error); - let removal = registration::unregister().map_err(api_error); - login?; - removal?; - let menu = roaming.join("Microsoft/Windows/Start Menu/Programs/SmartKey"); - // Keep the currently running uninstall CMD until its final block. - for name in [ - "Status-SmartKey.cmd", - "Enable-SmartKey.cmd", - "Disable-SmartKey.cmd", - ] { - let path = menu.join(name); - if path.exists() { - std::fs::remove_file(path).map_err(|e| e.to_string())?; + if dacl.is_null() { + return Err("Refusing an unprotected machine destination (NULL DACL)".into()); + } + for index in 0..u32::from(unsafe { (*dacl).AceCount }) { + let mut raw = std::ptr::null_mut(); + unsafe { GetAce(dacl, index, &mut raw) }.map_err(api_error)?; + let header = unsafe { &*(raw as *const ACE_HEADER) }; + if header.AceFlags & 8 != 0 || header.AceType == 1 { + continue; + } // inherit-only / deny + if header.AceType != 0 { + return Err("Machine destination has an unsupported access-grant ACE".into()); + } + let ace = unsafe { &*(raw as *const ACCESS_ALLOWED_ACE) }; + // Write/delete/permission-change rights; read/synchronize are allowed. + if ace.Mask & 0x500D0156 != 0 { + let sid = PSID(std::ptr::addr_of!(ace.SidStart).cast_mut().cast()); + if !trusted_sid(sid)? { + return Err( + "Machine destination grants write/delete access to an untrusted principal" + .into(), + ); } } - Ok("SmartKey registration and its login entry were removed. Your ordinary keyboards and personal data remain.\n\nThe Uninstall command removes staged binaries after this window closes. If an app still holds the DLL, close that app and repeat file cleanup. Data/configuration under AppData\\smartkey are preserved.".into()) } - _ => Err("Use --install, --status, --enable, --disable or --uninstall.".into()), + Ok(()) + })(); + unsafe { + LocalFree(HLOCAL(descriptor.0)); + } + checked +} + +#[cfg(windows)] +fn refuse_user_com_override() -> Result<(), String> { + if registry_class_exists(windows::Win32::System::Registry::HKEY_CURRENT_USER) + .map_err(api_error)? + { + return Err("An existing per-user SmartKey COM registration could override the protected machine DLL. It was preserved. Ask an administrator to review this exact old user registration before retrying. Do not run a legacy SmartKey uninstaller after machine installation: it may remove the shared TSF catalog.".into()); } + Ok(()) +} + +#[cfg(windows)] +fn registry_class_exists( + root: windows::Win32::System::Registry::HKEY, +) -> windows::core::Result { + use windows::core::*; + use windows::Win32::Foundation::ERROR_FILE_NOT_FOUND; + use windows::Win32::System::Registry::*; + let key = format!( + "SOFTWARE\\Classes\\CLSID\\{{{}}}", + smartkey_win::config::CLSID_SMARTKEY_STR + ); + let key: Vec = key.encode_utf16().chain(Some(0)).collect(); + let mut opened = HKEY::default(); + let status = unsafe { RegOpenKeyExW(root, PCWSTR(key.as_ptr()), 0, KEY_READ, &mut opened) }; + if status == ERROR_FILE_NOT_FOUND { + return Ok(false); + } + if status.0 != 0 { + return Err(Error::from(HRESULT::from_win32(status.0))); + } + let closed = unsafe { RegCloseKey(opened) }; + if closed.0 != 0 { + return Err(Error::from(HRESULT::from_win32(closed.0))); + } + Ok(true) } #[cfg(windows)] @@ -201,7 +433,11 @@ fn show(message: &str, failed: bool) { } #[cfg(windows)] -fn read_value(key: &str, name: Option<&str>) -> windows::core::Result> { +fn read_value( + root: windows::Win32::System::Registry::HKEY, + key: &str, + name: Option<&str>, +) -> windows::core::Result> { use windows::core::*; use windows::Win32::Foundation::ERROR_FILE_NOT_FOUND; use windows::Win32::System::Registry::*; @@ -212,7 +448,7 @@ fn read_value(key: &str, name: Option<&str>) -> windows::core::Result windows::core::Result<()> { "SOFTWARE\\Classes\\CLSID\\{{{}}}\\InProcServer32", smartkey_win::config::CLSID_SMARTKEY_STR ); - let value = read_value(&key, None) - .map_err(|e| { - Error::new( - e.code(), - format!("Verification HKCU COM path / RegGetValueW: {e}"), - ) - })? - .ok_or_else(|| { - Error::new( - E_FAIL, - "Verification HKCU COM path: SmartKey registration is missing", - ) - })?; + let value = read_value( + windows::Win32::System::Registry::HKEY_LOCAL_MACHINE, + &key, + None, + ) + .map_err(|e| { + Error::new( + e.code(), + format!("Verification HKLM protected machine COM path / RegGetValueW: {e}"), + ) + })? + .ok_or_else(|| { + Error::new( + E_FAIL, + "Verification HKLM protected machine COM path: SmartKey registration is missing", + ) + })?; if std::path::Path::new(&value) != expected || !expected.is_file() { return Err(Error::new( E_FAIL, - "Verification HKCU COM path: registration does not point to the installed DLL", + "Verification HKLM protected machine COM path: registration does not point to the installed DLL", )); } Ok(()) @@ -269,7 +509,7 @@ fn set_login(enabled: bool, exe: &std::path::Path) -> windows::core::Result<()> const KEY: &str = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"; const NAME: &str = "SmartKey"; let expected = format!("\"{}\" --login", exe.display()); - let existing = read_value(KEY, Some(NAME))?; + let existing = read_value(HKEY_CURRENT_USER, KEY, Some(NAME))?; if existing.as_ref().is_some_and(|value| value != &expected) { return Err(Error::new( E_FAIL, diff --git a/crates/smartkey-win/src/registration.rs b/crates/smartkey-win/src/registration.rs index c3be261..8a3c3b4 100644 --- a/crates/smartkey-win/src/registration.rs +++ b/crates/smartkey-win/src/registration.rs @@ -36,12 +36,36 @@ const DISPLAY_NAME: &str = "SmartKey"; /// Any denied TSF operation is a real installation failure, not a skipped step. pub fn register(dll_path: &str) -> Result { register_com_server_hkcu(dll_path).map_err(|e| step_error("HKCU COM registration", e))?; - register_tip_profile(dll_path, 0).map_err(|e| step_error("Persistent TSF profile", e))?; + register_tip_profile(dll_path, 0, true).map_err(|e| step_error("Persistent TSF profile", e))?; register_categories().map_err(|e| step_error("TSF categories", e))?; set_user_enabled(true)?; Ok(false) } +/// Explicit elevated machine phase. The caller must stage and validate a +/// protected machine DLL first. Never changes any user's availability or data. +pub fn register_machine(dll_path: &str) -> Result<()> { + register_com_server(HKEY_LOCAL_MACHINE, dll_path) + .map_err(|e| step_error("Machine COM registration", e))?; + register_tip_profile(dll_path, 0, false) + .map_err(|e| step_error("Persistent machine TSF profile", e))?; + register_categories().map_err(|e| step_error("Machine TSF categories", e)) +} + +/// Remove only the executing user's availability. Shared catalog/COM remain. +pub fn unregister_user() -> Result<()> { + install_layout_or_tip(1).map_err(|e| step_error("Current-user profile removal", e)) +} + +/// Explicit elevated machine cleanup; never changes a user's Run/data/menu. +pub fn unregister_machine() -> Result<()> { + collect_removal_errors([ + ("Machine categories", unregister_categories()), + ("Machine TSF profile", unregister_tip_profile()), + ("Machine COM", unregister_com_server(HKEY_LOCAL_MACHINE)), + ]) +} + /// Attempt each own-identity cleanup and return failures rather than claiming /// success after partial removal. Never deletes HKLM or another keyboard. pub fn unregister() -> Result<()> { @@ -51,6 +75,10 @@ pub fn unregister() -> Result<()> { ("TSF profile", unregister_tip_profile()), ("HKCU COM", unregister_com_server_hkcu()), ]; + collect_removal_errors(operations) +} + +fn collect_removal_errors(operations: [(&str, Result<()>); N]) -> Result<()> { let errors: Vec<_> = operations .into_iter() .filter_map(|(name, result)| result.err().map(|e| (e.code(), format!("{name}: {e}")))) @@ -133,6 +161,15 @@ fn install_layout_or_tip(flags: u32) -> Result<()> { /// Fresh-process verification must use this query after the installer exits. /// It observes the actual TSF profile rather than a local registration flag. pub fn profile_enabled() -> Result { + Ok(query_profile()?.dwFlags & TF_IPP_FLAG_ENABLED != 0) +} + +/// Machine installation checks presence, without enabling the administrator. +pub fn profile_present() -> Result<()> { + query_profile().map(|_| ()) +} + +fn query_profile() -> Result { let mgr: ITfInputProcessorProfileMgr = unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER) } .map_err(|e| { @@ -152,12 +189,16 @@ pub fn profile_enabled() -> Result { &mut profile, ).map_err(|e| step_error("Verification ITfInputProcessorProfileMgr::GetProfile(type=INPUTPROCESSOR, langid=0x0402, hkl=NULL)", e))?; } - Ok(profile.dwFlags & TF_IPP_FLAG_ENABLED != 0) + Ok(profile) } // -- COM server registration (registry) -------------------------------- fn register_com_server_hkcu(dll_path: &str) -> Result<()> { + register_com_server(HKEY_CURRENT_USER, dll_path) +} + +fn register_com_server(root: HKEY, dll_path: &str) -> Result<()> { let subkey = format!( "SOFTWARE\\Classes\\CLSID\\{{{}}}\\InProcServer32", CLSID_SMARTKEY_STR @@ -165,7 +206,7 @@ fn register_com_server_hkcu(dll_path: &str) -> Result<()> { let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); let mut hkey = HKEY::default(); - check_win32(unsafe { RegCreateKeyW(HKEY_CURRENT_USER, PCWSTR(subkey_w.as_ptr()), &mut hkey) })?; + check_win32(unsafe { RegCreateKeyW(root, PCWSTR(subkey_w.as_ptr()), &mut hkey) })?; let result = set_reg_sz(hkey, None, dll_path) .and_then(|_| set_reg_sz(hkey, Some("ThreadingModel"), "Apartment")); @@ -174,9 +215,13 @@ fn register_com_server_hkcu(dll_path: &str) -> Result<()> { } fn unregister_com_server_hkcu() -> Result<()> { + unregister_com_server(HKEY_CURRENT_USER) +} + +fn unregister_com_server(root: HKEY) -> Result<()> { let subkey = format!("SOFTWARE\\Classes\\CLSID\\{{{}}}", CLSID_SMARTKEY_STR); let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); - let result = unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, PCWSTR(subkey_w.as_ptr())) }; + let result = unsafe { RegDeleteTreeW(root, PCWSTR(subkey_w.as_ptr())) }; if result == windows::Win32::Foundation::ERROR_FILE_NOT_FOUND { Ok(()) } else { @@ -186,7 +231,7 @@ fn unregister_com_server_hkcu() -> Result<()> { // -- TSF TIP profile registration -------------------------------------- -fn register_tip_profile(dll_path: &str, flags: u32) -> Result<()> { +fn register_tip_profile(dll_path: &str, flags: u32, enabled_by_default: bool) -> Result<()> { let profile_mgr: ITfInputProcessorProfileMgr = unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER) } .map_err(|e| step_error("CoCreateInstance(ITfInputProcessorProfileMgr)", e))?; @@ -205,7 +250,7 @@ fn register_tip_profile(dll_path: &str, flags: u32) -> Result<()> { 0, // icon index HKL::default(), // no substitute layout 0, // no preferred layout - true, // enable by default + enabled_by_default, flags, ) .map_err(|e| step_error("ITfInputProcessorProfileMgr::RegisterProfile", e))?; diff --git a/crates/smartkey-win/src/tsf.rs b/crates/smartkey-win/src/tsf.rs index 163fcaa..7336000 100644 --- a/crates/smartkey-win/src/tsf.rs +++ b/crates/smartkey-win/src/tsf.rs @@ -72,6 +72,44 @@ impl SmartKeyTextService { } } + /// Respect the application's TSF eligibility flags before inspecting keys. + /// Unset compartments are normal; unavailable or malformed state is not. + fn context_accepts_input(context: Option<&ITfContext>) -> bool { + let Some(context) = context else { + return false; + }; + let allowed = (|| -> Result { + let status = unsafe { context.GetStatus()? }; + if status.dwDynamicFlags & TF_SD_READONLY != 0 { + return Ok(false); + } + let compartments: ITfCompartmentMgr = context.cast()?; + for guid in [ + GUID_COMPARTMENT_KEYBOARD_DISABLED, + GUID_COMPARTMENT_EMPTYCONTEXT, + ] { + let value = unsafe { compartments.GetCompartment(&guid)?.GetValue()? }; + if !compartment_allows_input(&value) { + return Ok(false); + } + } + Ok(true) + })(); + allowed.unwrap_or(false) + } + + fn admit_context(&self, context: Option<&ITfContext>) -> bool { + if Self::context_accepts_input(context) { + return true; + } + // reset discards pending text; focus_lost would commit and learn it. + // Do not dispatch an edit through a missing/disabled/new context. + let _ = self.core.borrow_mut().reset(); + let stale_composition = self.composition.borrow_mut().take(); + drop(stale_composition); + false + } + /// Translate a Windows virtual key code to our platform-neutral Key. /// /// Uses `ToUnicodeEx` for layout-aware character resolution — supports @@ -194,6 +232,14 @@ impl SmartKeyTextService { } } +fn compartment_allows_input(value: &VARIANT) -> bool { + // The TSF compartments are VT_I4 flags. Do not coerce strings or booleans. + const VT_I4: u16 = 3; + value.is_empty() + || (unsafe { value.as_raw().Anonymous.Anonymous.vt } == VT_I4 + && i32::try_from(value).is_ok_and(|flag| flag == 0)) +} + // -- ITfTextInputProcessor implementation (base trait: Activate + Deactivate) -- impl ITfTextInputProcessor_Impl for SmartKeyTextService_Impl { @@ -295,10 +341,13 @@ impl ITfKeyEventSink_Impl for SmartKeyTextService_Impl { fn OnTestKeyDown( &self, - _pic: Option<&ITfContext>, + pic: Option<&ITfContext>, wparam: WPARAM, lparam: LPARAM, ) -> Result { + if !self.admit_context(pic) { + return Ok(BOOL::from(false)); + } let scan_code = ((lparam.0 >> 16) & 0xFF) as u32; let key = SmartKeyTextService::vk_to_key(wparam.0 as u32, scan_code); let core = self.core.borrow(); @@ -325,6 +374,9 @@ impl ITfKeyEventSink_Impl for SmartKeyTextService_Impl { } fn OnKeyDown(&self, pic: Option<&ITfContext>, wparam: WPARAM, lparam: LPARAM) -> Result { + if !self.admit_context(pic) { + return Ok(BOOL::from(false)); + } let vk = wparam.0 as u32; let scan_code = ((lparam.0 >> 16) & 0xFF) as u32; let key = SmartKeyTextService::vk_to_key(vk, scan_code); @@ -392,3 +444,33 @@ impl ITfCompositionSink_Impl for SmartKeyTextService_Impl { Ok(()) } } + +#[cfg(test)] +mod context_tests { + use super::*; + + #[test] + fn unset_and_zero_compartments_allow_input_but_other_values_do_not() { + assert!(compartment_allows_input(&VARIANT::new())); + assert!(compartment_allows_input(&VARIANT::from(0i32))); + assert!(!compartment_allows_input(&VARIANT::from(1i32))); + assert!(!compartment_allows_input(&VARIANT::from(-1i32))); + assert!(!compartment_allows_input(&VARIANT::from(false))); + assert!(!compartment_allows_input(&VARIANT::from("0"))); + } + + #[test] + fn missing_context_neither_claims_nor_feeds_a_key_and_discards_pending_text() { + let service = windows_core::ComObject::new(SmartKeyTextService::new()); + let sink: ITfKeyEventSink = service.to_interface(); + let _ = service.core.borrow_mut().handle_key(KeyEvent { + key: Key::Char('q'), + modifiers: Modifiers::empty(), + }); + assert_eq!(service.core.borrow().current_word(), "q"); + assert!(!unsafe { sink.OnTestKeyDown(None, WPARAM(0x41), LPARAM(0)).unwrap() }.as_bool()); + assert!(service.core.borrow().current_word().is_empty()); + assert!(!unsafe { sink.OnKeyDown(None, WPARAM(0x41), LPARAM(0)).unwrap() }.as_bool()); + assert!(service.core.borrow().current_word().is_empty()); + } +} diff --git a/crates/smartkey-win/windows-runtime-manifest.json b/crates/smartkey-win/windows-runtime-manifest.json index 1e99cd1..9f2dc28 100644 --- a/crates/smartkey-win/windows-runtime-manifest.json +++ b/crates/smartkey-win/windows-runtime-manifest.json @@ -2,13 +2,13 @@ "schema_version": 1, "package_name": "smartkey-windows-standalone", "status": "candidate_native_acceptance_pending", - "native_artifact_layout": "Extract complete ZIP; Install-SmartKey.cmd stages the per-user application in %LOCALAPPDATA%\\SmartKey.", + "native_artifact_layout": "Extract complete19-file ZIP. Explicit administrator Install-Machine-SmartKey.cmd installs protected ProgramFiles knownfolder\\SmartKey once; normal Install-SmartKey.cmd enables the executing user.", "runtime_data_destination_directory": "%APPDATA%\\smartkey", "native_files": [ { "name": "smartkey-register.exe", "repository_source": "target/release/smartkey-register.exe", - "purpose": "Visible current-user setup, status, enable, disable and removal; fresh-process profile verification." + "purpose": "Visible explicit machine install/remove; normal-user enable/data/login/maintenance; separate persistent profile verification." }, { "name": "smartkey_win.dll", @@ -96,6 +96,16 @@ "name": "README-WINDOWS.md", "repository_source": "crates/smartkey-win/packaging/README-WINDOWS.md", "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "Install-Machine-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd", + "purpose": "Explicit one-time administrator machine catalog/protectedbundle installation; no user enablement" + }, + { + "name": "Uninstall-Machine-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd", + "purpose": "Explicit administrator exact shared machine removal, run from original archive" } ], "excluded_files": [ @@ -111,11 +121,12 @@ "runtime_contract": { "network_required": false, "autostart_created": "One owned HKCU Run value after successful setup; removed by Disable/Uninstall", - "automatic_registration": "Only on explicit installer launch; no elevation fallback", + "automatic_registration": "Only explicit --install-machine with actual elevated token. No automatic elevation/fallback.", "automatic_appdata_mutation": "Setup copies only missing public starter data; preserves personal files", - "missing_public_corpus_is_package_failure": true + "missing_public_corpus_is_package_failure": true, + "machine_user_split": "Machine profile enabledByDefaultfalse. Normal originaluser --install applies only missingdata/userenable/login/menu after machine prerequisite." }, - "uninstall_boundary": "Uninstall-SmartKey removes exact SmartKey registrations, its Run value and installed EXE/DLL. Existing keyboards/default and personal data remain. Locked files are reported.", + "uninstall_boundary": "Normal user removal only useravailability/Run/menu; preserves globalcatalog/sharedfiles/personaldata. Explicit elevated machine removal removes exact globalcatalog/COM+allowlistedprotectedfiles from originalarchive; never edits otherusers profiles. Errors/lockedfiles are reported.", "dependency_evidence": { "build_assumption": "x64 MSVC static CRT; CI inspects both PE import lists", "runtime_dll_completeness": "Requires successful CI dependency check; Windows 10/11 system DLLs supplied by OS" From 72b875958d965fd78b01667d6bc8db97e6d03cf6 Mon Sep 17 00:00:00 2001 From: RMANOV <96174405+RMANOV@users.noreply.github.com> Date: Fri, 9 Oct 2026 02:16:19 +0300 Subject: [PATCH 6/9] Query registered TSF metadata independently of user enablement --- .github/workflows/ci.yml | 21 ++++++++ crates/smartkey-win/src/registration.rs | 70 +++++++++++++++---------- 2 files changed, 64 insertions(+), 27 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3fe8e55..63b20b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -226,6 +226,25 @@ jobs: machine_install_exit=$null; machine_verify_exit=$null; machine_cleanup_exit=$null frozen_bundle_matches=$false; machine_state_removed=$false typing_exercised=$false; logon_exercised=$false; cleanup_errors=@() + machine_tip_snapshots=[ordered]@{} + } + function Save-OwnedTipSnapshot([string]$phase) { + try { + $present = Test-Path -LiteralPath $machineTip + $snapshot = [ordered]@{ present=$present; query_exit=$null } + if ($present) { + # Read only SmartKey's exact owned subtree; never modify CTF state. + $PSNativeCommandUseErrorActionPreference = $false + $lines = & reg.exe query "HKLM\Software\Microsoft\CTF\TIP\$guid" /s 2>&1 + $snapshot.query_exit = $LASTEXITCODE + $lines | Set-Content -LiteralPath (Join-Path $root "machine-tip-$phase.txt") -Encoding utf8 + if ($snapshot.query_exit -ne 0) { throw "Owned TIP query failed: $($snapshot.query_exit)" } + } + $result.machine_tip_snapshots[$phase] = $snapshot + } catch { + # A diagnostic failure must not prevent the cleanup attempt. + $result.cleanup_errors += "TIP snapshot ${phase}: $($_.Exception.Message)" + } } function Invoke-MachineHelper([string]$helper, [string]$action, [string]$exitField) { $process = [Diagnostics.Process]::new() @@ -320,6 +339,7 @@ jobs: $result['error'] = $failure } finally { if ($machineAttempted) { + Save-OwnedTipSnapshot 'before-cleanup' try { # The original archive helper can remove the installed EXE; # the product deliberately refuses to delete its running self. @@ -329,6 +349,7 @@ jobs: } $result.machine_state_removed = $true } catch { $result.cleanup_errors += "Machine cleanup: $($_.Exception.Message)" } + finally { Save-OwnedTipSnapshot 'after-cleanup' } } if ($created) { try { Remove-LocalUser -Name $name } diff --git a/crates/smartkey-win/src/registration.rs b/crates/smartkey-win/src/registration.rs index 8a3c3b4..0d99d85 100644 --- a/crates/smartkey-win/src/registration.rs +++ b/crates/smartkey-win/src/registration.rs @@ -61,7 +61,7 @@ pub fn unregister_user() -> Result<()> { pub fn unregister_machine() -> Result<()> { collect_removal_errors([ ("Machine categories", unregister_categories()), - ("Machine TSF profile", unregister_tip_profile()), + ("Machine text service", unregister_text_service()), ("Machine COM", unregister_com_server(HKEY_LOCAL_MACHINE)), ]) } @@ -158,38 +158,54 @@ fn install_layout_or_tip(flags: u32) -> Result<()> { result } -/// Fresh-process verification must use this query after the installer exits. -/// It observes the actual TSF profile rather than a local registration flag. +/// Verify exact registration metadata before querying current-user enablement. +/// API failures remain failures; a missing profile is never treated as disabled. pub fn profile_enabled() -> Result { - Ok(query_profile()?.dwFlags & TF_IPP_FLAG_ENABLED != 0) + profile_present()?; + let profiles = + input_processor_profiles("Enabled-state CoCreateInstance(ITfInputProcessorProfiles)")?; + unsafe { profiles.IsEnabledLanguageProfile(&CLSID_SMARTKEY, LANGID_BG, &GUID_PROFILE) } + .map(|enabled| enabled.as_bool()) + .map_err(|e| step_error("ITfInputProcessorProfiles::IsEnabledLanguageProfile", e)) } -/// Machine installation checks presence, without enabling the administrator. +/// Machine verification reads registered metadata without requiring enablement. +/// The caller's fresh process must see this exact CLSID/language/profile tuple. pub fn profile_present() -> Result<()> { - query_profile().map(|_| ()) + let profiles = input_processor_profiles( + "Registration metadata CoCreateInstance(ITfInputProcessorProfiles)", + )?; + let description = unsafe { + profiles.GetLanguageProfileDescription(&CLSID_SMARTKEY, LANGID_BG, &GUID_PROFILE) + } + .map_err(|e| { + step_error( + "ITfInputProcessorProfiles::GetLanguageProfileDescription", + e, + ) + })?; + if description != DISPLAY_NAME { + return Err(Error::new( + windows::Win32::Foundation::E_FAIL, + "Registered SmartKey profile description does not match the expected metadata", + )); + } + Ok(()) } -fn query_profile() -> Result { - let mgr: ITfInputProcessorProfileMgr = - unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER) } - .map_err(|e| { - step_error( - "Verification CoCreateInstance(ITfInputProcessorProfileMgr)", - e, - ) - })?; - let mut profile = TF_INPUTPROCESSORPROFILE::default(); - unsafe { - mgr.GetProfile( - TF_PROFILETYPE_INPUTPROCESSOR, - LANGID_BG, - &CLSID_SMARTKEY, - &GUID_PROFILE, - HKL::default(), - &mut profile, - ).map_err(|e| step_error("Verification ITfInputProcessorProfileMgr::GetProfile(type=INPUTPROCESSOR, langid=0x0402, hkl=NULL)", e))?; - } - Ok(profile) +fn input_processor_profiles(operation: &str) -> Result { + unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER) } + .map_err(|e| step_error(operation, e)) +} + +/// Explicit machine removal owns the entire SmartKey text service. This is not +/// called by ordinary user removal, and does not edit CTF registry keys directly. +fn unregister_text_service() -> Result<()> { + let profiles = input_processor_profiles( + "Machine service removal CoCreateInstance(ITfInputProcessorProfiles)", + )?; + unsafe { profiles.Unregister(&CLSID_SMARTKEY) } + .map_err(|e| step_error("ITfInputProcessorProfiles::Unregister", e)) } // -- COM server registration (registry) -------------------------------- From 053f70c94793da418ed822ede8d23d3a1ff2a2c8 Mon Sep 17 00:00:00 2001 From: RMANOV <96174405+RMANOV@users.noreply.github.com> Date: Fri, 9 Oct 2026 02:23:42 +0300 Subject: [PATCH 7/9] Retain exact ephemeral keyboard state at preservation checks --- crates/smartkey-win/packaging/smoke-user.ps1 | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/smartkey-win/packaging/smoke-user.ps1 b/crates/smartkey-win/packaging/smoke-user.ps1 index d0e3314..7c9fba2 100644 --- a/crates/smartkey-win/packaging/smoke-user.ps1 +++ b/crates/smartkey-win/packaging/smoke-user.ps1 @@ -56,7 +56,7 @@ function Get-Login { return (Get-Item -LiteralPath $run).GetValue('SmartKey', $null) } function Keyboard-Snapshot { - # Only the ephemeral account is read. The receipt reports equality, not values. + # Only the ephemeral account's bounded keyboard configuration is read. $snapshot = [ordered]@{} foreach ($name in @('Keyboard Layout\Preload', 'Keyboard Layout\Substitutes')) { $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($name) @@ -143,6 +143,12 @@ $receipt = [ordered]@{ machine_prerequisite_refused=$false; machine_install_preserved=$false } $before = Keyboard-Snapshot +$before | Set-Content -LiteralPath (Join-Path $OutDir 'keyboard-before.json') -Encoding UTF8 +function Assert-KeyboardPreserved([string]$message) { + $after = Keyboard-Snapshot + $after | Set-Content -LiteralPath (Join-Path $OutDir ('keyboard-after-{0:D2}.json' -f $steps.Count)) -Encoding UTF8 + Assert-True ($after -eq $before) $message +} try { # Never use a daily account or delete a prior installation for this smoke. Assert-True (-not (Test-Path -LiteralPath $localInstall)) 'The ephemeral user already has a SmartKey install folder.' @@ -162,7 +168,7 @@ try { Assert-True (-not (Test-Path -LiteralPath $path)) "Prerequisite refusal created unexpected state: $path" } Assert-True ($null -eq (Get-Login)) 'Prerequisite refusal created a login entry.' - Assert-True ((Keyboard-Snapshot) -eq $before) 'Prerequisite refusal changed keyboard/default settings.' + Assert-KeyboardPreserved 'Prerequisite refusal changed keyboard/default settings.' $receipt['machine_prerequisite_refused']=$true $receipt['keyboard_defaults_preserved']=$true $receipt['status']='PASS_NATIVE_STANDARD_USER_PREREQUISITE' @@ -196,11 +202,11 @@ try { Assert-True (Test-Path -LiteralPath (Join-Path $menu $name) -PathType Leaf) "Missing Start menu command: $name" } Assert-True ((Get-Login) -eq ('"' + $helper + '" --login')) 'Login entry does not identify the stable installed helper.' - Assert-True ((Keyboard-Snapshot) -eq $before) 'Installation changed existing keyboard/default settings.' + Assert-KeyboardPreserved 'Installation changed existing keyboard/default settings.' Invoke-Helper $helper '--status' | Out-Null Invoke-Helper $helper '--disable' | Out-Null Assert-True ($null -eq (Get-Login)) 'Disable left the owned login entry.' - Assert-True ((Keyboard-Snapshot) -eq $before) 'Disable changed existing keyboard/default settings.' + Assert-KeyboardPreserved 'Disable changed existing keyboard/default settings.' Invoke-Helper $helper '--enable' | Out-Null Assert-True ((Get-Login) -eq ('"' + $helper + '" --login')) 'Enable did not restore the exact owned login entry.' Invoke-Helper $helper '--uninstall' | Out-Null @@ -214,7 +220,7 @@ try { foreach ($name in @('Status-SmartKey.cmd','Enable-SmartKey.cmd','Disable-SmartKey.cmd')) { Assert-True (-not (Test-Path -LiteralPath (Join-Path $menu $name))) "Uninstall left a user maintenance command: $name" } - Assert-True ((Keyboard-Snapshot) -eq $before) 'Maintenance changed existing keyboard/default settings.' + Assert-KeyboardPreserved 'Maintenance changed existing keyboard/default settings.' Assert-True ((Get-FileHash -LiteralPath $personal -Algorithm SHA256).Hash -eq $personalHash) 'Maintenance changed the synthetic personal file.' Assert-True (-not (Test-Path -LiteralPath $localInstall)) 'User setup created an unprotected local binary folder.' Assert-True ((Machine-Snapshot) -eq $machineBefore) 'User maintenance changed the protected bundle or machine registration.' From aebaff4a36de54be3b386ad18c8243b4a88c4c7c Mon Sep 17 00:00:00 2001 From: RMANOV <96174405+RMANOV@users.noreply.github.com> Date: Fri, 9 Oct 2026 02:23:57 +0300 Subject: [PATCH 8/9] Distinguish TSF status initialization from user enablement --- crates/smartkey-win/packaging/smoke-user.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/smartkey-win/packaging/smoke-user.ps1 b/crates/smartkey-win/packaging/smoke-user.ps1 index 7c9fba2..4d91ffa 100644 --- a/crates/smartkey-win/packaging/smoke-user.ps1 +++ b/crates/smartkey-win/packaging/smoke-user.ps1 @@ -186,6 +186,7 @@ try { $helper = Join-Path $install 'smartkey-register.exe' $initialStatus = Invoke-Helper $helper '--status' Assert-True ($initialStatus.stdout -match '(?m)^TSF profile: disabled\.') 'Machine registration enabled SmartKey before this user opted in.' + Keyboard-Snapshot | Set-Content -LiteralPath (Join-Path $OutDir 'keyboard-after-initial-status.json') -Encoding UTF8 New-Item -ItemType Directory -Path $data | Out-Null $personal = Join-Path $data 'personal.json' [IO.File]::WriteAllText($personal, '{"synthetic_smoke_sentinel":true}') From e27be337c5a3992a4f8f0c2a43a0c8b748f38e32 Mon Sep 17 00:00:00 2001 From: RMANOV <96174405+RMANOV@users.noreply.github.com> Date: Fri, 9 Oct 2026 02:33:15 +0300 Subject: [PATCH 9/9] Verify preserved keyboard defaults while allowing SmartKey language opt-in --- crates/smartkey-win/packaging/smoke-user.ps1 | 37 +++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/smartkey-win/packaging/smoke-user.ps1 b/crates/smartkey-win/packaging/smoke-user.ps1 index 4d91ffa..97db786 100644 --- a/crates/smartkey-win/packaging/smoke-user.ps1 +++ b/crates/smartkey-win/packaging/smoke-user.ps1 @@ -140,6 +140,7 @@ $receipt = [ordered]@{ status='NOT_RUN'; standard_nonadmin=$true; current_user_profile_confirmed=$true; no_dialog=$true phase=$Phase; typing_exercised=$false; logon_exercised=$false steps=$steps; keyboard_defaults_preserved=$false; personal_sentinel_preserved=$false + keyboard_allowed_language_additions_observed=$false machine_prerequisite_refused=$false; machine_install_preserved=$false } $before = Keyboard-Snapshot @@ -147,7 +148,40 @@ $before | Set-Content -LiteralPath (Join-Path $OutDir 'keyboard-before.json') -E function Assert-KeyboardPreserved([string]$message) { $after = Keyboard-Snapshot $after | Set-Content -LiteralPath (Join-Path $OutDir ('keyboard-after-{0:D2}.json' -f $steps.Count)) -Encoding UTF8 - Assert-True ($after -eq $before) $message + if ($Phase -eq 'Prerequisite') { Assert-True ($after -ceq $before) $message; return } + $baseline = $before | ConvertFrom-Json + $current = $after | ConvertFrom-Json + foreach ($name in @('InputMethodOverride', 'DefaultInputMethodOverride', 'WindowsDefaultInputTip')) { + Assert-True (($current.$name | ConvertTo-Json -Compress) -ceq ($baseline.$name | ConvertTo-Json -Compress)) $message + } + foreach ($name in @('Keyboard Layout\Preload', 'Keyboard Layout\Substitutes')) { + $old = @($baseline.$name.PSObject.Properties) + $new = @($current.$name.PSObject.Properties) + $oldNames = @($old | ForEach-Object Name) + $newNames = @($new | ForEach-Object Name) + foreach ($entry in $old) { + Assert-True ($newNames -ccontains $entry.Name) $message + $value = $current.$name.PSObject.Properties[$entry.Name].Value + Assert-True (($value | ConvertTo-Json -Compress) -ceq ($entry.Value | ConvertTo-Json -Compress)) $message + } + $added = @($new | Where-Object { $oldNames -cnotcontains $_.Name }) + Assert-True ($added.Count -le 1) $message + if ($added.Count -eq 0) { continue } + # Permit only the observed LANG 0402 addition on this known CI baseline. + $first = $baseline.'Keyboard Layout\Preload'.PSObject.Properties['1'] + Assert-True ($null -ne $first -and $first.Value -is [string] -and $first.Value -ceq '00000409') $message + $entry = $added[0] + Assert-True ($entry.Value -is [string]) $message + if ($name -eq 'Keyboard Layout\Preload') { + Assert-True (@($oldNames | Where-Object { $_ -cnotmatch '^[1-9][0-9]*$' }).Count -eq 0) $message + $max = ($oldNames | ForEach-Object { [int]$_ } | Measure-Object -Maximum).Maximum + Assert-True ($entry.Name -cmatch '^[1-9][0-9]*$' -and [int]$entry.Name -gt $max -and $entry.Value -ceq '00000402') $message + Assert-True (@($old | Where-Object { $_.Value -ceq '00000402' }).Count -eq 0) $message + } else { + Assert-True ($entry.Name -ceq '00000402' -and $entry.Value -ceq $first.Value) $message + } + $receipt['keyboard_allowed_language_additions_observed']=$true + } } try { # Never use a daily account or delete a prior installation for this smoke. @@ -210,6 +244,7 @@ try { Assert-KeyboardPreserved 'Disable changed existing keyboard/default settings.' Invoke-Helper $helper '--enable' | Out-Null Assert-True ((Get-Login) -eq ('"' + $helper + '" --login')) 'Enable did not restore the exact owned login entry.' + Assert-KeyboardPreserved 'Enable changed existing keyboard/default settings.' Invoke-Helper $helper '--uninstall' | Out-Null Assert-True ($null -eq (Get-Login)) 'Uninstall left the owned login entry.' Assert-True (-not (Test-Path -LiteralPath $clsid)) 'Uninstall left own HKCU COM registration.'