提交记录修改cmd/cage/mac_guest_install_darwin_arm64.go+5 −2看文件
修改docs/getting-started.md+5 −3看文件
修改docs/guide/guest-systems.md+4 −2看文件
修改internal/guestos/macos_profile.go+12 −0看文件
修改internal/workbench/account.go+75 −2看文件
修改internal/workbench/account_store.go+59 −0看文件
修改internal/workbench/guest_install.go+8 −4看文件
修改internal/workbench/macos_credentials.go+241 −27看文件
修改internal/workbench/macos_credentials_test.go+221 −30看文件
修改internal/workbench/macos_guest.go+3 −0看文件
新增internal/workbench/macos_password_live_test.go+163 −0看文件
新增internal/workbench/macos_password_sync.go+85 −0看文件
修改internal/workbench/trusted_login.go+4 −0看文件
修改internal/workbench/trusted_login_test.go+14 −2看文件
修改scripts/guest-os/configure-macos-session.sh+3 −1看文件
修改scripts/guest-os/macos-setup-account.m+98 −16看文件
修改scripts/guest-os/provision-macos-workbench.sh+4 −3看文件
修改ui/scripts/account-remember-live-smoke.mjs+2 −2看文件
修改ui/scripts/account-remember-smoke.mjs+1 −1看文件
修改ui/scripts/account-smoke.mjs+1 −1看文件
修改ui/scripts/diagnostics-smoke.mjs+2 −2看文件
新增ui/scripts/macos-shared-account-smoke.mjs+82 −0看文件
修改ui/scripts/packaged-startup-smoke.mjs+2 −2看文件
修改ui/scripts/workbench-fixture.mjs+2 −1看文件
修改ui/src/account.jsx+49 −25看文件
修改ui/src/initialization.jsx+3 −3看文件
修改ui/src/macos-first-setup.jsx+3 −3看文件
修改ui/src/main.jsx+1 −6看文件
| @@ -34,6 +34,10 @@ func installMacWorkbench(ctx context.Context, profile, state string, l *vm.Lima) | ||
| 34 | 34 | return errors.New("客机初始密码需使用 8 至 256 个英文键盘可输入的字母、数字、空格或符号") |
| 35 | 35 | } |
| 36 | 36 | defer clear(pw) |
| 37 | 新增: ordinaryUser := os.Getenv("CAGE_MACOS_ACCOUNT") | |
| 38 | 新增: if !guestos.ValidMacOSAccountName(ordinaryUser) { | |
| 39 | 新增: return errors.New("请从 Cage 注册共用账密后继续安装 macOS 客机") | |
| 40 | 新增: } | |
| 37 | 41 | if !macGuestLoginAvailable() { |
| 38 | 42 | return errors.New("此 Cage 构建缺少虚拟 Mac 登录组件") |
| 39 | 43 | } |
| @@ -92,7 +96,6 @@ func installMacWorkbench(ctx context.Context, profile, state string, l *vm.Lima) | ||
| 92 | 96 | if err != nil { |
| 93 | 97 | return err |
| 94 | 98 | } |
| 95 | 删除: ordinaryUser := "cage" | |
| 96 | 99 | if provision != "cageprovision" { |
| 97 | 100 | return errors.New("此开发客机的置备身份不匹配") |
| 98 | 101 | } |
| @@ -144,7 +147,7 @@ func installMacWorkbench(ctx context.Context, profile, state string, l *vm.Lima) | ||
| 144 | 147 | if err := auth.Run(); err != nil { |
| 145 | 148 | return errors.New("无法准备虚拟 Mac 账户") |
| 146 | 149 | } |
| 147 | 删除: cmd := guestCommand(ctx, `sudo -S -p '' /bin/sh -ec `+shellescape.Quote(`cd `+remote+`; exec 4<login-input; rm login-input; /usr/bin/perl ./native-component-manifest.pl source ./native-components.json .; /bin/bash ./provision-macos-workbench.sh `+remote+` `+i.ID.String()+` `+provision+` <&4; /usr/bin/perl ./native-component-manifest.pl publish ./native-components.json .`)+adminPassword) | |
| 150 | 新增: cmd := guestCommand(ctx, `sudo -S -p '' /bin/sh -ec `+shellescape.Quote(`cd `+remote+`; exec 4<login-input; rm login-input; /usr/bin/perl ./native-component-manifest.pl source ./native-components.json .; /bin/bash ./provision-macos-workbench.sh `+remote+` `+i.ID.String()+` `+provision+` `+ordinaryUser+` <&4; /usr/bin/perl ./native-component-manifest.pl publish ./native-components.json .`)+adminPassword) | |
| 148 | 151 | cmd.Stdout = os.Stdout |
| 149 | 152 | if err := cmd.Run(); err != nil { |
| 150 | 153 | return fmt.Errorf("安装虚拟 Mac 应用失败,可在工作台继续安装:%w", err) |
| @@ -28,7 +28,9 @@ | ||
| 28 | 28 | |
| 29 | 29 | 无需先安装开发工具或 Clash。签名、公证和平台验证情况以该安装包的 Release 说明为准。如果系统拒绝打开,先按[安装问题](troubleshooting.md#下载或安装受阻)核对版本与来源。下述代理、环境和项目操作共用。 |
| 30 | 30 | |
| 31 | 删除:首次打开本机工作台时,可以信任此电脑直接进入,也可以设置用户名和至少 8 个字符的密码。macOS、Windows 和 Linux 完整桌面版在创建密码账户时默认勾选“记住我”,可取消勾选;已有密码账户可在登录时勾选,或在“设置 → 账户 → 记住我”中开启。关闭后的选择会保留。账户只用于当前主机的 Cage;从左下角头像菜单打开“设置”,即可在“账户”中更换头像、用户名和密码。请妥善保存密码,没有在线找回。它不替代 Claude 账号,也不会加密项目文件或整个虚拟磁盘。 | |
| 31 | 新增:首次打开 Cage,先注册用户名和至少 8 个字符的密码,再选择客机系统、存储位置和网络代理。Mac 上的用户名使用小写字母开头的 1–31 个小写字母、数字或下划线,密码使用 8–256 个英文键盘可输入的字符;新建 macOS 客机使用同一套账密。三平台完整桌面版默认勾选“记住我”,可取消勾选;已有密码账户也可在登录时勾选,或在“设置 → 账户 → 记住我”中开启。关闭后的选择会保留。 | |
| 32 | 新增: | |
| 33 | 新增:账户保存在当前主机,没有在线找回。左下角头像菜单的“设置 → 账户”可以更换头像和密码;用户名用于 macOS 客机后会固定,以保留用户目录和文件。修改共用密码时,客机关闭或暂时无法连接,会在下次启动时继续同步;完成前客机可能仍需原密码。Cage 账户不替代 Claude 账号,也不会加密项目文件或整个虚拟磁盘。 | |
| 32 | 34 | |
| 33 | 35 | ### 选择客机系统 |
| 34 | 36 | |
| @@ -63,9 +65,9 @@ macOS 使用 Apple 提供的兼容恢复镜像,或用户已有的官方 IPSW | ||
| 63 | 65 | |
| 64 | 66 | ### 受信任的本机登录 |
| 65 | 67 | |
| 66 | 删除:首次在完整桌面版打开空配置,选择「信任此电脑并进入」,以后同一系统用户打开 Cage 可自动进入。也可以选择「使用用户名和密码」。已有密码账户在登录页勾选「记住我」,验证密码后即可信任此电脑;也可在「设置 → 账户 → 记住我」中开启或关闭。三平台使用相同的本机信任机制。手动锁定仍需验证,退出账户会撤销此项信任。远程连接不能使用本机信任登录;Claude 服务仍需自己的授权。 | |
| 68 | 新增:注册账户时勾选「记住我」,以后同一系统用户打开 Cage 可自动进入。已有密码账户在登录页验证密码后也可启用,或在「设置 → 账户 → 记住我」中开启或关闭。三平台使用相同的本机信任机制。手动锁定仍需验证,退出账户会撤销此项信任。远程连接不能使用本机信任登录;Claude 服务仍需自己的授权。 | |
| 67 | 69 | |
| 68 | 删除:受信任模式依赖操作系统的用户登录。离开电脑时请锁定系统。需要 Cage 独立锁屏、远程密码登录,或查看、复制保险箱密码时,在「设置 → 账户」设置密码即可转换;工作区内部密钥和已有数据继续使用。备份免账号工作区时,还需备份系统用户配置目录(Windows 使用 `%LOCALAPPDATA%`)下的 `Cage/trusted-local` 私有信任凭据,并以私有权限保存。 | |
| 70 | 新增:受信任模式依赖操作系统的用户登录。离开电脑时请锁定系统。已有免账号工作区仍可继续使用;准备 macOS 客机时,引导会先要求设置共用账密,工作区内部密钥和已有数据继续保留。备份免账号工作区时,还需备份系统用户配置目录(Windows 使用 `%LOCALAPPDATA%`)下的 `Cage/trusted-local` 私有信任凭据,并以私有权限保存。 | |
| 69 | 71 | |
| 70 | 72 | ## 2. 导入并选择代理 |
| 71 | 73 | |
| @@ -79,14 +79,16 @@ Windows 在确认系统提权后自动创建磁盘、安装系统和建立客机 | ||
| 79 | 79 | |
| 80 | 80 | ### Mac 的首次系统授权 |
| 81 | 81 | |
| 82 | 删除:选择 macOS 后,Cage 自动创建普通账户 `cage`、生成独立随机密码并加密保管。安装中断后点击「继续安装」复用同一密码,原磁盘和文件保留。 | |
| 82 | 新增:先注册 Cage 用户名和密码,再选择 macOS 客机。Cage 用同一套账密创建客机普通账户,并加密保管安装凭据。用户名需以小写英文字母开头,使用 1–31 个小写字母、数字或下划线,不能使用系统保留名称;密码使用 8–256 个英文键盘可输入的字符。安装中断后点击「继续安装」复用原安装身份和凭据,原磁盘和文件保留。 | |
| 83 | 新增: | |
| 84 | 新增:在「设置 → 账户」修改共用密码时,会同步客机账户、登录钥匙串、首次授权密码和自动登录记录。客机关闭或同步中断时,Cage 保留待同步记录,下次启动继续处理;完成前客机可能仍需原密码,暂时不能再次改密。已有客机保留用户名与用户目录,设置共用账密时 Cage 使用该用户名。用户名用于客机后会固定。 | |
| 83 | 85 | |
| 84 | 86 | 安装完成后,Cage 自动启动和登录虚拟 Mac,跳过可选的首次设置页面,并显示需要确认的系统权限: |
| 85 | 87 | |
| 86 | 88 | 1. 在客机的「窗口录制」「辅助功能」设置里允许 Cage Guest Window;若系统要求「退出并重新打开」,按提示完成。Cage 自动定位下一项未完成的权限,也可点击同名按钮重新打开。 |
| 87 | 89 | 2. 在「文件系统扩展」中同时启用 `macFUSE` 和 `macFUSE (local)`。Cage 自动检查只读测试卷能否挂载和卸载;只打开其中一项不能完成验证。 |
| 88 | 90 | |
| 89 | 删除:这些权限都在虚拟 Mac 内确认,首次设置期间客机断网。Apple 询问管理员身份时,用户名填 `cagesetup`,点选密码框后使用「填写授权密码」,再确认授权。辅助功能尚未开启时,可通过「查看授权密码」获取密码。Cage 检查三项授权后自动完成设置并进入工作台;收尾失败时提供重试入口。 | |
| 91 | 新增:这些权限都在虚拟 Mac 内确认,首次设置期间客机断网。Apple 询问管理员身份时,用户名填 `cagesetup`,密码与 Cage 账户相同;也可点选密码框后使用「填写授权密码」。Cage 检查三项授权后自动完成设置并进入工作台;收尾失败时提供重试入口。 | |
| 90 | 92 | |
| 91 | 93 | Cage 会撤销临时管理员并关闭这台客机的首次设置入口。以后启动自动登录;主动锁屏或注销时,从「登录客机账户」登录,必要时点击「查看客机密码」。FileVault 或其他系统设置阻止自动登录时,保留手动入口。账户、权限和文件随客机磁盘保留。客机系统自动登录使开机后账户直接可用,主机账户和 Cage 的解锁负责保护访问入口。 |
| 92 | 94 | |
| @@ -26,6 +26,18 @@ type MacOSProfile struct { | ||
| 26 | 26 | |
| 27 | 27 | var macUser = regexp.MustCompile(`^[a-z][a-z0-9_]{0,30}$`) |
| 28 | 28 | |
| 29 | 新增:// New accounts must not collide with macOS or Cage's provisioning identities. | |
| 30 | 新增:func ValidMacOSAccountName(name string) bool { | |
| 31 | 新增: if !macUser.MatchString(name) { | |
| 32 | 新增: return false | |
| 33 | 新增: } | |
| 34 | 新增: switch name { | |
| 35 | 新增: case "root", "daemon", "nobody", "guest", "cageprovision", "cagesetup": | |
| 36 | 新增: return false | |
| 37 | 新增: } | |
| 38 | 新增: return true | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 29 | 41 | func macMachineID(profile string) (string, error) { |
| 30 | 42 | path := filepath.Join(profile, "state", "lima", "mac", "vz-identifier") |
| 31 | 43 | info, err := os.Lstat(path) |
| @@ -2,10 +2,18 @@ package workbench | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "net/http" |
| 5 | 新增: "runtime" | |
| 6 | 新增: | |
| 7 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 5 | 8 | ) |
| 6 | 9 | |
| 10 | 新增:func (s *Server) macAccountHost() bool { | |
| 11 | 新增: return runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" && s.localVMStorage() | |
| 12 | 新增:} | |
| 13 | 新增: | |
| 7 | 14 | func (s *Server) accountStatus(w http.ResponseWriter, r *http.Request) { |
| 8 | 15 | v := s.account.viewFor(s.hasTrustedView(r)) |
| 16 | 新增: v.MacOSAccountHost = s.macAccountHost() | |
| 9 | 17 | v.BackgroundRunning = s.vmRunning() |
| 10 | 18 | if s.macosGuest != nil { |
| 11 | 19 | v.GuestSystem = "macos" |
| @@ -15,6 +23,13 @@ func (s *Server) accountStatus(w http.ResponseWriter, r *http.Request) { | ||
| 15 | 23 | if s.windowsGuest != nil { |
| 16 | 24 | v.GuestSystem = "windows-11" |
| 17 | 25 | } |
| 26 | 新增: if v.MacOSAccountHost && v.Unlocked && !v.MacOSCredentialsReady && v.MacOSGuestUser == "" { | |
| 27 | 新增: if install, err := guestos.LoadInstallation(s.profile); err == nil && install != nil { | |
| 28 | 新增: if previous, err := s.account.legacyMacGuestPassword(r.Context(), install.ID); err == nil && previous != "" { | |
| 29 | 新增: v.MacOSGuestUser = "cage" | |
| 30 | 新增: } | |
| 31 | 新增: } | |
| 32 | 新增: } | |
| 18 | 33 | jsonReply(w, v) |
| 19 | 34 | } |
| 20 | 35 | |
| @@ -24,7 +39,7 @@ func (s *Server) accountAction(w http.ResponseWriter, r *http.Request) { | ||
| 24 | 39 | return |
| 25 | 40 | } |
| 26 | 41 | action := r.PathValue("action") |
| 27 | 删除: if action != "create" && action != "unlock" && action != "profile" && action != "password" && action != "lock" && action != "logout" && action != "suspend" && action != "device-enroll" && action != "device-revoke" && action != "device-unlock" { | |
| 42 | 新增: if action != "prepare-macos" && action != "create" && action != "unlock" && action != "profile" && action != "password" && action != "lock" && action != "logout" && action != "suspend" && action != "device-enroll" && action != "device-revoke" && action != "device-unlock" { | |
| 28 | 43 | http.NotFound(w, r) |
| 29 | 44 | return |
| 30 | 45 | } |
| @@ -54,13 +69,66 @@ func (s *Server) accountAction(w http.ResponseWriter, r *http.Request) { | ||
| 54 | 69 | vaultLease := s.account.vaultLease |
| 55 | 70 | s.account.mu.Unlock() |
| 56 | 71 | var err error |
| 72 | 新增: if action == "password" || action == "prepare-macos" { | |
| 73 | 新增: if !s.op.TryLock() { | |
| 74 | 新增: http.Error(w, "环境操作仍在进行,请等待完成后设置密码", http.StatusConflict) | |
| 75 | 新增: return | |
| 76 | 新增: } | |
| 77 | 新增: defer s.op.Unlock() | |
| 78 | 新增: if s.busy() { | |
| 79 | 新增: http.Error(w, "环境操作仍在进行,请等待完成后设置密码", http.StatusConflict) | |
| 80 | 新增: return | |
| 81 | 新增: } | |
| 82 | 新增: } | |
| 57 | 83 | switch action { |
| 58 | 84 | case "create": |
| 59 | 85 | if input.Password != input.ConfirmPassword { |
| 60 | 86 | http.Error(w, "两次密码不一致", 400) |
| 61 | 87 | return |
| 62 | 88 | } |
| 63 | 删除: err = s.account.create(input.Username, input.Password, input.Avatar) | |
| 89 | 新增: err = s.account.createAccount(input.Username, input.Password, input.Avatar, s.macAccountHost()) | |
| 90 | 新增: case "prepare-macos": | |
| 91 | 新增: if !s.macAccountHost() || !s.hasTrustedView(r) { | |
| 92 | 新增: http.Error(w, "请在本机 Cage 窗口设置共用账密", http.StatusForbidden) | |
| 93 | 新增: return | |
| 94 | 新增: } | |
| 95 | 新增: if input.Password != input.ConfirmPassword { | |
| 96 | 新增: http.Error(w, "两次密码不一致", http.StatusBadRequest) | |
| 97 | 新增: return | |
| 98 | 新增: } | |
| 99 | 新增: guests := map[string]macGuestCredential{} | |
| 100 | 新增: install, loadErr := guestos.LoadInstallation(s.profile) | |
| 101 | 新增: if loadErr != nil { | |
| 102 | 新增: requestError(w, loadErr) | |
| 103 | 新增: return | |
| 104 | 新增: } | |
| 105 | 新增: if s.macosGuest != nil && install == nil { | |
| 106 | 新增: http.Error(w, "原客机安装记录缺失,请恢复备份后继续", http.StatusConflict) | |
| 107 | 新增: return | |
| 108 | 新增: } | |
| 109 | 新增: if install != nil { | |
| 110 | 新增: previous, loadErr := s.account.savedMacGuestPassword(r.Context(), install.ID) | |
| 111 | 新增: if loadErr != nil { | |
| 112 | 新增: requestError(w, loadErr) | |
| 113 | 新增: return | |
| 114 | 新增: } | |
| 115 | 新增: if s.macosGuest != nil && previous == "" { | |
| 116 | 新增: http.Error(w, "原客机凭据缺失,请恢复加密保险箱后继续", http.StatusConflict) | |
| 117 | 新增: return | |
| 118 | 新增: } | |
| 119 | 新增: if previous != "" { | |
| 120 | 新增: user := "cage" | |
| 121 | 新增: if s.macosGuest != nil { | |
| 122 | 新增: user = s.macosGuest.User | |
| 123 | 新增: } | |
| 124 | 新增: if input.Username != user { | |
| 125 | 新增: http.Error(w, "请使用现有客机用户名;安装记录和原文件已保留", http.StatusConflict) | |
| 126 | 新增: return | |
| 127 | 新增: } | |
| 128 | 新增: guests[install.ID.String()] = macGuestCredential{Username: user, Password: previous} | |
| 129 | 新增: } | |
| 130 | 新增: } | |
| 131 | 新增: err = s.account.prepareMacAccount(input.Username, input.Password, guests) | |
| 64 | 132 | case "unlock": |
| 65 | 133 | err = s.account.unlock(input.Password) |
| 66 | 134 | case "profile": |
| @@ -97,5 +165,10 @@ func (s *Server) accountAction(w http.ResponseWriter, r *http.Request) { | ||
| 97 | 165 | if action == "lock" || action == "suspend" { |
| 98 | 166 | s.clearBrowserVault(vaultLease) |
| 99 | 167 | } |
| 168 | 新增: if (action == "password" || action == "prepare-macos") && s.macosGuest != nil && s.vmRunning() { | |
| 169 | 新增: // The account write already succeeded. A failed guest update remains a | |
| 170 | 新增: // durable pending state, rather than reporting that the old Cage password works. | |
| 171 | 新增: _ = s.syncMacGuestPassword(r.Context()) | |
| 172 | 新增: } | |
| 100 | 173 | s.accountStatus(w, r) |
| 101 | 174 | } |
| @@ -24,6 +24,7 @@ import ( | ||
| 24 | 24 | ) |
| 25 | 25 | |
| 26 | 26 | type accountRecord struct { |
| 27 | 新增: MacLogin *macAccountEnvelope `json:"mac_login,omitempty"` | |
| 27 | 28 | TrustedDevice string `json:"trusted_device,omitempty"` |
| 28 | 29 | TrustedUnlock *accountDevice `json:"trusted_unlock,omitempty"` |
| 29 | 30 | Version int `json:"version"` |
| @@ -37,6 +38,7 @@ type accountRecord struct { | ||
| 37 | 38 | } |
| 38 | 39 | |
| 39 | 40 | type localAccount struct { |
| 41 | 新增: macSync sync.Mutex | |
| 40 | 42 | mu sync.Mutex |
| 41 | 43 | path string |
| 42 | 44 | record *accountRecord |
| @@ -49,6 +51,10 @@ type localAccount struct { | ||
| 49 | 51 | } |
| 50 | 52 | |
| 51 | 53 | type accountView struct { |
| 54 | 新增: MacOSAccountHost bool `json:"macos_account_host,omitempty"` | |
| 55 | 新增: MacOSCredentialsReady bool `json:"macos_credentials_ready,omitempty"` | |
| 56 | 新增: MacOSUsernameBound bool `json:"macos_username_bound,omitempty"` | |
| 57 | 新增: MacOSPasswordPending bool `json:"macos_password_pending,omitempty"` | |
| 52 | 58 | MacOSGuestUser string `json:"macos_guest_user,omitempty"` |
| 53 | 59 | InitialMacSetup bool `json:"initial_mac_setup,omitempty"` |
| 54 | 60 | GuestSystem string `json:"guest_system,omitempty"` |
| @@ -155,6 +161,15 @@ func (a *localAccount) viewFor(desktop bool) accountView { | ||
| 155 | 161 | v := accountView{Exists: a.record != nil, Unlocked: len(a.key) == 32 && (!a.trustedSession || desktop)} |
| 156 | 162 | v.DeviceBinding = fmtAccountBinding(a.path) |
| 157 | 163 | if a.record != nil { |
| 164 | 新增: if a.record.MacLogin != nil && v.Unlocked { | |
| 165 | 新增: if login, err := a.openMacAccount(); err == nil { | |
| 166 | 新增: v.MacOSCredentialsReady = true | |
| 167 | 新增: v.MacOSUsernameBound = len(login.Guests) != 0 | |
| 168 | 新增: for _, guest := range login.Guests { | |
| 169 | 新增: v.MacOSPasswordPending = v.MacOSPasswordPending || guest.Password != login.Password | |
| 170 | 新增: } | |
| 171 | 新增: } | |
| 172 | 新增: } | |
| 158 | 173 | v.TrustedLocal = a.record.TrustedDevice != "" |
| 159 | 174 | v.TrustedLogin = a.record.TrustedUnlock != nil |
| 160 | 175 | v.Username = a.record.Username |
| @@ -205,7 +220,16 @@ func (a *localAccount) lock() { | ||
| 205 | 220 | } |
| 206 | 221 | |
| 207 | 222 | func (a *localAccount) create(name, password, avatar string) error { |
| 223 | 新增: return a.createAccount(name, password, avatar, false) | |
| 224 | 新增:} | |
| 225 | 新增: | |
| 226 | 新增:func (a *localAccount) createAccount(name, password, avatar string, mac bool) error { | |
| 208 | 227 | name = strings.TrimSpace(name) |
| 228 | 新增: if mac { | |
| 229 | 新增: if err := validMacAccount(name, password); err != nil { | |
| 230 | 新增: return err | |
| 231 | 新增: } | |
| 232 | 新增: } | |
| 209 | 233 | if err := validAccountName(name); err != nil { |
| 210 | 234 | return err |
| 211 | 235 | } |
| @@ -230,6 +254,11 @@ func (a *localAccount) create(name, password, avatar string) error { | ||
| 230 | 254 | if err = sealAccountKey(record, password, key); err != nil { |
| 231 | 255 | return err |
| 232 | 256 | } |
| 257 | 新增: if mac { | |
| 258 | 新增: if err = sealMacAccount(record, key, macAccountData{Password: password}); err != nil { | |
| 259 | 新增: return err | |
| 260 | 新增: } | |
| 261 | 新增: } | |
| 233 | 262 | if err = writePrivate(a.path, record); err != nil { |
| 234 | 263 | return errors.New("账户未能保存,请检查磁盘空间与目录权限") |
| 235 | 264 | } |
| @@ -275,6 +304,18 @@ func (a *localAccount) updateProfile(name, avatar string) error { | ||
| 275 | 304 | if len(a.key) != 32 { |
| 276 | 305 | return errors.New("请先解锁 Cage") |
| 277 | 306 | } |
| 307 | 新增: if a.record.MacLogin != nil && name != a.record.Username { | |
| 308 | 新增: login, err := a.openMacAccount() | |
| 309 | 新增: if err != nil { | |
| 310 | 新增: return err | |
| 311 | 新增: } | |
| 312 | 新增: if len(login.Guests) != 0 { | |
| 313 | 新增: return errors.New("用户名已用于 macOS 客机,保留该名称以继续使用原账户和文件") | |
| 314 | 新增: } | |
| 315 | 新增: if err := validMacAccount(name, login.Password); err != nil { | |
| 316 | 新增: return err | |
| 317 | 新增: } | |
| 318 | 新增: } | |
| 278 | 319 | record := *a.record |
| 279 | 320 | record.Username = name |
| 280 | 321 | record.Avatar = normalized |
| @@ -304,6 +345,24 @@ func (a *localAccount) changePassword(oldPassword, newPassword string) error { | ||
| 304 | 345 | } |
| 305 | 346 | defer clear(key) |
| 306 | 347 | record := *a.record |
| 348 | 新增: if record.MacLogin != nil { | |
| 349 | 新增: login, err := a.openMacAccount() | |
| 350 | 新增: if err != nil { | |
| 351 | 新增: return err | |
| 352 | 新增: } | |
| 353 | 新增: if err = validMacAccount(record.Username, newPassword); err != nil { | |
| 354 | 新增: return err | |
| 355 | 新增: } | |
| 356 | 新增: for _, guest := range login.Guests { | |
| 357 | 新增: if guest.Password != login.Password { | |
| 358 | 新增: return errors.New("客机密码仍待同步,请先启动 macOS 客机并完成同步后再改密") | |
| 359 | 新增: } | |
| 360 | 新增: } | |
| 361 | 新增: login.Password = newPassword | |
| 362 | 新增: if err = sealMacAccount(&record, key, login); err != nil { | |
| 363 | 新增: return err | |
| 364 | 新增: } | |
| 365 | 新增: } | |
| 307 | 366 | if err = sealAccountKey(&record, newPassword, key); err != nil { |
| 308 | 367 | return err |
| 309 | 368 | } |
| @@ -188,6 +188,10 @@ func (s *Server) installedWindowsVMOwner(install guestos.Installation) (string, | ||
| 188 | 188 | } |
| 189 | 189 | |
| 190 | 190 | func (s *Server) beginGuestInstall(w http.ResponseWriter, r *http.Request, in guestInstallRequest) { |
| 191 | 新增: if in.System == guestos.MacOS && !s.account.view().MacOSCredentialsReady { | |
| 192 | 新增: http.Error(w, "请先注册或确认 Cage 账密,再安装 macOS 客机", http.StatusConflict) | |
| 193 | 新增: return | |
| 194 | 新增: } | |
| 191 | 195 | v, err := s.guestInstallView() |
| 192 | 196 | if err != nil { |
| 193 | 197 | requestError(w, err) |
| @@ -304,7 +308,7 @@ func (s *Server) beginGuestInstall(w http.ResponseWriter, r *http.Request, in gu | ||
| 304 | 308 | return err |
| 305 | 309 | } |
| 306 | 310 | } |
| 307 | 删除: var password string | |
| 311 | 新增: var credential macGuestCredential | |
| 308 | 312 | if install.System == guestos.MacOS { |
| 309 | 313 | saved, err := s.account.savedMacGuestPassword(s.operationContext(), install.ID) |
| 310 | 314 | if err != nil { |
| @@ -317,7 +321,7 @@ func (s *Server) beginGuestInstall(w http.ResponseWriter, r *http.Request, in gu | ||
| 317 | 321 | if saved == "" && !unstarted { |
| 318 | 322 | return errors.New("客机安装凭据缺失,请恢复加密保险箱;现有账户和磁盘已保留") |
| 319 | 323 | } |
| 320 | 删除: password, err = s.account.macGuestPassword(s.operationContext(), install.ID) | |
| 324 | 新增: credential, err = s.account.macGuestCredentials(s.operationContext(), install.ID) | |
| 321 | 325 | if err != nil { |
| 322 | 326 | return err |
| 323 | 327 | } |
| @@ -339,8 +343,8 @@ func (s *Server) beginGuestInstall(w http.ResponseWriter, r *http.Request, in gu | ||
| 339 | 343 | var cmd *exec.Cmd |
| 340 | 344 | if install.System == guestos.MacOS { |
| 341 | 345 | cmd = exec.CommandContext(s.operationContext(), s.exe, "guest-os", "macos", "install") |
| 342 | 删除: cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath) | |
| 343 | 删除: cmd.Stdin = strings.NewReader(password) | |
| 346 | 新增: cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath, "CAGE_MACOS_ACCOUNT="+credential.Username) | |
| 347 | 新增: cmd.Stdin = strings.NewReader(credential.Password) | |
| 344 | 348 | } else { |
| 345 | 349 | cmd, err = guestos.WindowsInstallCommand(s.operationContext(), s.profile, filepath.Join(filepath.Dir(s.exe), "guest-os"), install) |
| 346 | 350 | if err != nil { |
| @@ -2,45 +2,259 @@ package workbench | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "context" |
| 5 | 新增: "crypto/aes" | |
| 6 | 新增: "crypto/cipher" | |
| 5 | 7 | "crypto/rand" |
| 6 | 删除: "encoding/base64" | |
| 8 | 新增: "encoding/json" | |
| 7 | 9 | "errors" |
| 10 | 新增: "strings" | |
| 11 | 新增: "time" | |
| 8 | 12 | |
| 9 | 13 | "github.com/google/uuid" |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 10 | 15 | ) |
| 11 | 16 | |
| 12 | 删除:// Guest credentials use the account's existing encrypted vault and installation | |
| 13 | 删除:// identity. They are never website entries or returned by the vault API. | |
| 14 | 删除:func (a *localAccount) macGuestPassword(ctx context.Context, id uuid.UUID) (string, error) { | |
| 15 | 删除: var password string | |
| 16 | 删除: err := a.withVault(ctx, true, func(db *vaultData) error { | |
| 17 | 删除: if id == uuid.Nil { | |
| 18 | 删除: return errors.New("缺少客机安装身份") | |
| 19 | 删除: } | |
| 20 | 删除: password = db.GuestPasswords[id.String()] | |
| 21 | 删除: if password != "" { | |
| 22 | 删除: return nil | |
| 17 | 新增:// This credential is encrypted with the account key, with a separate domain. | |
| 18 | 新增:// Saving it in the account record makes password changes and the guest retry | |
| 19 | 新增:// record one atomic write. Website vault APIs never see this data. | |
| 20 | 新增:type macAccountEnvelope struct{ Nonce, Data []byte } | |
| 21 | 新增:type macGuestCredential struct{ Username, Password string } | |
| 22 | 新增:type macAccountData struct { | |
| 23 | 新增: Password string | |
| 24 | 新增: Guests map[string]macGuestCredential | |
| 25 | 新增:} | |
| 26 | 新增: | |
| 27 | 新增:const macAccountDomain = "Cage shared macOS account v1" | |
| 28 | 新增: | |
| 29 | 新增:func validMacAccount(name, password string) error { | |
| 30 | 新增: if !guestos.ValidMacOSAccountName(name) { | |
| 31 | 新增: return errors.New("macOS 共用用户名需以小写英文字母开头,使用 1–31 个小写字母、数字或下划线;不能使用系统保留名称") | |
| 32 | 新增: } | |
| 33 | 新增: if !guestos.ValidMacOSInstallPassword(password) { | |
| 34 | 新增: return errors.New("macOS 共用密码需使用 8–256 个英文键盘可输入的字母、数字、空格或符号") | |
| 35 | 新增: } | |
| 36 | 新增: return nil | |
| 37 | 新增:} | |
| 38 | 新增:func sealMacAccount(record *accountRecord, key []byte, login macAccountData) error { | |
| 39 | 新增: block, err := aes.NewCipher(key) | |
| 40 | 新增: if err != nil { | |
| 41 | 新增: return err | |
| 42 | 新增: } | |
| 43 | 新增: aead, err := cipher.NewGCM(block) | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: return err | |
| 46 | 新增: } | |
| 47 | 新增: plain, err := json.Marshal(login) | |
| 48 | 新增: if err != nil { | |
| 49 | 新增: return err | |
| 50 | 新增: } | |
| 51 | 新增: defer clear(plain) | |
| 52 | 新增: sealed := &macAccountEnvelope{Nonce: make([]byte, aead.NonceSize())} | |
| 53 | 新增: if _, err = rand.Read(sealed.Nonce); err != nil { | |
| 54 | 新增: return err | |
| 55 | 新增: } | |
| 56 | 新增: sealed.Data = aead.Seal(nil, sealed.Nonce, plain, []byte(macAccountDomain)) | |
| 57 | 新增: record.MacLogin = sealed | |
| 58 | 新增: return nil | |
| 59 | 新增:} | |
| 60 | 新增: | |
| 61 | 新增:// Caller holds a.mu. | |
| 62 | 新增:func (a *localAccount) openMacAccount() (macAccountData, error) { | |
| 63 | 新增: var login macAccountData | |
| 64 | 新增: if len(a.key) != 32 || a.record == nil { | |
| 65 | 新增: return login, errors.New("请先解锁 Cage") | |
| 66 | 新增: } | |
| 67 | 新增: if a.record.MacLogin == nil { | |
| 68 | 新增: return login, errors.New("请先确认 Cage 用户名和密码,再安装 macOS 客机") | |
| 69 | 新增: } | |
| 70 | 新增: block, _ := aes.NewCipher(a.key) | |
| 71 | 新增: aead, _ := cipher.NewGCM(block) | |
| 72 | 新增: sealed := a.record.MacLogin | |
| 73 | 新增: if len(sealed.Nonce) != aead.NonceSize() { | |
| 74 | 新增: return login, errors.New("客机共用凭据损坏,请恢复账户备份") | |
| 75 | 新增: } | |
| 76 | 新增: plain, err := aead.Open(nil, sealed.Nonce, sealed.Data, []byte(macAccountDomain)) | |
| 77 | 新增: if err != nil { | |
| 78 | 新增: return login, errors.New("客机共用凭据无法解密,请恢复账户备份") | |
| 79 | 新增: } | |
| 80 | 新增: defer clear(plain) | |
| 81 | 新增: if json.Unmarshal(plain, &login) != nil || validMacAccount(a.record.Username, login.Password) != nil { | |
| 82 | 新增: return login, errors.New("客机共用凭据无效,请恢复账户备份") | |
| 83 | 新增: } | |
| 84 | 新增: return login, nil | |
| 85 | 新增:} | |
| 86 | 新增: | |
| 87 | 新增:// Existing password accounts prove their password; older trusted local accounts | |
| 88 | 新增:// set their first password without replacing the account key or personal data. | |
| 89 | 新增:func (a *localAccount) prepareMacAccount(name, password string, guests map[string]macGuestCredential) error { | |
| 90 | 新增: name = strings.TrimSpace(name) | |
| 91 | 新增: if err := validMacAccount(name, password); err != nil { | |
| 92 | 新增: return err | |
| 93 | 新增: } | |
| 94 | 新增: a.mu.Lock() | |
| 95 | 新增: defer a.mu.Unlock() | |
| 96 | 新增: if len(a.key) != 32 || a.record == nil { | |
| 97 | 新增: return errors.New("请先解锁 Cage") | |
| 98 | 新增: } | |
| 99 | 新增: if a.record.MacLogin != nil { | |
| 100 | 新增: return errors.New("共用账密已经设置,请在账户设置中修改密码") | |
| 101 | 新增: } | |
| 102 | 新增: if a.record.TrustedDevice == "" { | |
| 103 | 新增: if time.Now().Before(a.nextAttempt) { | |
| 104 | 新增: return errors.New("请稍后再试") | |
| 23 | 105 | } |
| 24 | 删除: var bytes [24]byte | |
| 25 | 删除: if _, err := rand.Read(bytes[:]); err != nil { | |
| 106 | 新增: key, err := openAccountKey(a.record, password) | |
| 107 | 新增: if err != nil { | |
| 108 | 新增: a.nextAttempt = time.Now().Add(time.Second) | |
| 26 | 109 | return err |
| 27 | 110 | } |
| 28 | 删除: password = base64.RawURLEncoding.EncodeToString(bytes[:]) | |
| 29 | 删除: clear(bytes[:]) | |
| 30 | 删除: if db.GuestPasswords == nil { | |
| 31 | 删除: db.GuestPasswords = map[string]string{} | |
| 32 | 删除: } | |
| 33 | 删除: db.GuestPasswords[id.String()] = password | |
| 34 | 删除: return nil | |
| 35 | 删除: }) | |
| 36 | 删除: return password, err | |
| 111 | 新增: clear(key) | |
| 112 | 新增: a.nextAttempt = time.Time{} | |
| 113 | 新增: } | |
| 114 | 新增: record := *a.record | |
| 115 | 新增: record.Username, record.TrustedDevice = name, "" | |
| 116 | 新增: if err := sealAccountKey(&record, password, a.key); err != nil { | |
| 117 | 新增: return err | |
| 118 | 新增: } | |
| 119 | 新增: if err := sealMacAccount(&record, a.key, macAccountData{Password: password, Guests: guests}); err != nil { | |
| 120 | 新增: return err | |
| 121 | 新增: } | |
| 122 | 新增: if err := writePrivate(a.path, &record); err != nil { | |
| 123 | 新增: return errors.New("共用账密未能保存,原账户和文件已保留") | |
| 124 | 新增: } | |
| 125 | 新增: a.record, a.trustedSession = &record, false | |
| 126 | 新增: return nil | |
| 37 | 127 | } |
| 38 | 128 | |
| 129 | 新增:func (a *localAccount) macGuestCredentials(ctx context.Context, id uuid.UUID) (macGuestCredential, error) { | |
| 130 | 新增: if ctx.Err() != nil { | |
| 131 | 新增: return macGuestCredential{}, ctx.Err() | |
| 132 | 新增: } | |
| 133 | 新增: if id == uuid.Nil { | |
| 134 | 新增: return macGuestCredential{}, errors.New("缺少客机安装身份") | |
| 135 | 新增: } | |
| 136 | 新增: a.mu.Lock() | |
| 137 | 新增: if a.record != nil && a.record.MacLogin != nil { | |
| 138 | 新增: login, err := a.openMacAccount() | |
| 139 | 新增: a.mu.Unlock() | |
| 140 | 新增: if err != nil { | |
| 141 | 新增: return macGuestCredential{}, err | |
| 142 | 新增: } | |
| 143 | 新增: if guest, ok := login.Guests[id.String()]; ok { | |
| 144 | 新增: return guest, nil | |
| 145 | 新增: } | |
| 146 | 新增: } else { | |
| 147 | 新增: a.mu.Unlock() | |
| 148 | 新增: } | |
| 149 | 新增: // Old installations retain their existing account and password. | |
| 150 | 新增: legacy, err := a.legacyMacGuestPassword(ctx, id) | |
| 151 | 新增: if err != nil { | |
| 152 | 新增: return macGuestCredential{}, err | |
| 153 | 新增: } | |
| 154 | 新增: if legacy != "" { | |
| 155 | 新增: return macGuestCredential{Username: "cage", Password: legacy}, nil | |
| 156 | 新增: } | |
| 157 | 新增: a.mu.Lock() | |
| 158 | 新增: defer a.mu.Unlock() | |
| 159 | 新增: if ctx.Err() != nil { | |
| 160 | 新增: return macGuestCredential{}, ctx.Err() | |
| 161 | 新增: } | |
| 162 | 新增: login, err := a.openMacAccount() | |
| 163 | 新增: if err != nil { | |
| 164 | 新增: return macGuestCredential{}, err | |
| 165 | 新增: } | |
| 166 | 新增: if guest, ok := login.Guests[id.String()]; ok { | |
| 167 | 新增: return guest, nil | |
| 168 | 新增: } | |
| 169 | 新增: guest := macGuestCredential{Username: a.record.Username, Password: login.Password} | |
| 170 | 新增: if login.Guests == nil { | |
| 171 | 新增: login.Guests = map[string]macGuestCredential{} | |
| 172 | 新增: } | |
| 173 | 新增: login.Guests[id.String()] = guest | |
| 174 | 新增: record := *a.record | |
| 175 | 新增: if err = sealMacAccount(&record, a.key, login); err != nil { | |
| 176 | 新增: return macGuestCredential{}, err | |
| 177 | 新增: } | |
| 178 | 新增: if err = writePrivate(a.path, &record); err != nil { | |
| 179 | 新增: return macGuestCredential{}, errors.New("客机账密未能保存,请检查磁盘空间与目录权限") | |
| 180 | 新增: } | |
| 181 | 新增: a.record = &record | |
| 182 | 新增: return guest, nil | |
| 183 | 新增:} | |
| 39 | 184 | func (a *localAccount) savedMacGuestPassword(ctx context.Context, id uuid.UUID) (string, error) { |
| 185 | 新增: a.mu.Lock() | |
| 186 | 新增: if len(a.key) != 32 || ctx.Err() != nil { | |
| 187 | 新增: a.mu.Unlock() | |
| 188 | 新增: return "", errors.New("请先解锁 Cage") | |
| 189 | 新增: } | |
| 190 | 新增: if a.record.MacLogin != nil { | |
| 191 | 新增: login, err := a.openMacAccount() | |
| 192 | 新增: a.mu.Unlock() | |
| 193 | 新增: if err != nil { | |
| 194 | 新增: return "", err | |
| 195 | 新增: } | |
| 196 | 新增: if guest, ok := login.Guests[id.String()]; ok { | |
| 197 | 新增: return guest.Password, nil | |
| 198 | 新增: } | |
| 199 | 新增: } else { | |
| 200 | 新增: a.mu.Unlock() | |
| 201 | 新增: } | |
| 202 | 新增: return a.legacyMacGuestPassword(ctx, id) | |
| 203 | 新增:} | |
| 204 | 新增:func (a *localAccount) legacyMacGuestPassword(ctx context.Context, id uuid.UUID) (string, error) { | |
| 40 | 205 | var password string |
| 41 | 删除: err := a.withVault(ctx, false, func(db *vaultData) error { | |
| 42 | 删除: password = db.GuestPasswords[id.String()] | |
| 43 | 删除: return nil | |
| 44 | 删除: }) | |
| 206 | 新增: err := a.withVault(ctx, false, func(db *vaultData) error { password = db.GuestPasswords[id.String()]; return nil }) | |
| 45 | 207 | return password, err |
| 46 | 208 | } |
| 209 | 新增: | |
| 210 | 新增:// syncMacPassword retries with both the last confirmed and the target password. | |
| 211 | 新增:// The guest operation must be idempotent after any individual system write. | |
| 212 | 新增:func (a *localAccount) syncMacPassword(ctx context.Context, id uuid.UUID, user string, apply func(context.Context, string, string) error) error { | |
| 213 | 新增: a.macSync.Lock() | |
| 214 | 新增: defer a.macSync.Unlock() | |
| 215 | 新增: a.mu.Lock() | |
| 216 | 新增: if a.record == nil || a.record.MacLogin == nil || len(a.key) != 32 { | |
| 217 | 新增: a.mu.Unlock() | |
| 218 | 新增: return nil | |
| 219 | 新增: } | |
| 220 | 新增: login, err := a.openMacAccount() | |
| 221 | 新增: if err != nil { | |
| 222 | 新增: a.mu.Unlock() | |
| 223 | 新增: return err | |
| 224 | 新增: } | |
| 225 | 新增: guest, ok := login.Guests[id.String()] | |
| 226 | 新增: if !ok || guest.Password == login.Password { | |
| 227 | 新增: a.mu.Unlock() | |
| 228 | 新增: return nil | |
| 229 | 新增: } | |
| 230 | 新增: if guest.Username != user { | |
| 231 | 新增: a.mu.Unlock() | |
| 232 | 新增: return errors.New("客机同步账户与安装记录不一致,原账户已保留") | |
| 233 | 新增: } | |
| 234 | 新增: target := login.Password | |
| 235 | 新增: a.mu.Unlock() | |
| 236 | 新增: if err = apply(ctx, guest.Password, target); err != nil { | |
| 237 | 新增: return errors.New("Cage 密码已保存;客机密码尚待同步,请启动客机后重试,期间客机仍可能需要原密码") | |
| 238 | 新增: } | |
| 239 | 新增: a.mu.Lock() | |
| 240 | 新增: defer a.mu.Unlock() | |
| 241 | 新增: login, err = a.openMacAccount() | |
| 242 | 新增: if err != nil { | |
| 243 | 新增: return err | |
| 244 | 新增: } | |
| 245 | 新增: current, ok := login.Guests[id.String()] | |
| 246 | 新增: if !ok || current != guest || login.Password != target { | |
| 247 | 新增: return errors.New("客机密码同步记录已变化,请重试") | |
| 248 | 新增: } | |
| 249 | 新增: current.Password = target | |
| 250 | 新增: login.Guests[id.String()] = current | |
| 251 | 新增: record := *a.record | |
| 252 | 新增: if err = sealMacAccount(&record, a.key, login); err != nil { | |
| 253 | 新增: return err | |
| 254 | 新增: } | |
| 255 | 新增: if err = writePrivate(a.path, &record); err != nil { | |
| 256 | 新增: return errors.New("客机密码已更新,确认记录待保存;下次启动会重试确认") | |
| 257 | 新增: } | |
| 258 | 新增: a.record = &record | |
| 259 | 新增: return nil | |
| 260 | 新增:} | |
| @@ -4,6 +4,8 @@ import ( | ||
| 4 | 4 | "bytes" |
| 5 | 5 | "context" |
| 6 | 6 | "encoding/json" |
| 7 | 新增: "errors" | |
| 8 | 新增: "net/http" | |
| 7 | 9 | "net/http/httptest" |
| 8 | 10 | "os" |
| 9 | 11 | "path/filepath" |
| @@ -12,57 +14,246 @@ import ( | ||
| 12 | 14 | "github.com/google/uuid" |
| 13 | 15 | ) |
| 14 | 16 | |
| 17 | 新增:func TestMacSharedAccountHTTPRegistration(t *testing.T) { | |
| 18 | 新增: s := testServer(t) | |
| 19 | 新增: if !s.macAccountHost() { | |
| 20 | 新增: t.Skip("requires a Mac host") | |
| 21 | 新增: } | |
| 22 | 新增: a, err := loadLocalAccount(t.TempDir()) | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: t.Fatal(err) | |
| 25 | 新增: } | |
| 26 | 新增: defer a.lock() | |
| 27 | 新增: s.account = a | |
| 28 | 新增: w := request(s, "POST", "/api/account/create", s.origin, `{"username":"unsupported name","password":"fixture-password","confirm_password":"fixture-password"}`, true) | |
| 29 | 新增: if w.Code != http.StatusBadRequest || a.view().Exists { | |
| 30 | 新增: t.Fatalf("invalid registration: %d", w.Code) | |
| 31 | 新增: } | |
| 32 | 新增: w = request(s, "POST", "/api/account/create", s.origin, `{"username":"http_qa","password":"fixture-password","confirm_password":"fixture-password"}`, true) | |
| 33 | 新增: var view accountView | |
| 34 | 新增: if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &view) != nil || !view.MacOSCredentialsReady || view.Username != "http_qa" { | |
| 35 | 新增: t.Fatalf("registration did not prepare shared credentials: %d %s", w.Code, w.Body.String()) | |
| 36 | 新增: } | |
| 37 | 新增: guest, err := a.macGuestCredentials(context.Background(), uuid.New()) | |
| 38 | 新增: if err != nil || guest.Username != view.Username || guest.Password != "fixture-password" { | |
| 39 | 新增: t.Fatal("installer did not receive registered account", err) | |
| 40 | 新增: } | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:func newSharedMacAccount(t *testing.T) *localAccount { | |
| 44 | 新增: t.Helper() | |
| 45 | 新增: a, err := loadLocalAccount(t.TempDir()) | |
| 46 | 新增: if err != nil { | |
| 47 | 新增: t.Fatal(err) | |
| 48 | 新增: } | |
| 49 | 新增: if err = a.createAccount("shihao", "initial-test-password", "", true); err != nil { | |
| 50 | 新增: t.Fatal(err) | |
| 51 | 新增: } | |
| 52 | 新增: t.Cleanup(a.lock) | |
| 53 | 新增: return a | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 15 | 56 | func TestMacGuestCredentialEncryptionResumeAndIsolation(t *testing.T) { |
| 16 | 删除: a := newTestAccount(t) | |
| 57 | 新增: a := newSharedMacAccount(t) | |
| 17 | 58 | ctx := context.Background() |
| 18 | 59 | id := uuid.New() |
| 19 | 删除: password, err := a.macGuestPassword(ctx, id) | |
| 20 | 删除: if err != nil || len(password) != 32 { | |
| 21 | 删除: t.Fatalf("generate: %v", err) | |
| 60 | 新增: guest, err := a.macGuestCredentials(ctx, id) | |
| 61 | 新增: if err != nil || guest.Username != "shihao" || guest.Password != "initial-test-password" { | |
| 62 | 新增: t.Fatalf("shared account: %#v %v", guest, err) | |
| 22 | 63 | } |
| 23 | 删除: raw, _ := os.ReadFile(filepath.Join(filepath.Dir(a.path), "password-vault.json")) | |
| 24 | 删除: if bytes.Contains(raw, []byte(password)) { | |
| 25 | 删除: t.Fatal("plaintext guest password persisted") | |
| 64 | 新增: raw, _ := os.ReadFile(a.path) | |
| 65 | 新增: if bytes.Contains(raw, []byte(guest.Password)) { | |
| 66 | 新增: t.Fatal("plaintext password persisted") | |
| 26 | 67 | } |
| 27 | 删除: resumed, err := a.macGuestPassword(ctx, id) | |
| 28 | 删除: if err != nil || resumed != password { | |
| 29 | 删除: t.Fatal("retry changed guest password", err) | |
| 68 | 新增: a.lock() | |
| 69 | 新增: if err = a.unlock(guest.Password); err != nil { | |
| 70 | 新增: t.Fatal(err) | |
| 71 | 新增: } | |
| 72 | 新增: resumed, err := a.macGuestCredentials(ctx, id) | |
| 73 | 新增: if err != nil || resumed != guest { | |
| 74 | 新增: t.Fatal("retry changed installation credentials", err) | |
| 30 | 75 | } |
| 31 | 删除: other, err := a.macGuestPassword(ctx, uuid.New()) | |
| 32 | 删除: if err != nil || other == password { | |
| 33 | 删除: t.Fatal("separate installation reused credential", err) | |
| 76 | 新增: other, err := a.macGuestCredentials(ctx, uuid.New()) | |
| 77 | 新增: if err != nil || other != guest { | |
| 78 | 新增: t.Fatal("new installation did not reuse Cage credentials", err) | |
| 34 | 79 | } |
| 35 | 80 | s := &Server{account: a} |
| 36 | 81 | w := httptest.NewRecorder() |
| 37 | 82 | s.vaultList(w, httptest.NewRequest("GET", "/api/vault", nil)) |
| 38 | 删除: if bytes.Contains(w.Body.Bytes(), []byte(password)) || bytes.Contains(w.Body.Bytes(), []byte("guest_passwords")) { | |
| 39 | 删除: t.Fatal("guest credential exposed by website vault API") | |
| 83 | 新增: if bytes.Contains(w.Body.Bytes(), []byte(guest.Password)) || bytes.Contains(w.Body.Bytes(), []byte("MacLogin")) { | |
| 84 | 新增: t.Fatal("website vault exposed shared credentials") | |
| 85 | 新增: } | |
| 86 | 新增: if err := a.updateProfile("another", ""); err == nil { | |
| 87 | 新增: t.Fatal("bound username was renamed") | |
| 88 | 新增: } | |
| 89 | 新增: a.lock() | |
| 90 | 新增: if _, err = a.savedMacGuestPassword(ctx, id); err == nil { | |
| 91 | 新增: t.Fatal("locked account decrypted guest credentials") | |
| 92 | 新增: } | |
| 93 | 新增:} | |
| 94 | 新增: | |
| 95 | 新增:func TestMacGuestPasswordChangeOfflineAndInterruptedSync(t *testing.T) { | |
| 96 | 新增: a := newSharedMacAccount(t) | |
| 97 | 新增: ctx := context.Background() | |
| 98 | 新增: id := uuid.New() | |
| 99 | 新增: _, err := a.macGuestCredentials(ctx, id) | |
| 100 | 新增: if err != nil { | |
| 101 | 新增: t.Fatal(err) | |
| 102 | 新增: } | |
| 103 | 新增: if err = a.changePassword("initial-test-password", "replacement-test-password"); err != nil { | |
| 104 | 新增: t.Fatal(err) | |
| 105 | 新增: } | |
| 106 | 新增: if !a.view().MacOSPasswordPending { | |
| 107 | 新增: t.Fatal("offline guest update disappeared") | |
| 108 | 新增: } | |
| 109 | 新增: // A second edit must not discard a password that may already be in the guest. | |
| 110 | 新增: if err = a.changePassword("replacement-test-password", "third-test-password"); err == nil { | |
| 111 | 新增: t.Fatal("pending target was replaced") | |
| 112 | 新增: } | |
| 113 | 新增: path := a.path | |
| 114 | 新增: a.lock() | |
| 115 | 新增: a, err = loadLocalAccount(filepath.Dir(path)) | |
| 116 | 新增: if err != nil { | |
| 117 | 新增: t.Fatal(err) | |
| 118 | 新增: } | |
| 119 | 新增: defer a.lock() | |
| 120 | 新增: if err = a.unlock("replacement-test-password"); err != nil { | |
| 121 | 新增: t.Fatal(err) | |
| 122 | 新增: } | |
| 123 | 新增: old, _ := a.savedMacGuestPassword(ctx, id) | |
| 124 | 新增: if old != "initial-test-password" { | |
| 125 | 新增: t.Fatal("offline guest lost its confirmed password") | |
| 126 | 新增: } | |
| 127 | 新增: applied := "initial-test-password" | |
| 128 | 新增: if err = a.syncMacPassword(ctx, id, "different-user", func(context.Context, string, string) error { t.Fatal("wrong guest account changed"); return nil }); err == nil { | |
| 129 | 新增: t.Fatal("identity mismatch accepted") | |
| 130 | 新增: } | |
| 131 | 新增: // Simulate loss of the reply after the guest password changes. | |
| 132 | 新增: err = a.syncMacPassword(ctx, id, "shihao", func(_ context.Context, old, target string) error { | |
| 133 | 新增: if old != applied { | |
| 134 | 新增: t.Fatal("missing original credential") | |
| 135 | 新增: } | |
| 136 | 新增: applied = target | |
| 137 | 新增: return errors.New("lost reply") | |
| 138 | 新增: }) | |
| 139 | 新增: if err == nil || !a.view().MacOSPasswordPending { | |
| 140 | 新增: t.Fatal("partial update was reported complete") | |
| 40 | 141 | } |
| 142 | 新增: err = a.syncMacPassword(ctx, id, "shihao", func(_ context.Context, old, target string) error { | |
| 143 | 新增: if old != "initial-test-password" || target != applied { | |
| 144 | 新增: t.Fatal("retry lost original or target credential") | |
| 145 | 新增: } | |
| 146 | 新增: return nil | |
| 147 | 新增: }) | |
| 148 | 新增: if err != nil || a.view().MacOSPasswordPending { | |
| 149 | 新增: t.Fatal("retry did not finish", err) | |
| 150 | 新增: } | |
| 151 | 新增: saved, _ := a.savedMacGuestPassword(ctx, id) | |
| 152 | 新增: if saved != applied { | |
| 153 | 新增: t.Fatal("authorization helper received stale password") | |
| 154 | 新增: } | |
| 155 | 新增: if err = a.changePassword(applied, "third-test-password"); err != nil { | |
| 156 | 新增: t.Fatal("completed sync blocked next change", err) | |
| 157 | 新增: } | |
| 158 | 新增:} | |
| 159 | 新增: | |
| 160 | 新增:func TestMacGuestPasswordFailedSaveAndAcknowledgement(t *testing.T) { | |
| 161 | 新增: a := newSharedMacAccount(t) | |
| 162 | 新增: ctx := context.Background() | |
| 163 | 新增: id := uuid.New() | |
| 164 | 新增: if _, err := a.macGuestCredentials(ctx, id); err != nil { | |
| 165 | 新增: t.Fatal(err) | |
| 166 | 新增: } | |
| 167 | 新增: path := a.path | |
| 168 | 新增: a.path = t.TempDir() | |
| 169 | 新增: if err := a.changePassword("initial-test-password", "replacement-test-password"); err == nil { | |
| 170 | 新增: t.Fatal("failed account write accepted") | |
| 171 | 新增: } | |
| 172 | 新增: a.path = path | |
| 173 | 新增: if a.view().MacOSPasswordPending { | |
| 174 | 新增: t.Fatal("failed account write published new guest target") | |
| 175 | 新增: } | |
| 176 | 新增: if err := a.changePassword("initial-test-password", "replacement-test-password"); err != nil { | |
| 177 | 新增: t.Fatal(err) | |
| 178 | 新增: } | |
| 179 | 新增: err := a.syncMacPassword(ctx, id, "shihao", func(context.Context, string, string) error { a.path = t.TempDir(); return nil }) | |
| 180 | 新增: a.path = path | |
| 181 | 新增: if err == nil || !a.view().MacOSPasswordPending { | |
| 182 | 新增: t.Fatal("failed acknowledgement lost retry") | |
| 183 | 新增: } | |
| 184 | 新增: if err = a.syncMacPassword(ctx, id, "shihao", func(context.Context, string, string) error { return nil }); err != nil { | |
| 185 | 新增: t.Fatal(err) | |
| 186 | 新增: } | |
| 187 | 新增:} | |
| 188 | 新增: | |
| 189 | 新增:func TestMacGuestLegacyCredentialAndAccountAdoption(t *testing.T) { | |
| 190 | 新增: a := newTestAccount(t) | |
| 191 | 新增: ctx := context.Background() | |
| 192 | 新增: id := uuid.New() | |
| 41 | 193 | if err := a.withVault(ctx, true, func(db *vaultData) error { |
| 42 | 删除: return db.save(vaultEntry{Origin: "https://example.com", Username: "fixture", Password: "website-password"}) | |
| 194 | 新增: db.GuestPasswords = map[string]string{id.String(): "old-guest-password"} | |
| 195 | 新增: return nil | |
| 43 | 196 | }); err != nil { |
| 44 | 197 | t.Fatal(err) |
| 45 | 198 | } |
| 46 | 删除: stored, _ := a.savedMacGuestPassword(ctx, id) | |
| 47 | 删除: if stored != password { | |
| 48 | 删除: t.Fatal("website mutation dropped guest credential") | |
| 199 | 新增: old, err := a.macGuestCredentials(ctx, id) | |
| 200 | 新增: if err != nil || old.Username != "cage" || old.Password != "old-guest-password" { | |
| 201 | 新增: t.Fatal("legacy installation credential changed", err) | |
| 49 | 202 | } |
| 50 | 删除: if err := a.changePassword("initial-test-password", "replacement-test-password"); err != nil { | |
| 203 | 新增: before, _ := a.desktopKey() | |
| 204 | 新增: if err = a.prepareMacAccount("cage", "initial-test-password", map[string]macGuestCredential{id.String(): old}); err != nil { | |
| 51 | 205 | t.Fatal(err) |
| 52 | 206 | } |
| 53 | 删除: a.lock() | |
| 54 | 删除: if _, err := a.savedMacGuestPassword(ctx, id); err == nil { | |
| 55 | 删除: t.Fatal("locked account decrypted guest credential") | |
| 207 | 新增: after, _ := a.desktopKey() | |
| 208 | 新增: defer clear(before) | |
| 209 | 新增: defer clear(after) | |
| 210 | 新增: if !bytes.Equal(before, after) { | |
| 211 | 新增: t.Fatal("adoption replaced personal-data encryption key") | |
| 56 | 212 | } |
| 57 | 删除: if err := a.unlock("replacement-test-password"); err != nil { | |
| 213 | 新增: if err = a.syncMacPassword(ctx, id, "cage", func(_ context.Context, old, target string) error { | |
| 214 | 新增: if old != "old-guest-password" || target != "initial-test-password" { | |
| 215 | 新增: t.Fatal("legacy migration lost either password") | |
| 216 | 新增: } | |
| 217 | 新增: return nil | |
| 218 | 新增: }); err != nil { | |
| 58 | 219 | t.Fatal(err) |
| 59 | 220 | } |
| 60 | 删除: stored, _ = a.savedMacGuestPassword(ctx, id) | |
| 61 | 删除: if stored != password { | |
| 62 | 删除: t.Fatal("account password change lost guest credential") | |
| 221 | 新增: resumed, err := a.macGuestCredentials(ctx, id) | |
| 222 | 新增: if err != nil || resumed.Password != "initial-test-password" { | |
| 223 | 新增: t.Fatal("legacy vault overrode synced password", err) | |
| 224 | 新增: } | |
| 225 | 新增:} | |
| 226 | 新增: | |
| 227 | 新增:func TestMacAccountRegistrationAndTrustedAdoption(t *testing.T) { | |
| 228 | 新增: for _, name := range []string{"root", "cagesetup", "cageprovision", "Guest", "测试", "name with spaces"} { | |
| 229 | 新增: if validMacAccount(name, "fixture-password") == nil { | |
| 230 | 新增: t.Fatalf("accepted unsupported username %q", name) | |
| 231 | 新增: } | |
| 232 | 新增: } | |
| 233 | 新增: a, err := loadLocalAccount(t.TempDir()) | |
| 234 | 新增: if err != nil { | |
| 235 | 新增: t.Fatal(err) | |
| 236 | 新增: } | |
| 237 | 新增: defer a.lock() | |
| 238 | 新增: devices := t.TempDir() | |
| 239 | 新增: if err = a.trustedLogin("create", "", devices); err != nil { | |
| 240 | 新增: t.Fatal(err) | |
| 241 | 新增: } | |
| 242 | 新增: before, _ := a.desktopKey() | |
| 243 | 新增: defer clear(before) | |
| 244 | 新增: if err = a.prepareMacAccount("shihao", "new-test-password", nil); err != nil { | |
| 245 | 新增: t.Fatal(err) | |
| 246 | 新增: } | |
| 247 | 新增: after, _ := a.desktopKey() | |
| 248 | 新增: defer clear(after) | |
| 249 | 新增: if !bytes.Equal(before, after) || a.view().TrustedLocal { | |
| 250 | 新增: t.Fatal("trusted adoption lost data key or retained passwordless account") | |
| 251 | 新增: } | |
| 252 | 新增: a.lock() | |
| 253 | 新增: if err = a.unlock("new-test-password"); err != nil { | |
| 254 | 新增: t.Fatal(err) | |
| 63 | 255 | } |
| 64 | 删除: var view map[string]any | |
| 65 | 删除: if json.Unmarshal(w.Body.Bytes(), &view) != nil { | |
| 66 | 删除: t.Fatal("invalid vault response") | |
| 256 | 新增: if validMacAccount("shihao", "密码不可用于macOS") == nil { | |
| 257 | 新增: t.Fatal("accepted unenterable guest password") | |
| 67 | 258 | } |
| 68 | 259 | } |
| @@ -137,6 +137,9 @@ func (s *Server) startMacOSGuest() error { | ||
| 137 | 137 | return err |
| 138 | 138 | } |
| 139 | 139 | } |
| 140 | 新增: if err := s.syncMacGuestPassword(s.operationContext()); err != nil { | |
| 141 | 新增: return err | |
| 142 | 新增: } | |
| 140 | 143 | if err := s.attachMacOSGuest(); err != nil { |
| 141 | 144 | return err |
| 142 | 145 | } |
| @@ -0,0 +1,163 @@ | ||
| 1 | 新增://go:build darwin && arm64 | |
| 2 | 新增: | |
| 3 | 新增:package workbench | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: "crypto/sha256" | |
| 9 | 新增: "encoding/hex" | |
| 10 | 新增: "encoding/json" | |
| 11 | 新增: "os" | |
| 12 | 新增: "os/exec" | |
| 13 | 新增: "path/filepath" | |
| 14 | 新增: "strings" | |
| 15 | 新增: "testing" | |
| 16 | 新增: "time" | |
| 17 | 新增: | |
| 18 | 新增: "github.com/google/uuid" | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 20 | 新增:) | |
| 21 | 新增: | |
| 22 | 新增:// Opt-in only: use the isolated release QA VM, never a personal profile. The | |
| 23 | 新增:// source account and its key remain unchanged; guest passwords are restored. | |
| 24 | 新增:func TestMacSharedPasswordLive(t *testing.T) { | |
| 25 | 新增: root := os.Getenv("CAGE_MACOS_SHARED_ACCOUNT_QA_ROOT") | |
| 26 | 新增: if root == "" { | |
| 27 | 新增: t.Skip("requires an owned, running macOS release QA VM") | |
| 28 | 新增: } | |
| 29 | 新增: raw, err := os.ReadFile(filepath.Join(root, "ownership.json")) | |
| 30 | 新增: if err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: var ownership struct { | |
| 34 | 新增: Purpose string `json:"purpose"` | |
| 35 | 新增: Existing bool `json:"existing_user_data"` | |
| 36 | 新增: } | |
| 37 | 新增: if json.Unmarshal(raw, &ownership) != nil || ownership.Existing || ownership.Purpose != "Seven release issue fixes and native guest acceptance" { | |
| 38 | 新增: t.Fatal("not the isolated release QA environment") | |
| 39 | 新增: } | |
| 40 | 新增: profile := filepath.Join(root, "profile") | |
| 41 | 新增: original, err := loadLocalAccount(profile) | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: t.Fatal(err) | |
| 44 | 新增: } | |
| 45 | 新增: defer original.lock() | |
| 46 | 新增: password, err := os.ReadFile(filepath.Join(root, "qa-account-password")) | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: t.Fatal(err) | |
| 49 | 新增: } | |
| 50 | 新增: defer clear(password) | |
| 51 | 新增: if err = original.unlock(string(password)); err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: accountBefore, err := os.ReadFile(original.path) | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: install, err := guestos.LoadInstallation(profile) | |
| 59 | 新增: if err != nil || install == nil { | |
| 60 | 新增: t.Fatal("missing QA installation") | |
| 61 | 新增: } | |
| 62 | 新增: bound, err := guestos.LoadMacOSProfile(profile) | |
| 63 | 新增: if err != nil || bound == nil { | |
| 64 | 新增: t.Fatal("missing QA guest binding") | |
| 65 | 新增: } | |
| 66 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) | |
| 67 | 新增: defer cancel() | |
| 68 | 新增: previous, err := original.savedMacGuestPassword(ctx, install.ID) | |
| 69 | 新增: if err != nil || previous == "" { | |
| 70 | 新增: t.Fatal("missing encrypted QA credential") | |
| 71 | 新增: } | |
| 72 | 新增: target := `Shared test-'"\$! 2026` | |
| 73 | 新增: fixture, err := loadLocalAccount(t.TempDir()) | |
| 74 | 新增: if err != nil { | |
| 75 | 新增: t.Fatal(err) | |
| 76 | 新增: } | |
| 77 | 新增: defer fixture.lock() | |
| 78 | 新增: if err = fixture.create(bound.User, target, ""); err != nil { | |
| 79 | 新增: t.Fatal(err) | |
| 80 | 新增: } | |
| 81 | 新增: if err = fixture.prepareMacAccount(bound.User, target, map[string]macGuestCredential{install.ID.String(): {Username: bound.User, Password: previous}}); err != nil { | |
| 82 | 新增: t.Fatal(err) | |
| 83 | 新增: } | |
| 84 | 新增: kit := t.TempDir() | |
| 85 | 新增: if err = os.Mkdir(filepath.Join(kit, "guest-os"), 0700); err != nil { | |
| 86 | 新增: t.Fatal(err) | |
| 87 | 新增: } | |
| 88 | 新增: helper, err := os.ReadFile(os.Getenv("CAGE_MACOS_SHARED_ACCOUNT_HELPER")) | |
| 89 | 新增: if err != nil { | |
| 90 | 新增: t.Fatal(err) | |
| 91 | 新增: } | |
| 92 | 新增: if err = os.WriteFile(filepath.Join(kit, "guest-os", "cage-finish-initial-setup"), helper, 0700); err != nil { | |
| 93 | 新增: t.Fatal(err) | |
| 94 | 新增: } | |
| 95 | 新增: s := &Server{profile: profile, account: fixture, macosGuest: bound, exe: filepath.Join(kit, "cage")} | |
| 96 | 新增: sentinel := ".cage-shared-account-" + uuid.NewString() | |
| 97 | 新增: cmd := s.macOSSSHCommand(ctx, "-T", "cage-macos", "--", `umask 077; printf preserved > "$HOME/`+sentinel+`"`) | |
| 98 | 新增: if err = cmd.Run(); err != nil { | |
| 99 | 新增: t.Fatal("cannot prepare isolated guest sentinel", err) | |
| 100 | 新增: } | |
| 101 | 新增: defer func() { | |
| 102 | 新增: _ = s.macOSSSHCommand(context.Background(), "-T", "cage-macos", "--", `rm -f "$HOME/`+sentinel+`"`).Run() | |
| 103 | 新增: }() | |
| 104 | 新增: defer func() { | |
| 105 | 新增: restore, cancel := context.WithTimeout(context.Background(), time.Minute) | |
| 106 | 新增: defer cancel() | |
| 107 | 新增: if err := s.applyMacGuestPassword(restore, install.ID, target, previous); err != nil { | |
| 108 | 新增: t.Errorf("restore original QA guest credential: %v", err) | |
| 109 | 新增: } | |
| 110 | 新增: }() | |
| 111 | 新增: if err = s.syncMacGuestPassword(ctx); err != nil { | |
| 112 | 新增: t.Fatal(err) | |
| 113 | 新增: } | |
| 114 | 新增: // Both ordinary login and the temporary authorization user accept Cage's | |
| 115 | 新增: // password. SSH still authenticates by key, so this checks password login too. | |
| 116 | 新增: for _, user := range []string{bound.User, "cagesetup"} { | |
| 117 | 新增: cmd = s.macOSSSHCommand(ctx, "-T", "cage-macos", "--", "/usr/bin/dscl /Local/Default -authonly "+user) | |
| 118 | 新增: cmd.Stdin = strings.NewReader(target + "\n") | |
| 119 | 新增: if err = cmd.Run(); err != nil { | |
| 120 | 新增: t.Fatal("guest account did not accept shared password for", user, err) | |
| 121 | 新增: } | |
| 122 | 新增: } | |
| 123 | 新增: cmd = s.macOSSSHCommand(ctx, "-T", "cage-macos", "--", "/usr/bin/dscl /Local/Default -authonly "+bound.User) | |
| 124 | 新增: cmd.Stdin = strings.NewReader(previous + "\n") | |
| 125 | 新增: if cmd.Run() == nil { | |
| 126 | 新增: t.Fatal("ordinary account still accepted its previous password") | |
| 127 | 新增: } | |
| 128 | 新增: provisionArgs, err := guestos.MacOSSSHArgs(profile, "cageprovision") | |
| 129 | 新增: if err != nil { | |
| 130 | 新增: t.Fatal(err) | |
| 131 | 新增: } | |
| 132 | 新增: check := exec.CommandContext(ctx, sshExecutable(), append(provisionArgs, "-T", "cage-macos", "--", `sudo -S -p '' /usr/bin/shasum -a 256 /etc/kcpassword < /Users/cageprovision/password`)...) | |
| 133 | 新增: actual, err := check.Output() | |
| 134 | 新增: if err != nil { | |
| 135 | 新增: t.Fatal("cannot verify system automatic login record", err) | |
| 136 | 新增: } | |
| 137 | 新增: encoded := append([]byte(target), 0) | |
| 138 | 新增: for len(encoded)%12 != 0 { | |
| 139 | 新增: encoded = append(encoded, 0) | |
| 140 | 新增: } | |
| 141 | 新增: key := []byte{0x7d, 0x89, 0x52, 0x23, 0xd2, 0xbc, 0xdd, 0xea, 0xa3, 0xb9, 0x1f} | |
| 142 | 新增: for i := range encoded { | |
| 143 | 新增: encoded[i] ^= key[i%len(key)] | |
| 144 | 新增: } | |
| 145 | 新增: expected := sha256.Sum256(encoded) | |
| 146 | 新增: clear(encoded) | |
| 147 | 新增: if !strings.HasPrefix(string(actual), hex.EncodeToString(expected[:])+" ") { | |
| 148 | 新增: t.Fatal("system automatic login did not receive the new password") | |
| 149 | 新增: } | |
| 150 | 新增: // Replay the durable old/target pair as if the first reply was lost. | |
| 151 | 新增: if err = s.applyMacGuestPassword(ctx, install.ID, previous, target); err != nil { | |
| 152 | 新增: t.Fatal("idempotent replay:", err) | |
| 153 | 新增: } | |
| 154 | 新增: cmd = s.macOSSSHCommand(ctx, "-T", "cage-macos", "--", `test "$(cat "$HOME/`+sentinel+`")" = preserved && ! id -Gn | /usr/bin/grep -qw admin`) | |
| 155 | 新增: if err = cmd.Run(); err != nil { | |
| 156 | 新增: t.Fatal("guest data or ordinary account privilege changed", err) | |
| 157 | 新增: } | |
| 158 | 新增: accountAfter, err := os.ReadFile(original.path) | |
| 159 | 新增: if err != nil || !bytes.Equal(accountBefore, accountAfter) { | |
| 160 | 新增: t.Fatal("source QA account changed") | |
| 161 | 新增: } | |
| 162 | 新增: t.Log("Shared password accepted by ordinary and setup accounts; old password rejected; automatic login and replay passed; source account and guest sentinel retained") | |
| 163 | 新增:} | |
| @@ -0,0 +1,85 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "github.com/google/uuid" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "regexp" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "al.essio.dev/pkg/shellescape" | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:func (s *Server) syncMacGuestPassword(ctx context.Context) error { | |
| 21 | 新增: if s.macosGuest == nil || s.account == nil { | |
| 22 | 新增: return nil | |
| 23 | 新增: } | |
| 24 | 新增: install, err := guestos.LoadInstallation(s.profile) | |
| 25 | 新增: if err != nil { | |
| 26 | 新增: return err | |
| 27 | 新增: } | |
| 28 | 新增: if install == nil { | |
| 29 | 新增: return nil | |
| 30 | 新增: } | |
| 31 | 新增: return s.account.syncMacPassword(ctx, install.ID, s.macosGuest.User, func(ctx context.Context, oldPassword, newPassword string) error { | |
| 32 | 新增: return s.applyMacGuestPassword(ctx, install.ID, oldPassword, newPassword) | |
| 33 | 新增: }) | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 36 | 新增:func (s *Server) applyMacGuestPassword(ctx context.Context, id uuid.UUID, oldPassword, newPassword string) error { | |
| 37 | 新增: ctx, cancel := context.WithTimeout(ctx, 45*time.Second) | |
| 38 | 新增: defer cancel() | |
| 39 | 新增: provision, err := guestos.MacOSProvisionUser(s.profile) | |
| 40 | 新增: if err != nil { | |
| 41 | 新增: return err | |
| 42 | 新增: } | |
| 43 | 新增: if provision != "cageprovision" { | |
| 44 | 新增: return errors.New("客机置备身份不匹配") | |
| 45 | 新增: } | |
| 46 | 新增: args, err := guestos.MacOSSSHArgs(s.profile, provision) | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: return err | |
| 49 | 新增: } | |
| 50 | 新增: command := func(ctx context.Context, script string) *exec.Cmd { | |
| 51 | 新增: cmd := exec.CommandContext(ctx, sshExecutable(), append(append([]string{}, args...), "-T", "cage-macos", "--", "exec /bin/sh -ec "+shellescape.Quote(script))...) | |
| 52 | 新增: cmd.Env = sshEnvironment() | |
| 53 | 新增: hideCommand(cmd) | |
| 54 | 新增: return cmd | |
| 55 | 新增: } | |
| 56 | 新增: // Use this build's helper so older managed guests can adopt the shared | |
| 57 | 新增: // credential without reinstalling their applications or personal disk. | |
| 58 | 新增: helper, err := os.ReadFile(filepath.Join(filepath.Dir(s.exe), "guest-os", "cage-finish-initial-setup")) | |
| 59 | 新增: if err != nil { | |
| 60 | 新增: return err | |
| 61 | 新增: } | |
| 62 | 新增: out, err := command(ctx, `umask 077; mktemp -d /private/var/tmp/cage-account.XXXXXXXX`).Output() | |
| 63 | 新增: stage := strings.TrimSpace(string(out)) | |
| 64 | 新增: if err != nil || !regexp.MustCompile(`^/private/var/tmp/cage-account\.[A-Za-z0-9]{8}$`).MatchString(stage) { | |
| 65 | 新增: return errors.New("无法准备客机改密组件") | |
| 66 | 新增: } | |
| 67 | 新增: admin := " < /Users/" + provision + "/password" | |
| 68 | 新增: defer func() { | |
| 69 | 新增: cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 70 | 新增: defer cancel() | |
| 71 | 新增: _ = command(cleanup, `sudo -S -p '' /bin/rm -rf `+stage+admin).Run() | |
| 72 | 新增: }() | |
| 73 | 新增: upload := command(ctx, `umask 077; cat > `+stage+`/helper`) | |
| 74 | 新增: upload.Stdin = bytes.NewReader(helper) | |
| 75 | 新增: if err = upload.Run(); err != nil { | |
| 76 | 新增: return err | |
| 77 | 新增: } | |
| 78 | 新增: script := `chown -R root:wheel ` + stage + `; chmod 700 ` + stage + ` ` + stage + `/helper; chmod 600 ` + stage + `/input; exec ` + stage + `/helper password ` + id.String() + ` ` + s.macosGuest.User + ` < ` + stage + `/input` | |
| 79 | 新增: apply := command(ctx, `umask 077; cat > `+stage+`/input; sudo -S -p '' /bin/sh -ec `+shellescape.Quote(script)+admin) | |
| 80 | 新增: apply.Stdin = strings.NewReader(oldPassword + "\n" + newPassword + "\n") | |
| 81 | 新增: if out, err := apply.CombinedOutput(); err != nil { | |
| 82 | 新增: return fmt.Errorf("guest password update: %w: %.2048s", err, out) | |
| 83 | 新增: } | |
| 84 | 新增: return nil | |
| 85 | 新增:} | |
| @@ -105,6 +105,10 @@ func (s *Server) localTrustedLogin(w http.ResponseWriter, r *http.Request) { | ||
| 105 | 105 | return |
| 106 | 106 | } |
| 107 | 107 | defer finish() |
| 108 | 新增: if in.Action == "create" { | |
| 109 | 新增: jsonReply(w, trustedLoginReply{Error: "请先注册 Cage 用户名和密码,再开始安装"}) | |
| 110 | 新增: return | |
| 111 | 新增: } | |
| 108 | 112 | base, err := os.UserConfigDir() |
| 109 | 113 | if runtime.GOOS == "windows" { |
| 110 | 114 | base = os.Getenv("LOCALAPPDATA") |
| @@ -9,6 +9,7 @@ import ( | ||
| 9 | 9 | "net/http/httptest" |
| 10 | 10 | "os" |
| 11 | 11 | "path/filepath" |
| 12 | 新增: "runtime" | |
| 12 | 13 | "strconv" |
| 13 | 14 | "testing" |
| 14 | 15 | "time" |
| @@ -240,8 +241,19 @@ func TestTrustedLocalDesktopEntryAndWorkload(t *testing.T) { | ||
| 240 | 241 | d.active = &desktopTarget{id: d.generation, mode: "local", ctx: life, session: session} |
| 241 | 242 | body, _ := json.Marshal(trustedLoginRequest{Action: "create", ConnectionID: d.generation}) |
| 242 | 243 | w := request(gateway, "POST", "/api/client/trusted-login", gateway.origin, string(body), true) |
| 243 | 删除: if w.Code != http.StatusOK { | |
| 244 | 删除: t.Fatalf("trust creation through gateway: %d %s", w.Code, w.Body.String()) | |
| 244 | 新增: if w.Code != http.StatusConflict || workload.account.view().Exists { | |
| 245 | 新增: t.Fatalf("fresh profile bypassed registration: %d %s", w.Code, w.Body.String()) | |
| 246 | 新增: } | |
| 247 | 新增: // An existing trusted workspace still resumes after upgrading. | |
| 248 | 新增: base, err := os.UserConfigDir() | |
| 249 | 新增: if runtime.GOOS == "windows" { | |
| 250 | 新增: base = os.Getenv("LOCALAPPDATA") | |
| 251 | 新增: } | |
| 252 | 新增: if err != nil { | |
| 253 | 新增: t.Fatal(err) | |
| 254 | 新增: } | |
| 255 | 新增: if err = workload.account.trustedLogin("create", "", filepath.Join(base, "Cage", "trusted-local")); err != nil { | |
| 256 | 新增: t.Fatal(err) | |
| 245 | 257 | } |
| 246 | 258 | read := gatewayRequest(gateway, "/api/account", d.generation) |
| 247 | 259 | var view accountView |
| @@ -5,10 +5,12 @@ export PATH=/usr/bin:/bin:/usr/sbin:/sbin | ||
| 5 | 5 | [[ $# == 2 && $EUID == 0 && $(uname -sm) == 'Darwin arm64' && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]] |
| 6 | 6 | user=$1 |
| 7 | 7 | installation=$2 |
| 8 | 删除:[[ $user == cage ]] | |
| 8 | 新增:[[ $user =~ ^[a-z][a-z0-9_]{0,30}$ && $user != root && $user != cageprovision && $user != cagesetup ]] | |
| 9 | 9 | [[ -f /var/db/cage-guest-os && ! -L /var/db/cage-guest-os && $(stat -f %u /var/db/cage-guest-os) == 0 && $(cat /var/db/cage-guest-os) == macos ]] |
| 10 | 10 | receipt=/var/db/cage-initial-setup/account.json |
| 11 | 11 | [[ -f $receipt && ! -L $receipt && $(stat -f %u "$receipt") == 0 && $(plutil -extract installation raw "$receipt") == "$installation" ]] |
| 12 | 新增:bound_user=$(plutil -extract user raw "$receipt" 2>/dev/null || echo cage) | |
| 13 | 新增:[[ $bound_user == "$user" ]] | |
| 12 | 14 | phase=$(plutil -extract state raw "$receipt") |
| 13 | 15 | [[ $phase == ready ]] |
| 14 | 16 | [[ $(dscl . -read /Users/$user NFSHomeDirectory) == "NFSHomeDirectory: /Users/$user" && " $(id -Gn "$user") " != *' admin '* ]] |
| @@ -42,6 +42,81 @@ static BOOL disabled(ODRecord *record) { | ||
| 42 | 42 | return !allowed && [error.domain isEqual:ODFrameworkErrorDomain] && error.code == kODErrorCredentialsAccountDisabled; |
| 43 | 43 | } |
| 44 | 44 | |
| 45 | 新增:static NSString *readPassword(void) { | |
| 46 | 新增: char buf[258] = {0}; | |
| 47 | 新增: require(fgets(buf,sizeof(buf),stdin) != NULL, "Missing virtual Mac password."); | |
| 48 | 新增: size_t len = strcspn(buf,"\r\n"); | |
| 49 | 新增: require(len >= 8 && len <= 256 && buf[len] == '\n', "Invalid virtual Mac password."); | |
| 50 | 新增: for (size_t i = 0; i < len; i++) require(buf[i] >= 32 && buf[i] <= 126, "Unsupported virtual Mac password character."); | |
| 51 | 新增: NSString *pw = [[NSString alloc] initWithBytes:buf length:len encoding:NSUTF8StringEncoding]; | |
| 52 | 新增: memset_s(buf,sizeof(buf),0,sizeof(buf)); | |
| 53 | 新增: require(pw != nil, "Invalid password encoding."); | |
| 54 | 新增: return pw; | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:static void updatePassword(ODRecord *record, NSString *old, NSString *target) { | |
| 58 | 新增: if ([record verifyPassword:target error:NULL]) return; | |
| 59 | 新增: require([record verifyPassword:old error:NULL] && [record changePassword:old toPassword:target error:NULL] && | |
| 60 | 新增: [record verifyPassword:target error:NULL], "Cannot synchronize the guest account password."); | |
| 61 | 新增:} | |
| 62 | 新增: | |
| 63 | 新增:// security -i accepts double-quoted tokens with escaped quotes/backslashes. | |
| 64 | 新增:// Its commands travel on a private pipe; no password enters process arguments. | |
| 65 | 新增:static NSString *securityToken(NSString *value) { | |
| 66 | 新增: return [NSString stringWithFormat:@"\"%@\"", [[value stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"] | |
| 67 | 新增: stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]]; | |
| 68 | 新增:} | |
| 69 | 新增: | |
| 70 | 新增:static void synchronize(ODRecord *ordinary, ODRecord *setupRecord, NSDictionary *receipt, NSString *name) { | |
| 71 | 新增: NSString *old = readPassword(), *target = readPassword(); | |
| 72 | 新增: NSString *home = [ordinary valuesForAttribute:kODAttributeTypeNFSHomeDirectory error:NULL].firstObject; | |
| 73 | 新增: require([home isEqual:[@"/Users/" stringByAppendingString:name]], "Unexpected guest home directory."); | |
| 74 | 新增: NSString *domain = @"/Library/Preferences/com.apple.loginwindow"; | |
| 75 | 新增: NSDictionary *preferences = [NSDictionary dictionaryWithContentsOfFile:[domain stringByAppendingString:@".plist"]]; | |
| 76 | 新增: require(!preferences[@"autoLoginUser"] || [preferences[@"autoLoginUser"] isEqual:name], "Automatic login belongs to another guest user."); | |
| 77 | 新增: struct stat st; | |
| 78 | 新增: require(lstat("/etc/kcpassword",&st) != 0 ? errno == ENOENT : S_ISREG(st.st_mode) && st.st_uid == 0, | |
| 79 | 新增: "Invalid system automatic login file."); | |
| 80 | 新增: // Keep the existing login keychain usable after the system account changes. | |
| 81 | 新增: // Each step accepts the target password, so retries can finish partial work. | |
| 82 | 新增: NSString *keychainPath = [home stringByAppendingString:@"/Library/Keychains/login.keychain-db"]; | |
| 83 | 新增: if (lstat(keychainPath.fileSystemRepresentation,&st) == 0) { | |
| 84 | 新增: require(S_ISREG(st.st_mode), "Invalid guest login keychain."); | |
| 85 | 新增: NSString *commands = [NSString stringWithFormat:@"set-keychain-password -o %@ -p %@ %@\nunlock-keychain -p %@ %@\n", | |
| 86 | 新增: securityToken(old),securityToken(target),securityToken(keychainPath),securityToken(target),securityToken(keychainPath)]; | |
| 87 | 新增: NSPipe *input = [NSPipe pipe]; | |
| 88 | 新增: NSTask *security = [[NSTask alloc] init]; | |
| 89 | 新增: security.executableURL = [NSURL fileURLWithPath:@"/usr/bin/security"]; | |
| 90 | 新增: security.arguments = @[@"-i"]; | |
| 91 | 新增: security.standardInput = input; | |
| 92 | 新增: security.standardOutput = security.standardError = [NSFileHandle fileHandleWithNullDevice]; | |
| 93 | 新增: require([security launchAndReturnError:NULL], "Cannot invoke the guest keychain tool."); | |
| 94 | 新增: [input.fileHandleForWriting writeData:[commands dataUsingEncoding:NSUTF8StringEncoding]]; | |
| 95 | 新增: [input.fileHandleForWriting closeFile]; | |
| 96 | 新增: [security waitUntilExit]; | |
| 97 | 新增: require(security.terminationStatus == 0, "Cannot synchronize the guest login keychain; existing data was retained."); | |
| 98 | 新增: } else require(errno == ENOENT, "Cannot inspect the guest login keychain."); | |
| 99 | 新增: updatePassword(ordinary,old,target); | |
| 100 | 新增: if ([receipt[@"state"] isEqual:@"ready"]) { | |
| 101 | 新增: require(setupRecord && !disabled(setupRecord), "The initial setup account is unavailable."); | |
| 102 | 新增: updatePassword(setupRecord,old,target); | |
| 103 | 新增: } | |
| 104 | 新增: unsigned char key[] = {0x7d,0x89,0x52,0x23,0xd2,0xbc,0xdd,0xea,0xa3,0xb9,0x1f}; | |
| 105 | 新增: NSMutableData *encoded = [[target dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; | |
| 106 | 新增: [encoded increaseLengthBy:1]; | |
| 107 | 新增: while (encoded.length % 12) [encoded increaseLengthBy:1]; | |
| 108 | 新增: unsigned char *bytes = encoded.mutableBytes; | |
| 109 | 新增: for (NSUInteger i=0; i<encoded.length; i++) bytes[i] ^= key[i % sizeof(key)]; | |
| 110 | 新增: require([encoded writeToFile:@"/etc/kcpassword" options:NSDataWritingAtomic error:NULL] && chmod("/etc/kcpassword",0600) == 0, | |
| 111 | 新增: "Cannot synchronize automatic login."); | |
| 112 | 新增: // This call contains only the non-secret account name. | |
| 113 | 新增: NSTask *task = [[NSTask alloc] init]; | |
| 114 | 新增: task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/defaults"]; | |
| 115 | 新增: task.arguments = @[@"write", domain, @"autoLoginUser", @"-string", name]; | |
| 116 | 新增: require([task launchAndReturnError:NULL], "Cannot configure automatic login."); | |
| 117 | 新增: [task waitUntilExit]; require(task.terminationStatus == 0, "Cannot persist automatic login user."); | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 45 | 120 | static void retire(ODNode *node, ODRecord *admin, ODRecord *record) { |
| 46 | 121 | if (member(admin, record)) require([admin removeMemberRecord:record error:NULL], "Cannot revoke setup administrator privileges."); |
| 47 | 122 | require(!member(admin, record), "The setup user still has administrator privileges."); |
| @@ -66,8 +141,9 @@ static void retire(ODNode *node, ODRecord *admin, ODRecord *record) { | ||
| 66 | 141 | |
| 67 | 142 | int main(int argc, const char **argv) { |
| 68 | 143 | @autoreleasepool { |
| 69 | 删除: BOOL prepare = argc == 3 && strcmp(argv[1], "prepare") == 0; | |
| 70 | 删除: require(prepare || argc == 1, "Invalid first setup operation."); | |
| 144 | 新增: BOOL prepare = (argc == 3 || argc == 4) && strcmp(argv[1], "prepare") == 0; | |
| 145 | 新增: BOOL password = argc == 4 && strcmp(argv[1], "password") == 0; | |
| 146 | 新增: require(prepare || password || argc == 1, "Invalid first setup operation."); | |
| 71 | 147 | char model[128] = {0}; |
| 72 | 148 | size_t size = sizeof(model); |
| 73 | 149 | struct stat st; |
| @@ -92,18 +168,15 @@ int main(int argc, const char **argv) { | ||
| 92 | 168 | } else require(errno == ENOENT && prepare, "Missing guest setup receipt."); |
| 93 | 169 | ODNode *node = [ODNode nodeWithSession:[ODSession defaultSession] name:@"/Local/Default" error:NULL]; |
| 94 | 170 | ODRecord *admin = [node recordWithRecordType:kODRecordTypeGroups name:@"admin" attributes:nil error:NULL]; |
| 95 | 删除: NSString *ordinaryName = @"cage"; | |
| 96 | 删除: ODRecord *ordinary = users(node, ordinaryName).firstObject; | |
| 97 | 删除: require(node && admin && ordinary && !member(admin, ordinary), "The regular Cage user must not be a guest administrator."); | |
| 98 | 171 | ODRecord *record = users(node, setup).firstObject; |
| 99 | 删除: NSString *install = prepare ? @(argv[2]) : nil; | |
| 100 | 删除: if (prepare) require([[NSUUID alloc] initWithUUIDString:install] != nil, "Invalid fresh guest installation ID."); | |
| 172 | 新增: NSString *install = prepare || password ? @(argv[2]) : nil; | |
| 173 | 新增: if (install) require([[NSUUID alloc] initWithUUIDString:install] != nil, "Invalid fresh guest installation ID."); | |
| 101 | 174 | NSMutableDictionary *receipt; |
| 102 | 175 | if (data) { |
| 103 | 176 | receipt = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL]; |
| 104 | 177 | require([receipt isKindOfClass:NSMutableDictionary.class] && |
| 105 | 178 | [[NSUUID alloc] initWithUUIDString:receipt[@"guid"]] && [receipt[@"uid"] intValue] >= 502 && |
| 106 | 删除: [[NSUUID alloc] initWithUUIDString:receipt[@"installation"]] && (!prepare || [receipt[@"installation"] isEqual:install]), | |
| 179 | 新增: [[NSUUID alloc] initWithUUIDString:receipt[@"installation"]] && (!install || [receipt[@"installation"] isEqual:install]), | |
| 107 | 180 | "The setup account belongs to a different installation."); |
| 108 | 181 | } else { |
| 109 | 182 | require(!record && !getpwnam("cagesetup"), "A user already has the setup name; no account was modified."); |
| @@ -111,8 +184,18 @@ int main(int argc, const char **argv) { | ||
| 111 | 184 | while (uid < 1000 && getpwuid(uid)) uid++; |
| 112 | 185 | require(uid < 1000, "No free local setup UID."); |
| 113 | 186 | receipt = [@{@"installation":install, @"guid":NSUUID.UUID.UUIDString, @"uid":@(uid), @"state":@"creating"} mutableCopy]; |
| 114 | 删除: save(receipt, file); | |
| 115 | 187 | } |
| 188 | 新增: NSString *ordinaryName = argc == 4 ? @(argv[3]) : receipt[@"user"] ?: @"cage"; | |
| 189 | 新增: NSRegularExpression *userPattern = [NSRegularExpression regularExpressionWithPattern:@"^[a-z][a-z0-9_]{0,30}$" options:0 error:NULL]; | |
| 190 | 新增: require([userPattern numberOfMatchesInString:ordinaryName options:0 range:NSMakeRange(0,ordinaryName.length)] == 1 && | |
| 191 | 新增: ![@[@"root",@"cagesetup",@"cageprovision"] containsObject:ordinaryName], "Invalid ordinary guest username."); | |
| 192 | 新增: require(!data || [ordinaryName isEqual:receipt[@"user"] ?: @"cage"], "The receipt belongs to another ordinary account."); | |
| 193 | 新增: ODRecord *ordinary = users(node, ordinaryName).firstObject; | |
| 194 | 新增: require(node && admin && ordinary && !member(admin, ordinary), "The regular Cage user must not be a guest administrator."); | |
| 195 | 新增: NSString *ordinaryGUID = [ordinary valuesForAttribute:kODAttributeTypeGUID error:NULL].firstObject; | |
| 196 | 新增: require(ordinaryGUID && (!receipt[@"ordinary_guid"] || [receipt[@"ordinary_guid"] isEqual:ordinaryGUID]), "The ordinary guest account has changed."); | |
| 197 | 新增: receipt[@"user"] = ordinaryName; receipt[@"ordinary_guid"] = ordinaryGUID; | |
| 198 | 新增: if (prepare) save(receipt,file); | |
| 116 | 199 | NSString *uid = [receipt[@"uid"] stringValue]; |
| 117 | 200 | if (record) { |
| 118 | 201 | NSString *guid = [record valuesForAttribute:kODAttributeTypeGUID error:NULL].firstObject; |
| @@ -122,15 +205,14 @@ int main(int argc, const char **argv) { | ||
| 122 | 205 | } |
| 123 | 206 | NSString *phase = receipt[@"state"]; |
| 124 | 207 | require([@[@"creating",@"ready",@"retiring",@"retired"] containsObject:phase], "Unknown guest setup state."); |
| 208 | 新增: if (password) { | |
| 209 | 新增: require(![phase isEqual:@"creating"] && ![phase isEqual:@"retiring"], "Finish guest account preparation before changing its password."); | |
| 210 | 新增: synchronize(ordinary,record,receipt,ordinaryName); | |
| 211 | 新增: save(receipt,file); close(lock); return 0; | |
| 212 | 新增: } | |
| 125 | 213 | if (prepare) { |
| 126 | 214 | require([phase isEqual:@"creating"] || [phase isEqual:@"ready"], "Initial setup has already closed."); |
| 127 | 删除: char buf[258]; | |
| 128 | 删除: require(fgets(buf,sizeof(buf),stdin) != NULL, "Missing virtual Mac login password."); | |
| 129 | 删除: size_t len = strcspn(buf,"\r\n"); | |
| 130 | 删除: require(len >= 8 && len <= 256, "Invalid virtual Mac login password."); | |
| 131 | 删除: NSString *pw = [[NSString alloc] initWithBytes:buf length:len encoding:NSUTF8StringEncoding]; | |
| 132 | 删除: memset_s(buf,sizeof(buf),0,sizeof(buf)); | |
| 133 | 删除: require(pw != nil, "Invalid password encoding."); | |
| 215 | 新增: NSString *pw = readPassword(); | |
| 134 | 216 | if (!record) { |
| 135 | 217 | require([phase isEqual:@"creating"] && !getpwuid([receipt[@"uid"] intValue]), "Setup account disappeared or its UID is in use."); |
| 136 | 218 | record = [node createRecordWithRecordType:kODRecordTypeUsers name:setup attributes:@{ |
| @@ -15,8 +15,9 @@ IFS= read -r login_password | ||
| 15 | 15 | cd / |
| 16 | 16 | provision=$3 |
| 17 | 17 | [[ $provision == cageprovision ]] |
| 18 | 删除:ordinary=cage | |
| 19 | 删除:full_name=cage | |
| 18 | 新增:ordinary=${4:-cage} | |
| 19 | 新增:[[ $ordinary =~ ^[a-z][a-z0-9_]{0,30}$ && $ordinary != root && $ordinary != cageprovision && $ordinary != cagesetup ]] | |
| 20 | 新增:full_name=$ordinary | |
| 20 | 21 | /usr/bin/dscl . -create "/Users/$provision" IsHidden 1 |
| 21 | 22 | claim=/var/db/cage-install-$ordinary |
| 22 | 23 | if [[ ! -e $claim ]]; then |
| @@ -37,7 +38,7 @@ if ! printf '%s\n' "$login_password" | dscl /Local/Default -authonly $ordinary > | ||
| 37 | 38 | fi |
| 38 | 39 | install -d -m 755 /usr/local/libexec |
| 39 | 40 | install -m 755 "$kit/cage-finish-initial-setup" /usr/local/libexec/cage-finish-initial-setup |
| 40 | 删除:printf '%s\n' "$login_password" | /usr/local/libexec/cage-finish-initial-setup prepare "$2" | |
| 41 | 新增:printf '%s\n' "$login_password" | /usr/local/libexec/cage-finish-initial-setup prepare "$2" "$ordinary" | |
| 41 | 42 | install -m 755 "$kit/configure-macos-session.sh" /usr/local/libexec/cage-configure-session |
| 42 | 43 | printf '%s\n' "$login_password" | /usr/local/libexec/cage-configure-session "$ordinary" "$2" |
| 43 | 44 | unset login_password |
| @@ -50,11 +50,11 @@ const unlock = async (enabled) => { | ||
| 50 | 50 | }; |
| 51 | 51 | try { |
| 52 | 52 | await restart(); |
| 53 | 删除: await page.getByRole("button", { name: "使用用户名和密码", exact: true }).click(); | |
| 53 | 新增: await page.getByRole("heading", { name: "注册 Cage 账户", exact: true }).waitFor(); | |
| 54 | 54 | await remember().waitFor(); |
| 55 | 55 | assert.equal(await remember().isChecked(), true); |
| 56 | 56 | await remember().uncheck(); |
| 57 | 删除: await page.getByLabel("用户名", { exact: true }).fill("Remember Live QA"); | |
| 57 | 新增: await page.getByLabel("用户名", { exact: true }).fill("remember_live_qa"); | |
| 58 | 58 | await page.getByLabel("设置密码", { exact: true }).fill(password); |
| 59 | 59 | await page.getByLabel("确认密码", { exact: true }).fill(password); |
| 60 | 60 | const created = page.waitForResponse(r => r.url().endsWith("/api/client/trusted-login")); |
| @@ -117,7 +117,7 @@ for (const platform of ["windows", "darwin", "linux"]) { | ||
| 117 | 117 | |
| 118 | 118 | Object.assign(state.account, { exists: false, unlocked: false, username: "", devices: {}, require_authentication: false }); |
| 119 | 119 | await page.reload(); |
| 120 | 删除: await page.getByRole("button", { name: "使用用户名和密码", exact: true }).click(); | |
| 120 | 新增: await page.getByRole("heading", { name: "注册 Cage 账户", exact: true }).waitFor(); | |
| 121 | 121 | await remember().waitFor(); |
| 122 | 122 | assert.equal(await remember().isChecked(), true); |
| 123 | 123 | await page.getByLabel("用户名", { exact: true }).fill("测试工作区"); |
| @@ -36,7 +36,7 @@ try { | ||
| 36 | 36 | Object.assign(state.account, {exists:false,unlocked:false,username:''}); |
| 37 | 37 | const previousAcks = launchAcks; |
| 38 | 38 | await page.reload(); |
| 39 | 删除: await page.getByRole('heading',{name:'让 Cage 成为你的工作空间'}).waitFor(); | |
| 39 | 新增: await page.getByRole('heading',{name:'注册 Cage 账户'}).waitFor(); | |
| 40 | 40 | await page.waitForFunction(async (previous) => await window.fixtureLaunchAcks() > previous, previousAcks); |
| 41 | 41 | await page.screenshot({path:output+'create.png'}); |
| 42 | 42 | await page.getByLabel('用户名',{exact:true}).fill('林间工作室'); |
| @@ -24,8 +24,8 @@ try { | ||
| 24 | 24 | browser = await chromium.launch({ headless: true }); |
| 25 | 25 | const page = await browser.newPage({ acceptDownloads: true, viewport: { width: 1280, height: 900 } }); |
| 26 | 26 | await page.goto(entry.url); |
| 27 | 删除: await page.getByRole("button", { name: "使用用户名和密码", exact: true }).click(); | |
| 28 | 删除: await page.getByLabel("用户名", { exact: true }).fill("诊断验证账户"); | |
| 27 | 新增: await page.getByRole("heading", { name: "注册 Cage 账户", exact: true }).waitFor(); | |
| 28 | 新增: await page.getByLabel("用户名", { exact: true }).fill("diagnostics_qa"); | |
| 29 | 29 | await page.getByLabel("设置密码", { exact: true }).fill("Test-only-password-8712"); |
| 30 | 30 | await page.getByLabel("确认密码", { exact: true }).fill("Test-only-password-8712"); |
| 31 | 31 | await page.getByRole("button", { name: "创建本地账户", exact: true }).click(); |
| @@ -0,0 +1,82 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import fs from "node:fs/promises"; | |
| 3 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 4 | 新增: | |
| 5 | 新增:const evidence = process.env.CAGE_SHARED_ACCOUNT_EVIDENCE; | |
| 6 | 新增:if (evidence) await fs.mkdir(evidence, { recursive:true }); | |
| 7 | 新增:for (const platform of ["darwin", "windows", "linux"]) { | |
| 8 | 新增: let creates = 0, installs = 0; | |
| 9 | 新增: const fixture = await createWorkbench({ | |
| 10 | 新增: waitForReady:false, | |
| 11 | 新增: initialization:{required:true,tracked:true,started:false}, | |
| 12 | 新增: clientContext:{mode:"local",desktop_gateway:true,connection_id:"local",client_platform:platform,server_platform:platform,connection:{state:"connected"}}, | |
| 13 | 新增: async beforeNavigate(page,state) { | |
| 14 | 新增: Object.assign(state.account,{exists:false,unlocked:false,username:"",macos_account_host:platform === "darwin"}); | |
| 15 | 新增: await page.route("**/api/environment/storage",route => route.fulfill({json:{directory:"/preview/shared-account-state",has_environment:false}})); | |
| 16 | 新增: await page.route("**/api/environment/guest-systems",route => route.fulfill({json:{fresh:true,available:true,system:platform === "darwin" ? "macos" : platform === "windows" ? "windows-11" : "ubuntu-22.04",linux_systems:["debian","ubuntu-22.04"]}})); | |
| 17 | 新增: await page.route("**/api/account/create",route => { | |
| 18 | 新增: const input = route.request().postDataJSON(); creates++; | |
| 19 | 新增: assert.equal(input.username,"shared_qa"); | |
| 20 | 新增: assert.equal(input.password,"Shared test-'\"\\$! 2026"); | |
| 21 | 新增: assert.equal(input.confirm_password,input.password); | |
| 22 | 新增: Object.assign(state.account,{exists:true,unlocked:true,username:input.username,macos_credentials_ready:platform === "darwin"}); | |
| 23 | 新增: return route.fulfill({json:state.account}); | |
| 24 | 新增: }); | |
| 25 | 新增: await page.route("**/api/client/trusted-login",route => { | |
| 26 | 新增: assert.ok(["enable","disable"].includes(route.request().postDataJSON().action),"registration was bypassed by a trusted creation"); | |
| 27 | 新增: return route.fulfill({json:{ok:true}}); | |
| 28 | 新增: }); | |
| 29 | 新增: await page.route("**/api/start",route => { installs++; return route.fulfill({json:{}}); }); | |
| 30 | 新增: }, | |
| 31 | 新增: }); | |
| 32 | 新增: const {page,state,browser,errors} = fixture; | |
| 33 | 新增: try { | |
| 34 | 新增: page.setDefaultTimeout(10000); | |
| 35 | 新增: await page.getByRole("heading",{name:"注册 Cage 账户",exact:true}).waitFor(); | |
| 36 | 新增: assert.equal(await page.getByRole("combobox",{name:"客户机系统"}).count(),0); | |
| 37 | 新增: assert.equal(await page.getByRole("button",{name:"信任此电脑并进入",exact:true}).count(),0); | |
| 38 | 新增: await page.getByLabel("用户名",{exact:true}).fill("shared_qa"); | |
| 39 | 新增: await page.getByLabel("设置密码",{exact:true}).fill("Shared test-'\"\\$! 2026"); | |
| 40 | 新增: await page.getByLabel("确认密码",{exact:true}).fill("different-password"); | |
| 41 | 新增: await page.getByRole("button",{name:"创建本地账户",exact:true}).click(); | |
| 42 | 新增: await page.getByRole("alert").filter({hasText:"两次密码不一致"}).waitFor(); | |
| 43 | 新增: assert.equal(creates,0); assert.equal(installs,0); | |
| 44 | 新增: await page.getByLabel("确认密码",{exact:true}).fill("Shared test-'\"\\$! 2026"); | |
| 45 | 新增: if (evidence) await page.screenshot({path:`${evidence}/${platform}-register.png`}); | |
| 46 | 新增: await page.getByRole("button",{name:"创建本地账户",exact:true}).click(); | |
| 47 | 新增: await page.getByRole("heading",{name:"为 Cage 准备独立环境",exact:true}).waitFor(); | |
| 48 | 新增: assert.equal(creates,1); assert.equal(installs,0); | |
| 49 | 新增: await page.reload(); | |
| 50 | 新增: await page.getByRole("heading",{name:"为 Cage 准备独立环境",exact:true}).waitFor(); | |
| 51 | 新增: assert.equal(state.account.username,"shared_qa"); assert.equal(creates,1); | |
| 52 | 新增: assert.deepEqual(errors,[]); | |
| 53 | 新增: console.log(`${platform}: registration precedes initialization; confirmation and reload passed`); | |
| 54 | 新增: } catch (error) { | |
| 55 | 新增: console.error(platform,errors,state.requests.filter(item => item.path === "/diagnostics/events"),await page.locator("body").innerText()); throw error; | |
| 56 | 新增: } finally { await browser.close(); } | |
| 57 | 新增:} | |
| 58 | 新增: | |
| 59 | 新增:const legacy = await createWorkbench({ | |
| 60 | 新增: waitForReady:false, | |
| 61 | 新增: async beforeNavigate(page,state) { | |
| 62 | 新增: Object.assign(state.account,{exists:true,unlocked:true,trusted_local:true,username:"本机用户",guest_system:"macos",initial_mac_setup:true,macos_guest_user:"cage",macos_account_host:true}); | |
| 63 | 新增: await page.route("**/api/account/prepare-macos",route => { | |
| 64 | 新增: const input = route.request().postDataJSON(); | |
| 65 | 新增: assert.equal(input.username,"cage"); assert.equal(input.password,input.confirm_password); | |
| 66 | 新增: Object.assign(state.account,{username:"cage",trusted_local:false,macos_credentials_ready:true,initial_mac_setup:false}); | |
| 67 | 新增: return route.fulfill({json:state.account}); | |
| 68 | 新增: }); | |
| 69 | 新增: }, | |
| 70 | 新增:}); | |
| 71 | 新增:try { | |
| 72 | 新增: const {page,errors} = legacy; page.setDefaultTimeout(10000); | |
| 73 | 新增: await page.getByRole("heading",{name:"设置 Cage 与 macOS 共用账密",exact:true}).waitFor(); | |
| 74 | 新增: assert.equal(await page.getByLabel("用户名",{exact:true}).inputValue(),"cage"); | |
| 75 | 新增: assert.equal(await page.getByLabel("用户名",{exact:true}).getAttribute("readonly"),""); | |
| 76 | 新增: await page.getByLabel("设置密码",{exact:true}).fill("Shared-test-2026"); | |
| 77 | 新增: await page.getByLabel("确认密码",{exact:true}).fill("Shared-test-2026"); | |
| 78 | 新增: await page.getByRole("button",{name:"保存账密并继续",exact:true}).click(); | |
| 79 | 新增: await page.getByRole("button",{name:/^账户菜单,cage/}).waitFor(); | |
| 80 | 新增: assert.deepEqual(errors,[]); | |
| 81 | 新增: console.log("legacy: shared credentials preserve the existing guest username and resume the workspace"); | |
| 82 | 新增:} finally { await legacy.browser.close(); } | |
| @@ -29,14 +29,14 @@ try { | ||
| 29 | 29 | const errors = []; |
| 30 | 30 | page.on("pageerror", (error) => errors.push(error.message)); |
| 31 | 31 | await page.goto(entry.url); |
| 32 | 删除: await page.getByRole("button", { name: "使用用户名和密码", exact: true }).click(); | |
| 32 | 新增: await page.getByRole("heading", { name: "注册 Cage 账户", exact: true }).waitFor(); | |
| 33 | 33 | await page.getByLabel("用户名",{exact:true}).waitFor(); |
| 34 | 34 | const initial = await page.evaluate(async () => (await fetch("/api/client/local-status")).json()); |
| 35 | 35 | assert.ok(initial.known && initial.service_running && !initial.running, "opening the local home must not boot the VM"); |
| 36 | 36 | assert.equal(await page.getByRole("heading",{name:"选择工作环境"}).count(),0); |
| 37 | 37 | if (evidence) await page.screenshot({ path:path.join(evidence,"desktop-first-open.png") }); |
| 38 | 38 | const password = randomBytes(24).toString("base64url"); |
| 39 | 删除: await page.getByLabel("用户名",{exact:true}).fill("Packaged Smoke"); | |
| 39 | 新增: await page.getByLabel("用户名",{exact:true}).fill("packaged_smoke"); | |
| 40 | 40 | await page.getByLabel("设置密码",{exact:true}).fill(password); |
| 41 | 41 | await page.getByLabel("确认密码",{exact:true}).fill(password); |
| 42 | 42 | const statusResponse = page.waitForResponse((response) => response.url().endsWith("/api/status") && response.ok()); |
| @@ -16,6 +16,7 @@ export async function createWorkbench({ | ||
| 16 | 16 | beforeNavigate, |
| 17 | 17 | launchOptions = {}, |
| 18 | 18 | startupFailure = false, |
| 19 | 新增: waitForReady = true, | |
| 19 | 20 | initialization = { required: false }, |
| 20 | 21 | clientContext = { mode: "local", connection_id: "local", client_platform: "darwin", server_platform: "darwin", connection: { state: "disconnected" } }, |
| 21 | 22 | } = {}) { |
| @@ -379,7 +380,7 @@ export async function createWorkbench({ | ||
| 379 | 380 | }); |
| 380 | 381 | if (beforeNavigate) await beforeNavigate(page, state); |
| 381 | 382 | await page.goto(url || process.env.CAGE_UI_URL || "http://127.0.0.1:5198"); |
| 382 | 删除: if (!startupFailure && !state.status.vm_running && clientContext.mode !== "none") await page.getByRole("heading", { name: state.initialization.required ? state.initialization.started ? "安装并检查客机环境" : "为 Cage 准备独立环境" : "先启动 Cage 环境" }).waitFor(); | |
| 383 | 新增: if (waitForReady && !startupFailure && !state.status.vm_running && clientContext.mode !== "none") await page.getByRole("heading", { name: state.initialization.required ? state.initialization.started ? "安装并检查客机环境" : "为 Cage 准备独立环境" : "先启动 Cage 环境" }).waitFor(); | |
| 383 | 384 | return { browser, context, page, state, errors }; |
| 384 | 385 | } |
| 385 | 386 | |
| @@ -140,6 +140,37 @@ export function AccountAvatar({ account, large = false }) { | ||
| 140 | 140 | ); |
| 141 | 141 | } |
| 142 | 142 | |
| 143 | 新增:export function MacOSAccountGate({ children }) { | |
| 144 | 新增: const { account, act } = useAccount(); | |
| 145 | 新增: const [name, setName] = useState(account?.macos_guest_user || account?.username || ""); | |
| 146 | 新增: const [password, setPassword] = useState(""); | |
| 147 | 新增: const [confirmation, setConfirmation] = useState(""); | |
| 148 | 新增: const [busy, setBusy] = useState(false); | |
| 149 | 新增: const [error, setError] = useState(""); | |
| 150 | 新增: if (!account?.macos_account_host || account.macos_credentials_ready) return children; | |
| 151 | 新增: async function submit(event) { | |
| 152 | 新增: event.preventDefault(); | |
| 153 | 新增: if (busy) return; | |
| 154 | 新增: if (password !== confirmation) { setError("两次密码不一致"); return; } | |
| 155 | 新增: setBusy(true); setError(""); | |
| 156 | 新增: try { await act("prepare-macos", { username:name, password, confirm_password:confirmation }); setPassword(""); setConfirmation(""); } | |
| 157 | 新增: catch (e) { setError(e.message); } | |
| 158 | 新增: finally { setBusy(false); } | |
| 159 | 新增: } | |
| 160 | 新增: return <main className="account-gate"><div className="account-brand"><img src={logo} alt="" />Cage</div><section className="account-entry"> | |
| 161 | 新增: <h1>设置 Cage 与 macOS 共用账密</h1> | |
| 162 | 新增: <p className="account-entry-intro">{account.trusted_local ? "先设置 Cage 用户名和密码,再继续客机安装。已有账户、文件和登录状态会保留。" : "输入当前 Cage 密码,确认用于 macOS 客机。已有客机保留用户名和用户目录。"}</p> | |
| 163 | 新增: <form onSubmit={submit}><fieldset disabled={busy}> | |
| 164 | 新增: <label className="account-field">用户名<input required value={name} onChange={event => setName(event.target.value)} maxLength={31} pattern="[a-z][a-z0-9_]{0,30}" readOnly={Boolean(account.macos_guest_user)} autoComplete="username" /></label> | |
| 165 | 新增: <p className="field-help">小写字母开头,1–31 个小写字母、数字或下划线。密码使用 8–256 个英文键盘可输入的字符。</p> | |
| 166 | 新增: <PasswordField label={account.trusted_local ? "设置密码" : "当前 Cage 密码"} value={password} onChange={setPassword} autoComplete={account.trusted_local ? "new-password" : "current-password"} /> | |
| 167 | 新增: <PasswordField label="确认密码" value={confirmation} onChange={setConfirmation} autoComplete={account.trusted_local ? "new-password" : "current-password"} /> | |
| 168 | 新增: {error && <p role="alert" className="account-error">{error}</p>} | |
| 169 | 新增: <button className="primary account-submit" disabled={busy}>{busy ? "正在保存…" : "保存账密并继续"}</button> | |
| 170 | 新增: </fieldset></form> | |
| 171 | 新增: </section></main>; | |
| 172 | 新增:} | |
| 173 | 新增: | |
| 143 | 174 | function PasswordField({ |
| 144 | 175 | label, |
| 145 | 176 | value, |
| @@ -184,7 +215,6 @@ export function AccountGate({ children }) { | ||
| 184 | 215 | const [error, setError] = useState(""); |
| 185 | 216 | const automaticAttempt = useRef(""); |
| 186 | 217 | const gateAcknowledged = useRef(false); |
| 187 | 删除: const [passwordSetup, setPasswordSetup] = useState(false); | |
| 188 | 218 | const trustedAttempt = useRef(false); |
| 189 | 219 | const enterTrusted = async (action) => { |
| 190 | 220 | setBusy(true); setError(""); |
| @@ -195,10 +225,9 @@ export function AccountGate({ children }) { | ||
| 195 | 225 | useEffect(() => { |
| 196 | 226 | if (account?.unlocked) { trustedAttempt.current = false; setRememberLogin(null); return; } |
| 197 | 227 | if (!account || !localDesktop() || trustedAttempt.current || account.require_authentication) return; |
| 198 | 删除: const firstMacGuest = account.guest_system === "macos" && !account.exists; | |
| 199 | 删除: if (!firstMacGuest && !(account.trusted_local || account.trusted_login)) return; | |
| 228 | 新增: if (!(account.trusted_local || account.trusted_login)) return; | |
| 200 | 229 | trustedAttempt.current = true; |
| 201 | 删除: void enterTrusted(firstMacGuest ? "create" : "resume"); | |
| 230 | 新增: void enterTrusted("resume"); | |
| 202 | 231 | }, [account?.unlocked, account?.exists, account?.guest_system, account?.trusted_local, account?.trusted_login, account?.require_authentication]); |
| 203 | 232 | useEffect(() => { |
| 204 | 233 | if (!account || account.unlocked || connectionError || gateAcknowledged.current || !nativeAvailable()) return; |
| @@ -279,14 +308,14 @@ export function AccountGate({ children }) { | ||
| 279 | 308 | )} |
| 280 | 309 | <h1> |
| 281 | 310 | {creating |
| 282 | 删除: ? "让 Cage 成为你的工作空间" | |
| 311 | 新增: ? "注册 Cage 账户" | |
| 283 | 312 | : account |
| 284 | 313 | ? `欢迎回来,${account.username}` |
| 285 | 314 | : "正在连接 Cage"} |
| 286 | 315 | </h1> |
| 287 | 316 | <p className="account-entry-intro"> |
| 288 | 317 | {creating |
| 289 | 删除: ? isRemoteClient() ? "在云端创建账户,保护这台主机上的工作与登录状态。" : localDesktop() && !passwordSetup ? "选择这台电脑的登录方式。" : "创建一个本地账户,收好你的工作与登录状态。" | |
| 318 | 新增: ? isRemoteClient() ? "在云端创建账户,保护这台主机上的工作与登录状态。" : "先注册用户名和密码,再选择客机系统并安装环境。macOS 客机会使用同一套账密。" | |
| 290 | 319 | : account |
| 291 | 320 | ? account.trusted_local ? "本机工作区" : "输入密码,继续你的工作。" |
| 292 | 321 | : isRemoteClient() ? "正在读取云端账户…" : "正在读取本机账户…"} |
| @@ -297,38 +326,29 @@ export function AccountGate({ children }) { | ||
| 297 | 326 | 后台环境仍在运行,任务没有停止 |
| 298 | 327 | </div> |
| 299 | 328 | )} |
| 300 | 删除: {localDesktop() && creating && ( | |
| 301 | 删除: <div className="account-trust-choice"> | |
| 302 | 删除: {!passwordSetup && <> | |
| 303 | 删除: <p>信任此电脑后,下次使用当前系统用户打开 Cage 会直接进入。</p> | |
| 304 | 删除: <button className="primary account-submit" disabled={busy} onClick={() => enterTrusted("create")}>信任此电脑并进入</button> | |
| 305 | 删除: </>} | |
| 306 | 删除: <button className="text-button" disabled={busy} onClick={() => setPasswordSetup(!passwordSetup)}> | |
| 307 | 删除: {passwordSetup ? "返回本机免账号登录" : "使用用户名和密码"} | |
| 308 | 删除: </button> | |
| 309 | 删除: </div> | |
| 310 | 删除: )} | |
| 311 | 329 | {account?.trusted_local && <div className="account-trust-choice"> |
| 312 | 330 | <p>{localDesktop() ? "使用当前系统用户的本机信任凭据进入工作区。" : "请回到受信任的桌面设置账户密码,再从此处登录。"}</p> |
| 313 | 331 | {localDesktop() && <button className="quiet-button" disabled={busy} onClick={() => enterTrusted("resume")}>{busy ? "正在进入…" : "重新进入本机工作区"}</button>} |
| 314 | 332 | </div>} |
| 315 | 删除: {(account?.trusted_local || (creating && localDesktop() && !passwordSetup)) && error && <p className="account-error" role="alert">{error}</p>} | |
| 316 | 删除: {account && !account.trusted_local && (!creating || !localDesktop() || passwordSetup) && ( | |
| 333 | 新增: {account?.trusted_local && error && <p className="account-error" role="alert">{error}</p>} | |
| 334 | 新增: {account && !account.trusted_local && ( | |
| 317 | 335 | <form onSubmit={submit}> |
| 318 | 336 | <fieldset disabled={busy}> |
| 319 | 337 | {creating && ( |
| 320 | 删除: <label className="account-field"> | |
| 338 | 新增: <><label className="account-field"> | |
| 321 | 339 | 用户名 |
| 322 | 340 | <input |
| 323 | 341 | autoFocus |
| 324 | 342 | autoComplete="username" |
| 325 | 删除: maxLength={40} | |
| 343 | 新增: maxLength={account.macos_account_host ? 31 : 40} | |
| 344 | 新增: pattern={account.macos_account_host ? "[a-z][a-z0-9_]{0,30}" : undefined} | |
| 326 | 345 | required |
| 327 | 346 | value={username} |
| 328 | 347 | onChange={(e) => setUsername(e.target.value)} |
| 329 | 删除: placeholder="你希望怎样被称呼" | |
| 348 | 新增: placeholder={account.macos_account_host ? "例如:shihao" : "你希望怎样被称呼"} | |
| 330 | 349 | /> |
| 331 | 350 | </label> |
| 351 | 新增: {account.macos_account_host && <p className="field-help">与 macOS 客机共用:小写字母开头,1–31 个小写字母、数字或下划线。</p>}</> | |
| 332 | 352 | )} |
| 333 | 353 | <PasswordField |
| 334 | 354 | label={creating ? "设置密码" : "账户密码"} |
| @@ -344,6 +364,7 @@ export function AccountGate({ children }) { | ||
| 344 | 364 | autoComplete="new-password" |
| 345 | 365 | /> |
| 346 | 366 | )} |
| 367 | 新增: {creating && account.macos_account_host && <p className="field-help">密码使用 8–256 个英文键盘可输入的字母、数字、空格或符号。安装中断后继续使用这套账密。</p>} | |
| 347 | 368 | {(error || connectionError) && ( |
| 348 | 369 | <p className="account-error" role="alert"> |
| 349 | 370 | {error || connectionError} |
| @@ -396,7 +417,7 @@ export function AccountGate({ children }) { | ||
| 396 | 417 | <LockKeyhole size={14} /> |
| 397 | 418 | {isRemoteClient() ? "账户资料保存在当前云端主机" : "账户资料仅保存在这台设备上"} |
| 398 | 419 | </p> |
| 399 | 删除: {(!localDesktop() || passwordSetup || account?.exists) && !account?.trusted_local && <p className="account-recovery-note"> | |
| 420 | 新增: {!account?.trusted_local && <p className="account-recovery-note"> | |
| 400 | 421 | {creating |
| 401 | 422 | ? "密码至少 8 个字符,用于保护应用登录凭据。请妥善保存,当前不支持在线找回。" |
| 402 | 423 | : isRemoteClient() ? "请输入云端 Cage 账户密码;当前不支持在线找回。" : "请输入本地账户密码;当前不支持在线找回。"} |
| @@ -587,7 +608,7 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) { | ||
| 587 | 608 | setOldPassword(""); |
| 588 | 609 | setPassword(""); |
| 589 | 610 | setConfirmation(""); |
| 590 | 删除: setMessage("密码已修改,应用登录状态保持不变"); | |
| 611 | 新增: setMessage(value.macos_password_pending ? "Cage 密码已修改。客机密码待同步,下次启动时自动重试;同步完成前客机可能仍需原密码。" : "密码已修改,应用登录状态保持不变"); | |
| 591 | 612 | } else { |
| 592 | 613 | setName(value.username); |
| 593 | 614 | setAvatar(value.avatar || ""); |
| @@ -614,6 +635,7 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) { | ||
| 614 | 635 | )} |
| 615 | 636 | </> |
| 616 | 637 | ); |
| 638 | 新增: if (account.macos_account_host && account.guest_system === "macos" && !account.macos_credentials_ready) return <MacOSAccountGate />; | |
| 617 | 639 | return ( |
| 618 | 640 | <div className="account-settings"> |
| 619 | 641 | <div className="section-title"> |
| @@ -663,8 +685,10 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) { | ||
| 663 | 685 | autoComplete="username" |
| 664 | 686 | onChange={(e) => setName(e.target.value)} |
| 665 | 687 | required |
| 688 | 新增: readOnly={account.macos_username_bound} | |
| 666 | 689 | /> |
| 667 | 690 | </label> |
| 691 | 新增: {account.macos_username_bound && <p className="field-help">用户名已用于 macOS 客机,保留该名称以继续使用原账户和文件。</p>} | |
| 668 | 692 | <button |
| 669 | 693 | className="primary" |
| 670 | 694 | disabled={!changed || !name.trim() || busy} |
| @@ -680,7 +704,7 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) { | ||
| 680 | 704 | <fieldset disabled={busy || environmentBusy}> |
| 681 | 705 | <h4>账户密码</h4> |
| 682 | 706 | <p className="field-help"> |
| 683 | 删除: 修改密码不会清除 Claude 的登录状态。{isRemoteClient() ? "密码用于解锁当前云端 Cage,没有在线找回。" : "密码仅用于本机解锁,没有在线找回。"} | |
| 707 | 新增: 修改密码不会清除 Claude 的登录状态。{account.macos_credentials_ready ? "Cage 与 macOS 客机共用密码;客机关闭时会在下次启动后同步。" : isRemoteClient() ? "密码用于解锁当前云端 Cage,没有在线找回。" : "密码用于本机解锁,没有在线找回。"} | |
| 684 | 708 | </p> |
| 685 | 709 | {!account.trusted_local && <PasswordField |
| 686 | 710 | label="当前密码" |
| @@ -2,7 +2,7 @@ import React, { useEffect, useRef, useState } from "react"; | ||
| 2 | 2 | import { Check, ChevronLeft, LoaderCircle, ShieldCheck } from "lucide-react"; |
| 3 | 3 | import { api, native, nativeAvailable } from "./api"; |
| 4 | 4 | import { isRemoteClient } from "./client-context.mjs"; |
| 5 | 删除:import { useAccount } from "./account"; | |
| 5 | 新增:import { MacOSAccountGate, useAccount } from "./account"; | |
| 6 | 6 | import { GuestSystemPicker, HostCloneSummary, validGuestChoice } from "./guest-system-picker"; |
| 7 | 7 | import { InitializationStorage } from "./initialization-storage"; |
| 8 | 8 | import { ProxySettings } from "./proxy-settings"; |
| @@ -41,10 +41,10 @@ export function InitializationGate({ children }) { | ||
| 41 | 41 | return () => { live = false; }; |
| 42 | 42 | }, [remote, attempt, account?.initial_mac_setup]); |
| 43 | 43 | if (remote) return children; |
| 44 | 删除: if (account?.initial_mac_setup) return <MacOSFirstSetup />; | |
| 44 | 新增: if (account?.initial_mac_setup) return <MacOSAccountGate><MacOSFirstSetup /></MacOSAccountGate>; | |
| 45 | 45 | if (error) return <InitializationFrame><section className="initialization-content"><h1>继续准备 Cage</h1><p role="alert"><SafetyMessage message={error} /></p><button className="primary" onClick={() => retry(value => value + 1)}>重新连接</button><DiagnosticSettings /></section></InitializationFrame>; |
| 46 | 46 | if (!state) return <InitializationFrame><section className="initialization-content"><h1>正在读取环境状态</h1><p role="status"><LoaderCircle size={18} className="spin" />正在检查已有配置和安装进度…</p></section></InitializationFrame>; |
| 47 | 删除: return state.required ? <Initialization initial={state} onComplete={() => setState({ required: false })} /> : children; | |
| 47 | 新增: return state.required ? <MacOSAccountGate><Initialization initial={state} onComplete={() => setState({ required: false })} /></MacOSAccountGate> : children; | |
| 48 | 48 | } |
| 49 | 49 | |
| 50 | 50 | function Initialization({ initial, onComplete }) { |
| @@ -25,7 +25,7 @@ export function MacOSFirstSetup() { | ||
| 25 | 25 | const next = await api("/status"); |
| 26 | 26 | if (!active) return; |
| 27 | 27 | setState(next); |
| 28 | 删除: if (!next.vm_running && !next.job?.running && !next.job?.error && !started.current) { | |
| 28 | 新增: if ((!next.vm_running || account.macos_password_pending) && !next.job?.running && !next.job?.error && !started.current) { | |
| 29 | 29 | started.current = true; |
| 30 | 30 | await api("/start", {guest_system:"macos"}); |
| 31 | 31 | } |
| @@ -92,8 +92,8 @@ export function MacOSFirstSetup() { | ||
| 92 | 92 | <li>在 Cage 打开的「窗口录制」「辅助功能」设置里允许 <strong>Cage Guest Window</strong>。如果提示「退出并重新打开」,按提示操作。需要重新定位时,点击同名按钮。</li> |
| 93 | 93 | <li>点击「文件系统扩展」,在客机设置中同时打开 <strong>macFUSE</strong> 和 <strong>macFUSE (local)</strong>。Cage 会自动验证并进入工作台。</li> |
| 94 | 94 | </ol> |
| 95 | 删除: <p>授权时若要求管理员,用户名填 <strong>cagesetup</strong>,点选系统密码框后点击「填写授权密码」,再确认授权。辅助功能尚未开启时,可用「查看授权密码」。此管理员在完成后自动停用。</p> | |
| 96 | 删除: {!state?.vm_running && <button className="primary" disabled={busy || !state || state.job?.running} onClick={() => act("start")}>启动虚拟 Mac</button>} | |
| 95 | 新增: <p>授权时若要求管理员,用户名填 <strong>cagesetup</strong>,{account.macos_password_pending ? "密码正在等待同步,完成前可能仍需原客机密码。" : account.macos_credentials_ready ? "密码与 Cage 账户相同。" : "可点选系统密码框后点击「填写授权密码」。"}确认后继续授权。此管理员在完成后自动停用。</p> | |
| 96 | 新增: {(!state?.vm_running || account.macos_password_pending) && <button className="primary" disabled={busy || !state || state.job?.running} onClick={() => act("start")}>{account.macos_password_pending ? "重试同步客机密码" : "启动虚拟 Mac"}</button>} | |
| 97 | 97 | {state?.vm_running && <MacOSLogin initialSetup autoOpen={Boolean(permissions.managed_credential)} managedCredential={permissions.managed_credential} disabled={!state.ready} setupActions={controls} |
| 98 | 98 | setupHint={`Cage 自动登录 ${loginName}。管理员授权用 cagesetup;打开两个 macFUSE 开关后会自动继续。`} |
| 99 | 99 | setupStatus={error || progress} setupError={Boolean(error)} />} |
| @@ -29,7 +29,6 @@ import { TailscalePanel } from "./tailscale"; | ||
| 29 | 29 | import { WorkspaceSidebar } from "./workspace-sidebar"; |
| 30 | 30 | import { useCLISessions, sessionsChanged } from "./cli-sessions"; |
| 31 | 31 | import { TerminalMenu } from "./terminal-menu"; |
| 32 | 删除:import { MacOSFirstSetup } from "./macos-first-setup"; | |
| 33 | 32 | import { InitializationGate } from "./initialization"; |
| 34 | 33 | import { MacOSLogin } from "./macos-login"; |
| 35 | 34 | import { MacOSClaudeWindow } from "./macos-claude-window"; |
| @@ -1897,10 +1896,6 @@ function App() { | ||
| 1897 | 1896 | </SafetyChecklistContext.Provider> |
| 1898 | 1897 | ); |
| 1899 | 1898 | } |
| 1900 | 删除:function GuestWorkspace() { | |
| 1901 | 删除: const { account } = useAccount(); | |
| 1902 | 删除: return account?.initial_mac_setup ? <MacOSFirstSetup /> : <InitializationGate><App /></InitializationGate>; | |
| 1903 | 删除:} | |
| 1904 | 1899 | export default function Workbench() { |
| 1905 | 删除: return <AccountProvider><AppearanceProvider><AccountGate><GuestWorkspace /></AccountGate></AppearanceProvider></AccountProvider>; | |
| 1900 | 新增: return <AccountProvider><AppearanceProvider><AccountGate><InitializationGate><App /></InitializationGate></AccountGate></AppearanceProvider></AccountProvider>; | |
| 1906 | 1901 | } |

