跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

WindowsSystemSettings.cs

80 行 · 6.5 KB历史下载
1using System.Diagnostics;
2using System.Globalization;
3using System.Security.AccessControl;
4using System.Security.Principal;
5using System.Text.Json.Nodes;
6using System.Text.RegularExpressions;
7
8namespace Cage.GuestClipboard;
9
10// Only the paired host can apply these bounded platform settings. No command,
11// registry path, executable, account or file name is accepted from the wire.
12internal static class WindowsSystemSettings
13{
14 internal static async Task Apply(JsonObject settings,Guid vm,string sid,CancellationToken token)
15 {
16 if(settings.Count is not (3 or 4) || settings["action"]?.GetValue<string>()!="apply")throw new InvalidDataException("settings_invalid");
17 var iana=settings["timezone"]?.GetValue<string>() ?? "";var locale=settings["locale"]?.GetValue<string>() ?? "";
18 if(iana.Length>128 || !TimeZoneInfo.TryConvertIanaIdToWindowsId(iana,out var windowsZone) ||
19 !Regex.IsMatch(windowsZone!,@"^[A-Za-z0-9 ()._+-]+$") || !Regex.IsMatch(locale,@"^[a-zA-Z]{2,3}_[a-zA-Z]{2,3}\.UTF-8$") || !Regex.IsMatch(sid,@"^S-1-5-21-\d+-\d+-\d+-\d+$"))throw new InvalidDataException("settings_invalid");
20 var tag=locale[..^6].Replace('_','-');var culture=CultureInfo.GetCultureInfo(tag);
21 _=TimeZoneInfo.FindSystemTimeZoneById(windowsZone!);
22 var configPath=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"Cage Guest Bridge",vm.ToString("D"),"guest-config.json");
23 var previous=ProtectedConfig(configPath);
24 var config=JsonNode.Parse(previous) as JsonObject ?? throw new InvalidDataException("settings_config_invalid");
25 if(config["network_mode"]?.GetValue<string>()!="packet")throw new InvalidDataException("settings_config_invalid");
26 // Existing v1 controllers omit browser_language. Preserve the protected
27 // selection during a component update; never derive it from locale.
28 var language=settings.Count==4 ? BrowserLanguage(settings) : BrowserLanguage(new JsonObject{["browser_language"]=config["language"]?.DeepClone()});
29 config["timezone"]=iana;config["language"]=language;
30 // Publish before applying the OS settings. A failed OS transaction
31 // restores the protected browser configuration as well.
32 PublishConfig(configPath,System.Text.Encoding.UTF8.GetBytes(config.ToJsonString()));
33 var script=$"$ErrorActionPreference='Stop';$key='Registry::HKEY_USERS\\{sid}\\Control Panel\\International';if(!(Test-Path -LiteralPath $key)){{throw 'gui_profile_not_loaded'}};$before=Get-ItemProperty -LiteralPath $key;$zone=(Get-TimeZone).Id;$system=(Get-WinSystemLocale).Name;try{{Set-TimeZone -Id '{windowsZone}';Set-ItemProperty -LiteralPath $key -Name LocaleName -Value '{culture.Name}';Set-ItemProperty -LiteralPath $key -Name Locale -Value '{culture.LCID:X8}';Set-WinSystemLocale -SystemLocale '{culture.Name}'}}catch{{Set-TimeZone -Id $zone;Set-ItemProperty -LiteralPath $key -Name LocaleName -Value $before.LocaleName;Set-ItemProperty -LiteralPath $key -Name Locale -Value $before.Locale;Set-WinSystemLocale -SystemLocale $system;throw}}";
34 var start=new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),@"System32\WindowsPowerShell\v1.0\powershell.exe")){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true,CreateNoWindow=true};
35 foreach(var argument in new[]{"-NoLogo","-NoProfile","-NonInteractive","-Command","-"})start.ArgumentList.Add(argument);
36 try
37 {
38 using var process=Process.Start(start) ?? throw new InvalidDataException("settings_apply_failed");
39 using var cancel=token.Register(()=>{try{process.Kill(true);}catch{}});
40 var output=process.StandardOutput.BaseStream.CopyToAsync(Stream.Null,token);var errors=process.StandardError.BaseStream.CopyToAsync(Stream.Null,token);
41 await process.StandardInput.WriteLineAsync(script);process.StandardInput.Close();await process.WaitForExitAsync(token);await Task.WhenAll(output,errors);
42 if(process.ExitCode!=0)throw new InvalidDataException("settings_apply_failed");
43 }
44 catch { PublishConfig(configPath,previous);throw; }
45 }
46
47 internal static string BrowserLanguage(JsonObject settings)
48 {
49 var language=settings["browser_language"]?.GetValue<string>() ?? "";
50 if(language.Length>128 || !Regex.IsMatch(language,@"^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$"))throw new InvalidDataException("settings_invalid");
51 return language;
52 }
53
54 private static byte[] ProtectedConfig(string path)
55 {
56 var file=new FileInfo(path);
57 for(var directory=file.Directory;directory!=null;directory=directory.Parent)
58 if(directory.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("settings_config_invalid");
59 if(!file.Exists || file.Length is <=0 or >16384 || file.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("settings_config_invalid");
60 var acl=file.GetAccessControl();
61 if(acl.GetOwner(typeof(SecurityIdentifier))?.Value is not ("S-1-5-18" or "S-1-5-32-544"))throw new InvalidDataException("settings_config_invalid");
62 const FileSystemRights writes=FileSystemRights.WriteData|FileSystemRights.AppendData|FileSystemRights.WriteAttributes|FileSystemRights.WriteExtendedAttributes|FileSystemRights.Delete|FileSystemRights.ChangePermissions|FileSystemRights.TakeOwnership;
63 foreach(FileSystemAccessRule rule in acl.GetAccessRules(true,true,typeof(SecurityIdentifier)))
64 if(rule.AccessControlType==AccessControlType.Allow && (rule.FileSystemRights&writes)!=0 && rule.IdentityReference.Value is not ("S-1-5-18" or "S-1-5-32-544"))throw new InvalidDataException("settings_config_invalid");
65 using var snapshot=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read|FileShare.Delete);
66 if(snapshot.Length is <=0 or >16384)throw new InvalidDataException("settings_config_invalid");
67 using var data=new MemoryStream();snapshot.CopyTo(data);return data.ToArray();
68 }
69 private static void PublishConfig(string path,byte[] data)
70 {
71 var stage=path+"."+Guid.NewGuid().ToString("N")+".part";
72 try
73 {
74 File.WriteAllBytes(stage,data);
75 new FileInfo(stage).SetAccessControl(new FileInfo(path).GetAccessControl());
76 WindowsFilePublication.Replace(stage,path,default).GetAwaiter().GetResult();
77 }
78 finally { if(File.Exists(stage))File.Delete(stage); }
79 }
80}