From c62bd9cf395b8091af0e1a6e912358f6fe7b31ea Mon Sep 17 00:00:00 2001 From: EJClaw Date: Wed, 11 Nov 2026 19:01:36 +0900 Subject: [PATCH] voice-changer: lock install folder ownership, migrate old mic backup, refresh comm modes on upgrade - installer/secure-dir.ps1 (run elevated from tmp): CheckParent: refuse folders whose nearest existing parent is not a drive root or owned by Administrators/SYSTEM/TrustedInstaller. Prepare (before files are copied): owner Administrators + protected DACL (SY/BA full, Users RX), verify, abort setup on failure; refuse links pointing outside the folder; on upgrade delete the old executable parts (scripts/app/launcher/uninstall/root files) that 21b4278 left user-writable. Finish: Users modify only on data dirs; verify every admin-run file is admin-owned and not user-writable, otherwise skip APO registration and engine download. - mic-apo.ps1: migrate config\mic-apo-backup.json to apo\ with value validation (CLSID/mode GUID/ DWORD only, own CLSID stripped), never record our own APO as the original value, upgrade the DEFAULT-only mode list written by 21b4278 to DEFAULT/COMMUNICATIONS/SPEECH/MEDIA, remove the old config\mic-apo.json. Windows 11 VM: user-precreated folder -> owner BA, basic-user WRITE_DAC/WRITE_OWNER/grant/icacls/ write/rename all ERROR_ACCESS_DENIED; user-owned parent refused (CheckParent exit 20); 21b4278 install -> upgrade: backup migrated, modes refreshed, Communications capture 440 Hz, uninstall restores FxProperties to the pre-install state. Co-Authored-By: Claude Opus 5.5 --- voice-changer/README.md | 6 +- voice-changer/installer/VoiceChanger.iss | 65 ++++++----- voice-changer/installer/secure-dir.ps1 | 138 +++++++++++++++++++++++ voice-changer/scripts/mic-apo.ps1 | 100 +++++++++++++--- 4 files changed, 263 insertions(+), 46 deletions(-) create mode 100644 voice-changer/installer/secure-dir.ps1 diff --git a/voice-changer/README.md b/voice-changer/README.md index b46e359..24eeb7c 100644 --- a/voice-changer/README.md +++ b/voice-changer/README.md @@ -12,7 +12,7 @@ 1. `VoiceChangerSetup.exe` 를 실행합니다 (관리자 권한 확인 창이 뜹니다). 2. **설치할 폴더**를 고릅니다. 기본값은 `C:\VoiceChanger` 이고, 다른 드라이브(`D:\...`)나 한글 · 띄어쓰기가 들어간 경로도 됩니다. - 비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). + 비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). 상위 폴더가 일반 사용자 소유인 곳(예: 바탕 화면 · 문서 아래)도 거절합니다. Python · 엔진 · torch · 목소리 모델 · 설정 · 학습 파일 · 캐시 · 임시 파일이 **모두 이 폴더 안에만** 저장됩니다. 설치하면서 약 8GB 를 내려받고 모델을 만들수록 늘어나므로 15GB 이상 비어 있는 드라이브를 고르세요. 3. 설치 프로그램이 마이크마다 변환 모듈을 붙이고(윈도우 소리가 1~2초 끊김), 검은 창에서 Python 3.12 · 엔진(Applio) · @@ -24,7 +24,7 @@ 디스코드 · 게임의 입력 장치는 **평소 쓰던 마이크 그대로** 두면 됩니다. - 내려받다가 끊기면 설치 폴더의 `install.bat` 을 실행합니다. 받은 곳부터 이어서 받습니다. -- 권한: 설치 폴더와 실행 파일 · `app\` · `scripts\` · `apo\` · `uninstall\` 은 관리자만 고칠 수 있습니다. 일반 사용자는 `models` · `training` · `datasets` · `config` · `cache` · `env` · `engine` · `tools` 에만 씁니다. 엔진 내려받기(`install.ps1`)는 관리자 권한 없이 돕니다. +- 권한: 설치 프로그램이 설치 폴더의 소유자를 Administrators 로 바꾸고 잠근 뒤 확인합니다(`installer\secure-dir.ps1`, 실패하면 설치 중단). 설치 폴더와 실행 파일 · `app\` · `scripts\` · `apo\` · `uninstall\` 은 관리자만 고칠 수 있습니다. 일반 사용자는 `models` · `training` · `datasets` · `config` · `cache` · `env` · `engine` · `tools` 에만 씁니다. 엔진 내려받기(`install.ps1`)는 관리자 권한 없이 돕니다. - 폴더 밖에 남는 것은 윈도우가 관리하는 항목뿐입니다: 시작 메뉴 바로 가기, 프로그램 제거 목록, 마이크 모듈 등록(레지스트리). 사용자 폴더(`%APPDATA%` · `%LOCALAPPDATA%` · `%TEMP%` · `.cache`)에는 아무것도 쓰지 않습니다. - 제거: 설정 → 앱 → 음성 변환기 → 제거. 마이크 설정을 원래대로 되돌리고, 만든 모델 · 녹음 · 설정까지 지울지 묻습니다. @@ -32,7 +32,7 @@ ### 마이크 모듈은 어떻게 동작하나 윈도우는 마이크 소리를 앱에 넘기기 전에 오디오 처리 모듈(APO, Equalizer APO 와 같은 방식)을 거칩니다. -설치 프로그램이 `apo\VoiceChangerAPO.dll` 을 각 마이크의 처리 단계에 붙입니다 (`scripts\mic-apo.ps1`, 바꾼 값의 원래 값은 `apo\mic-apo-backup.json`). +설치 프로그램이 `apo\VoiceChangerAPO.dll` 을 각 마이크의 처리 단계에 붙입니다 (`scripts\mic-apo.ps1`, 바꾼 값의 원래 값은 `apo\mic-apo-backup.json`, 이전 버전의 `config\mic-apo-backup.json` 은 값을 검증한 뒤 옮김). 통화 앱(디스코드 등)이 여는 통화(Communications) 모드 스트림에도 붙도록 기본 · 통화 · 음성 · 미디어 모드로 등록합니다. 드라이버가 이미 모드 목록을 갖고 있으면 그 목록을 그대로 둡니다. - 변환기가 꺼져 있으면 아무것도 하지 않습니다. 원래 목소리가 그대로 나갑니다 diff --git a/voice-changer/installer/VoiceChanger.iss b/voice-changer/installer/VoiceChanger.iss index c7dcf36..0f2aafd 100644 --- a/voice-changer/installer/VoiceChanger.iss +++ b/voice-changer/installer/VoiceChanger.iss @@ -45,6 +45,7 @@ ko.DiskSpaceMBLabel=설치 중에 약 8GB 를 더 내려받습니다. 15GB 이 Name: "desktopicon"; Description: "바탕 화면에 바로 가기 만들기"; Flags: unchecked [Files] +Source: "secure-dir.ps1"; Flags: dontcopy Source: "..\dist\payload\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion [Icons] @@ -58,10 +59,18 @@ Filename: "{app}\VoiceChanger.exe"; Description: "음성 변환기 실행"; Flag Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{app}\scripts\mic-apo.ps1"" -Uninstall -Root ""{app}"""; Flags: runhidden waituntilterminated; RunOnceId: "MicApoUninstall" [Code] -const - { 일반 사용자가 쓸 수 있는 폴더: 앱(일반 권한)이 만드는 데이터와, 일반 권한으로 내려받는 엔진 · Python. - 관리자 권한으로 실행되는 것(설치 폴더 루트의 exe, app\, scripts\, apo\, uninstall\)은 여기에 두지 않는다. } - UserDirs = 'models,training,datasets,config,cache,env,engine,tools'; +{ 설치 폴더 보안은 secure-dir.ps1 (설치 프로그램에 들어 있고 임시 폴더에 풀어서 관리자 권한으로 실행)이 맡는다. + 관리자 권한으로 실행되는 것(설치 폴더 루트의 exe, app\, scripts\, apo\, uninstall\)은 관리자만 고칠 수 있고, + 일반 사용자는 데이터 폴더(models · training · datasets · config · cache · env · engine · tools)에만 쓴다. } +function SecureDir(const Mode, Dir: String): Integer; +begin + ExtractTemporaryFile('secure-dir.ps1'); + if not Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), + '-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{tmp}\secure-dir.ps1') + '" -Mode ' + Mode + ' -App "' + Dir + '"', + '', SW_HIDE, ewWaitUntilTerminated, Result) then + Result := -1; + Log('secure-dir ' + Mode + ' exit=' + IntToStr(Result)); +end; function PowerShell(const Args: String; const Show: Integer; var Code: Integer): Boolean; begin @@ -102,30 +111,14 @@ begin SuppressibleMsgBox('이 폴더에는 이미 다른 파일이 있습니다.' + #13#10 + '비어 있는 폴더나 새 폴더를 골라 주세요. (예: ' + AddBackslash(Dir) + 'VoiceChanger)', mbError, MB_OK, IDOK); Result := False; + Exit; end; -end; - -{ 설치 폴더는 관리자 · SYSTEM 만 고칠 수 있게 잠그고(상위 폴더에서 물려받는 "인증된 사용자 수정" 권한을 끊음), - 일반 사용자에게는 UserDirs 폴더만 수정 권한을 준다. 일반 사용자가 관리자 권한으로 실행되는 - scripts\mic-apo.ps1 · 제거 프로그램 · APO DLL 을 바꿔치기할 수 없게 하기 위함. } -procedure LockDownAppDir; -var - Code, I: Integer; - App, Rest, D: String; -begin - App := ExpandConstant('{app}'); - Exec(ExpandConstant('{sys}\icacls.exe'), '"' + App + '" /inheritance:r /grant:r *S-1-5-18:(OI)(CI)F *S-1-5-32-544:(OI)(CI)F *S-1-5-32-545:(OI)(CI)RX', - '', SW_HIDE, ewWaitUntilTerminated, Code); - Log('icacls lock exit=' + IntToStr(Code)); - Rest := UserDirs + ','; - while Rest <> '' do + { 상위 폴더가 일반 사용자 소유면 그 사용자가 설치 폴더를 통째로 다른 것으로 바꿔칠 수 있다 } + if SecureDir('CheckParent', Dir) <> 0 then begin - I := Pos(',', Rest); - D := Copy(Rest, 1, I - 1); - Rest := Copy(Rest, I + 1, Length(Rest)); - ForceDirectories(App + '\' + D); - Exec(ExpandConstant('{sys}\icacls.exe'), '"' + App + '\' + D + '" /grant *S-1-5-32-545:(OI)(CI)M', '', SW_HIDE, ewWaitUntilTerminated, Code); - Log('icacls user dir ' + D + ' exit=' + IntToStr(Code)); + SuppressibleMsgBox('이 위치의 상위 폴더는 관리자 소유가 아니라서 설치할 수 없습니다.' + #13#10 + + '드라이브 바로 아래(예: C:\VoiceChanger, D:\VoiceChanger)나 Program Files 처럼 관리자가 관리하는 곳을 골라 주세요.', mbError, MB_OK, IDOK); + Result := False; end; end; @@ -139,6 +132,16 @@ begin if FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Stop-Service -Name AudioEndpointBuilder -Force"', '', SW_HIDE, ewWaitUntilTerminated, Code); + { 파일을 풀기 전에 설치 폴더를 관리자 소유로 잠근다. 실패하면 설치하지 않는다. } + case SecureDir('Prepare', ExpandConstant('{app}')) of + 0: ; + 10: Result := '이 폴더에는 이미 다른 파일이 있습니다. 비어 있는 폴더나 새 폴더를 골라 주세요.'; + 11: Result := '설치 폴더 안에 링크(정션 · 심볼릭 링크)가 있어 안전하게 설치할 수 없습니다. 링크를 지우거나 새 폴더를 골라 주세요.'; + else + Result := '설치 폴더의 권한을 잠그지 못했습니다. 다른 폴더를 골라 다시 설치해 주세요.'; + end; + if (Result <> '') and FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then + Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code); end; procedure CurStepChanged(CurStep: TSetupStep); @@ -146,7 +149,15 @@ var Code: Integer; begin if CurStep <> ssPostInstall then Exit; - LockDownAppDir; + { 데이터 폴더에만 사용자 쓰기 권한을 주고, 관리자 권한으로 실행되는 파일이 잠겼는지 확인한다. + 확인이 안 되면 관리자 권한으로 아무것도 실행하지 않는다. } + if SecureDir('Finish', ExpandConstant('{app}')) <> 0 then + begin + Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code); + SuppressibleMsgBox('설치 폴더의 권한을 확인하지 못해 마이크 연결과 엔진 내려받기를 하지 않았습니다.' + #13#10 + + '음성 변환기를 제거한 뒤 다른 폴더(예: C:\VoiceChanger)에 다시 설치해 주세요.', mbError, MB_OK, IDOK); + Exit; + end; WizardForm.StatusLabel.Caption := '마이크에 변환 모듈을 붙이는 중... (윈도우 소리가 잠깐 끊깁니다)'; if not PowerShell('-File "' + ExpandConstant('{app}\scripts\mic-apo.ps1') + '" -Install -Root "' + ExpandConstant('{app}') + '"', SW_HIDE, Code) or (Code <> 0) then diff --git a/voice-changer/installer/secure-dir.ps1 b/voice-changer/installer/secure-dir.ps1 new file mode 100644 index 0000000..e64b00e --- /dev/null +++ b/voice-changer/installer/secure-dir.ps1 @@ -0,0 +1,138 @@ +# 설치 폴더 보안 (설치 프로그램이 관리자 권한으로 {tmp} 에서 실행). 종료 코드로 결과를 알린다. +# -Mode CheckParent -App <폴더> 가장 가까운 상위 폴더가 드라이브 루트이거나 관리자 · SYSTEM · TrustedInstaller 소유인지 +# 0 = 괜찮음, 20 = 일반 사용자 소유 (그 사용자가 설치 폴더를 통째로 바꿔치기할 수 있음) +# -Mode Prepare -App <폴더> 파일을 풀기 전: 폴더를 만들고 소유자를 Administrators 로, 권한을 관리자 · SYSTEM 전체 + +# Users 읽기로 잠근다. 업데이트면 이전 버전이 사용자 쓰기 폴더에 두었던 실행 부분을 지운다. +# 10 = 다른 파일이 있는 폴더, 11 = 링크(정션 · 심볼릭 링크)가 있음, 12 = 잠그지 못함 +# -Mode Finish -App <폴더> 파일을 푼 뒤: 데이터 폴더에만 Users 수정 권한을 주고, 관리자 권한으로 실행되는 파일이 +# 관리자 소유이고 일반 사용자가 쓸 수 없는지 확인한다. 13 = 확인 실패 +param([Parameter(Mandatory)][string]$Mode, [Parameter(Mandatory)][string]$App) +$ErrorActionPreference = 'Stop' +$SY = 'S-1-5-18'; $BA = 'S-1-5-32-544'; $BU = 'S-1-5-32-545' +$TI = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464' +$UserDirs = 'models', 'training', 'datasets', 'config', 'cache', 'env', 'engine', 'tools' +# 쓰기 계열 권한 비트: WriteData · AppendData · WriteEA · DeleteChild · WriteAttributes · Delete · WriteDAC · WriteOwner + GENERIC_ALL/WRITE +$WriteBits = 0x2 -bor 0x4 -bor 0x10 -bor 0x40 -bor 0x100 -bor 0x10000 -bor 0x40000 -bor 0x80000 -bor 0x10000000 -bor 0x40000000 +$Sid = [System.Security.Principal.SecurityIdentifier] +$App = [IO.Path]::GetFullPath($App).TrimEnd('\') + +function Say($m) { Write-Host "[secure-dir] $m" } +function Is-Link([string]$p) { ([IO.File]::GetAttributes($p) -band [IO.FileAttributes]::ReparsePoint) -ne 0 } + +# 링크를 따라 들어가지 않고 폴더 안을 모두 훑어, 설치 폴더 밖을 가리키는 첫 링크를 찾는다. +# 안을 가리키는 링크는 괜찮다 (uv 가 tools\python 안에 "cpython-3.12-..." → "cpython-3.12.x-..." 정션을 만듦). +function Link-Target([string]$p) { + $t = @((Get-Item -LiteralPath $p -Force).Target) | Select-Object -First 1 + if (-not $t) { return $null } + $t = [string]$t + if ($t.StartsWith('\\?\')) { $t = $t.Substring(4) } + if (-not [IO.Path]::IsPathRooted($t)) { $t = Join-Path (Split-Path -Parent $p) $t } + return [IO.Path]::GetFullPath($t) +} +function Find-Link([string]$dir) { + $stack = New-Object System.Collections.Stack + $stack.Push($dir) + while ($stack.Count) { + foreach ($e in [IO.Directory]::EnumerateFileSystemEntries($stack.Pop())) { + $a = [IO.File]::GetAttributes($e) + if ($a -band [IO.FileAttributes]::ReparsePoint) { + $t = Link-Target $e + if (-not $t -or -not ($t.StartsWith($App + '\', [StringComparison]::OrdinalIgnoreCase))) { return "$e -> $t" } + continue # 안쪽 링크: 따라 들어가지 않음 (가리키는 곳은 따로 훑음) + } + if ($a -band [IO.FileAttributes]::Directory) { $stack.Push($e) } + } + } + return $null +} + +function Owner-Sid([string]$p) { (Get-Acl -LiteralPath $p).GetOwner($Sid).Value } + +if ($Mode -eq 'CheckParent') { + $p = Split-Path -Parent $App + while ($p -and -not (Test-Path -LiteralPath $p)) { $p = Split-Path -Parent $p } + if (-not $p -or $p -eq [IO.Path]::GetPathRoot($p)) { Say "상위: 드라이브 루트"; exit 0 } + $o = Owner-Sid $p + Say "상위: $p 소유자 $o" + if ($o -in @($BA, $SY, $TI)) { exit 0 } + exit 20 +} + +if ($Mode -eq 'Prepare') { + $upgrade = Test-Path -LiteralPath (Join-Path $App 'uninstall\unins000.exe') + if (Test-Path -LiteralPath $App) { + if (Is-Link $App) { Say "설치 폴더가 링크: $App"; exit 11 } + if (-not $upgrade -and [IO.Directory]::EnumerateFileSystemEntries($App).GetEnumerator().MoveNext()) { exit 10 } + $link = Find-Link $App + if ($link) { Say "링크 발견: $link"; exit 11 } + } + if ($upgrade) { + # 이전 버전(21b4278)은 설치 폴더 전체를 사용자 쓰기로 두었다. 관리자 권한으로 실행되는 부분(스크립트 · 앱 코드 · + # 제거 프로그램과 그 기록 · 실행기)은 믿지 않고 지운 뒤 새로 푼다. apo\ 는 원래 마이크 설정 백업만 남긴다(mic-apo.ps1 이 검증). + foreach ($d in 'scripts', 'app', 'launcher', 'uninstall') { + $p = Join-Path $App $d + if (Test-Path -LiteralPath $p) { Remove-Item -LiteralPath $p -Recurse -Force } + } + Get-ChildItem -LiteralPath $App -Force -File | Remove-Item -Force + $apo = Join-Path $App 'apo' + if (Test-Path -LiteralPath $apo) { Get-ChildItem -LiteralPath $apo -Force | ? { $_.Name -ne 'mic-apo-backup.json' } | Remove-Item -Recurse -Force } + Say "업데이트: 이전 실행 파일 정리" + } + New-Item -ItemType Directory -Force -Path $App | Out-Null + $sd = New-Object System.Security.AccessControl.DirectorySecurity + # 소유자 · 그룹 · DACL 만 쓴다 (SACL 까지 쓰면 감사 특권이 필요함) + $sd.SetSecurityDescriptorSddlForm("O:BAG:SYD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;BU)", + [System.Security.AccessControl.AccessControlSections]'Owner, Group, Access') + [IO.Directory]::SetAccessControl($App, $sd) + foreach ($c in Get-ChildItem -LiteralPath $App -Force) { + & icacls $c.FullName /setowner "*$BA" /C /Q | Out-Null + if ($LASTEXITCODE -ne 0) { Say "소유자 변경 실패: $($c.FullName)"; exit 12 } + if ($c.Name -notin $UserDirs) { + # 관리자 쪽 하위 항목(apo\ 백업 등): 전부 관리자 소유, 명시 권한 없이 상속만 + & icacls $c.FullName /setowner "*$BA" /T /C /Q | Out-Null + & icacls $c.FullName /reset /T /C /Q | Out-Null + if ($LASTEXITCODE -ne 0) { Say "권한 초기화 실패: $($c.FullName)"; exit 12 } + } + } + $acl = Get-Acl -LiteralPath $App + $rules = @($acl.GetAccessRules($true, $true, $Sid)) + $bad = @($rules | ? { $_.IsInherited -or $_.IdentityReference.Value -notin @($SY, $BA, $BU) -or + ($_.IdentityReference.Value -eq $BU -and ([int]$_.FileSystemRights -band $WriteBits)) }) + if ($acl.GetOwner($Sid).Value -ne $BA -or -not $acl.AreAccessRulesProtected -or $bad.Count -gt 0) { + Say "잠금 확인 실패: owner=$($acl.GetOwner($Sid).Value) protected=$($acl.AreAccessRulesProtected) bad=$($bad.Count)" + exit 12 + } + Say "잠금 완료" + exit 0 +} + +if ($Mode -eq 'Finish') { + foreach ($d in $UserDirs) { + $p = Join-Path $App $d + if (-not (Test-Path -LiteralPath $p)) { New-Item -ItemType Directory -Path $p | Out-Null } + if (Is-Link $p) { Say "데이터 폴더가 링크: $p"; exit 13 } + $has = @((Get-Acl -LiteralPath $p).GetAccessRules($true, $false, $Sid) | ? { + $_.IdentityReference.Value -eq $BU -and ([int]$_.FileSystemRights -band 0x2) -and $_.InheritanceFlags -eq 'ContainerInherit, ObjectInherit' }) + if (-not $has) { + & icacls $p /grant "*${BU}:(OI)(CI)M" /C /Q | Out-Null + if ($LASTEXITCODE -ne 0) { Say "데이터 폴더 권한 실패: $p"; exit 13 } + } + } + # 관리자 권한으로 실행되거나 읽히는 것: 루트 파일, scripts\ app\ apo\ launcher\ uninstall\ 아래 전부 + $items = @(Get-Item -LiteralPath $App -Force) + @(Get-ChildItem -LiteralPath $App -Force -File) + foreach ($d in 'scripts', 'app', 'apo', 'launcher', 'uninstall') { + $p = Join-Path $App $d + if (Test-Path -LiteralPath $p) { $items += Get-Item -LiteralPath $p -Force; $items += @(Get-ChildItem -LiteralPath $p -Recurse -Force) } + } + foreach ($it in $items) { + if (Is-Link $it.FullName) { Say "링크: $($it.FullName)"; exit 13 } + $acl = Get-Acl -LiteralPath $it.FullName + $o = $acl.GetOwner($Sid).Value + $w = @($acl.GetAccessRules($true, $true, $Sid) | ? { $_.AccessControlType -eq 'Allow' -and + $_.IdentityReference.Value -notin @($SY, $BA, $TI) -and ([int]$_.FileSystemRights -band $WriteBits) }) + if ($o -notin @($BA, $SY) -or $w.Count -gt 0) { Say "확인 실패: $($it.FullName) owner=$o 쓰기권한=$($w.Count)"; exit 13 } + } + Say "확인 완료: $($items.Count)개" + exit 0 +} +throw "알 수 없는 Mode: $Mode" diff --git a/voice-changer/scripts/mic-apo.ps1 b/voice-changer/scripts/mic-apo.ps1 index 6cbf78b..3e6c67d 100644 --- a/voice-changer/scripts/mic-apo.ps1 +++ b/voice-changer/scripts/mic-apo.ps1 @@ -14,6 +14,7 @@ $Dll = Join-Path $Root 'apo\VoiceChangerAPO.dll' $Config = Join-Path $Root 'apo' $BackupFile = Join-Path $Config 'mic-apo-backup.json' $ListFile = Join-Path $Config 'mic-apo.json' # 앱이 읽는 "모듈을 붙인 마이크" 목록 +$OldListFile = Join-Path $Root 'config\mic-apo.json' # 이전 버전(21b4278)의 목록 위치 (설치 · 제거 때 지움) # 실행 기록은 관리자만 쓸 수 있는 apo\mic-apo.log 에 남긴다 (앱이 실패 이유를 보여 줄 때 읽음) $LogFile = Join-Path $Config 'mic-apo.log' function Write-RunLog($m) { try { Add-Content -Path $LogFile -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $m" -Encoding UTF8 } catch {} } @@ -104,18 +105,84 @@ function Set-Val($key, [string]$name, $v) { $key.SetValue($name, $data, [Microsoft.Win32.RegistryValueKind]$v.kind) } +# 백업 값 검증. 이전 버전 백업(config\, 일반 사용자 쓰기 폴더)은 그대로 믿지 않는다. +# 허용: null, CLSID 문자열, CLSID 목록, 알려진 처리 모드 GUID 목록, DISABLE_SYSFX(0/1). 이 APO 자신의 CLSID 는 "원래 값" 에서 뺀다. +$GuidRe = '^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$' +$KNOWN_MODES = $CAPTURE_MODES + @( + '{9E90EA20-B493-4FD1-A1A8-7E1361A956CF}', # RAW + '{B26FEB0D-EC94-477C-9494-D1AB8E753F6E}', # MOVIE + '{9CF2A70B-F377-403B-BD6B-360863E0355C}' # NOTIFICATION +) +function Clean-Val([string]$field, $v) { + if ($null -eq $v) { return @{ ok = $true; v = $null } } + $kind = [string]$v.kind; $data = $v.data + switch ($field) { + 'sfx' { + if ($kind -ne 'String' -or [string]$data -notmatch $GuidRe) { break } + if ([string]$data -eq $Clsid) { return @{ ok = $true; v = $null } } + return @{ ok = $true; v = @{ kind = 'String'; data = [string]$data } } + } + 'sfx_composite' { + $list = @($data | ForEach-Object { [string]$_ }) + if ($kind -ne 'MultiString' -or @($list | Where-Object { $_ -notmatch $GuidRe }).Count) { break } + $list = @($list | Where-Object { $_ -ne $Clsid }) + if ($list.Count -eq 0) { return @{ ok = $true; v = $null } } + return @{ ok = $true; v = @{ kind = 'MultiString'; data = [string[]]$list } } + } + 'sfx_modes' { + $list = @($data | ForEach-Object { [string]$_ }) + if ($kind -ne 'MultiString' -or $list.Count -eq 0 -or @($list | Where-Object { $KNOWN_MODES -notcontains $_ }).Count) { break } + return @{ ok = $true; v = @{ kind = 'MultiString'; data = [string[]]$list } } + } + 'disable_sysfx' { + if ($kind -ne 'DWord' -or ($data -ne 0 -and $data -ne 1)) { break } + return @{ ok = $true; v = @{ kind = 'DWord'; data = [int]$data } } + } + } + return @{ ok = $false; v = $null } +} + +# 지금 레지스트리 값을 "원래 값" 으로 남길 때. 이전 설치가 넣은 이 APO 흔적은 뺀다. +function Current-Original([string]$sub) { + $fx = $HKLM.OpenSubKey("$sub\FxProperties") + $e = @{} + foreach ($f in @(@('sfx', $SFX), @('sfx_composite', $SFX_COMPOSITE), @('sfx_modes', $SFX_MODES), @('disable_sysfx', $DISABLE_SYSFX))) { + $r = Clean-Val $f[0] (Get-Val $fx $f[1]) + $e[$f[0]] = $r.v + } + $cur = Get-Val $fx $SFX + $modes = Get-Val $fx $SFX_MODES + # SFX 가 이 APO 이고 모드가 기본 하나뿐이면 이전 버전이 만든 목록이다 + if ($cur -and $cur.data -eq $Clsid -and $modes -and @($modes.data).Count -eq 1 -and @($modes.data)[0] -eq $CAPTURE_MODES[0]) { $e.sfx_modes = $null } + return $e +} + function Load-Backup { $b = @{} - if (Test-Path $BackupFile) { - $j = Get-Content $BackupFile -Raw -Encoding UTF8 | ConvertFrom-Json - foreach ($p in $j.PSObject.Properties) { - $e = @{} - foreach ($q in $p.Value.PSObject.Properties) { - $e[$q.Name] = if ($null -eq $q.Value) { $null } else { @{ kind = $q.Value.kind; data = $q.Value.data } } + $src = $BackupFile + $old = Join-Path $Root 'config\mic-apo-backup.json' # 이전 버전(21b4278)의 위치 + if (-not (Test-Path $src) -and (Test-Path $old)) { $src = $old; Log "이전 백업을 옮김: $old" } + if (Test-Path $src) { + try { $j = Get-Content $src -Raw -Encoding UTF8 | ConvertFrom-Json } catch { $j = $null; Log "백업을 읽지 못함: $src" } + if ($j) { + foreach ($p in $j.PSObject.Properties) { + if ($p.Name -notmatch $GuidRe -or -not $HKLM.OpenSubKey("$Capture\$($p.Name)")) { Log "백업 항목 무시: $($p.Name)"; continue } + $fallback = Current-Original "$Capture\$($p.Name)" + $e = @{} + foreach ($f in 'sfx', 'sfx_composite', 'sfx_modes', 'disable_sysfx') { + $raw = $p.Value.$f + $in = if ($null -eq $raw) { $null } else { @{ kind = $raw.kind; data = $raw.data } } + $r = Clean-Val $f $in + if ($r.ok) { $e[$f] = $r.v } else { $e[$f] = $fallback[$f]; Log "백업 값 거부($f): $($p.Name)" } + } + $b[$p.Name] = $e } - $b[$p.Name] = $e } } + if ($src -eq $old) { + Save-Backup $b + Remove-Item -Force $old -ErrorAction SilentlyContinue + } return $b } @@ -167,12 +234,7 @@ function Install-Apo { $sub = "$Capture\$($ep.guid)" try { if (-not $bk.ContainsKey($ep.guid)) { # 처음 붙일 때의 값만 남긴다 (다시 실행해도 덮어쓰지 않음) - $bk[$ep.guid] = @{ - sfx = Get-Val $HKLM.OpenSubKey("$sub\FxProperties") $SFX - sfx_composite = Get-Val $HKLM.OpenSubKey("$sub\FxProperties") $SFX_COMPOSITE - sfx_modes = Get-Val $HKLM.OpenSubKey("$sub\FxProperties") $SFX_MODES - disable_sysfx = Get-Val $HKLM.OpenSubKey("$sub\FxProperties") $DISABLE_SYSFX - } + $bk[$ep.guid] = Current-Original $sub Save-Backup $bk } if (-not $HKLM.OpenSubKey("$sub\FxProperties")) { New-FxKey $sub } @@ -188,8 +250,13 @@ function Install-Apo { } else { $fx.SetValue($SFX, $Clsid, 'String') } - # 드라이버가 이미 모드 목록을 갖고 있으면 그대로 둔다 (드라이버 효과가 지원하지 않는 모드를 억지로 켜지 않게) - if (-not ($fx.GetValueNames() -contains $SFX_MODES)) { $fx.SetValue($SFX_MODES, [string[]]$CAPTURE_MODES, 'MultiString') } + # 드라이버가 원래 갖고 있던 모드 목록은 그대로 둔다 (드라이버 효과가 지원하지 않는 모드를 억지로 켜지 않게). + # 원래 목록이 없었으면(백업이 null) 이 앱이 만든 목록이므로 통화 · 음성 · 미디어 모드까지 넣는다. + # 이전 버전이 넣은 "기본 모드 하나" 목록도 여기서 갱신된다. + $modes = Get-Val $fx $SFX_MODES + if ($null -eq $bk[$ep.guid].sfx_modes -and (-not $modes -or (Compare-Object @($modes.data) $CAPTURE_MODES))) { + $fx.SetValue($SFX_MODES, [string[]]$CAPTURE_MODES, 'MultiString') + } # 사용자가 "오디오 향상" 을 꺼 두면 APO 가 통째로 빠지므로 켠다 (해제할 때 되돌림) if ($fx.GetValueNames() -contains $DISABLE_SYSFX) { $fx.DeleteValue($DISABLE_SYSFX) } $fx.Close() @@ -201,6 +268,7 @@ function Install-Apo { } New-Item -ItemType Directory -Force $Config | Out-Null ConvertTo-Json -InputObject @($done) -Depth 3 | Set-Content $ListFile -Encoding UTF8 + Remove-Item -Force $OldListFile -ErrorAction SilentlyContinue Restart-Audio if ($done.Count -eq 0) { throw '마이크를 하나도 연결하지 못했습니다' } } @@ -225,7 +293,7 @@ function Uninstall-Apo { foreach ($sub in @("SOFTWARE\Classes\AudioEngine\AudioProcessingObjects\$Clsid", "SOFTWARE\Classes\CLSID\$Clsid")) { if ($HKLM.OpenSubKey($sub)) { $HKLM.DeleteSubKeyTree($sub) } } - Remove-Item -Force $BackupFile, $ListFile -ErrorAction SilentlyContinue + Remove-Item -Force $BackupFile, $ListFile, $OldListFile -ErrorAction SilentlyContinue Restart-Audio }