diff --git a/CHANGELOG.md b/CHANGELOG.md index 587d8bc..ae13e2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,11 +15,30 @@ dan proyek ini memakai [Semantic Versioning](https://semver.org/lang/id/). - **BAHASA** - berganti bahasa Indonesia/English; pilihan disimpan. - **Unshare** - berhenti membagikan printer langsung dari menu HOST. - Status printer yang sedang dibagikan ditampilkan di header menu. +- **Pemeriksaan awal (*pre-check*)** sebelum setiap operasi: menu memeriksa hak + Administrator, versi Windows, layanan Print Spooler, ketersediaan printer, + konektivitas host (port 445), dan ketersediaan file backup. Bila ada masalah + serius, operasi dibatalkan otomatis; peringatan ringan hanya meminta konfirmasi. +- **Verifikasi akhir otomatis** setelah operasi: menu memastikan hasilnya nyata + (printer benar-benar dibagikan, terpasang di klien, atau nilai registry + perbaikan sudah diterapkan) dan menampilkan hasilnya sebagai `[OK]`/`[WARN]`. +- **Prompt nama pengguna** pada menu KLIEN > batch Windows 7 (password tidak + pernah ditanyakan/dioper lewat menu). - **Test Pester** (`tests/`) untuk logika menu, kelengkapan struktur repositori, dan pemeriksa kualitas, plus runner `tests/Run-Tests.ps1`. - **`.editorconfig`** untuk menyeragamkan encoding, indentasi, dan akhir baris antar editor. - CI kini juga menjalankan test Pester (`test` job) selain lint. +### Security + +- **Password tidak pernah lewat command line**: + - `client/Win7/02-Connect-Win7.cmd` tidak lagi menerima argumen password; + bila pengguna host diisi, password diminta langsung oleh `net use ... *` + secara tersembunyi (tidak terlihat di daftar proses). + - `client/Win7/02-Connect-Win7.ps1 -SaveCredential` menyimpan kredensial ke + Windows Credential Manager lewat API `CredWrite` (advapi32), menggantikan + `cmdkey /add:... /pass:...` yang membocorkan password ke daftar proses. + ### Fixed - Test Pester kini kompatibel dengan Pester 5/6 (yang dipakai CI), bukan hanya diff --git a/Menu.ps1 b/Menu.ps1 index d3716c3..8a19e9a 100644 --- a/Menu.ps1 +++ b/Menu.ps1 @@ -165,6 +165,39 @@ $Script:Strings = @{ '@ qOpenReadme = 'Buka README di aplikasi default?' + qUser = 'Nama pengguna host (opsional, Enter = akun saat ini)' + batchPassNote = 'Password (bila perlu) diminta langsung oleh script batch dan tidak ditampilkan.' + + pfHeader = 'PEMERIKSAAN AWAL' + pfAdmin = 'Hak Administrator' + pfOs = 'Sistem operasi' + pfSpooler = 'Layanan Print Spooler' + pfPrinter = 'Printer lokal' + pfServer = 'Konektivitas host' + pfBackup = 'File backup' + pfRunning = 'berjalan' + pfStopped = 'berhenti' + pfSpoolerHint = 'Coba jalankan: Start-Service Spooler' + pfNotAdmin = 'Operasi share/perbaikan/rollback butuh Administrator.' + pfOsWin8 = 'Windows 8/8.1 belum resmi didukung.' + pfNoPrinter = 'Tidak ada printer lokal yang terdeteksi.' + pfPrinterFound = '{0} printer terdeteksi.' + pfServerOk = 'Port 445 (SMB) terbuka di {0}.' + pfServerUnreachable = 'Port 445 (SMB) tidak terjangkau di {0}.' + pfNoBackup = 'Belum ada file backup/journal di folder log.' + pfBlocked = 'Pemeriksaan awal menemukan masalah. Operasi dibatalkan.' + pfContinueAnyway = 'Tetap lanjutkan meski ada peringatan?' + + vfHeader = 'VERIFIKASI AKHIR' + vfSharedOk = 'Printer "{0}" sekarang dibagikan.' + vfSharedMissing = 'Printer "{0}" belum terlihat dibagikan.' + vfUnsharedOk = 'Printer "{0}" tidak lagi dibagikan.' + vfUnsharedMissing = 'Printer "{0}" masih terlihat dibagikan.' + vfConnectedOk = 'Printer "{0}" terpasang di PC ini.' + vfConnectedMissing = 'Printer "{0}" belum terpasang.' + vfFixOk = 'Perbaikan kompatibilitas sudah diterapkan (RpcAuthnLevelPrivacyEnabled = 0).' + vfFixMissing = 'Nilai registry perbaikan belum terlihat.' + langHeader = 'BAHASA' langCurrent = 'Bahasa saat ini: {0}' langName = 'Indonesia' @@ -290,6 +323,39 @@ $Script:Strings = @{ '@ qOpenReadme = 'Open README in the default app?' + qUser = 'Host user name (optional, Enter = current account)' + batchPassNote = 'The password (if needed) is requested by the batch script directly and is not echoed.' + + pfHeader = 'PRE-CHECK' + pfAdmin = 'Administrator rights' + pfOs = 'Operating system' + pfSpooler = 'Print Spooler service' + pfPrinter = 'Local printer' + pfServer = 'Host connectivity' + pfBackup = 'Backup file' + pfRunning = 'running' + pfStopped = 'stopped' + pfSpoolerHint = 'Try: Start-Service Spooler' + pfNotAdmin = 'Share/repair/rollback operations require Administrator.' + pfOsWin8 = 'Windows 8/8.1 is not officially supported.' + pfNoPrinter = 'No local printer detected.' + pfPrinterFound = '{0} printer(s) detected.' + pfServerOk = 'Port 445 (SMB) is open at {0}.' + pfServerUnreachable = 'Port 445 (SMB) is unreachable at {0}.' + pfNoBackup = 'No backup/journal file in the log folder yet.' + pfBlocked = 'Pre-check found problems. Operation cancelled.' + pfContinueAnyway = 'Continue anyway despite warnings?' + + vfHeader = 'FINAL VERIFICATION' + vfSharedOk = 'Printer "{0}" is now shared.' + vfSharedMissing = 'Printer "{0}" is not shown as shared yet.' + vfUnsharedOk = 'Printer "{0}" is no longer shared.' + vfUnsharedMissing = 'Printer "{0}" still appears shared.' + vfConnectedOk = 'Printer "{0}" is installed on this PC.' + vfConnectedMissing = 'Printer "{0}" is not installed yet.' + vfFixOk = 'Compatibility fix is applied (RpcAuthnLevelPrivacyEnabled = 0).' + vfFixMissing = 'The fix registry value is not visible yet.' + langHeader = 'LANGUAGE' langCurrent = 'Current language: {0}' langName = 'English' @@ -444,7 +510,7 @@ function Format-ToolArgs { } function Invoke-Tool { - param([string]$Path, $ToolArgs) + param([string]$Path, $ToolArgs, [scriptblock]$Verify) if (-not (Test-Path -LiteralPath $Path)) { Write-Host '' @@ -473,6 +539,12 @@ function Invoke-Tool { try { Stop-Transcript | Out-Null } catch { } } + # Verifikasi akhir opsional (#12): dijalankan sebelum jeda, agar hasilnya + # terlihat tepat setelah operasi selesai. + if ($Verify) { + try { & $Verify } catch { } + } + Pause-Menu } @@ -545,6 +617,180 @@ function Select-PrinterName { return $a } +# --------------------------------------------------------------------------- +# Pemeriksaan awal (pre-check) - #11 +# --------------------------------------------------------------------------- +function Test-TcpPort { + param([string]$Computer, [int]$Port, [int]$TimeoutMs = 1500) + $client = New-Object System.Net.Sockets.TcpClient + try { + $async = $client.BeginConnect($Computer, $Port, $null, $null) + if (-not $async.AsyncWaitHandle.WaitOne($TimeoutMs, $false)) { return $false } + $client.EndConnect($async) + return $true + } + catch { return $false } + finally { try { $client.Close() } catch { } } +} + +function Test-SpoolerRunning { + try { + $svc = Get-Service -Name 'Spooler' -ErrorAction Stop + return ($svc.Status -eq 'Running') + } + catch { return $false } +} + +function Get-LatestBackupFile { + $dir = Join-Path $env:ProgramData 'PrinterShare\logs' + if (-not (Test-Path -LiteralPath $dir)) { return $null } + $pattern = 'backup-*.json' + if ($Script:OsFamily -eq 'Win7') { $pattern = 'Win7-backup-*.txt' } + $files = @(Get-ChildItem -LiteralPath $dir -Filter $pattern -ErrorAction SilentlyContinue | + Sort-Object LastWriteTime -Descending) + if ($files.Count -eq 0) { return $null } + return $files[0] +} + +function New-PreflightCheck { + param([string]$Key, [string]$Status, [string]$Detail = '') + return (New-Object PSObject -Property @{ + Key = $Key + Name = (T $Key) + Status = $Status + Detail = $Detail + }) +} + +function Test-Preflight { + param([string]$Context = '', [string]$Server = '') + + $checks = New-Object System.Collections.ArrayList + + # 1. Hak Administrator + if (Test-IsAdmin) { + [void]$checks.Add((New-PreflightCheck 'pfAdmin' 'OK')) + } + else { + [void]$checks.Add((New-PreflightCheck 'pfAdmin' 'WARN' (T 'pfNotAdmin'))) + } + + # 2. Sistem operasi + if ($Script:OsFamily -eq 'Win8') { + [void]$checks.Add((New-PreflightCheck 'pfOs' 'WARN' (T 'pfOsWin8'))) + } + else { + [void]$checks.Add((New-PreflightCheck 'pfOs' 'OK' ((Get-OsLabel) + ' ' + $Script:ArchBits))) + } + + # 3. Layanan Print Spooler + if (Test-SpoolerRunning) { + [void]$checks.Add((New-PreflightCheck 'pfSpooler' 'OK' (T 'pfRunning'))) + } + else { + [void]$checks.Add((New-PreflightCheck 'pfSpooler' 'FAIL' ((T 'pfStopped') + ' - ' + (T 'pfSpoolerHint')))) + } + + # 4. Pemeriksaan khusus per konteks + if ($Context -eq 'Host') { + $count = @(Get-LocalPrinterNames).Count + if ($count -gt 0) { + [void]$checks.Add((New-PreflightCheck 'pfPrinter' 'OK' ((T 'pfPrinterFound') -f $count))) + } + else { + [void]$checks.Add((New-PreflightCheck 'pfPrinter' 'FAIL' (T 'pfNoPrinter'))) + } + } + + if ($Context -eq 'Client' -and $Server -ne '') { + if (Test-TcpPort -Computer $Server -Port 445) { + [void]$checks.Add((New-PreflightCheck 'pfServer' 'OK' ((T 'pfServerOk') -f $Server))) + } + else { + [void]$checks.Add((New-PreflightCheck 'pfServer' 'FAIL' ((T 'pfServerUnreachable') -f $Server))) + } + } + + if ($Context -eq 'Rollback') { + $backup = Get-LatestBackupFile + if ($backup) { + [void]$checks.Add((New-PreflightCheck 'pfBackup' 'OK' $backup.Name)) + } + else { + [void]$checks.Add((New-PreflightCheck 'pfBackup' 'FAIL' (T 'pfNoBackup'))) + } + } + + return ,$checks +} + +function Show-Preflight { + param($Checks, [bool]$Blocking = $true) + + Write-Header (T 'pfHeader') + $hasFail = $false + $hasWarn = $false + foreach ($c in @($Checks)) { + $color = 'Green' + if ($c.Status -eq 'WARN') { $color = 'Yellow'; $hasWarn = $true } + elseif ($c.Status -eq 'FAIL') { $color = 'Red'; $hasFail = $true } + $line = ' [{0,-4}] {1}' -f $c.Status, $c.Name + if ($c.Detail -ne '') { $line = $line + ' : ' + $c.Detail } + Write-Host $line -ForegroundColor $color + } + Write-Host '' + + if (-not $Blocking) { return $true } + + if ($hasFail) { + Write-Host (' ' + (T 'pfBlocked')) -ForegroundColor Red + Pause-Menu + return $false + } + if ($hasWarn) { + return (Read-YesNo (' ' + (T 'pfContinueAnyway')) $true) + } + return $true +} + +# --------------------------------------------------------------------------- +# Verifikasi akhir (post-check) - #12 +# --------------------------------------------------------------------------- +function Test-SharePresent { + param([string]$PrinterName = '', [string]$ShareName = '') + foreach ($p in @(Get-SharedPrinters)) { + if ($PrinterName -ne '' -and $p.Name -eq $PrinterName) { return $true } + if ($ShareName -ne '' -and $p.ShareName -eq $ShareName) { return $true } + } + return $false +} + +function Test-LocalPrinterMatch { + param([string]$Name = '', [string]$ShareName = '') + foreach ($n in @(Get-LocalPrinterNames)) { + if ($Name -ne '' -and $n -eq $Name) { return $true } + if ($ShareName -ne '' -and $n -like ('*' + $ShareName + '*')) { return $true } + } + return $false +} + +function Test-CompatFixApplied { + try { + $item = Get-ItemProperty -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Control\Print' ` + -Name 'RpcAuthnLevelPrivacyEnabled' -ErrorAction Stop + return ([int]$item.RpcAuthnLevelPrivacyEnabled -eq 0) + } + catch { return $false } +} + +function Write-VerifyResult { + param([bool]$Ok, [string]$Message) + Write-Host '' + Write-Host (' ' + (T 'vfHeader')) -ForegroundColor Cyan + if ($Ok) { Write-Host (' [OK] ' + $Message) -ForegroundColor Green } + else { Write-Host (' [WARN] ' + $Message) -ForegroundColor Yellow } +} + # --------------------------------------------------------------------------- # Menu utama # --------------------------------------------------------------------------- @@ -614,7 +860,17 @@ function Start-HostSharing { return } - Invoke-Tool (Get-HostScript) $toolArgs + if (-not (Show-Preflight (Test-Preflight -Context 'Host'))) { return } + + $verify = $null + if (-not $DryRun) { + $verify = { + $ok = Test-SharePresent -PrinterName $printer -ShareName $share + if ($ok) { Write-VerifyResult $true ((T 'vfSharedOk') -f $printer) } + else { Write-VerifyResult $false ((T 'vfSharedMissing') -f $printer) } + } + } + Invoke-Tool (Get-HostScript) $toolArgs $verify $Script:ShareStatus = $null } @@ -654,6 +910,8 @@ function Stop-HostSharing { return } + if (-not (Show-Preflight (Test-Preflight -Context 'Unshare'))) { return } + $ok = $false $code = '' if (Get-Command Set-Printer -ErrorAction SilentlyContinue) { @@ -680,6 +938,10 @@ function Stop-HostSharing { if ($ok) { Write-Host (' ' + (T 'unshareDone')) -ForegroundColor Green } else { Write-Host (' ' + ((T 'unshareFail') -f $code)) -ForegroundColor Red } + $gone = -not (Test-SharePresent -PrinterName $target.Name -ShareName $target.ShareName) + if ($gone) { Write-VerifyResult $true ((T 'vfUnsharedOk') -f $target.Name) } + else { Write-VerifyResult $false ((T 'vfUnsharedMissing') -f $target.Name) } + $Script:ShareStatus = $null Pause-Menu } @@ -715,6 +977,8 @@ function Show-HostMenu { function Start-Win7Batch { Clear-Host Write-Header (T 'clientItemBatch') + Write-Host (' ' + (T 'batchPassNote')) -ForegroundColor Gray + Write-Host '' $server = Read-Text (' ' + (T 'qHost')) if ($server -eq '') { Write-Host (' ' + ((T 'required') -f (T 'qHost'))) -ForegroundColor Yellow; Pause-Menu; return } @@ -722,13 +986,25 @@ function Start-Win7Batch { $share = Read-Text (' ' + (T 'qShare')) if ($share -eq '') { Write-Host (' ' + ((T 'required') -f (T 'qShare'))) -ForegroundColor Yellow; Pause-Menu; return } + # Password TIDAK ditanyakan/dioper di sini: script batch yang meminta langsung + # (net use ... *), sehingga password tidak pernah muncul di command line. + $user = Read-Text (' ' + (T 'qUser')) + if ($user -eq '') { $user = '-' } + $testStr = '-' if (Read-YesNo (' ' + (T 'qTestPage')) $false) { $testStr = 'test' } $repairStr = '-' if (Read-YesNo (' ' + (T 'clientItemRepair')) $false) { $repairStr = 'repair' } + if (-not (Show-Preflight (Test-Preflight -Context 'Client' -Server $server))) { return } + + $unc = '\\' + $server + '\' + $share $cmdPath = Join-Path $Script:Root 'client\Win7\02-Connect-Win7.cmd' - Invoke-Tool $cmdPath @($server, $share, '-', '-', $testStr, $repairStr) + Invoke-Tool $cmdPath @($server, $share, $user, $testStr, $repairStr) { + $ok = Test-LocalPrinterMatch -Name $unc -ShareName $share + if ($ok) { Write-VerifyResult $true ((T 'vfConnectedOk') -f $unc) } + else { Write-VerifyResult $false ((T 'vfConnectedMissing') -f $unc) } + } } function Start-ClientConnect { @@ -741,6 +1017,8 @@ function Start-ClientConnect { $server = Read-Text (' ' + (T 'qHost')) if ($server -eq '') { Write-Host (' ' + ((T 'required') -f (T 'qHost'))) -ForegroundColor Yellow; Pause-Menu; return } + if (-not (Show-Preflight (Test-Preflight -Context 'Client' -Server $server))) { return } + if ($Action -eq 'list') { Invoke-Tool $scriptPath @{ Server = $server; ListRemote = $true } return @@ -767,7 +1045,12 @@ function Start-ClientConnect { } } - Invoke-Tool $scriptPath $toolArgs + $unc = '\\' + $server + '\' + $share + Invoke-Tool $scriptPath $toolArgs { + $ok = Test-LocalPrinterMatch -Name $unc -ShareName $share + if ($ok) { Write-VerifyResult $true ((T 'vfConnectedOk') -f $unc) } + else { Write-VerifyResult $false ((T 'vfConnectedMissing') -f $unc) } + } } function Show-ClientMenu { @@ -824,6 +1107,9 @@ function Show-DiagMenu { if ($share -ne '') { $toolArgs['ShareName'] = $share } if ($printer -ne '') { $toolArgs['PrinterName'] = $printer } + # Diagnosa bersifat read-only, jadi pemeriksaan awal hanya sebagai info. + [void](Show-Preflight (Test-Preflight -Context 'Diagnose' -Server $server) -Blocking $false) + Invoke-Tool (Join-Path $Script:Root 'tools\03-Test-PrinterShare.ps1') $toolArgs } @@ -847,7 +1133,13 @@ function Show-FixMenu { $toolArgs = @{ AllowLegacyWin7 = $true } if (Read-YesNo (' ' + (T 'qFixGuest')) $false) { $toolArgs['AllowGuest'] = $true } - Invoke-Tool (Join-Path $Script:Root 'tools\04-Fix-LegacyCompat.ps1') $toolArgs + if (-not (Show-Preflight (Test-Preflight -Context 'Repair'))) { return } + + Invoke-Tool (Join-Path $Script:Root 'tools\04-Fix-LegacyCompat.ps1') $toolArgs { + $ok = Test-CompatFixApplied + if ($ok) { Write-VerifyResult $true (T 'vfFixOk') } + else { Write-VerifyResult $false (T 'vfFixMissing') } + } } # --------------------------------------------------------------------------- @@ -882,6 +1174,8 @@ function Show-RollbackMenu { $toolArgs = @{} if ($file -ne '') { $toolArgs[$fileParam] = $file } + if (-not (Show-Preflight (Test-Preflight -Context 'Rollback'))) { return } + Invoke-Tool $scriptPath $toolArgs $Script:ShareStatus = $null } diff --git a/README.en.md b/README.en.md index 816c360..3250d5d 100644 --- a/README.en.md +++ b/README.en.md @@ -52,6 +52,9 @@ Specifically built to eliminate recurring Windows printer sharing errors caused - **Cross-Architecture Support**: Built-in `-Mode LocalPort` workflow allows 32-bit (x86) Windows 7 clients to print to 64-bit (x64) hosts without driver architecture conflicts. - **Dry-Run Mode (`-WhatIf`)**: Safely test and preview all changes before applying them. - **Automated Rollback Journal**: Saves state snapshots in JSON / text logs, allowing you to restore the system to its prior state with a single command. +- **Pre-check**: before running an operation, the menu verifies Administrator rights, Windows version, the *Print Spooler* service, printer availability, host connectivity (port 445), and backup availability. Serious problems cancel the operation automatically. +- **Automatic Final Verification**: after an operation, the menu confirms the real result — the printer is actually shared, installed on the client, or the repair registry value is applied. +- **No Password on the Command Line**: host credentials are requested silently and are never passed as command-line arguments (so they never appear in the process list). --- @@ -170,6 +173,8 @@ The menu detects your Windows version (7 / 10 / 11) and picks the right script, > - **DIAGNOSTICS**: choose `3` (safe, changes nothing). > - **LOGS**: choose `6` to list recent logs/backups, open the folder, or view the content. > - **LANGUAGE**: choose `8` to switch between Indonesian and English; the choice is remembered. +> - **Pre-check**: every operation starts with a short check (Administrator, Spooler, printer, host connectivity, backup). Serious problems cancel the operation automatically. +> - **Final verification**: after an operation the menu shows the result (`[OK]`/`[WARN]`) so you know it truly succeeded. > - The menu only **wraps** the original scripts in `host\`, `client\`, and `tools\`; manual PowerShell usage below still works exactly as before. --- @@ -258,6 +263,12 @@ You can use the simple batch file (no PowerShell required) or the PowerShell scr .\02-Connect-Win7.ps1 -Server HOST-PC-NAME -ShareName EPSON-L120 -SetDefault -TestPage ``` +> [!NOTE] +> **No password on the command line.** The batch script never accepts a password as an argument (so it never appears in the process list). If the Host requires a login, pass the user name as the third argument — the password is then requested directly and silently by `net use`: +> ```cmd +> 02-Connect-Win7.cmd HOST-PC-NAME EPSON-L120 username +> ``` + --- #### Scenario C: Windows 7 (32-bit / x86) Client @@ -334,6 +345,7 @@ To revert all modifications back to their original state: 2. **Opt-in Legacy Compatibility**: Compatibility relaxations such as `-AllowLegacyWin7` and `-AllowGuest` are strictly opt-in flags. 3. **Driver Isolation via LocalPort**: 32-bit clients use local vendor drivers rather than pulling unsigned or mismatched drivers from the Host. 4. **Complete Auditability & Rollback**: Every registry change, firewall rule adjustment, and service configuration is logged and fully reversible. +5. **No Password on the Command Line**: host credentials are never passed as command-line arguments. The batch script requests the password silently (`net use ... *`), while `-SaveCredential` stores it in Windows Credential Manager via the `CredWrite` API (instead of `cmdkey /pass:`), so the password never shows up in the process list. --- diff --git a/README.md b/README.md index 551c6f5..1ff6579 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,9 @@ Dibuat khusus untuk mengatasi error printer sharing Windows yang sering muncul a - **Penanganan Khusus Arsitektur Berbeda**: Menyediakan solusi `-Mode LocalPort` agar klien Windows 7 32-bit dapat mencetak ke Host 64-bit tanpa konflik driver. - **Aman untuk Diuji (*Dry-Run*)**: Mendukung parameter `-WhatIf` untuk simulasi sebelum konfigurasi diterapkan. - **Rollback Otomatis**: Setiap perubahan dicatat ke dalam jurnal backup JSON / teks sehingga sistem dapat dikembalikan ke keadaan awal kapan saja. +- **Pemeriksaan Awal (*Pre-check*)**: sebelum menjalankan operasi, menu memeriksa hak Administrator, versi Windows, layanan *Print Spooler*, ketersediaan printer, konektivitas host (port 445), dan ketersediaan file backup. Bila ada masalah serius, operasi dibatalkan otomatis. +- **Verifikasi Akhir Otomatis**: setelah operasi, menu memastikan hasilnya nyata — printer benar-benar dibagikan, terpasang di klien, atau nilai registry perbaikan sudah diterapkan. +- **Tanpa Password di Command Line**: kredensial host diminta secara tersembunyi dan tidak pernah dikirim lewat argumen command line (tidak terlihat di daftar proses). --- @@ -170,6 +173,8 @@ Menu otomatis mendeteksi versi Windows (7 / 10 / 11) dan memilih script yang tep > - **DIAGNOSA**: pilih menu `3` (aman, tidak mengubah apa pun). > - **LOG**: pilih menu `6` untuk melihat log/backup terbaru, membuka foldernya, atau menampilkan isinya. > - **BAHASA**: pilih menu `8` untuk berganti antara Bahasa Indonesia dan English; pilihan disimpan. +> - **Pemeriksaan awal**: setiap operasi diawali pemeriksaan singkat (Administrator, Spooler, printer, konektivitas host, backup). Bila ada masalah serius, operasi dibatalkan otomatis. +> - **Verifikasi akhir**: setelah operasi, menu menampilkan hasil pemeriksaan akhir (`[OK]`/`[WARN]`) agar Anda tahu operasinya benar-benar berhasil. > - Menu ini hanya **membungkus** script asli di folder `host\`, `client\`, dan `tools\`; pemakaian manual lewat PowerShell tetap tersedia seperti dijelaskan di bawah. --- @@ -258,6 +263,12 @@ Bisa menggunakan script Batch biasa (cepat & tanpa repot) atau PowerShell: .\02-Connect-Win7.ps1 -Server NAMA-PC-HOST -ShareName EPSON-L120 -SetDefault -TestPage ``` +> [!NOTE] +> **Password tidak lewat command line.** Script batch tidak menerima password sebagai argumen (agar tidak terlihat di daftar proses). Bila host meminta login, tambahkan nama pengguna sebagai argumen ketiga — password akan diminta langsung secara tersembunyi oleh `net use`: +> ```cmd +> 02-Connect-Win7.cmd NAMA-PC-HOST EPSON-L120 namauser +> ``` + --- #### Kasus C: Klien Windows 7 (32-bit / x86) @@ -334,6 +345,7 @@ Untuk mengembalikan konfigurasi Host ke kondisi awal: 2. **Opt-in Compatibility**: Opsi pelonggaran keamanan seperti `-AllowLegacyWin7` dan `-AllowGuest` bersifat **opsional per switch**, dan tidak aktif secara default. 3. **Isolasi Driver LocalPort**: Klien 32-bit tidak dipaksa mengambil driver dari Host 64-bit, melainkan memuat driver lokal terisolasi untuk stabilitas spooler. 4. **Audit & Rollback Penuh**: Seluruh modifikasi registry, status layanan, dan rule firewall tersimpan dalam file cadangan JSON / teks yang dapat dipulihkan sewaktu-waktu. +5. **Tanpa Password di Command Line**: kredensial host tidak pernah dikirim lewat argumen command line. Script batch meminta password secara tersembunyi (`net use ... *`), sedangkan `-SaveCredential` menyimpannya ke Windows Credential Manager lewat API `CredWrite` (bukan `cmdkey /pass:`), sehingga password tidak muncul di daftar proses. --- diff --git a/client/Win7/02-Connect-Win7.cmd b/client/Win7/02-Connect-Win7.cmd index d1d3d90..78c466e 100644 --- a/client/Win7/02-Connect-Win7.cmd +++ b/client/Win7/02-Connect-Win7.cmd @@ -6,13 +6,19 @@ rem =========================================================================== rem KLIEN Windows 7 - connect printer lewat batch (tanpa PowerShell) rem rem Pemakaian: -rem 02-Connect-Win7.cmd [USER] [PASSWORD] [test] [repair] +rem 02-Connect-Win7.cmd [USER] [test] [repair] rem rem Contoh: rem 02-Connect-Win7.cmd PC-HOST EPSON-L120 -rem 02-Connect-Win7.cmd PC-HOST EPSON-L120 printer P@ssw0rd -rem 02-Connect-Win7.cmd PC-HOST EPSON-L120 - - test -rem 02-Connect-Win7.cmd PC-HOST EPSON-L120 - - - repair +rem 02-Connect-Win7.cmd PC-HOST EPSON-L120 printer +rem 02-Connect-Win7.cmd PC-HOST EPSON-L120 - test +rem 02-Connect-Win7.cmd PC-HOST EPSON-L120 - - repair +rem +rem KEAMANAN: password TIDAK PERNAH diterima lewat command line, supaya tidak +rem terlihat di daftar proses (Task Manager / wmic process). Bila USER diisi, +rem password diminta langsung oleh "net use ... *" dan ketikannya tidak +rem ditampilkan. Untuk akses tanpa password (akun saat ini), kosongkan USER +rem atau isi dengan tanda "-". rem rem CATATAN: ini hanya untuk Windows 7 64-bit. rem Windows 7 32-bit butuh driver x86 lokal - pakai 02-Connect-Win7.ps1 @@ -22,12 +28,12 @@ rem =========================================================================== set "SERVER=%~1" set "SHARE=%~2" set "PUSER=%~3" -set "PPASS=%~4" -set "DOTEST=%~5" -set "DOREPAIR=%~6" +set "DOTEST=%~4" +set "DOREPAIR=%~5" if "%SERVER%"=="" goto :usage if "%SHARE%"=="" goto :usage +if /i "%PUSER%"=="-" set "PUSER=" set "UNC=\\%SERVER%\%SHARE%" @@ -51,8 +57,10 @@ if errorlevel 1 ( echo [OK] Share host bisa dibaca ) -if not "%PUSER%"=="" if not "%PUSER%"=="-" if not "%PPASS%"=="" ( - net use \\%SERVER%\IPC$ /user:%PUSER% %PPASS% >nul 2>&1 +rem --- Autentikasi (password tidak pernah lewat command line) ---------------- +if not "%PUSER%"=="" ( + echo Autentikasi sebagai "%PUSER%" ^(ketik password, tidak ditampilkan^): + net use \\%SERVER%\IPC$ /user:%PUSER% * if errorlevel 1 ( echo [WARN] Autentikasi gagal. Periksa user/password. ) else ( @@ -104,11 +112,13 @@ goto :end :usage echo. echo Pemakaian: -echo 02-Connect-Win7.cmd ^ ^ [USER] [PASSWORD] [test] [repair] +echo 02-Connect-Win7.cmd ^ ^ [USER] [test] [repair] echo. echo Contoh: echo 02-Connect-Win7.cmd PC-HOST EPSON-L120 -echo 02-Connect-Win7.cmd PC-HOST EPSON-L120 printer P@ssw0rd test +echo 02-Connect-Win7.cmd PC-HOST EPSON-L120 printer test +echo. +echo Password diminta otomatis ^(tidak ditampilkan^) bila USER diisi. echo. echo Windows 7 32-bit: jalankan 02-Connect-Win7.ps1 -Mode LocalPort echo. diff --git a/client/Win7/02-Connect-Win7.ps1 b/client/Win7/02-Connect-Win7.ps1 index e167b79..b38bd6f 100644 --- a/client/Win7/02-Connect-Win7.ps1 +++ b/client/Win7/02-Connect-Win7.ps1 @@ -82,6 +82,64 @@ function Find-Printer { return $null } +# Menyimpan kredensial ke Windows Credential Manager TANPA menaruh password di +# command line. Cara lama (cmdkey /pass:...) membuat password terlihat di daftar +# proses. Di sini dipakai CredWriteW dari advapi32.dll - cara yang sama yang +# dipakai cmdkey secara internal - dengan password dikirim lewat memori. +$script:CredentialApiSource = @' +using System; +using System.Runtime.InteropServices; + +public static class PrinterShareCredential { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct CREDENTIAL { + public int Flags; + public int Type; + [MarshalAs(UnmanagedType.LPWStr)] public string TargetName; + [MarshalAs(UnmanagedType.LPWStr)] public string Comment; + public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten; + public int CredentialBlobSize; + public IntPtr CredentialBlob; + public int Persist; + public int AttributeCount; + public IntPtr Attributes; + [MarshalAs(UnmanagedType.LPWStr)] public string TargetAlias; + [MarshalAs(UnmanagedType.LPWStr)] public string UserName; + } + + [DllImport("advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern bool CredWrite(ref CREDENTIAL userCredential, int flags); +} +'@ + +function Save-HostCredential { + param([string]$Computer, [System.Management.Automation.PSCredential]$Credential) + + if (-not ('PrinterShareCredential' -as [type])) { + Add-Type -TypeDefinition $script:CredentialApiSource -ErrorAction Stop + } + + $bytes = [System.Text.Encoding]::Unicode.GetBytes($Credential.GetNetworkCredential().Password) + $ptr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($bytes.Length) + try { + [System.Runtime.InteropServices.Marshal]::Copy($bytes, 0, $ptr, $bytes.Length) + + $cred = New-Object 'PrinterShareCredential+CREDENTIAL' + $cred.Type = 2 # CRED_TYPE_DOMAIN_PASSWORD + $cred.TargetName = 'Domain:target=' + $Computer + $cred.CredentialBlob = $ptr + $cred.CredentialBlobSize = $bytes.Length + $cred.Persist = 2 # CRED_PERSIST_LOCAL_MACHINE + $cred.UserName = $Credential.UserName + + if ([PrinterShareCredential]::CredWrite([ref]$cred, 0)) { return 0 } + return [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + } + finally { + [System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($ptr) + } +} + function Show-Hints { Write-Host '' Write-Host 'Penyebab umum:' -ForegroundColor Yellow @@ -162,8 +220,9 @@ if ($Server -ne '.' -and $Server -ne 'localhost' -and $Server -ne $env:COMPUTERN if ($SaveCredential) { if (-not $Credential) { $Credential = Get-Credential -Credential $null } if ($Credential -and -not $WhatIf) { - & cmdkey.exe ('/add:' + $Server) ('/user:' + $Credential.UserName) ('/pass:' + $Credential.GetNetworkCredential().Password) | Out-Null - Write-Ok 'Kredensial disimpan' + $rc = Save-HostCredential -Computer $Server -Credential $Credential + if ($rc -eq 0) { Write-Ok 'Kredensial disimpan (Credential Manager)' } + else { Write-Warn2 ('Gagal menyimpan kredensial (kode {0})' -f $rc) } } } diff --git a/tests/Menu.Tests.ps1 b/tests/Menu.Tests.ps1 index 4ff25bd..45942df 100644 --- a/tests/Menu.Tests.ps1 +++ b/tests/Menu.Tests.ps1 @@ -140,3 +140,63 @@ Describe 'Menu.ps1 - printer' { Assert-True ((Test-IsAdmin) -is [bool]) } } + +Describe 'Menu.ps1 - pemeriksaan awal' { + It 'mengembalikan daftar pemeriksaan untuk konteks Host' { + $checks = Test-Preflight -Context 'Host' + Assert-True ($checks.Count -ge 3) 'Pemeriksaan awal Host terlalu sedikit.' + foreach ($c in $checks) { + Assert-True (@('OK', 'WARN', 'FAIL') -contains $c.Status) ('Status tidak dikenal: ' + $c.Status) + Assert-True ($c.Name.Length -gt 0) 'Nama pemeriksaan kosong.' + } + } + + It 'memeriksa konektivitas host pada konteks Client' { + $checks = Test-Preflight -Context 'Client' -Server $env:COMPUTERNAME + $server = @($checks | Where-Object { $_.Key -eq 'pfServer' }) + Assert-Equal $server.Count 1 + } + + It 'melewati pemeriksaan host bila Server kosong' { + $checks = Test-Preflight -Context 'Client' + $server = @($checks | Where-Object { $_.Key -eq 'pfServer' }) + Assert-Equal $server.Count 0 + } + + It 'memeriksa ketersediaan backup pada konteks Rollback' { + $checks = Test-Preflight -Context 'Rollback' + $backup = @($checks | Where-Object { $_.Key -eq 'pfBackup' }) + Assert-Equal $backup.Count 1 + } + + It 'memeriksa jumlah printer pada konteks Host' { + $checks = Test-Preflight -Context 'Host' + $printer = @($checks | Where-Object { $_.Key -eq 'pfPrinter' }) + Assert-Equal $printer.Count 1 + } +} + +Describe 'Menu.ps1 - verifikasi akhir' { + It 'Test-SharePresent mengembalikan boolean' { + Assert-True ((Test-SharePresent -ShareName 'PASTI-TIDAK-ADA-XYZ') -is [bool]) + } + + It 'Test-LocalPrinterMatch mengembalikan boolean' { + Assert-True ((Test-LocalPrinterMatch -Name 'PASTI-TIDAK-ADA-XYZ') -is [bool]) + } + + It 'Test-CompatFixApplied mengembalikan boolean' { + Assert-True ((Test-CompatFixApplied) -is [bool]) + } + + It 'Test-SpoolerRunning mengembalikan boolean' { + Assert-True ((Test-SpoolerRunning) -is [bool]) + } + + It 'mengenali printer yang memang sedang dibagikan' { + $shared = @(Get-SharedPrinters) + if ($shared.Count -gt 0) { + Assert-True (Test-SharePresent -PrinterName $shared[0].Name -ShareName $shared[0].ShareName) + } + } +} diff --git a/tests/Structure.Tests.ps1 b/tests/Structure.Tests.ps1 index 4070c4b..5f7541f 100644 --- a/tests/Structure.Tests.ps1 +++ b/tests/Structure.Tests.ps1 @@ -67,4 +67,22 @@ Describe 'Struktur repositori' { $c = Get-Content -LiteralPath (Join-Path $RepoRoot 'README.en.md') -Raw Assert-Match $c 'Menu\.cmd' } + + It 'batch Win7 tidak menerima password lewat command line' { + $c = Get-Content -LiteralPath (Join-Path $RepoRoot 'client\Win7\02-Connect-Win7.cmd') -Raw + Assert-NotMatch $c '%PPASS%' + Assert-Match $c '/user:%PUSER% \*' + } + + It 'klien Win7 .ps1 menyimpan kredensial tanpa cmdkey /pass:' { + $c = Get-Content -LiteralPath (Join-Path $RepoRoot 'client\Win7\02-Connect-Win7.ps1') -Raw + Assert-NotMatch $c 'cmdkey\.exe' + Assert-Match $c 'CredWrite' + } + + It 'menu mengoper user (bukan password) ke batch Win7' { + $c = Get-Content -LiteralPath (Join-Path $RepoRoot 'Menu.ps1') -Raw + Assert-Match $c '02-Connect-Win7\.cmd' + Assert-Match $c '\$server, \$share, \$user' + } }