Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(installer): preflight installation directories before elevation

Lizi553816b98de5
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index 3e6b77166a..a45a65102b 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -1471,7 +1471,10 @@ if (isWin) {
extraMetadata: { description: BRAND_IDENTITY.displayName },
nsis: {
oneClick: false,
- allowToChangeInstallationDirectory: true,
+ allowElevation: true,
+ // installer-directory.nsh supplies the directory page with a write-access
+ // check before installation. The stock page only elevates for all-users.
+ allowToChangeInstallationDirectory: false,
installerIcon: 'resources/icon.ico',
uninstallerIcon: 'resources/icon.ico',
createDesktopShortcut: 'always',
diff --git a/apps/desktop/resources/installer-directory-messages.nsh b/apps/desktop/resources/installer-directory-messages.nsh
new file mode 100644
index 0000000000..9342db35c7
--- /dev/null
+++ b/apps/desktop/resources/installer-directory-messages.nsh
@@ -0,0 +1,33 @@
+; NSIS runs before Electron/i18next. Keep the five client languages here, with
+; English fallback for other installer languages. Windows styles the dialogs.
+!macro cindyDirectoryMessage KEY
+ ${Switch} $LANGUAGE
+ ${Case} 2052 ; zh-CN
+ StrCpy $cindyDirectoryMessage "${${KEY}_zh_CN}"
+ ${Break}
+ ${Case} 1028 ; zh-TW
+ StrCpy $cindyDirectoryMessage "${${KEY}_zh_TW}"
+ ${Break}
+ ${Case} 1041 ; ja
+ StrCpy $cindyDirectoryMessage "${${KEY}_ja}"
+ ${Break}
+ ${Case} 1042 ; ko
+ StrCpy $cindyDirectoryMessage "${${KEY}_ko}"
+ ${Break}
+ ${Default}
+ StrCpy $cindyDirectoryMessage "${${KEY}_en}"
+ ${Break}
+ ${EndSwitch}
+!macroend
+
+!define cindyDirectoryNotWritable_en "Cindy cannot write to this installation directory. Choose another directory, or close apps using its files and check your security software before trying again."
+!define cindyDirectoryNotWritable_zh_CN "Cindy 无法写入这个安装目录。请选择其他目录,或关闭占用文件的程序并检查安全软件后重试。"
+!define cindyDirectoryNotWritable_zh_TW "Cindy 無法寫入這個安裝目錄。請選擇其他目錄,或關閉占用檔案的程式並檢查安全軟體後重試。"
+!define cindyDirectoryNotWritable_ja "このインストール先に Cindy を書き込めません。別のディレクトリを選ぶか、ファイルを使用中のアプリを閉じ、セキュリティソフトを確認してから再試行してください。"
+!define cindyDirectoryNotWritable_ko "이 설치 디렉터리에 Cindy를 쓸 수 없습니다. 다른 디렉터리를 선택하거나 파일을 사용 중인 앱을 닫고 보안 소프트웨어를 확인한 후 다시 시도하세요."
+
+!define cindyDirectoryDifferentUser_en "Windows authorization used a different account. To keep Cindy installed for your account, choose a directory you can write to. To install for all users, go back and select that option."
+!define cindyDirectoryDifferentUser_zh_CN "Windows 授权使用了另一个账号。如需仅为当前账号安装 Cindy,请选择可写入的目录;如需为所有用户安装,请返回并选择该选项。"
+!define cindyDirectoryDifferentUser_zh_TW "Windows 授權使用了另一個帳號。如需僅為目前帳號安裝 Cindy,請選擇可寫入的目錄;如需為所有使用者安裝,請返回並選擇該選項。"
+!define cindyDirectoryDifferentUser_ja "Windows の認証に別のアカウントが使われました。現在のアカウントにのみ Cindy をインストールするには、書き込み可能なディレクトリを選んでください。すべてのユーザーにインストールするには、前の画面でそのオプションを選んでください。"
+!define cindyDirectoryDifferentUser_ko "Windows 인증에 다른 계정이 사용되었습니다. 현재 계정에만 Cindy를 설치하려면 쓰기 가능한 디렉터리를 선택하세요. 모든 사용자에게 설치하려면 이전 화면으로 돌아가 해당 옵션을 선택하세요."
diff --git a/apps/desktop/resources/installer-directory.nsh b/apps/desktop/resources/installer-directory.nsh
new file mode 100644
index 0000000000..9f80cf968b
--- /dev/null
+++ b/apps/desktop/resources/installer-directory.nsh
@@ -0,0 +1,254 @@
+; Replace only the assisted directory page. Keep electron-builder's install
+; section, registry layout and UAC broker, including current-user installs.
+!ifndef BUILD_UNINSTALLER
+!include LogicLib.nsh
+!include FileFunc.nsh
+!include UAC.nsh
+!include StrContains.nsh
+
+Var cindyDirectoryElevation
+Var cindyRequestedDirectory
+Var cindyRequestedMode
+Var cindyRequestedUserSid
+Var cindyUserSid
+Var cindyDirectoryError
+Var cindyDirectoryMessage
+
+!define CINDY_ELEVATION_DIFFERENT_USER 49617
+
+!macro customPageAfterChangeDir
+ !define MUI_PAGE_CUSTOMFUNCTION_PRE CindyDirectoryPre
+ !define MUI_PAGE_CUSTOMFUNCTION_LEAVE CindyDirectoryLeave
+ !insertmacro MUI_PAGE_DIRECTORY
+ !define MUI_PAGE_CUSTOMFUNCTION_PRE CindyDirectoryBeforeInstall
+ ; Preserve the stock shortcut policy. Define AFTER the stock page branch,
+ ; otherwise electron-builder would insert a second directory page.
+ !define allowToChangeInstallationDirectory
+!macroend
+
+!macro cindyDirectoryInit
+ ${If} ${UAC_IsInnerInstance}
+ !insertmacro UAC_AsUser_GetGlobalVar $cindyDirectoryElevation
+ ${If} $cindyDirectoryElevation == "1"
+ !insertmacro UAC_AsUser_GetGlobalVar $cindyRequestedDirectory
+ !insertmacro UAC_AsUser_GetGlobalVar $cindyRequestedMode
+ !insertmacro UAC_AsUser_GetGlobalVar $cindyRequestedUserSid
+ ; Other-account elevation must not put a current-user install into the
+ ; administrator's HKCU/profile. Compare OS identities, not account names.
+ ${If} $cindyRequestedMode == "CurrentUser"
+ Call CindyGetUserSid
+ ${If} $cindyUserSid == ""
+ ${OrIf} $cindyUserSid != $cindyRequestedUserSid
+ SetErrorLevel ${CINDY_ELEVATION_DIFFERENT_USER}
+ Quit
+ ${EndIf}
+ ${EndIf}
+ Call CindyRestoreDirectory
+ ${EndIf}
+ ${EndIf}
+ ; Silent installs skip page callbacks. Check before uninstalling an old
+ ; version, and preserve their /D directory verbatim as the stock installer does.
+ ${If} ${Silent}
+ Call CindyEnsureDirectoryWritable
+ ${If} ${Errors}
+ SetErrorLevel 5
+ Quit
+ ${EndIf}
+ ${If} ${UAC_IsInnerInstance}
+ !insertmacro customCheckAppRunning
+ ${EndIf}
+ ${EndIf}
+!macroend
+
+!macro customHeader
+ !ifndef BUILD_UNINSTALLER
+ !include "installer-directory-messages.nsh"
+
+ Function CindyGetUserSid
+ StrCpy $cindyUserSid ""
+ System::Call 'kernel32::GetCurrentProcess() p.r0'
+ System::Call 'advapi32::OpenProcessToken(p r0, i 8, *p .r1) i.r2'
+ ${If} $2 != 0
+ ; TOKEN_USER starts with a SID pointer.
+ System::Call 'advapi32::GetTokenInformation(p r1, i 1, p 0, i 0, *i .r2)'
+ System::Alloc $2
+ Pop $3
+ ${If} $3 != 0
+ System::Call 'advapi32::GetTokenInformation(p r1, i 1, p r3, i r2, *i .r4) i.r5'
+ ${If} $5 != 0
+ System::Call '*$3(p .r4)'
+ System::Call 'advapi32::ConvertSidToStringSidW(p r4, *p .r5) i.r6'
+ ${If} $6 != 0
+ System::Call '*$5(&w${NSIS_MAX_STRLEN} .r6)'
+ StrCpy $cindyUserSid $6
+ System::Call 'kernel32::LocalFree(p r5)'
+ ${EndIf}
+ ${EndIf}
+ System::Free $3
+ ${EndIf}
+ System::Call 'kernel32::CloseHandle(p r1)'
+ ${EndIf}
+ FunctionEnd
+
+ Function CindyRestoreDirectory
+ StrCpy $INSTDIR $cindyRequestedDirectory
+ StrCpy $installMode $cindyRequestedMode
+ ${If} $installMode == "CurrentUser"
+ SetShellVarContext current
+ StrCpy $hasPerUserInstallation "1"
+ StrCpy $hasPerMachineInstallation "0"
+ ${Else}
+ SetShellVarContext all
+ StrCpy $hasPerUserInstallation "0"
+ StrCpy $hasPerMachineInstallation "1"
+ ${EndIf}
+ FunctionEnd
+
+ Function CindyNormalizeDirectory
+ ; Match the stock assisted installer's application subdirectory behavior.
+ ${StrContains} $0 "${APP_FILENAME}" $INSTDIR
+ ${If} $0 == ""
+ StrCpy $INSTDIR "$INSTDIR\${APP_FILENAME}"
+ ${EndIf}
+ FunctionEnd
+
+ Function CindyDirectoryPre
+ ${If} $cindyDirectoryElevation == "1"
+ ; The stock mode page assumes every UAC child is machine-wide. Restore
+ ; the real choice after that page and resume without asking for it again.
+ Call CindyRestoreDirectory
+ Abort
+ ${EndIf}
+ ${If} ${isUpdated}
+ Abort
+ ${EndIf}
+ FunctionEnd
+
+ Function CindyDirectoryLeave
+ ; NSIS commits the edit control to INSTDIR AFTER this callback. Read the
+ ; current text so the probe checks the new choice, not the old directory.
+ ${NSD_GetText} $mui.DirectoryPage.Directory $INSTDIR
+ Call CindyNormalizeDirectory
+ ${NSD_SetText} $mui.DirectoryPage.Directory $INSTDIR
+ Call CindyEnsureDirectoryWritable
+ ${If} ${Errors}
+ Abort ; keep the directory page and selection when authorization fails
+ ${EndIf}
+ FunctionEnd
+
+ Function CindyDirectoryBeforeInstall
+ Call CindyNormalizeDirectory
+ Call CindyEnsureDirectoryWritable
+ ${If} ${Errors}
+ ; Abort in an instfiles PRE would skip to the finish page. Quit instead.
+ SetErrorLevel 5
+ Quit
+ ${EndIf}
+ ${If} ${UAC_IsInnerInstance}
+ !insertmacro customCheckAppRunning
+ ${EndIf}
+ FunctionEnd
+
+ ; Probe the destination or its nearest existing parent without creating an
+ ; installation tree. Delete only the unique file created by GetTempFileName.
+ Function CindyProbeDirectory
+ StrCpy $cindyDirectoryError 0
+ StrCpy $0 $INSTDIR
+ cindy_probe_parent:
+ System::Call 'kernel32::GetFileAttributesW(w r0) i.r1 ?e'
+ Pop $2
+ ${If} $1 == -1
+ ${If} $2 != 2
+ ${AndIf} $2 != 3
+ StrCpy $cindyDirectoryError $2
+ Return
+ ${EndIf}
+ ${GetParent} "$0" $1
+ ${If} $1 == ""
+ ${OrIf} $1 == $0
+ StrCpy $cindyDirectoryError 3
+ Return
+ ${EndIf}
+ StrCpy $0 $1
+ Goto cindy_probe_parent
+ ${EndIf}
+ IntOp $1 $1 & 0x10
+ ${If} $1 == 0
+ StrCpy $cindyDirectoryError 267 ; ERROR_DIRECTORY
+ Return
+ ${EndIf}
+ System::Call 'kernel32::GetTempFileNameW(w r0, w "cdy", i 0, w .r1) i.r2 ?e'
+ Pop $3
+ ${If} $2 == 0
+ StrCpy $cindyDirectoryError $3
+ Return
+ ${EndIf}
+ System::Call 'kernel32::DeleteFileW(w r1) i.r2 ?e'
+ Pop $3
+ ${If} $2 == 0
+ StrCpy $cindyDirectoryError $3
+ Return
+ ${EndIf}
+ ; Also catch a read-only/locked old icon in an otherwise writable directory.
+ ; OPEN_EXISTING requests write access without changing any existing bytes.
+ IfFileExists "$INSTDIR\uninstallerIcon.ico" 0 cindy_probe_done
+ System::Call 'kernel32::CreateFileW(w "$INSTDIR\uninstallerIcon.ico", i 0x40000000, i 7, p 0, i 3, i 0, p 0) p.r1 ?e'
+ Pop $2
+ ${If} $1 == -1
+ StrCpy $cindyDirectoryError $2
+ ${Else}
+ System::Call 'kernel32::CloseHandle(p r1)'
+ ${EndIf}
+ cindy_probe_done:
+ FunctionEnd
+
+ Function CindyEnsureDirectoryWritable
+ ClearErrors
+ Call CindyProbeDirectory
+ ${If} $cindyDirectoryError == 0
+ Return
+ ${EndIf}
+ ; Only ACCESS_DENIED may be repaired by elevation. Do not prompt for a
+ ; locked file, invalid path, full disk, or an already elevated process.
+ ${If} $cindyDirectoryError == 5
+ ${AndIfNot} ${UAC_IsAdmin}
+ Call CindyGetUserSid
+ ${If} $cindyUserSid != ""
+ StrCpy $cindyRequestedUserSid $cindyUserSid
+ StrCpy $cindyRequestedDirectory $INSTDIR
+ StrCpy $cindyRequestedMode $installMode
+ StrCpy $cindyDirectoryElevation "1"
+ ShowWindow $HWNDPARENT ${SW_HIDE}
+ !insertmacro UAC_RunElevated
+ ${If} $0 == 0
+ ${AndIf} $1 == 1
+ ${If} $2 != ${CINDY_ELEVATION_DIFFERENT_USER}
+ SetErrorLevel $2
+ Quit ; the child has finished; never install again in the parent
+ ${EndIf}
+ ${EndIf}
+ StrCpy $cindyDirectoryElevation "0"
+ ShowWindow $HWNDPARENT ${SW_SHOW}
+ BringToFront
+ ${If} $0 == 1223
+ SetErrors ; UAC cancelled: return to directory selection quietly
+ Return
+ ${EndIf}
+ ${If} $0 == 0
+ ${AndIf} $1 == 1
+ ${AndIf} $2 == ${CINDY_ELEVATION_DIFFERENT_USER}
+ !insertmacro cindyDirectoryMessage cindyDirectoryDifferentUser
+ MessageBox MB_OK|MB_ICONEXCLAMATION "$cindyDirectoryMessage" /SD IDOK
+ SetErrors
+ Return
+ ${EndIf}
+ ${EndIf}
+ ${EndIf}
+ !insertmacro cindyDirectoryMessage cindyDirectoryNotWritable
+ MessageBox MB_OK|MB_ICONEXCLAMATION "$cindyDirectoryMessage$\r$\n$\r$\n$INSTDIR$\r$\n($cindyDirectoryError)" /SD IDOK
+ SetErrors
+ FunctionEnd
+ !endif
+!macroend
+
+!endif ; BUILD_UNINSTALLER
diff --git a/apps/desktop/resources/installer.nsh b/apps/desktop/resources/installer.nsh
index 5e151a509a..63d6922cea 100644
--- a/apps/desktop/resources/installer.nsh
+++ b/apps/desktop/resources/installer.nsh
@@ -7,7 +7,17 @@
; 接受);dev 仍独立名,dev 安装器绝不误伤同机并存的正式安装。注册表键名
; Windows 大小写不敏感,shell 键 "Cindy" 与历史写入的 "cindy" 是同一个键,
; 行为零变化。
+!include "installer-directory.nsh"
+
+!ifndef BUILD_UNINSTALLER
!macro customInit
+ !insertmacro cindyDirectoryInit
+!macroend
+
+; Run only after the directory preflight, immediately before replacing the app.
+; The upstream install section skips this hook in elevated inner instances;
+; cindyDirectoryBeforeInstall invokes it for those instances instead.
+!macro customCheckAppRunning
; Check if the app is already running
check_running:
nsProcess::_FindProcess "${APP_EXECUTABLE_FILENAME}"
@@ -15,8 +25,9 @@
${If} $R0 == 0
MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION \
"${PRODUCT_FILENAME} 正在运行,请先关闭后再继续安装。$\n$\n点击「确定」将在关闭后继续。" \
- IDOK kill_app
- Abort
+ /SD IDCANCEL IDOK kill_app
+ SetErrorLevel 1602
+ Quit
kill_app:
nsProcess::_KillProcess "${APP_EXECUTABLE_FILENAME}"
Sleep 1000
@@ -35,6 +46,7 @@
; 同步清掉 PinnedTaskbar 里的副本(任务栏固定项也会缓存图标)
Delete "$APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\${SHORTCUT_NAME}.lnk"
!macroend
+!endif
!macro customInstall
; 注册文件夹右键菜单 "通过 <区域名> 打开" (与 main/folderContextMenu.ts 写的是同一组键)。
diff --git a/apps/desktop/scripts/check-windows-installer.mjs b/apps/desktop/scripts/check-windows-installer.mjs
new file mode 100644
index 0000000000..91057da3d8
--- /dev/null
+++ b/apps/desktop/scripts/check-windows-installer.mjs
@@ -0,0 +1,215 @@
+// Compile the production NSIS hooks and exercise their Win32 preflight in an
+// isolated native harness. Does not install Cindy, change registry keys, or open UAC.
+// Run explicitly on Windows: node apps/desktop/scripts/check-windows-installer.mjs
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createRequire } from 'node:module';
+import { spawnSync } from 'node:child_process';
+
+const require = createRequire(import.meta.url);
+const desktop = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const resources = path.join(desktop, 'resources');
+const { build, Platform, Arch } = require('app-builder-lib');
+
+if (process.platform !== 'win32')
+ throw new Error('This check requires Windows and the NSIS toolchain.');
+const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-installer-check-'));
+console.log(`Installer check directory: ${root}`);
+try {
+ const payload = path.join(root, 'payload');
+ await fs.mkdir(path.join(payload, 'resources'), { recursive: true });
+ await fs.writeFile(
+ path.join(payload, 'CindyInstallerProbe.exe'),
+ 'Compile fixture; never execute.',
+ );
+ await fs.writeFile(
+ path.join(root, 'package.json'),
+ JSON.stringify({
+ name: 'cindy-installer-probe',
+ version: '0.0.1',
+ description: 'Installer compile check',
+ author: 'Test',
+ }),
+ );
+ // Exercise the real electron-builder installer AND uninstaller templates, with
+ // a tiny inert payload. The generated setup is deliberately never launched.
+ await build({
+ projectDir: root,
+ prepackaged: payload,
+ targets: Platform.WINDOWS.createTarget('nsis', Arch.x64),
+ config: {
+ appId: 'app.cindy.installer-test',
+ productName: 'CindyInstallerProbe',
+ electronVersion: '41.10.3',
+ compression: 'store',
+ directories: { output: path.join(root, 'out'), buildResources: resources },
+ win: { signAndEditExecutable: false, sign: async () => {} },
+ nsis: {
+ oneClick: false,
+ allowElevation: true,
+ allowToChangeInstallationDirectory: false,
+ include: path.join(resources, 'installer.nsh'),
+ uninstallerIcon: path.join(resources, 'icon.ico'),
+ artifactName: 'compile-only.exe',
+ },
+ },
+ });
+ console.log('PASS: production installer and uninstaller compile (warnings are errors)');
+
+ const { NSIS_PATH, nsisTemplatesDir } = require('app-builder-lib/out/targets/nsis/nsisUtil');
+ const nsis = await NSIS_PATH();
+ const compile = spawnSync(
+ path.join(nsis, 'Bin', 'makensis.exe'),
+ [
+ '/WX',
+ '/V2',
+ `/DTEST_ROOT=${root}`,
+ `/X!addincludedir "${resources}"`,
+ `/X!addincludedir "${path.join(nsisTemplatesDir, 'include')}"`,
+ path.join(desktop, 'scripts', 'fixtures', 'installer-directory-check.nsi'),
+ ],
+ { encoding: 'utf8', windowsHide: true, timeout: 30_000 },
+ );
+ assert.equal(compile.status, 0, compile.error?.message ?? compile.stdout + compile.stderr);
+
+ const writable = path.join(root, '目录 with spaces', 'CindyInstallerProbe');
+ await fs.mkdir(writable, { recursive: true });
+ const icon = path.join(writable, 'uninstallerIcon.ico');
+ const originalIcon = 'existing icon contents must not change';
+ await fs.writeFile(icon, originalIcon);
+ const fileAsDirectory = path.join(root, 'ordinary-file');
+ await fs.writeFile(fileAsDirectory, 'not a directory');
+
+ async function runCase(
+ name,
+ { directory = writable, admin = 0, elevationResult = 1223, childExit = 0 } = {},
+ ) {
+ const ini = `[input]\r\ncase=${name}\r\ndirectory=${directory}\r\nadmin=${admin}\r\nelevationResult=${elevationResult}\r\nchildExit=${childExit}\r\n`;
+ await fs.writeFile(path.join(root, 'case.ini'), '\ufeff' + ini, 'utf16le');
+ await fs.writeFile(path.join(root, 'result.ini'), '\ufeff', 'utf16le');
+ const processResult = spawnSync(path.join(root, 'directory-check.exe'), [], {
+ windowsHide: true,
+ timeout: 15_000,
+ encoding: 'utf8',
+ });
+ assert.ifError(processResult.error);
+ const resultText = await fs.readFile(path.join(root, 'result.ini'), 'utf16le');
+ const result = Object.fromEntries(
+ resultText
+ .split(/\r?\n/)
+ .filter((line) => line.includes('='))
+ .map((line) => {
+ const split = line.indexOf('=');
+ return [line.slice(0, split), line.slice(split + 1)];
+ }),
+ );
+ console.log(`Native case: ${name} (exit ${processResult.status})`);
+ return { ...result, exit: processResult.status };
+ }
+
+ const writableResult = await runCase('writable');
+ assert.equal(writableResult.failed, '0');
+ assert.equal(writableResult.elevations, '0');
+ assert.equal(writableResult.directory, writable);
+ assert.match(writableResult.sid, /^S-1-/);
+ assert.deepEqual(await fs.readdir(writable), ['uninstallerIcon.ico']);
+ assert.equal(await fs.readFile(icon, 'utf8'), originalIcon);
+
+ // Deny writes only inside our unique fixture using the real current SID.
+ // This reproduces protected directories without changing system ACLs.
+ const protectedDirectory = path.join(root, 'protected');
+ await fs.mkdir(protectedDirectory);
+ const acl = (args) => {
+ const result = spawnSync('icacls.exe', [protectedDirectory, ...args], {
+ windowsHide: true,
+ encoding: 'utf8',
+ timeout: 15_000,
+ });
+ assert.equal(result.status, 0, result.error?.message ?? result.stdout + result.stderr);
+ };
+ acl(['/deny', `*${writableResult.sid}:(WD,AD)`]);
+ try {
+ for (const directory of [
+ protectedDirectory,
+ path.join(protectedDirectory, 'CindyInstallerProbe'),
+ ]) {
+ const denied = await runCase('protected-directory', { directory });
+ assert.equal(denied.error, '5');
+ assert.equal(denied.elevations, '1');
+ assert.equal(denied.failed, '1');
+ assert.equal(denied.prepare, '0');
+ }
+ assert.deepEqual(await fs.readdir(protectedDirectory), []);
+ } finally {
+ acl(['/remove:d', `*${writableResult.sid}`]);
+ }
+
+ const missing = path.join(writable, 'new', 'nested');
+ assert.equal((await runCase('missing', { directory: missing })).failed, '0');
+ await assert.rejects(fs.stat(missing), { code: 'ENOENT' });
+ const invalid = await runCase('file-as-directory', { directory: fileAsDirectory });
+ assert.equal(invalid.error, '267');
+ assert.equal(invalid.failed, '1');
+ assert.equal(invalid.elevations, '0');
+
+ const locked = await runCase('locked');
+ assert.equal(locked.error, '32');
+ assert.equal(locked.elevations, '0');
+ assert.equal(locked.failed, '1');
+
+ await fs.chmod(icon, 0o444);
+ try {
+ const cancelled = await runCase('cancelled');
+ assert.equal(cancelled.error, '5');
+ assert.equal(cancelled.elevations, '1');
+ assert.equal(cancelled.failed, '1');
+ assert.equal(cancelled.directory, writable);
+ assert.equal(cancelled.prepare, '0');
+
+ const alreadyAdmin = await runCase('already-admin', { admin: 1 });
+ assert.equal(alreadyAdmin.failed, '1');
+ assert.equal(alreadyAdmin.elevations, '0');
+
+ const differentUser = await runCase('different-user', { elevationResult: 0, childExit: 49617 });
+ assert.equal(differentUser.failed, '1');
+ assert.equal(differentUser.prepare, '0');
+ assert.equal(differentUser.mode, 'CurrentUser');
+
+ for (const childExit of [0, 5]) {
+ const completed = await runCase('completed-child', { elevationResult: 0, childExit });
+ assert.equal(completed.exit, childExit);
+ assert.equal(
+ completed.directory,
+ undefined,
+ 'outer process must not continue after child exits',
+ );
+ }
+ } finally {
+ await fs.chmod(icon, 0o666);
+ }
+
+ const resumedUser = await runCase('resume-user', { admin: 1 });
+ assert.equal(resumedUser.directory, writable);
+ assert.equal(resumedUser.mode, 'CurrentUser');
+ assert.equal(resumedUser.prepare, '1');
+ const resumedOther = await runCase('resume-other', { admin: 1 });
+ assert.equal(resumedOther.exit, 49617);
+ assert.equal(resumedOther.prepare, undefined);
+ const resumedAll = await runCase('resume-all', { admin: 1 });
+ assert.equal(resumedAll.directory, writable);
+ assert.equal(resumedAll.mode, 'all');
+ assert.equal(resumedAll.prepare, '1');
+ assert.equal(await fs.readFile(icon, 'utf8'), originalIcon);
+ assert.deepEqual(await fs.readdir(writable), ['uninstallerIcon.ico']);
+ console.log(
+ 'PASS: directory access, locked/read-only files, cancellation, child exit and identity/scope preservation',
+ );
+} finally {
+ // Delete only the unique test root allocated above, never an inferred workspace.
+ assert.equal(path.dirname(root), path.resolve(os.tmpdir()));
+ assert.ok(path.basename(root).startsWith('cindy-installer-check-'));
+ await fs.rm(root, { recursive: true, force: true });
+}
diff --git a/apps/desktop/scripts/fixtures/installer-directory-check.nsi b/apps/desktop/scripts/fixtures/installer-directory-check.nsi
new file mode 100644
index 0000000000..e2a4b01ec1
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/installer-directory-check.nsi
@@ -0,0 +1,108 @@
+; Native preflight contract harness. Real Win32 file/SID calls; simulated UAC
+; outcomes so automated checks never launch secure-desktop authorization.
+Unicode true
+RequestExecutionLevel user
+SilentInstall silent
+OutFile "${TEST_ROOT}\directory-check.exe"
+!include MUI2.nsh
+!include nsDialogs.nsh
+!include "installer-directory.nsh"
+
+!define APP_FILENAME CindyInstallerProbe
+Var installMode
+Var hasPerUserInstallation
+Var hasPerMachineInstallation
+Var testCase
+Var testAdmin
+Var testInner
+Var testElevationResult
+Var testChildExit
+Var testElevationCalls
+Var testPrepareCalls
+Var testFailed
+Var testLock
+
+!macroundef _UAC_IsAdmin
+!macro _UAC_IsAdmin _a _b _t _f
+ !insertmacro _= $testAdmin 1 `${_t}` `${_f}`
+!macroend
+!macroundef _UAC_IsInnerInstance
+!macro _UAC_IsInnerInstance _a _b _t _f
+ !insertmacro _= $testInner 1 `${_t}` `${_f}`
+!macroend
+!macroundef UAC_RunElevated
+!macro UAC_RunElevated
+ IntOp $testElevationCalls $testElevationCalls + 1
+ StrCpy $0 $testElevationResult
+ StrCpy $1 1
+ StrCpy $2 $testChildExit
+!macroend
+!macroundef UAC_AsUser_GetGlobalVar
+!macro UAC_AsUser_GetGlobalVar VAR
+ ; Inputs are already supplied by case.ini instead of a real outer process.
+!macroend
+!define isUpdated `"" HarnessIsUpdated ""`
+!macro _HarnessIsUpdated _a _b _t _f
+ !insertmacro _= 0 1 `${_t}` `${_f}`
+!macroend
+!macro customCheckAppRunning
+ IntOp $testPrepareCalls $testPrepareCalls + 1
+!macroend
+
+!insertmacro customPageAfterChangeDir
+!insertmacro MUI_PAGE_INSTFILES
+!insertmacro MUI_LANGUAGE English
+!insertmacro customHeader
+
+Section
+ ReadINIStr $testCase "${TEST_ROOT}\case.ini" input case
+ ReadINIStr $INSTDIR "${TEST_ROOT}\case.ini" input directory
+ ReadINIStr $testAdmin "${TEST_ROOT}\case.ini" input admin
+ ReadINIStr $testElevationResult "${TEST_ROOT}\case.ini" input elevationResult
+ ReadINIStr $testChildExit "${TEST_ROOT}\case.ini" input childExit
+ StrCpy $testElevationCalls 0
+ StrCpy $testPrepareCalls 0
+ StrCpy $installMode CurrentUser
+
+ ${If} $testCase == "locked"
+ System::Call 'kernel32::CreateFileW(w "$INSTDIR\uninstallerIcon.ico", i 0x80000000, i 0, p 0, i 3, i 0, p 0) p.r0'
+ StrCpy $testLock $0
+ ${EndIf}
+
+ ${If} $testCase == "resume-user"
+ ${OrIf} $testCase == "resume-other"
+ ${OrIf} $testCase == "resume-all"
+ StrCpy $testInner 1
+ StrCpy $cindyDirectoryElevation 1
+ StrCpy $cindyRequestedDirectory $INSTDIR
+ StrCpy $INSTDIR "wrong directory from stock multi-user page"
+ StrCpy $cindyRequestedMode CurrentUser
+ Call CindyGetUserSid
+ StrCpy $cindyRequestedUserSid $cindyUserSid
+ ${If} $testCase == "resume-other"
+ ${OrIf} $testCase == "resume-all"
+ StrCpy $cindyRequestedUserSid "S-1-5-21-0-0-0-1000"
+ ${EndIf}
+ ${If} $testCase == "resume-all"
+ StrCpy $cindyRequestedMode all
+ ${EndIf}
+ !insertmacro cindyDirectoryInit
+ ${Else}
+ Call CindyEnsureDirectoryWritable
+ ${EndIf}
+ StrCpy $testFailed 0
+ ${If} ${Errors}
+ StrCpy $testFailed 1
+ ${EndIf}
+ ${If} $testCase == "locked"
+ System::Call 'kernel32::CloseHandle(p $testLock)'
+ ${EndIf}
+ Call CindyGetUserSid
+ WriteINIStr "${TEST_ROOT}\result.ini" result error $cindyDirectoryError
+ WriteINIStr "${TEST_ROOT}\result.ini" result failed $testFailed
+ WriteINIStr "${TEST_ROOT}\result.ini" result elevations $testElevationCalls
+ WriteINIStr "${TEST_ROOT}\result.ini" result prepare $testPrepareCalls
+ WriteINIStr "${TEST_ROOT}\result.ini" result directory $INSTDIR
+ WriteINIStr "${TEST_ROOT}\result.ini" result mode $installMode
+ WriteINIStr "${TEST_ROOT}\result.ini" result sid $cindyUserSid
+SectionEnd
diff --git a/apps/desktop/scripts/installer-directory-messages.test.mjs b/apps/desktop/scripts/installer-directory-messages.test.mjs
new file mode 100644
index 0000000000..c36df67bfe
--- /dev/null
+++ b/apps/desktop/scripts/installer-directory-messages.test.mjs
@@ -0,0 +1,70 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it } from 'vitest';
+import {
+ caseStandardFor,
+ findCaseMismatch,
+ occursIn,
+ sourceMentions,
+ stripNonProse,
+ findHalfWidthPunct,
+ hasAsciiEllipsis,
+ normalizeForPunctuation,
+ HALFWIDTH_PUNCT_LOCALES,
+ ELLIPSIS_LOCALES,
+} from '../../../scripts/shared/glossary-rules.mjs';
+
+// Native NSIS dialogs cannot load i18next. Check their separate catalog using
+// the same glossary rules as the client instead of leaving it outside the gate.
+const source = readFileSync(
+ new URL('../resources/installer-directory-messages.nsh', import.meta.url),
+ 'utf8',
+);
+const glossary = JSON.parse(
+ readFileSync(new URL('../../../i18n/glossary.json', import.meta.url), 'utf8'),
+);
+const locales = { en: 'en', zh_CN: 'zh-CN', zh_TW: 'zh-TW', ja: 'ja', ko: 'ko' };
+const entries = [...source.matchAll(/^!define (\w+)_(en|zh_CN|zh_TW|ja|ko) "([^"]+)"$/gm)].map(
+ ([, key, language, value]) => ({ key, locale: locales[language], value }),
+);
+const english = new Map(
+ entries.filter((entry) => entry.locale === 'en').map((entry) => [entry.key, entry.value]),
+);
+
+describe('Windows installer directory messages', () => {
+ it('provides every message in all five client languages', () => {
+ expect(english.size).toBeGreaterThan(0);
+ for (const key of english.keys()) {
+ expect(
+ entries
+ .filter((entry) => entry.key === key)
+ .map((entry) => entry.locale)
+ .sort(),
+ ).toEqual([...glossary.locales].sort());
+ }
+ expect(entries.length).toBe(english.size * glossary.locales.length);
+ });
+
+ it('uses the decided glossary and locale punctuation', () => {
+ const violations = [];
+ for (const { key, locale, value } of entries) {
+ const prose = stripNonProse(value);
+ for (const term of glossary.terms.filter((term) => term.status === 'decided')) {
+ for (const forbidden of term.forbidden?.[locale] ?? []) {
+ const bad = typeof forbidden === 'string' ? forbidden : forbidden.text;
+ if (typeof forbidden !== 'string' && !sourceMentions(english.get(key), forbidden.whenEn))
+ continue;
+ if (occursIn(prose, bad)) violations.push(`${locale} ${key}: ${bad}`);
+ }
+ const standard = caseStandardFor(term, locale);
+ if (standard && findCaseMismatch(prose, standard))
+ violations.push(`${locale} ${key}: ${standard}`);
+ }
+ const punctuation = normalizeForPunctuation(value);
+ if (HALFWIDTH_PUNCT_LOCALES.has(locale) && findHalfWidthPunct(punctuation))
+ violations.push(`${locale} ${key}: punctuation`);
+ if (ELLIPSIS_LOCALES.has(locale) && hasAsciiEllipsis(punctuation))
+ violations.push(`${locale} ${key}: ellipsis`);
+ }
+ expect(violations).toEqual([]);
+ });
+});
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index 93f5a7634b..ed62e5edfd 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -183,3 +183,31 @@ pnpm test:unit
- 数据库 migration、协议、更新器、权限与用户数据另有高风险专项规则;命中时先读取
对应规则,不以本页命令替代专项验证。
- 记录实际执行和结果;未执行的高相关检查必须说明原因。
+
+## Windows 安装目录与授权
+
+NSIS 安装器保留当前用户/所有用户两种范围。普通用户可写的目录无需提权;选择受保护的
+目录时,在替换文件和卸载旧版之前探测写权限,仅遇到 Windows `ACCESS_DENIED` 才通过
+现有 UAC broker 请求授权。取消授权保留目录选择;文件占用、无效路径等错误提示换目录
+或处理占用,不反复申请管理员权限。静默安装同样在卸载旧版之前检查目录。
+
+同账号提权保留原目录和安装范围。当前用户安装若通过另一个管理员账号授权,则停止该次
+提权安装,提示选择当前账号可写的目录,或返回选择为所有用户安装;不得把当前用户安装
+悄悄登记到管理员账号名下。此改动不调整 Cindy 运行时的权限、用户数据目录或更新器。
+
+实现使用 `resources/installer-directory.nsh` 的目录页和预检查,
+`forge.config.ts` 因此关闭上游自带目录页,由 `customPageAfterChangeDir` 插入同款原生页。
+不要单独打开上游 `allowToChangeInstallationDirectory`,否则会重复插入页面。
+
+在 Windows 显式运行原生验证(临时目录内编译,不安装 Cindy):
+
+```bash
+node apps/desktop/scripts/check-windows-installer.mjs
+pnpm --filter desktop exec vitest run scripts/installer-directory-messages.test.mjs
+```
+
+前者编译真实安装器/卸载器,并实跑 Win32 文件访问与账号 SID 探测;UAC 返回值由测试
+替身提供,覆盖取消、子进程退出和账号/范围恢复。它不能代替真实 UAC 交互验收。发布前
+还需在普通权限 Windows 环境走查:默认目录、自定义受保护目录、允许/取消授权、使用
+另一管理员账号、旧版覆盖安装,以及静默安装失败时旧版仍在。原生对话框的 Light/Dark
+外观由 Windows 提供,自动测试不代表两种模式已完成目检。