From 26e76932cb56115fea30c8e82bb9ecf30b692bbc Mon Sep 17 00:00:00 2001 From: beichen24a1 <262405272+beichen24a1@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:13:44 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E9=87=8D=E5=81=9A=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E5=99=A8=E6=9B=B4=E6=96=B0=E8=AE=BE=E7=BD=AE=E5=92=8C=E5=87=AD?= =?UTF-8?q?=E6=8D=AE=E4=BF=9D=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.en.md | 4 +- README.md | 4 +- changelog.d/428.feat.md | 2 + internal/i18n/locales/en/ui.json | 4 +- internal/i18n/locales/en/update.json | 3 + internal/i18n/locales/en/web.json | 39 +--- internal/ui/API.en.md | 8 +- internal/ui/API.md | 8 +- internal/ui/http_test.go | 7 + internal/ui/update.go | 16 +- internal/ui/update_apply.go | 2 +- internal/ui/web/app.css | 22 +- internal/ui/web/dev/mock.js | 33 +++ internal/ui/web/js/actions.js | 15 +- internal/ui/web/js/settings-page.js | 33 +-- internal/ui/web/js/update.js | 293 +++++++++++------------- internal/update/caller_settings_test.go | 79 +++++++ internal/update/range.go | 8 +- internal/update/settings.go | 88 +++++-- internal/update/source.go | 88 +++++-- internal/update/updater.go | 5 +- scripts/test_topbar_ui.mjs | 10 +- scripts/test_update_handoff.mjs | 81 +++---- 23 files changed, 513 insertions(+), 339 deletions(-) create mode 100644 changelog.d/428.feat.md diff --git a/README.en.md b/README.en.md index 812d94df..072dd461 100644 --- a/README.en.md +++ b/README.en.md @@ -370,7 +370,7 @@ Double-click `ModAVD.exe` in the package root: it starts a local server that lis - `prepare` downloads, unpacks, verifies file by file against the `modavd-manifest.json` in the package, and stages the result; instances can be running; - `install` runs `prepare` first if needed, then swaps in `sdk\emulator` and the other files in the package. All instances, the manager (including one left in the tray) and MCP clients must be closed first; if any program is using the files, it changes nothing (exit code 5), and the staged new version is kept so the next run can swap it in directly; - `recover` finishes or rolls back a swap that was left unfinished last time (it also runs first at the start of every step). -- The update source is chosen in the manager's "Settings": GitHub (the latest Release of `ModAVD/ModAVD`; only the changed files are fetched with HTTP Range requests and the rest is copied from the root, falling back to the full package, with the reason in `notices`, when the server does not serve ranges, more than 40% of the package or 3000 files changed, or the fetched data or the assembled result fails its checks) or MirrorChyan (downloads need a CDK, and it can provide delta packages; on errors it downloads from GitHub instead and says so in the result's `notices`). The CDK is encrypted with Windows DPAPI and stored in `%LOCALAPPDATA%\ModAVD\update-settings.json`; only this Windows user can decrypt it, and it is not written to logs and does not appear on the command line or in API responses. +- The update source is chosen in the manager's "Settings": GitHub (the latest Release of `ModAVD/ModAVD`; only the changed files are fetched with HTTP Range requests and the rest is copied from the root, falling back to the full package, with the reason in `notices`, when the server does not serve ranges, more than 40% of the package or 3000 files changed, or the fetched data or the assembled result fails its checks) or MirrorChyan (downloads need a CDK, and it can provide delta packages; on errors it downloads from GitHub instead and says so in the result's `notices`). The optional GitHub token is used for GitHub version checks and downloads in the manager and CLI. The CDK and token are encrypted with Windows DPAPI and stored in `%LOCALAPPDATA%\ModAVD\update-settings.json`; only this Windows user can decrypt it, and the values stay out of logs, command-line arguments and API responses. - Settings the caller passes for one run (`status`, `check`, `prepare` and `install` accept them, `recover` does not; they only override "Settings", are never saved, and `source` / `cdk_set` in the result report what was in effect): - `--source github|mirrorchyan`: the update source for this run. - `--cdk-dpapi `: the MirrorChyan CDK for this run. The value is the base64 of a blob the caller encrypted with Windows DPAPI: `CryptProtectData` of the UTF-8 CDK, without entropy, current-user or machine scope. modavd decrypts it and checks it with the same rules as "Settings" (at most 256 bytes after trimming, no spaces, tabs, line breaks or `&?#=`). Not base64, not decryptable or not a valid CDK is `invalid_argument` (exit code 2), and the error quotes neither the blob nor the CDK; on other platforms it is `unsupported`. An empty value (`--cdk-dpapi ""`, or only blanks) means no CDK for this run, even when one is saved. @@ -381,7 +381,7 @@ Double-click `ModAVD.exe` in the package root: it starts a local server that lis - `downloading` has no such line: the first line when the download stage begins already carries the real `percent` and bytes, then about one line every 2 seconds, and the line of the finished download is always there. - Not printed with `--quiet` (progress is info level). Without `--json` the human-readable text is unchanged. stdout still carries only the final result line. - "Update" in "Settings" downloads, verifies and stages the package while instances can start, stop and be created. Once prepared, it refuses new instance operations. Unfinished jobs or settings writes, creation in progress, or another program using this root's modavd cause the update to stop before shutting down any instance. The stage stays for retry. Otherwise it shuts down running instances normally and starts `tools\modavd.exe update install --after-pid --reopen [--reopen-arg ARG]...`. The manager exits after the CLI confirms ownership. A duplicate launch during handoff displays an update notice and exits. A stale record after a crash cannot block the next launch. The CLI revalidates the newer stage and installs it without another remote check, then reopens the manager with its original arguments. The result in `.update\manager-results\.json` belongs to that restart and is shown once. Failed installation also reopens the manager and retains a valid stage. CLI output goes to `logs\modavd-update.log`. `--after-pid`, `--reopen`, `--reopen-arg` and `--handoff-id` are manager options for `install` only. -- On macOS, update settings and component download sources use `~/Library/Application Support/ModAVD/update-settings.json` and `components-settings.json`. The CDK is encrypted with AES-GCM using a random wrapping key kept in the current user's Keychain. A locked or unauthorized Keychain makes saving fail without plaintext storage; copying the settings to another user or device does not transfer that key. +- On macOS, update settings and component download sources use `~/Library/Application Support/ModAVD/update-settings.json` and `components-settings.json`. The CDK and GitHub token are encrypted with AES-GCM using a random wrapping key kept in the current user's Keychain. A locked or unauthorized Keychain makes saving fail without plaintext storage; copying the settings to another user or device does not transfer that key. - Native Apple Silicon builds accept `modavd update prepare --package /path/update.zip --sha256 <64-digit digest from a trusted independent source>`, followed by offline `modavd update install` or `recover`. Packages must follow the [macOS update contract](internal/update/MACOS.en.md); ARM64 Mach-O, code signature integrity, modes and symlinks are checked, with at least 20 GiB free space retained. Signature verification does not establish publisher identity. Native transactions are separate from the Windows/AUTO-MAS journal. Remote checks return `update_unavailable` when no compatible macOS release asset exists; release packaging is a later stage. - Only files from the package are swapped: `avd\`, `mas-avd.json` (only `components.emulator` is changed and an `updateHistory` entry is recorded), `sdk\platform-tools`, `sdk\system-images`, `logs\` and so on are never touched; `sdk\emulator` is replaced as a whole. A root folder that sets `sdkRoot` in `mas-avd.json` is not updated. - `--automas-version` is the version of the calling AUTO-MAS: if the first line of the new version's announcement requires a higher AUTO-MAS, it does not install. diff --git a/README.md b/README.md index 052af5eb..71e213a0 100644 --- a/README.md +++ b/README.md @@ -373,7 +373,7 @@ Apple Silicon macOS 可运行 `ModAVD` 管理器;`ModAVD.app` 放在包根目 - `prepare` 下载、解包、按包里的 `modavd-manifest.json` 逐文件核对、暂存好,实例开着也行; - `install` 需要时先 `prepare`,再换上 `sdk\emulator` 和包里的其他文件。要先关掉所有实例、管理器(包括托盘里的)和 MCP 客户端,有程序在用就什么都不动(退出码 5),暂存的新版留着,下次直接换; - `recover` 补完或退回上次没做完的换上(每一步开始前也会先做)。 -- 更新源在管理器的「设置」里选:GitHub(`ModAVD/ModAVD` 的最新 Release;先按区间只下变了的文件、没变的从本地复制,服务器不认 Range、变了的超过整包 40% 或 3000 个文件、取回的数据或拼好后的清单核对不过时改下整包,原因写进 `notices`)或 Mirror 酱(填了 CDK 才能下载,能拿到增量包;出错时改从 GitHub 下,并在结果的 `notices` 里写明)。CDK 用 Windows DPAPI 加密存在 `%LOCALAPPDATA%\ModAVD\update-settings.json`,只有这个 Windows 用户能解开,不写日志、不出现在命令行和接口返回里。 +- 更新源在管理器的「设置」里选:GitHub(`ModAVD/ModAVD` 的最新 Release;先按区间只下变了的文件、没变的从本地复制,服务器不认 Range、变了的超过整包 40% 或 3000 个文件、取回的数据或拼好后的清单核对不过时改下整包,原因写进 `notices`)或 Mirror 酱(填了 CDK 才能下载,能拿到增量包;出错时改从 GitHub 下,并在结果的 `notices` 里写明)。GitHub token 可留空,填好后用于管理器和命令行的 GitHub 版本查询及下载。CDK 和 token 用 Windows DPAPI 加密存在 `%LOCALAPPDATA%\ModAVD\update-settings.json`,只有这个 Windows 用户能解开,不写日志、不出现在命令行和接口返回里。 - 调用方传这一次的设置(`status`、`check`、`prepare`、`install` 都可以带,`recover` 不带;只盖过「设置」里的,不保存,`status` 等结果里的 `source`、`cdk_set` 是这次生效的): - `--source github|mirrorchyan`:这次用的更新源。 - `--cdk-dpapi `:这次用的 Mirror 酱 CDK。值是调用方用 Windows DPAPI 加密好的密文的 base64:`CryptProtectData` 加密 UTF-8 的 CDK,不带 entropy,当前用户或本机作用域都行。modavd 解开后按和「设置」一样的规则检查(去掉首尾空白后不超过 256 个字节,不含空格、制表符、换行和 `&?#=`)。不是 base64、解不开、格式不对都是 `invalid_argument`(退出码 2),错误里不带密文和 CDK;不是 Windows 是 `unsupported`。给空串(`--cdk-dpapi ""`,或只有空白)表示这次不用 CDK,「设置」里存了也不用。 @@ -384,7 +384,7 @@ Apple Silicon macOS 可运行 `ModAVD` 管理器;`ModAVD.app` 放在包根目 - `downloading` 没有这样的一行:进入下载阶段的第一行就带真实的 `percent` 和字节数,之后约 2 秒一行,下完那行一定有。 - `--quiet` 时不出(进度是 info 级)。不带 `--json` 时照旧是人看的文字。stdout 仍然只有最后一行结果。 - 管理器「设置」里点「更新」:先下载、核对、暂存,期间可以开机、关机和新建。准备完成后不再接收实例操作;还有任务或设置修改没做完、有实例正在新建,或者其他程序在用这个根目录的 modavd 时,一台实例都不关,保留暂存、提示处理后重试。全部通过才正常关掉运行中的实例,交给 `tools\modavd.exe update install --after-pid <管理器 pid> --reopen <管理器程序> [--reopen-arg 参数]...`,确认命令行接手后管理器退出。交接期间再次打开会提示正在更新并退出;异常退出留下的交接记录不会挡住下次启动。命令行重新核对较新暂存后直接换包,不重复查远端,再按原来的参数打开管理器。本次结果存进 `.update\manager-results\.json`,只交给对应启动的管理器、提示一次。换不上也重新打开,有效暂存留着,下次不用重下。命令行输出在 `logs\modavd-update.log`。`--after-pid`、`--reopen`、`--reopen-arg`、`--handoff-id` 只和 `install` 一起用,是给管理器用的。 -- macOS 的更新设置和组件下载源分别保存在 `~/Library/Application Support/ModAVD/update-settings.json` 和 `components-settings.json`。CDK 使用 AES-GCM 加密,随机包装密钥留在当前用户的 Keychain;钥匙串锁定或未授权时保存失败,不会降级为明文存储。复制设置文件到其他用户或设备不会同时转移密钥。 +- macOS 的更新设置和组件下载源分别保存在 `~/Library/Application Support/ModAVD/update-settings.json` 和 `components-settings.json`。CDK 和 GitHub token 使用 AES-GCM 加密,随机包装密钥留在当前用户的 Keychain;钥匙串锁定或未授权时保存失败,不会降级为明文存储。复制设置文件到其他用户或设备不会同时转移密钥。 - Apple Silicon 原生构建可用 `modavd update prepare --package /path/update.zip --sha256 <可信渠道取得的64位摘要>` 暂存本地包,再用 `modavd update install` 离线安装;`recover` 也可离线补完或恢复。包须符合 [macOS 更新包协议](internal/update/MACOS.md),核对 ARM64 Mach-O、代码签名完整性、模式和符号链接,并保留至少 20 GiB 可用空间。签名核对不代表发布者身份可信,SHA256 必须独立取得。原生事务与 Windows/AUTO-MAS 状态隔离;尚无符合协议的 macOS 发布资产时,远端检查返回 `update_unavailable`。发布打包流程由后续阶段接入。 - 只换包里的文件:`avd\`、`mas-avd.json`(只改 `components.emulator` 并记一条 `updateHistory`)、`sdk\platform-tools`、`sdk\system-images`、`logs\` 等一律不碰;`sdk\emulator` 整个换掉。根目录在 `mas-avd.json` 里设了 `sdkRoot` 的不更新。 - `--automas-version` 是调用方 AUTO-MAS 的版本:新版的公告第一行要求更高的 AUTO-MAS 时不装。 diff --git a/changelog.d/428.feat.md b/changelog.d/428.feat.md new file mode 100644 index 00000000..d92cd1c0 --- /dev/null +++ b/changelog.d/428.feat.md @@ -0,0 +1,2 @@ +设置页集中显示版本和更新进度,支持加密保存 GitHub token。 +Settings shows update versions and progress and supports saving an encrypted GitHub token. diff --git a/internal/i18n/locales/en/ui.json b/internal/i18n/locales/en/ui.json index c791b406..532f6177 100644 --- a/internal/i18n/locales/en/ui.json +++ b/internal/i18n/locales/en/ui.json @@ -271,7 +271,6 @@ "补全组件": "fetching components", "补全组件必须明确同意许可协议": "Fetching components requires explicitly accepting the license agreement", "补全组件要带上看过的许可协议的 license_sha256": "Fetching components requires the license_sha256 of the license agreement you read", - "要给 source 或 cdk": "source or cdk is required", "规则挂不上:%v;名单里的应用现在直连": "The rules could not be applied: %v; apps on the list connect directly now", "规则没挂上:名单里的应用现在直连": "The rules were not applied: apps on the list connect directly now", "规则缺了几条,正在补上": "Some rules are missing; adding them", @@ -304,5 +303,6 @@ "问题包已经不在了: %s": "The problem report no longer exists: %s", "页面文件没有打包进程序": "The page files are not bundled into the program", "(%d 个还没装)": " (%d not installed yet)", - "(UDP 不通)": " (UDP unreachable)" + "(UDP 不通)": " (UDP unreachable)", + "请提供要修改的更新设置": "Provide an update setting to change" } diff --git a/internal/i18n/locales/en/update.json b/internal/i18n/locales/en/update.json index 03db5f5d..fcfb833e 100644 --- a/internal/i18n/locales/en/update.json +++ b/internal/i18n/locales/en/update.json @@ -79,6 +79,9 @@ "从 Mirror 酱下载全量包 %v": "Download full package %v from MirrorChyan", "从 Mirror 酱下载增量包(%s → %s)": "Download delta package from MirrorChyan (%s -> %s)", "保存更新设置失败": "Failed to save update settings", + "正在保存更新设置,请稍后再试": "Update settings are being saved. Try again shortly", + "GitHub token 的格式不对": "Invalid GitHub token format", + "加密 GitHub token 失败": "Could not encrypt the GitHub token", "保存更新设置失败: %v": "Failed to save update settings: %v", "关掉这个根目录的所有管理器窗口(托盘里的也退出),再运行 tools\\modavd.exe update install;上次换到一半的,运行 tools\\modavd.exe update recover": "Close all manager windows of this root folder (also exit the one in the tray), then run tools\\modavd.exe update install; if a swap was left half done, run tools\\modavd.exe update recover", "准备好的版本不比装着的新": "The prepared version is not newer than the installed one", diff --git a/internal/i18n/locales/en/web.json b/internal/i18n/locales/en/web.json index 3a88b6d2..4910a843 100644 --- a/internal/i18n/locales/en/web.json +++ b/internal/i18n/locales/en/web.json @@ -16,7 +16,6 @@ "KernelSU 组件文件已就绪": "KernelSU component files ready", "Mirror 酱": "MirrorChyan", "Mirror 酱 CDK": "MirrorChyan CDK", - "ModAVD 整包:模拟器、组件、脚本和管理器": "Full ModAVD package: emulator, components, scripts and manager", "Play 商店会记着旧的设备信息:改完后到实例里 设置 → 应用 → Google Play 商店 → 存储,清除数据(账号不会退出),它才会按新版本重新判断兼容。": "The Play Store remembers the old device info: afterwards, in the instance go to Settings → Apps → Google Play Store → Storage and clear data (accounts stay signed in) so it re-checks compatibility with the new version.", "Win 的组合 Windows 自己留着用,换一个": "Windows keeps Win combinations for itself; choose another", "adb 地址": "adb address", @@ -31,7 +30,6 @@ "{kind},UDP 没试通:{reason}": "{kind}, UDP did not work: {reason}", "{kind},但这个代理不转 UDP:名单里的应用只能用 TCP": "{kind}, but this proxy does not forward UDP: the listed apps can only use TCP", "{kind}:只转 TCP,UDP 不通(换成代理软件的 SOCKS5 或混合端口就都能用)": "{kind}: forwards TCP only, UDP does not work (use the SOCKS5 or mixed port of your proxy software for both)", - "{message}。这个窗口会自己关掉。": "{message}. This window will close by itself.", "{min}–{max} GB,以后只能改大;快满时会提醒": "{min}–{max} GB; it can only be enlarged later; you are warned when it is nearly full", "{m} 分 {s} 秒": "{m} min {s} s", "{m} 分钟": "{m} min", @@ -47,7 +45,6 @@ "{sec} 秒": "{sec} s", "{text}要用的实例在「更多操作」里启用 KernelSU。": "{text}Enable KernelSU from More Actions on any instance that needs it.", "{text}要用的实例在「更多操作」里补全商店。": "{text} To use the store on an instance, add it under “More actions”.", - "{version} 或更新(用 AUTO-MAS 的才要)": "{version} or newer (only if you use AUTO-MAS)", "{what}没有成功": "{what} failed", "{what},最后强行结束了模拟器进程": "{what}; in the end the emulator process was killed", "{who}{what}没有成功": "{who}: {what} failed", @@ -91,7 +88,6 @@ "一开始就是 {gb} GB,按实际写入占电脑硬盘,不用管大小": "It is {gb} GB from the start and only takes as much space on the computer as is written; no need to care about the size", "一次最多选 {max} 个文件": "Select at most {max} files at a time", "一般要几分钟": "usually a few minutes", - "上次": "Last time", "上次开机没有成功": "The last start failed", "上次补全中途失败,没能全部撤回:在「更多操作」里移除,或者再补全一次": "The last add failed halfway and could not be fully undone: remove it under “More actions”, or add it again", "下次开机生效。60 是默认;30 给锁 30 帧的游戏,帧间隔最匀;15 只适合纯挂机,整个系统都是 15 帧": "Takes effect at the next start. 60 is the default; 30 for games locked at 30 fps, the most even frame times; 15 only for idling, the whole system runs at 15 fps", @@ -108,7 +104,6 @@ "不填就显示「{name}」,以后可以随时改": "If left empty, “{name}” is shown; you can change it any time", "不影响开机": "Does not block starting", "不等待安卓回收完成;电脑上的磁盘文件要关机后用「整理磁盘」才会变小。": "It does not wait for Android to finish reclaiming; the disk file on the computer only shrinks after shutdown with “Compact disk”.", - "不能更新": "Cannot update", "为{who}单独生成带 KernelSU 的 ramdisk(不改全局系统镜像),装入 ksud、KernelSU Manager 和 meta-overlayfs 模块系统。": "Build a per-instance KernelSU ramdisk for {who} (leaving the global system image untouched) and install ksud, KernelSU Manager, and meta-overlayfs.", "主页": "Home", "五个文件本来就齐全,给的文件也核对无误,没有改动。": "All five files were already there and the files you gave check out; nothing was changed.", @@ -122,15 +117,11 @@ "代理地址": "Proxy address", "使用我自己的文件…": "Use my own files…", "保存": "Save", - "保存 CDK": "Save CDK", "修正 mas-avd.json 的 regional 设置后重试。": "Fix the regional setting in mas-avd.json and try again.", - "先下载并核对新版,这时实例照常用(现在没有实例在运行);然后管理器关闭、换上新版,换好后自动重新打开管理器。": "The new version is downloaded and verified first (instances keep working meanwhile; none is running now); then the manager closes, installs the new version and reopens automatically.", - "先下载并核对新版,这时实例照常用;然后正常关掉正在运行的 {n} 台实例(安卓正常关机),管理器关闭、换上新版,换好后自动重新打开管理器。": "The new version is downloaded and verified first (instances keep working meanwhile); then the {n} running instance(s) are shut down normally (Android shuts down cleanly), the manager closes, installs the new version and reopens automatically.", "先关机": "Shut it down first", "先关机才能删除": "Shut it down before deleting", "先填代理地址,或者点「从系统代理读取」": "Enter a proxy address first, or choose “Read from system proxy”", "先导入 KernelSU 组件文件": "Import KernelSU component files first", - "先点「检查更新」": "Choose “Check for updates” first", "先补全 Google Play 商店服务": "Fetch the Google Play Store service first", "先显示许可协议,同意后下载(约 1.5 GB)": "Shows the license agreement first, then downloads (about 1.5 GB)", "全部 {n} 台": "All {n} instances", @@ -190,7 +181,6 @@ "可一次选择多个模块 .zip(如 ReZygisk 与 Vector / LSPosed),自动按依赖顺序刷入并冷启动一次生效。": "Select multiple module .zip archives at once (such as ReZygisk and Vector / LSPosed); they are flashed in dependency order and activated with one cold reboot.", "可以修改": "Editable", "可以开机,有提示": "Can start, with notes", - "可以更新到 {version}": "Update to {version} is available", "可回收约 {size}": "Reclaimable about {size}", "可选组件": "Optional components", "同意并下载": "Agree and download", @@ -221,7 +211,6 @@ "在资源管理器里显示": "Show in File Explorer", "填好自定义地址后,这里显示从它取到的许可协议全文。": "Once a custom address is entered, the full license agreement from it is shown here.", "声音": "Sound", - "处理上述原因后,再试一次更新。": "Resolve the issue above, then try updating again.", "一直开启": "Always on", "只在带窗口时开启": "Only with a window", "不开启": "Off", @@ -265,7 +254,6 @@ "实例没有开机": "The instance is not running", "实例照原样关着": "the instance was left off", "实例现在报 GLES 3.2": "The instance now reports GLES 3.2", - "实例的数据(avd 文件夹)和设置都不动。正在新建的实例要先等它建完;用 modavd mcp 的 AI 助手等程序也要先关掉。": "Instance data (the avd folder) and settings are left untouched. Wait for instances being created to finish, and close programs such as AI assistants that use modavd mcp.", "实例运行中,内存、CPU、帧率、分辨率、DPI、数据盘和声音在下次开机生效。诊断设置立即生效。": "The instance is running. Memory, CPU, frame rate, resolution, DPI, data disk and sound take effect at the next start; the diagnostics setting takes effect at once.", "实例里没有装别的应用": "No other apps are installed in the instance", "实例里的 Google 服务框架联网登记后才有:开着网等一两分钟,再试一次。": "It exists once Google Services Framework in the instance has registered online: stay online for a minute or two, then try again.", @@ -290,7 +278,6 @@ "导出日志": "Export logs", "已从镜像压缩包取出五个文件,核对无误。": "Took the five files out of the image archive; they check out.", "已保存": "Saved", - "已保存 CDK": "CDK saved", "已保存,下次开机生效": "Saved, takes effect at the next start", "已保存,但没生效": "Saved, but not in effect", "已保存,但老板键用不了": "Saved, but the boss key cannot be used", @@ -309,7 +296,6 @@ "已取消": "Canceled", "已取消导出日志。": "Exporting logs was canceled.", "已填入这台电脑的代理设置": "Filled in the proxy settings of this computer", - "已填(加密保存在本机,只有这个 Windows 用户能读)": "Set (stored encrypted on this computer; only this Windows user can read it)", "已填,输入新的会替换": "Set; entering a new one replaces it", "已复制": "Copied", "已复制到剪贴板。": "Copied to the clipboard.", @@ -322,14 +308,10 @@ "已强制关机(先保存了数据)": "Force-stopped (the data was saved first)", "已恢复原版 ramdisk 启动": "Restored stock ramdisk boot", "已把十进制的 GSF ID 复制到剪贴板。": "The decimal GSF ID was copied to the clipboard.", - "已是最新": "Up to date", - "已更新到 {version}": "Updated to {version}", "已正常关机": "Shut down normally", - "已清除 CDK": "CDK cleared", "已生成": "created", "已生效": "In effect", "已移除商店,换回了系统原来的占位应用": "The store was removed and the original placeholder app restored", - "已经是最新版本": "Already up to date", "已经有 9 台实例了": "There are already 9 instances", "已补全": "Added", "已装 Google Play 商店": "Google Play Store installed", @@ -411,8 +393,6 @@ "新建时的初始化没做完": "Initial setup did not finish", "新建的实例不带商店,要用的实例在「更多操作」里补全。": "New instances come without the store. To use it on an instance, add it under “More actions”.", "新建第一台实例": "Create the first instance", - "新版已下载并核对好,待安装": "The new version is downloaded and verified, waiting to be installed", - "新版没有换上": "The new version was not installed", "方向": "Orientation", "无": "none", "无头:命令行开的,没有窗口,可以在这里关机": "Headless: started from the command line, no window; you can shut it down here", @@ -427,9 +407,6 @@ "暂时不能开机": "Cannot start for now", "更多操作:{name}": "More actions: {name}", "更新": "Update", - "更新会正常关掉{names},和点「关机」一样。实例里正在跑的游戏和任务会中断,更新完要自己再开机。": "The update shuts down {names} normally, just like “Shut down”. Games and tasks running in them are interrupted; start the instances again after updating.", - "更新到 {target}": "Update to {target}", - "更新没成功:{reason}": "Update failed: {reason}", "更新源": "Update source", "最多 9 台实例(编号 0–9,5 除外)": "At most 9 instances (numbers 0–9, except 5)", "最多 9 台(编号 0–9,5 除外)。删掉不用的实例再新建。": "At most 9 (numbers 0–9, except 5). Delete an instance you do not use, then create a new one.", @@ -471,7 +448,6 @@ "正在关机…": "Shutting down…", "正在关闭报告 GLES 3.2…": "Turning off GLES 3.2 reporting…", "正在准备…": "Preparing…", - "正在准备新版": "Preparing the new version", "正在删除…": "Deleting…", "正在取画面…": "Getting the screen…", "正在启动模拟器…": "Starting the emulator…", @@ -491,14 +467,12 @@ "正在开机,开好后这里会显示画面": "Starting; the screen shows here once it is up", "正在把 {n} 个文件交给后台(共 {bytes})…": "Handing {n} file(s) to the background service ({bytes} in total)…", "正在挂上客体库补丁…": "Applying the guest library patches…", - "正在换上新版": "Swapping in the new version", "正在收尾…": "Finishing up…", "正在整理磁盘": "Compacting the disk", "正在整理磁盘…": "Compacting the disk…", "正在新建…": "Creating…", "正在新建实例 {index}": "Creating instance {index}", "正在新建:后台开机做初始化…": "Creating: starting in the background for initial setup…", - "正在更新": "Updating", "正在更新…": "Updating…", "正在查看磁盘占用…": "Checking disk usage…", "正在核对文件…": "Checking the files…", @@ -527,7 +501,6 @@ "每台实例是一台独立的安卓模拟器,可以各登录一个游戏账号。": "Each instance is an independent Android emulator and can log in to one game account.", "每台实例的 GSF ID 不一样,每台都要登记;清除「Google 服务框架」的数据或者重建实例以后会变,要重新登记。": "Every instance has its own GSF ID and each one must be registered; it changes after clearing the data of “Google Services Framework” or recreating the instance, and then must be registered again.", "永久删除": "Delete permanently", - "没填:没有 CDK 时只能从 GitHub 下载": "Not set: without a CDK downloads come from GitHub only", "没找到 AUTO-MAS 安装目录。用 AUTO-MAS 的,反馈时请另附上它 debug 文件夹里的日志;不用 AUTO-MAS 的不用管。": "AUTO-MAS installation folder not found. If you use AUTO-MAS, attach the logs from its debug folder when you report; if you do not use AUTO-MAS, ignore this.", "没有": "None", "没有取到这个下载源的许可协议,可以换一个下载源。": "Could not get the license agreement from this source. Try another one.", @@ -555,7 +528,6 @@ "游戏、登录状态和设置都带过去了;两台的设备标识一样,别同时登同一个账号。": "Games, logins and settings came along. Both have the same device IDs, so do not log in to the same account on both at once.", "游戏已导入到{who}": "Games imported to {who}", "源模拟器实例": "Source emulator instance", - "点「更新」会先下载并核对新版(这时实例照常用),再正常关掉所有实例,管理器关闭、换上新版,换好后自动重新打开。用 AUTO-MAS 的也可以在 AUTO-MAS 里更新,它用 AUTO-MAS 设置里的更新源和 CDK;这里的更新源和 CDK 用于这里和命令行 modavd update。": "“Update” first downloads and verifies the new version (instances keep working meanwhile), then shuts down all instances normally, closes the manager, installs the new version and reopens it automatically. If you use AUTO-MAS you can also update from AUTO-MAS, which uses the update source and CDK in AUTO-MAS settings; the update source and CDK here are used here and by the command line modavd update.", "点「重试初始化」再做一次,或在「更多」里删除这台实例": "Choose “Retry initial setup” to do it again, or delete this instance under “More”", "点「重试初始化」再做一次,或在「更多」里删除这台实例;日志 {log}": "Choose “Retry initial setup” to do it again, or delete this instance under “More”. Log: {log}", "点一下输入框,再按想用的组合,至少带 Ctrl、Alt、Shift 中的一个。按一下藏起这台的窗口,再按一下叫回来;几台用同一个键就一起藏、一起显示。立即生效;关掉管理器窗口后留在托盘,照样能用。": "Click the box, then press the combination you want, with at least one of Ctrl, Alt, Shift. Press it once to hide this instance's window and again to bring it back; instances sharing a key are hidden and shown together. Takes effect at once and keeps working from the tray after the manager window is closed.", @@ -599,7 +571,6 @@ "等一会儿让登记生效,把实例关机再开机,再去登录。": "Wait a while for the registration to take effect, shut the instance down and start it again, then sign in.", "等它做完再下载": "Wait for it to finish, then download", "等它做完再导入": "Wait for it to finish, then import", - "粘贴 CDK": "Paste CDK", "系统": "System", "约 1⁠–⁠2 分钟": "about 1⁠–⁠2 minutes", "组件": "Components", @@ -635,7 +606,6 @@ "要填 1–{n} 之间的整数": "Enter a whole number from 1 to {n}", "要填 {min}–{max} 之间的整数(单位 GB)": "Enter a whole number from {min} to {max} (in GB)", "要执行桥": "Needs the execution bridge", - "要求 AUTO-MAS": "AUTO-MAS required", "要用的话在实例的「更多操作」菜单里补全": "To use it, add it from the instance's “More actions” menu", "要的是 Google 官方的 Google Play 版镜像压缩包 x86_64-34_r14.zip,或者从它里面取出的五个文件。": "Use Google's official Google Play system image archive x86_64-34_r14.zip, or the five files taken out of it.", "触发请求用时 {time}": "request took {time}", @@ -681,7 +651,6 @@ "这个目录还没有商店的五个文件:在下面下载,或者用自己的文件导入,再给实例补全。": "This folder does not have the store's five files yet: download them below or import your own, then add the store to the instance.", "这个目录还没有齐全的 KernelSU 五个文件:在下面下载或导入后,再给实例启用。": "This root does not have all five KernelSU files yet. Download or import them below before enabling KernelSU on an instance.", "这个管理器不能自己更新": "This manager cannot update itself", - "这个管理器不能自己更新:关掉所有实例和管理器后运行 tools\\modavd.exe update install。用 AUTO-MAS 的也可以在 AUTO-MAS 里更新,它用 AUTO-MAS 设置里的更新源和 CDK。": "This manager cannot update itself: shut down all instances and the manager, then run tools\\modavd.exe update install. If you use AUTO-MAS you can also update from AUTO-MAS, which uses the update source and CDK in AUTO-MAS settings.", "这个键不能用:要数字、字母、F1–F24、小键盘数字或 Home / End 这类键": "This key cannot be used: it must be a digit, letter, F1–F24, numpad digit or a key like Home / End", "这个键被别的程序占了,换一个": "This key is taken by another program; choose another", "这台实例已经不在了": "This instance no longer exists", @@ -689,7 +658,6 @@ "进行中": "Running", "进行中…": "Running…", "连不上 ModAVD 的后台服务": "Cannot reach the ModAVD background service", - "选 Mirror 酱时才用到": "Only used with MirrorChyan", "选择 Android/data 资源…": "Choose Android/data resources…", "选择实例": "Select instances", "选择源实例会按需启动它。勾选游戏会复制安装包和 OBB;Android/data 里勾选的文件夹会原样复制(游戏资源一般在 files 里,有的游戏存档也在这里)。登录状态和存在应用内部的存档、设置搬不过去,导入后要重新登录。导入期间请退出两边的游戏。": "Selecting a source starts it if needed. Selected games copy their APK and OBB. Folders you tick under Android/data are copied as they are (game resources are usually in files; some games keep saves there too). Login state and saves or settings stored inside the app itself cannot be moved, so sign in again after importing. Close the game on both instances during the import.", @@ -707,7 +675,7 @@ "问题信息已收集": "Problem info collected", "问题包只保存在这台电脑上,不会自动上传。生成以后,这里会写明包里有什么、哪些可以公开、哪些不要公开。": "The problem report is only saved on this computer and is never uploaded automatically. Once it is created, this page says what is inside and what can or must not be shared.", "问题包已生成。": "The problem report was created.", - "正在读取组件状态…": "Reading component status\u2026", + "正在读取组件状态…": "Reading component status…", "预计约 {size}(压缩前)": "About {size} before compression", "超过 GitHub Issue 附件上限 25 MB:可以少选几台实例再导出,或者删掉包里的 mas、crash 文件夹再上传。": "Larger than the 25 MB GitHub allows for an issue attachment: tick fewer instances and export again, or delete the mas and crash folders from the report before uploading.", "问题包:{path}": "Problem report: {path}", @@ -740,5 +708,8 @@ "KernelSU 组件已下载并校验。": "KernelSU components were downloaded and verified.", "正在准备 KernelSU 组件:{progress}": "Preparing KernelSU components: {progress}", "正在更新执行桥…": "Updating the execution bridge…", - "正在为执行桥重新开机…": "Restarting for the execution bridge…" + "正在为执行桥重新开机…": "Restarting for the execution bridge…", + "当前版本": "Current version", + "下载并核对新版后会正常关掉{names},然后更新。": "After downloading and verifying the package, the manager will shut down {names} and install the update.", + "更新进度": "Update progress" } diff --git a/internal/ui/API.en.md b/internal/ui/API.en.md index f96adf31..8dfecc10 100644 --- a/internal/ui/API.en.md +++ b/internal/ui/API.en.md @@ -90,7 +90,7 @@ HTTP 4xx / 5xx with the body `{"error":{"code":"…","message":"…","advice":" | GET | `/api/events` | | `text/event-stream`, see below | | GET | `/api/update` | | `UpdateView`, see below (does not use the network) | | POST | `/api/update/check` | `{}` | `UpdateView`: looks up the latest version from the configured update source (without a CDK); 409 `busy` while a check is in progress | -| POST | `/api/update/settings` | `{source?: "github"\|"mirrorchyan", cdk?: string}` | `UpdateView`; a `cdk` of `""` clears it; the CDK is stored encrypted and never returned | +| POST | `/api/update/settings` | `{source?: "github"\|"mirrorchyan", cdk?: string, github_token?: string}` | `UpdateView`; an empty string clears that credential. The CDK and token are encrypted and only their presence is returned | | POST | `/api/update/handoff/take` | `{id}` | 200 this handoff's `HandoffResult`, claimed once across all windows; `null` if already claimed or the ID does not match | | POST | `/api/update/handoff/receive` | `{id}` | 200 `{received}`, used by a restarted launcher to deliver this handoff to an already running manager | | POST | `/api/update/apply` | `{confirmed?}` | 202 `Job` (`kind` is `update`, a root job, `index` is `-1`): updates this root folder, see "Update" below; the result is `{handoff, version, stopped, message}` | @@ -206,10 +206,10 @@ The optional start-result field `language_pending: true` means the language requ ### Update `UpdateView` -All the fields of `update.Status` (the same as the `data` of `modavd update --json`: `root`, `updatable`, `not_updatable_reason`, `current_version`, `current_build`, `source`, `cdk_set`, `checked`, `check_error`, `latest_version`, `latest_source`, `update_available`, `required_automas`, `release_url`, `phase`, `prepared_version`, `last_result`, `recovered`, `updated`, `message`, `notices`), plus `checking`, `checked_at` (RFC 3339, `""` if no check has been made since this start), `error` (the error object of the last check, `null` if none), `can_install` (`POST /api/update/apply` can be tried: the manager knows how to reopen itself), `install_by_cli` (the opposite of `can_install`: it can only be installed with the command line), and `handoff` (the result that the command line left after the last click on "Update" handed over to it, `{id, at, ok, updated, version, message, error: {code, message, advice} | null}`; `null` if no handoff ID was delivered, a window has already claimed the result, or the result is older than 30 minutes). +All the fields of `update.Status` (the same as the `data` of `modavd update --json`: `root`, `updatable`, `not_updatable_reason`, `current_version`, `current_build`, `source`, `cdk_set`, `github_token_set`, `checked`, `check_error`, `latest_version`, `latest_source`, `update_available`, `required_automas`, `release_url`, `phase`, `prepared_version`, `last_result`, `recovered`, `updated`, `message`, `notices`), plus `checking`, `checked_at` (RFC 3339, `""` if no check has been made since this start), `error` (the error object of the last check, `null` if none), `can_install` (`POST /api/update/apply` can be tried: the manager knows how to reopen itself), `install_by_cli` (the opposite of `can_install`: it can only be installed with the command line), and `handoff` (the result that the command line left after the last click on "Update" handed over to it, `{id, at, ok, updated, version, message, error: {code, message, advice} | null}`; `null` if no handoff ID was delivered, a window has already claimed the result, or the result is older than 30 minutes). - `last_update_failure` contains `{code, message, advice}` if the last update started by the manager failed. It remains available after a manager restart. A successful handoff, a change to the installed version, or a newer `last_result` makes this field `null`. -- Only clicking "Check for updates" or "Update" uses the network; there is no automatic check. +- Opening Settings checks once. The "Check for updates" button checks again on request. The GitHub token is used for GitHub release checks and asset downloads. - The update source and the CDK are settings of the current system user, used by both the manager and the command line when updating; AUTO-MAS's own updater uses AUTO-MAS's settings. Windows uses `%LOCALAPPDATA%\ModAVD\update-settings.json` and DPAPI; macOS uses `~/Library/Application Support/ModAVD/update-settings.json`, with the random AES-GCM wrapping key of the CDK kept in the current user's Keychain. When the keychain is locked or access is not authorized, saving fails, no authorization prompt is shown, and no plaintext key is saved. - "Update" (`POST /api/update/apply`): the manager cannot replace itself while running, so it takes three steps. 1. The root job (`kind` is `update`) downloads, verifies and stages the package. Instances can start, stop, be created and accept operations during preparation. Other root jobs remain excluded. If already current, it finishes with `handoff` `false`. When Prepare returns `update_unavailable`, it continues offline only if the stage fingerprint and version records still match and the stage is newer than the known installed version. Cancellation, a damaged stage, and other errors still end the job. @@ -217,7 +217,7 @@ All the fields of `update.Status` (the same as the `data` of `modavd update --js 3. `host.StartOrphan` starts the root's `tools\modavd.exe --root --json update install --after-pid --reopen --handoff-id --reopen-arg …`, appending output to `logs\modavd-update.log`. The CLI takes `.update\manager-handoff.lock` and publishes its ID, PID, process creation time and root identity. The manager requires both half a second of process survival and confirmation of ownership (it waits up to 30 seconds) before the job succeeds with `{handoff: true, version, stopped, message}`. It exits about 1.5 seconds later. Cancellation before confirmation withdraws the CLI's wait and releases the gate. After confirmation the handoff cannot be canceled. The cancel mark is written next to the result file under this handoff's ID and the CLI reads it both before and after waiting for the manager, so nothing is installed even when the manager canceled and exited before the CLI started; marks left unread for more than 10 minutes are removed at the next ordinary start. The CLI waits for the manager to exit and revalidates the stage and versions. A valid newer stage is installed without another remote check. The launch gate covers waiting, replacement and recovery. A duplicate manager displays an update notice and exits (the notice is handed to the session's system process with `WTSSendMessage` and closes after 15 seconds; the manager starts no child process). Image locks also prevent new manager mappings during replacement. The OS releases the gate on process death, and a stale record cannot veto the next launch. The CLI writes the result and its random ID to `.update\manager-results\.json`, releases the launch gate, then reopens the manager with its original arguments (`--root`, plus `--port`, `--no-window` and `--dev`) and `--update-handoff `. The new manager reads only the matching result into `handoff`. If a manager is already running, the restart forwards this ID through `POST /api/update/handoff/receive`. A page first claims the result with `POST /api/update/handoff/take`. Only the receiving window shows it, and the server clears the claim. Ordinary launches ignore legacy results without an ID. Failed installation still reopens the manager and retains a valid stage for retry. Failure or cancellation releases job admission so instance operations can resume. -- When the manager installs, it does not do the AUTO-MAS version check (the same as installing by hand with the command line); when `required_automas` is not empty, the page prompts the user to update AUTO-MAS first with AUTO-MAS. +- When the manager installs, it does not do the AUTO-MAS version check (the same as installing by hand with the command line). - Refused before starting, with no job (422): not Windows, or the manager does not know how to reopen itself (`unsupported`); the root folder has no `tools\modavd.exe`, or its version differs from the manager's (`not_ready`; an older command line does not recognize these options). Conflicting root jobs get 409 `busy`. Instance operations also get 409 once the update takes exclusive admission. - Native macOS update is done with the CLI's `update prepare/install --package ZIP --sha256 HEX`, selecting a local signed package; after staging, `install/recover` can run offline. Without a compatible `macos-arm64` remote asset, the check result is `update_unavailable`. The UI offers no install entry; for the package protocol see `internal/update/MACOS.en.md`. diff --git a/internal/ui/API.md b/internal/ui/API.md index ab0698e3..222f1b79 100644 --- a/internal/ui/API.md +++ b/internal/ui/API.md @@ -90,7 +90,7 @@ HTTP 4xx / 5xx,体为 `{"error":{"code":"…","message":"…","advice":"…"," | GET | `/api/events` | | `text/event-stream`,见下 | | GET | `/api/update` | | `UpdateView`,见下(不联网) | | POST | `/api/update/check` | `{}` | `UpdateView`:按设置的更新源查最新版本(不带 CDK);检查进行中回 409 `busy` | -| POST | `/api/update/settings` | `{source?: "github"\|"mirrorchyan", cdk?: string}` | `UpdateView`;`cdk` 为 `""` 时清除,CDK 加密保存,从不返回 | +| POST | `/api/update/settings` | `{source?: "github"\|"mirrorchyan", cdk?: string, github_token?: string}` | `UpdateView`;凭据为空字符串时清除。CDK 和 token 加密保存,返回值只包含是否已保存 | | POST | `/api/update/handoff/take` | `{id}` | 200 本次交接的 `HandoffResult`,全管理器只领取一次;已领走或 ID 不匹配是 `null` | | POST | `/api/update/handoff/receive` | `{id}` | 200 `{received}`,供重开启动把本次交接结果转交给已运行的管理器 | | POST | `/api/update/apply` | `{confirmed?}` | 202 `Job`(`kind` 是 `update`,根任务,`index` 为 `-1`):更新这个根目录,见下「更新」;结果是 `{handoff, version, stopped, message}` | @@ -207,10 +207,10 @@ Apple Silicon macOS 的组件下载/导入使用 API35 Google Play ARM64 r9, ### 更新 `UpdateView` -`update.Status` 的全部字段(和 `modavd update --json` 的 `data` 相同:`root`、`updatable`、`not_updatable_reason`、`current_version`、`current_build`、`source`、`cdk_set`、`checked`、`check_error`、`latest_version`、`latest_source`、`update_available`、`required_automas`、`release_url`、`phase`、`prepared_version`、`last_result`、`recovered`、`updated`、`message`、`notices`),加上 `checking`、`checked_at`(RFC 3339,本次启动后没查过是 `""`)、`error`(上次检查的错误对象,没有是 `null`)、`can_install`(可以试 `POST /api/update/apply`:管理器知道怎么重新打开自己)、`install_by_cli`(`can_install` 的反面:只能用命令行装)、`handoff`(上次点「更新」交给命令行以后命令行留下的结果 `{id, at, ok, updated, version, message, error: {code, message, advice} | null}`;没有收到本次交接 ID、结果已被任一窗口领取、或者结果超过 30 分钟,是 `null`)。 +`update.Status` 的全部字段(和 `modavd update --json` 的 `data` 相同:`root`、`updatable`、`not_updatable_reason`、`current_version`、`current_build`、`source`、`cdk_set`、`github_token_set`、`checked`、`check_error`、`latest_version`、`latest_source`、`update_available`、`required_automas`、`release_url`、`phase`、`prepared_version`、`last_result`、`recovered`、`updated`、`message`、`notices`),加上 `checking`、`checked_at`(RFC 3339,本次启动后没查过是 `""`)、`error`(上次检查的错误对象,没有是 `null`)、`can_install`(可以试 `POST /api/update/apply`:管理器知道怎么重新打开自己)、`install_by_cli`(`can_install` 的反面:只能用命令行装)、`handoff`(上次点「更新」交给命令行以后命令行留下的结果 `{id, at, ok, updated, version, message, error: {code, message, advice} | null}`;没有收到本次交接 ID、结果已被任一窗口领取、或者结果超过 30 分钟,是 `null`)。 - `last_update_failure` 为管理器发起的更新最近一次失败的详情 `{code, message, advice}`,重新打开管理器仍可查询。成功交接、已安装版本变化或有更新的 `last_result` 后返回 `null`。 -- 只有点「检查更新」或「更新」才联网;没有自动检查。 +- 打开设置页时检查一次更新,也可手动点「检查更新」。GitHub token 用于 GitHub 的版本查询和附件下载。 - 更新源和 CDK 是当前系统用户的设置,管理器和命令行更新时都按它来;AUTO-MAS 自己的更新器用 AUTO-MAS 的设置。Windows 使用 `%LOCALAPPDATA%\ModAVD\update-settings.json` 和 DPAPI;macOS 使用 `~/Library/Application Support/ModAVD/update-settings.json`,CDK 的随机 AES-GCM 包装密钥保存在当前用户的 Keychain。钥匙串锁定或未授权时保存失败,不弹授权框,不保存明文密钥。 - 「更新」(`POST /api/update/apply`):管理器不能在自己运行时换掉自己,所以分三步。 1. 任务(`kind` 是 `update`,根任务)先下载、按清单核对、暂存好新版。这个阶段可以开机、关机、新建和操作实例,但与其他根任务互斥。已经是最新就到此为止,结果 `handoff` 为 `false`。Prepare 回 `update_unavailable` 时,只有暂存指纹和版本记录仍相符、且暂存版本比已安装的已知版本新,才离线继续;取消、损坏暂存和其他错误仍终止任务。 @@ -218,7 +218,7 @@ Apple Silicon macOS 的组件下载/导入使用 API35 Google Play ARM64 r9, 3. 用 `host.StartOrphan` 启动根目录的 `tools\modavd.exe --root <根> --json update install --after-pid <管理器 pid> --reopen <管理器程序> --handoff-id --reopen-arg …`(输出追加到 `logs\modavd-update.log`)。命令行先持有 `.update\manager-handoff.lock`,发布带本次 ID、PID、进程创建时间和根目录身份的交接记录。管理器等它存活半秒且确认持锁(最多等 30 秒)后,任务才成功,结果 `{handoff: true, version, stopped, message}`,约 1.5 秒后管理器退出。确认交接前可以取消,命令行撤销等待并释放锁;确认后不能再取消。取消标记按本次 ID 写在结果文件旁,命令行在等管理器退出的前后都会查,管理器先取消并退出、命令行才启动时也不会换包;留下没人读的标记,超过 10 分钟的在下次正常启动时清掉。命令行等旧管理器退出,重新核对暂存指纹和版本;已有较新暂存时直接换上,不重复查远端。启动锁覆盖等待、换包和恢复,重复打开的管理器提示「正在更新」后退出(提示用 `WTSSendMessage` 交给会话里的系统进程显示,15 秒自动关,管理器不起子进程);换包时程序映像锁还会阻止新的映射。进程异常退出后系统释放锁,遗留交接记录不阻挡下次启动。 命令行把结果和本次随机 ID 写进 `.update\manager-results\.json`,释放启动锁,再按原来的参数(`--root`,以及 `--port`、`--no-window`、`--dev`)重新打开管理器,通过 `--update-handoff ` 传递本次 ID。新管理器只读对应结果,放进 `handoff`。如果已有管理器在运行,这次启动通过 `POST /api/update/handoff/receive` 转交本次 ID。页面先用 `POST /api/update/handoff/take` 领取结果,只有领到的窗口提示,随后从服务端清掉。普通启动不读取无 ID 的旧版结果。换不上也照样重新打开,仍有效的暂存留着,下次不用重下。失败和取消会释放任务独占,允许再次操作实例。 -- 管理器装的时候不带 AUTO-MAS 的版本检查(和人用命令行装一样),页面在 `required_automas` 不为空时提示用 AUTO-MAS 的先更新 AUTO-MAS。 +- 管理器装的时候不带 AUTO-MAS 的版本检查(和人用命令行装一样)。 - 开始前就拒绝、不开任务(422):不是 Windows,或者管理器不知道怎么重新打开自己(`unsupported`);根目录没有 `tools\modavd.exe`,或者它的版本和管理器不一样(`not_ready`,旧版命令行不认这些选项)。与其他根任务冲突时回 409 `busy`;更新进入独占后,实例操作也回 409。 - macOS 原生更新由 CLI 的 `update prepare/install --package ZIP --sha256 HEX` 选择本地签名包;暂存后可离线 `install/recover`。没有兼容的 `macos-arm64` 远端资产时,检查结果为 `update_unavailable`。界面不提供安装入口;包协议见 `internal/update/MACOS.md`。 diff --git a/internal/ui/http_test.go b/internal/ui/http_test.go index 00b74a3f..47961dd8 100644 --- a/internal/ui/http_test.go +++ b/internal/ui/http_test.go @@ -350,6 +350,13 @@ func TestUpdateSettings(t *testing.T) { } expectError(t, h.do("POST", "/api/update/settings", `{}`), 400, errs.Usage) expectError(t, h.do("POST", "/api/update/settings", `{"source":"ftp"}`), 400, errs.InvalidArgument) + resp = h.do("POST", "/api/update/settings", `{"source":"github","github_token":"github_pat_fixture_428"}`) + body = readBody(t, resp) + if resp.StatusCode != http.StatusOK || strings.Contains(body, "github_pat_fixture_428") || + !strings.Contains(body, `"github_token_set":true`) { + t.Fatalf("POST GitHub token: unexpected response %d", resp.StatusCode) + } + expectError(t, h.do("POST", "/api/update/settings", `{"github_token":"token with spaces"}`), 400, errs.InvalidArgument) // a manager that cannot start itself again (no Options.Reopen) does not install expectError(t, h.do("POST", "/api/update/apply", `{}`), 422, errs.Unsupported) } diff --git a/internal/ui/update.go b/internal/ui/update.go index 03da48ef..44d92e2f 100644 --- a/internal/ui/update.go +++ b/internal/ui/update.go @@ -2,8 +2,7 @@ package ui // The update part of the manager's settings (API.md "更新"): the root's ModAVD package version and update state, the // update source (GitHub / MirrorChyan) and the MirrorChyan CDK, a check on request, and 更新 (update_apply.go). The -// source and CDK are also `modavd update`'s; AUTO-MAS's own updater uses AUTO-MAS's settings. Nothing goes online -// unless the user clicks 检查更新 or 更新. +// source and credentials are also used by `modavd update`. Opening the settings page checks the chosen source. import ( "context" @@ -175,24 +174,25 @@ func (s *server) handleUpdateCheck(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, v) } -// handleUpdateSettings: {source?, cdk?} — cdk "" clears it; it is stored encrypted and never sent back. +// handleUpdateSettings accepts only settings changes, with an empty credential clearing it. func (s *server) handleUpdateSettings(w http.ResponseWriter, r *http.Request) { var body struct { - Source *string `json:"source"` - CDK *string `json:"cdk"` + Source *string `json:"source"` + CDK *string `json:"cdk"` + GitHubToken *string `json:"github_token"` } if !decode(w, r, &body) { return } - if body.Source == nil && body.CDK == nil { - writeError(w, errs.New(errs.Usage, "要给 source 或 cdk")) + if body.Source == nil && body.CDK == nil && body.GitHubToken == nil { + writeError(w, errs.New(errs.Usage, "请提供要修改的更新设置")) return } source := "" if body.Source != nil { source = *body.Source } - if _, err := update.SaveSettings(source, body.CDK); err != nil { + if _, err := update.SaveCredentials(source, body.CDK, body.GitHubToken); err != nil { writeError(w, err) return } diff --git a/internal/ui/update_apply.go b/internal/ui/update_apply.go index 7d993b9b..4d5bb59f 100644 --- a/internal/ui/update_apply.go +++ b/internal/ui/update_apply.go @@ -87,7 +87,7 @@ func (s *server) applyReady() error { } func (s *server) handleUpdateApply(w http.ResponseWriter, r *http.Request) { - // Confirmed: the running instances the user agreed to have shut down (the page's second confirmation). Absent: + // Confirmed: the running instances the user agreed to have shut down. Absent: // whatever runs when the download is done is stopped, as before. var body struct { Confirmed *[]int `json:"confirmed"` diff --git a/internal/ui/web/app.css b/internal/ui/web/app.css index 8e6a6ebd..8b8f9e45 100644 --- a/internal/ui/web/app.css +++ b/internal/ui/web/app.css @@ -917,9 +917,25 @@ dialog > .toasts .toast.out { animation-name: toast-out-left; } .game-resource-folder { display: flex; align-items: baseline; gap: .4rem; } .dlg-update .dlg-body { display: grid; gap: 12px; } .upd-panel { display: grid; gap: 12px; } -.upd-msg { margin: 0; color: var(--text); } -.upd-cdk { display: flex; gap: 8px; align-items: center; } -.upd-cdk .input { flex: 1; min-width: 0; } +.dlg-manager-settings { --w: 660px; height: auto; } +.dlg-manager-settings .fields { grid-template-columns: 9rem minmax(0, 1fr); align-items: center; } +.dlg-manager-settings .f-label { padding-top: 0; } +.dlg-manager-settings .select { width: 100%; } +.upd-source-choice { grid-column: 2; } +.upd-version { font-variant-numeric: tabular-nums; } +.upd-actions, .upd-inline { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } +.upd-inline .input { flex: 1; min-width: min(100%, 12rem); } +.upd-root { flex-wrap: nowrap; } +.upd-root .diag-path { margin: 0; flex: 1; min-width: 0; } +.upd-root .btn { flex: none; } +.upd-progress { display: grid; gap: 8px; } +.upd-progress[hidden] { display: none; } +.upd-progress progress { width: 100%; accent-color: var(--bar-fill); } +.upd-progress [role="status"] { white-space: pre-line; } +@media (max-width: 540px) { + .dlg-manager-settings .fields { grid-template-columns: minmax(0, 1fr); } + .upd-source-choice { grid-column: 1; } +} .upd-dot { background: var(--err); min-width: 8px; height: 8px; padding: 0; } /* 按应用走代理 */ .dlg-proxy { --w: 520px; } diff --git a/internal/ui/web/dev/mock.js b/internal/ui/web/dev/mock.js index bae99958..65237c90 100644 --- a/internal/ui/web/dev/mock.js +++ b/internal/ui/web/dev/mock.js @@ -961,6 +961,11 @@ function validate(b, create) { const runningJobOf = (i) => db.jobs.find((j) => j.index === i && j.state === 'running'); +const updateView = { + source: 'github', cdk_set: false, github_token_set: false, current_version: 'v0.45.0', + latest_version: '', updatable: true, can_install: true, checking: false, +}; + async function handle(url, init) { const method = (init.method || 'GET').toUpperCase(); const p = url.pathname; @@ -981,6 +986,34 @@ async function handle(url, init) { return json({ preference: db.theme || 'system', saved: !!db.theme }); } if (p === '/api/info') return json({ version: '0.1.0', protocol: 1, root: rootInfo() }); + if (p === '/api/update') return json(updateView); + if (p === '/api/update/check' && method === 'POST') { + await sleep(400); + Object.assign(updateView, { checked: true, latest_version: 'v0.46.0', update_available: true }); + return json(updateView); + } + if (p === '/api/update/settings' && method === 'POST') { + if (body.cdk && /[\s&?#=]/.test(body.cdk)) return errResp('invalid_argument', 'CDK 的格式不对'); + if (body.github_token && /[^a-zA-Z0-9_]/.test(body.github_token)) return errResp('invalid_argument', 'GitHub token 的格式不对'); + if ('cdk' in body) updateView.cdk_set = !!body.cdk; + if ('github_token' in body) updateView.github_token_set = !!body.github_token; + if ('source' in body) updateView.source = body.source; + return json(updateView); + } + if (p === '/api/update/apply' && method === 'POST') { + const j = newJob('update', -1); + (async () => { + for (const progress of [200, 400, 600, 800, 1000]) { + step(j, 'downloading', `正在下载:${progress / 10}%`, progress); + await sleep(350); + } + updateView.current_version = updateView.latest_version; + updateView.update_available = false; + finishJob(j, { message: '已更新到 ' + updateView.current_version }); + emit('update', updateView); + })(); + return json(j, 202); + } if (p === '/api/instances' && method === 'GET') return json(list()); if (p === '/api/instances' && method === 'POST') { if ('play_store' in body) return errResp('usage', '新建不带 Google Play 商店(没有 play_store 字段)', '建好后在实例的「更多操作」里补全'); diff --git a/internal/ui/web/js/actions.js b/internal/ui/web/js/actions.js index 32fe2635..398c5037 100644 --- a/internal/ui/web/js/actions.js +++ b/internal/ui/web/js/actions.js @@ -41,7 +41,9 @@ const safe = (fn) => async (...a) => { try { return await fn(...a); } catch (e) export function onJob(job) { if (!job || !job.id) return; const prev = S.jobs.get(job.id); - if (prev && job.state === 'running' && (prev.state !== 'running' || (prev.progress && job.progress && job.progress.done < prev.progress.done))) return; + const sameProgressScale = job.kind !== 'update' || prev?.progress?.step === job.progress?.step; + if (prev && job.state === 'running' && (prev.state !== 'running' || + (sameProgressScale && prev.progress && job.progress && job.progress.done < prev.progress.done))) return; S.jobs.set(job.id, job); // components were just installed: 组件 and its chip in the top bar read the root again (the server dropped its cached check) if (job.kind === 'components' && job.state === 'done' && prev && prev.state === 'running') runCheck(true); @@ -61,6 +63,10 @@ function notify(job) { const who = job.index < 0 ? '' : quoted(instance(job.index), job.index); const r = job.result || {}; const e = job.error || {}; + if (job.kind === 'update') { + if (r.handoff) setTimeout(() => window.close(), 1200); + return; + } const activity = { label: t('查看详情'), run: () => openActivity(job.id) }; if (job.state === 'failed') toast({ tone: 'err', title: who ? t('{who}{what}没有成功', { who, what: VERB[job.kind] || '' }) : t('{what}没有成功', { what: VERB[job.kind] || '' }), text: e.message, advice: job.kind === 'playstore-import' ? importAdvice(e) : e.advice, action: activity }); else if (job.state === 'canceled') { if (isBoot(job)) toast({ tone: 'info', title: t('已停止等待'), text: t('{who}的模拟器会继续开机。', { who }) }); } @@ -104,13 +110,6 @@ function notify(job) { toast({ title: t('{who}已导入 KernelSU 模块', { who }), text: ksuText(job.kind, r), timeout: 9000 }); } else if (job.kind === 'ksu-module-remove') { toast({ title: t('{who}已移除 KernelSU 模块', { who }), text: ksuText(job.kind, r), timeout: 6000 }); - } else if (job.kind === 'update') { - if (!r.handoff) toast({ tone: 'info', title: r.message || t('已经是最新版本') }); - else { - // the manager exits now and tools\modavd.exe starts it again after the swap, in a new window - toast({ title: t('正在换上新版'), text: t('{message}。这个窗口会自己关掉。', { message: r.message || '' }), timeout: 15000 }); - setTimeout(() => window.close(), 1200); - } } } diff --git a/internal/ui/web/js/settings-page.js b/internal/ui/web/js/settings-page.js index 41f6ece1..1c2405cd 100644 --- a/internal/ui/web/js/settings-page.js +++ b/internal/ui/web/js/settings-page.js @@ -1,11 +1,11 @@ import { t, localeView, setPreference } from './i18n.js'; -import { h, icon, btn, setText } from './dom.js'; +import { h, icon, btn, setText, showError } from './dom.js'; import { S, subscribe } from './store.js'; -import { openDialog, toastError } from './ui.js'; -import { openFolder } from './actions.js'; +import { openDialog } from './ui.js'; +import { api } from './api.js'; import { createUpdatePanel } from './update.js'; -function languageSelect() { +function languageSelect(error) { const locale = localeView(); const languages = locale.languages || []; const system = languages.find((language) => language.code === locale.system); @@ -15,13 +15,14 @@ function languageSelect() { select.value = locale.preference || 'auto'; select.addEventListener('change', async () => { select.disabled = true; + error.hidden = true; try { await setPreference(select.value); location.reload(); } catch (e) { select.disabled = false; select.value = locale.preference || 'auto'; - toastError(e); + showError(error, e); } }); return select; @@ -34,22 +35,27 @@ function section(id, title, ...children) { let current = null; -// 设置: 更新, then 通用 (the language and the root folder). The components are under 组件 in the top bar (panels.js -// openComponents), not here. target 'update' lands on 更新. +// target 'update' focuses the update section when opening Settings from a deep link. export function openManagerSettings(target) { if (current) { current.go(target); return; } const update = createUpdatePanel(); - const updates = section('manager-update', t('更新'), update.body, update.foot); + const updates = section('manager-update', t('更新'), update.body); + const sources = section('manager-update-source', t('更新源'), update.source); const path = h('span', { class: 'diag-path' }); - const folder = btn('btn btn-secondary btn-sm', [icon('folder'), t('打开目录')], () => openFolder('root')); + const error = h('div', { class: 'form-error', role: 'alert', hidden: true }); + const folder = btn('btn btn-secondary btn-sm', [icon('folder'), t('打开目录')], async () => { + error.hidden = true; + try { await api.post('/api/open', { what: 'root' }); } + catch (e) { showError(error, e); } + }); const general = section('manager-general', t('通用'), h('div', { class: 'fields' }, - h('label', { class: 'f-label', for: 'upd-lang', text: t('语言') }), languageSelect(), - h('span', { class: 'f-label', text: t('根目录') }), h('div', { class: 'f-ctl' }, path, h('div', null, folder)))); - const ctl = openDialog({ title: t('设置'), cls: 'dlg-check', light: true, - body: h('div', { class: 'dlg-body' }, updates, general) }); + h('label', { class: 'f-label', for: 'upd-lang', text: t('语言') }), languageSelect(error), + h('span', { class: 'f-label', text: t('根目录') }), h('div', { class: 'f-ctl upd-inline upd-root' }, path, folder)), error); + const ctl = openDialog({ title: t('设置'), cls: 'dlg-check dlg-manager-settings', light: true, + body: h('div', { class: 'dlg-body' }, updates, sources, general) }); function go(target) { if (target !== 'update') return; @@ -68,4 +74,5 @@ export function openManagerSettings(target) { ctl.onClose.push(() => { unsubscribe(); update.dispose(); current = null; }); render(); go(target); + update.check(); } diff --git a/internal/ui/web/js/update.js b/internal/ui/web/js/update.js index 3816200c..4df40528 100644 --- a/internal/ui/web/js/update.js +++ b/internal/ui/web/js/update.js @@ -1,223 +1,200 @@ -// 设置 → ModAVD 更新 (API.md "更新"): version and update state of this root, the update source and the Mirror 酱 CDK, -// a check on request, and 更新: the server's update job downloads and verifies, stops the instances and hands the swap -// to tools\modavd.exe; the manager then closes and is started again by it (update_apply.go), and that manager shows -// what happened (v.handoff). These settings are also `modavd update`'s; AUTO-MAS's own updater uses its own. - -import { t, lang, paren, colon } from './i18n.js'; +// Settings and the whole-package update workflow (internal/ui/API.md). +import { t, lang } from './i18n.js'; import { h, icon, btn, attr, setText, showError } from './dom.js'; import { S, update, subscribe } from './store.js'; import { api } from './api.js'; -import { openDialog, toast, toastError } from './ui.js'; -import { activeJob, progressText } from './diagnostics.js'; +import { openDialog } from './ui.js'; +import { activeJob, latestJob, progressText } from './diagnostics.js'; import { onJob, notifyJob } from './actions.js'; import { quoted } from './format.js'; -const clock = (ms) => new Date(ms).toLocaleString(lang(), { hour12: false }); -const ver = (v) => (v ? v.replace(/^v/, '') : ''); -const PHASE = { idle: '', preparing: t('正在准备新版'), staged: t('新版已下载并核对好,待安装'), swapping: t('正在换上新版') }; -const NOTE = t('点「更新」会先下载并核对新版(这时实例照常用),再正常关掉所有实例,管理器关闭、换上新版,换好后自动重新打开。用 AUTO-MAS 的也可以在 AUTO-MAS 里更新,它用 AUTO-MAS 设置里的更新源和 CDK;这里的更新源和 CDK 用于这里和命令行 modavd update。'); -const NOTE_CLI = t('这个管理器不能自己更新:关掉所有实例和管理器后运行 tools\\modavd.exe update install。用 AUTO-MAS 的也可以在 AUTO-MAS 里更新,它用 AUTO-MAS 设置里的更新源和 CDK。'); - +const ver = (v) => v?.replace(/^v/, '') || ''; let pending = null; - -async function runUpdateRequest(request, run) { - if (pending || S.update?.checking || activeJob('update')) return; - pending = request; - update(); - try { - await run(); - } catch (e) { - toastError(e); - } finally { - pending = null; - update(); - } -} +let handoffResult = null; export function loadUpdate() { return api.get('/api/update').then(onUpdate).catch(() => {}); } -// GET /api/update, the "update" event and every answer of the settings API. export function onUpdate(v) { S.update = v; - showHandoff(v.handoff); + claimHandoff(v.handoff); update(); } -// The server grants the notification to one page across all manager windows. +// Keep the restart result on this page after the server broadcasts that it has been claimed. const handoffClaims = new Set(); -async function showHandoff(x) { - if (!x || !x.id || handoffClaims.has(x.id)) return; +async function claimHandoff(x) { + if (!x?.id || handoffClaims.has(x.id)) return; handoffClaims.add(x.id); try { const claimed = await api.post('/api/update/handoff/take', { id: x.id }); - if (!claimed) return; - if (claimed.ok) toast({ title: claimed.updated ? t('已更新到 {version}', { version: ver(claimed.version) }) : (claimed.message || t('已经是最新版本')), timeout: 9000 }); - else toast({ tone: 'err', title: t('新版没有换上'), text: (claimed.error && claimed.error.message) || claimed.message, advice: claimed.error && claimed.error.advice, timeout: 15000 }); + if (claimed) { + handoffResult = claimed; + update(); + } } catch { handoffClaims.delete(x.id); } } -// 更新 may be clicked: this manager can come back after the swap, the root can be updated, a check found a newer -// version (or one is already downloaded), and no update is running. -const installable = (v) => !!(v && v.can_install && v.updatable && (v.update_available || v.prepared_version) +const installable = (v) => !!(v?.can_install && v.updatable && (v.update_available || v.prepared_version) && !pending && !v.checking && !activeJob('update')); -function installTitle(v) { - if (!v) return ''; - if (activeJob('update')) return t('正在更新'); - if (!v.can_install) return t('这个管理器不能自己更新'); - if (!v.updatable) return v.not_updatable_reason; - if (!v.update_available && !v.prepared_version && (!v.checked || v.error)) return t('先点「检查更新」'); - return ''; -} - -// The confirmation, then the update job (its end: actions.js notify, which closes this window on a hand-off). With -// instances running, a second confirmation names them: the update shuts them all down normally (as 关机 does). -function confirmInstall(v) { - const target = ver(v.prepared_version || v.latest_version); - const runningList = ((S.list && S.list.instances) || []).filter((x) => x.running); - const running = runningList.length; - const body = running - ? t('先下载并核对新版,这时实例照常用;然后正常关掉正在运行的 {n} 台实例(安卓正常关机),管理器关闭、换上新版,换好后自动重新打开管理器。', { n: running }) - : t('先下载并核对新版,这时实例照常用(现在没有实例在运行);然后管理器关闭、换上新版,换好后自动重新打开管理器。'); - const apply = () => runUpdateRequest({ kind: 'install' }, async () => { - // what the user just agreed to shut down: one started while the download runs makes the update stop and ask again - const j = await api.post('/api/update/apply', { confirmed: runningList.map((x) => x.index) }); - const seen = S.jobs.get(j.id); - if (seen && seen.state !== 'running') notifyJob(seen); - else { - S.watch.add(j.id); - onJob(j); - } - }); - const confirmStop = () => { - const names = runningList.map((x) => quoted(x, x.index)).join(lang() === 'en' ? ', ' : ''); - const stop = btn('btn btn-primary', [icon('stop'), t('关机并更新')], () => { second.close(); apply(); }); - const second = openDialog({ - title: t('要关掉 {n} 台实例', { n: running }), light: true, - body: h('div', { class: 'dlg-body' }, - h('p', { text: t('更新会正常关掉{names},和点「关机」一样。实例里正在跑的游戏和任务会中断,更新完要自己再开机。', { names }) })), - actions: { ok: stop }, - }); - }; - const go = btn('btn btn-primary', [icon('download'), t('更新')], () => { +function confirmInstall(apply) { + const running = (S.list?.instances || []).filter(x => x.running); + const confirmed = running.map(x => x.index); + if (!running.length) { + apply(confirmed); + return; + } + const names = running.map(x => quoted(x, x.index)).join(lang() === 'en' ? ', ' : ''); + const go = btn('btn btn-primary', [icon('stop'), t('关机并更新')], () => { dlg.close(); - if (running) confirmStop(); - else apply(); + apply(confirmed); }); const dlg = openDialog({ - title: t('更新到 {target}', { target }), sub: t('ModAVD 整包:模拟器、组件、脚本和管理器'), light: true, + title: t('要关掉 {n} 台实例', { n: running.length }), light: true, body: h('div', { class: 'dlg-body' }, - h('p', { text: body }), - h('p', { class: 'f-hint', text: t('实例的数据(avd 文件夹)和设置都不动。正在新建的实例要先等它建完;用 modavd mcp 的 AI 助手等程序也要先关掉。') })), + h('p', { text: t('下载并核对新版后会正常关掉{names},然后更新。', { names }) })), actions: { ok: go }, }); } -// The chip: 设置, with a dot when a check found a newer ModAVD. export function renderUpdateChip(chip, badge) { const v = S.update; - const fresh = !!(v && v.update_available); + const fresh = !!v?.update_available; badge.hidden = !fresh; chip.title = fresh ? t('有新版本 ModAVD {version}', { version: ver(v.latest_version) }) : t('设置'); chip.setAttribute('aria-label', fresh ? t('设置,有新版本 ModAVD {version}', { version: ver(v.latest_version) }) : chip.title); } export function createUpdatePanel() { - const box = h('div', { class: 'form-error', role: 'alert', hidden: true }); - const kv = h('dl', { class: 'kv', hidden: true }); - const msg = h('p', { class: 'upd-msg', hidden: true }); - const radios = ['github', 'mirrorchyan'].map((value) => h('input', { type: 'radio', name: 'upd-src', value })); - const seg = h('div', { class: 'seg', role: 'radiogroup', 'aria-labelledby': 'upd-src-l' }, + const current = h('span', { class: 'upd-version' }); + const latest = h('span', { class: 'upd-version' }); + const bar = h('progress', { max: '100', 'aria-label': t('更新进度') }); + const status = h('span', { role: 'status' }); + const error = h('div', { class: 'form-error', role: 'alert', hidden: true }); + const progress = h('div', { class: 'upd-progress', hidden: true }, bar, status, error); + const radios = ['github', 'mirrorchyan'].map(value => h('input', { type: 'radio', name: 'upd-src', value })); + const seg = h('div', { class: 'seg', role: 'radiogroup', 'aria-labelledby': 'manager-update-source' }, h('label', null, radios[0], h('span', { text: 'GitHub' })), h('label', null, radios[1], h('span', { text: t('Mirror 酱') }))); - const cdk = h('input', { type: 'password', id: 'upd-cdk', class: 'input', autocomplete: 'off', spellcheck: 'false', maxlength: '256' }); - const cdkState = h('p', { class: 'f-hint' }); - const save = btn('btn btn-secondary', t('保存 CDK'), () => cdk.value.trim() && saveSettings({ cdk: cdk.value.trim() }, t('已保存 CDK'))); - const clear = btn('btn btn-ghost', t('清除'), () => saveSettings({ cdk: '' }, t('已清除 CDK'))); - const fields = h('div', { class: 'fields' }, - h('span', { class: 'f-label', id: 'upd-src-l', text: t('更新源') }), h('div', { class: 'f-ctl' }, seg), - h('label', { class: 'f-label', for: 'upd-cdk', text: t('Mirror 酱 CDK') }), - h('div', { class: 'f-ctl' }, h('div', { class: 'upd-cdk' }, cdk, save, clear), cdkState)); - const note = h('p', { class: 'f-hint' }); - const when = h('span', { class: 'foot-note', role: 'status' }); - const checkBtn = btn('btn btn-secondary', [icon('refresh'), t('检查更新')], () => - runUpdateRequest({ kind: 'check' }, () => api.post('/api/update/check').then(onUpdate))); - const installBtn = btn('btn btn-primary', [icon('download'), t('更新')], () => installable(S.update) && confirmInstall(S.update), { disabled: true }); - for (const r of radios) r.addEventListener('change', () => r.checked && saveSettings({ source: r.value })); - - function saveSettings(body, done) { - return runUpdateRequest({ kind: 'settings', source: body.source }, async () => { - onUpdate(await api.post('/api/update/settings', body)); - if (done) { - cdk.value = ''; - toast({ title: done }); + const secretLabel = h('label', { class: 'f-label', for: 'upd-credential' }); + const secret = h('input', { type: 'password', id: 'upd-credential', class: 'input', autocomplete: 'off', spellcheck: 'false', maxlength: '256' }); + const save = btn('btn btn-secondary', t('保存'), () => saveCredential(secret.value.trim())); + const clear = btn('btn btn-ghost', t('清除'), () => saveCredential('')); + const source = h('div', { class: 'fields' }, + h('div', { class: 'f-ctl upd-source-choice' }, seg), + secretLabel, h('div', { class: 'f-ctl upd-inline' }, secret, save, clear)); + const checkBtn = btn('btn btn-secondary', [icon('refresh'), t('检查更新')], () => check()); + const installBtn = btn('btn btn-primary', [icon('download'), t('更新')], () => { + if (installable(S.update)) confirmInstall(apply); + }, { disabled: true }); + + let requestError = null; + let credentialSource; + function run(request, action) { + if (pending || S.update?.checking || activeJob('update')) return; + pending = request; + requestError = null; + render(); + update(); + return Promise.resolve().then(action).catch(e => { requestError = e; }).finally(() => { + pending = null; + render(); + update(); + }); + } + + function check() { + return run({ kind: 'check' }, () => api.post('/api/update/check').then(onUpdate)); + } + + function apply(confirmed) { + return run({ kind: 'install' }, async () => { + const j = await api.post('/api/update/apply', { confirmed }); + const seen = S.jobs.get(j.id); + if (seen && seen.state !== 'running') notifyJob(seen); + else { + S.watch.add(j.id); + if (!seen) onJob(j); } }); } + function saveCredential(value) { + const key = credentialSource === 'mirrorchyan' ? 'cdk' : 'github_token'; + return run({ kind: 'settings' }, async () => { + onUpdate(await api.post('/api/update/settings', { [key]: value })); + secret.value = ''; + }); + } + + for (const r of radios) r.addEventListener('change', () => { + if (r.checked) run({ kind: 'settings', source: r.value }, () => api.post('/api/update/settings', { source: r.value }).then(onUpdate)); + }); + secret.addEventListener('input', () => { save.disabled = secret.disabled || !secret.value.trim(); }); + secret.addEventListener('keydown', e => { + if (e.key === 'Enter' && !save.disabled) { + e.preventDefault(); + saveCredential(secret.value.trim()); + } + }); + const render = () => { const v = S.update; const job = activeJob('update'); + const lastJob = latestJob('update'); const checking = v?.checking || pending?.kind === 'check'; - const installing = !!job || pending?.kind === 'install'; + const installing = !!job || pending?.kind === 'install' || !!lastJob?.result?.handoff; const blocked = !!pending || checking || installing; + const chosen = pending?.source || v?.source || 'github'; + if (credentialSource !== chosen) { + credentialSource = chosen; + secret.value = ''; + } for (const r of radios) { r.disabled = !v || blocked; - r.checked = r.value === (pending?.source || v?.source || 'github'); + r.checked = r.value === chosen; } - cdk.disabled = save.disabled = clear.disabled = !v || blocked; - clear.hidden = !v?.cdk_set; + const mirror = chosen === 'mirrorchyan'; + const stored = mirror ? v?.cdk_set : v?.github_token_set; + setText(secretLabel, mirror ? t('Mirror 酱 CDK') : t('GitHub token')); + secret.placeholder = stored ? t('已填,输入新的会替换') : ''; + secret.disabled = clear.disabled = !v || blocked; + save.disabled = secret.disabled || !secret.value.trim(); + clear.hidden = !stored; + + setText(current, ver(v?.current_version) || '—'); + setText(latest, ver(v?.latest_version || v?.prepared_version) || '—'); checkBtn.disabled = blocked; - if (!v) return; - const rows = []; - if (v.not_updatable_reason) rows.push([t('不能更新'), v.not_updatable_reason]); - if (v.checked && v.update_available) { - const source = v.latest_source === 'mirrorchyan' ? t('Mirror 酱') : 'GitHub'; - rows.push([t('最新版本'), t('可以更新到 {version}', { version: ver(v.latest_version) }) + paren(source)]); - } - if (v.update_available && v.required_automas) rows.push([t('要求 AUTO-MAS'), t('{version} 或更新(用 AUTO-MAS 的才要)', { version: v.required_automas })]); - const phase = PHASE[v.phase] || ''; - if (phase) rows.push([t('状态'), v.prepared_version ? phase + colon() + ver(v.prepared_version) : phase]); - const lr = v.last_result; - const failure = v.last_update_failure || (lr?.action && lr.ok === false ? { message: lr.error, advice: lr.advice } : null); - if (failure) { - rows.push([t('上次'), t('更新没成功:{reason}', { reason: failure.message || t('原因未知') }), - failure.advice || t('处理上述原因后,再试一次更新。')]); - } - kv.replaceChildren(...rows.flatMap(([key, value, advice]) => [ - h('dt', { text: key }), - h('dd', null, h('span', { class: 'v' }, value, advice && h('span', { class: 'dim', text: advice }))), - ])); - kv.hidden = rows.length === 0; - // the server's own message when the rows above do not say it: after a successful check it only repeats 最新版本 - // or 已是最新; otherwise it is news (macOS: the files and signature verified, ready to install offline; a check - // that failed with a version already prepared) - const line = job ? progressText(job) : (!v.checked && v.message) || ''; - setText(msg, line); - msg.hidden = !line; - setText(note, v.can_install ? NOTE : NOTE_CLI); - if (v.error && !checking) showError(box, v.error); - else box.hidden = true; - setText(cdkState, v.cdk_set ? t('已填(加密保存在本机,只有这个 Windows 用户能读)') : v.source === 'mirrorchyan' ? t('没填:没有 CDK 时只能从 GitHub 下载') : t('选 Mirror 酱时才用到')); - cdk.placeholder = v.cdk_set ? t('已填,输入新的会替换') : t('粘贴 CDK'); - const current = v.checked && !checking && !v.error && !v.not_updatable_reason && !v.update_available && !v.prepared_version; - setText(when, current ? t('已是最新') : v.checked_at ? t('检查于 {time}', { time: clock(v.checked_at) }) : ''); - checkBtn.replaceChildren(checking ? h('span', { class: 'spin' }) : icon('refresh'), checking ? t('正在检查…') : t('检查更新')); + installBtn.disabled = installing || !installable(v); attr(checkBtn, 'aria-busy', checking || null); - installBtn.replaceChildren(installing ? h('span', { class: 'spin' }) : icon('download'), installing ? t('正在更新…') : t('更新')); - const can = installable(v); - installBtn.disabled = !can; - attr(installBtn, 'aria-disabled', can ? null : 'true'); attr(installBtn, 'aria-busy', installing || null); - attr(installBtn, 'title', installTitle(v) || null); + attr(installBtn, 'title', !v?.can_install ? t('这个管理器不能自己更新') : v?.not_updatable_reason || null); + + const failedHandoff = handoffResult && !handoffResult.ok ? handoffResult.error || handoffResult : v?.last_update_failure; + const failure = !checking && !installing && (requestError || v?.error || lastJob?.error || failedHandoff); + const activity = job ? progressText(job) : checking ? t('正在检查…') : installing ? lastJob?.result?.message || t('正在更新…') + : lastJob?.result?.message || (handoffResult?.ok ? handoffResult.message : ''); + const warning = !checking && !requestError && (job || lastJob)?.warnings?.at(-1); + const message = [failure ? '' : activity, warning].filter(Boolean).join('\n'); + const step = job?.progress; + attr(bar, 'value', step?.total > 0 ? 100 * step.done / step.total : null); + bar.hidden = !checking && !installing; + setText(status, message); + status.hidden = !message; + if (failure) showError(error, failure); + else error.hidden = true; + progress.hidden = !failure && !message; }; render(); return { - body: h('div', { class: 'upd-panel' }, msg, box, kv, fields, note), - foot: h('footer', { class: 'dlg-foot' }, when, checkBtn, installBtn), - dispose: subscribe(render), + body: h('div', { class: 'upd-panel' }, + h('div', { class: 'fields upd-versions' }, + h('span', { class: 'f-label', text: t('当前版本') }), current, + h('span', { class: 'f-label', text: t('最新版本') }), latest), + h('div', { class: 'upd-actions' }, checkBtn, installBtn), progress), + source, check, dispose: subscribe(render), }; } diff --git a/internal/update/caller_settings_test.go b/internal/update/caller_settings_test.go index b994ad8a..4e9b1f0f 100644 --- a/internal/update/caller_settings_test.go +++ b/internal/update/caller_settings_test.go @@ -7,6 +7,8 @@ import ( "context" "encoding/base64" "encoding/json" + "io" + "net/http" "os" "path/filepath" "strings" @@ -91,6 +93,83 @@ func settingsBytes(t *testing.T) []byte { return b } +func TestSavedGitHubToken(t *testing.T) { + const token = "github_pat_fixture_428" + const cdk = "test-mirror-cdk" + withSettings(t, SourceMirrorChyan, cdk) + value := token + if _, err := SaveCredentials("", nil, &value); err != nil { + t.Fatal(err) + } + if b := settingsBytes(t); bytes.Contains(b, []byte(token)) || !bytes.Contains(b, []byte("github_token")) { + t.Fatal("credential was not saved as encrypted data") + } + u := New(writeRoot(t, 36, nil), nil, Options{}) + seen := map[string]int{} + u.httpClient = &http.Client{Transport: sourceTransport(func(req *http.Request) (*http.Response, error) { + host := req.URL.Hostname() + seen[host]++ + resp := &http.Response{StatusCode: 200, Header: make(http.Header), Request: req} + body := "" + auth := req.Header.Get("Authorization") + switch host { + case "mirrorchyan.com": + if req.URL.Query().Has("cdk") || auth != "" { + t.Error("mirror version check sent a credential") + } + body = `{"code":0,"data":{"version_name":"v0.37.0"}}` + case "api.github.com": + if auth != "Bearer "+token { + t.Error("GitHub request missing the saved token") + } + if req.URL.String() == githubAPI { + body = `{"tag_name":"v0.37.0","assets":[{"id":99,"name":"ModAVD-0.37.0-` + platform + `.zip","browser_download_url":"https://github.com/test.zip","size":3}]}` + } else { + if !strings.HasSuffix(req.URL.Path, "/assets/99") || req.Header.Get("Accept") != "application/octet-stream" { + t.Error("expected the binary asset endpoint") + } + resp.StatusCode = 302 + resp.Header.Set("Location", "https://release-assets.githubusercontent.com/package.zip") + } + case "release-assets.githubusercontent.com": + if auth != "" { + t.Error("download redirect received the token") + } + body = "zip" + if req.Header.Get("Range") == "bytes=0-1" { + body, resp.StatusCode = "zi", http.StatusPartialContent + resp.Header.Set("Content-Range", "bytes 0-1/3") + } + default: + t.Fatalf("unexpected request to %s", host) + } + resp.Body = io.NopCloser(strings.NewReader(body)) + resp.ContentLength = int64(len(body)) + return resp, nil + })} + st, err := u.Check(t.Context()) + if err != nil || st.LatestSource != SourceMirrorChyan || !st.GitHubTokenSet || seen["mirrorchyan.com"] != 1 { + t.Fatalf("MirrorChyan check: status=%+v err=%v", st, err) + } + if _, err := SaveSettings(SourceGitHub, nil); err != nil { + t.Fatal(err) + } + r, err := u.pick(t.Context(), u.status()) + if err != nil || r == nil { + t.Fatalf("GitHub selection: %v", err) + } + part := filepath.Join(t.TempDir(), "asset.part") + if err := u.fetch(t.Context(), r, part, "test"); err != nil || seen["api.github.com"] != 2 || seen["release-assets.githubusercontent.com"] != 1 { + t.Fatalf("GitHub authenticated download: %v, requests %v", err, seen) + } + if b, err := u.rangeRead(t.Context(), r, 0, 2, "test"); err != nil || string(b) != "zi" || seen["api.github.com"] != 3 { + t.Fatalf("GitHub authenticated range download failed: %v", err) + } + if s, err := SaveCredentials("", nil, new(string)); err != nil || s.githubToken != "" || s.CDK() != cdk { + t.Fatal("clearing the token did not preserve the CDK") + } +} + // TestCallerSettingsOverride: --source / --cdk-dpapi of one run beat the saved settings, reach MirrorChyan, are // reported as in effect, and are never saved, logged or written anywhere in the root. func TestCallerSettingsOverride(t *testing.T) { diff --git a/internal/update/range.go b/internal/update/range.go index aadc76b4..cdfcae0f 100644 --- a/internal/update/range.go +++ b/internal/update/range.go @@ -192,10 +192,10 @@ func (l layout) sameAsLocal(e zipEntry) bool { // rangeRead is bounded by rangeMaxDirectory for metadata and rangeMaxGroup for small entry groups. func (u *Updater) rangeRead(ctx context.Context, r *release, off, n int64, what string) ([]byte, error) { - d := download.Client{HTTP: u.client(), StallTimeout: u.stallTimeout} + d, rawURL := u.assetClient(r) var data []byte err := u.rangeRetry(ctx, off, n, what, func() (err error) { - data, err = d.Range(ctx, r.url, off, n, r.size, what) + data, err = d.Range(ctx, rawURL, off, n, r.size, what) return err }) return data, err @@ -407,7 +407,7 @@ func (u *Updater) stageRangeGroup(ctx context.Context, r *release, g rangeGroup, err = rerr } }() - d := download.Client{HTTP: u.client(), StallTimeout: u.stallTimeout} + d, rawURL := u.assetClient(r) if err := u.rangeRetry(ctx, g.start, g.length, r.assetName, func() error { if _, err := f.Seek(0, io.SeekStart); err != nil { return err @@ -415,7 +415,7 @@ func (u *Updater) stageRangeGroup(ctx context.Context, r *release, g rangeGroup, if err := f.Truncate(0); err != nil { return err } - return d.RangeTo(ctx, r.url, g.start, g.length, r.size, r.assetName, f) + return d.RangeTo(ctx, rawURL, g.start, g.length, r.size, r.assetName, f) }); err != nil { return err } diff --git a/internal/update/settings.go b/internal/update/settings.go index 1894dfd7..06c6e917 100644 --- a/internal/update/settings.go +++ b/internal/update/settings.go @@ -19,13 +19,12 @@ const ( SourceMirrorChyan = "mirrorchyan" ) -// Settings are the user's update choices, set in the manager (设置 → 更新) and used by `modavd update` (AUTO-MAS -// calls it): which source to download from, and the MirrorChyan CDK. Settings -// use the per-user ModAVD configuration directory. The CDK is encrypted with -// Windows DPAPI or a macOS Keychain wrapping key, never written or logged clear. +// Settings are the user's update source and credentials, shared by the manager and `modavd update`. +// The per-user file encrypts credentials with Windows DPAPI or a macOS Keychain wrapping key. type Settings struct { - Source string // SourceGitHub or SourceMirrorChyan - cdk string + Source string // SourceGitHub or SourceMirrorChyan + cdk string + githubToken string } // CDK is the MirrorChyan CDK ("" when none). @@ -35,13 +34,15 @@ func (s Settings) CDK() string { return s.cdk } func (s Settings) HasCDK() bool { return s.cdk != "" } type settingsFile struct { - Source string `json:"source"` - CDK string `json:"cdk,omitempty"` // base64 of the platform-protected blob + Source string `json:"source"` + CDK string `json:"cdk,omitempty"` // base64 of the platform-protected blob + GitHubToken string `json:"github_token,omitempty"` } // cdkEntropy binds the protected blob to this use. It is DPAPI's optional // entropy on Windows and the Keychain key purpose / authenticated data on macOS. var cdkEntropy = []byte("ModAVD update: MirrorChyan CDK") +var githubTokenEntropy = []byte("ModAVD update: GitHub token") func settingsSupported() bool { p := root.CurrentPlatform() @@ -79,12 +80,19 @@ func LoadSettings() Settings { if f.Source == SourceMirrorChyan { s.Source = SourceMirrorChyan } - if blob, err := base64.StdEncoding.DecodeString(f.CDK); err == nil && len(blob) > 0 { - if plain, err := host.Unprotect(blob, cdkEntropy); err == nil { - s.cdk = strings.TrimSpace(string(plain)) + s.cdk = unprotectSetting(f.CDK, cdkEntropy) + s.githubToken = unprotectSetting(f.GitHubToken, githubTokenEntropy) + return s +} + +func unprotectSetting(value string, entropy []byte) string { + if blob, err := base64.StdEncoding.DecodeString(value); err == nil && len(blob) > 0 { + if plain, err := host.Unprotect(blob, entropy); err == nil { + defer clear(plain) + return strings.TrimSpace(string(plain)) } } - return s + return "" } // checkCDK is cdk trimmed, or invalid_argument when it cannot be a MirrorChyan CDK. The error never quotes it. @@ -133,12 +141,37 @@ func CallerCDK(b64 string) (string, error) { return v, nil } -// SaveSettings changes the source (when not "") and the CDK (when cdk is not nil; "" clears it). +// SaveSettings changes the source and CDK, preserving the GitHub token. func SaveSettings(source string, cdk *string) (Settings, error) { - s := LoadSettings() + return SaveCredentials(source, cdk, nil) +} + +// SaveCredentials preserves omitted values. An empty credential clears the stored value. +func SaveCredentials(source string, cdk, token *string) (Settings, error) { + var s Settings if !settingsSupported() { return s, errs.New(errs.Unsupported, "当前平台暂不支持保存更新设置") } + path := settingsPath() + if path == "" { + return s, errs.New(errs.Internal, "找不到当前用户的配置目录,无法保存更新设置") + } + dirMode := os.FileMode(0o755) + if runtime.GOOS == "darwin" { + dirMode = 0o700 + } + if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil { + return s, errs.Wrap(errs.Internal, err, "保存更新设置失败: "+err.Error()) + } + lock, ok, err := host.TryLock(path + ".lock") + if err != nil { + return s, errs.Wrap(errs.Internal, err, "保存更新设置失败: "+err.Error()) + } + if !ok { + return s, errs.New(errs.Busy, "正在保存更新设置,请稍后再试") + } + defer lock.Unlock() + s = LoadSettings() switch source { case "": case SourceGitHub, SourceMirrorChyan: @@ -153,6 +186,15 @@ func SaveSettings(source string, cdk *string) (Settings, error) { } s.cdk = v } + if token != nil { + v := strings.TrimSpace(*token) + if len(v) > 256 || strings.ContainsFunc(v, func(r rune) bool { + return !(r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r == '_') + }) { + return s, errs.New(errs.InvalidArgument, "GitHub token 的格式不对") + } + s.githubToken = v + } f := settingsFile{Source: s.Source} if s.cdk != "" { blob, err := host.Protect([]byte(s.cdk), cdkEntropy) @@ -161,21 +203,17 @@ func SaveSettings(source string, cdk *string) (Settings, error) { } f.CDK = base64.StdEncoding.EncodeToString(blob) } + if s.githubToken != "" { + blob, err := host.Protect([]byte(s.githubToken), githubTokenEntropy) + if err != nil { + return s, errs.Wrap(errs.Internal, err, "加密 GitHub token 失败") + } + f.GitHubToken = base64.StdEncoding.EncodeToString(blob) + } b, err := json.MarshalIndent(f, "", " ") if err != nil { return s, errs.Wrap(errs.Internal, err, "保存更新设置失败") } - path := settingsPath() - if path == "" { - return s, errs.New(errs.Internal, "找不到当前用户的配置目录,无法保存更新设置") - } - dirMode := os.FileMode(0o755) - if runtime.GOOS == "darwin" { - dirMode = 0o700 - } - if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil { - return s, errs.Wrap(errs.Internal, err, "保存更新设置失败: "+err.Error()) - } tmp := path + ".tmp" if err := os.WriteFile(tmp, append(b, '\n'), 0o600); err != nil { return s, errs.Wrap(errs.Internal, err, "保存更新设置失败: "+err.Error()) diff --git a/internal/update/source.go b/internal/update/source.go index 7885160d..f61149af 100644 --- a/internal/update/source.go +++ b/internal/update/source.go @@ -26,28 +26,31 @@ import ( ) const ( - githubAPI = "https://api.github.com/repos/ModAVD/ModAVD/releases/latest" - mirrorAPI = "https://mirrorchyan.com/api/resources" - mirrorRID = "ModAVD" - apiTimeout = 15 * time.Second - maxAPIBytes = 4 << 20 - userAgentApp = "ModAVDManager" + githubReleases = "https://api.github.com/repos/ModAVD/ModAVD/releases" + githubAPI = githubReleases + "/latest" + mirrorAPI = "https://mirrorchyan.com/api/resources" + mirrorRID = "ModAVD" + apiTimeout = 15 * time.Second + maxAPIBytes = 4 << 20 + userAgentApp = "ModAVDManager" ) // release is a version to install and the package to download for it. type release struct { - source string // SourceGitHub / SourceMirrorChyan - tag string // GitHub tag_name or MirrorChyan version_name - version Version - minAutoMAS string - assetName string - url string // "" when MirrorChyan gave none (no CDK) - size int64 - sha256 string // lower hex, "" when unknown - topDir string // legacy GitHub packages only - incremental bool - base Version // incremental only - pageURL string + source string // SourceGitHub / SourceMirrorChyan + tag string // GitHub tag_name or MirrorChyan version_name + version Version + minAutoMAS string + assetName string + url string // "" when MirrorChyan gave none (no CDK) + size int64 + sha256 string // lower hex, "" when unknown + topDir string // legacy GitHub packages only + incremental bool + base Version // incremental only + pageURL string + githubAssetID int64 + githubToken string } // target is the release as state.json's "target" (the MirrorChyan URL, which is good for one download, is never @@ -95,6 +98,36 @@ func (u *Updater) client() *http.Client { // ---- GitHub +// GitHub's downloads can redirect to a CDN. Add the token only to the exact API request; the HTTP client never +// sees the Authorization header on the request that it uses as the basis for redirects. +type githubTransport struct { + base http.RoundTripper + endpoint, token, accept string +} + +func (t githubTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL.String() == t.endpoint { + req = req.Clone(req.Context()) + req.Header.Set("Authorization", "Bearer "+t.token) + req.Header.Set("Accept", t.accept) + } + return t.base.RoundTrip(req) +} + +func (u *Updater) githubClient(endpoint, token, accept string) *http.Client { + c := u.client() + if token == "" { + return c + } + base := c.Transport + if base == nil { + base = http.DefaultTransport + } + copy := *c + copy.Transport = githubTransport{base: base, endpoint: endpoint, token: token, accept: accept} + return © +} + func (u *Updater) githubLatest(ctx context.Context) (*release, error) { api := u.githubAPI if api == "" { @@ -106,7 +139,8 @@ func (u *Updater) githubLatest(ctx context.Context) (*release, error) { req.Header.Set("Accept", "application/vnd.github+json") req.Header.Set("User-Agent", download.UserAgent()) req.Header.Set("Accept-Encoding", "identity") - resp, err := u.client().Do(req) + token := u.settings().githubToken + resp, err := u.githubClient(githubAPI, token, "application/vnd.github+json").Do(req) if err != nil { return nil, sourceError("连不上 GitHub(%s)", download.NetError(err, "")).WithAdvice(hostproxy.Advice()) } @@ -123,6 +157,7 @@ func (u *Updater) githubLatest(ctx context.Context) (*release, error) { Body string `json:"body"` HTMLURL string `json:"html_url"` Assets []struct { + ID int64 `json:"id"` Name string `json:"name"` URL string `json:"browser_download_url"` Size int64 `json:"size"` @@ -152,6 +187,7 @@ func (u *Updater) githubLatest(ctx context.Context) (*release, error) { return nil, sourceError("GitHub 返回的附件信息不完整: %s", a.Name) } r.assetName, r.url, r.size = a.Name, a.URL, a.Size + r.githubAssetID, r.githubToken = a.ID, token if m := digestRe.FindStringSubmatch(a.Digest); m != nil { r.sha256 = strings.ToLower(m[1]) } @@ -394,6 +430,16 @@ func hashOr(p string) string { return s } +func (u *Updater) assetClient(r *release) (download.Client, string) { + d := download.Client{HTTP: u.client(), StallTimeout: u.stallTimeout} + if r.source != SourceGitHub || r.githubAssetID <= 0 || r.githubToken == "" { + return d, r.url + } + endpoint := fmt.Sprintf("%s/assets/%d", githubReleases, r.githubAssetID) + d.HTTP = u.githubClient(endpoint, r.githubToken, "application/octet-stream") + return d, endpoint +} + // fetch preserves MirrorChyan's fresh-download policy; GitHub can resume a verified range. func (u *Updater) fetch(ctx context.Context, r *release, part, label string) error { last := time.Time{} @@ -403,7 +449,7 @@ func (u *Updater) fetch(ctx context.Context, r *release, part, label string) err if st, err := os.Stat(part); err == nil && st.Size() >= r.size { fresh = true } - d := download.Client{HTTP: u.client(), StallTimeout: u.stallTimeout} + d, rawURL := u.assetClient(r) var beforeWrite func() error if u.nativeUpdates() { beforeWrite = func() error { @@ -413,7 +459,7 @@ func (u *Updater) fetch(ctx context.Context, r *release, part, label string) err return u.checkSpace() } } - return d.File(ctx, download.FileOptions{URL: r.url, Path: part, Label: label, Size: r.size, + return d.File(ctx, download.FileOptions{URL: rawURL, Path: part, Label: label, Size: r.size, Fresh: fresh, BeforeWrite: beforeWrite, Progress: func(done int64) { diff --git a/internal/update/updater.go b/internal/update/updater.go index 303f7020..8f2d65fa 100644 --- a/internal/update/updater.go +++ b/internal/update/updater.go @@ -137,7 +137,8 @@ type Status struct { CurrentBuild string `json:"current_build"` // Pkg.BuildId: mas-N (legacy, up to 0.41) or X.Y.Z; "" when unknown Source string `json:"source"` // in effect: --source, else the setting (github / mirrorchyan) CDKSet bool `json:"cdk_set"` // a MirrorChyan CDK is in effect (--cdk-dpapi or saved; never the CDK) - Checked bool `json:"checked"` // a source was asked and answered + GitHubTokenSet bool `json:"github_token_set"` + Checked bool `json:"checked"` // a source was asked and answered CheckError string `json:"check_error"` LatestVersion string `json:"latest_version"` // vX.Y.Z of the latest release, "" when not asked LatestSource string `json:"latest_source"` @@ -173,7 +174,7 @@ func (u *Updater) status() *Status { if u.Opt.PackagePath == "" && !u.hasNativeTransaction() && !u.localOperation { set = u.settings() } - st := &Status{Root: u.Root.Dir, Source: set.Source, CDKSet: set.HasCDK(), Notices: []string{}} + st := &Status{Root: u.Root.Dir, Source: set.Source, CDKSet: set.HasCDK(), GitHubTokenSet: set.githubToken != "", Notices: []string{}} st.NotUpdatableReason = u.notUpdatable() st.Updatable = st.NotUpdatableReason == "" if v, ok := LocalVersion(u.Root); ok { diff --git a/scripts/test_topbar_ui.mjs b/scripts/test_topbar_ui.mjs index 9a54dda8..5bc48163 100644 --- a/scripts/test_topbar_ui.mjs +++ b/scripts/test_topbar_ui.mjs @@ -640,18 +640,20 @@ test('问题反馈 glows with the very rule of 组件 (no second animation); nei // ---- settings-page.js: 更新 and 通用 only -test('设置 has 更新 and 通用 (language, root folder) and no 可选组件', async () => { +test('设置 opens with one check above update source and general settings', async () => { const r = { dialogs: [], toasts: [], errors: [] }; + let checks = 0; const m = await load('settings-page.js', { 'dom.js': dom, 'ui.js': dialogs(r), - 'actions.js': { openFolder: noop }, - 'update.js': { createUpdatePanel: () => ({ body: h('div'), foot: h('div'), dispose: noop }) }, + 'api.js': { api: {} }, + 'update.js': { createUpdatePanel: () => ({ body: h('div'), source: h('div'), check: () => checks++, dispose: noop }) }, }); m.mod.openManagerSettings(); const d = r.dialogs[0]; assert.equal(d.options.title, '设置'); - assert.deepEqual(titles(d), ['更新', '通用']); + assert.deepEqual(titles(d), ['更新', '更新源', '通用']); + assert.equal(checks, 1); assert.doesNotMatch(d.options.body.textContent, /可选组件|Google Play|KernelSU/); assert.match(d.options.body.textContent, /根目录/); }); diff --git a/scripts/test_update_handoff.mjs b/scripts/test_update_handoff.mjs index f3423c89..913a6ee6 100644 --- a/scripts/test_update_handoff.mjs +++ b/scripts/test_update_handoff.mjs @@ -12,6 +12,7 @@ const settle = () => new Promise(resolve => setImmediate(resolve)); async function page(post, instances = []) { const notices = []; + const requests = []; const dialogs = []; const noop = () => {}; const stubs = { @@ -24,13 +25,13 @@ async function page(post, instances = []) { dialogs.push(dialog); return dialog; }, toast: value => notices.push(value), toastError: noop }, - './diagnostics.js': { openDiagnostics: noop, activeJob: noop, progressText: noop }, + './diagnostics.js': { openDiagnostics: noop, activeJob: noop, latestJob: noop, progressText: noop }, './actions.js': { onJob: noop, notifyJob: noop }, './i18n.js': { ...i18n }, './format.js': { quoted: x => `「${x.title}」` }, }; const context = vm.createContext({}); - const module = new vm.SourceTextModule(source + '\nexport { confirmInstall };', { context }); + const module = new vm.SourceTextModule(source + '\nexport { confirmInstall, handoffResult };', { context }); await module.link(specifier => { const values = stubs[specifier]; return new vm.SyntheticModule(Object.keys(values), function() { @@ -39,7 +40,8 @@ async function page(post, instances = []) { }); await module.evaluate(); return { update: value => module.namespace.onUpdate({ handoff: value }), - confirm: value => module.namespace.confirmInstall(value), notices, dialogs }; + confirm: () => module.namespace.confirmInstall(confirmed => requests.push(JSON.stringify(confirmed))), + result: () => module.namespace.handoffResult, requests, notices, dialogs }; } test('two windows claim once, then repeated events and reloads stay silent', async () => { @@ -60,28 +62,30 @@ test('two windows claim once, then repeated events and reloads stay silent', asy first.update(result); second.update(result); await settle(); - assert.equal(first.notices.length + second.notices.length, 1); - assert.equal(first.notices[0].title, '已更新到 0.40.0'); + assert.equal(first.notices.length + second.notices.length, 0); + assert.equal(first.result(), result); + assert.equal(second.result(), null); assert.equal(calls, 2); first.update(result); const reloaded = await page(post); reloaded.update(result); await settle(); - assert.equal(reloaded.notices.length, 0); + assert.equal(reloaded.result(), null); }); -test('different IDs in the same second show their own success and error', async () => { +test('different IDs in the same second replace the inline result', async () => { const results = [ { id: 'a'.repeat(32), at: 'same-second', ok: true, message: 'already current' }, { id: 'b'.repeat(32), at: 'same-second', ok: false, error: { message: 'busy', advice: 'close manager' } }, ]; const p = await page(async (_path, body) => results.find(x => x.id === body.id)); - for (const result of results) p.update(result); + p.update(results[0]); + await settle(); + assert.equal(p.result(), results[0]); + p.update(results[1]); await settle(); - assert.equal(p.notices.length, 2); - assert.equal(p.notices[0].title, 'already current'); - assert.equal(p.notices[1].text, 'busy'); - assert.equal(p.notices[1].advice, 'close manager'); + assert.equal(p.result(), results[1]); + assert.equal(p.notices.length, 0); }); test('a failed request retries on the next update without showing unclaimed data', async () => { @@ -98,45 +102,34 @@ test('a failed request retries on the next update without showing unclaimed data p.update(result); await settle(); assert.equal(calls, 2); - assert.equal(p.notices.length, 1); + assert.equal(p.result(), result); + assert.equal(p.notices.length, 0); }); -test('updating with running instances keeps the named shutdown confirmation', async () => { - const requests = []; - const p = await page(async (path, body) => { - requests.push({ path, body }); - return { id: 'j1', kind: 'update', state: 'running' }; - }, [{ index: 3, title: '甲', running: true }, { index: 4, title: '乙', running: true }]); - p.confirm({ latest_version: 'v0.40.0' }); +test('updating with running instances opens one confirmation and names the instances', async () => { + const p = await page(async () => { assert.fail('unexpected network request'); }, + [{ index: 3, title: '甲', running: true }, { index: 4, title: '乙', running: true }]); + p.confirm(); + assert.equal(p.dialogs.length, 1); + assert.equal(p.requests.length, 0); + assert.equal(p.dialogs[0].title, '要关掉 2 台实例'); + assert.match(JSON.stringify(p.dialogs[0].body), /「甲」「乙」/); p.dialogs[0].actions.ok.run(); - assert.equal(requests.length, 0); - assert.equal(p.dialogs[1].title, '要关掉 2 台实例'); - assert.match(JSON.stringify(p.dialogs[1].body), /「甲」「乙」/); - p.dialogs[1].actions.ok.run(); - await settle(); - assert.equal(requests.length, 1); - assert.equal(requests[0].path, '/api/update/apply'); - // the server stops only these: one started during the download makes it ask again - assert.equal(JSON.stringify(requests[0].body), '{"confirmed":[3,4]}'); + assert.deepEqual(p.requests, ['[3,4]']); }); -test('updating with nothing running confirms an empty list', async () => { - const requests = []; - const p = await page(async (path, body) => { requests.push({ path, body }); return { id: 'j1', kind: 'update', state: 'running' }; }, +test('updating with nothing running submits an empty list directly', async () => { + const p = await page(async () => { assert.fail('unexpected network request'); }, [{ index: 3, title: '甲', running: false }]); - p.confirm({ latest_version: 'v0.40.0' }); - p.dialogs[0].actions.ok.run(); - await settle(); - assert.equal(p.dialogs.length, 1); - assert.equal(JSON.stringify(requests[0].body), '{"confirmed":[]}'); + p.confirm(); + assert.equal(p.dialogs.length, 0); + assert.deepEqual(p.requests, ['[]']); }); test('dismissing the shutdown confirmation never starts an update', async () => { - let requests = 0; - const p = await page(async () => { requests++; }, [{ index: 3, title: '甲', running: true }]); - p.confirm({ latest_version: 'v0.40.0' }); - p.dialogs[0].actions.ok.run(); - p.dialogs[1].close(); - await settle(); - assert.equal(requests, 0); + const p = await page(async () => { assert.fail('unexpected network request'); }, + [{ index: 3, title: '甲', running: true }]); + p.confirm(); + p.dialogs[0].close(); + assert.equal(p.requests.length, 0); }); From a1917b296de96244020849b2e08f75bbdef299f3 Mon Sep 17 00:00:00 2001 From: beichen24a1 <262405272+beichen24a1@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:17:21 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E5=8F=AA=E5=85=81=E8=AE=B8=E5=AE=89?= =?UTF-8?q?=E8=A3=85=E6=AF=94=E5=BD=93=E5=89=8D=E7=89=88=E6=9C=AC=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E7=9A=84=E6=9A=82=E5=AD=98=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/ui/API.en.md | 2 +- internal/ui/API.md | 2 +- internal/ui/update.go | 13 +++++++------ internal/ui/web/js/update.js | 6 +++--- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/internal/ui/API.en.md b/internal/ui/API.en.md index 8dfecc10..a58a06f8 100644 --- a/internal/ui/API.en.md +++ b/internal/ui/API.en.md @@ -206,7 +206,7 @@ The optional start-result field `language_pending: true` means the language requ ### Update `UpdateView` -All the fields of `update.Status` (the same as the `data` of `modavd update --json`: `root`, `updatable`, `not_updatable_reason`, `current_version`, `current_build`, `source`, `cdk_set`, `github_token_set`, `checked`, `check_error`, `latest_version`, `latest_source`, `update_available`, `required_automas`, `release_url`, `phase`, `prepared_version`, `last_result`, `recovered`, `updated`, `message`, `notices`), plus `checking`, `checked_at` (RFC 3339, `""` if no check has been made since this start), `error` (the error object of the last check, `null` if none), `can_install` (`POST /api/update/apply` can be tried: the manager knows how to reopen itself), `install_by_cli` (the opposite of `can_install`: it can only be installed with the command line), and `handoff` (the result that the command line left after the last click on "Update" handed over to it, `{id, at, ok, updated, version, message, error: {code, message, advice} | null}`; `null` if no handoff ID was delivered, a window has already claimed the result, or the result is older than 30 minutes). +All the fields of `update.Status` (the same as the `data` of `modavd update --json`: `root`, `updatable`, `not_updatable_reason`, `current_version`, `current_build`, `source`, `cdk_set`, `github_token_set`, `checked`, `check_error`, `latest_version`, `latest_source`, `update_available`, `required_automas`, `release_url`, `phase`, `prepared_version`, `last_result`, `recovered`, `updated`, `message`, `notices`), plus `checking`, `checked_at` (RFC 3339, `""` if no check has been made since this start), `error` (the error object of the last check, `null` if none), `can_install` (`POST /api/update/apply` can be tried: the manager knows how to reopen itself), `prepared_update` (a newer version is staged), `install_by_cli` (the opposite of `can_install`: it can only be installed with the command line), and `handoff` (the result that the command line left after the last click on "Update" handed over to it, `{id, at, ok, updated, version, message, error: {code, message, advice} | null}`; `null` if no handoff ID was delivered, a window has already claimed the result, or the result is older than 30 minutes). - `last_update_failure` contains `{code, message, advice}` if the last update started by the manager failed. It remains available after a manager restart. A successful handoff, a change to the installed version, or a newer `last_result` makes this field `null`. - Opening Settings checks once. The "Check for updates" button checks again on request. The GitHub token is used for GitHub release checks and asset downloads. diff --git a/internal/ui/API.md b/internal/ui/API.md index 222f1b79..e5f68fac 100644 --- a/internal/ui/API.md +++ b/internal/ui/API.md @@ -207,7 +207,7 @@ Apple Silicon macOS 的组件下载/导入使用 API35 Google Play ARM64 r9, ### 更新 `UpdateView` -`update.Status` 的全部字段(和 `modavd update --json` 的 `data` 相同:`root`、`updatable`、`not_updatable_reason`、`current_version`、`current_build`、`source`、`cdk_set`、`github_token_set`、`checked`、`check_error`、`latest_version`、`latest_source`、`update_available`、`required_automas`、`release_url`、`phase`、`prepared_version`、`last_result`、`recovered`、`updated`、`message`、`notices`),加上 `checking`、`checked_at`(RFC 3339,本次启动后没查过是 `""`)、`error`(上次检查的错误对象,没有是 `null`)、`can_install`(可以试 `POST /api/update/apply`:管理器知道怎么重新打开自己)、`install_by_cli`(`can_install` 的反面:只能用命令行装)、`handoff`(上次点「更新」交给命令行以后命令行留下的结果 `{id, at, ok, updated, version, message, error: {code, message, advice} | null}`;没有收到本次交接 ID、结果已被任一窗口领取、或者结果超过 30 分钟,是 `null`)。 +`update.Status` 的全部字段(和 `modavd update --json` 的 `data` 相同:`root`、`updatable`、`not_updatable_reason`、`current_version`、`current_build`、`source`、`cdk_set`、`github_token_set`、`checked`、`check_error`、`latest_version`、`latest_source`、`update_available`、`required_automas`、`release_url`、`phase`、`prepared_version`、`last_result`、`recovered`、`updated`、`message`、`notices`),加上 `checking`、`checked_at`(RFC 3339,本次启动后没查过是 `""`)、`error`(上次检查的错误对象,没有是 `null`)、`can_install`(可以试 `POST /api/update/apply`:管理器知道怎么重新打开自己)、`prepared_update`(已有比当前版本新的暂存包)、`install_by_cli`(`can_install` 的反面:只能用命令行装)、`handoff`(上次点「更新」交给命令行以后命令行留下的结果 `{id, at, ok, updated, version, message, error: {code, message, advice} | null}`;没有收到本次交接 ID、结果已被任一窗口领取、或者结果超过 30 分钟,是 `null`)。 - `last_update_failure` 为管理器发起的更新最近一次失败的详情 `{code, message, advice}`,重新打开管理器仍可查询。成功交接、已安装版本变化或有更新的 `last_result` 后返回 `null`。 - 打开设置页时检查一次更新,也可手动点「检查更新」。GitHub token 用于 GitHub 的版本查询和附件下载。 diff --git a/internal/ui/update.go b/internal/ui/update.go index 44d92e2f..d301b058 100644 --- a/internal/ui/update.go +++ b/internal/ui/update.go @@ -20,11 +20,12 @@ const updateCheckTimeout = time.Minute // updateView is GET /api/update and the "update" event. type updateView struct { *update.Status - Checking bool `json:"checking"` - CheckedAt string `json:"checked_at"` // RFC 3339, "" when not checked since the manager started - Error *errorBody `json:"error"` // the last check's failure - InstallByCLI bool `json:"install_by_cli"` // 更新 is not offered here (CanInstall false): only the CLI installs - CanInstall bool `json:"can_install"` // POST /api/update/apply may be tried + Checking bool `json:"checking"` + CheckedAt string `json:"checked_at"` // RFC 3339, "" when not checked since the manager started + Error *errorBody `json:"error"` // the last check's failure + InstallByCLI bool `json:"install_by_cli"` // 更新 is not offered here (CanInstall false): only the CLI installs + CanInstall bool `json:"can_install"` // POST /api/update/apply may be tried + PreparedUpdate bool `json:"prepared_update"` // a staged version newer than the installed one // Handoff is what the CLI reported after the last 更新 handed to it (the swap and the manager's restart); null when // no matching hand-off was delivered, or a window has already claimed the notification. Handoff *update.HandoffResult `json:"handoff"` @@ -68,7 +69,7 @@ func (s *server) updateView() updateView { st.Message = c.Message } can := s.canInstall() - v := updateView{Status: st, Checking: p.checking, Error: p.err, InstallByCLI: !can, CanInstall: can, + v := updateView{Status: st, Checking: p.checking, Error: p.err, InstallByCLI: !can, CanInstall: can, PreparedUpdate: stagedNewer(st), Handoff: p.handoff, LastUpdateFailure: lastFailure} if !p.at.IsZero() { v.CheckedAt = p.at.Format(time.RFC3339) diff --git a/internal/ui/web/js/update.js b/internal/ui/web/js/update.js index 4df40528..4af6a9ff 100644 --- a/internal/ui/web/js/update.js +++ b/internal/ui/web/js/update.js @@ -8,7 +8,7 @@ import { activeJob, latestJob, progressText } from './diagnostics.js'; import { onJob, notifyJob } from './actions.js'; import { quoted } from './format.js'; -const ver = (v) => v?.replace(/^v/, '') || ''; +const ver = (v) => v ? v.replace(/^v/, '') : ''; let pending = null; let handoffResult = null; @@ -38,7 +38,7 @@ async function claimHandoff(x) { } } -const installable = (v) => !!(v?.can_install && v.updatable && (v.update_available || v.prepared_version) +const installable = (v) => !!(v?.can_install && v.updatable && (v.update_available || v.prepared_update) && !pending && !v.checking && !activeJob('update')); function confirmInstall(apply) { @@ -166,7 +166,7 @@ export function createUpdatePanel() { clear.hidden = !stored; setText(current, ver(v?.current_version) || '—'); - setText(latest, ver(v?.latest_version || v?.prepared_version) || '—'); + setText(latest, ver(v?.latest_version || (v?.prepared_update && v.prepared_version)) || '—'); checkBtn.disabled = blocked; installBtn.disabled = installing || !installable(v); attr(checkBtn, 'aria-busy', checking || null);