From af15cdf6c2e4d072c15f6bec239a081b354f7495 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:37:40 +0800 Subject: [PATCH 01/90] fix(desktop): clean owned Windows registrations on manual uninstall --- apps/desktop/README.i18n.yaml | 8 +- apps/desktop/README.md | 4 +- apps/desktop/README.zh.md | 4 +- apps/desktop/installer/locales/de_DE.json | 4 +- apps/desktop/installer/locales/en_US.json | 4 +- apps/desktop/installer/locales/es_ES.json | 4 +- apps/desktop/installer/locales/fr_FR.json | 4 +- apps/desktop/installer/locales/ja_JP.json | 4 +- apps/desktop/installer/locales/pt_BR.json | 4 +- apps/desktop/installer/locales/ru_RU.json | 4 +- apps/desktop/installer/locales/zh_CN.json | 4 +- apps/desktop/installer/uninstall.nsh | 22 ++++++ apps/desktop/scripts/installer.nsh | 1 + .../scripts/test-windows-installer.mjs | 5 +- .../scripts/uninstall-registration.ps1 | 26 +++++++ .../scripts/windows-directory-installer.d.mts | 2 +- .../scripts/windows-directory-installer.mjs | 17 ++++- .../tests/expected/windows-uninstall.json | 10 ++- apps/desktop/tests/fixtures/command-path.ps1 | 23 ++++++ .../desktop/tests/windows-uninstall-smoke.ps1 | 73 ++++++++++++++++++- 20 files changed, 201 insertions(+), 26 deletions(-) create mode 100644 apps/desktop/scripts/uninstall-registration.ps1 diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index dc6cb5f9e0..b0c627b8db 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -18,8 +18,8 @@ en: d4afa46403997884 zh: 9b9fe126afda70f0 /deepseek-harness-desktop/terminal-command: - en: 5f2d25a1d8472647 - zh: 2acb5c5d7d1917e2 + en: 988bf8bb84cf7c9a + zh: 28cefc949c7f52ce /deepseek-harness-desktop/closing-the-window-and-quitting: en: bb35a022c37955c9 zh: ab2ef22d398d83a0 @@ -54,8 +54,8 @@ en: ac31ebdd9de54f34 zh: 921e534d5c4b3a16 /deepseek-harness-desktop/windows-installer-interface: - en: f1302ed4a3ab58bb - zh: cb53b9b349815028 + en: 4f61d5a4038423fd + zh: 5ad67e1f9526d517 /deepseek-harness-desktop/updates: en: 67bf0a18faa7aa76 zh: 782e14ce62bb939f diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 68596d719f..619d4a620a 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -63,7 +63,7 @@ The application menu's **Manage dsh Command…** entry, immediately below **Chec On macOS, installation creates `/usr/local/bin/dsh` and requests administrator authentication when the directory requires it. Shell startup files are unchanged. On Windows, the management dialog registers the command in the current user's PATH. A pre-existing command requires confirmation before switching; repairing Desktop's own selected command does not repeat that confirmation. The macOS link preserves and restores the displaced launcher; Windows preserves other PATH entries, including entries that predate registration. A command with higher PATH precedence is reported with its location. After moving the application, use Repair on macOS or Install from the new location on Windows. Remove leaves unrelated installations intact. -Command registration is optional after installing Desktop. Use **Manage dsh Command… → Remove** before uninstalling Desktop to remove its CLI registration; the application uninstaller does not remove it. Finish CLI commands before updating or uninstalling Desktop. The CLI runtime version follows the installed Desktop release. See [bundled command runtime](#bundled-command-runtime) for Desktop plugin commands and runtime limitations. +Command registration is optional after installing Desktop. Windows manual uninstall removes CLI registration owned by that installation; on macOS, use **Manage dsh Command… → Remove** before uninstalling Desktop. Finish CLI commands before updating or uninstalling Desktop. The CLI runtime version follows the installed Desktop release. See [bundled command runtime](#bundled-command-runtime) for Desktop plugin commands and runtime limitations. @@ -260,7 +260,7 @@ Windows packaging compiles an x86 Win32/GDI+ helper with Visual C++ Build Tools Run `pnpm --dir apps/desktop run test:installer` from the repository root on an interactive Windows x64 desktop to build and exercise a small native test payload through the production installer configuration. Each run uses a unique product identity and sequentially exercises English-only and Chinese-only installer variants, selecting test labels from the displayed welcome button. Both variants install into private directories and uninstall after testing; screenshots and results remain under `.desktop-build/installer-tests/`. The checks include restart-notice process cleanup, upgrades to registered paths with trailing separators and rejection of drive roots. The renderer receives caption colors from the NSIS theme; pixel checks print into an off-screen bitmap and also run with the progress child hidden. Native rendering checks cover light/dark palettes at 100% and 200% scale, the painted 100% completion state, caption-button hover/pressed colors and release/cancellation, minimize/restore geometry, and GDI resource release; repaint timings are diagnostics in `render-results.log`, not CI performance limits. Run the generated `ui/render-test.exe [interactive-title]` with a title to inspect the real progress page without installing a payload. The optional `--signed` flag uses the [Windows EV configuration](windows-signing/README.md#signing-configuration) to sign test executables and the helper before embedding them; it does not enable an update feed. -The Windows uninstaller removes the Electron user-data directory (browser storage and caches under `%APPDATA%`, nested under the package scope), the `%APPDATA%` product directory, and the updater download cache under `%LOCALAPPDATA%` together with the application, then removes ordinary empty scope directories below `%APPDATA%`. The Harness home (`~/.dsh` or `DSH_HOME`: sessions, settings, credentials, plugins) is never touched, and a `DSH_HOME` published as a Windows environment variable additionally protects any target overlapping it. Silent uninstalls remove the same data; an uninstaller started with `--updated` or `/KEEP_APP_DATA`, as electron-builder does for in-place updates and for replacing an older installation from another directory, retains it. Removal runs through the native helper, which refuses protected Windows folders and paths overlapping the installation or the home, requires a fixed local drive, leaves a linked root or ancestor in place, unlinks reparse points without entering their targets, clears read-only attributes, and keeps deleting siblings after a locked file; residue never stops uninstallation and is not reported. Installation records `InstallLocation` on the Windows uninstall entry as standard inventory metadata; on Windows 11, Uninstall in the Start menu context menu opens the installed-apps list for every Win32 application, and only MSIX packages uninstall directly from there. The uninstaller declares DPI awareness and uses Microsoft YaHei UI for Chinese. This behavior is Windows-only. +The Windows uninstaller removes the Electron user-data directory (browser storage and caches under `%APPDATA%`, nested under the package scope), the `%APPDATA%` product directory, and the updater download cache under `%LOCALAPPDATA%` together with the application, then removes ordinary empty scope directories below `%APPDATA%`. The Harness home (`~/.dsh` or `DSH_HOME`: sessions, settings, credentials, plugins) is never touched, and a `DSH_HOME` published as a Windows environment variable additionally protects any target overlapping it. Silent uninstalls remove the same data; an uninstaller started with `--updated` or `/KEEP_APP_DATA`, as electron-builder does for in-place updates and for replacing an older installation from another directory, retains it. Removal runs through the native helper, which refuses protected Windows folders and paths overlapping the installation or the home, requires a fixed local drive, leaves a linked root or ancestor in place, unlinks reparse points without entering their targets, clears read-only attributes, and keeps deleting siblings after a locked file; residue never stops uninstallation and is not reported. Installation records `InstallLocation` on the Windows uninstall entry as standard inventory metadata; on Windows 11, Uninstall in the Start menu context menu opens the installed-apps list for every Win32 application, and only MSIX packages uninstall directly from there. The uninstaller declares DPI awareness and uses Microsoft YaHei UI for Chinese. Manual uninstall also removes the owned command PATH entry and its ownership values, and removes `dsh://` only when its command still names this installation. `--updated` preserves these registrations; `/KEEP_APP_DATA` alone does not. A stale uninstaller refuses to proceed when the installation record points elsewhere. Registration-cleanup failure stops before application files are removed; close other installers and retry. This behavior is Windows-only. Use `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` to compile isolated English and Chinese fixtures with a per-run scoped package name. Omit `--compile-only` to run the native remover regression and the interactive, silent, `--updated`, `/KEEP_APP_DATA` and `DSH_HOME`-inside-Electron-data checks against seeded data. Compilation does not establish installed-uninstall behavior. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 13661f0590..ae991bc7d8 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -63,7 +63,7 @@ Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform macOS 安装会创建 `/usr/local/bin/dsh`;目录权限需要时,系统会请求管理员认证,不会修改 shell 启动文件。Windows 管理对话框将命令注册到当前用户的 PATH。切换已有命令前会要求确认;修复当前已选中的 Desktop 命令不会重复要求切换确认。macOS 链接会保留并恢复被替换的启动器;Windows 会保留其他 PATH 条目,包括注册前就已存在的条目。若其他命令的 PATH 优先级更高,对话框会显示其位置。移动应用后,macOS 使用“修复”,Windows 从新位置使用“安装”。“移除”不会改动无关安装。 -命令注册是安装 Desktop 后的可选操作。卸载 Desktop 前,请通过**管理 dsh 命令… → 移除**删除其 CLI 注册;应用卸载程序不会移除该注册。更新或卸载 Desktop 前请结束 CLI 命令。CLI 运行时版本随已安装的 Desktop 版本变化。Desktop 插件命令与运行时限制见[内置命令运行时](#bundled-command-runtime)。 +命令注册是安装 Desktop 后的可选操作。Windows 手动卸载会移除属于该安装的 CLI 注册;macOS 卸载前请通过**管理 dsh 命令… → 移除**删除注册。更新或卸载 Desktop 前请结束 CLI 命令。CLI 运行时版本随已安装的 Desktop 版本变化。Desktop 插件命令与运行时限制见[内置命令运行时](#bundled-command-runtime)。 @@ -260,7 +260,7 @@ Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI 在有交互式桌面的 Windows x64 上,从仓库根目录运行 `pnpm --dir apps/desktop run test:installer`,可将小型原生测试载荷接入正式安装配置并执行验证。每次运行使用独立产品身份,依次验证仅英文和仅中文的安装器变体,并根据实际显示的欢迎页按钮选择测试文案。两个变体均安装到私有目录并在测试后卸载;截图和结果保留在 `.desktop-build/installer-tests/` 下。检查包含重启提示窗的进程回收、末尾带分隔符的已登记路径升级,以及磁盘根目录拒绝。绘制器接收 NSIS 主题传入的标题栏颜色;像素检查绘制到离屏位图,并在隐藏进度子窗口时验证。原生绘制检查覆盖 100% 和 200% 缩放下的浅色/深色配色、绘制到 100% 的完成状态、标题栏按钮的悬停/按下颜色和松开触发与取消、最小化恢复后的窗口位置和尺寸,以及 GDI 资源释放;`render-results.log` 中的重绘耗时仅供诊断,不作为 CI 性能阈值。运行生成的 `ui/render-test.exe [interactive-title]` 并指定标题,可在不安装载荷的情况下查看真实进度页。可选的 `--signed` 标志使用[Windows EV 配置](windows-signing/README.zh.md#signing-configuration),在嵌入前对测试程序和辅助库签名;它不会启用更新源。 -Windows 卸载程序会随应用一起删除 Electron 用户数据目录(`%APPDATA%` 下按包作用域嵌套的浏览器存储与缓存)、`%APPDATA%` 下的产品目录,以及 `%LOCALAPPDATA%` 下的更新下载缓存,随后移除 `%APPDATA%` 之下普通且已空的作用域目录。Harness 主目录(`~/.dsh` 或 `DSH_HOME`:会话、设置、凭据、插件)不会被触碰;以 Windows 环境变量发布的 `DSH_HOME` 还会保护所有与其重叠的目标。静默卸载删除相同的数据;以 `--updated` 或 `/KEEP_APP_DATA` 启动的卸载程序保留数据,electron-builder 在原地更新和从其他目录替换旧安装时正是这样启动它。删除通过原生辅助程序执行:它拒绝受保护的 Windows 目录以及与安装目录或主目录重叠的路径,要求固定的本地驱动器,链接的根目录或祖先目录原样保留,遇到重解析点只解除链接而不进入目标,清除只读属性,并在遇到被占用文件后继续删除其余兄弟项;残余不会中止卸载,也不会提示。安装时在 Windows 卸载注册项上记录 `InstallLocation` 作为标准的清单元数据;在 Windows 11 上,开始菜单右键菜单中的“卸载”对所有 Win32 应用都会打开已安装应用列表,只有 MSIX 包能从那里直接卸载。卸载程序声明 DPI 感知,中文使用微软雅黑 UI。此行为仅适用于 Windows。 +Windows 卸载程序会随应用一起删除 Electron 用户数据目录(`%APPDATA%` 下按包作用域嵌套的浏览器存储与缓存)、`%APPDATA%` 下的产品目录,以及 `%LOCALAPPDATA%` 下的更新下载缓存,随后移除 `%APPDATA%` 之下普通且已空的作用域目录。Harness 主目录(`~/.dsh` 或 `DSH_HOME`:会话、设置、凭据、插件)不会被触碰;以 Windows 环境变量发布的 `DSH_HOME` 还会保护所有与其重叠的目标。静默卸载删除相同的数据;以 `--updated` 或 `/KEEP_APP_DATA` 启动的卸载程序保留数据,electron-builder 在原地更新和从其他目录替换旧安装时正是这样启动它。删除通过原生辅助程序执行:它拒绝受保护的 Windows 目录以及与安装目录或主目录重叠的路径,要求固定的本地驱动器,链接的根目录或祖先目录原样保留,遇到重解析点只解除链接而不进入目标,清除只读属性,并在遇到被占用文件后继续删除其余兄弟项;残余不会中止卸载,也不会提示。安装时在 Windows 卸载注册项上记录 `InstallLocation` 作为标准的清单元数据;在 Windows 11 上,开始菜单右键菜单中的“卸载”对所有 Win32 应用都会打开已安装应用列表,只有 MSIX 包能从那里直接卸载。卸载程序声明 DPI 感知,中文使用微软雅黑 UI。手动卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。安装登记指向其他目录时,旧卸载器拒绝继续。注册清理失败会在删除应用文件之前停止;请关闭其他安装程序后重试。此行为仅适用于 Windows。 使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译独立的中英文夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 和 `DSH_HOME` 位于 Electron 数据内的检查。编译本身不能证明已安装卸载行为。 diff --git a/apps/desktop/installer/locales/de_DE.json b/apps/desktop/installer/locales/de_DE.json index 595002b284..3a2d7bfb9c 100644 --- a/apps/desktop/installer/locales/de_DE.json +++ b/apps/desktop/installer/locales/de_DE.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "Details ausblenden", "INSTALLER_EXTRACT_SAVED": "Der vollständige Bericht wurde unter %s gespeichert", "INSTALLER_EXTRACT_UNSAVED": "Der vollständige Bericht konnte nicht gespeichert werden. Verwenden Sie „Fehlerdetails kopieren“, um sie beizubehalten.", - "INSTALLER_EXTRACT_COPIED": "Fehlerdetails wurden in die Zwischenablage kopiert." + "INSTALLER_EXTRACT_COPIED": "Fehlerdetails wurden in die Zwischenablage kopiert.", + "INSTALLER_UNINSTALL_OWNER": "Dieses Deinstallationsprogramm gehört zu einer anderen Installation. Entfernen Sie die aktuelle Installation über Installierte Apps.", + "INSTALLER_UNINSTALL_REGISTRATION": "Die Windows-Befehls- oder Linkregistrierung konnte nicht entfernt werden. Die Anwendungsdateien wurden beibehalten. Schließen Sie andere Installationsprogramme und versuchen Sie es erneut." }, "uninstaller": { "welcome": "Willkommen", diff --git a/apps/desktop/installer/locales/en_US.json b/apps/desktop/installer/locales/en_US.json index 73af2ede5e..b2ed5e8a8c 100644 --- a/apps/desktop/installer/locales/en_US.json +++ b/apps/desktop/installer/locales/en_US.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "Hide details", "INSTALLER_EXTRACT_SAVED": "The full report was saved to %s", "INSTALLER_EXTRACT_UNSAVED": "The full report could not be saved. Use Copy error details to keep it.", - "INSTALLER_EXTRACT_COPIED": "Error details were copied to the clipboard." + "INSTALLER_EXTRACT_COPIED": "Error details were copied to the clipboard.", + "INSTALLER_UNINSTALL_OWNER": "This uninstaller belongs to another installation. Use Installed apps to uninstall the current installation.", + "INSTALLER_UNINSTALL_REGISTRATION": "Windows command or link registration could not be removed. Application files were kept. Close other installers and retry." }, "uninstaller": { "welcome": "Welcome", diff --git a/apps/desktop/installer/locales/es_ES.json b/apps/desktop/installer/locales/es_ES.json index 99e5abe63e..fafcf9dae0 100644 --- a/apps/desktop/installer/locales/es_ES.json +++ b/apps/desktop/installer/locales/es_ES.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "Ocultar detalles", "INSTALLER_EXTRACT_SAVED": "El informe completo se guardó en %s.", "INSTALLER_EXTRACT_UNSAVED": "No se pudo guardar el informe completo. Utilice Copiar detalles del error para conservarlo.", - "INSTALLER_EXTRACT_COPIED": "Los detalles del error se copiaron al portapapeles." + "INSTALLER_EXTRACT_COPIED": "Los detalles del error se copiaron al portapapeles.", + "INSTALLER_UNINSTALL_OWNER": "Este desinstalador pertenece a otra instalación. Use Aplicaciones instaladas para desinstalar la instalación actual.", + "INSTALLER_UNINSTALL_REGISTRATION": "No se pudo eliminar el registro de comandos o enlaces de Windows. Se conservaron los archivos de la aplicación. Cierre los otros instaladores e inténtelo de nuevo." }, "uninstaller": { "welcome": "Bienvenido", diff --git a/apps/desktop/installer/locales/fr_FR.json b/apps/desktop/installer/locales/fr_FR.json index 167922256b..a1c6f0a480 100644 --- a/apps/desktop/installer/locales/fr_FR.json +++ b/apps/desktop/installer/locales/fr_FR.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "Masquer les détails", "INSTALLER_EXTRACT_SAVED": "Le rapport complet a été enregistré dans %s", "INSTALLER_EXTRACT_UNSAVED": "Le rapport complet n'a pas pu être enregistré. Utilisez Copier les détails de l'erreur pour le conserver.", - "INSTALLER_EXTRACT_COPIED": "Les détails de l'erreur ont été copiés dans le presse-papiers." + "INSTALLER_EXTRACT_COPIED": "Les détails de l'erreur ont été copiés dans le presse-papiers.", + "INSTALLER_UNINSTALL_OWNER": "Ce programme de désinstallation appartient à une autre installation. Utilisez Applications installées pour supprimer l’installation actuelle.", + "INSTALLER_UNINSTALL_REGISTRATION": "Impossible de supprimer l’enregistrement des commandes ou des liens Windows. Les fichiers de l’application ont été conservés. Fermez les autres programmes d’installation et réessayez." }, "uninstaller": { "welcome": "Bienvenue", diff --git a/apps/desktop/installer/locales/ja_JP.json b/apps/desktop/installer/locales/ja_JP.json index 72ef1cc641..00f29daef3 100644 --- a/apps/desktop/installer/locales/ja_JP.json +++ b/apps/desktop/installer/locales/ja_JP.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "詳細を非表示", "INSTALLER_EXTRACT_SAVED": "完全なレポートを %s に保存しました", "INSTALLER_EXTRACT_UNSAVED": "完全なレポートを保存できませんでした。「エラーの詳細をコピー」で保存してください。", - "INSTALLER_EXTRACT_COPIED": "エラーの詳細をクリップボードにコピーしました。" + "INSTALLER_EXTRACT_COPIED": "エラーの詳細をクリップボードにコピーしました。", + "INSTALLER_UNINSTALL_OWNER": "このアンインストーラーは別のインストール先用です。「インストールされているアプリ」から現在のアプリを削除してください。", + "INSTALLER_UNINSTALL_REGISTRATION": "Windows のコマンドまたはリンク登録を削除できませんでした。アプリのファイルは保持されています。他のインストーラーを閉じて再試行してください。" }, "uninstaller": { "welcome": "アンインストール ウィザードへようこそ", diff --git a/apps/desktop/installer/locales/pt_BR.json b/apps/desktop/installer/locales/pt_BR.json index 93aacd5dc8..24e756f4f5 100644 --- a/apps/desktop/installer/locales/pt_BR.json +++ b/apps/desktop/installer/locales/pt_BR.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "Ocultar detalhes", "INSTALLER_EXTRACT_SAVED": "O relatório completo foi salvo em %s", "INSTALLER_EXTRACT_UNSAVED": "Não foi possível salvar o relatório completo. Use Copiar detalhes do erro para mantê-lo.", - "INSTALLER_EXTRACT_COPIED": "Os detalhes do erro foram copiados para a área de transferência." + "INSTALLER_EXTRACT_COPIED": "Os detalhes do erro foram copiados para a área de transferência.", + "INSTALLER_UNINSTALL_OWNER": "Este desinstalador pertence a outra instalação. Use Aplicativos instalados para desinstalar a instalação atual.", + "INSTALLER_UNINSTALL_REGISTRATION": "Não foi possível remover o registro de comandos ou links do Windows. Os arquivos do aplicativo foram mantidos. Feche os outros instaladores e tente novamente." }, "uninstaller": { "welcome": "Bem-vindo", diff --git a/apps/desktop/installer/locales/ru_RU.json b/apps/desktop/installer/locales/ru_RU.json index 20345ea37c..c2363f6be8 100644 --- a/apps/desktop/installer/locales/ru_RU.json +++ b/apps/desktop/installer/locales/ru_RU.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "Скрыть детали", "INSTALLER_EXTRACT_SAVED": "Полный отчет сохранен в %s.", "INSTALLER_EXTRACT_UNSAVED": "Полный отчет не удалось сохранить. Используйте Скопировать сведения об ошибке, чтобы сохранить их.", - "INSTALLER_EXTRACT_COPIED": "Подробности об ошибке скопированы в буфер обмена." + "INSTALLER_EXTRACT_COPIED": "Подробности об ошибке скопированы в буфер обмена.", + "INSTALLER_UNINSTALL_OWNER": "Этот деинсталлятор относится к другой установке. Удалите текущую установку через раздел «Установленные приложения».", + "INSTALLER_UNINSTALL_REGISTRATION": "Не удалось удалить регистрацию команд или ссылок Windows. Файлы приложения сохранены. Закройте другие установщики и повторите попытку." }, "uninstaller": { "welcome": "Вас приветствует мастер удаления", diff --git a/apps/desktop/installer/locales/zh_CN.json b/apps/desktop/installer/locales/zh_CN.json index 7951f34340..510dc018b3 100644 --- a/apps/desktop/installer/locales/zh_CN.json +++ b/apps/desktop/installer/locales/zh_CN.json @@ -32,7 +32,9 @@ "INSTALLER_EXTRACT_COLLAPSE": "隐藏详情", "INSTALLER_EXTRACT_SAVED": "完整错误报告已保存到 %s", "INSTALLER_EXTRACT_UNSAVED": "无法保存完整错误报告,请使用“复制错误信息”保留。", - "INSTALLER_EXTRACT_COPIED": "错误信息已复制到剪贴板。" + "INSTALLER_EXTRACT_COPIED": "错误信息已复制到剪贴板。", + "INSTALLER_UNINSTALL_OWNER": "此卸载程序属于另一安装目录。请从“已安装的应用”卸载当前安装。", + "INSTALLER_UNINSTALL_REGISTRATION": "无法清理 Windows 命令或链接注册。应用文件已保留。请关闭其他安装程序后重试。" }, "uninstaller": { "welcome": "欢迎", diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index defdd15923..43f3709202 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -34,3 +34,25 @@ Function un.CleanData StrCpy $UnTarget "$LOCALAPPDATA\${DSH_UPDATER_CACHE_NAME}" Call un.RemoveData FunctionEnd + +; Upgrade replacement retains integrations; KEEP_APP_DATA controls only user data. +!define /ifndef DSH_COMMAND_ENVIRONMENT_KEY "Environment" +!define /ifndef DSH_COMMAND_OWNER_KEY "Software\DeepSeekHarness\Command" +!define /ifndef DSH_PROTOCOL_KEY "Software\Classes\dsh" +Function un.CleanRegistration + ${If} ${isUpdated} + Return + ${EndIf} + InitPluginsDir + File /oname=$PLUGINSDIR\command-path.ps1 "${__FILEDIR__}\..\scripts\command-path.ps1" + File /oname=$PLUGINSDIR\uninstall-registration.ps1 "${__FILEDIR__}\..\scripts\uninstall-registration.ps1" + nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$PLUGINSDIR\uninstall-registration.ps1" -Directory "$INSTDIR" -ExecutableName "${APP_EXECUTABLE_FILENAME}" -EnvironmentKey "${DSH_COMMAND_ENVIRONMENT_KEY}" -OwnerKey "${DSH_COMMAND_OWNER_KEY}" -ProtocolKey "${DSH_PROTOCOL_KEY}"' + Pop $0 + Pop $1 + ${If} $0 != 0 + DetailPrint $1 + MessageBox MB_OK|MB_ICONSTOP "$(INSTALLER_UNINSTALL_REGISTRATION)" /SD IDOK + SetErrorLevel 2 + Quit + ${EndIf} +FunctionEnd diff --git a/apps/desktop/scripts/installer.nsh b/apps/desktop/scripts/installer.nsh index 219522f1ee..18b30d5b7a 100644 --- a/apps/desktop/scripts/installer.nsh +++ b/apps/desktop/scripts/installer.nsh @@ -94,6 +94,7 @@ ManifestDPIAware true !macroend !macro customUnInstall + Call un.CleanRegistration Call un.CleanData !macroend diff --git a/apps/desktop/scripts/test-windows-installer.mjs b/apps/desktop/scripts/test-windows-installer.mjs index 02e356b924..3c354d1393 100644 --- a/apps/desktop/scripts/test-windows-installer.mjs +++ b/apps/desktop/scripts/test-windows-installer.mjs @@ -131,11 +131,12 @@ SectionEnd const strings = join(languageOutput, 'strings.nsh') await writeFile(strings, renderInstallerStrings([locale]), 'utf8') const include = join(languageOutput, 'include.nsh') - await writeFile(include, `!define INSTALLER_BUILD_DIR "${join(output, 'ui')}"\n!define INSTALLER_STRINGS_FILE "${strings}"\n!include "${join(appRoot, 'scripts', 'installer.nsh')}"\n`) + await writeFile(include, `!define DSH_COMMAND_ENVIRONMENT_KEY "Software\\DSHUninstallTests\\${guid}\\CommandEnvironment"\n!define DSH_COMMAND_OWNER_KEY "Software\\DSHUninstallTests\\${guid}\\CommandOwner"\n!define DSH_PROTOCOL_KEY "Software\\Classes\\dsh-test-${guid}"\n!define INSTALLER_BUILD_DIR "${join(output, 'ui')}"\n!define INSTALLER_STRINGS_FILE "${strings}"\n!include "${join(appRoot, 'scripts', 'installer.nsh')}"\n`) await build({ projectDir: appRoot, prepackaged: payload, targets: Platform.WINDOWS.createTarget(['nsis'], Arch.x64), publish: 'never', config: { ...config, productName, extraMetadata: { ...config.extraMetadata, name: packageName }, artifactName: 'installer-test.exe', directories: { output: languageOutput }, - nsis: { ...config.nsis, guid, include, installerLanguages: [language] }, beforeBuild: undefined, afterPack: undefined, afterSign: undefined, artifactBuildCompleted: undefined }, + nsis: { ...config.nsis, guid, include, installerSidebar: join(output, 'ui', 'uninstaller-sidebar.bmp'), + uninstallerSidebar: join(output, 'ui', 'uninstaller-sidebar.bmp'), installerLanguages: [language] }, beforeBuild: undefined, afterPack: undefined, afterSign: undefined, artifactBuildCompleted: undefined }, }) if (process.argv.includes('--compile-only')) continue const result = await execute('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', diff --git a/apps/desktop/scripts/uninstall-registration.ps1 b/apps/desktop/scripts/uninstall-registration.ps1 new file mode 100644 index 0000000000..e30c3b432b --- /dev/null +++ b/apps/desktop/scripts/uninstall-registration.ps1 @@ -0,0 +1,26 @@ +<# Remove only this installation's user registrations. Fail before payload deletion on an unknown outcome. #> +param([Parameter(Mandatory)][string]$Directory, + [string]$ExecutableName = 'DeepSeek Harness.exe', + [string]$EnvironmentKey = 'Environment', + [string]$OwnerKey = 'Software\DeepSeekHarness\Command', + [string]$ProtocolKey = 'Software\Classes\dsh') +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'command-path.ps1') +try { + $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $options = @{ EnvironmentKey=$EnvironmentKey; OwnerKey=$OwnerKey; MachinePath=''; MutexName=('Global\DeepSeekHarness.Command.' + $sid) } + $command = Join-Path $Directory 'resources\runtime\cli\bin' + $state = Invoke-DshCommandPath -Request @{operation='inspect'; directory=$command} @options + [void](Invoke-DshCommandPath -Request @{operation='remove'; directory=$command; expected=$state.fingerprint} @options) + Send-DshCommandEnvironmentChange + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($ProtocolKey + '\shell\open\command') + try { $registered = if ($key) { $key.GetValue('') } else { $null } } + finally { if ($key) { $key.Dispose() } } + $expected = '"' + (Join-Path $Directory $ExecutableName) + '" "%1"' + if ($registered -eq $expected) { + [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($ProtocolKey, $false) + } +} catch { + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/apps/desktop/scripts/windows-directory-installer.d.mts b/apps/desktop/scripts/windows-directory-installer.d.mts index a9be087fe6..5f4863d112 100644 --- a/apps/desktop/scripts/windows-directory-installer.d.mts +++ b/apps/desktop/scripts/windows-directory-installer.d.mts @@ -15,7 +15,7 @@ export function directoryInstallSection(source: string): string export function directoryInstallerExits(source: string): string /** - * Keep user-data removal in the native helper, which refuses unsafe roots and never follows links. + * Retain the original uninstall directory, reject another installation owner, and use native data cleanup. * @param source - Pinned upstream uninstaller source. * @returns Uninstaller with long-path application removal and no upstream RMDir data removal. */ diff --git a/apps/desktop/scripts/windows-directory-installer.mjs b/apps/desktop/scripts/windows-directory-installer.mjs index 8508730b47..247bd11ee3 100644 --- a/apps/desktop/scripts/windows-directory-installer.mjs +++ b/apps/desktop/scripts/windows-directory-installer.mjs @@ -85,12 +85,25 @@ export function installWindowsDirectoryInstaller() { } /** - * Keep user-data removal in the native helper, which refuses unsafe roots and never follows links. + * Retain the original uninstall directory, reject another installation owner, and use native data cleanup. * @param {string} source - Pinned upstream uninstaller source. * @returns {string} Uninstaller with long-path application removal and no upstream RMDir data removal. */ export function directoryUninstaller(source) { - const normalized = source.replaceAll('\r\n', '\n') + let normalized = source.replaceAll('\r\n', '\n') + normalized = replaceOnce(normalized, 'Function un.onInit\n', 'Var dshUninstallDirectory\nFunction un.onInit\n StrCpy $dshUninstallDirectory $INSTDIR\n') + normalized = replaceOnce(normalized, ' !insertmacro initMultiUser', ` !insertmacro initMultiUser + StrCpy $INSTDIR $dshUninstallDirectory + ReadRegStr $R0 SHELL_CONTEXT "\${INSTALL_REGISTRY_KEY}" InstallLocation + \${If} $R0 != "" + GetFullPathName $R0 "$R0\\." + GetFullPathName $R1 "$INSTDIR\\." + \${If} $R0 != $R1 + MessageBox MB_OK|MB_ICONSTOP "$(INSTALLER_UNINSTALL_OWNER)" /SD IDOK + SetErrorLevel 2 + Quit + \${EndIf} + \${EndIf}`) const start = normalized.indexOf(' Var /GLOBAL isDeleteAppData\n') const end = normalized.indexOf(' DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}"', start) if (start < 0 || end < 0) throw new Error('NSIS uninstaller data removal template changed') diff --git a/apps/desktop/tests/expected/windows-uninstall.json b/apps/desktop/tests/expected/windows-uninstall.json index 8a6a99cc57..80737cdce7 100644 --- a/apps/desktop/tests/expected/windows-uninstall.json +++ b/apps/desktop/tests/expected/windows-uninstall.json @@ -1,3 +1,11 @@ { - "cases": ["interactive", "silent", "upgrade", "replaced", "home-inside"] + "cases": [ + "interactive", + "silent", + "upgrade", + "replaced", + "home-inside", + "registration-error", + "self-copy" + ] } diff --git a/apps/desktop/tests/fixtures/command-path.ps1 b/apps/desktop/tests/fixtures/command-path.ps1 index ef6f15930a..5c5aa08829 100644 --- a/apps/desktop/tests/fixtures/command-path.ps1 +++ b/apps/desktop/tests/fixtures/command-path.ps1 @@ -92,6 +92,29 @@ try { Require ((UserPath) -eq ($desktop + ';' + $invalidPath)) 'a notification failure changed the committed PATH' [void](Apply 'remove' $desktop) Require ((UserPath) -eq $invalidPath) 'removal changed invalid user PATH entries' + # Uninstalling A must preserve independently registered B integrations. + $app = Join-Path $Root 'Uninstall A' + $bin = Join-Path $app 'resources\runtime\cli\bin' + New-Item -ItemType Directory -Force $bin | Out-Null + [IO.File]::WriteAllText((Join-Path $bin 'dsh.cmd'), 'fixture') + [void](Apply 'install' $other) + $protocolKey = $keyRoot + '\Protocol' + $foreignCommand = '"' + (Join-Path $other 'DeepSeek Harness.exe') + '" "%1"' + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command') + try { $key.SetValue('', $foreignCommand) } finally { $key.Dispose() } + $helper = Join-Path (Split-Path $Worker) 'uninstall-registration.ps1' + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey + Require ($LASTEXITCODE -eq 0) 'foreign integration cleanup failed' + Require ((State $other).managed) 'uninstall removed foreign command ownership' + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($protocolKey + '\shell\open\command') + try { Require ($key.GetValue('') -eq $foreignCommand) 'uninstall removed foreign protocol' } finally { $key.Dispose() } + [void](Apply 'install' $bin) + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($protocolKey + '\shell\open\command', $true) + try { $key.SetValue('', '"' + (Join-Path $app 'DeepSeek Harness.exe') + '" "%1"') } finally { $key.Dispose() } + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey + Require ($LASTEXITCODE -eq 0) 'owned integration cleanup failed' + Require (-not (State $bin).managed) 'uninstall retained command ownership' + Require (-not (Test-Path -LiteralPath ('HKCU:\' + $protocolKey))) 'uninstall retained protocol' 'WINDOWS_COMMAND_PATH_OK' } finally { [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($keyRoot, $false) diff --git a/apps/desktop/tests/windows-uninstall-smoke.ps1 b/apps/desktop/tests/windows-uninstall-smoke.ps1 index dad594f7c3..8450eef6e1 100644 --- a/apps/desktop/tests/windows-uninstall-smoke.ps1 +++ b/apps/desktop/tests/windows-uninstall-smoke.ps1 @@ -20,6 +20,9 @@ $scopePath = Join-Path $roaming $PackageName.Split('/')[0] $userDataPath = Join-Path $roaming ($PackageName -replace '/', '\') $cachePath = Join-Path $local (($PackageName -replace '[/\\?<>:*|"]', '').ToLowerInvariant() + '-updater') $uninstaller = Join-Path $OutputDirectory 'uninstall-copy.exe' +$environmentKey = "Software\DSHUninstallTests\$RegistryKey\CommandEnvironment" +$ownerKey = "Software\DSHUninstallTests\$RegistryKey\CommandOwner" +$protocolKey = "Software\Classes\dsh-test-$RegistryKey" $process = $null function Wait-Text([string]$Text) { $timer = [Diagnostics.Stopwatch]::StartNew() @@ -62,13 +65,31 @@ try { [IO.File]::WriteAllText((Join-Path $userDataPath 'Local State'), 'chromium profile') [IO.File]::WriteAllText((Join-Path $cachePath 'download.txt'), 'update') Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force + $commandDirectory = Join-Path $installPath 'resources\runtime\cli\bin' + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($environmentKey) + try { $key.SetValue('Path', $commandDirectory + ';C:\Windows', [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $key.Dispose() } + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ownerKey) + try { $key.SetValue('Directory', $commandDirectory); $key.SetValue('RetainedEntries', 0) } finally { $key.Dispose() } + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command') + try { $key.SetValue('', '"' + (Join-Path $installPath ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() } + $launchUninstaller = $uninstaller $arguments = '_?=' + $installPath - if ($mode -in @('silent', 'home-inside')) { $arguments = '/S ' + $arguments } + if ($mode -in @('silent', 'home-inside', 'registration-error')) { $arguments = '/S ' + $arguments } # electron-builder's installUtil.nsh runs an older uninstaller with exactly these flags when replacing it. - if ($mode -eq 'upgrade') { $arguments = '/S /KEEP_APP_DATA --updated /currentuser ' + $arguments } + if ($mode -eq 'upgrade') { + Set-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation -Value ($installPath + '\') + $arguments = '/S /KEEP_APP_DATA --updated /currentuser ' + $arguments } if ($mode -eq 'replaced') { $arguments = '/S /KEEP_APP_DATA /currentuser ' + $arguments } + if ($mode -eq 'self-copy') { + $launchUninstaller = Join-Path $installPath ('Uninstall ' + $ProductName + '.exe') + $arguments = '/S /KEEP_APP_DATA' + } if ($mode -eq 'home-inside') { $env:DSH_HOME = Join-Path $userDataPath 'home' } else { Remove-Item Env:DSH_HOME -ErrorAction SilentlyContinue } - $process = Start-Process -FilePath $uninstaller -ArgumentList $arguments -PassThru -WindowStyle ($(if ($mode -eq 'interactive') { 'Normal' } else { 'Hidden' })) + if ($mode -eq 'registration-error') { + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey, $true) + try { $key.SetValue('Path', 42, [Microsoft.Win32.RegistryValueKind]::DWord) } finally { $key.Dispose() } + } + $process = Start-Process -FilePath $launchUninstaller -ArgumentList $arguments -PassThru -WindowStyle ($(if ($mode -eq 'interactive') { 'Normal' } else { 'Hidden' })) if ($mode -eq 'interactive') { $welcomeText = $copy.welcome $welcome = Wait-Text $welcomeText @@ -79,8 +100,16 @@ try { [void](Wait-Text $finishedText) [InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1)) } + if ($mode -eq 'registration-error') { + if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Registration failure did not stop uninstall' } + $process.Dispose(); $process = $null + if (-not (Test-Path -LiteralPath (Join-Path $installPath ($ProductName + '.exe')))) { throw 'Failed registration cleanup deleted application' } + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey, $true) + try { $key.SetValue('Path', $commandDirectory + ';C:\Windows', [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $key.Dispose() } + $process = Start-Process -FilePath $launchUninstaller -ArgumentList $arguments -PassThru -WindowStyle Hidden + } Wait-Exit - $retained = $mode -in @('upgrade', 'replaced') + $retained = $mode -in @('upgrade', 'replaced', 'self-copy') # A DSH_HOME inside the Electron directory protects that directory (and its scope) but not the other roots. $userDataRetained = $retained -or $mode -eq 'home-inside' if ([IO.File]::ReadAllText((Join-Path $externalPath 'keep.txt')) -ne 'outside data root') { throw 'Cleanup followed a junction into a project' } @@ -89,9 +118,45 @@ try { if ((Test-Path (Join-Path $userDataPath 'Local State')) -ne $userDataRetained) { throw "Electron user data retention failed: $mode" } if ((Test-Path -LiteralPath $scopePath) -ne $userDataRetained) { throw "Package scope directory retention failed: $mode" } if ((Test-Path (Join-Path $cachePath 'download.txt')) -ne $retained) { throw "Update cache retention failed: $mode" } + $integrationsRetained = $mode -eq 'upgrade' + $owner = Get-ItemProperty -LiteralPath ('HKCU:\' + $ownerKey) + if ([bool]$owner.Directory -ne $integrationsRetained) { throw "Command ownership cleanup failed: $mode" } + $path = (Get-ItemProperty -LiteralPath ('HKCU:\' + $environmentKey)).Path + if ($path.Contains($commandDirectory) -ne $integrationsRetained -or -not $path.Contains('C:\Windows')) { throw "PATH cleanup failed: $mode" } + if ((Test-Path -LiteralPath ('HKCU:\' + $protocolKey)) -ne $integrationsRetained) { throw "Protocol cleanup failed: $mode" } Write-Output "passed: $mode" } + # Real replacement publishes B after the old A uninstaller has been retained. + $setup = Start-Process $Installer -ArgumentList ('/S /D=' + $installPath) -PassThru -WindowStyle Hidden + try { if (-not $setup.WaitForExit(30000) -or $setup.ExitCode -ne 0) { throw 'Takeover A setup failed' } } finally { $setup.Dispose() } + Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force + $newPath = Join-Path $OutputDirectory 'Replacement App' + $setup = Start-Process $Installer -ArgumentList ('/S /D=' + $newPath) -PassThru -WindowStyle Hidden + try { if (-not $setup.WaitForExit(30000) -or $setup.ExitCode -ne 0) { throw 'Takeover B setup failed' } } finally { $setup.Dispose() } + $newCommand = Join-Path $newPath 'resources\runtime\cli\bin' + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ownerKey) + try { $key.SetValue('Directory', $newCommand) } finally { $key.Dispose() } + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($environmentKey) + try { $key.SetValue('Path', $newCommand + ';C:\Windows') } finally { $key.Dispose() } + $newProtocol = '"' + (Join-Path $newPath ($ProductName + '.exe')) + '" "%1"' + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command') + try { $key.SetValue('', $newProtocol) } finally { $key.Dispose() } + $process = Start-Process $uninstaller -ArgumentList ('/S /currentuser _?=' + $installPath) -PassThru -WindowStyle Hidden + if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Stale uninstaller was not rejected' } + $process.Dispose(); $process = $null + if (-not (Test-Path -LiteralPath (Join-Path $newPath ($ProductName + '.exe')))) { throw 'Stale uninstaller deleted B' } + $entry = Get-ItemProperty ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey) + if ($entry.InstallLocation.TrimEnd('\') -ne $newPath) { throw 'Stale uninstaller removed B registration' } + if ((Get-ItemProperty ('HKCU:\' + $ownerKey)).Directory -ne $newCommand) { throw 'Stale uninstaller changed B command owner' } + if ((Get-ItemProperty ('HKCU:\' + $environmentKey)).Path -ne ($newCommand + ';C:\Windows')) { throw 'Stale uninstaller changed B PATH' } + if ((Get-Item ('HKCU:\' + $protocolKey + '\shell\open\command')).GetValue('') -ne $newProtocol) { throw 'Stale uninstaller changed B protocol' } + $installPath = $newPath + Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force + $process = Start-Process $uninstaller -ArgumentList ('/S _?=' + $installPath) -PassThru -WindowStyle Hidden + Wait-Exit + Write-Output 'passed: installation takeover' } finally { + foreach ($key in @("Software\DSHUninstallTests\$RegistryKey", $protocolKey)) { [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($key, $false) } Remove-Item Env:DSH_HOME -ErrorAction SilentlyContinue if ($process) { if (-not $process.HasExited) { $process.Kill(); $process.WaitForExit() }; $process.Dispose() } # Only unique test identities below known application-data parents are removed. From 6f6c8f14005c4cc243a33375a8072b09c22e79bf Mon Sep 17 00:00:00 2001 From: winewill Date: Mon, 9 Nov 2026 15:09:28 +0800 Subject: [PATCH 02/90] feat(desktop): support Windows pre-login packaging runners --- .github/workflows/ci-windows.yml | 11 +- apps/desktop/publishing/ci/README.i18n.yaml | 4 +- apps/desktop/publishing/ci/README.md | 2 +- apps/desktop/publishing/ci/README.zh.md | 2 +- .../scripts/run-windows-runner-task.ps1 | 29 +- .../scripts/windows-runner-processes.cs | 50 ++++ .../scripts/windows-runner-scheduler.ps1 | 63 +++++ apps/desktop/scripts/windows-runner-task.ps1 | 110 +++++--- apps/desktop/tests/windows-runner-boot.ps1 | 252 ++++++++++++++++++ .../tests/windows-runner-processes.ps1 | 22 ++ .../desktop/tests/windows-runner-recovery.ps1 | 48 ++++ apps/desktop/tests/windows-runner-task.ps1 | 2 +- apps/desktop/windows-signing/README.i18n.yaml | 7 +- apps/desktop/windows-signing/README.md | 19 +- apps/desktop/windows-signing/README.zh.md | 19 +- 15 files changed, 583 insertions(+), 57 deletions(-) create mode 100644 apps/desktop/scripts/windows-runner-processes.cs create mode 100644 apps/desktop/scripts/windows-runner-scheduler.ps1 create mode 100644 apps/desktop/tests/windows-runner-boot.ps1 create mode 100644 apps/desktop/tests/windows-runner-processes.ps1 create mode 100644 apps/desktop/tests/windows-runner-recovery.ps1 diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index 47ba28681e..692a29379b 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -82,12 +82,21 @@ jobs: - name: Parse Windows runner supervision scripts shell: pwsh run: | - foreach ($path in @('apps/desktop/scripts/windows-runner-task.ps1', 'apps/desktop/scripts/run-windows-runner-task.ps1', 'apps/desktop/scripts/start-windows-packaging-runner.ps1', 'apps/desktop/scripts/windows-runner-network.ps1', 'apps/desktop/scripts/run-windows-runner-network-process.ps1', 'apps/desktop/tests/windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-launcher.ps1', 'apps/desktop/tests/windows-runner-network.ps1', 'apps/desktop/tests/windows-runner-network-process.ps1')) { + foreach ($path in @('apps/desktop/scripts/windows-runner-task.ps1', 'apps/desktop/scripts/windows-runner-scheduler.ps1', 'apps/desktop/tests/windows-runner-boot.ps1', 'apps/desktop/tests/windows-runner-processes.ps1', 'apps/desktop/tests/windows-runner-recovery.ps1', 'apps/desktop/scripts/run-windows-runner-task.ps1', 'apps/desktop/scripts/start-windows-packaging-runner.ps1', 'apps/desktop/scripts/windows-runner-network.ps1', 'apps/desktop/scripts/run-windows-runner-network-process.ps1', 'apps/desktop/tests/windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-launcher.ps1', 'apps/desktop/tests/windows-runner-network.ps1', 'apps/desktop/tests/windows-runner-network-process.ps1')) { $tokens = $null $parseErrors = $null $null = [Management.Automation.Language.Parser]::ParseFile((Join-Path $env:GITHUB_WORKSPACE $path), [ref]$tokens, [ref]$parseErrors) if ($parseErrors.Count) { throw ($parseErrors -join "`n") } } + - name: Verify Windows unattended runner definitions and recovery + shell: pwsh + run: | + ./apps/desktop/tests/windows-runner-boot.ps1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + ./apps/desktop/tests/windows-runner-recovery.ps1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + ./apps/desktop/tests/windows-runner-processes.ps1 + exit $LASTEXITCODE - name: Verify windowless Windows runner launcher shell: pwsh run: ./apps/desktop/tests/windows-runner-launcher.ps1 diff --git a/apps/desktop/publishing/ci/README.i18n.yaml b/apps/desktop/publishing/ci/README.i18n.yaml index d240ef646f..a1d7210bf1 100644 --- a/apps/desktop/publishing/ci/README.i18n.yaml +++ b/apps/desktop/publishing/ci/README.i18n.yaml @@ -15,8 +15,8 @@ en: 37d76f8473b967b7 zh: d211cc54af96672d /desktop-ci-publication/setup-sequence: - en: 2be541ef35a092a4 - zh: 77d87c00deb45758 + en: 4a7458326bb10b10 + zh: e48c2345ebd54aac /desktop-ci-publication/runner-labels-and-queue-diagnosis: en: d2195ee7581b74ec zh: 0b9847afe9a2a373 diff --git a/apps/desktop/publishing/ci/README.md b/apps/desktop/publishing/ci/README.md index 7841dcb406..be001eb216 100644 --- a/apps/desktop/publishing/ci/README.md +++ b/apps/desktop/publishing/ci/README.md @@ -28,7 +28,7 @@ Use this sequence when onboarding a dedicated machine. The deployment operator o 1. Prepare a runner-owned checkout and an external configuration directory. Follow [Windows machine setup and signing](../../windows-signing/README.md#machine-setup) or [macOS runner and signing setup](../../packaging/README.md#macos-actions) for tools, templates and platform credentials. 2. Register the runner using GitHub **Settings → Actions → Runners**, or the organization's runner administration page. Record its exact registered name, grant this repository access to its runner group, and assign the [required labels](#runner-labels). Keep the default labels during registration. -3. Install and start the platform supervisor described in the platform guide. Windows Task Scheduler and the macOS LaunchAgent require the configured user's login; they do not provide unattended startup before login. Confirm both GitHub connectivity and `Listening for Jobs`, then check the runner is online in GitHub. +3. Install and start the platform supervisor described in the platform guide. Windows supports optional Boot tasks for startup before login; its default Interactive task and the macOS LaunchAgent require the configured user's desktop login. Confirm both GitHub connectivity and `Listening for Jobs`, then check the runner is online in GitHub. 4. Complete [machine publication configuration](#machine-setup), the repository's `DESKTOP_PUBLISH_RUNNERS` variable, and the two deployment Environments. The repository administrator owns routing and reviewers; the COS administrator owns bucket configuration and object read/write permissions; production also needs the configured GitHub App. 5. Run a signed Windows or notarized macOS **test** package using [Package and publish](#package-and-publish). Confirm the packaging job used the intended registered runner and retained its files. Dispatch publication from `master` with that run ID and attempt; confirm `prepare` actually starts on the same machine and produces the approval summary. 6. Inspect the summary's environment, version, channel and URLs before approving the test upload. Verify the publication record, public installer download and update feed. Test acceptance does not establish production permissions: provision and approve production separately. Keep the run/attempt and acceptance results for recovery. diff --git a/apps/desktop/publishing/ci/README.zh.md b/apps/desktop/publishing/ci/README.zh.md index 249db63816..9b0bffe7a8 100644 --- a/apps/desktop/publishing/ci/README.zh.md +++ b/apps/desktop/publishing/ci/README.zh.md @@ -28,7 +28,7 @@ description: "在专用 macOS 和 Windows runner 上发布留存的 Desktop 安 1. 准备 runner 专用 checkout 和仓库外的配置目录。按 [Windows 机器与签名配置](../../windows-signing/README.zh.md#machine-setup)或 [macOS runner 与签名配置](../../packaging/README.zh.md#macos-actions)准备工具、模板和平台凭据。 2. 通过 GitHub **Settings → Actions → Runners** 或组织的 runner 管理页面注册 runner。记录准确的注册名称,允许本仓库访问其 runner group,并分配[必需标签](#runner-labels)。注册时保留默认标签。 -3. 按平台指南安装并启动守护任务。Windows 计划任务和 macOS LaunchAgent 都要求配置的用户登录,不能在登录前无人值守启动。确认已连接 GitHub 且出现 `Listening for Jobs`,再检查 GitHub 中 runner 在线。 +3. 按平台指南安装并启动守护任务。Windows 可选 Boot 任务支持登录前启动;默认 Interactive 任务和 macOS LaunchAgent 仍要求配置的用户登录桌面。确认已连接 GitHub 且出现 `Listening for Jobs`,再检查 GitHub 中 runner 在线。 4. 完成[本机发布配置](#machine-setup)、仓库变量 `DESKTOP_PUBLISH_RUNNERS` 和两个部署 Environment。仓库管理员负责路由与审批人;COS 管理员负责桶配置及对象读写权限;production 还需要配置 GitHub App。 5. 按[打包与发布](#package-and-publish)完成一次 Windows 已签名或 macOS 已公证的 **test** 打包。确认打包 job 使用预期的注册 runner 并留存文件。从 `master` 发起发布,填写该 run ID 和 attempt;确认 `prepare` 确实在同一台机器上启动并生成审批摘要。 6. 审核摘要中的环境、版本、频道和 URL 后,再批准测试上传。验证发布记录、公开安装包下载和升级 feed。test 验收不能证明 production 权限可用:production 需独立配置与审批。保留 run/attempt 和验收结果,供故障恢复使用。 diff --git a/apps/desktop/scripts/run-windows-runner-task.ps1 b/apps/desktop/scripts/run-windows-runner-task.ps1 index 56371e970c..51b8890b97 100644 --- a/apps/desktop/scripts/run-windows-runner-task.ps1 +++ b/apps/desktop/scripts/run-windows-runner-task.ps1 @@ -4,17 +4,17 @@ $runnerRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot)).TrimEnd $digest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($runnerRoot.ToUpperInvariant()))) $taskName = 'DSH-Packaging-' + $digest.Substring(0,16) $log = Join-Path $PSScriptRoot ('run-' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ') + '-' + $PID + '.log') +$attemptReserved = $false try { $config = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'config.json') -Raw | ConvertFrom-Json $attemptFile = Join-Path $PSScriptRoot 'attempts.txt' $attempts = [int](Get-Content -LiteralPath $attemptFile -Raw) if ($attempts -lt 0 -or $config.RestartCount -lt 1 -or $config.RestartCount -gt 999) { throw 'Invalid restart budget; reinstall the task.' } if ($attempts -gt $config.RestartCount) { - $null = Disable-ScheduledTask -TaskName $config.TaskName -TaskPath '\' - Set-Content -LiteralPath $log -Value 'Restart budget exhausted. Task disabled; inspect runner logs, fix the cause and run start.' - exit 1 + throw 'Restart budget exhausted; inspect runner logs, fix the cause and run start.' } Set-Content -LiteralPath $attemptFile -Value ($attempts + 1) + $attemptReserved = $true $startup = Join-Path $PSScriptRoot 'start.ps1' if ($config.NetworkRoot) { if (-not (Test-Path -LiteralPath (Join-Path $config.ConfigRoot 'runner-network.json') -PathType Leaf)) { throw 'Owned network supervision requires runner-network.json.' } @@ -27,10 +27,25 @@ try { # An unexpected exit is a task failure even when run.cmd hides the listener's nonzero status; the log retains its code. exit 1 } catch { - # A missing or unwritable counter cannot bound retries; the task name must not depend on readable configuration. - $null = Disable-ScheduledTask -TaskName $taskName -TaskPath '\' - $message = 'Runner task failed: ' + $_.Exception.Message + $failure = $_.Exception.Message + $disposition = 'Scheduled recovery remains bounded by the persisted attempt budget.' + # Stop triggers when the budget is exhausted or an attempt could not be persisted. + if (-not $attemptReserved) { + try { + $scheduler = New-Object -ComObject 'Schedule.Service' + $scheduler.Connect() + $scheduler.GetFolder('\').GetTask($taskName).Enabled = $false + $disposition = 'Task disabled; inspect configuration and attempt storage before starting.' + } catch { + # A limited task account may lack permission to change its scheduler registration. + $disposition = 'Task disable failed; an administrator must disable its triggers. No runner was launched.' + } + } + $message = 'Runner task failed: ' + $failure + ' ' + $disposition [Console]::Error.WriteLine($message) - Add-Content -LiteralPath $log -Value $message + try { Add-Content -LiteralPath $log -Value $message } catch { + # The launcher captures stderr independently when the runner log is unavailable. + [Console]::Error.WriteLine('Runner log unavailable: ' + $_.Exception.Message) + } exit 1 } diff --git a/apps/desktop/scripts/windows-runner-processes.cs b/apps/desktop/scripts/windows-runner-processes.cs new file mode 100644 index 0000000000..171f17798a --- /dev/null +++ b/apps/desktop/scripts/windows-runner-processes.cs @@ -0,0 +1,50 @@ +// Toolhelp snapshots expose parent IDs without the WMI namespace permissions required by CIM. +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; + +public static class DshRunnerProcesses +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct Entry + { + public uint Size, Usage, ProcessId; + public UIntPtr DefaultHeapId; + public uint ModuleId, Threads, ParentProcessId; + public int Priority; + public uint Flags; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string Name; + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processId); + [DllImport("kernel32.dll", EntryPoint = "Process32FirstW", SetLastError = true)] + private static extern bool First(IntPtr snapshot, ref Entry entry); + [DllImport("kernel32.dll", EntryPoint = "Process32NextW", SetLastError = true)] + private static extern bool Next(IntPtr snapshot, ref Entry entry); + [DllImport("kernel32.dll")] + private static extern bool CloseHandle(IntPtr handle); + + // These parent IDs select handles to await; taskkill retains termination authority over the live tree. + public static Dictionary ReadParents() + { + IntPtr snapshot = CreateToolhelp32Snapshot(2, 0); + if (snapshot == new IntPtr(-1)) throw new Win32Exception(Marshal.GetLastWin32Error()); + try + { + var result = new Dictionary(); + var entry = new Entry { Size = (uint)Marshal.SizeOf(typeof(Entry)) }; + bool found = First(snapshot, ref entry); + while (found) + { + result.Add((int)entry.ProcessId, (int)entry.ParentProcessId); + found = Next(snapshot, ref entry); + } + int error = Marshal.GetLastWin32Error(); + if (error != 18) throw new Win32Exception(error); + return result; + } + finally { CloseHandle(snapshot); } + } +} diff --git a/apps/desktop/scripts/windows-runner-scheduler.ps1 b/apps/desktop/scripts/windows-runner-scheduler.ps1 new file mode 100644 index 0000000000..a9db21c3c6 --- /dev/null +++ b/apps/desktop/scripts/windows-runner-scheduler.ps1 @@ -0,0 +1,63 @@ +# Build an unregistered runner task. Credentials are supplied only to the scheduler at installation. +function New-WindowsRunnerTaskDefinition($Scheduler, [string]$Sid, [string]$RunnerRoot, [string]$PowerShell, [int]$RestartMinutes, [ValidateSet('Interactive','Boot')][string]$StartupMode = 'Boot') { + $definition = $Scheduler.NewTask(0) + $definition.RegistrationInfo.Description = "DSH packaging runner: $RunnerRoot; owner: $Sid" + $definition.Principal.UserId = $Sid + $definition.Principal.LogonType = if ($StartupMode -eq 'Boot') { 1 } else { 3 } # Password or InteractiveToken. + $definition.Principal.RunLevel = 0 # TASK_RUNLEVEL_LUA: the job does not inherit installer elevation. + $definition.Settings.Priority = 4 + $definition.Settings.Enabled = $false + $definition.Settings.MultipleInstances = 2 # TASK_INSTANCES_IGNORE_NEW + $definition.Settings.ExecutionTimeLimit = 'PT0S' + $definition.Settings.DisallowStartIfOnBatteries = $false + $definition.Settings.StopIfGoingOnBatteries = $false + if ($StartupMode -eq 'Boot') { + $null = $definition.Triggers.Create(8) # TASK_TRIGGER_BOOT + } else { + $logon = $definition.Triggers.Create(9) # TASK_TRIGGER_LOGON + $logon.UserId = $Sid + } + $recovery = $definition.Triggers.Create(1) # TASK_TRIGGER_TIME + $recovery.StartBoundary = (Get-Date).AddMinutes($RestartMinutes).ToString('yyyy-MM-ddTHH:mm:ss') + $recovery.Repetition.Interval = "PT${RestartMinutes}M" + $execution = $definition.Actions.Create(0) # TASK_ACTION_EXEC + $execution.Path = Join-Path $RunnerRoot 'dsh-task/launcher.exe' + $execution.Arguments = '"' + $PowerShell + '"' + $execution.WorkingDirectory = $RunnerRoot + return $definition +} + +# Prompt locally and submit once; credential-bearing COM failures must not reach diagnostics. +function Register-WindowsRunnerBootTask($Scheduler, [string]$TaskName, $Definition, [string]$Sid, [string]$RunAs) { + $credential = Get-Credential -UserName $RunAs -Message 'Windows account password for unattended runner startup (not the signing Token PIN)' + if (-not $credential -or $credential.UserName -ne $RunAs -or $credential.Password.Length -eq 0) { + throw 'Credential entry cancelled or account changed; no task was registered.' + } + try { + # COM avoids putting a plaintext password in command arguments or cmdlet parameter logging. + $null = $Scheduler.GetFolder('\').RegisterTaskDefinition($TaskName, $Definition, 2, $Sid, $credential.GetNetworkCredential().Password, 1, "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$Sid)") + } catch { + # Registration may have committed before an error reached this caller. + throw 'Boot task registration failed; registration outcome is unconfirmed. Inspect Task Scheduler, batch-logon policy and account credentials locally before retrying.' + } finally { + $credential = $null + } +} + +# Validate machine-owned preparation data before credentials or scheduler registration. +function Assert-WindowsRunnerBootConfiguration($Config, [string]$Sid, [string]$RunnerRoot, [string]$TaskName) { + if ($Config.StartupMode -ne 'Boot' -or $Config.AccountSid -ne $Sid -or $Config.RunnerRoot -ne $RunnerRoot -or $Config.TaskName -ne $TaskName) { + throw 'Prepared Boot configuration does not match RunAs and RunnerRoot; prepare again as the runner account.' + } + if (($Config.RestartMinutes -isnot [int] -and $Config.RestartMinutes -isnot [long]) -or $Config.RestartMinutes -lt 1 -or $Config.RestartMinutes -gt 1440 -or $Config.PowerShell -isnot [string] -or $Config.PowerShell -notmatch '^[A-Za-z]:[\\/]' -or -not (Test-Path -LiteralPath $Config.PowerShell -PathType Leaf) -or -not (Test-Path -LiteralPath (Join-Path $RunnerRoot 'dsh-task/launcher.exe') -PathType Leaf)) { + throw 'Prepared Boot startup files or restart interval are invalid; prepare again as the runner account.' + } +} + +# Missing tasks are distinct from denied or unavailable scheduler access. +function Get-WindowsRunnerTask($Scheduler, [string]$TaskName) { + try { return $Scheduler.GetFolder('\').GetTask($TaskName) } catch { + if ($_.Exception.GetBaseException().HResult -eq -2147024894) { return $null } + throw + } +} diff --git a/apps/desktop/scripts/windows-runner-task.ps1 b/apps/desktop/scripts/windows-runner-task.ps1 index e940eef988..d3f6303898 100644 --- a/apps/desktop/scripts/windows-runner-task.ps1 +++ b/apps/desktop/scripts/windows-runner-task.ps1 @@ -1,18 +1,21 @@ -# Manage a registered packaging runner in the current user's interactive Windows session. +# Prepare runner-owned startup files; an administrator registers Boot tasks for that account. [CmdletBinding()] param( - [Parameter(Mandatory=$true)][ValidateSet('install','start','stop','status','uninstall')][string]$Action, + [Parameter(Mandatory=$true)][ValidateSet('install','register-boot','start','stop','status','uninstall')][string]$Action, [Parameter(Mandatory=$true)][string]$RunnerRoot, [string]$ConfigRoot, [string]$NetworkRoot, + [ValidateSet('Interactive','Boot')][string]$StartupMode = 'Interactive', + [string]$RunAs, [ValidateRange(1,1440)][int]$RestartMinutes = 1, [ValidateRange(1,999)][int]$RestartCount = 10 ) $ErrorActionPreference = 'Stop' if (-not $IsWindows) { throw 'This command requires PowerShell 7 on Windows.' } -if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) { - throw 'ConfigRoot, NetworkRoot, RestartMinutes and RestartCount apply only to install; reinstall to change them.' +if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','StartupMode','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) { + throw 'Configuration and retry options apply only to install; reinstall to change them.' } +if ($Action -ne 'register-boot' -and $PSBoundParameters.ContainsKey('RunAs')) { throw 'RunAs applies only to register-boot.' } if ($RunnerRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'RunnerRoot must be an absolute local directory.' } $RunnerRoot = [IO.Path]::GetFullPath($RunnerRoot).TrimEnd('\','/') if (-not (Test-Path -LiteralPath (Join-Path $RunnerRoot '.runner') -PathType Leaf)) { throw 'Register the runner before managing its task.' } @@ -23,11 +26,45 @@ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value $digest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($RunnerRoot.ToUpperInvariant()))) $taskName = 'DSH-Packaging-' + $digest.Substring(0,16) $serviceDir = Join-Path $RunnerRoot 'dsh-task' -$task = Get-ScheduledTask -TaskPath '\' | Where-Object TaskName -eq $taskName -if ($task -and $task.Description -ne "DSH packaging runner: $RunnerRoot; owner: $sid") { throw 'Task ownership differs; inspect it in Task Scheduler.' } +if ($Action -eq 'register-boot') { + if (-not $RunAs) { throw 'Boot registration requires -RunAs with the prepared runner account.' } + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + if (-not ([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + throw 'Boot registration requires an elevated PowerShell; the runner account remains limited.' + } + $sid = ([Security.Principal.NTAccount]::new($RunAs)).Translate([Security.Principal.SecurityIdentifier]).Value + if ($sid -in @('S-1-5-18','S-1-5-19','S-1-5-20') -or $sid.EndsWith('-500')) { throw 'Use a dedicated runner account, not a built-in service or Administrator account.' } +} +. (Join-Path $PSScriptRoot 'windows-runner-scheduler.ps1') +$scheduler = New-Object -ComObject 'Schedule.Service' +$scheduler.Connect() +$task = Get-WindowsRunnerTask $scheduler $taskName +if ($task -and $task.Definition.RegistrationInfo.Description -ne "DSH packaging runner: $RunnerRoot; owner: $sid") { throw 'Task ownership differs; inspect it in Task Scheduler.' } + +if ($Action -in @('install','register-boot')) { + if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' } + # Pause dispatch before migration; never overwrite a live startup snapshot. + foreach ($process in @(Get-Process | Where-Object { $_.ProcessName -in @('Runner.Listener','Runner.Worker') })) { + if (-not $process.Path -or $process.Path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { + throw 'A runner process is active or its location is unreadable. Pause dispatch and stop its supervisor before installing.' + } + } + if (Test-Path -LiteralPath (Join-Path $RunnerRoot '.service')) { throw 'A native runner service is configured; inspect and remove it before task migration.' } + if ((Test-Path -LiteralPath $serviceDir) -and ((Get-Item -LiteralPath $serviceDir).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Task directory cannot be a link.' } +} +if ($Action -eq 'register-boot') { + # This elevated path only registers a limited task; it never executes runner-owned files. + $configFile = Join-Path $serviceDir 'config.json' + if ((Get-Item -LiteralPath $configFile).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Task configuration cannot be a link.' } + $config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json + Assert-WindowsRunnerBootConfiguration $config $sid $RunnerRoot $taskName + $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $config.PowerShell $config.RestartMinutes + Register-WindowsRunnerBootTask $scheduler $taskName $definition $sid $RunAs + Write-Output "Registered disabled Boot task $taskName. Run start as the runner account. Logs: $serviceDir" + exit 0 +} if ($Action -eq 'install') { - if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' } if (-not $ConfigRoot -or $ConfigRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'Install requires an absolute ConfigRoot.' } $ConfigRoot = [IO.Path]::GetFullPath($ConfigRoot) $pwsh = Join-Path $PSHOME 'pwsh.exe' @@ -56,46 +93,46 @@ if ($Action -eq 'install') { foreach ($helper in @('windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $PSScriptRoot $helper) -Destination (Join-Path $serviceDir $helper) } - @{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8 + @{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount; StartupMode = $StartupMode; AccountSid = $sid; PowerShell = $pwsh; RestartMinutes = $RestartMinutes } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8 Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0' - $execution = New-ScheduledTaskAction -Execute $launcher -Argument ('"' + $pwsh + '"') -WorkingDirectory $RunnerRoot - $principal = New-ScheduledTaskPrincipal -UserId $sid -LogonType Interactive -RunLevel Limited - $trigger = @( - (New-ScheduledTaskTrigger -AtLogOn -User $sid), - (New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes($RestartMinutes) -RepetitionInterval (New-TimeSpan -Minutes $RestartMinutes)) - ) - $settings = New-ScheduledTaskSettingsSet -Priority 4 -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries - $settings.Enabled = $false - $null = Register-ScheduledTask -TaskName $taskName -TaskPath '\' -Action $execution -Principal $principal -Trigger $trigger -Settings $settings -Description "DSH packaging runner: $RunnerRoot; owner: $sid" + if ($StartupMode -eq 'Boot') { + Write-Output "Prepared Boot startup for account $sid. An administrator must run register-boot with RunnerRoot and RunAs; no task was registered." + exit 0 + } + $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $pwsh $RestartMinutes 'Interactive' + $null = $scheduler.GetFolder('\').RegisterTaskDefinition($taskName, $definition, 2, $sid, $null, 3, $null) Write-Output "Installed disabled task $taskName. Run start while logged in; reboot requires desktop login. Logs: $serviceDir" exit 0 } if (-not $task) { throw 'Task is not installed for this runner directory.' } switch ($Action) { 'status' { - $info = Get-ScheduledTaskInfo -InputObject $task + $bootTrigger = $false + for ($index = 1; $index -le $task.Definition.Triggers.Count; $index++) { + if ($task.Definition.Triggers.Item($index).Type -eq 8) { $bootTrigger = $true } + } $launches = [int](Get-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Raw) $config = Get-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Raw | ConvertFrom-Json - [pscustomobject]@{ TaskName = $taskName; State = $task.State; LastRunTime = $info.LastRunTime; LastTaskResult = $info.LastTaskResult; Launches = $launches; RemainingLaunches = [Math]::Max(0, 1 + $config.RestartCount - $launches); Logs = $serviceDir } + [pscustomobject]@{ TaskName = $taskName; State = @('Unknown','Disabled','Queued','Ready','Running')[[int]$task.State]; Account = $task.Definition.Principal.UserId; LogonType = @('None','Password','S4U','Interactive','Group','ServiceAccount','InteractiveOrPassword')[[int]$task.Definition.Principal.LogonType]; BootTrigger = $bootTrigger; LastRunTime = $task.LastRunTime; LastTaskResult = $task.LastTaskResult; Launches = $launches; RemainingLaunches = [Math]::Max(0, 1 + $config.RestartCount - $launches); Logs = $serviceDir } } 'start' { - if ($task.State -eq 'Running') { Write-Output "$taskName is already running."; break } + if ($task.State -eq 4) { Write-Output "$taskName is already running."; break } Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0' - $null = Enable-ScheduledTask -InputObject $task - Start-ScheduledTask -InputObject $task + $task.Enabled = $true + $null = $task.Run($null) Write-Output "Start requested for $taskName. Verify Connected to GitHub and Listening for Jobs in $serviceDir." } 'stop' { # Operators pause workflow dispatch first; this local check cannot reserve an idle GitHub runner. - $workers = Get-CimInstance Win32_Process -Filter "Name = 'Runner.Worker.exe'" + $workers = Get-Process | Where-Object ProcessName -eq 'Runner.Worker' foreach ($worker in $workers) { - if (-not $worker.ExecutablePath -or $worker.ExecutablePath.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { + if (-not $worker.Path -or $worker.Path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'A runner job is active or its location is unreadable. Wait for completion before stopping.' } } - $null = Disable-ScheduledTask -InputObject $task - $task = Get-ScheduledTask -TaskName $taskName -TaskPath '\' - if ($task.State -eq 'Running') { + $task.Enabled = $false + $task = Get-WindowsRunnerTask $scheduler $taskName + if ($task.State -eq 4) { $recordFile = Join-Path $serviceDir 'process.json' if (-not (Test-Path -LiteralPath $recordFile)) { throw 'Running task process identity is unavailable. Automatic starts are disabled; inspect the task before stopping it.' } $record = Get-Content -LiteralPath $recordFile -Raw | ConvertFrom-Json @@ -104,13 +141,14 @@ switch ($Action) { throw 'Running task process identity is unavailable. Automatic starts are disabled; inspect the task before stopping it.' } # Parent IDs can be reused; this snapshot supplies wait handles, not termination authority. - $processes = @(Get-CimInstance Win32_Process) + if (-not ('DshRunnerProcesses' -as [type])) { Add-Type -Path (Join-Path $PSScriptRoot 'windows-runner-processes.cs') } + $processes = [DshRunnerProcesses]::ReadParents() $ownedIds = [Collections.Generic.HashSet[int]]::new() $null = $ownedIds.Add($owner.Id) do { $added = $false - foreach ($process in $processes) { - if ($ownedIds.Contains([int]$process.ParentProcessId) -and $ownedIds.Add([int]$process.ProcessId)) { $added = $true } + foreach ($process in $processes.GetEnumerator()) { + if ($ownedIds.Contains([int]$process.Value) -and $ownedIds.Add([int]$process.Key)) { $added = $true } } } while ($added) $owned = @(foreach ($ownedId in $ownedIds) { Get-Process -Id $ownedId -ErrorAction SilentlyContinue }) @@ -120,19 +158,19 @@ switch ($Action) { if (-not $process.WaitForExit(30000)) { throw 'Runner task child remains alive; inspect it before restarting.' } } } - Stop-ScheduledTask -InputObject $task + $task.Stop(0) $deadline = [DateTime]::UtcNow.AddSeconds(30) do { - $state = (Get-ScheduledTask -TaskName $taskName -TaskPath '\').State - if ($state -ne 'Running') { break } + $state = (Get-WindowsRunnerTask $scheduler $taskName).State + if ($state -ne 4) { break } Start-Sleep -Milliseconds 200 } while ([DateTime]::UtcNow -lt $deadline) - if ($state -eq 'Running') { throw 'Task remains running; inspect its processes before further maintenance.' } + if ($state -eq 4) { throw 'Task remains running; inspect its processes before further maintenance.' } Write-Output "Stopped and disabled $taskName. Run start to enable automatic starts again." } 'uninstall' { - if ($task.State -ne 'Disabled') { throw 'Stop the task before uninstalling.' } - Unregister-ScheduledTask -InputObject $task -Confirm:$false + if ($task.State -ne 1) { throw 'Stop the task before uninstalling.' } + $scheduler.GetFolder('\').DeleteTask($taskName, 0) Write-Output "Uninstalled $taskName. Registration, configuration and logs remain in $RunnerRoot." } } diff --git a/apps/desktop/tests/windows-runner-boot.ps1 b/apps/desktop/tests/windows-runner-boot.ps1 new file mode 100644 index 0000000000..4d9bf7b06d --- /dev/null +++ b/apps/desktop/tests/windows-runner-boot.ps1 @@ -0,0 +1,252 @@ +# Inspect real Task Scheduler definitions without registering tasks, passwords, GitHub or signing hardware. +$ErrorActionPreference = 'Stop' +if (-not $IsWindows) { throw 'Requires PowerShell 7 on Windows.' } +. (Join-Path $PSScriptRoot '../scripts/windows-runner-scheduler.ps1') +$scheduler = New-Object -ComObject 'Schedule.Service' +$scheduler.Connect() +$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value +$root = Join-Path ([IO.Path]::GetTempPath()) ('dsh-boot-definition-' + [guid]::NewGuid().ToString('N')) +$null = New-Item -ItemType Directory -Path $root +$runner = Join-Path $root 'runner with spaces' +$null = New-Item -ItemType Directory -Path $runner +Set-Content -LiteralPath (Join-Path $runner '.runner') -Value '{}' +$pwsh = Join-Path $PSHOME 'pwsh.exe' +foreach ($minutes in @(1, 7, 1440)) { + $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh $minutes + [xml]$xml = $definition.XmlText + $ns = [Xml.XmlNamespaceManager]::new($xml.NameTable) + $ns.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task') + function Read-Value([string]$Path) { return $xml.SelectSingleNode('/t:Task/' + $Path, $ns).InnerText } + if ((Read-Value 't:Principals/t:Principal/t:UserId') -ne $sid -or + (Read-Value 't:Principals/t:Principal/t:LogonType') -ne 'Password' -or + (Read-Value 't:Principals/t:Principal/t:RunLevel') -ne 'LeastPrivilege') { throw 'Boot account or logon configuration differs.' } + if ($xml.SelectNodes('/t:Task/t:Triggers/t:BootTrigger', $ns).Count -ne 1 -or + $xml.SelectNodes('/t:Task/t:Triggers/t:LogonTrigger', $ns).Count -ne 0 -or + (Read-Value 't:Triggers/t:TimeTrigger/t:Repetition/t:Interval') -ne "PT${minutes}M") { throw 'Boot or recovery trigger differs.' } + if ((Read-Value 't:Settings/t:Priority') -ne '4' -or + (Read-Value 't:Settings/t:Enabled') -ne 'false' -or + (Read-Value 't:Settings/t:MultipleInstancesPolicy') -ne 'IgnoreNew' -or + (Read-Value 't:Settings/t:ExecutionTimeLimit') -ne 'PT0S' -or + (Read-Value 't:Settings/t:DisallowStartIfOnBatteries') -ne 'false' -or + (Read-Value 't:Settings/t:StopIfGoingOnBatteries') -ne 'false') { throw 'Boot task lifetime settings differ.' } + if ((Read-Value 't:Actions/t:Exec/t:Command') -ne (Join-Path $runner 'dsh-task/launcher.exe') -or + (Read-Value 't:Actions/t:Exec/t:Arguments') -ne ('"' + $pwsh + '"') -or + (Read-Value 't:Actions/t:Exec/t:WorkingDirectory') -ne $runner) { throw 'Boot task bypasses the existing launcher.' } + # Round-trip through the scheduler's parser, without storing or enabling a task. + $parsed = $scheduler.NewTask(0) + $parsed.XmlText = $definition.XmlText + $parsedSid = ([Security.Principal.NTAccount]::new($parsed.Principal.UserId)).Translate([Security.Principal.SecurityIdentifier]).Value + if ($parsedSid -ne $sid -or $parsed.Settings.Enabled) { throw 'Definition did not round-trip.' } +} +$interactive = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh 1 'Interactive' +[xml]$interactiveXml = $interactive.XmlText +$interactiveNs = [Xml.XmlNamespaceManager]::new($interactiveXml.NameTable) +$interactiveNs.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task') +if ($interactive.Principal.LogonType -ne 3 -or $interactive.Principal.RunLevel -ne 0 -or $interactive.Settings.Priority -ne 4 -or $interactive.Settings.Enabled -or $interactiveXml.SelectNodes('/t:Task/t:Triggers/t:LogonTrigger/t:UserId', $interactiveNs).Count -ne 1 -or $interactiveXml.SelectSingleNode('/t:Task/t:Triggers/t:LogonTrigger/t:UserId', $interactiveNs).InnerText -ne $sid -or $interactiveXml.SelectNodes('/t:Task/t:Triggers/t:BootTrigger', $interactiveNs).Count -ne 0) { throw 'Interactive task defaults changed.' } +if (Get-WindowsRunnerTask $scheduler ('DSH-absent-' + [guid]::NewGuid().ToString('N'))) { throw 'Missing task lookup returned a task.' } +$deniedFolder = [pscustomobject]@{} +$deniedFolder | Add-Member ScriptMethod GetTask { param($Name); throw [Runtime.InteropServices.COMException]::new('Injected scheduler access denied', -2147024891) } +$deniedScheduler = [pscustomobject]@{ Folder=$deniedFolder } +$deniedScheduler | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder } +$denied = $false +try { $null = Get-WindowsRunnerTask $deniedScheduler 'fixture' } catch { $denied = $true } +if (-not $denied) { throw 'Denied task lookup was treated as a missing task.' } +$manager = Join-Path $PSScriptRoot '../scripts/windows-runner-task.ps1' +function Reject-Options([string[]]$Options, [string]$Message) { + $output = & $pwsh -NoProfile -NonInteractive -File $manager -RunnerRoot $runner @Options 2>&1 | Out-String + if ($LASTEXITCODE -eq 0 -or -not $output.Contains($Message)) { throw "Expected rejection: $Message`n$output" } + if (Test-Path -LiteralPath (Join-Path $runner 'dsh-task')) { throw 'Rejected options wrote a startup snapshot.' } +} +Reject-Options @('-Action','register-boot') 'requires -RunAs' +Reject-Options @('-Action','install','-StartupMode','Boot','-RunAs','NT AUTHORITY\SYSTEM') 'RunAs applies only to register-boot' +Reject-Options @('-Action','install','-RunAs','unused') 'RunAs applies only to register-boot' +Reject-Options @('-Action','start','-StartupMode','Boot') 'apply only to install' +$processProbe = Join-Path $root 'process-probe.ps1' +@' +param([string]$Manager, [string]$Runner, [switch]$Unreadable) +$ErrorActionPreference = 'Stop' +function Get-Process { + param($Name,$ErrorAction) + [pscustomobject]@{ ProcessName = 'Runner.Worker'; Path = if ($Unreadable) { $null } else { Join-Path $Runner 'bin/Runner.Worker.exe' } } +} +& $Manager -Action install -RunnerRoot $Runner +'@ | Set-Content -LiteralPath $processProbe +foreach ($unreadable in @($false, $true)) { + $probeOptions = if ($unreadable) { @('-Unreadable') } else { @() } + $output = & $pwsh -NoProfile -NonInteractive -File $processProbe -Manager $manager -Runner $runner @probeOptions 2>&1 | Out-String + if ($LASTEXITCODE -eq 0 -or -not $output.Contains('A runner process is active or its location is unreadable')) { throw "Live-process installation guard failed: $output" } + if (Test-Path -LiteralPath (Join-Path $runner 'dsh-task')) { throw 'Live-process rejection wrote a startup snapshot.' } +} +Set-Content -LiteralPath (Join-Path $runner '.service') -Value 'fixture' +Reject-Options @('-Action','install','-ConfigRoot',$root) 'native runner service is configured' + +Remove-Item -LiteralPath (Join-Path $runner '.service') + +# Exercise preparation with isolated toolchain/network and process-inventory fixtures. +$fixture = Join-Path $root 'scripts' +$null = New-Item -ItemType Directory -Path $fixture +foreach ($name in @('windows-runner-task.ps1','windows-runner-scheduler.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { + Copy-Item -LiteralPath (Join-Path $PSScriptRoot "../scripts/$name") -Destination $fixture +} +Set-Content -LiteralPath (Join-Path $fixture 'start-windows-packaging-runner.ps1') -Value 'param($RunnerRoot,$ConfigRoot,[switch]$CheckOnly); if (-not $CheckOnly) { throw "Unexpected runner launch" }; exit 0' +$prepareProbe = Join-Path $root 'prepare-probe.ps1' +@' +param($Manager,$Runner,$ConfigRoot) +$ErrorActionPreference = 'Stop' +function Get-Process { param($Name,$ErrorAction); return @() } +& $Manager -Action install -StartupMode Boot -RunnerRoot $Runner -ConfigRoot $ConfigRoot -RestartMinutes 7 -RestartCount 3 +'@ | Set-Content -LiteralPath $prepareProbe +& $pwsh -NoProfile -NonInteractive -File $prepareProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -ConfigRoot $root +if ($LASTEXITCODE -ne 0) { throw 'Boot preparation failed.' } +$configFile = Join-Path $runner 'dsh-task/config.json' +$config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json +if ($config.StartupMode -ne 'Boot' -or $config.AccountSid -ne $sid -or $config.RestartMinutes -ne 7 -or $config.RestartCount -ne 3) { throw 'Preparation lost account or recovery settings.' } +if (Get-WindowsRunnerTask $scheduler $config.TaskName) { throw 'Preparation registered a task.' } +Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName +$expectedTaskName = $config.TaskName +foreach ($field in @('StartupMode','AccountSid','RunnerRoot','TaskName','PowerShell','RestartMinutes')) { + $saved = $config.$field + try { + foreach ($invalid in @($null, 'invalid')) { + $config.$field = $invalid + $failure = $null + try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $expectedTaskName } catch { $failure = $_ } + if (-not $failure) { throw "Invalid $field was accepted." } + } + } finally { $config.$field = $saved } +} +foreach ($invalid in @(0, 1441, 1.5, '7')) { + $config.RestartMinutes = $invalid + $failure = $null + try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName } catch { $failure = $_ } + if (-not $failure) { throw 'Invalid restart interval was accepted.' } +} +$config.RestartMinutes = 7 +$registrationProbe = Join-Path $root 'register-probe.ps1' +@' +param($Manager,$Runner,$RunAs,$Result) +$ErrorActionPreference = 'Stop' +function Get-Process { param($Name,$ErrorAction); return @() } +$nativeScheduler = New-Object -ComObject 'Schedule.Service' +$nativeScheduler.Connect() +$folder = [pscustomobject]@{} +$folder | Add-Member ScriptMethod GetTask { param($Name); return $null } +$folder | Add-Member ScriptMethod RegisterTaskDefinition { + param($Name,$Definition,$Flags,$User,$Password,$Logon,$Sddl) + if ($Password -ne 'fake-only-never-authenticated' -or $Flags -ne 2 -or $Logon -ne 1) { throw 'Invalid registration transport.' } + @{ Name=$Name; User=$User; Sddl=$Sddl; Xml=$Definition.XmlText } | ConvertTo-Json | Set-Content -LiteralPath $Result +} +$fake = [pscustomobject]@{ Native=$nativeScheduler; Folder=$folder } +$fake | Add-Member ScriptMethod Connect {} +$fake | Add-Member ScriptMethod NewTask { param($Flags); return $this.Native.NewTask($Flags) } +$fake | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder } +function New-Object { param($ComObject); if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }; return $fake } +function Get-Credential { param($UserName,$Message); return [Management.Automation.PSCredential]::new($UserName,(ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force)) } +& $Manager -Action register-boot -RunnerRoot $Runner -RunAs $RunAs +'@ | Set-Content -LiteralPath $registrationProbe +$registrationResult = Join-Path $root 'registration.json' +$account = [Security.Principal.WindowsIdentity]::GetCurrent().Name +$elevated = ([Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +$registrationOutput = & $pwsh -NoProfile -NonInteractive -File $registrationProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -RunAs $account -Result $registrationResult 2>&1 | Out-String +if ($elevated -and -not $sid.EndsWith('-500')) { + if ($LASTEXITCODE -ne 0) { throw "Boot registration entry failed: $registrationOutput" } + $submitted = Get-Content -LiteralPath $registrationResult -Raw | ConvertFrom-Json + if ($submitted.User -ne $sid -or $submitted.Name -ne $config.TaskName -or $submitted.Sddl -notlike "*(A;;GA;;;$sid)*") { throw 'Registration lost prepared account or management access.' } +} else { + if ($LASTEXITCODE -eq 0 -or (Test-Path -LiteralPath $registrationResult)) { throw 'Boot registration accepted an unsupported installer context.' } +} +if (Get-WindowsRunnerTask $scheduler $config.TaskName) { throw 'Isolated registration created a real task.' } +# Exercise management against a registered-task substitute, without CIM or real scheduler mutation. +$managementProbe = Join-Path $root 'manage-probe.ps1' +@' +param($Manager,$Runner,$Operation,$Result) +$ErrorActionPreference = 'Stop' +. (Join-Path (Split-Path $Manager) 'windows-runner-scheduler.ps1') +$native = New-Object -ComObject 'Schedule.Service' +$native.Connect() +$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value +$definition = New-WindowsRunnerTaskDefinition $native $sid $Runner (Join-Path $PSHOME 'pwsh.exe') 1 +$script:enabled = $Operation -ne 'uninstall' +$task = [pscustomobject]@{ Definition=$definition; State=$(if ($script:enabled) { 3 } else { 1 }); LastRunTime=[DateTime]::MinValue; LastTaskResult=0 } +$task | Add-Member ScriptProperty Enabled { return $script:enabled } { + param($Value) + $script:enabled = $Value + Add-Content -LiteralPath $Result -Value "enabled=$Value" + if (-not $Value -and $this.State -ne 4) { $this.State = 1 } +} +$task | Add-Member ScriptMethod Run { param($Parameters); Add-Content -LiteralPath $Result -Value 'run'; $this.State=4 } +$task | Add-Member ScriptMethod Stop { param($Flags); Add-Content -LiteralPath $Result -Value 'stop'; $this.State=1 } +$folder = [pscustomobject]@{ Task=$task } +$folder | Add-Member ScriptMethod GetTask { param($Name); return $this.Task } +$folder | Add-Member ScriptMethod DeleteTask { param($Name,$Flags); Add-Content -LiteralPath $Result -Value 'delete' } +$fake = [pscustomobject]@{ Folder=$folder } +$fake | Add-Member ScriptMethod Connect {} +$fake | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder } +function New-Object { param($ComObject); if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }; return $fake } +function Get-Process { param($Name,$ErrorAction); return @() } +$status = & $Manager -Action $Operation -RunnerRoot $Runner +if ($Operation -eq 'status') { $status | ConvertTo-Json | Set-Content -LiteralPath $Result } +'@ | Set-Content -LiteralPath $managementProbe +foreach ($operation in @('status','start','stop','uninstall')) { + $resultFile = Join-Path $root "manage-$operation.txt" + & $pwsh -NoProfile -NonInteractive -File $managementProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -Operation $operation -Result $resultFile + if ($LASTEXITCODE -ne 0) { throw "Management failed: $operation" } + $result = Get-Content -LiteralPath $resultFile -Raw + if ($operation -eq 'status') { + $status = $result | ConvertFrom-Json + if (-not $status.BootTrigger -or $status.LogonType -ne 'Password' -or $status.State -ne 'Ready' -or $status.RemainingLaunches -ne 4) { throw 'Status lost startup mode or recovery budget.' } + } else { + $expected = switch ($operation) { 'start' { "enabled=True`nrun" }; 'stop' { "enabled=False`nstop" }; 'uninstall' { 'delete' } } + if ($result.Replace("`r`n","`n").Trim() -ne $expected) { throw "Unexpected management effects: $operation" } + } +} +Remove-Item -LiteralPath (Join-Path $runner 'dsh-task/launcher.exe') +$failure = $null +try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName } catch { $failure = $_ } +if (-not $failure) { throw 'Missing launcher was accepted.' } + +# Only the credential dialog and registration transport are replaced; no account authentication occurs. +$script:credentialResult = $null +$script:registrationCalls = 0 +$script:registrationFails = $false +$script:registrationMismatch = $false +function Get-Credential { param($UserName, $Message); return $script:credentialResult } +$fakeFolder = [pscustomobject]@{} +$fakeFolder | Add-Member ScriptMethod RegisterTaskDefinition { + param($Name, $Definition, $Flags, $User, $Password, $Logon, $Sddl) + $script:registrationCalls++ + if ($Name -ne 'fixture' -or $Flags -ne 2 -or $User -ne $sid -or $Logon -ne 1 -or $Sddl -ne "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$sid)" -or $Password -ne 'fake-only-never-authenticated') { + $script:registrationMismatch = $true; throw 'Unexpected registration request.' + } + if ($script:registrationFails) { throw 'fake-only-never-authenticated' } +} +$fakeScheduler = [pscustomobject]@{ Folder = $fakeFolder } +$fakeScheduler | Add-Member ScriptMethod GetFolder { param($Path); if ($Path -ne '\') { throw 'Unexpected task folder.' }; return $this.Folder } +function Reject-Registration([string]$Message) { + $failure = $null + try { Register-WindowsRunnerBootTask $fakeScheduler 'fixture' $definition $sid 'fixture-user' } catch { $failure = $_ } + if (-not $failure -or -not $failure.Exception.Message.Contains($Message) -or $failure.ToString().Contains('fake-only-never-authenticated')) { + throw 'Registration failure was not contained or exposed the fake credential.' + } +} +try { + Reject-Registration 'Credential entry cancelled' + $script:credentialResult = [Management.Automation.PSCredential]::new('other-user', (ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force)) + Reject-Registration 'Credential entry cancelled' + $script:credentialResult = [Management.Automation.PSCredential]::new('fixture-user', [Security.SecureString]::new()) + Reject-Registration 'Credential entry cancelled' + if ($script:registrationCalls -ne 0) { throw 'Invalid credential input reached registration.' } + $script:credentialResult = [Management.Automation.PSCredential]::new('fixture-user', (ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force)) + Register-WindowsRunnerBootTask $fakeScheduler 'fixture' $definition $sid 'fixture-user' + if ($script:registrationCalls -ne 1) { throw 'Registration was not submitted once.' } + $script:registrationFails = $true + Reject-Registration 'registration outcome is unconfirmed' + if ($script:registrationMismatch) { throw 'Unexpected registration request.' } + if ($script:registrationCalls -ne 2) { throw 'Failed registration retried authentication.' } +} finally { + Remove-Item Function:Get-Credential + $script:credentialResult = $null +} +Remove-Item -LiteralPath $root -Recurse -Force +Write-Output "PASS: boot/password/least-privilege definition, recovery settings, duplicate policy, launcher reuse, XML round-trip, invalid options, credential cancellation and single-attempt registration failure containment. No task registered." +exit 0 diff --git a/apps/desktop/tests/windows-runner-processes.ps1 b/apps/desktop/tests/windows-runner-processes.ps1 new file mode 100644 index 0000000000..18958374c6 --- /dev/null +++ b/apps/desktop/tests/windows-runner-processes.ps1 @@ -0,0 +1,22 @@ +# Verify native parent IDs with an owned process and await its exit; no scheduler or runner is used. +$ErrorActionPreference = 'Stop' +if (-not $IsWindows) { throw 'Requires PowerShell 7 on Windows.' } +Add-Type -Path (Join-Path $PSScriptRoot '../scripts/windows-runner-processes.cs') +$info = [Diagnostics.ProcessStartInfo]::new((Join-Path $PSHOME 'pwsh.exe')) +$info.UseShellExecute = $false +$info.CreateNoWindow = $true +foreach ($argument in @('-NoProfile','-NonInteractive','-Command','Start-Sleep -Seconds 120')) { $info.ArgumentList.Add($argument) } +$child = [Diagnostics.Process]::Start($info) +try { + $parents = [DshRunnerProcesses]::ReadParents() + if (-not $parents.ContainsKey($PID) -or -not $parents.ContainsKey($child.Id) -or $parents[$child.Id] -ne $PID) { + throw 'Native process snapshot did not identify the owned child and parent.' + } +} finally { + try { + if (-not $child.HasExited) { $child.Kill($true) } + if (-not $child.WaitForExit(30000)) { throw 'Owned process did not exit.' } + } finally { $child.Dispose() } +} +Write-Output 'PASS: native process ancestry and owned child teardown without CIM.' +exit 0 diff --git a/apps/desktop/tests/windows-runner-recovery.ps1 b/apps/desktop/tests/windows-runner-recovery.ps1 new file mode 100644 index 0000000000..6703ba069b --- /dev/null +++ b/apps/desktop/tests/windows-runner-recovery.ps1 @@ -0,0 +1,48 @@ +# Isolated supervisor failures; no scheduler registration, GitHub or signing hardware. +$ErrorActionPreference = 'Stop' +$root = Join-Path ([IO.Path]::GetTempPath()) ('runner-recovery-' + [guid]::NewGuid().ToString('N')) +$null = New-Item -ItemType Directory $root +$source = Get-Content (Join-Path $PSScriptRoot '../scripts/run-windows-runner-task.ps1') -Raw +try { + foreach ($case in @('log-failure','counter-failure','exhausted','child-failure','disable-failure')) { + $dir = Join-Path $root $case + $null = New-Item -ItemType Directory $dir + @{RestartCount=1;TaskName='fake';RunnerRoot=$dir;ConfigRoot=$dir} | ConvertTo-Json | Set-Content (Join-Path $dir 'config.json') + Set-Content (Join-Path $dir 'attempts.txt') $(if($case -in @('exhausted','disable-failure')){'2'}else{'0'}) + Set-Content (Join-Path $dir 'start.ps1') 'Set-Content (Join-Path $PSScriptRoot "launched") yes; exit 7' + $mocks = @' +function New-Object { + param($ComObject) + if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' } + $task = [pscustomobject]@{} + $task | Add-Member ScriptProperty Enabled { return $true } { param($Value); [IO.File]::WriteAllText((Join-Path $PSScriptRoot 'disabled'),'yes') } + $folder = [pscustomobject]@{ Task = $task } + $folder | Add-Member ScriptMethod GetTask { param($Name); return $this.Task } + $scheduler = [pscustomobject]@{ Folder = $folder } + $scheduler | Add-Member ScriptMethod Connect {} + $scheduler | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder } + return $scheduler +} +'@ + if ($case -eq 'log-failure') { $mocks += "`nfunction Add-Content { throw 'Injected log storage unavailable' }" } + if ($case -eq 'counter-failure') { $mocks += "`nfunction Set-Content { throw 'Injected counter storage unavailable' }" } + if ($case -eq 'disable-failure') { $mocks = "function New-Object { throw 'Injected access denied' }" } + Set-Content (Join-Path $dir 'run.ps1') ($mocks + "`n" + $source) + $output = & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -File (Join-Path $dir 'run.ps1') 2>&1 | Out-String + if ($LASTEXITCODE -ne 1) { throw "$case must fail visibly" } + $disabled = Test-Path (Join-Path $dir 'disabled') + if ($disabled -ne ($case -in @('counter-failure','exhausted'))) { throw "$case unexpected task disposition" } + if ($case -in @('log-failure','child-failure') -and [int](Get-Content (Join-Path $dir 'attempts.txt')) -ne 1) { throw 'Attempt must be persisted before launch' } + if ($case -in @('log-failure','child-failure') -and -not (Test-Path (Join-Path $dir 'launched'))) { throw 'Allowed attempt did not execute the child.' } + if ($case -eq 'child-failure' -and -not ((Get-Content (Join-Path $dir 'run-*.log') -Raw) -match 'exited with code 7')) { throw 'Child failure code was not retained.' } + if ($case -eq 'log-failure' -and $output -notmatch 'Runner log unavailable') { throw 'Missing stderr fallback' } + if ($case -in @('exhausted','disable-failure','counter-failure') -and (Test-Path (Join-Path $dir 'launched'))) { throw 'A blocked attempt launched a runner' } + if ($case -eq 'disable-failure') { + if ($output -notmatch 'Restart budget exhausted' -or $output -notmatch 'Task disable failed') { throw 'Missing original failure or scheduler disposition' } + if ([int](Get-Content (Join-Path $dir 'attempts.txt')) -ne 2) { throw 'Exhausted budget changed' } + } + Write-Output "PASS: $case" + } +} finally { + if ([IO.Path]::GetFullPath($root).StartsWith([IO.Path]::GetTempPath(),[StringComparison]::OrdinalIgnoreCase)) { Remove-Item -LiteralPath $root -Recurse -Force } +} diff --git a/apps/desktop/tests/windows-runner-task.ps1 b/apps/desktop/tests/windows-runner-task.ps1 index a01a90c3f4..654beaaeee 100644 --- a/apps/desktop/tests/windows-runner-task.ps1 +++ b/apps/desktop/tests/windows-runner-task.ps1 @@ -7,7 +7,7 @@ $source = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../scripts')) $runner = Join-Path $root 'runner with spaces' $null = New-Item -ItemType Directory -Path $runner Set-Content -LiteralPath (Join-Path $runner '.runner') -Value '{}' -foreach ($file in @('windows-runner-task.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $source $file) -Destination $root } +foreach ($file in @('windows-runner-task.ps1','windows-runner-scheduler.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-processes.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $source $file) -Destination $root } $manager = Join-Path $root 'windows-runner-task.ps1' @' param([string]$RunnerRoot, [string]$ConfigRoot, [switch]$CheckOnly) diff --git a/apps/desktop/windows-signing/README.i18n.yaml b/apps/desktop/windows-signing/README.i18n.yaml index c1354ca9e8..7f2b2d0036 100644 --- a/apps/desktop/windows-signing/README.i18n.yaml +++ b/apps/desktop/windows-signing/README.i18n.yaml @@ -21,8 +21,11 @@ en: bb889e9514678d1c zh: 48cbec1e907d6a2b /windows-signing-and-runner-operations/machine-setup-and-runner-startup/supervised-startup: - en: cada81c15a20ecc2 - zh: 80b7a4af7b1e0e5d + en: f4fcb23be1f3df4a + zh: f3699f0a64a9b94b +/windows-signing-and-runner-operations/machine-setup-and-runner-startup/unattended-windows-startup: + en: def90f6dad81c4c4 + zh: a1cf176f59d38176 /windows-signing-and-runner-operations/machine-setup-and-runner-startup/optional-network-dependency: en: 60f34f8637b3c252 zh: 805435964ab20263 diff --git a/apps/desktop/windows-signing/README.md b/apps/desktop/windows-signing/README.md index f7b48b9b3e..ca156e8171 100644 --- a/apps/desktop/windows-signing/README.md +++ b/apps/desktop/windows-signing/README.md @@ -38,14 +38,27 @@ Run `pwsh -NoProfile -File apps/desktop/scripts/setup-windows-packaging.ps1 -Roo For the complete registration, label, routing and approval sequence, start with [CI publication setup](../publishing/ci/README.md#setup-sequence). The task installer requires the Windows .NET Framework 4.5+ compiler at `%SystemRoot%/Microsoft.NET/Framework64/v4.0.30319/csc.exe`. It compiles a GUI executable into `runner/dsh-task/launcher.exe`; this executable starts PowerShell with no console and waits for it to exit. The output and errors of `run.ps1` itself go to uniquely named `launcher-*.out.log` and `launcher-*.err.log`; filenames include UTC time, PID and a random identifier. Launcher failures disable periodic starts, including failures before the retry budget can be read. Task result `2` indicates launcher failure; `3` means its error log could not be written; `4` means disabling the task also failed and an operator must disable it in Task Scheduler. After the direct child exits, output draining is limited to five seconds. A timeout returns `5` with a `launcher-*.drain.log` diagnostic: output may be incomplete, but periodic recovery continues within the existing restart budget. Descendant processes may outlive the exited runner; draining logs does not terminate them. The recorded stop target is the launcher process, so stop includes the launcher and its descendants. Normal runner output remains in `run-*.log`. -Run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot -ConfigRoot /packaging` as the runner's Windows user, using its installed PowerShell 7. The installer checks the environment and copies startup scripts into `runner/dsh-task`; registration, tools and secrets remain separate. It registers a disabled, limited-permission interactive Task Scheduler task without storing an account password. Task priority 4 gives the runner and its children normal CPU, I/O and memory priority; the scheduler default 7 lowers all three and slows dependency installation. Existing tasks retain their settings: while the runner is idle, stop, uninstall and reinstall the task before starting it again. For `-Action start` or `-Action status`, pass only `-RunnerRoot`; configuration and retry options apply only to installation. The task starts after this user's desktop login, including after reboot, and stops on logout. It does not provide unattended boot or unlock a signing Token. +Run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot -ConfigRoot /packaging` as the runner's Windows user, using its installed PowerShell 7. The installer checks the environment and copies startup scripts into `runner/dsh-task`; registration, tools and secrets remain separate. It registers a disabled, limited-permission interactive Task Scheduler task without storing an account password. Task priority 4 gives the runner and its children normal CPU, I/O and memory priority; the scheduler default 7 lowers all three and slows dependency installation. Existing tasks retain their settings: while the runner is idle, stop, uninstall and reinstall the task before starting it again. For `-Action start` or `-Action status`, pass only `-RunnerRoot`; configuration and retry options apply only to installation. The task starts after this user's desktop login, including after reboot, and stops on logout. This default `Interactive` mode requires desktop login; neither startup mode unlocks a signing Token. -The task permits one instance and has no execution time limit. A repeating trigger checks every `-RestartMinutes` minutes (default `1`) and restarts an exited launcher, including an unexpected zero exit. The persisted budget permits the initial launch plus `-RestartCount` restarts (default `10`) between explicit starts. Every desktop login also consumes this budget; `status` shows the remaining launches. After the budget is exhausted, login alone cannot restart the runner. Starting an already running task does not reset the budget. Missing or invalid budget/configuration files disable automatic starts until repaired. GitHub's launcher owns runner updates; task recovery does not rerun a failed workflow or clear signing interlocks. After retries are exhausted, inspect `runner/dsh-task/run-*.log`, the runner's `_diag` logs and `status`, correct the cause, then run `start`. A running task alone does not prove connectivity: verify `Connected to GitHub` and `Listening for Jobs`, then verify assignment in Actions. Both `run-*.log` and `launcher-*.log` are retained for operator-managed cleanup. +The task permits one instance and has no execution time limit. A repeating trigger checks every `-RestartMinutes` minutes (default `1`) and restarts an exited launcher, including an unexpected zero exit. The persisted budget permits the initial launch plus `-RestartCount` restarts (default `10`) between explicit starts. Every trigger that launches the task also consumes this budget; `status` shows the remaining launches. After the budget is exhausted, login or reboot alone cannot restart the runner. Starting an already running task does not reset the budget. Missing or invalid budget/configuration files prevent runner launches and request task disabling. If scheduler access is denied, an administrator must disable the triggers. Failures after reserving an attempt retain bounded recovery; unavailable runner logs fall back to launcher stderr. GitHub's launcher owns runner updates; task recovery does not rerun a failed workflow or clear signing interlocks. After retries are exhausted, inspect `runner/dsh-task/run-*.log`, the runner's `_diag` logs and `status`, correct the cause, then run `start`. A running task alone does not prove connectivity: verify `Connected to GitHub` and `Listening for Jobs`, then verify assignment in Actions. Both `run-*.log` and `launcher-*.log` are retained for operator-managed cleanup. -Before maintenance, pause new workflow dispatch and wait for the runner to become idle. `-Action stop` refuses an active worker for this runner, disables future starts and stops its task process tree; the local check cannot prevent a concurrent GitHub assignment. `-Action uninstall` requires a stopped, disabled task and retains registration, configuration and logs. Pulling repository changes does not update the installed copy. To upgrade it, record the original -ConfigRoot, optional -NetworkRoot and retry settings, then run `stop`, `uninstall`, `install` with those settings, and `start` from the updated checkout. Confirm listening and job assignment again. When migrating a manually launched runner, stop its existing launcher only after it is idle, then start the task; never run both launchers together. +Before maintenance, pause new workflow dispatch and wait for the runner to become idle. `-Action stop` refuses an active worker for this runner, disables future starts and stops its task process tree; the local check cannot prevent a concurrent GitHub assignment. `-Action uninstall` requires a stopped, disabled task and retains registration, configuration and logs. Pulling repository changes does not update the installed copy. To upgrade it, record the startup mode, original -ConfigRoot, optional -NetworkRoot and retry settings, then run `stop`, `uninstall`, `install` with those settings, and `start` from the updated checkout; Boot mode also requires `register-boot` before `start`. Confirm listening and job assignment again. When migrating a manually launched runner, stop its existing launcher only after it is idle, then start the task; never run both launchers together. Operators can run `pwsh -NoProfile -File apps/desktop/tests/windows-runner-task.ps1` on Windows to exercise installation, console-free initial launch and automatic recovery, duplicate-start prevention, stop, child-process teardown, containment of startup/logging failures and uninstall against an isolated fake runner. This opt-in test creates a temporary task and retains diagnostic files; it does not contact GitHub or access signing hardware. `pwsh -NoProfile -File apps/desktop/tests/windows-runner-launcher.ps1` checks the GUI executable, child console absence, exit status, diagnostic output and bounded draining with an inherited writer without Task Scheduler; Windows CI runs it. Real-machine acceptance additionally checks an idle runner coming online without a visible Terminal window, an Actions job being assigned, and login after an operator-approved reboot. Signed packaging and logout/reboot acceptance require separate operator verification. +### Unattended Windows startup + +Use `Boot` mode when the runner must accept jobs before desktop login. Prepare files under the existing runner account, which may remain a standard user. Use a separate elevated administrator session only for registration. Run the administrator command from a trusted checkout; it reads prepared configuration but does not execute the runner-owned launcher or preflight. The task grants its runner account management access and always runs with limited privileges and priority 4. Management uses Task Scheduler COM and native process snapshots instead of requiring CIM namespace access. + +1. Pause workflow dispatch, wait for idle and stop any existing launcher. For an installed task, run `stop` then `uninstall` as its owner; retain configuration, caches and signing interlocks. Installation rejects active or unreadable runner processes and a native runner `.service` registration. +2. As the runner account, run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -StartupMode Boot -RunnerRoot -ConfigRoot /packaging`, retaining any `-NetworkRoot` and retry options. This checks tools/network, compiles the launcher and prepares the startup snapshot; it does not register a task. +3. In an elevated administrator PowerShell, run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action register-boot -RunnerRoot -RunAs `. The account must match preparation. Enter its Windows password in the local prompt, not a Hello PIN or signing PIN. Registration submits credentials once and creates a disabled Password/AtStartup task. On failure, inspect Task Scheduler before retrying because registration may have committed; no automatic authentication retry occurs. +4. As the runner account, run the same manager with `-Action start -RunnerRoot `, then `-Action status`. Check the account, `LogonType=Password`, `BootTrigger=True`, remaining launches and listener logs. To return to login-only startup, stop and uninstall the task, then install without `-StartupMode Boot` and start. + +The administrator must ensure batch-logon permission, no overriding deny policy, and runner access to its tools, private configuration, caches and logs. Account password changes require re-registration. Network dependencies, disk access and signing hardware must be available before login; prevent sleep during service hours. There is no desktop auto-login configuration. Recovery cannot clear a signing interlock or retry failed hardware signing. + +Windows CI checks task XML, preparation, invalid configuration, credential cancellation and single-attempt registration with isolated substitutes; it does not register a real Boot task. Deployment operators must validate registration with separate administrator/standard accounts, task management permissions and a reboot without desktop login, followed by actual job assignment and a signed package on each new machine. Existing machine results do not qualify a new startup snapshot. + ### Optional network dependency Without `runner-network.json` in `ConfigRoot`, startup retains its scrubbed direct-network behavior. To configure a network dependency, create that operator-owned JSON file outside the checkout with exactly `proxyUrl`, `noProxy`, `serviceName`, `probeUrl`, `attempts`, `timeoutSeconds` and `retrySeconds`. The first four fields are strings; the three budgets are integers from 1 through 60. Use an empty `proxyUrl` for direct access and an empty `serviceName` when no Windows service owns the dependency. URLs must use HTTP(S) without credentials, queries or fragments; the proxy URL cannot include a path. Startup applies `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and `NODE_USE_ENV_PROXY` after environment scrubbing, then requires a successful Node HEAD probe before admitting the runner. Service readiness checks never start or stop a Windows service. diff --git a/apps/desktop/windows-signing/README.zh.md b/apps/desktop/windows-signing/README.zh.md index 0b7ff50cd2..55804faac9 100644 --- a/apps/desktop/windows-signing/README.zh.md +++ b/apps/desktop/windows-signing/README.zh.md @@ -38,14 +38,27 @@ description: "配置和维护 Windows 打包 runner、签名凭据、EV Token 完整的注册、标签、路由和审批配置顺序见 [CI 发布配置](../publishing/ci/README.zh.md#setup-sequence)。任务安装器需要 Windows .NET Framework 4.5+ 编译器,路径为 `%SystemRoot%/Microsoft.NET/Framework64/v4.0.30319/csc.exe`。它将 GUI 可执行文件编译到 `runner/dsh-task/launcher.exe`;该程序不分配控制台地启动 PowerShell,并等待其退出。`run.ps1` 自身的输出和错误分别写入名称唯一的 `launcher-*.out.log` 和 `launcher-*.err.log`,文件名包含 UTC 时间、PID 和随机标识。启动器失败时禁用周期启动,包括尚未读取重试预算时发生的失败。任务结果 `2` 表示启动器失败,`3` 表示无法写入错误日志,`4` 表示禁用任务也失败,需要操作者在计划任务中手动禁用。直接子进程退出后,最多等待五秒排空输出;超时返回 `5`,将诊断写入 `launcher-*.drain.log`:输出可能不完整,但周期恢复仍受原有重试预算约束。后代进程可能在 runner 退出后继续运行;日志排空不会终止它们。记录的停止目标是启动器进程,因此 stop 覆盖启动器及其后代。正常 runner 输出仍保存在 `run-*.log`。 -以 runner 的 Windows 用户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot -ConfigRoot /packaging`,使用该机器安装的 PowerShell 7。安装器检查环境,并将启动脚本复制到 `runner/dsh-task`;注册、工具和凭据仍单独管理。它注册一个初始禁用、权限受限的交互式计划任务,不保存账户密码。任务优先级 4 让 runner 及子进程使用普通 CPU、I/O 和内存优先级;计划任务默认值 7 会降低三者的优先级,使依赖安装变慢。已有任务保留原设置:在 runner 空闲时停止、卸载并重新安装任务,再启动。执行 `-Action start` 或 `-Action status` 时只传 `-RunnerRoot`;配置目录及重试选项仅适用于安装。任务在该用户登录桌面后启动,重启后也需要登录,注销时停止。它不提供无人值守开机,也不解锁签名 Token。 +以 runner 的 Windows 用户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot -ConfigRoot /packaging`,使用该机器安装的 PowerShell 7。安装器检查环境,并将启动脚本复制到 `runner/dsh-task`;注册、工具和凭据仍单独管理。它注册一个初始禁用、权限受限的交互式计划任务,不保存账户密码。任务优先级 4 让 runner 及子进程使用普通 CPU、I/O 和内存优先级;计划任务默认值 7 会降低三者的优先级,使依赖安装变慢。已有任务保留原设置:在 runner 空闲时停止、卸载并重新安装任务,再启动。执行 `-Action start` 或 `-Action status` 时只传 `-RunnerRoot`;配置目录及重试选项仅适用于安装。任务在该用户登录桌面后启动,重启后也需要登录,注销时停止。默认的 `Interactive` 模式需要桌面登录;两种启动模式都不会解锁签名 Token。 -任务只允许一个实例,且没有执行时限。周期触发器每隔 `-RestartMinutes` 分钟(默认 `1`)检查一次,并恢复已退出的启动器,包括意外的零退出码。持久预算允许首次启动及 `-RestartCount` 次重启(默认 `10`),直到再次显式启动。每次桌面登录也会消耗预算,`status` 显示剩余启动次数;预算耗尽后,仅登录不能重启 runner。对正在运行的任务执行 start 不会重置预算。预算或配置文件缺失、无效时,自动启动会禁用,需修复后恢复。GitHub 启动器负责 runner 更新;任务恢复不会重跑失败的 workflow,也不会清除签名互锁。重试耗尽后,检查 `runner/dsh-task/run-*.log`、runner 的 `_diag` 日志和 `status`,修复原因后运行 `start`。任务运行不等于连接成功:确认出现 `Connected to GitHub` 和 `Listening for Jobs`,再到 Actions 确认任务分配。`run-*.log` 和 `launcher-*.log` 均保留,由操作者管理清理。 +任务只允许一个实例,且没有执行时限。周期触发器每隔 `-RestartMinutes` 分钟(默认 `1`)检查一次,并恢复已退出的启动器,包括意外的零退出码。持久预算允许首次启动及 `-RestartCount` 次重启(默认 `10`),直到再次显式启动。每次触发器启动任务也会消耗预算,`status` 显示剩余启动次数;预算耗尽后,仅登录或重启机器不能重启 runner。对正在运行的任务执行 start 不会重置预算。预算或配置文件缺失、无效时阻止 runner 启动并请求禁用任务;若计划任务访问被拒绝,管理员需禁用触发器。预留启动次数后发生的失败保留有界恢复;runner 日志不可用时回退到启动器 stderr。GitHub 启动器负责 runner 更新;任务恢复不会重跑失败的 workflow,也不会清除签名互锁。重试耗尽后,检查 `runner/dsh-task/run-*.log`、runner 的 `_diag` 日志和 `status`,修复原因后运行 `start`。任务运行不等于连接成功:确认出现 `Connected to GitHub` 和 `Listening for Jobs`,再到 Actions 确认任务分配。`run-*.log` 和 `launcher-*.log` 均保留,由操作者管理清理。 -维护前暂停新 workflow 的触发,等待 runner 空闲。`-Action stop` 在该 runner 存在活跃 worker 时拒绝停止,否则禁用后续启动并停止任务进程树;本地检查无法阻止 GitHub 同时分配任务。`-Action uninstall` 要求任务已停止并禁用,保留注册、配置和日志。拉取仓库更新不会更新已安装的副本。升级时先记录原来的 -ConfigRoot、可选的 -NetworkRoot 和重试设置,再从更新后的 checkout 依次执行 `stop`、`uninstall`、携带原设置的 `install` 和 `start`,最后重新确认监听与 job 分配。迁移手动启动的 runner 时,只在空闲后停止原启动器,再启动计划任务;不要同时运行两个启动器。 +维护前暂停新 workflow 的触发,等待 runner 空闲。`-Action stop` 在该 runner 存在活跃 worker 时拒绝停止,否则禁用后续启动并停止任务进程树;本地检查无法阻止 GitHub 同时分配任务。`-Action uninstall` 要求任务已停止并禁用,保留注册、配置和日志。拉取仓库更新不会更新已安装的副本。升级时先记录启动模式、原来的 -ConfigRoot、可选的 -NetworkRoot 和重试设置,再从更新后的 checkout 依次执行 `stop`、`uninstall`、携带原设置的 `install` 和 `start`;Boot 模式还需在 `start` 前执行 `register-boot`,最后重新确认监听与 job 分配。迁移手动启动的 runner 时,只在空闲后停止原启动器,再启动计划任务;不要同时运行两个启动器。 操作者可在 Windows 上运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-task.ps1`,使用隔离的假 runner 验证安装、无控制台的首次启动与自动恢复、防止重复启动、停止、子进程退出、启动/日志失败时的禁用处理和卸载。此显式运行的测试创建临时任务并保留诊断文件,不连接 GitHub 或访问签名硬件。`pwsh -NoProfile -File apps/desktop/tests/windows-runner-launcher.ps1` 无需计划任务,检查 GUI 可执行文件、子进程无控制台、退出状态、诊断输出以及存在继承管道写端时的有界排空;Windows CI 会执行该测试。真实机器验收还需检查空闲 runner 上线且不出现 Terminal 窗口、Actions job 分配,以及经操作者批准的重启后登录。签名打包和注销/重启验收需要操作者单独验证。 +### Windows 无人值守启动 + +runner 需要在桌面登录前接单时使用 `Boot` 模式。由原 runner 账户准备文件,该账户可保持标准用户;仅注册步骤使用独立的管理员提权会话。管理员从可信 checkout 执行命令;该步骤读取已准备的配置,不执行 runner 所属的启动器或预检。任务授予运行账户管理权限,始终以受限权限和优先级 4 运行。管理使用 Task Scheduler COM 和原生进程快照,不要求 CIM 命名空间访问权限。 + +1. 暂停 workflow 触发,等待空闲并停止现有启动器。已有任务由所属账户先执行 `stop` 再执行 `uninstall`,保留配置、缓存及签名互锁。安装会拒绝活跃或路径不可读的 runner 进程,以及原生 runner 的 `.service` 注册。 +2. 以 runner 账户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -StartupMode Boot -RunnerRoot -ConfigRoot /packaging`,保留原有 `-NetworkRoot` 和重试选项。此步骤检查工具和网络、编译启动器并准备启动快照,不注册任务。 +3. 在管理员提权 PowerShell 中运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action register-boot -RunnerRoot -RunAs `。账户必须与准备阶段一致。在本机提示中输入该账户的 Windows 密码,不是 Hello PIN 或签名 PIN。注册只提交一次凭据,创建初始禁用的 Password/AtStartup 任务。失败后先检查计划任务再重试,因为注册可能已经完成;不会自动重试认证。 +4. 以 runner 账户运行同一管理脚本,传入 `-Action start -RunnerRoot `,再执行 `-Action status`。核对账户、`LogonType=Password`、`BootTrigger=True`、剩余启动次数和监听日志。恢复登录后启动时,停止并卸载任务,再不带 `-StartupMode Boot` 安装并启动。 + +管理员须确保批处理登录权限、没有覆盖它的拒绝策略,以及 runner 对工具、私有配置、缓存和日志的访问权限。账户密码变更后需重新注册。网络依赖、磁盘和签名硬件须在登录前可用,服务时段应避免睡眠。脚本不配置桌面自动登录。恢复不能清除签名互锁或重试失败的硬件签名。 + +Windows CI 使用隔离替身检查任务 XML、准备阶段、无效配置、凭据取消和单次注册,不注册真实 Boot 任务。部署操作者须在每台新机器验证独立管理员与标准账户的注册、任务管理权限,以及不登录桌面的重启、实际接单和签名打包。旧机器结果不能替代新启动快照的验收。 + ### 可选网络依赖 `ConfigRoot` 中没有 `runner-network.json` 时,启动仍使用清理继承环境后的直连行为。要配置网络依赖,请在 checkout 外创建操作者管理的该 JSON 文件,且只包含 `proxyUrl`、`noProxy`、`serviceName`、`probeUrl`、`attempts`、`timeoutSeconds` 和 `retrySeconds`。前四个字段为字符串,后三个预算为 1 至 60 的整数。直连时将 `proxyUrl` 留空,没有 Windows 服务管理依赖时将 `serviceName` 留空。URL 必须使用 HTTP(S),不能包含凭据、查询参数或片段;代理 URL 不能包含路径。启动脚本在清理环境后设置 `HTTP_PROXY`、`HTTPS_PROXY`、`NO_PROXY` 和 `NODE_USE_ENV_PROXY`,并要求 Node HEAD 探测成功才允许启动 runner。服务就绪检查不会启动或停止 Windows 服务。 From 10ae2b3911fd179a9eb514bc07112cf6b35c08e4 Mon Sep 17 00:00:00 2001 From: winewill Date: Mon, 9 Nov 2026 16:51:15 +0800 Subject: [PATCH 03/90] fix(desktop): address Windows boot runner review findings --- .../scripts/windows-runner-scheduler.ps1 | 15 +++++-- apps/desktop/scripts/windows-runner-task.ps1 | 10 +++-- apps/desktop/tests/windows-runner-boot.ps1 | 39 ++++++++++++------- .../desktop/tests/windows-runner-recovery.ps1 | 1 + apps/desktop/windows-signing/README.i18n.yaml | 4 +- apps/desktop/windows-signing/README.md | 8 ++-- apps/desktop/windows-signing/README.zh.md | 8 ++-- 7 files changed, 55 insertions(+), 30 deletions(-) diff --git a/apps/desktop/scripts/windows-runner-scheduler.ps1 b/apps/desktop/scripts/windows-runner-scheduler.ps1 index a9db21c3c6..4514ffba60 100644 --- a/apps/desktop/scripts/windows-runner-scheduler.ps1 +++ b/apps/desktop/scripts/windows-runner-scheduler.ps1 @@ -1,5 +1,5 @@ # Build an unregistered runner task. Credentials are supplied only to the scheduler at installation. -function New-WindowsRunnerTaskDefinition($Scheduler, [string]$Sid, [string]$RunnerRoot, [string]$PowerShell, [int]$RestartMinutes, [ValidateSet('Interactive','Boot')][string]$StartupMode = 'Boot') { +function New-WindowsRunnerTaskDefinition($Scheduler, [string]$Sid, [string]$RunnerRoot, [string]$PowerShell, [int]$RestartMinutes, [ValidateSet('Interactive','Boot')][string]$StartupMode = 'Interactive') { $definition = $Scheduler.NewTask(0) $definition.RegistrationInfo.Description = "DSH packaging runner: $RunnerRoot; owner: $Sid" $definition.Principal.UserId = $Sid @@ -35,10 +35,11 @@ function Register-WindowsRunnerBootTask($Scheduler, [string]$TaskName, $Definiti } try { # COM avoids putting a plaintext password in command arguments or cmdlet parameter logging. - $null = $Scheduler.GetFolder('\').RegisterTaskDefinition($TaskName, $Definition, 2, $Sid, $credential.GetNetworkCredential().Password, 1, "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$Sid)") + $null = $Scheduler.GetFolder('\').RegisterTaskDefinition($TaskName, $Definition, 2, $RunAs, $credential.GetNetworkCredential().Password, 1, "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$Sid)") } catch { # Registration may have committed before an error reached this caller. - throw 'Boot task registration failed; registration outcome is unconfirmed. Inspect Task Scheduler, batch-logon policy and account credentials locally before retrying.' + $code = '0x{0:X8}' -f $_.Exception.GetBaseException().HResult + throw "Boot task registration failed ($code); registration outcome is unconfirmed. Inspect Task Scheduler, batch-logon policy and account credentials locally before retrying." } finally { $credential = $null } @@ -61,3 +62,11 @@ function Get-WindowsRunnerTask($Scheduler, [string]$TaskName) { throw } } + +# Unreadable process locations must reject maintenance just like missing locations. +function Get-WindowsRunnerProcessPath($Process) { + try { return $Process.Path } catch { + # Access-denied and exited-process errors cannot establish an unrelated location. + return $null + } +} diff --git a/apps/desktop/scripts/windows-runner-task.ps1 b/apps/desktop/scripts/windows-runner-task.ps1 index d3f6303898..3bb086b9e8 100644 --- a/apps/desktop/scripts/windows-runner-task.ps1 +++ b/apps/desktop/scripts/windows-runner-task.ps1 @@ -1,4 +1,4 @@ -# Prepare runner-owned startup files; an administrator registers Boot tasks for that account. +# Prepare startup files and manage runner tasks; Boot registration requires an administrator. [CmdletBinding()] param( [Parameter(Mandatory=$true)][ValidateSet('install','register-boot','start','stop','status','uninstall')][string]$Action, @@ -45,7 +45,8 @@ if ($Action -in @('install','register-boot')) { if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' } # Pause dispatch before migration; never overwrite a live startup snapshot. foreach ($process in @(Get-Process | Where-Object { $_.ProcessName -in @('Runner.Listener','Runner.Worker') })) { - if (-not $process.Path -or $process.Path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { + $path = Get-WindowsRunnerProcessPath $process + if (-not $path -or $path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'A runner process is active or its location is unreadable. Pause dispatch and stop its supervisor before installing.' } } @@ -58,7 +59,7 @@ if ($Action -eq 'register-boot') { if ((Get-Item -LiteralPath $configFile).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Task configuration cannot be a link.' } $config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json Assert-WindowsRunnerBootConfiguration $config $sid $RunnerRoot $taskName - $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $config.PowerShell $config.RestartMinutes + $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $config.PowerShell $config.RestartMinutes 'Boot' Register-WindowsRunnerBootTask $scheduler $taskName $definition $sid $RunAs Write-Output "Registered disabled Boot task $taskName. Run start as the runner account. Logs: $serviceDir" exit 0 @@ -126,7 +127,8 @@ switch ($Action) { # Operators pause workflow dispatch first; this local check cannot reserve an idle GitHub runner. $workers = Get-Process | Where-Object ProcessName -eq 'Runner.Worker' foreach ($worker in $workers) { - if (-not $worker.Path -or $worker.Path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { + $path = Get-WindowsRunnerProcessPath $worker + if (-not $path -or $path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'A runner job is active or its location is unreadable. Wait for completion before stopping.' } } diff --git a/apps/desktop/tests/windows-runner-boot.ps1 b/apps/desktop/tests/windows-runner-boot.ps1 index 4d9bf7b06d..6a82749a05 100644 --- a/apps/desktop/tests/windows-runner-boot.ps1 +++ b/apps/desktop/tests/windows-runner-boot.ps1 @@ -7,12 +7,13 @@ $scheduler.Connect() $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value $root = Join-Path ([IO.Path]::GetTempPath()) ('dsh-boot-definition-' + [guid]::NewGuid().ToString('N')) $null = New-Item -ItemType Directory -Path $root +try { $runner = Join-Path $root 'runner with spaces' $null = New-Item -ItemType Directory -Path $runner Set-Content -LiteralPath (Join-Path $runner '.runner') -Value '{}' $pwsh = Join-Path $PSHOME 'pwsh.exe' foreach ($minutes in @(1, 7, 1440)) { - $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh $minutes + $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh $minutes 'Boot' [xml]$xml = $definition.XmlText $ns = [Xml.XmlNamespaceManager]::new($xml.NameTable) $ns.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task') @@ -38,7 +39,7 @@ foreach ($minutes in @(1, 7, 1440)) { $parsedSid = ([Security.Principal.NTAccount]::new($parsed.Principal.UserId)).Translate([Security.Principal.SecurityIdentifier]).Value if ($parsedSid -ne $sid -or $parsed.Settings.Enabled) { throw 'Definition did not round-trip.' } } -$interactive = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh 1 'Interactive' +$interactive = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh 1 [xml]$interactiveXml = $interactive.XmlText $interactiveNs = [Xml.XmlNamespaceManager]::new($interactiveXml.NameTable) $interactiveNs.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task') @@ -63,16 +64,21 @@ Reject-Options @('-Action','install','-RunAs','unused') 'RunAs applies only to r Reject-Options @('-Action','start','-StartupMode','Boot') 'apply only to install' $processProbe = Join-Path $root 'process-probe.ps1' @' -param([string]$Manager, [string]$Runner, [switch]$Unreadable) +param([string]$Manager, [string]$Runner, [switch]$Unreadable, [switch]$ThrowPath) $ErrorActionPreference = 'Stop' function Get-Process { param($Name,$ErrorAction) + if ($ThrowPath) { + $process = [pscustomobject]@{ ProcessName = 'Runner.Worker' } + $process | Add-Member ScriptProperty Path { throw [ComponentModel.Win32Exception]::new(5) } + return $process + } [pscustomobject]@{ ProcessName = 'Runner.Worker'; Path = if ($Unreadable) { $null } else { Join-Path $Runner 'bin/Runner.Worker.exe' } } } & $Manager -Action install -RunnerRoot $Runner '@ | Set-Content -LiteralPath $processProbe -foreach ($unreadable in @($false, $true)) { - $probeOptions = if ($unreadable) { @('-Unreadable') } else { @() } +foreach ($mode in @('readable','missing','throwing')) { + $probeOptions = switch ($mode) { 'missing' { @('-Unreadable') }; 'throwing' { @('-ThrowPath') }; default { @() } } $output = & $pwsh -NoProfile -NonInteractive -File $processProbe -Manager $manager -Runner $runner @probeOptions 2>&1 | Out-String if ($LASTEXITCODE -eq 0 -or -not $output.Contains('A runner process is active or its location is unreadable')) { throw "Live-process installation guard failed: $output" } if (Test-Path -LiteralPath (Join-Path $runner 'dsh-task')) { throw 'Live-process rejection wrote a startup snapshot.' } @@ -151,8 +157,9 @@ $registrationOutput = & $pwsh -NoProfile -NonInteractive -File $registrationProb if ($elevated -and -not $sid.EndsWith('-500')) { if ($LASTEXITCODE -ne 0) { throw "Boot registration entry failed: $registrationOutput" } $submitted = Get-Content -LiteralPath $registrationResult -Raw | ConvertFrom-Json - if ($submitted.User -ne $sid -or $submitted.Name -ne $config.TaskName -or $submitted.Sddl -notlike "*(A;;GA;;;$sid)*") { throw 'Registration lost prepared account or management access.' } + if ($submitted.User -ne $account -or $submitted.Name -ne $config.TaskName -or $submitted.Sddl -notlike "*(A;;GA;;;$sid)*") { throw 'Registration lost prepared account or management access.' } } else { + Write-Output 'SKIP: elevated registration entry with substitute transport; unsupported installer context. Real cross-account registration is not tested.' if ($LASTEXITCODE -eq 0 -or (Test-Path -LiteralPath $registrationResult)) { throw 'Boot registration accepted an unsupported installer context.' } } if (Get-WindowsRunnerTask $scheduler $config.TaskName) { throw 'Isolated registration created a real task.' } @@ -165,7 +172,7 @@ $ErrorActionPreference = 'Stop' $native = New-Object -ComObject 'Schedule.Service' $native.Connect() $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value -$definition = New-WindowsRunnerTaskDefinition $native $sid $Runner (Join-Path $PSHOME 'pwsh.exe') 1 +$definition = New-WindowsRunnerTaskDefinition $native $sid $Runner (Join-Path $PSHOME 'pwsh.exe') 1 'Boot' $script:enabled = $Operation -ne 'uninstall' $task = [pscustomobject]@{ Definition=$definition; State=$(if ($script:enabled) { 3 } else { 1 }); LastRunTime=[DateTime]::MinValue; LastTaskResult=0 } $task | Add-Member ScriptProperty Enabled { return $script:enabled } { @@ -207,18 +214,19 @@ if (-not $failure) { throw 'Missing launcher was accepted.' } # Only the credential dialog and registration transport are replaced; no account authentication occurs. $script:credentialResult = $null +$script:credentialThrows = $false $script:registrationCalls = 0 $script:registrationFails = $false $script:registrationMismatch = $false -function Get-Credential { param($UserName, $Message); return $script:credentialResult } +function Get-Credential { param($UserName, $Message); if ($script:credentialThrows) { throw 'Prompt unavailable' }; return $script:credentialResult } $fakeFolder = [pscustomobject]@{} $fakeFolder | Add-Member ScriptMethod RegisterTaskDefinition { param($Name, $Definition, $Flags, $User, $Password, $Logon, $Sddl) $script:registrationCalls++ - if ($Name -ne 'fixture' -or $Flags -ne 2 -or $User -ne $sid -or $Logon -ne 1 -or $Sddl -ne "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$sid)" -or $Password -ne 'fake-only-never-authenticated') { + if ($Name -ne 'fixture' -or $Flags -ne 2 -or $User -ne 'fixture-user' -or $Logon -ne 1 -or $Sddl -ne "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$sid)" -or $Password -ne 'fake-only-never-authenticated') { $script:registrationMismatch = $true; throw 'Unexpected registration request.' } - if ($script:registrationFails) { throw 'fake-only-never-authenticated' } + if ($script:registrationFails) { throw [Runtime.InteropServices.COMException]::new('fake-only-never-authenticated', -2147023570) } } $fakeScheduler = [pscustomobject]@{ Folder = $fakeFolder } $fakeScheduler | Add-Member ScriptMethod GetFolder { param($Path); if ($Path -ne '\') { throw 'Unexpected task folder.' }; return $this.Folder } @@ -230,6 +238,9 @@ function Reject-Registration([string]$Message) { } } try { + $script:credentialThrows = $true + Reject-Registration 'Prompt unavailable' + $script:credentialThrows = $false Reject-Registration 'Credential entry cancelled' $script:credentialResult = [Management.Automation.PSCredential]::new('other-user', (ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force)) Reject-Registration 'Credential entry cancelled' @@ -240,13 +251,15 @@ try { Register-WindowsRunnerBootTask $fakeScheduler 'fixture' $definition $sid 'fixture-user' if ($script:registrationCalls -ne 1) { throw 'Registration was not submitted once.' } $script:registrationFails = $true - Reject-Registration 'registration outcome is unconfirmed' + Reject-Registration '0x8007052E' if ($script:registrationMismatch) { throw 'Unexpected registration request.' } if ($script:registrationCalls -ne 2) { throw 'Failed registration retried authentication.' } } finally { Remove-Item Function:Get-Credential $script:credentialResult = $null } -Remove-Item -LiteralPath $root -Recurse -Force -Write-Output "PASS: boot/password/least-privilege definition, recovery settings, duplicate policy, launcher reuse, XML round-trip, invalid options, credential cancellation and single-attempt registration failure containment. No task registered." +} finally { + Remove-Item -LiteralPath $root -Recurse -Force +} +Write-Output "PASS: boot/password/least-privilege definition, recovery settings, duplicate policy, launcher reuse, XML round-trip, invalid options, credential substitutes and single-attempt registration failure containment. No task registered." exit 0 diff --git a/apps/desktop/tests/windows-runner-recovery.ps1 b/apps/desktop/tests/windows-runner-recovery.ps1 index 6703ba069b..87d6af710f 100644 --- a/apps/desktop/tests/windows-runner-recovery.ps1 +++ b/apps/desktop/tests/windows-runner-recovery.ps1 @@ -46,3 +46,4 @@ function New-Object { } finally { if ([IO.Path]::GetFullPath($root).StartsWith([IO.Path]::GetTempPath(),[StringComparison]::OrdinalIgnoreCase)) { Remove-Item -LiteralPath $root -Recurse -Force } } +exit 0 diff --git a/apps/desktop/windows-signing/README.i18n.yaml b/apps/desktop/windows-signing/README.i18n.yaml index 7f2b2d0036..1ca636c854 100644 --- a/apps/desktop/windows-signing/README.i18n.yaml +++ b/apps/desktop/windows-signing/README.i18n.yaml @@ -24,8 +24,8 @@ en: f4fcb23be1f3df4a zh: f3699f0a64a9b94b /windows-signing-and-runner-operations/machine-setup-and-runner-startup/unattended-windows-startup: - en: def90f6dad81c4c4 - zh: a1cf176f59d38176 + en: 3b6ae5eb5177dba8 + zh: 0e7a3edeca2286c6 /windows-signing-and-runner-operations/machine-setup-and-runner-startup/optional-network-dependency: en: 60f34f8637b3c252 zh: 805435964ab20263 diff --git a/apps/desktop/windows-signing/README.md b/apps/desktop/windows-signing/README.md index ca156e8171..6cd4f534b4 100644 --- a/apps/desktop/windows-signing/README.md +++ b/apps/desktop/windows-signing/README.md @@ -48,16 +48,16 @@ Operators can run `pwsh -NoProfile -File apps/desktop/tests/windows-runner-task. ### Unattended Windows startup -Use `Boot` mode when the runner must accept jobs before desktop login. Prepare files under the existing runner account, which may remain a standard user. Use a separate elevated administrator session only for registration. Run the administrator command from a trusted checkout; it reads prepared configuration but does not execute the runner-owned launcher or preflight. The task grants its runner account management access and always runs with limited privileges and priority 4. Management uses Task Scheduler COM and native process snapshots instead of requiring CIM namespace access. +Use `Boot` mode when the runner must accept jobs before desktop login. Prepare files under the existing runner account, which may remain a standard user. Use a separate elevated administrator session only for registration. Run the administrator command from a verified, administrator-owned checkout whose scripts and parent directories are not writable by the runner account; never elevate scripts from its checkout; it reads prepared configuration but does not execute the runner-owned launcher or preflight. The task grants its runner account management access and always runs with limited privileges and priority 4. Management uses Task Scheduler COM and native process snapshots instead of requiring CIM namespace access. 1. Pause workflow dispatch, wait for idle and stop any existing launcher. For an installed task, run `stop` then `uninstall` as its owner; retain configuration, caches and signing interlocks. Installation rejects active or unreadable runner processes and a native runner `.service` registration. 2. As the runner account, run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -StartupMode Boot -RunnerRoot -ConfigRoot /packaging`, retaining any `-NetworkRoot` and retry options. This checks tools/network, compiles the launcher and prepares the startup snapshot; it does not register a task. -3. In an elevated administrator PowerShell, run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action register-boot -RunnerRoot -RunAs `. The account must match preparation. Enter its Windows password in the local prompt, not a Hello PIN or signing PIN. Registration submits credentials once and creates a disabled Password/AtStartup task. On failure, inspect Task Scheduler before retrying because registration may have committed; no automatic authentication retry occurs. +3. In an elevated administrator PowerShell, run `pwsh -NoProfile -File /apps/desktop/scripts/windows-runner-task.ps1 -Action register-boot -RunnerRoot -RunAs `. The account must match preparation. Enter its Windows password in the local prompt, not a Hello PIN or signing PIN. Registration submits credentials once and creates a disabled Password/AtStartup task. On failure, inspect Task Scheduler before retrying because registration may have committed; no automatic authentication retry occurs. 4. As the runner account, run the same manager with `-Action start -RunnerRoot `, then `-Action status`. Check the account, `LogonType=Password`, `BootTrigger=True`, remaining launches and listener logs. To return to login-only startup, stop and uninstall the task, then install without `-StartupMode Boot` and start. -The administrator must ensure batch-logon permission, no overriding deny policy, and runner access to its tools, private configuration, caches and logs. Account password changes require re-registration. Network dependencies, disk access and signing hardware must be available before login; prevent sleep during service hours. There is no desktop auto-login configuration. Recovery cannot clear a signing interlock or retry failed hardware signing. +The administrator must ensure batch-logon permission, no overriding deny policy, and runner access to its tools, private configuration, caches and logs. After an account password change, pause dispatch, wait for idle, run `stop` and `uninstall` as the runner account, repeat administrator `register-boot`, then run `start`; retain the prepared files without repeating `install`. Network dependencies, disk access and signing hardware must be available before login; prevent sleep during service hours. There is no desktop auto-login configuration. Healthy reboots also consume the persisted launch budget; no healthy-runtime reset or exhaustion alert exists. Check `status` and `RemainingLaunches` during maintenance; while idle, `stop` then `start` resets the budget. Recovery cannot clear a signing interlock or retry failed hardware signing. -Windows CI checks task XML, preparation, invalid configuration, credential cancellation and single-attempt registration with isolated substitutes; it does not register a real Boot task. Deployment operators must validate registration with separate administrator/standard accounts, task management permissions and a reboot without desktop login, followed by actual job assignment and a signed package on each new machine. Existing machine results do not qualify a new startup snapshot. +Windows CI checks task XML, preparation, invalid configuration, absent/mismatched credentials, prompt errors and single-attempt registration with isolated substitutes; it does not register a real Boot task. Interactive prompt cancellation may terminate through the PowerShell host; substituted credential tests do not qualify that host behavior. Deployment operators must validate registration with separate administrator/standard accounts, task management permissions and a reboot without desktop login, followed by actual job assignment and a signed package on each new machine. Existing machine results do not qualify a new startup snapshot. ### Optional network dependency diff --git a/apps/desktop/windows-signing/README.zh.md b/apps/desktop/windows-signing/README.zh.md index 55804faac9..941a52749b 100644 --- a/apps/desktop/windows-signing/README.zh.md +++ b/apps/desktop/windows-signing/README.zh.md @@ -48,16 +48,16 @@ description: "配置和维护 Windows 打包 runner、签名凭据、EV Token ### Windows 无人值守启动 -runner 需要在桌面登录前接单时使用 `Boot` 模式。由原 runner 账户准备文件,该账户可保持标准用户;仅注册步骤使用独立的管理员提权会话。管理员从可信 checkout 执行命令;该步骤读取已准备的配置,不执行 runner 所属的启动器或预检。任务授予运行账户管理权限,始终以受限权限和优先级 4 运行。管理使用 Task Scheduler COM 和原生进程快照,不要求 CIM 命名空间访问权限。 +runner 需要在桌面登录前接单时使用 `Boot` 模式。由原 runner 账户准备文件,该账户可保持标准用户;仅注册步骤使用独立的管理员提权会话。管理员必须从已核验、归管理员所有且 runner 账户无法写入脚本及其父目录的 checkout 执行命令,不得提权执行 runner checkout 中的脚本;该步骤读取已准备的配置,不执行 runner 所属的启动器或预检。任务授予运行账户管理权限,始终以受限权限和优先级 4 运行。管理使用 Task Scheduler COM 和原生进程快照,不要求 CIM 命名空间访问权限。 1. 暂停 workflow 触发,等待空闲并停止现有启动器。已有任务由所属账户先执行 `stop` 再执行 `uninstall`,保留配置、缓存及签名互锁。安装会拒绝活跃或路径不可读的 runner 进程,以及原生 runner 的 `.service` 注册。 2. 以 runner 账户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -StartupMode Boot -RunnerRoot -ConfigRoot /packaging`,保留原有 `-NetworkRoot` 和重试选项。此步骤检查工具和网络、编译启动器并准备启动快照,不注册任务。 -3. 在管理员提权 PowerShell 中运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action register-boot -RunnerRoot -RunAs `。账户必须与准备阶段一致。在本机提示中输入该账户的 Windows 密码,不是 Hello PIN 或签名 PIN。注册只提交一次凭据,创建初始禁用的 Password/AtStartup 任务。失败后先检查计划任务再重试,因为注册可能已经完成;不会自动重试认证。 +3. 在管理员提权 PowerShell 中运行 `pwsh -NoProfile -File /apps/desktop/scripts/windows-runner-task.ps1 -Action register-boot -RunnerRoot -RunAs `。账户必须与准备阶段一致。在本机提示中输入该账户的 Windows 密码,不是 Hello PIN 或签名 PIN。注册只提交一次凭据,创建初始禁用的 Password/AtStartup 任务。失败后先检查计划任务再重试,因为注册可能已经完成;不会自动重试认证。 4. 以 runner 账户运行同一管理脚本,传入 `-Action start -RunnerRoot `,再执行 `-Action status`。核对账户、`LogonType=Password`、`BootTrigger=True`、剩余启动次数和监听日志。恢复登录后启动时,停止并卸载任务,再不带 `-StartupMode Boot` 安装并启动。 -管理员须确保批处理登录权限、没有覆盖它的拒绝策略,以及 runner 对工具、私有配置、缓存和日志的访问权限。账户密码变更后需重新注册。网络依赖、磁盘和签名硬件须在登录前可用,服务时段应避免睡眠。脚本不配置桌面自动登录。恢复不能清除签名互锁或重试失败的硬件签名。 +管理员须确保批处理登录权限、没有覆盖它的拒绝策略,以及 runner 对工具、私有配置、缓存和日志的访问权限。账户密码变更后,暂停触发并等待空闲,由 runner 账户执行 `stop`、`uninstall`,管理员重新执行 `register-boot`,再由 runner 账户执行 `start`;保留准备文件,无需再次 `install`。网络依赖、磁盘和签名硬件须在登录前可用,服务时段应避免睡眠。脚本不配置桌面自动登录。正常重启也消耗持久启动预算,没有健康运行后自动重置或耗尽告警;维护时检查 `status` 的 `RemainingLaunches`,空闲时执行 `stop` 再 `start` 可重置预算。恢复不能清除签名互锁或重试失败的硬件签名。 -Windows CI 使用隔离替身检查任务 XML、准备阶段、无效配置、凭据取消和单次注册,不注册真实 Boot 任务。部署操作者须在每台新机器验证独立管理员与标准账户的注册、任务管理权限,以及不登录桌面的重启、实际接单和签名打包。旧机器结果不能替代新启动快照的验收。 +Windows CI 使用隔离替身检查任务 XML、准备阶段、无效配置、凭据缺失/不匹配及提示抛错和单次注册,不注册真实 Boot 任务。交互式取消可能由 PowerShell 宿主直接终止,凭据替身测试不代表该宿主行为已经验收。部署操作者须在每台新机器验证独立管理员与标准账户的注册、任务管理权限,以及不登录桌面的重启、实际接单和签名打包。旧机器结果不能替代新启动快照的验收。 ### 可选网络依赖 From 0fa66b81f26357113dc254c8d653afc86fadf05e Mon Sep 17 00:00:00 2001 From: winewill Date: Mon, 9 Nov 2026 17:42:36 +0800 Subject: [PATCH 04/90] fix(desktop): let Windows network probes exit naturally --- .../scripts/windows-runner-network.ps1 | 2 +- apps/desktop/tests/windows-runner-network.ps1 | 29 +++++++++++++++++-- apps/desktop/windows-signing/README.i18n.yaml | 4 +-- apps/desktop/windows-signing/README.md | 2 +- apps/desktop/windows-signing/README.zh.md | 2 +- 5 files changed, 31 insertions(+), 8 deletions(-) diff --git a/apps/desktop/scripts/windows-runner-network.ps1 b/apps/desktop/scripts/windows-runner-network.ps1 index 9ab2491901..7112e200fd 100644 --- a/apps/desktop/scripts/windows-runner-network.ps1 +++ b/apps/desktop/scripts/windows-runner-network.ps1 @@ -48,7 +48,7 @@ function Wait-RunnerNetwork($Config) { $info.Environment['DSH_NETWORK_PROBE_TIMEOUT'] = [string]($Config.timeoutSeconds * 1000) $info.ArgumentList.Add('--input-type=module') $info.ArgumentList.Add('-e') - $info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exit(r.ok ? 0 : 1); } catch { process.exit(1); }') + $info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exitCode = r.ok ? 0 : 1; } catch { process.exitCode = 1; }') for ($attempt = 1; $attempt -le $Config.attempts; $attempt++) { $ready = $true if ($Config.serviceName) { diff --git a/apps/desktop/tests/windows-runner-network.ps1 b/apps/desktop/tests/windows-runner-network.ps1 index bb9e4fe94e..e1db9629b5 100644 --- a/apps/desktop/tests/windows-runner-network.ps1 +++ b/apps/desktop/tests/windows-runner-network.ps1 @@ -9,7 +9,7 @@ $pwshLink = Join-Path $root 'tools/pwsh-7.6.6' if ($CheckStartup) { $null = New-Item -ItemType Junction -Path $pwshLink -Target $PSHOME } $server = $null $saved = @{} -foreach ($name in @('HTTP_PROXY','HTTPS_PROXY','NO_PROXY','NODE_USE_ENV_PROXY')) { $saved[$name] = [Environment]::GetEnvironmentVariable($name,'Process') } +foreach ($name in @('HTTP_PROXY','HTTPS_PROXY','NO_PROXY','NODE_USE_ENV_PROXY','NODE_OPTIONS')) { $saved[$name] = [Environment]::GetEnvironmentVariable($name,'Process') } try { if ($null -ne (Read-RunnerNetwork $root)) { throw 'Absent configuration changed behavior.' } $fixture = Join-Path $root 'proxy.cjs' @@ -41,6 +41,16 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St if ($server.HasExited -or [DateTime]::UtcNow -gt $deadline) { throw 'Proxy fixture did not become ready.' } Start-Sleep -Milliseconds 50 } + # Observe natural event-loop drain in the real redirected probe, without replacing fetch. + $lifecycle = Join-Path $root 'probe-lifecycle.cjs' + @' +const fs = require('node:fs'); +const path = require('node:path'); +if (process.env.DSH_NETWORK_PROBE_URL) { + process.once('beforeExit', () => fs.appendFileSync(path.join(__dirname, 'drained'), 'drained\n')); +} +'@ | Set-Content -LiteralPath $lifecycle + $env:NODE_OPTIONS = '--require "' + $lifecycle.Replace('\', '/') + '"' $port = Get-Content (Join-Path $root 'port') -Raw $config = @{proxyUrl="http://127.0.0.1:$port";noProxy='';serviceName='';probeUrl='http://runner-probe.invalid/ready';attempts=2;timeoutSeconds=2;retrySeconds=1} function Write-Config { $config | ConvertTo-Json | Set-Content (Join-Path $root 'runner-network.json') } @@ -48,6 +58,7 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St $parsed = Read-RunnerNetwork $root Set-RunnerNetwork $parsed Wait-RunnerNetwork $parsed + if (-not (Test-Path (Join-Path $root 'drained')) -or (Get-Content (Join-Path $root 'drained')).Count -ne 1) { throw 'Successful probe bypassed normal Node event-loop drain.' } if ($env:NODE_USE_ENV_PROXY -ne '1' -or $env:HTTP_PROXY -ne $config.proxyUrl -or $env:HTTPS_PROXY -ne $config.proxyUrl) { throw 'Proxy environment was not applied.' } # Full startup requires the operator's installed packaging toolchain and persistent PATH. if ($CheckStartup) { @@ -90,7 +101,19 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St $config.timeoutSeconds = 1 $failure = $null try { Wait-RunnerNetwork $config } catch { $failure = $_ } - if (-not $failure -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Unresponsive endpoint did not terminate its probe.' } + if (-not $failure -or -not $failure.Exception.Message.StartsWith('Runner network dependency unavailable;') -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Unresponsive endpoint did not terminate its probe.' } + # Retain a bound non-listening socket so no concurrent fixture can claim the refused port. + $refused = [Net.Sockets.Socket]::new([Net.Sockets.AddressFamily]::InterNetwork, [Net.Sockets.SocketType]::Stream, [Net.Sockets.ProtocolType]::Tcp) + try { + $refused.Bind([Net.IPEndPoint]::new([Net.IPAddress]::Loopback, 0)) + $config.proxyUrl = "http://127.0.0.1:$($refused.LocalEndPoint.Port)" + $config.noProxy = '' + $config.probeUrl = 'http://runner-probe.invalid/ready' + Set-RunnerNetwork $config + $failure = $null + try { Wait-RunnerNetwork $config } catch { $failure = $_ } + if (-not $failure -or -not $failure.Exception.Message.StartsWith('Runner network dependency unavailable;') -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Refused proxy connection admitted startup or reached the HTTP fixture.' } + } finally { $refused.Dispose() } foreach ($invalid in @('extra','credential','budget','type','wildcard','malformed')) { $bad = $config.Clone() switch ($invalid) { @@ -106,7 +129,7 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St try { $null = Read-RunnerNetwork $root } catch { $failure = $_ } if (-not $failure -or $failure.ToString().Contains('fake-secret')) { throw 'Invalid configuration accepted or disclosed.' } } - Write-Output "PASS: absent config, proxy routing, Node proxy opt-in, service readiness, bounded failure and redacted invalid config; startup integration=$CheckStartup." + Write-Output "PASS: absent config, redirected native Node HTTP success, non-2xx, refused proxy, request timeout, proxy routing, Node proxy opt-in, service readiness, bounded failure and redacted invalid config; startup integration=$CheckStartup." } finally { foreach ($name in $saved.Keys) { [Environment]::SetEnvironmentVariable($name,$saved[$name],'Process') } if ($server) { if (-not $server.HasExited) { $server.Kill($true); $server.WaitForExit() }; $server.Dispose() } diff --git a/apps/desktop/windows-signing/README.i18n.yaml b/apps/desktop/windows-signing/README.i18n.yaml index 1ca636c854..1e86bbca1b 100644 --- a/apps/desktop/windows-signing/README.i18n.yaml +++ b/apps/desktop/windows-signing/README.i18n.yaml @@ -27,8 +27,8 @@ en: 3b6ae5eb5177dba8 zh: 0e7a3edeca2286c6 /windows-signing-and-runner-operations/machine-setup-and-runner-startup/optional-network-dependency: - en: 60f34f8637b3c252 - zh: 805435964ab20263 + en: 5ac6cf96f6ec75f0 + zh: 7f7a498c656ee332 /windows-signing-and-runner-operations/signing-configuration: en: 4b5548818375eb9a zh: 8c975adbb1dca9c8 diff --git a/apps/desktop/windows-signing/README.md b/apps/desktop/windows-signing/README.md index 6cd4f534b4..12c111792c 100644 --- a/apps/desktop/windows-signing/README.md +++ b/apps/desktop/windows-signing/README.md @@ -67,7 +67,7 @@ For a dedicated child process, add `-NetworkRoot diff --git a/apps/desktop/windows-signing/README.zh.md b/apps/desktop/windows-signing/README.zh.md index 941a52749b..22b6cbe20c 100644 --- a/apps/desktop/windows-signing/README.zh.md +++ b/apps/desktop/windows-signing/README.zh.md @@ -67,7 +67,7 @@ Windows CI 使用隔离替身检查任务 XML、准备阶段、无效配置、 安装时会启动依赖进行就绪检查,并在注册任务前停止它。runner 存活期间,守卫仅在自己拥有的网络进程退出后,按配置间隔重新启动它;启动连续失败时仍会重试,但不会重启 runner、重跑任务或重试签名。退出、重启和启动失败消息写入 `run-*.log`,依赖进程的输出会被丢弃。重启消息只表明进程已创建,不代表网络可用;请在 runner 日志中确认重新连接。进程仍存活但无响应时需要操作者排查。守卫独占锁定 `NetworkRoot`,回收残留子进程前核对 PID、启动时间和可执行文件,并在 runner 退出时停止子进程。不可恢复的守卫错误会保留活动 runner 直到其退出,并报告恢复已停止。重新安装时保留 `NetworkRoot`;仅拉取代码不会替换已安装的辅助脚本。 -Windows CI 使用隔离的本地 fixture 运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` 和 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1`。在已配置的打包机器上,给第一条命令添加 `-CheckStartup`,可验证实际启动环境清理后的网络配置。这些测试不会使用签名硬件或外部网络端点。 +Windows CI 使用隔离的本地 fixture 运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` 和 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1`。在已配置的打包机器上,给第一条命令添加 `-CheckStartup`,可验证实际启动环境清理后的网络配置。就绪探测设置退出状态并让 Node 正常完成清理,保留响应体取消、请求超时和外层进程期限保护。测试通过真实重定向子进程路径覆盖 HTTP 成功、非 2xx、代理连接拒绝和请求超时,不使用签名硬件或外部网络端点。 From 0116485ca321a32b7172eb3d317c84e7428d2ce6 Mon Sep 17 00:00:00 2001 From: winewill Date: Mon, 9 Nov 2026 18:02:01 +0800 Subject: [PATCH 05/90] docs(desktop): clarify pre-login network deployment and acceptance --- apps/desktop/windows-signing/README.i18n.yaml | 4 ++-- apps/desktop/windows-signing/README.md | 4 ++++ apps/desktop/windows-signing/README.zh.md | 4 ++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/desktop/windows-signing/README.i18n.yaml b/apps/desktop/windows-signing/README.i18n.yaml index 1e86bbca1b..b13b57c069 100644 --- a/apps/desktop/windows-signing/README.i18n.yaml +++ b/apps/desktop/windows-signing/README.i18n.yaml @@ -27,8 +27,8 @@ en: 3b6ae5eb5177dba8 zh: 0e7a3edeca2286c6 /windows-signing-and-runner-operations/machine-setup-and-runner-startup/optional-network-dependency: - en: 5ac6cf96f6ec75f0 - zh: 7f7a498c656ee332 + en: 31ffd631dd215fc6 + zh: ebfe8a3a64ed6e02 /windows-signing-and-runner-operations/signing-configuration: en: 4b5548818375eb9a zh: 8c975adbb1dca9c8 diff --git a/apps/desktop/windows-signing/README.md b/apps/desktop/windows-signing/README.md index 12c111792c..41a6b62282 100644 --- a/apps/desktop/windows-signing/README.md +++ b/apps/desktop/windows-signing/README.md @@ -61,6 +61,8 @@ Windows CI checks task XML, preparation, invalid configuration, absent/mismatche ### Optional network dependency +Choose the network owner before installing Boot startup. An external service is suitable only after its forwarding process and required destinations have been verified after reboot without desktop login. A service reporting `Running`, a saved restore setting or a successful probe after login does not establish this: desktop software may stop its forwarding process and clear recovery state during logout or shutdown. If networking depends on that software, use the dedicated child-process mode below or provision an independently managed pre-login service. `runner-network.json` configures checks and proxy variables; it does not launch the proxy. Omitting `-NetworkRoot` leaves network startup to the external owner. + Without `runner-network.json` in `ConfigRoot`, startup retains its scrubbed direct-network behavior. To configure a network dependency, create that operator-owned JSON file outside the checkout with exactly `proxyUrl`, `noProxy`, `serviceName`, `probeUrl`, `attempts`, `timeoutSeconds` and `retrySeconds`. The first four fields are strings; the three budgets are integers from 1 through 60. Use an empty `proxyUrl` for direct access and an empty `serviceName` when no Windows service owns the dependency. URLs must use HTTP(S) without credentials, queries or fragments; the proxy URL cannot include a path. Startup applies `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and `NODE_USE_ENV_PROXY` after environment scrubbing, then requires a successful Node HEAD probe before admitting the runner. Service readiness checks never start or stop a Windows service. For a dedicated child process, add `-NetworkRoot ` to task installation. That directory must contain `launch.json` with exactly an absolute `executable` filename, an `arguments` string array and an integer `restartDelaySeconds` from 1 through 3600. This mode requires `runner-network.json`; set its `serviceName` to empty. Give the child its own data directory, listener bindings and executable identity, distinct from applications managed by desktop software; separate ports alone do not prevent another manager from terminating a process by executable name. The scripts do not alter desktop network settings. Keep actual provider names, paths, addresses, ports and arguments in machine configuration, never in repository files or shared logs. Restrict access to both configuration directories to the runner operator. @@ -69,6 +71,8 @@ Installation starts the dependency for readiness checking and stops it before re Windows CI runs `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` and `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1` with isolated local fixtures. On a configured packaging machine, add `-CheckStartup` to the first command to verify network configuration after the actual startup environment scrub. The readiness probe sets its exit status and lets Node drain normally; response cancellation, request timeout and the outer process deadline remain enforced. Tests cover HTTP success, non-2xx responses, refused proxy connections and request timeout through the real redirected child-process path, without signing hardware or external endpoints. +For a new machine, keep the runner disabled while preparing and testing network access. A disabled runner task does not launch its owned network child; test that child separately without starting the listener. After an operator-approved reboot, verify the selected proxy and required destinations before any desktop login or manual network-client launch. Record whether a desktop shell was present and which process supplied the proxy. If this fails, inspect the network owner's startup/shutdown logs before retrying. Only after network qualification should an operator enable the runner and validate Boot startup and job assignment; signing qualification remains separate. + ## Signing configuration diff --git a/apps/desktop/windows-signing/README.zh.md b/apps/desktop/windows-signing/README.zh.md index 22b6cbe20c..19796a291c 100644 --- a/apps/desktop/windows-signing/README.zh.md +++ b/apps/desktop/windows-signing/README.zh.md @@ -61,6 +61,8 @@ Windows CI 使用隔离替身检查任务 XML、准备阶段、无效配置、 ### 可选网络依赖 +安装 Boot 启动前,先明确网络进程由谁管理。只有在重启后、不登录桌面的条件下验证转发进程及所需目标地址可用,才能依赖外部服务。服务显示 `Running`、已保存恢复设置或登录后探测成功都不足以证明这一点:桌面软件可能在注销或关机时停止转发进程并清除恢复状态。若网络依赖此类软件,请使用下述专用子进程模式,或部署独立管理的登录前服务。`runner-network.json` 只配置检查和代理变量,不会启动代理;省略 `-NetworkRoot` 就意味着由外部管理者负责网络启动。 + `ConfigRoot` 中没有 `runner-network.json` 时,启动仍使用清理继承环境后的直连行为。要配置网络依赖,请在 checkout 外创建操作者管理的该 JSON 文件,且只包含 `proxyUrl`、`noProxy`、`serviceName`、`probeUrl`、`attempts`、`timeoutSeconds` 和 `retrySeconds`。前四个字段为字符串,后三个预算为 1 至 60 的整数。直连时将 `proxyUrl` 留空,没有 Windows 服务管理依赖时将 `serviceName` 留空。URL 必须使用 HTTP(S),不能包含凭据、查询参数或片段;代理 URL 不能包含路径。启动脚本在清理环境后设置 `HTTP_PROXY`、`HTTPS_PROXY`、`NO_PROXY` 和 `NODE_USE_ENV_PROXY`,并要求 Node HEAD 探测成功才允许启动 runner。服务就绪检查不会启动或停止 Windows 服务。 若使用专用子进程,在安装任务时添加 `-NetworkRoot `。该目录必须包含 `launch.json`,且只包含绝对路径的 `executable` 文件名、字符串数组 `arguments`,以及 1 至 3600 的整数 `restartDelaySeconds`。此模式要求存在 `runner-network.json`,其中 `serviceName` 应留空。为子进程分配独立的数据目录、监听绑定和可执行文件标识,与桌面软件管理的应用分离;仅使用不同端口无法防止其他管理器按可执行文件名终止进程。脚本不会修改桌面网络设置。实际服务商名称、路径、地址、端口和参数只保存在机器配置中,不得写入仓库文件或共享日志。将两个配置目录的访问权限限制为 runner 操作者。 @@ -69,6 +71,8 @@ Windows CI 使用隔离替身检查任务 XML、准备阶段、无效配置、 Windows CI 使用隔离的本地 fixture 运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` 和 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1`。在已配置的打包机器上,给第一条命令添加 `-CheckStartup`,可验证实际启动环境清理后的网络配置。就绪探测设置退出状态并让 Node 正常完成清理,保留响应体取消、请求超时和外层进程期限保护。测试通过真实重定向子进程路径覆盖 HTTP 成功、非 2xx、代理连接拒绝和请求超时,不使用签名硬件或外部网络端点。 +新机器准备和测试网络时,保持 runner 禁用。禁用的 runner 任务不会启动其托管的网络子进程;应单独测试该子进程,不启动 listener。经操作者批准重启后,在登录桌面或手动打开网络客户端之前,验证所选代理及所需目标地址,记录当时是否存在桌面 Shell,以及由哪个进程提供代理。若失败,先检查网络管理者的启动和关闭日志,再重试。网络验收通过后,才由操作者启用 runner,验证 Boot 启动与任务分配;签名另行验收。 + ## 签名配置 From d28a0ed8043ba8ba0d92ab5dce4c922c8f44f5c8 Mon Sep 17 00:00:00 2001 From: winewill Date: Tue, 10 Nov 2026 14:43:34 +0800 Subject: [PATCH 06/90] fix(desktop): verify long Windows paths with PowerShell 7 --- .../scripts/desktop-toolchain-preflight.ts | 10 ++++++++++ .../scripts/windows-runtime-signature.mjs | 5 ++--- apps/desktop/scripts/windows-signature-batch.mjs | 4 ++-- apps/desktop/tests/desktop-build-commit.spec.ts | 12 ++++++++++++ apps/desktop/tests/windows-sign.spec.ts | 2 +- .../tests/windows-signature-batch.spec.ts | 16 +++++++++++----- apps/desktop/windows-signing/README.i18n.yaml | 4 ++-- apps/desktop/windows-signing/README.md | 2 ++ apps/desktop/windows-signing/README.zh.md | 2 ++ 9 files changed, 44 insertions(+), 13 deletions(-) diff --git a/apps/desktop/scripts/desktop-toolchain-preflight.ts b/apps/desktop/scripts/desktop-toolchain-preflight.ts index ff855cfd09..da0f06a8ec 100644 --- a/apps/desktop/scripts/desktop-toolchain-preflight.ts +++ b/apps/desktop/scripts/desktop-toolchain-preflight.ts @@ -14,6 +14,8 @@ import { tmpdir } from 'node:os' import { basename, dirname, join } from 'node:path' import { promisify } from 'node:util' +import { scrubWindowsSigningEnvironment } from './windows-sign.mjs' + const run = promisify(execFile) /** One tool the packaging run requires, and what went wrong with it. */ @@ -45,6 +47,14 @@ async function probeTar(): Promise { async function probeWindowsInstallerToolchain(environment: NodeJS.ProcessEnv): Promise { const failures: DesktopToolchainProbeFailure[] = [] + try { + await run('pwsh', ['-NoProfile', '-NonInteractive', '-Command', + '$ErrorActionPreference="Stop"; if ($PSVersionTable.PSVersion.Major -lt 7) { throw "PowerShell 7 or newer is required" }; Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop; Get-Command Get-AuthenticodeSignature -ErrorAction Stop | Out-Null'], + { env: scrubWindowsSigningEnvironment(environment), windowsHide: true, timeout: 20_000 }) + } + catch (error) { + failures.push({ tool: 'pwsh', detail: `PowerShell 7 with Authenticode support must be available on PATH: ${error instanceof Error ? error.message : String(error)}` }) + } const programFiles = environment['ProgramFiles(x86)'] const vswhere = programFiles === undefined ? undefined diff --git a/apps/desktop/scripts/windows-runtime-signature.mjs b/apps/desktop/scripts/windows-runtime-signature.mjs index 9f79547b34..c85a23fbda 100644 --- a/apps/desktop/scripts/windows-runtime-signature.mjs +++ b/apps/desktop/scripts/windows-runtime-signature.mjs @@ -9,13 +9,12 @@ import { inspectSignaturesBatched } from './windows-signature-batch.mjs' import { packagingStep } from './packaging-step.mjs' /** - * Read Windows trust, timestamp and signer identity using the engine's bundled modules, without accessing the private key. + * Read Windows trust, timestamp and signer identity using PowerShell 7's bundled modules, without accessing the private key. * @param {string} path File to inspect. * @returns {Promise<{status: string, timestamped: boolean, thumbprint: string | null}>} Authenticode verification result. */ export async function inspectWindowsRuntimeSignature(path) { - // Node can inherit PowerShell 7's module search path while launching Windows PowerShell 5. - const { stdout, stderr } = await promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', + const { stdout, stderr } = await promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-Command', '$ErrorActionPreference="Stop"; [Console]::OutputEncoding=[System.Text.UTF8Encoding]::new(); Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop; Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1" -ErrorAction Stop; $s=Get-AuthenticodeSignature -LiteralPath $env:DSH_RUNTIME_VERIFY_FILE; [pscustomobject]@{status=[string]$s.Status;timestamped=($null -ne $s.TimeStamperCertificate);thumbprint=$s.SignerCertificate.Thumbprint}|ConvertTo-Json -Compress'], { env: { ...scrubWindowsSigningEnvironment(process.env), DSH_RUNTIME_VERIFY_FILE: path }, encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024, diff --git a/apps/desktop/scripts/windows-signature-batch.mjs b/apps/desktop/scripts/windows-signature-batch.mjs index cbc37b9d30..4b54428c45 100644 --- a/apps/desktop/scripts/windows-signature-batch.mjs +++ b/apps/desktop/scripts/windows-signature-batch.mjs @@ -1,4 +1,4 @@ -/** Bounded public-key verification batches; every output row must match its requested file. */ +/** Bounded PowerShell 7 public-key verification batches; every output row must match its requested file. */ import { execFile } from 'node:child_process' import { promisify } from 'node:util' import { scrubWindowsSigningEnvironment } from './windows-sign.mjs' @@ -27,7 +27,7 @@ export function parseSignatureRows(stdout, stderr, files) { } async function inspectBatch(files) { - const pending = promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], { + const pending = promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-Command', command], { env: scrubWindowsSigningEnvironment(process.env), encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024 * files.length, }) diff --git a/apps/desktop/tests/desktop-build-commit.spec.ts b/apps/desktop/tests/desktop-build-commit.spec.ts index 57016a5e7e..ab3c252e67 100644 --- a/apps/desktop/tests/desktop-build-commit.spec.ts +++ b/apps/desktop/tests/desktop-build-commit.spec.ts @@ -73,6 +73,18 @@ describe('desktop toolchain preflight', () => { expect(failures.find(failure => failure.tool === 'vswhere')?.detail).toContain('ProgramFiles(x86)') }) + it('reports missing PowerShell before Windows packaging', async () => { + const empty = await mkdtemp(join(tmpdir(), 'dsh-no-pwsh-')) + directories.push(empty) + const failures = await probeDesktopToolchain('win32', { PATH: empty }) + expect(failures.find(failure => failure.tool === 'pwsh')?.detail).toContain('PowerShell 7') + }) + + it.skipIf(process.platform !== 'win32')('accepts the Windows Authenticode toolchain', async () => { + const failures = await probeDesktopToolchain('win32', process.env) + expect(failures.filter(failure => failure.tool === 'pwsh')).toEqual([]) + }) + it('writes nothing into the working directory while probing', async () => { const directory = await mkdtemp(join(tmpdir(), 'dsh-probe-cwd-')) directories.push(directory) diff --git a/apps/desktop/tests/windows-sign.spec.ts b/apps/desktop/tests/windows-sign.spec.ts index 3e0ec371a7..b76ca35d5d 100644 --- a/apps/desktop/tests/windows-sign.spec.ts +++ b/apps/desktop/tests/windows-sign.spec.ts @@ -74,7 +74,7 @@ describe('Windows token signing', () => { } else { expect(options.env.DSH_DESKTOP_WINDOWS_TOKEN_PIN).toBeUndefined() expect(options.env.DSH_DESKTOP_WINDOWS_KEY_CONTAINER).toBeUndefined() - if (command === 'powershell.exe') { + if (command === 'pwsh') { const timestamped = readFileSync(options.env.DSH_RUNTIME_VERIFY_FILE!, 'utf8').endsWith(':timestamp') if (!timestamped) expect(existsSync(join(stateDirectory, 'attempt.json'))).toBe(true) callback(null, JSON.stringify({ status: mode === 'invalid-primary' ? 'NotTrusted' : 'Valid', timestamped, thumbprint: 'A'.repeat(40) }), '') diff --git a/apps/desktop/tests/windows-signature-batch.spec.ts b/apps/desktop/tests/windows-signature-batch.spec.ts index 6e6ebe602f..d4ee626bbd 100644 --- a/apps/desktop/tests/windows-signature-batch.spec.ts +++ b/apps/desktop/tests/windows-signature-batch.spec.ts @@ -1,7 +1,7 @@ /** Parser fault checks; real-file equivalence is measured separately. */ import { it as test } from 'vitest' import assert from 'node:assert/strict' -import { copyFile, mkdtemp, rm } from 'node:fs/promises' +import { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { parseSignatureRows, inspectSignaturesBatched } from '../scripts/windows-signature-batch.mjs' @@ -33,12 +33,18 @@ test('empty input launches no verifier and returns no rows', async () => { assert.deepEqual(await inspectSignaturesBatched([]), []) }) -test.skipIf(process.platform !== 'win32')('Unicode paths retain the same Windows trust result as individual inspection', async (t) => { +test.skipIf(process.platform !== 'win32')('long Unicode paths retain the same Windows trust result as short paths', async (t) => { const root = await mkdtemp(join(tmpdir(), 'signature-batch-')) t.onTestFinished(() => rm(root, { recursive: true, force: true })) - const path = join(root, "验证 ' 文件.exe") - await copyFile(join(process.env.SystemRoot!, 'System32', 'cmd.exe'), path) - const expected = await inspectWindowsRuntimeSignature(path) + const shortPath = join(root, 'short.exe') + const directory = join(root, 'nested-'.repeat(15), 'nested-'.repeat(15)) + await mkdir(directory, { recursive: true }) + const path = join(directory, "验证 ' 文件.exe") + assert.ok(path.length > 260) + await copyFile(join(process.env.SystemRoot!, 'System32', 'cmd.exe'), shortPath) + await copyFile(shortPath, path) + const expected = await inspectWindowsRuntimeSignature(shortPath) + assert.deepEqual(await inspectWindowsRuntimeSignature(path), expected) assert.equal(expected.status, 'Valid') assert.deepEqual(await inspectSignaturesBatched([path]), [expected]) await signWindowsCode(root, { diff --git a/apps/desktop/windows-signing/README.i18n.yaml b/apps/desktop/windows-signing/README.i18n.yaml index b13b57c069..e68512d0f6 100644 --- a/apps/desktop/windows-signing/README.i18n.yaml +++ b/apps/desktop/windows-signing/README.i18n.yaml @@ -30,8 +30,8 @@ en: 31ffd631dd215fc6 zh: ebfe8a3a64ed6e02 /windows-signing-and-runner-operations/signing-configuration: - en: 4b5548818375eb9a - zh: 8c975adbb1dca9c8 + en: b38f6fbfcfd73f7a + zh: f3afb7053af7480b /windows-signing-and-runner-operations/signing-and-timestamp-completion: en: a8d23c931cafc236 zh: 28fd4860549cdc7b diff --git a/apps/desktop/windows-signing/README.md b/apps/desktop/windows-signing/README.md index 41a6b62282..4e3b47d74e 100644 --- a/apps/desktop/windows-signing/README.md +++ b/apps/desktop/windows-signing/README.md @@ -77,6 +77,8 @@ For a new machine, keep the runner disabled while preparing and testing network ## Signing configuration +Windows packaging requires PowerShell 7 (`pwsh`) on `PATH`. The toolchain check verifies Authenticode support before building; runtime signature checks use this engine to handle paths longer than 260 characters. + The [machine preset configuration](../packaging/README.md#configuration-and-local-builds) selects public settings and the signing file. Without a preset, use the target dotenv file. Fill in `.env.windows` with `DSH_DESKTOP_WINDOWS_CER_FILE` (public EV leaf certificate), `DSH_DESKTOP_WINDOWS_SIGNTOOL` (SafeNet-compatible SignTool), `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` (matching private-key container), and `DSH_DESKTOP_WINDOWS_TOKEN_PIN` (Token Password). The private key stays on the USB token; keep the certificate and local credential file out of Git. diff --git a/apps/desktop/windows-signing/README.zh.md b/apps/desktop/windows-signing/README.zh.md index 19796a291c..c8da7c7aee 100644 --- a/apps/desktop/windows-signing/README.zh.md +++ b/apps/desktop/windows-signing/README.zh.md @@ -77,6 +77,8 @@ Windows CI 使用隔离的本地 fixture 运行 `pwsh -NoProfile -File apps/desk ## 签名配置 +Windows 打包要求 `PATH` 中提供 PowerShell 7(`pwsh`)。工具链检查在构建前验证 Authenticode 支持;运行时签名检查使用此引擎处理超过 260 个字符的路径。 + 通过[机器 preset 配置](../packaging/README.zh.md#configuration-and-local-builds)选择公开设置与签名文件;不选择 preset 时使用目标 dotenv 文件。 在 `.env.windows` 中填写 `DSH_DESKTOP_WINDOWS_CER_FILE`(公开 EV 叶证书)、`DSH_DESKTOP_WINDOWS_SIGNTOOL`(SafeNet 兼容的 SignTool)、`DSH_DESKTOP_WINDOWS_KEY_CONTAINER`(匹配的私钥容器)和 `DSH_DESKTOP_WINDOWS_TOKEN_PIN`(Token Password)。私钥仍保留在 USB Token;不要把证书或本地凭据文件提交到 Git。 From 8074bda9f444a5d4ff4011fd57c837d44462bbf3 Mon Sep 17 00:00:00 2001 From: winewill Date: Tue, 10 Nov 2026 15:09:08 +0800 Subject: [PATCH 07/90] feat(desktop): summarize Windows packaging parameters --- .github/workflows/windows-package.yml | 11 +++- apps/desktop/publishing/ci/README.i18n.yaml | 4 +- apps/desktop/publishing/ci/README.md | 2 + apps/desktop/publishing/ci/README.zh.md | 2 + .../scripts/windows-packaging-summary.d.mts | 7 +++ .../scripts/windows-packaging-summary.mjs | 45 ++++++++++++++ .../tests/windows-packaging-summary.spec.ts | 58 +++++++++++++++++++ 7 files changed, 126 insertions(+), 3 deletions(-) create mode 100644 apps/desktop/scripts/windows-packaging-summary.d.mts create mode 100644 apps/desktop/scripts/windows-packaging-summary.mjs create mode 100644 apps/desktop/tests/windows-packaging-summary.spec.ts diff --git a/.github/workflows/windows-package.yml b/.github/workflows/windows-package.yml index 405ee6bd29..c54f013a59 100644 --- a/.github/workflows/windows-package.yml +++ b/.github/workflows/windows-package.yml @@ -105,10 +105,11 @@ jobs: ref: ${{ github.workflow_sha }} sparse-checkout: apps/desktop/scripts - name: Stage workflow helpers + id: helpers run: | $helpers = Join-Path $env:RUNNER_TEMP "packaging-helpers-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" New-Item -ItemType Directory -Path $helpers -ErrorAction Stop | Out-Null - foreach ($name in @('windows-packaging-priority.ps1')) { + foreach ($name in @('windows-packaging-priority.ps1', 'windows-packaging-summary.mjs')) { Copy-Item -LiteralPath (Join-Path 'apps/desktop/scripts' $name) -Destination $helpers -ErrorAction Stop } "PACKAGE_CI_HELPERS=$helpers" >> $env:GITHUB_ENV @@ -176,6 +177,14 @@ jobs: env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} run: node apps/desktop/scripts/prepare-windows-ci.mjs + - name: Summarize packaging parameters + if: always() && steps.helpers.outcome == 'success' + env: + PACKAGE_INPUT_VERSION_MODE: ${{ inputs.version_mode }} + PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} + PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} + PACKAGE_VERSION: ${{ steps.settings.outputs.version }} + run: node "$env:PACKAGE_CI_HELPERS/windows-packaging-summary.mjs" - name: Check packaging configuration and toolchain env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} diff --git a/apps/desktop/publishing/ci/README.i18n.yaml b/apps/desktop/publishing/ci/README.i18n.yaml index a1d7210bf1..d6eaef8e8b 100644 --- a/apps/desktop/publishing/ci/README.i18n.yaml +++ b/apps/desktop/publishing/ci/README.i18n.yaml @@ -24,8 +24,8 @@ en: 0f43f2e193e95043 zh: 1c1efb062c06f7b8 /desktop-ci-publication/package-and-publish: - en: 6325c71df74a9915 - zh: edaa8a4502ed80a1 + en: 2b75de75308c7729 + zh: 1b09a6edd8c7e9b0 /desktop-ci-publication/rollout-and-website-publication: en: ee7a9ab8c66df979 zh: c355668bc9bdb635 diff --git a/apps/desktop/publishing/ci/README.md b/apps/desktop/publishing/ci/README.md index be001eb216..7516a3c755 100644 --- a/apps/desktop/publishing/ci/README.md +++ b/apps/desktop/publishing/ci/README.md @@ -69,6 +69,8 @@ Environment approval gates this workflow, not arbitrary code running under the s ## Package and publish +The Windows packaging run shows a Chinese parameter summary with the requested source, environment, channel, version mode, signing mode, compression, test release ID and cache namespace, plus the workflow identity, checked-out commit, resolved version and runner. Once workflow helpers are staged, earlier failures still produce the summary with unavailable results labeled explicitly. The summary reads no machine configuration; a blank test release ID is shown as machine-default selection, not its resolved value. It does not establish build, signature or publication success. + The publication form accepts an optional `staging_percentage` integer from 0 to 100. It applies to the retained package’s channel (nightly or stable), appears in the approval summary, and is included in the published YAML and audit record without modifying retained artifacts. Leave it blank for the packaged default (normally full rollout). Completed publications cannot change this percentage through a retry; same-version feed conflicts remain errors. For publication to either test or production, choose Windows `signing=signed` or leave macOS **Skip notarization** unchecked. Unsigned and unnotarized packages are only for internal debugging; they cannot publish or provide automatic updates. Before installing dependencies, the hosted routing job rejects debugging artifacts identified by the selected run and attempt. An archive-only rerun retains the original build attempt in artifact names, so this early check can miss it; local manifest qualification still rejects debugging builds before publication. Missing artifact metadata does not establish eligibility: the original machine still validates its retained manifest and signatures. A debugging-package rejection requires a new signed/notarized package and its run ID / attempt; retrying publication cannot qualify the existing bytes. diff --git a/apps/desktop/publishing/ci/README.zh.md b/apps/desktop/publishing/ci/README.zh.md index 9b0bffe7a8..1dc229fd4c 100644 --- a/apps/desktop/publishing/ci/README.zh.md +++ b/apps/desktop/publishing/ci/README.zh.md @@ -69,6 +69,8 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任 ## 打包与发布 +Windows 打包运行会展示中文参数摘要,列出请求的源码、环境、通道、版本模式、签名方式、压缩等级、测试 release ID 和缓存命名空间,以及工作流标识、检出提交、解析版本和 runner。工作流辅助脚本暂存成功后,即使前序步骤失败仍会生成摘要,并明确标记尚未取得的结果。摘要不读取机器配置;测试 release ID 留空时仅显示选择了机器默认值,不展示其解析值。摘要不代表构建、签名或发布成功。 + 发布表单支持可选的 `staging_percentage`,取值为 0 到 100 的整数。该值作用于保留包所属的 nightly 或 stable 渠道,显示在审批摘要中,并写入发布的 YAML 和审计记录,不修改保留产物。留空沿用包内默认值(通常为全量)。已完成的发布不能通过重试修改比例;同版本清单内容冲突仍会报错。 发布到 test 或 production 都必须在 Windows 选择 `signing=signed`,或在 macOS 不勾选**跳过公证**。无签名、无公证的包仅限内部调试,不能发布或用于自动更新。托管路由 job 会在安装依赖前,依据所选 run 和 attempt 对应的 artifact 名称拒绝已标明的调试包。仅重跑归档时,artifact 名称保留原构建 attempt,早期检查可能未识别该包;本地清单资格校验仍会在发布前拒绝调试包。缺少 artifact 元数据不代表允许发布:原机器仍会验证留存清单和签名。遇到调试包拒绝提示时,需重新完成签名或公证,再使用新包的 run ID / attempt 发布;重跑发布不能使现有产物获得发布资格。 diff --git a/apps/desktop/scripts/windows-packaging-summary.d.mts b/apps/desktop/scripts/windows-packaging-summary.d.mts new file mode 100644 index 0000000000..d369273144 --- /dev/null +++ b/apps/desktop/scripts/windows-packaging-summary.d.mts @@ -0,0 +1,7 @@ +/** Windows packaging parameter summary without machine configuration access. */ +/** + * Summarize allowlisted workflow inputs and resolved build identity. + * @param environment Workflow inputs and GitHub run identity. + * @returns Markdown tables without a build or signature success claim. + */ +export function windowsPackagingSummary(environment: NodeJS.ProcessEnv): string diff --git a/apps/desktop/scripts/windows-packaging-summary.mjs b/apps/desktop/scripts/windows-packaging-summary.mjs new file mode 100644 index 0000000000..c5f9d2aac4 --- /dev/null +++ b/apps/desktop/scripts/windows-packaging-summary.mjs @@ -0,0 +1,45 @@ +/** Render Windows packaging inputs and resolved build identity without loading machine configuration. */ +import { appendFile } from 'node:fs/promises' +import { realpathSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +function text(value) { + return value.replace(/[&<>"'|`\r\n\\*_\[\]()!~:]/gu, character => `&#${character.charCodeAt(0)};`) +} + +/** + * Summarize allowlisted workflow inputs separately from resolved checkout and version values. + * @param {NodeJS.ProcessEnv} environment Workflow inputs and GitHub run identity. + * @returns {string} Markdown parameter tables; no signature or publication success claim. + */ +export function windowsPackagingSummary(environment) { + const row = (label, value, fallback = '未提供') => `| ${label} | ${value ? `${text(value)}` : fallback} |` + return [ + '## Windows 打包参数', '', + '以下记录输入参数与已解析结果,不代表构建、签名或发布成功;执行结果以各步骤状态为准。', '', + '### 输入参数', '', '| 项目 | 选择值 |', '| --- | --- |', + row('源码 ref', environment.PACKAGE_SOURCE_REF), + row('环境', environment.DSH_PACKAGING_PRESET), + row('升级通道', environment.DSH_DESKTOP_UPDATE_CHANNEL), + row('版本模式', environment.PACKAGE_INPUT_VERSION_MODE), + row('手动版本号', environment.PACKAGE_BUILD_VERSION, '未填写'), + row('签名方式(请求)', environment.PACKAGE_SIGNING), + row('安装器压缩等级', environment.PACKAGE_WINDOWS_COMPRESSION_LEVEL), + row('测试 release ID(输入)', environment.PACKAGE_TEST_RELEASE_ID, '使用机器默认值(本摘要不读取)'), + row('缓存命名空间', environment.PACKAGE_CACHE_NAMESPACE, '共享缓存'), '', + '### 执行信息', '', '| 项目 | 已知值 |', '| --- | --- |', + row('平台', 'win-x64'), + row('工作流 ref', environment.GITHUB_WORKFLOW_REF), + row('工作流 SHA', environment.GITHUB_WORKFLOW_SHA), + row('检出源码 SHA', environment.PACKAGE_SOURCE_SHA, '尚未取得'), + row('解析后的版本号', environment.PACKAGE_VERSION, '尚未解析成功'), + row('Runner', environment.RUNNER_NAME), + row('运行 ID', environment.GITHUB_RUN_ID), + row('尝试次数', environment.GITHUB_RUN_ATTEMPT), '', + ].join('\n') +} + +if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) { + if (!process.env.GITHUB_STEP_SUMMARY) throw new Error('Windows packaging summary requires GITHUB_STEP_SUMMARY') + await appendFile(process.env.GITHUB_STEP_SUMMARY, windowsPackagingSummary(process.env)) +} diff --git a/apps/desktop/tests/windows-packaging-summary.spec.ts b/apps/desktop/tests/windows-packaging-summary.spec.ts new file mode 100644 index 0000000000..328cb85d16 --- /dev/null +++ b/apps/desktop/tests/windows-packaging-summary.spec.ts @@ -0,0 +1,58 @@ +/** Workflow summaries distinguish requested options from completed build evidence. */ +import { execFile } from 'node:child_process' +import { copyFile, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { promisify } from 'node:util' +import { expect, it } from 'vitest' +import { windowsPackagingSummary } from '../scripts/windows-packaging-summary.mjs' + +it('separates workflow identity, requested source, and resolved build version', () => { + const summary = windowsPackagingSummary({ + PACKAGE_SOURCE_REF: 'feature/windows', PACKAGE_SOURCE_SHA: 'source-sha', + GITHUB_WORKFLOW_REF: 'repo/.github/workflows/windows-package.yml@refs/heads/master', + GITHUB_WORKFLOW_SHA: 'workflow-sha', PACKAGE_INPUT_VERSION_MODE: 'default', + PACKAGE_VERSION: '0.2.2-rc.1.20261110.1.1', PACKAGE_SIGNING: 'signed', + DSH_PACKAGING_PRESET: 'test', DSH_DESKTOP_UPDATE_CHANNEL: 'nightly', + }) + expect(summary).toContain('| 源码 ref | feature/windows |') + expect(summary).toContain('| 检出源码 SHA | source-sha |') + expect(summary).toContain('| 工作流 SHA | workflow-sha |') + expect(summary).toContain('| 版本模式 | default |') + expect(summary).toContain('| 解析后的版本号 | 0.2.2-rc.1.20261110.1.1 |') + expect(summary).toContain('不代表构建、签名或发布成功') +}) + +it('retains unresolved and machine-default labels after an earlier failure', () => { + const summary = windowsPackagingSummary({ PACKAGE_SOURCE_REF: 'bad-source' }) + expect(summary).toContain('| 检出源码 SHA | 尚未取得 |') + expect(summary).toContain('| 解析后的版本号 | 尚未解析成功 |') + expect(summary).toContain('使用机器默认值(本摘要不读取)') + expect(summary).toContain('| 缓存命名空间 | 共享缓存 |') +}) + +it('escapes input markup and excludes unrelated environment and private configuration', () => { + const summary = windowsPackagingSummary({ + PACKAGE_SOURCE_REF: '') + const view = render() + const iframe = await screen.findByTitle(en.frame) + expect(iframe.getAttribute('sandbox')).toBe('allow-scripts') + expect(initial.readRelated).not.toHaveBeenCalled() + expect(initial.addResource).not.toHaveBeenCalled() + expect(initial.setResources).toHaveBeenLastCalledWith([]) + const payload = /text\("([^"]*)"\)/u.exec(await create.mock.calls[0]![0].text())![1]! + const json = new TextDecoder().decode(Uint8Array.from(atob(payload), character => character.charCodeAt(0))) + const bundle = JSON.parse(json) as { html: string; assets: unknown[] } + expect(bundle.assets).toEqual([]) + expect(bundle.html).toContain('') - const view = render() - const iframe = await screen.findByTitle(en.frame) - expect(iframe.getAttribute('sandbox')).toBe('allow-scripts') - expect(initial.readRelated).not.toHaveBeenCalled() - expect(initial.addResource).not.toHaveBeenCalled() - expect(initial.setResources).toHaveBeenLastCalledWith([]) - const payload = /text\("([^"]*)"\)/u.exec(await create.mock.calls[0]![0].text())![1]! - const json = new TextDecoder().decode(Uint8Array.from(atob(payload), character => character.charCodeAt(0))) - const bundle = JSON.parse(json) as { html: string; assets: unknown[] } - expect(bundle.assets).toEqual([]) - expect(bundle.html).toContain('