From c24cd1f9c0bc4cf4b2ad3efc5f554865645bda28 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Wed, 11 Nov 2026 22:09:39 +0900 Subject: [PATCH] voice-changer: allow installing under user-owned folders (Desktop); move admin-run parts to Program Files The installer refused folders whose parent is user-owned (Desktop, Documents) because a user could swap the whole install folder and get the elevated/audiodg-run parts replaced. Instead of refusing, the parts that run with admin rights or inside audiodg now live in {commonpf}\VoiceChanger, which only admins can change; the chosen folder keeps the app, Python, engine, models and data. - VoiceChanger.iss: SysDir = {commonpf}\VoiceChanger holds apo\ (VoiceChangerAPO.dll), scripts\mic-apo.ps1 and the uninstaller (UninstallFilesDir). CheckParent removed. Upgrade detection also matches the previous install dir from the uninstall registry (PrevAppDir) since uninstall\ is no longer inside the app folder. Stop the audio service when either the new or the v1.0.1-layout APO exists. Ask before installing into a OneDrive-synced folder. - secure-dir.ps1: drop CheckParent; Prepare takes -Upgrade. - mic-apo.ps1: -From migrates a v1.0.1 apo\ or 21b4278 config\ backup (validated as before) into the Program Files apo\, removing the emptied old apo\. - app: admin_root() finds Program Files\VoiceChanger (falls back to the app folder for the zip layout); hooked-mic list, mic-apo log and the reconnect button use it. Windows 11 VM (Inno 6.7.4 build, AppVersion 1.0.2): v1.0.1 at C:\VoiceChanger -> upgrade: backup moved byte-equal, APO re-pointed to Program Files, old apo\ scripts\mic-apo.ps1 uninstall\ gone; fresh install to C:\Users\ci\Desktop\VoiceChanger (owner WIN-CI\ci) with full engine download: exit 0, audiodg loads C:\Program Files\VoiceChanger\apo\VoiceChangerAPO.dll, 440 Hz APO test + Communications stream PASS; basic-user token can rename the Desktop folder but every Program Files write/rename is ERROR_ACCESS_DENIED; reinstall over the same folder keeps user files; uninstall restores FxProperties (only the endpoint timestamp properties differ, same as v1.0.1) and removes both folders. Co-Authored-By: Claude Opus 5.5 --- voice-changer/README.md | 14 +-- voice-changer/app/common.py | 9 ++ voice-changer/app/voice_changer.py | 10 +-- voice-changer/installer/VoiceChanger.iss | 103 ++++++++++++++++++----- voice-changer/installer/secure-dir.ps1 | 23 ++--- voice-changer/scripts/mic-apo.ps1 | 30 ++++--- voice-changer/tests/test_admin_root.py | 27 ++++++ 7 files changed, 156 insertions(+), 60 deletions(-) create mode 100644 voice-changer/tests/test_admin_root.py diff --git a/voice-changer/README.md b/voice-changer/README.md index 94bf563..922af24 100644 --- a/voice-changer/README.md +++ b/voice-changer/README.md @@ -12,7 +12,7 @@ 1. `VoiceChangerSetup.exe` 를 실행합니다 (관리자 권한 확인 창이 뜹니다). 2. **설치할 폴더**를 고릅니다. 기본값은 `C:\VoiceChanger` 이고, 다른 드라이브(`D:\...`)나 한글 · 띄어쓰기가 들어간 경로도 됩니다. - 비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). 상위 폴더가 일반 사용자 소유인 곳(예: 바탕 화면 · 문서 아래)도 거절합니다. + 비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). 바탕 화면 · 문서 아래(예: `바탕 화면\VoiceChanger`)도 됩니다. OneDrive 로 동기화되는 폴더를 고르면 한 번 더 묻습니다. Python · 엔진 · torch · 목소리 모델 · 설정 · 학습 파일 · 캐시 · 임시 파일이 **모두 이 폴더 안에만** 저장됩니다. 설치하면서 약 8GB 를 내려받고 모델을 만들수록 늘어나므로 15GB 이상 비어 있는 드라이브를 고르세요. 3. 설치 프로그램이 마이크마다 변환 모듈을 붙이고(윈도우 소리가 1~2초 끊김), 검은 창에서 Python 3.12 · 엔진(Applio) · @@ -24,7 +24,7 @@ 디스코드 · 게임의 입력 장치는 **평소 쓰던 마이크 그대로** 두면 됩니다. - 내려받다가 끊기면 설치 폴더의 `install.bat` 을 실행합니다. 받은 곳부터 이어서 받습니다. -- 권한: 설치 프로그램이 설치 폴더의 소유자를 Administrators 로 바꾸고 잠근 뒤 확인합니다(`installer\secure-dir.ps1`, 실패하면 설치 중단). 설치 폴더와 실행 파일 · `app\` · `scripts\` · `apo\` · `uninstall\` 은 관리자만 고칠 수 있습니다. 일반 사용자는 `models` · `training` · `datasets` · `config` · `cache` · `env` · `engine` · `tools` 에만 씁니다. 엔진 내려받기(`install.ps1`)는 관리자 권한 없이 돕니다. +- 권한: 관리자 권한 · 오디오 서비스가 실행하는 마이크 모듈(`apo\`) · `mic-apo.ps1` · 제거 프로그램은 고른 폴더가 아니라 `C:\Program Files\VoiceChanger` 에 설치합니다 (고른 폴더의 상위가 사용자 소유여도 폴더를 바꿔쳐 관리자 권한을 얻지 못하게). 설치 프로그램은 고른 폴더의 소유자도 Administrators 로 바꾸고 잠근 뒤 확인합니다(`installer\secure-dir.ps1`, 실패하면 설치 중단). 설치 폴더와 실행 파일 · `app\` · `scripts\` 는 관리자만 고칠 수 있습니다. 일반 사용자는 `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`, 이전 버전의 `config\mic-apo-backup.json` 은 값을 검증한 뒤 옮김). +설치 프로그램이 `C:\Program Files\VoiceChanger\apo\VoiceChangerAPO.dll` 을 각 마이크의 처리 단계에 붙입니다 (`scripts\mic-apo.ps1`, 바꾼 값의 원래 값은 같은 곳의 `apo\mic-apo-backup.json`, 이전 버전이 앱 폴더의 `apo\` · `config\` 에 둔 백업은 값을 검증한 뒤 옮김). 통화 앱(디스코드 등)이 여는 통화(Communications) 모드 스트림에도 붙도록 기본 · 통화 · 음성 · 미디어 모드로 등록합니다. 드라이버가 이미 모드 목록을 갖고 있으면 그 목록을 그대로 둡니다. - 변환기가 꺼져 있으면 아무것도 하지 않습니다. 원래 목소리가 그대로 나갑니다 @@ -109,15 +109,17 @@ install.bat 엔진 내려받기 · 이어 받기 (scripts\install.ps1, train.bat 학습 (app\train.py) examples.bat 예시 모델 (app\examples.py) app\ 화면 · 학습 · 모델 목록 · 마이크 모듈 연결(mic_bridge.py) · 녹음 서버(record_servers.py) 코드 -apo\ 마이크 모듈 VoiceChangerAPO.dll 과 소스 (vcapo.cpp, 주고받는 규약 vccore.h) -scripts\mic-apo.ps1 마이크 모듈 붙이기 · 떼기 (관리자) +apo\ 마이크 모듈 VoiceChangerAPO.dll 과 소스 (vcapo.cpp, 주고받는 규약 vccore.h) * +scripts\mic-apo.ps1 마이크 모듈 붙이기 · 떼기 (관리자) * models\<아이디>\ model.pth · model.index · info.json(이름 · 성별 · 출처 · 라이선스) config\ 설정 · 마이크 모듈 백업 cache\ 임시 파일 · torch · huggingface · matplotlib 등 라이브러리 캐시 (지워도 됨) engine\ env\ tools\ 설치하면 생기는 폴더 (엔진 · Python · uv) -uninstall\ 제거 프로그램 +uninstall\ 제거 프로그램 * ``` +`*` 표시는 설치 프로그램으로 설치하면 고른 폴더가 아니라 `C:\Program Files\VoiceChanger` 에 들어갑니다 (zip 으로 풀어 쓰면 같은 폴더). + ## 배포 파일 만들기 ```bash diff --git a/voice-changer/app/common.py b/voice-changer/app/common.py index d4b6833..9aed3b8 100644 --- a/voice-changer/app/common.py +++ b/voice-changer/app/common.py @@ -15,6 +15,15 @@ SETTINGS = CONFIG / "settings.json" CACHE = ROOT / "cache" +def admin_root() -> Path: + """마이크 모듈(apo\\)과 그것을 붙이는 scripts\\mic-apo.ps1 이 있는 폴더. 관리자 권한으로 실행되는 부분이라 + 설치 프로그램은 앱 폴더가 아니라 Program Files\\VoiceChanger 에 둔다. 그곳에 없으면(zip 으로 푼 경우) 앱 폴더.""" + pf = os.environ.get("ProgramW6432") or os.environ.get("ProgramFiles") + if pf and (Path(pf) / "VoiceChanger" / "scripts" / "mic-apo.ps1").is_file(): + return Path(pf) / "VoiceChanger" + return ROOT + + def keep_files_in_root(): """라이브러리가 사용자 폴더(%TEMP% · %USERPROFILE%\\.cache · %APPDATA%)에 쓰는 캐시와 임시 파일을 모두 설치 폴더 안 cache\\ 로 돌린다. 다른 import 보다 먼저 돌아야 해서 이 모듈을 불러올 때 바로 한다.""" diff --git a/voice-changer/app/voice_changer.py b/voice-changer/app/voice_changer.py index 9fe152f..f2e838e 100644 --- a/voice-changer/app/voice_changer.py +++ b/voice-changer/app/voice_changer.py @@ -13,7 +13,7 @@ import time import tkinter as tk from tkinter import messagebox, ttk -from common import ROOT, SETTINGS, load_json, save_json, use_engine +from common import SETTINGS, admin_root, load_json, save_json, use_engine from models import GENDERS, auto_pitch, list_models from record_servers import ServerDialog @@ -34,7 +34,7 @@ def list_devices(): def hooked_mics() -> list: """설치할 때 마이크 모듈을 붙인 마이크들 (scripts/mic-apo.ps1 이 apo\\ 에 남긴 목록).""" try: - items = json.loads((ROOT / "apo" / "mic-apo.json").read_text(encoding="utf-8-sig")) + items = json.loads((admin_root() / "apo" / "mic-apo.json").read_text(encoding="utf-8-sig")) except (OSError, ValueError): return [] items = items if isinstance(items, list) else [items] @@ -47,7 +47,7 @@ def is_hooked(name: str, hooked: list) -> bool: def reconnect_params(root=None) -> str: """관리자 PowerShell 에 넘길 인자. Windows 경로에는 " 가 들어갈 수 없어서 큰따옴표로만 감싸면 공백 · 한글 경로도 안전하다.""" - root = ROOT if root is None else root + root = admin_root() if root is None else root script, r = str(root / "scripts" / "mic-apo.ps1"), str(root) if r.endswith("\\"): # "D:\" 처럼 \ 로 끝나면 닫는 따옴표가 이스케이프되므로 "D:\." 로 r += "." @@ -57,7 +57,7 @@ def reconnect_params(root=None) -> str: def mic_apo_log_tail(lines: int = 8) -> str: """scripts/mic-apo.ps1 이 apo\\mic-apo.log 에 남긴 마지막 기록.""" try: - text = (ROOT / "apo" / "mic-apo.log").read_text(encoding="utf-8-sig", errors="replace") + text = (admin_root() / "apo" / "mic-apo.log").read_text(encoding="utf-8-sig", errors="replace") except OSError: return "(기록 없음)" return "\n".join(text.strip().splitlines()[-lines:]) @@ -83,7 +83,7 @@ def reconnect_mics() -> int: k32.CloseHandle.argtypes = [wintypes.HANDLE] sei = SHELLEXECUTEINFOW(cbSize=ctypes.sizeof(SHELLEXECUTEINFOW), fMask=0x40, # SEE_MASK_NOCLOSEPROCESS lpVerb="runas", lpFile="powershell.exe", lpParameters=reconnect_params(), - lpDirectory=str(ROOT), nShow=0) + lpDirectory=str(admin_root()), nShow=0) if not shell32.ShellExecuteExW(ctypes.byref(sei)): return -ctypes.get_last_error() try: diff --git a/voice-changer/installer/VoiceChanger.iss b/voice-changer/installer/VoiceChanger.iss index 0f2aafd..56c2096 100644 --- a/voice-changer/installer/VoiceChanger.iss +++ b/voice-changer/installer/VoiceChanger.iss @@ -2,7 +2,10 @@ ; ISCC.exe installer\VoiceChanger.iss → dist\VoiceChangerSetup.exe ; 하는 일 ; 1. 설치할 폴더를 고르게 한다. Python · 엔진 · 모델 · 설정 · 캐시 · 임시 파일이 모두 그 폴더 안에만 생긴다 -; 2. 그 폴더에 앱 파일을 풀고, 마이크마다 변환 모듈(APO)을 붙인다 (가상 오디오 장치 설치 없음) +; (바탕 화면처럼 일반 사용자 폴더 아래도 됨) +; 2. 그 폴더에 앱 파일을 풀고, 마이크마다 변환 모듈(APO)을 붙인다 (가상 오디오 장치 설치 없음). +; 관리자 권한 · 오디오 서비스가 실행하는 부분(APO · mic-apo.ps1 · 제거 프로그램)은 고른 폴더가 아니라 +; Program Files\VoiceChanger 에 둔다. 고른 폴더의 상위가 사용자 소유면 그 사용자가 폴더를 통째로 바꿔칠 수 있기 때문 ; 3. Python · 엔진 · torch(CUDA) · 엔진 기본 모델을 그 폴더 안으로 내려받는다 (scripts\install.ps1, 10~20분) ; 제거할 때는 마이크 설정을 원래대로 되돌리고, 모델 · 녹음까지 지울지 묻는다. @@ -10,6 +13,8 @@ #ifndef AppVersion #define AppVersion "1.0.0" #endif +; 관리자 권한 · 오디오 서비스(audiodg)가 실행하는 부분. Program Files 아래라 관리자만 고칠 수 있다 +#define SysDir "{commonpf}\VoiceChanger" [Setup] AppId={{8C3F2A51-6D0B-4E7A-9F3C-2B5E1D7A4C90} @@ -30,7 +35,7 @@ OutputBaseFilename=VoiceChangerSetup Compression=lzma2 SolidCompression=yes WizardStyle=modern -UninstallFilesDir={app}\uninstall +UninstallFilesDir={#SysDir}\uninstall UninstallDisplayIcon={app}\VoiceChanger.exe UninstallDisplayName={#AppName} @@ -46,7 +51,9 @@ Name: "desktopicon"; Description: "바탕 화면에 바로 가기 만들기"; Fl [Files] Source: "secure-dir.ps1"; Flags: dontcopy -Source: "..\dist\payload\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion +Source: "..\dist\payload\*"; DestDir: "{app}"; Excludes: "\apo,\apo\*,\scripts\mic-apo.ps1"; Flags: recursesubdirs createallsubdirs ignoreversion +Source: "..\dist\payload\apo\*"; DestDir: "{#SysDir}\apo"; Flags: ignoreversion +Source: "..\dist\payload\scripts\mic-apo.ps1"; DestDir: "{#SysDir}\scripts"; Flags: ignoreversion [Icons] Name: "{autoprograms}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir: "{app}" @@ -56,17 +63,18 @@ Name: "{autodesktop}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir Filename: "{app}\VoiceChanger.exe"; Description: "음성 변환기 실행"; Flags: postinstall nowait skipifsilent unchecked [UninstallRun] -Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{app}\scripts\mic-apo.ps1"" -Uninstall -Root ""{app}"""; Flags: runhidden waituntilterminated; RunOnceId: "MicApoUninstall" +Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{#SysDir}\scripts\mic-apo.ps1"" -Uninstall -Root ""{#SysDir}"""; Flags: runhidden waituntilterminated; RunOnceId: "MicApoUninstall" [Code] { 설치 폴더 보안은 secure-dir.ps1 (설치 프로그램에 들어 있고 임시 폴더에 풀어서 관리자 권한으로 실행)이 맡는다. - 관리자 권한으로 실행되는 것(설치 폴더 루트의 exe, app\, scripts\, apo\, uninstall\)은 관리자만 고칠 수 있고, - 일반 사용자는 데이터 폴더(models · training · datasets · config · cache · env · engine · tools)에만 쓴다. } -function SecureDir(const Mode, Dir: String): Integer; + 설치 폴더의 실행 파일 · app\ · scripts\ 는 관리자만 고칠 수 있고, + 일반 사용자는 데이터 폴더(models · training · datasets · config · cache · env · engine · tools)에만 쓴다. + 관리자 권한으로 실행되는 APO · mic-apo.ps1 · 제거 프로그램은 Program Files 쪽(SysDir)에 있다. } +function SecureDir(const Mode, Dir, Extra: 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 + '"', + '-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{tmp}\secure-dir.ps1') + '" -Mode ' + Mode + ' -App "' + Dir + '"' + Extra, '', SW_HIDE, ewWaitUntilTerminated, Result) then Result := -1; Log('secure-dir ' + Mode + ' exit=' + IntToStr(Result)); @@ -97,6 +105,48 @@ begin end; end; +{ 이 앱을 이미 설치한 폴더인지. v1.0.1 까지는 제거 프로그램이 설치 폴더 안(uninstall\)에 있었고, + 지금은 Program Files 쪽에 있으므로 이전 설치 위치(관리자만 쓰는 제거 정보 레지스트리, PrevAppDir)와도 비교한다. } +function IsOurInstall(const Dir: String): Boolean; +begin + Result := FileExists(AddBackslash(Dir) + 'uninstall\unins000.exe') or + ((WizardForm.PrevAppDir <> '') and DirExists(Dir) and + (CompareText(RemoveBackslashUnlessRoot(WizardForm.PrevAppDir), RemoveBackslashUnlessRoot(Dir)) = 0)); +end; + +{ 마이크 백업을 옮겨 올 이전 설치 폴더. 명령줄에서 "D:\" 처럼 \ 로 끝나면 닫는 따옴표가 이스케이프되므로 "D:\." 로 } +function PrevRoot: String; +begin + Result := RemoveBackslashUnlessRoot(WizardForm.PrevAppDir); + if Result = '' then + Result := RemoveBackslashUnlessRoot(ExpandConstant('{app}')); + if Copy(Result, Length(Result), 1) = '\' then + Result := Result + '.'; +end; + +{ OneDrive 로 동기화되는 폴더(바탕 화면이 OneDrive 로 옮겨진 PC 가 많음)인지 } +function InOneDrive(const Dir: String): Boolean; +var + I: Integer; + OD: String; +begin + Result := False; + for I := 0 to 2 do + begin + case I of + 0: OD := GetEnv('OneDrive'); + 1: OD := GetEnv('OneDriveConsumer'); + else + OD := GetEnv('OneDriveCommercial'); + end; + if (OD <> '') and (Pos(Lowercase(AddBackslash(OD)), Lowercase(AddBackslash(Dir))) = 1) then + begin + Result := True; + Exit; + end; + end; +end; + { 다른 파일이 들어 있는 폴더에는 설치하지 않는다. 설치 폴더의 권한을 잠그고, 제거할 때 지우기 때문. 이 앱을 이미 설치한 폴더(업데이트)나 비어 있는 · 새 폴더만 받는다. } function NextButtonClick(CurPageID: Integer): Boolean; @@ -106,41 +156,47 @@ begin Result := True; if CurPageID <> wpSelectDir then Exit; Dir := WizardDirValue; - if DirExists(Dir) and not IsEmptyDir(Dir) and not FileExists(AddBackslash(Dir) + 'uninstall\unins000.exe') then + if DirExists(Dir) and not IsEmptyDir(Dir) and not IsOurInstall(Dir) then begin SuppressibleMsgBox('이 폴더에는 이미 다른 파일이 있습니다.' + #13#10 + '비어 있는 폴더나 새 폴더를 골라 주세요. (예: ' + AddBackslash(Dir) + 'VoiceChanger)', mbError, MB_OK, IDOK); Result := False; Exit; end; - { 상위 폴더가 일반 사용자 소유면 그 사용자가 설치 폴더를 통째로 다른 것으로 바꿔칠 수 있다 } - if SecureDir('CheckParent', Dir) <> 0 then - begin - SuppressibleMsgBox('이 위치의 상위 폴더는 관리자 소유가 아니라서 설치할 수 없습니다.' + #13#10 + - '드라이브 바로 아래(예: C:\VoiceChanger, D:\VoiceChanger)나 Program Files 처럼 관리자가 관리하는 곳을 골라 주세요.', mbError, MB_OK, IDOK); + if InOneDrive(Dir) and (SuppressibleMsgBox('이 폴더는 OneDrive 로 동기화됩니다.' + #13#10 + + '설치하면서 받는 8GB 이상(Python · 엔진 · 모델)이 OneDrive 에 올라가고, OneDrive 가 공간 확보로 파일을 내리면 음성 변환기가 실행되지 않을 수 있습니다.' + #13#10#13#10 + + '그래도 여기에 설치할까요? ("아니요" 를 누르고 C:\VoiceChanger 처럼 OneDrive 밖의 폴더를 고르는 것을 권합니다)', + mbConfirmation, MB_YESNO, IDYES) <> IDYES) then Result := False; - end; end; function PrepareToInstall(var NeedsRestart: Boolean): String; var Code: Integer; + ApoInUse: Boolean; + Extra: String; begin Result := ''; { 다시 설치(업데이트)할 때 오디오 엔진이 쥐고 있는 APO 파일을 바꿀 수 있게 잠깐 오디오 서비스를 멈춘다. 설치 뒤 mic-apo.ps1 이 다시 켠다. } - if FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then + { 이전 버전(v1.0.1 까지)은 APO 를 설치 폴더의 apo\ 에 두었다. secure-dir 이 그 파일을 지운다. } + ApoInUse := FileExists(ExpandConstant('{#SysDir}\apo\VoiceChangerAPO.dll')) or FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')); + if ApoInUse then Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Stop-Service -Name AudioEndpointBuilder -Force"', '', SW_HIDE, ewWaitUntilTerminated, Code); + if IsOurInstall(ExpandConstant('{app}')) then + Extra := ' -Upgrade' + else + Extra := ''; { 파일을 풀기 전에 설치 폴더를 관리자 소유로 잠근다. 실패하면 설치하지 않는다. } - case SecureDir('Prepare', ExpandConstant('{app}')) of + case SecureDir('Prepare', ExpandConstant('{app}'), Extra) of 0: ; 10: Result := '이 폴더에는 이미 다른 파일이 있습니다. 비어 있는 폴더나 새 폴더를 골라 주세요.'; 11: Result := '설치 폴더 안에 링크(정션 · 심볼릭 링크)가 있어 안전하게 설치할 수 없습니다. 링크를 지우거나 새 폴더를 골라 주세요.'; else Result := '설치 폴더의 권한을 잠그지 못했습니다. 다른 폴더를 골라 다시 설치해 주세요.'; end; - if (Result <> '') and FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then + if (Result <> '') and ApoInUse then Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code); end; @@ -151,7 +207,7 @@ begin if CurStep <> ssPostInstall then Exit; { 데이터 폴더에만 사용자 쓰기 권한을 주고, 관리자 권한으로 실행되는 파일이 잠겼는지 확인한다. 확인이 안 되면 관리자 권한으로 아무것도 실행하지 않는다. } - if SecureDir('Finish', ExpandConstant('{app}')) <> 0 then + 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 + @@ -160,7 +216,8 @@ begin 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 + if not PowerShell('-File "' + ExpandConstant('{#SysDir}\scripts\mic-apo.ps1') + '" -Install -Root "' + ExpandConstant('{#SysDir}') + + '" -From "' + PrevRoot + '"', SW_HIDE, Code) or (Code <> 0) then begin Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code); SuppressibleMsgBox('마이크에 변환 모듈을 붙이지 못했습니다. 설치가 끝난 뒤 음성 변환기의 "마이크 다시 연결" 을 눌러 주세요.', mbError, MB_OK, IDOK); @@ -203,7 +260,11 @@ begin RemoveDir(App + '\training'); RemoveDir(App + '\datasets'); RemoveDir(App + '\config'); - DeleteFile(App + '\apo\mic-apo.log'); RemoveDir(App + '\apo'); RemoveDir(App); + { Program Files 쪽: mic-apo.ps1 이 남긴 기록 } + DeleteFile(ExpandConstant('{#SysDir}\apo\mic-apo.log')); + RemoveDir(ExpandConstant('{#SysDir}\apo')); + RemoveDir(ExpandConstant('{#SysDir}\scripts')); + RemoveDir(ExpandConstant('{#SysDir}')); end; diff --git a/voice-changer/installer/secure-dir.ps1 b/voice-changer/installer/secure-dir.ps1 index 5cad33e..b806788 100644 --- a/voice-changer/installer/secure-dir.ps1 +++ b/voice-changer/installer/secure-dir.ps1 @@ -1,12 +1,12 @@ # 설치 폴더 보안 (설치 프로그램이 관리자 권한으로 {tmp} 에서 실행). 종료 코드로 결과를 알린다. -# -Mode CheckParent -App <폴더> 가장 가까운 상위 폴더가 드라이브 루트이거나 관리자 · SYSTEM · TrustedInstaller 소유인지 -# 0 = 괜찮음, 20 = 일반 사용자 소유 (그 사용자가 설치 폴더를 통째로 바꿔치기할 수 있음) -# -Mode Prepare -App <폴더> 파일을 풀기 전: 폴더를 만들고 소유자를 Administrators 로, 권한을 관리자 · SYSTEM 전체 + -# Users 읽기로 잠근다. 업데이트면 이전 버전이 사용자 쓰기 폴더에 두었던 실행 부분을 지운다. +# (상위 폴더는 일반 사용자 소유여도 된다. 관리자 권한으로 실행되는 APO · mic-apo.ps1 · 제거 프로그램은 설치 폴더가 아니라 +# Program Files\VoiceChanger 에 있어서, 사용자가 설치 폴더를 통째로 바꿔쳐도 관리자 권한을 얻지 못한다) +# -Mode Prepare -App <폴더> [-Upgrade] 파일을 풀기 전: 폴더를 만들고 소유자를 Administrators 로, 권한을 관리자 · SYSTEM 전체 + +# Users 읽기로 잠근다. 업데이트(-Upgrade 또는 v1.0.1 까지의 uninstall\ 이 있음)면 이전 버전이 사용자 쓰기 폴더에 두었던 실행 부분을 지운다. # 10 = 다른 파일이 있는 폴더, 11 = 링크(정션 · 심볼릭 링크)가 있음, 12 = 잠그지 못함 # -Mode Finish -App <폴더> 파일을 푼 뒤: 데이터 폴더에만 Users 수정 권한을 주고, 관리자 권한으로 실행되는 파일이 # 관리자 소유이고 일반 사용자가 쓸 수 없는지 확인한다. 13 = 확인 실패 -param([Parameter(Mandatory)][string]$Mode, [Parameter(Mandatory)][string]$App) +param([Parameter(Mandatory)][string]$Mode, [Parameter(Mandatory)][string]$App, [switch]$Upgrade) $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' @@ -46,20 +46,9 @@ function Find-Link([string]$dir) { 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') + $upgrade = $Upgrade -or (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 } diff --git a/voice-changer/scripts/mic-apo.ps1 b/voice-changer/scripts/mic-apo.ps1 index 3e6c67d..4b1b933 100644 --- a/voice-changer/scripts/mic-apo.ps1 +++ b/voice-changer/scripts/mic-apo.ps1 @@ -1,9 +1,11 @@ # 마이크 APO 등록 · 해제 (관리자 권한). 설치 프로그램과 앱의 "마이크 다시 연결" 버튼이 실행한다. -# mic-apo.ps1 -Install [-Root <설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작 -# mic-apo.ps1 -Uninstall [-Root <설치 폴더>] 원래 설정으로 되돌림 -# 바꾼 레지스트리 값의 원래 값은 <설치 폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다. +# mic-apo.ps1 -Install [-Root <폴더>] [-From <이전 설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작 +# mic-apo.ps1 -Uninstall [-Root <폴더>] 원래 설정으로 되돌림 +# <폴더> 는 apo\ 가 있는 곳이다. 설치 프로그램은 Program Files\VoiceChanger, zip 으로 풀어 쓰면 그 폴더. +# 바꾼 레지스트리 값의 원래 값은 <폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다. # apo\ 는 관리자만 쓸 수 있는 폴더다 (일반 사용자가 백업을 바꿔 관리자 권한으로 레지스트리를 쓰게 만들 수 없게). -param([switch]$Install, [switch]$Uninstall, [string]$Root) +# -From: 이전 버전이 백업을 둔 앱 폴더 (21b4278 은 config\, v1.0.1 까지는 앱 폴더의 apo\). 값을 검증한 뒤 옮긴다. +param([switch]$Install, [switch]$Uninstall, [string]$Root, [string]$From) $ErrorActionPreference = 'Stop' if (-not $Root) { $Root = Split-Path -Parent $PSScriptRoot } $Root = (Resolve-Path $Root).Path @@ -14,7 +16,8 @@ $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)의 목록 위치 (설치 · 제거 때 지움) +$OldDirs = @($Root) + @(if ($From -and (Test-Path -LiteralPath $From)) { (Resolve-Path -LiteralPath $From).Path }) +$OldListFiles = @($OldDirs | ForEach-Object { Join-Path $_ '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 {} } @@ -160,8 +163,11 @@ function Current-Original([string]$sub) { function Load-Backup { $b = @{} $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 (-not (Test-Path -LiteralPath $src)) { + $old = @(foreach ($d in $OldDirs) { Join-Path $d 'apo\mic-apo-backup.json'; Join-Path $d 'config\mic-apo-backup.json' }) | + Where-Object { $_ -ne $BackupFile -and (Test-Path -LiteralPath $_) } | Select-Object -First 1 + if ($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) { @@ -179,9 +185,11 @@ function Load-Backup { } } } - if ($src -eq $old) { + if ($src -ne $BackupFile) { Save-Backup $b - Remove-Item -Force $old -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $src -Force -ErrorAction SilentlyContinue + $d = Split-Path $src # v1.0.1 까지의 앱 폴더 apo\ 는 비었으면 지운다 + if ((Split-Path -Leaf $d) -eq 'apo' -and -not (Get-ChildItem -LiteralPath $d -Force)) { Remove-Item -LiteralPath $d -Force } } return $b } @@ -268,7 +276,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 + Remove-Item -Force $OldListFiles -ErrorAction SilentlyContinue Restart-Audio if ($done.Count -eq 0) { throw '마이크를 하나도 연결하지 못했습니다' } } @@ -293,7 +301,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, $OldListFile -ErrorAction SilentlyContinue + Remove-Item -Force (@($BackupFile, $ListFile) + $OldListFiles) -ErrorAction SilentlyContinue Restart-Audio } diff --git a/voice-changer/tests/test_admin_root.py b/voice-changer/tests/test_admin_root.py new file mode 100644 index 0000000..58a149b --- /dev/null +++ b/voice-changer/tests/test_admin_root.py @@ -0,0 +1,27 @@ +"""관리자 권한으로 도는 부분(apo\\ · mic-apo.ps1)을 설치 프로그램이 둔 Program Files\\VoiceChanger 에서 찾는지.""" +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "app")) +import common # noqa: E402 + + +class AdminRootTest(unittest.TestCase): + def test_installed_uses_program_files(self): + with tempfile.TemporaryDirectory() as pf: + (Path(pf) / "VoiceChanger" / "scripts").mkdir(parents=True) + (Path(pf) / "VoiceChanger" / "scripts" / "mic-apo.ps1").write_text("x") + with mock.patch.dict(os.environ, {"ProgramW6432": pf}): + self.assertEqual(common.admin_root(), Path(pf) / "VoiceChanger") + + def test_zip_layout_uses_app_folder(self): + with tempfile.TemporaryDirectory() as pf, mock.patch.dict(os.environ, {"ProgramW6432": pf}): + self.assertEqual(common.admin_root(), common.ROOT) + + +if __name__ == "__main__": + unittest.main()