2 Commits

Author SHA1 Message Date
EJClaw
85f5782876 voice-changer installer: never touch the chosen folder with admin rights (1.0.3)
Review of c24cd1f: with a user-owned parent (Desktop), the user could swap the chosen folder for a junction
to a protected folder after secure-dir Prepare, and the elevated Finish would grant Users modify on the
target's config\ etc. Any elevated path operation on a user-controlled path has this race, so the elevated
installer now only works in Program Files.

- VoiceChanger.iss: {app} is always {commonpf}\VoiceChanger (apo\, scripts\mic-apo.ps1, scripts\deploy.ps1,
  uninstall\, payload\). The user's folder comes from a custom page (/DATADIR=, previous DataDir, or the
  v1.0.x App Path) and is only read for checks. deploy.ps1 runs with ExecAsOriginalUser: copies payload,
  moves data folders of an older install, runs install.ps1. Shortcuts are created after the copy
  (CreateShellLink; [Icons] made empty-target links) and the postinstall launch runs as the original user.
  Uninstall restores the mic settings and removes Program Files only; the user's folder is left (message).
- legacy.ps1 (replaces secure-dir.ps1): for a v1.0.0/1.0.1 folder (admin-locked, uninstall\ inside) deletes the
  old executable parts by name, moves the mic backup to Program Files and renames the folder to <dir>.old,
  only if no non-admin principal can delete/rename the folder or any ancestor (owner + ACL check; ACLs can
  only be changed by admins, so the check stays valid during the operation). Otherwise refuses (exit 20).
- deploy.ps1 (user level): refuses a junction; a v1.0.2 admin-locked folder under a user-owned parent is
  renamed aside by the user and its data folders moved into a fresh folder.
- mic-apo.ps1: back to its pre-c24cd1f logic (no -From); header documents the Program Files root.

Windows 11 VM, Inno 6.7.4, AppVersion 1.0.3:
- J: chosen folder = junction to admin-owned C:\vctarget (config\keep.txt, protected ACL): setup exit 0,
  legacy exit 0, deploy exit 31; target files + SDDL unchanged after setup, after limited-token deploy
  (exit 31), after limited-token write/icacls/rename attempts (all denied), and after uninstall.
- J2: same target with uninstall\unins000.exe: legacy exit 20, setup aborted (exit 7), target unchanged.
- U1: v1.0.1 at C:\VoiceChanger -> 1.0.3 with the default folder: legacy exit 1, backup moved byte-equal,
  models\mine.txt kept, C:\VoiceChanger.old removed, APO from Program Files; uninstall restores FxProperties.
- U2: v1.0.2 on Desktop -> limited-token deploy renamed it aside, moved models, new folder owned by the user;
  1.0.3 setup on it exit 0; uninstall restores FxProperties, folder and models kept.
- D: fresh Desktop install with full engine download: deploy exit 0, admin_root = Program Files,
  audiodg loads the Program Files DLL, APO 440 Hz + Communications PASS, Start menu/desktop shortcuts point
  at <Desktop>\VoiceChanger\VoiceChanger.exe and are removed on uninstall.
- python unittest: 16 run, 2 skipped (tkinter missing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:51:52 +09:00
EJClaw
c24cd1f9c0 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 <previous app folder> 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 <noreply@anthropic.com>
2026-11-11 22:09:39 +09:00
9 changed files with 396 additions and 269 deletions

View File

@@ -12,8 +12,8 @@
1. `VoiceChangerSetup.exe` 를 실행합니다 (관리자 권한 확인 창이 뜹니다).
2. **설치할 폴더**를 고릅니다. 기본값은 `C:\VoiceChanger` 이고, 다른 드라이브(`D:\...`)나 한글 · 띄어쓰기가 들어간 경로도 됩니다.
비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). 상위 폴더가 일반 사용자 소유인 곳(예: 바탕 화면 · 문서 아래)도 거절합니다.
Python · 엔진 · torch · 목소리 모델 · 설정 · 학습 파일 · 캐시 · 임시 파일이 **모두 이 폴더 안에만** 저장됩니다.
비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). 바탕 화면 · 문서 아래(예: `바탕 화면\VoiceChanger`)도 됩니다. OneDrive 로 동기화되는 폴더를 고르면 한 번 더 묻습니다.
앱 · Python · 엔진 · torch · 목소리 모델 · 설정 · 학습 파일 · 캐시 · 임시 파일이 **모두 이 폴더 안에만** 저장됩니다.
설치하면서 약 8GB 를 내려받고 모델을 만들수록 늘어나므로 15GB 이상 비어 있는 드라이브를 고르세요.
3. 설치 프로그램이 마이크마다 변환 모듈을 붙이고(윈도우 소리가 1~2초 끊김), 검은 창에서 Python 3.12 · 엔진(Applio) ·
torch(CUDA 12.8) · 엔진 기본 모델(rmvpe · contentvec · 사전학습 가중치 · ffmpeg)을 그 폴더로 내려받습니다. 10~20분 걸립니다.
@@ -24,15 +24,18 @@
디스코드 · 게임의 입력 장치는 **평소 쓰던 마이크 그대로** 두면 됩니다.
- 내려받다가 끊기면 설치 폴더의 `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` 에 설치합니다 (관리자만 고칠 수 있음).
고른 폴더는 관리자 권한으로 건드리지 않습니다. 앱 파일 복사(`installer\deploy.ps1`)와 엔진 내려받기(`install.ps1`)는 설치를 시작한 사용자 권한으로 합니다.
바탕 화면처럼 상위가 사용자 소유인 폴더는 설치 도중 다른 곳을 가리키는 정션으로 바꿔칠 수 있어서, 관리자 권한으로 그 경로를 다루면 엉뚱한 곳이 바뀔 수 있기 때문입니다.
v1.0.1 까지 관리자 소유로 잠가 둔 설치 폴더는 설치 프로그램이 이전 실행 파일만 지우고 `<폴더>.old` 로 비켜 둔 뒤(`installer\legacy.ps1`, 상위가 관리자 소유일 때만) 모델 · 설정 · Python · 엔진을 새 폴더로 옮깁니다.
- 폴더 밖에 남는 것은 윈도우가 관리하는 항목뿐입니다: 시작 메뉴 바로 가기, 프로그램 제거 목록, 마이크 모듈 등록(레지스트리).
사용자 폴더(`%APPDATA%` · `%LOCALAPPDATA%` · `%TEMP%` · `.cache`)에는 아무것도 쓰지 않습니다.
- 제거: 설정 → 앱 → 음성 변환기 → 제거. 마이크 설정을 원래대로 되돌리고, 만든 모델 · 녹음 · 설정까지 지울지 묻습니다.
- 제거: 설정 → 앱 → 음성 변환기 → 제거. 마이크 설정을 원래대로 되돌리고 `C:\Program Files\VoiceChanger` 를 지웁니다. 고른 폴더(앱 · 모델 · 녹음 · 설정)는 남기므로 필요 없으면 직접 지웁니다 (내 계정 폴더라 관리자 권한 없이 지울 수 있음).
### 마이크 모듈은 어떻게 동작하나
윈도우는 마이크 소리를 앱에 넘기기 전에 오디오 처리 모듈(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`, v1.0.1 까지 고른 폴더의 `apo\` 에 있던 백업은 설치 프로그램이 이 자리로 옮기고 mic-apo.ps1 이 값을 검증).
통화 앱(디스코드 등)이 여는 통화(Communications) 모드 스트림에도 붙도록 기본 · 통화 · 음성 · 미디어 모드로 등록합니다. 드라이버가 이미 모드 목록을 갖고 있으면 그 목록을 그대로 둡니다.
- 변환기가 꺼져 있으면 아무것도 하지 않습니다. 원래 목소리가 그대로 나갑니다
@@ -109,15 +112,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

View File

@@ -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 보다 먼저 돌아야 해서 이 모듈을 불러올 때 바로 한다."""

View File

@@ -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:

View File

@@ -1,10 +1,14 @@
; 음성 변환기 설치 프로그램 (Inno Setup 6). 빌드: scripts/build-release.sh 가 만든 dist\payload 를 담는다.
; ISCC.exe installer\VoiceChanger.iss → dist\VoiceChangerSetup.exe
; 하는 일
; 1. 설치할 폴더를 고르게 한다. Python · 엔진 · 모델 · 설정 · 캐시 · 임시 파일이 모두 그 폴더 안에만 생긴다
; 2. 그 폴더에 앱 파일을 풀고, 마이크마다 변환 모듈(APO)을 붙인다 (가상 오디오 장치 설치 없음)
; 3. Python · 엔진 · torch(CUDA) · 엔진 기본 모델을 그 폴더 안으로 내려받는다 (scripts\install.ps1, 10~20분)
; 제거할 때는 마이크 설정을 원래대로 되돌리고, 모델 · 녹음까지 지울지 묻는다.
; 1. 설치할 폴더를 고르게 한다 (바탕 화면 · 문서 아래도 됨). 앱 · Python · 엔진 · 모델 · 설정 · 캐시가 모두 그 폴더에 생긴다.
; 2. 관리자 권한 · 오디오 서비스가 실행하는 부분(마이크 모듈 APO · mic-apo.ps1 · 제거 프로그램)은
; Program Files\VoiceChanger({app})에 두고, 마이크마다 APO 를 붙인다 (가상 오디오 장치 설치 없음).
; 3. 고른 폴더는 관리자 권한으로 건드리지 않는다. 앱 파일 복사와 Python · 엔진 · 기본 모델 내려받기는
; 설치를 시작한 사용자 권한으로 한다 (scripts\deploy.ps1 → install.ps1, 10~20분).
; 고른 폴더의 상위가 사용자 소유면 설치 중에 그 폴더를 다른 곳을 가리키는 정션으로 바꿔칠 수 있어서,
; 관리자 권한으로 그 경로에 쓰거나 권한을 바꾸면 엉뚱한 곳이 바뀔 수 있기 때문이다.
; 제거할 때는 마이크 설정을 원래대로 되돌리고 Program Files 쪽을 지운다. 고른 폴더는 남긴다 (사용자가 직접 지울 수 있음).
#define AppName "음성 변환기"
#ifndef AppVersion
@@ -16,11 +20,11 @@ AppId={{8C3F2A51-6D0B-4E7A-9F3C-2B5E1D7A4C90}
AppName={#AppName}
AppVersion={#AppVersion}
AppPublisher=voice_copy
DefaultDirName={sd}\VoiceChanger
DisableDirPage=no
; {app} 은 항상 Program Files\VoiceChanger. 사용자가 고르는 폴더는 아래 [Code] 의 DataPage
DefaultDirName={commonpf}\VoiceChanger
DisableDirPage=yes
UsePreviousAppDir=no
DisableProgramGroupPage=yes
DirExistsWarning=no
AllowUNCPath=no
PrivilegesRequired=admin
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
@@ -31,51 +35,94 @@ Compression=lzma2
SolidCompression=yes
WizardStyle=modern
UninstallFilesDir={app}\uninstall
UninstallDisplayIcon={app}\VoiceChanger.exe
UninstallDisplayIcon={app}\payload\VoiceChanger.exe
UninstallDisplayName={#AppName}
[Languages]
Name: "ko"; MessagesFile: "compiler:Languages\Korean.isl"
[Messages]
ko.SelectDirLabel3=음성 변환기를 설치할 폴더를 골라 주세요.%n%nPython · 변환 엔진 · 목소리 모델 · 설정 · 학습 파일 · 캐시가 모두 이 폴더 안에만 저장됩니다. 설치 중에 약 8GB 를 내려받고, 모델을 만들면 더 늘어나므로 15GB 이상 여유가 있는 드라이브를 골라 주세요.
ko.DiskSpaceMBLabel=설치 중에 약 8GB 를 더 내려받습니다. 15GB 이상 비어 있는 드라이브를 권합니다.
[Tasks]
Name: "desktopicon"; Description: "바탕 화면에 바로 가기 만들기"; Flags: unchecked
[Files]
Source: "secure-dir.ps1"; Flags: dontcopy
Source: "..\dist\payload\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion
Source: "legacy.ps1"; Flags: dontcopy
Source: "deploy.ps1"; DestDir: "{app}\scripts"; Flags: ignoreversion
Source: "..\dist\payload\apo\*"; DestDir: "{app}\apo"; Flags: ignoreversion
Source: "..\dist\payload\scripts\mic-apo.ps1"; DestDir: "{app}\scripts"; Flags: ignoreversion
; 고른 폴더에 사용자 권한으로 복사할 앱 파일
Source: "..\dist\payload\*"; DestDir: "{app}\payload"; Excludes: "\apo,\apo\*,\scripts\mic-apo.ps1"; Flags: recursesubdirs createallsubdirs ignoreversion
[Icons]
Name: "{autoprograms}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir: "{app}"
Name: "{autodesktop}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir: "{app}"; Tasks: desktopicon
; 바로 가기는 앱을 복사한 뒤 [Code] 에서 만든다 ([Icons] 는 대상 파일이 아직 없을 때 만들어져 대상이 빈 바로 가기가 됨)
[UninstallDelete]
Type: files; Name: "{autoprograms}\{#AppName}.lnk"
Type: files; Name: "{autodesktop}\{#AppName}.lnk"
[Run]
Filename: "{app}\VoiceChanger.exe"; Description: "음성 변환기 실행"; Flags: postinstall nowait skipifsilent unchecked
Filename: "{code:DataDir}\VoiceChanger.exe"; Description: "음성 변환기 실행"; Flags: postinstall nowait skipifsilent unchecked runasoriginaluser
[UninstallRun]
Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{app}\scripts\mic-apo.ps1"" -Uninstall -Root ""{app}"""; 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;
const
UninstKey = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{8C3F2A51-6D0B-4E7A-9F3C-2B5E1D7A4C90}_is1';
var
DataPage: TInputDirWizardPage;
LegacyOld: String;
UninstDataDir: String;
{ Program Files\VoiceChanger. 설치 폴더 상수와 같지만 그 상수는 InitializeWizard 때 아직 정해지지 않아서 따로 둔다 }
function SysDir: String;
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));
Result := ExpandConstant('{commonpf}\VoiceChanger');
end;
function PowerShell(const Args: String; const Show: Integer; var Code: Integer): Boolean;
function DataDir(Param: String): String;
begin
Result := Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
'-NoProfile -ExecutionPolicy Bypass ' + Args, ExpandConstant('{app}'), Show, ewWaitUntilTerminated, Code);
Result := RemoveBackslashUnlessRoot(DataPage.Values[0]);
end;
{ 명령줄 인자로 넘길 경로. "D:\" 처럼 \ 로 끝나면 닫는 따옴표가 이스케이프되므로 "D:\." 로 }
function ArgPath(const S: String): String;
begin
Result := S;
if Copy(Result, Length(Result), 1) = '\' then
Result := Result + '.';
end;
function PowerShellExe: String;
begin
Result := ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe');
end;
procedure InitializeWizard;
var
Def, Prev: String;
begin
DataPage := CreateInputDirPage(wpSelectDir, '설치할 폴더', '음성 변환기를 어디에 설치할까요?',
'앱 · Python · 변환 엔진 · 목소리 모델 · 설정 · 학습 파일 · 캐시가 모두 이 폴더에 저장됩니다. ' +
'바탕 화면이나 문서 아래도 됩니다. 설치 중에 약 8GB 를 내려받고, 모델을 만들면 더 늘어나므로 15GB 이상 여유가 있는 드라이브를 골라 주세요.',
False, 'VoiceChanger');
DataPage.Add('');
{ 기본값: /DATADIR=, 지난 설치에서 고른 폴더, v1.0.2 까지의 설치 폴더(제거 정보의 App Path), C:\VoiceChanger }
Def := ExpandConstant('{param:DATADIR|}');
if Def = '' then
Def := GetPreviousData('DataDir', '');
if (Def = '') and RegQueryStringValue(HKLM, UninstKey, 'Inno Setup: App Path', Prev) and
(CompareText(RemoveBackslashUnlessRoot(Prev), SysDir) <> 0) then
Def := Prev;
if Def = '' then
Def := ExpandConstant('{sd}\VoiceChanger');
DataPage.Values[0] := Def;
end;
procedure RegisterPreviousData(PreviousDataKey: Integer);
begin
SetPreviousData(PreviousDataKey, 'DataDir', DataDir(''));
end;
function IsEmptyDir(const Dir: String): Boolean;
@@ -97,113 +144,168 @@ begin
end;
end;
{ 다른 파일이 들어 있는 폴더에는 설치하지 않는다. 설치 폴더의 권한을 잠그고, 제거할 때 지우기 때문.
이 앱을 이미 설치한 폴더(업데이트)나 비어 있는 · 새 폴더만 받는다. }
function IsUnder(const Child, Parent: String): Boolean;
begin
Result := Pos(Lowercase(AddBackslash(Parent)), Lowercase(AddBackslash(Child))) = 1;
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 IsUnder(Dir, OD) then
begin
Result := True;
Exit;
end;
end;
end;
{ 고른 폴더 확인 (읽기만 함). 문제가 있으면 안내 문구 }
function CheckDataDir(const Dir: String): String;
begin
Result := '';
if (Length(Dir) < 3) or (Copy(Dir, 2, 2) <> ':\') then
Result := '드라이브 문자로 시작하는 폴더를 골라 주세요. (예: C:\VoiceChanger)'
else if IsUnder(Dir, SysDir) or IsUnder(SysDir, Dir) then
Result := SysDir + ' 은 설치 프로그램이 쓰는 곳입니다. 다른 폴더를 골라 주세요.'
{ 다른 파일이 든 폴더에는 설치하지 않는다 (예: 바탕 화면 자체). 이 앱이 이미 설치된 폴더(업데이트)는 된다 }
else if DirExists(Dir) and not IsEmptyDir(Dir) and not FileExists(AddBackslash(Dir) + 'VoiceChanger.exe') then
Result := '이 폴더에는 이미 다른 파일이 있습니다. 비어 있는 폴더나 새 폴더를 골라 주세요. (예: ' + AddBackslash(Dir) + 'VoiceChanger)';
end;
function NextButtonClick(CurPageID: Integer): Boolean;
var
Dir: String;
Msg: String;
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 CurPageID <> DataPage.ID then Exit;
Msg := CheckDataDir(DataDir(''));
if Msg <> '' then
begin
SuppressibleMsgBox('이 폴더에는 이미 다른 파일이 있습니다.' + #13#10 +
'비어 있는 폴더나 새 폴더를 골라 주세요. (예: ' + AddBackslash(Dir) + 'VoiceChanger)', mbError, MB_OK, IDOK);
SuppressibleMsgBox(Msg, 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(DataDir('')) 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;
procedure StartAudio;
var
Code: Integer;
begin
Exec(PowerShellExe, '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
var
Code: Integer;
ApoInUse: Boolean;
begin
Result := '';
Result := CheckDataDir(DataDir('')); { 조용한 설치(/DATADIR=)에서도 확인 }
if Result <> '' then Exit;
{ 다시 설치(업데이트)할 때 오디오 엔진이 쥐고 있는 APO 파일을 바꿀 수 있게 잠깐 오디오 서비스를 멈춘다.
설치 뒤 mic-apo.ps1 이 다시 켠다. }
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 := '설치 폴더 안에 링크(정션 · 심볼릭 링크)가 있어 안전하게 설치할 수 없습니다. 링크를 지우거나 새 폴더를 골라 주세요.';
v1.0.1 까지는 APO 가 고른 폴더의 apo\ 에 있었다 (legacy.ps1 이 지움). 설치 뒤 mic-apo.ps1 이 다시 켠다. }
ApoInUse := FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) or FileExists(DataDir('') + '\apo\VoiceChangerAPO.dll');
if ApoInUse then
Exec(PowerShellExe, '-NoProfile -Command "Stop-Service -Name AudioEndpointBuilder -Force"', '', SW_HIDE, ewWaitUntilTerminated, Code);
{ v1.0.0 · v1.0.1 이 관리자 소유로 잠가 둔 폴더면, 그 실행 부분을 지우고 <폴더>.old 로 비켜 둔다 (관리자 권한).
상위 폴더가 관리자 소유라 일반 사용자가 바꿔칠 수 없을 때만 legacy.ps1 이 한다. }
LegacyOld := DataDir('') + '.old';
ExtractTemporaryFile('legacy.ps1');
if not Exec(PowerShellExe, '-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{tmp}\legacy.ps1') +
'" -App "' + ArgPath(DataDir('')) + '" -Sys "' + ExpandConstant('{app}') + '" -Old "' + LegacyOld + '"',
'', SW_HIDE, ewWaitUntilTerminated, Code) then
Code := -1;
Log('legacy exit=' + IntToStr(Code));
case Code of
0: LegacyOld := '';
1: ;
20: Result := '이 폴더에 있는 이전 버전을 안전하게 옮길 수 없습니다. 새 폴더를 골라 주세요.';
22: Result := LegacyOld + ' 폴더가 이미 있습니다. 그 폴더를 지우거나 다른 폴더를 골라 주세요.';
else
Result := '설치 폴더의 권한을 잠그지 못했습니다. 다른 폴더를 골라 다시 설치해 주세요.';
Result := '이전 버전 폴더를 정리하지 못했습니다 (코드 ' + IntToStr(Code) + '). 다른 폴더를 골라 다시 설치해 주세요.';
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);
if (Result <> '') and ApoInUse then
StartAudio;
end;
procedure CurStepChanged(CurStep: TSetupStep);
var
Code: Integer;
Args: String;
begin
if CurStep <> ssPostInstall then Exit;
{ 데이터 폴더에만 사용자 쓰기 권한을 주고, 관리자 권한으로 실행되는 파일이 잠겼는지 확인한다.
확인이 안 되면 관리자 권한으로 아무것도 실행하지 않는다. }
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
if not Exec(PowerShellExe, '-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{app}\scripts\mic-apo.ps1') +
'" -Install -Root "' + ExpandConstant('{app}') + '"', ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) or (Code <> 0) then
begin
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
StartAudio;
SuppressibleMsgBox('마이크에 변환 모듈을 붙이지 못했습니다. 설치가 끝난 뒤 음성 변환기의 "마이크 다시 연결" 을 눌러 주세요.', mbError, MB_OK, IDOK);
end;
WizardForm.StatusLabel.Caption := 'Python · 변환 엔진 · 기본 모델을 설치 폴더로 내려받는 중... (10~20분, 검은 창에 진행 상황이 나옵니다)';
{ 일반 권한(설치를 시작한 사용자)으로 받는다. 관리자 권한으로 사용자 쓰기 폴더(env · engine)의 코드를 돌리지 않게. }
if not ExecAsOriginalUser(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
'-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{app}\scripts\install.ps1') + '"',
ExpandConstant('{app}'), SW_SHOWNORMAL, ewWaitUntilTerminated, Code) or (Code <> 0) then
WizardForm.StatusLabel.Caption := '앱을 복사하고 Python · 변환 엔진 · 기본 모델을 내려받는 중... (10~20분, 검은 창에 진행 상황이 나옵니다)';
{ 설치를 시작한 사용자 권한으로: 고른 폴더에 앱 파일 복사 → 이전 버전의 데이터 폴더 옮기기 → install.ps1 }
Args := '-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{app}\scripts\deploy.ps1') + '" -Data "' + ArgPath(DataDir('')) + '"';
if LegacyOld <> '' then
Args := Args + ' -From "' + LegacyOld + '"';
if not ExecAsOriginalUser(PowerShellExe, Args, ExpandConstant('{app}'), SW_SHOWNORMAL, ewWaitUntilTerminated, Code) then
Code := -1;
Log('deploy exit=' + IntToStr(Code));
case Code of
0: ;
31: SuppressibleMsgBox(DataDir('') + ' 이 다른 곳을 가리키는 링크(정션)라서 앱을 복사하지 않았습니다.' + #13#10 +
'링크를 지우거나 다른 폴더를 골라 다시 설치해 주세요.', mbError, MB_OK, IDOK);
32: SuppressibleMsgBox(DataDir('') + ' 에 앱 파일을 복사하지 못했습니다 (쓰기 권한이 없는 폴더일 수 있습니다).' + #13#10 +
'내 계정으로 쓸 수 있는 폴더(예: C:\VoiceChanger, 바탕 화면)를 골라 다시 설치해 주세요.', mbError, MB_OK, IDOK);
else
SuppressibleMsgBox('엔진을 내려받지 못했습니다 (인터넷 연결을 확인해 주세요).' + #13#10 +
'설치 폴더의 install.bat 을 실행하면 받은 곳부터 이어서 받습니다.', mbError, MB_OK, IDOK);
DataDir('') + '\install.bat 을 실행하면 받은 곳부터 이어서 받습니다.', mbError, MB_OK, IDOK);
end;
if FileExists(DataDir('') + '\VoiceChanger.exe') then
begin
CreateShellLink(ExpandConstant('{autoprograms}\{#AppName}.lnk'), '{#AppName}', DataDir('') + '\VoiceChanger.exe', '', DataDir(''), '', 0, SW_SHOWNORMAL);
if WizardIsTaskSelected('desktopicon') then
CreateShellLink(ExpandConstant('{autodesktop}\{#AppName}.lnk'), '{#AppName}', DataDir('') + '\VoiceChanger.exe', '', DataDir(''), '', 0, SW_SHOWNORMAL);
end;
{ legacy.ps1 이 비켜 둔 이전 버전 폴더: 데이터 폴더를 다 옮겼으면 비어 있다 (상위가 관리자 소유라 이 경로는 안전) }
if (LegacyOld <> '') and DirExists(LegacyOld) and not RemoveDir(LegacyOld) then
SuppressibleMsgBox('이전 버전 폴더 ' + LegacyOld + ' 에 옮기지 못한 파일이 남아 있습니다. 확인한 뒤 지워 주세요.', mbInformation, MB_OK, IDOK);
end;
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
var
App: String;
begin
if CurUninstallStep = usUninstall then
begin
if not RegQueryStringValue(HKLM, UninstKey, 'Inno Setup CodeFile: DataDir', UninstDataDir) then
UninstDataDir := '';
Exit;
end;
{ 마이크 되돌리기([UninstallRun])와 설치 파일 지우기가 끝난 뒤 }
if CurUninstallStep <> usPostUninstall then Exit;
App := ExpandConstant('{app}');
{ 설치 중에 내려받은 것들 (설치 파일 목록에 없어서 직접 지운다) }
DelTree(App + '\env', True, True, True);
DelTree(App + '\engine', True, True, True);
DelTree(App + '\tools', True, True, True);
DelTree(App + '\cache', True, True, True);
DelTree(App + '\app\__pycache__', True, True, True);
RemoveDir(App + '\app');
{ 사용자가 만든 것은 물어보고 지운다. 조용히 제거할 때는 남겨 둔다 }
{ 앱이 만든 폴더만 지운다. 설치 폴더 자체는 비어 있을 때만 지운다 (RemoveDir 는 빈 폴더만 지움) }
if (not UninstallSilent) and (MsgBox('만든 목소리 모델 · 학습 파일 · 녹음 · 설정도 지울까요?' + #13#10 +
'(models, training, datasets, config 폴더)' + #13#10#13#10 + '"아니요" 를 누르면 남겨 둡니다.', mbConfirmation, MB_YESNO) = IDYES) then
begin
DelTree(App + '\models', True, True, True);
DelTree(App + '\training', True, True, True);
DelTree(App + '\datasets', True, True, True);
DelTree(App + '\config', True, True, True);
end;
RemoveDir(App + '\models');
RemoveDir(App + '\training');
RemoveDir(App + '\datasets');
RemoveDir(App + '\config');
DeleteFile(App + '\apo\mic-apo.log');
RemoveDir(App + '\apo');
RemoveDir(App);
DeleteFile(ExpandConstant('{app}\apo\mic-apo.log'));
RemoveDir(ExpandConstant('{app}\apo'));
RemoveDir(ExpandConstant('{app}\scripts'));
RemoveDir(ExpandConstant('{app}'));
{ 고른 폴더는 관리자 권한으로 지우지 않는다 (정션으로 바꿔쳐 다른 곳을 지우게 만들 수 있음). 내 계정 폴더라 직접 지울 수 있다 }
if (UninstDataDir <> '') and DirExists(UninstDataDir) and not UninstallSilent then
MsgBox('마이크 설정을 되돌리고 프로그램을 지웠습니다.' + #13#10#13#10 +
'앱 · Python · 엔진 · 목소리 모델 · 녹음 · 설정이 든 폴더는 남겨 두었습니다:' + #13#10 + UninstDataDir + #13#10#13#10 +
'필요 없으면 이 폴더를 직접 지워 주세요.', mbInformation, MB_OK);
end;

View File

@@ -0,0 +1,51 @@
# 고른 폴더에 앱을 설치한다. 설치 프로그램이 "설치를 시작한 사용자" 권한으로 실행한다 (ExecAsOriginalUser).
# 고른 폴더(바탕 화면 등)는 상위가 사용자 소유일 수 있어서 관리자 권한으로는 건드리지 않는다:
# 관리자 권한으로 경로를 다루는 도중에 폴더를 정션으로 바꿔치면 엉뚱한 곳에 쓰거나 권한을 바꾸게 되기 때문.
# deploy.ps1 -Data <고른 폴더> [-From <이전 버전 폴더>]
# 1. 이전 버전 폴더에서 데이터 폴더(models · config · env 등)를 옮겨 온다
# - v1.0.0 · v1.0.1: 설치 프로그램(legacy.ps1)이 <폴더>.old 로 비켜 두고 -From 으로 알려 줌
# - v1.0.2: 고른 폴더가 관리자 소유로 잠겨 있으면, 상위 폴더가 내 것일 때 이름을 바꿔 비켜 두고 새로 만든다
# 2. Program Files\VoiceChanger\payload 의 앱 파일을 복사한다
# 3. scripts\install.ps1 로 Python · 엔진 · 기본 모델을 받는다
# 종료 코드: 0 성공, 31 고른 폴더가 링크(정션), 32 폴더를 만들거나 복사하지 못함, 그 밖 = install.ps1 실패
param([Parameter(Mandatory)][string]$Data, [string]$From)
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [Text.Encoding]::UTF8
$Payload = Join-Path (Split-Path -Parent $PSScriptRoot) 'payload'
$DataDirs = 'models', 'training', 'datasets', 'config', 'cache', 'env', 'engine', 'tools'
$Data = [IO.Path]::GetFullPath($Data).TrimEnd('\')
function Say($m) { Write-Host "[deploy] $m" }
function Is-Link([string]$p) { ([IO.File]::GetAttributes($p) -band [IO.FileAttributes]::ReparsePoint) -ne 0 }
function Can-Write([string]$d) {
$t = Join-Path $d ".vc-write-test-$PID"
try { [IO.File]::WriteAllText($t, ''); Remove-Item -LiteralPath $t -Force; return $true } catch { return $false }
}
try {
if (Test-Path -LiteralPath $Data) {
if (Is-Link $Data) { Say "고른 폴더가 링크(정션)입니다: $Data"; exit 31 }
if (-not (Can-Write $Data)) {
$old = "$Data.old-$(Get-Date -Format yyyyMMddHHmmss)"
Rename-Item -LiteralPath $Data -NewName (Split-Path -Leaf $old)
Say "이전 버전 폴더를 비켜 둠: $old"
$From = $old
}
}
New-Item -ItemType Directory -Force -Path $Data | Out-Null
if ($From -and (Test-Path -LiteralPath $From)) {
foreach ($d in $DataDirs) {
$s = Join-Path $From $d
$t = Join-Path $Data $d
if ((Test-Path -LiteralPath $s) -and -not (Test-Path -LiteralPath $t)) { Move-Item -LiteralPath $s -Destination $t; Say "옮김: $d" }
}
}
} catch {
Say "실패: $($_.Exception.Message)"
exit 32
}
& robocopy $Payload $Data /E /R:1 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Host
if ($LASTEXITCODE -ge 8) { Say "앱 파일을 복사하지 못함 (robocopy $LASTEXITCODE)"; exit 32 }
$global:LASTEXITCODE = 0
& (Join-Path $Data 'scripts\install.ps1')
exit $LASTEXITCODE

View File

@@ -0,0 +1,84 @@
# v1.0.0 · v1.0.1 이 설치한 폴더 정리 (설치 프로그램이 관리자 권한으로 {tmp} 에서 실행).
# 그 버전은 고른 폴더를 관리자 소유로 잠그고 그 안에 실행 파일 · 제거 프로그램 · 마이크 모듈을 두었다.
# 이제 앱 파일은 사용자 권한으로 복사하므로(deploy.ps1), 관리자 권한으로 하는 일은 이것뿐이다:
# 이전 실행 부분을 이름을 지정해 지우고, 마이크 백업을 Program Files 쪽으로 옮기고, 폴더 이름을 -Old 로 바꾼다.
# 남은 데이터 폴더(models · config · env 등, 일반 사용자가 쓸 수 있음)는 deploy.ps1 이 사용자 권한으로 새 폴더에 옮긴다.
# 관리자가 아닌 누구도 이 폴더나 그 위 폴더를 지우거나 이름을 바꿀 수 없을 때만 한다 (소유자 · ACL 로 확인).
# 그래야 일반 사용자가 이 작업 도중에 경로를 다른 곳을 가리키는 정션으로 바꿔칠 수 없다. ACL 은 관리자만 바꿀 수 있어서
# 확인한 뒤에도 그대로다. v1.0.0 · v1.0.1 은 상위가 관리자 소유인 곳에만 설치했고 폴더를 이렇게 잠갔다.
# -App <고른 폴더> -Sys <Program Files\VoiceChanger> -Old <새 이름 전체 경로>
# 종료 코드: 0 = 이전 버전 폴더 아님(할 일 없음), 1 = 정리하고 -Old 로 옮김,
# 20 = 이전 버전 폴더지만 안전하게 다룰 수 없음, 22 = -Old 가 이미 있음, 12 = 실패
param([Parameter(Mandatory)][string]$App, [Parameter(Mandatory)][string]$Sys, [Parameter(Mandatory)][string]$Old)
$ErrorActionPreference = 'Stop'
$SY = 'S-1-5-18'; $BA = 'S-1-5-32-544'
$TI = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
$Sid = [System.Security.Principal.SecurityIdentifier]
$App = [IO.Path]::GetFullPath($App).TrimEnd('\')
function Say($m) { Write-Host "[legacy] $m" }
function Is-Link([string]$p) { ([IO.File]::GetAttributes($p) -band [IO.FileAttributes]::ReparsePoint) -ne 0 }
function Owner-Sid([string]$p) { (Get-Acl -LiteralPath $p).GetOwner($Sid).Value }
# 관리자가 아닌 사람이 $p 를 지우거나 이름을 바꿀 수 있는지: 소유자가 관리자가 아니거나,
# $p 에 DELETE · WRITE_DAC · WRITE_OWNER · GENERIC_ALL, 또는 상위 폴더에 DELETE_CHILD · WRITE_DAC · WRITE_OWNER · GENERIC_ALL 을 주는 항목이 있으면 그렇다
$Admins = @($SY, $BA, $TI)
function Grants([string]$p, [int]$bits) {
$acl = Get-Acl -LiteralPath $p
@($acl.GetAccessRules($true, $true, $Sid) | Where-Object { $_.AccessControlType -eq 'Allow' -and
($_.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -eq 0 -and
$_.IdentityReference.Value -notin $Admins -and ([int]$_.FileSystemRights -band $bits) }).Count -gt 0
}
function Swappable([string]$p) {
$parent = Split-Path -Parent $p
if (-not $parent) { return $false } # 드라이브 루트는 지우거나 이름을 바꿀 수 없음
if ((Owner-Sid $p) -notin $Admins) { return $true }
if (Grants $p (0x10000 -bor 0x40000 -bor 0x80000 -bor 0x10000000)) { return $true }
if (Grants $parent (0x40 -bor 0x40000 -bor 0x80000 -bor 0x10000000)) { return $true }
return $false
}
try {
if (-not (Test-Path -LiteralPath (Join-Path $App 'uninstall\unins000.exe'))) { exit 0 }
$p = $App
while ($p) {
if ((Is-Link $p) -or (Swappable $p)) { Say "안전하게 다룰 수 없음: $p (link=$(Is-Link $p) owner=$(Owner-Sid $p))"; exit 20 }
$p = Split-Path -Parent $p
}
if (Test-Path -LiteralPath $Old) { Say "이미 있음: $Old"; exit 22 }
# 이전 배포의 실행 부분만 이름을 지정해 지운다. 목록에 없는 파일은 남겨 두고 폴더째 -Old 로 옮긴다.
$known = [ordered]@{
'.' = @('VoiceChanger.exe', 'install.bat', 'train.bat', 'examples.bat', 'README.md')
'scripts' = @('install.ps1', 'mic-apo.ps1')
'app' = @('common.py', 'examples.py', 'mic_bridge.py', 'models.py', 'record_servers.py', 'setup_engine.py', 'train.py', 'voice_changer.py')
'launcher' = @('launcher.c')
'apo' = @('VoiceChangerAPO.dll', 'vcapo.cpp', 'vccore.h', 'vcapo.def', 'mic-apo.json', 'mic-apo.log')
'uninstall' = @('unins*.exe', 'unins*.dat', 'unins*.msg')
'app\__pycache__' = @('*.pyc')
}
$n = 0
foreach ($d in $known.Keys) {
$dir = if ($d -eq '.') { $App } else { Join-Path $App $d }
if (-not (Test-Path -LiteralPath $dir -PathType Container)) { continue }
foreach ($pat in $known[$d]) {
Get-ChildItem -LiteralPath $dir -Force -File -Filter $pat | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force; $n++ }
}
}
# 마이크 설정 백업 (apo\ 는 관리자만 쓰던 폴더). mic-apo.ps1 이 Program Files 쪽에서 읽고 값을 다시 검증한다
$bk = Join-Path $App 'apo\mic-apo-backup.json'
$sysBk = Join-Path $Sys 'apo\mic-apo-backup.json'
if ((Test-Path -LiteralPath $bk) -and -not (Test-Path -LiteralPath $sysBk)) {
New-Item -ItemType Directory -Force -Path (Split-Path $sysBk) | Out-Null
Move-Item -LiteralPath $bk -Destination $sysBk
Say "마이크 백업을 옮김: $sysBk"
}
foreach ($d in 'app\__pycache__', 'app', 'scripts', 'launcher', 'uninstall', 'apo') { # 비었을 때만
$dir = Join-Path $App $d
if ((Test-Path -LiteralPath $dir) -and -not [IO.Directory]::EnumerateFileSystemEntries($dir).GetEnumerator().MoveNext()) { Remove-Item -LiteralPath $dir -Force }
}
Rename-Item -LiteralPath $App -NewName (Split-Path -Leaf $Old)
Say "이전 배포 파일 $n 개를 지우고 $Old 로 옮김"
exit 1
} catch {
Say "실패: $($_.Exception.Message)"
exit 12
}

View File

@@ -1,153 +0,0 @@
# 설치 폴더 보안 (설치 프로그램이 관리자 권한으로 {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)은 설치 폴더 전체를 사용자 쓰기로 두었다. 이전 배포에 들어 있던 실행 부분은 믿지 않고
# 이름을 하나씩 지정해서만 지운다 (새 파일은 곧 다시 풂). 목록에 없는 파일(사용자가 넣어 둔 녹음 등)은 지우지 않고,
# 아래에서 소유자 · 권한만 관리자 쪽으로 정리한다. 제거 기록(unins*.dat)은 제거할 때 관리자 권한으로 쓰이므로 꼭 지운다.
$known = [ordered]@{
'.' = @('VoiceChanger.exe', 'install.bat', 'train.bat', 'examples.bat', 'README.md')
'scripts' = @('install.ps1', 'mic-apo.ps1')
'app' = @('common.py', 'examples.py', 'mic_bridge.py', 'models.py', 'record_servers.py', 'setup_engine.py', 'train.py', 'voice_changer.py')
'launcher' = @('launcher.c')
'apo' = @('VoiceChangerAPO.dll', 'vcapo.cpp', 'vccore.h', 'vcapo.def', 'mic-apo.json', 'mic-apo.log')
'uninstall' = @('unins*.exe', 'unins*.dat', 'unins*.msg')
'app\__pycache__' = @('*.pyc')
}
$n = 0
foreach ($d in $known.Keys) {
$dir = if ($d -eq '.') { $App } else { Join-Path $App $d }
if (-not (Test-Path -LiteralPath $dir -PathType Container)) { continue }
foreach ($pat in $known[$d]) {
Get-ChildItem -LiteralPath $dir -Force -File -Filter $pat | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force; $n++ }
}
}
foreach ($d in 'app\__pycache__', 'app', 'scripts', 'launcher', 'uninstall') { # 비었을 때만
$dir = Join-Path $App $d
if ((Test-Path -LiteralPath $dir) -and -not [IO.Directory]::EnumerateFileSystemEntries($dir).GetEnumerator().MoveNext()) { Remove-Item -LiteralPath $dir -Force }
}
Say "업데이트: 이전 배포 파일 $n 개 정리 (그 밖의 파일은 남김)"
}
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"

View File

@@ -1,7 +1,9 @@
# 마이크 APO 등록 · 해제 (관리자 권한). 설치 프로그램과 앱의 "마이크 다시 연결" 버튼이 실행한다.
# mic-apo.ps1 -Install [-Root <설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작
# mic-apo.ps1 -Uninstall [-Root <설치 폴더>] 원래 설정으로 되돌림
# 바꾼 레지스트리 값의 원래 값은 <설치 폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다.
# mic-apo.ps1 -Install [-Root <폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작
# mic-apo.ps1 -Uninstall [-Root <폴더>] 원래 설정으로 되돌림
# <폴더> 는 apo\ 가 있는 곳이다. 설치 프로그램은 Program Files\VoiceChanger, zip 으로 풀어 쓰면 그 폴더.
# 바꾼 레지스트리 값의 원래 값은 <폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다.
# (v1.0.1 까지 고른 폴더의 apo\ 에 있던 백업은 설치 프로그램의 legacy.ps1 이 이 자리로 옮긴다)
# apo\ 는 관리자만 쓸 수 있는 폴더다 (일반 사용자가 백업을 바꿔 관리자 권한으로 레지스트리를 쓰게 만들 수 없게).
param([switch]$Install, [switch]$Uninstall, [string]$Root)
$ErrorActionPreference = 'Stop'

View File

@@ -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()