跳到主要内容

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

提交记录
新增internal/guestos/maintenance_macos.go+149 −0看文件
@@ -0,0 +1,149 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "encoding/json"
7新增: "errors"
8新增: "fmt"
9新增: "io"
10新增: "os"
11新增: "os/exec"
12新增: "path/filepath"
13新增: "reflect"
14新增: "regexp"
15新增: "runtime"
16新增: "strings"
17新增: "time"
18新增:
19新增: "al.essio.dev/pkg/shellescape"
20新增:)
21新增:
22新增:// MaintainMacOSComponents operates only on an already bound VZ identity. Its
23新增:// staging and installers are independent of account creation and OS restoration.
24新增:func MaintainMacOSComponents(ctx context.Context, profile, kit, manifestPath string, tools bool, stdout, stderr io.Writer) error {
25新增: if runtime.GOOS != "darwin" {
26新增: return errors.New("macOS 客机维护需要其 Mac 主机")
27新增: }
28新增: binding, err := LoadMacOSProfile(profile)
29新增: if err != nil {
30新增: return err
31新增: }
32新增: if binding == nil {
33新增: return errors.New("此配置尚未绑定 macOS 客机")
34新增: }
35新增: required, err := RequiredNativeComponents(kit, MacOS)
36新增: if err != nil {
37新增: return err
38新增: }
39新增: data, err := os.ReadFile(manifestPath)
40新增: if err != nil {
41新增: return err
42新增: }
43新增: var selected NativeComponentManifest
44新增: if json.Unmarshal(data, &selected) != nil || selected.Validate() != nil || !reflect.DeepEqual(required, selected) {
45新增: return errors.New("当前应用组件包已变化,请重新发起更新")
46新增: }
47新增: provision, err := MacOSProvisionUser(profile)
48新增: if err != nil {
49新增: return err
50新增: }
51新增: args, err := MacOSSSHArgs(profile, provision)
52新增: if err != nil {
53新增: return err
54新增: }
55新增: guest := func(callctx context.Context, script string) *exec.Cmd {
56新增: argv := append(append([]string{}, args...), "-T", "cage-macos", "--", "exec /bin/bash -ec "+shellescape.Quote(script))
57新增: command := exec.CommandContext(callctx, "/usr/bin/ssh", argv...)
58新增: command.Stderr = stderr
59新增: return command
60新增: }
61新增: mode := "components"
62新增: cache := filepath.Join(profile, "state", "guest-media", MacOS)
63新增: if tools {
64新增: mode = "tools"
65新增: command := exec.CommandContext(ctx, "/bin/bash", filepath.Join(kit, "prepare-macos-media.sh"), cache)
66新增: command.Env = append(os.Environ(), "CAGE_REFRESH_TOOLS=1")
67新增: command.Stdout, command.Stderr = stdout, stderr
68新增: if err = command.Run(); err != nil {
69新增: return fmt.Errorf("准备原生工具包失败:%w", err)
70新增: }
71新增: }
72新增: local, err := os.MkdirTemp("", "cage-native-components-")
73新增: if err != nil {
74新增: return err
75新增: }
76新增: defer os.RemoveAll(local)
77新增: if err = os.WriteFile(filepath.Join(local, "native-components.json"), data, 0600); err != nil {
78新增: return err
79新增: }
80新增: output, err := guest(ctx, `umask 077; test "$(id -un)" = `+shellescape.Quote(provision)+`; mktemp -d /private/var/tmp/cage-components.XXXXXXXX`).Output()
81新增: remote := strings.TrimSpace(string(output))
82新增: if err != nil || !regexp.MustCompile(`^/private/var/tmp/cage-components\.[A-Za-z0-9]{8}$`).MatchString(remote) {
83新增: return errors.New("无法在已绑定客机中准备组件维护目录")
84新增: }
85新增: passwordInput := ` < /Users/` + provision + `/password`
86新增: defer func() {
87新增: cleanup, cancel := context.WithTimeout(context.Background(), 10*time.Second)
88新增: defer cancel()
89新增: _ = guest(cleanup, `sudo -S -p '' /bin/rm -rf `+remote+passwordInput).Run()
90新增: }()
91新增: archiveArgs := []string{"--no-mac-metadata", "-cf", "-", "-C", kit, ".", "-C", local, "native-components.json"}
92新增: if tools {
93新增: archiveArgs = append(archiveArgs, "-C", cache, "node.tgz", "editor.tgz", "playwright.tgz", "chrome.dmg", "cli")
94新增: }
95新增: archive := exec.CommandContext(ctx, "/usr/bin/tar", archiveArgs...)
96新增: archive.Env = append(os.Environ(), "COPYFILE_DISABLE=1")
97新增: var archiveErrors bytes.Buffer
98新增: archive.Stderr = &archiveErrors
99新增: pipe, err := archive.StdoutPipe()
100新增: if err != nil {
101新增: return err
102新增: }
103新增: receiver := guest(ctx, `umask 077; cd `+remote+`; /usr/bin/tar -xf -`)
104新增: receiver.Stdin = pipe
105新增: if err = archive.Start(); err != nil {
106新增: return err
107新增: }
108新增: receiveErr := receiver.Run()
109新增: pipe.Close()
110新增: archiveErr := archive.Wait()
111新增: if archiveErrors.Len() > 0 {
112新增: _, _ = stderr.Write(archiveErrors.Bytes())
113新增: }
114新增: if err = errors.Join(receiveErr, archiveErr); err != nil {
115新增: return fmt.Errorf("传递原生组件失败:%w", err)
116新增: }
117新增: takeOwnership := guest(ctx, `sudo -S -p '' /usr/sbin/chown -R root:wheel `+remote+passwordInput)
118新增: if err = takeOwnership.Run(); err != nil {
119新增: return errors.New("无法取得已绑定客机的组件维护权限")
120新增: }
121新增: script := shellescape.QuoteCommand([]string{"/bin/bash", remote + "/maintain-macos-workbench.sh", remote, binding.User, mode})
122新增: command := guest(ctx, `sudo -S -p '' `+script+passwordInput)
123新增: command.Stdout = stdout
124新增: if err = command.Run(); err != nil {
125新增: return fmt.Errorf("原生组件维护未完成,原系统和账户已保留,可重试更新:%w", err)
126新增: }
127新增: return nil
128新增:}
129新增:
130新增:func WriteNativeComponentManifest(filename string, manifest NativeComponentManifest) error {
131新增: if err := manifest.Validate(); err != nil {
132新增: return err
133新增: }
134新增: data, err := json.Marshal(manifest)
135新增: if err != nil {
136新增: return err
137新增: }
138新增: file, err := os.CreateTemp(filepath.Dir(filename), ".native-components-*.json")
139新增: if err != nil {
140新增: return err
141新增: }
142新增: defer os.Remove(file.Name())
143新增: _, writeErr := file.Write(append(bytes.TrimSpace(data), '\n'))
144新增: err = errors.Join(writeErr, file.Sync(), file.Close())
145新增: if err != nil {
146新增: return err
147新增: }
148新增: return os.Rename(file.Name(), filename)
149新增:}
新增scripts/guest-os/build-macos-claude-window.sh+25 −0看文件
@@ -0,0 +1,25 @@
1新增:#!/bin/bash
2新增:# Build the GUI-session helper for an Apple-silicon guest (macOS 14+).
3新增:set -euo pipefail
4新增:src=$(cd "$(dirname "$0")" && pwd)
5新增:app=${1:?Specify a new output .app path}
6新增:[[ $app == *.app && ! -e $app ]] || { echo 'Choose a new .app path.' >&2; exit 2; }
7新增:mkdir -p "$app/Contents/MacOS"
8新增:cat > "$app/Contents/Info.plist" <<'PLIST'
9新增:<?xml version="1.0" encoding="UTF-8"?>
10新增:<plist version="1.0"><dict>
11新增:<key>CFBundleIdentifier</key><string>dev.cage.GuestClaudeWindow</string>
12新增:<key>CFBundleName</key><string>Cage Guest Window</string>
13新增:<key>CFBundleExecutable</key><string>CageGuestWindow</string>
14新增:<key>CFBundlePackageType</key><string>APPL</string>
15新增:<key>CFBundleShortVersionString</key><string>1.0</string>
16新增:<key>CFBundleVersion</key><string>1</string>
17新增:<key>LSUIElement</key><true/>
18新增:</dict></plist>
19新增:PLIST
20新增:objects=$(mktemp -d)
21新增:trap 'rm -rf "$objects"' EXIT
22新增:xcrun clang -target arm64-apple-macos14.0 -Wall -Wextra -Werror -O2 -c "$src/macos-file-writers.c" -o "$objects/file-writers.o"
23新增:xcrun swiftc -parse-as-library -D GUEST_WINDOW_APP -O -target arm64-apple-macos14.0 "$src/../../desktop/MacKeyboard.swift" "$src/claude-window-macos.swift" "$src/macos-diagnostics.swift" "$src/macos-claude-window-app.swift" "$src/macos-window-input.swift" "$src/macos-project-panel.swift" "$src/macos-claude-canvas.swift" "$src/macos-window-stream.swift" "$src/macos-audio.swift" "$src/macos-gui-session.swift" "$src/macos-phone-desktop.swift" "$src/macos-desktop-files.swift" "$src/macos-desktop-downloads.swift" "$objects/file-writers.o" -o "$app/Contents/MacOS/CageGuestWindow"
24新增:codesign --force --sign "${CAGE_GUEST_SIGN_IDENTITY:-${CAGE_SIGNING_IDENTITY:--}}" --identifier dev.cage.GuestClaudeWindow "$app"
25新增:codesign --verify --strict "$app"
新增scripts/guest-os/build-macos-clipboard.sh+25 −0看文件
@@ -0,0 +1,25 @@
1新增:#!/bin/bash
2新增:# Build the per-user clipboard agent and its bounded file-transfer helper.
3新增:set -euo pipefail
4新增:src=$(cd "$(dirname "$0")" && pwd)
5新增:app=${1:?Specify a new output .app path}
6新增:[[ $app == /*.app && ! -e $app ]] || { echo 'Choose a new absolute .app path.' >&2; exit 2; }
7新增:mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources"
8新增:cat > "$app/Contents/Info.plist" <<'PLIST'
9新增:<?xml version="1.0" encoding="UTF-8"?>
10新增:<plist version="1.0"><dict>
11新增:<key>CFBundleIdentifier</key><string>dev.cage.GuestClipboard</string>
12新增:<key>CFBundleName</key><string>Cage Guest Clipboard</string>
13新增:<key>CFBundleExecutable</key><string>CageGuestClipboard</string>
14新增:<key>CFBundlePackageType</key><string>APPL</string>
15新增:<key>CFBundleShortVersionString</key><string>1.0</string>
16新增:<key>CFBundleVersion</key><string>1</string>
17新增:<key>LSUIElement</key><true/>
18新增:</dict></plist>
19新增:PLIST
20新增:xcrun swiftc -parse-as-library -O -target arm64-apple-macos14.0 "$src/guest-clipboard-macos.swift" "$src/macos-diagnostics.swift" -o "$app/Contents/MacOS/CageGuestClipboard"
21新增:(cd "$src/../.." && CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags '-s -w' -o "$app/Contents/Resources/cage-guest-files" ./cmd/cage-guest-files)
22新增:identity=${CAGE_GUEST_SIGN_IDENTITY:-${CAGE_SIGNING_IDENTITY:--}}
23新增:codesign --force --sign "$identity" "$app/Contents/Resources/cage-guest-files"
24新增:codesign --force --sign "$identity" --identifier dev.cage.GuestClipboard "$app"
25新增:codesign --verify --deep --strict "$app"
新增scripts/guest-os/build-macos-guest-core.sh+30 −0看文件
@@ -0,0 +1,30 @@
1新增:#!/bin/bash
2新增:# Add the small raw-object accessor needed by the hostagent's AppKit view to a
3新增:# private copy of the pinned VZ binding. The Go module cache stays read-only.
4新增:set -euo pipefail
5新增:cd "$(dirname "$0")/../.."
6新增:work=$(mktemp -d)
7新增:trap 'rm -rf "$work"' EXIT
8新增:mod=github.com/Code-Hex/vz/v3
9新增:version=$(go list -m -f '{{.Version}}' "$mod")
10新增:[[ $version == v3.7.1 ]] || { echo "Review the login view against VZ binding $version" >&2; exit 1; }
11新增:dir=$(go list -m -f '{{.Dir}}' "$mod")
12新增:cp -R "$dir" "$work/vz"
13新增:chmod -R u+w "$work/vz"
14新增:cat > "$work/vz/cage_view_object_darwin.go" <<'GO'
15新增://go:build darwin && cgo
16新增:
17新增:package vz
18新增:
19新增:import (
20新增: "unsafe"
21新增: "github.com/Code-Hex/vz/v3/internal/objc"
22新增:)
23新增:
24新增:// CageViewObject borrows the VZVirtualMachine for the duration of RunGUI.
25新增:func (v *VirtualMachine) CageViewObject() unsafe.Pointer { return objc.Ptr(v) }
26新增:GO
27新增:cp go.mod "$work/trial.mod"
28新增:cp go.sum "$work/trial.sum"
29新增:go mod edit -modfile "$work/trial.mod" -replace "$mod=$work/vz"
30新增:GOFLAGS="${GOFLAGS:-} -modfile=$work/trial.mod" make cage VERSION="$1"
新增scripts/guest-os/build-macos-project-access.sh+25 −0看文件
@@ -0,0 +1,25 @@
1新增:#!/bin/sh
2新增:# Build the scoped project-access application for the native arm64 guest.
3新增:set -eu
4新增:[ "$#" = 1 ] || { echo "usage: $0 /path/to/CageProjectAccess.app" >&2; exit 2; }
5新增:bundle=$1
6新增:[ ! -e "$bundle" ] || { echo "Choose a new output path." >&2; exit 1; }
7新增:mkdir -p "$bundle/Contents/MacOS"
8新增:cat > "$bundle/Contents/Info.plist" <<'PLIST'
9新增:<?xml version="1.0" encoding="UTF-8"?>
10新增:<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
11新增:<plist version="1.0"><dict>
12新增:<key>CFBundleIdentifier</key><string>dev.cage.guest.project-access</string>
13新增:<key>CFBundleDisplayName</key><string>Cage Project Access</string>
14新增:<key>CFBundleName</key><string>Cage Project Access</string>
15新增:<key>CFBundleExecutable</key><string>CageProjectAccess</string>
16新增:<key>CFBundlePackageType</key><string>APPL</string>
17新增:<key>CFBundleVersion</key><string>1</string>
18新增:<key>CFBundleShortVersionString</key><string>1.0</string>
19新增:<key>LSUIElement</key><true/>
20新增:<key>NSNetworkVolumesUsageDescription</key><string>Open the mounted project you selected in Cage.</string>
21新增:</dict></plist>
22新增:PLIST
23新增:xcrun clang -arch arm64 -mmacosx-version-min=14.0 -fobjc-arc -O2 -framework AppKit \
24新增: "$(dirname "$0")/macos-project-access.m" -o "$bundle/Contents/MacOS/CageProjectAccess"
25新增:codesign --force --sign "${CAGE_SIGNING_IDENTITY:--}" "$bundle"
新增scripts/guest-os/build-macos-setup-probe.py+90 −0看文件
@@ -0,0 +1,90 @@
1新增:"""Build a QA-only Go runner with the Apple VM setup view bound to one temporary instance."""
2新增:
3新增:import argparse
4新增:import json
5新增:import shutil
6新增:import subprocess
7新增:import tempfile
8新增:from pathlib import Path
9新增:
10新增:
11新增:SCRIPTS = Path(__file__).resolve().parent
12新增:REPO = SCRIPTS.parents[1]
13新增:VZ = "github.com/Code-Hex/vz/v3"
14新增:
15新增:
16新增:def run(*command):
17新增: subprocess.run(command, check=True, cwd=REPO)
18新增:
19新增:
20新增:def replace_once(text, old, new):
21新增: if text.count(old) != 1:
22新增: raise SystemExit(f"Upstream hook changed. Inspect the source containing {old!r}.")
23新增: return text.replace(old, new)
24新增:
25新增:
26新增:def main():
27新增: parser = argparse.ArgumentParser(description=__doc__)
28新增: parser.add_argument("instance", type=Path, help="Directory of the disposable Lima macOS instance")
29新增: parser.add_argument("output", type=Path, help="New directory for the signed QA runner and its library")
30新增: parser.add_argument("--runner", default="./cmd/cage", help="Go main package which owns the fixture runtime")
31新增: args = parser.parse_args()
32新增: instance = args.instance.resolve(strict=True)
33新增: temp_roots = {Path(tempfile.gettempdir()).resolve(), Path("/private/tmp").resolve()}
34新增: if not instance.is_dir() or not any(root in instance.parents for root in temp_roots):
35新增: parser.error("Select an instance inside a disposable temporary directory.")
36新增: out = args.output.resolve()
37新增: out.mkdir(mode=0o700)
38新增: dylib = out / "libcagesetup.dylib"
39新增: run("xcrun", "clang", "-target", "arm64-apple-macos14.0", "-fobjc-arc", "-Wall", "-Wextra", "-Werror",
40新增: "-dynamiclib", SCRIPTS / "macos-setup-view.m", SCRIPTS / "macos-setup-bridge.m",
41新增: "-framework", "AppKit", "-framework", "Virtualization", "-o", dylib)
42新增: with tempfile.TemporaryDirectory(prefix="cage-setup-build-") as scratch:
43新增: work = Path(scratch)
44新增: module = json.loads(subprocess.check_output(["go", "list", "-m", "-json", VZ], cwd=REPO))
45新增: if module.get("Version") != "v3.7.1":
46新增: raise SystemExit("Review the native bridge for the current Code-Hex/vz version.")
47新增: source = Path(module["Dir"])
48新增: copy = work / "vz"
49新增: shutil.copytree(source, copy)
50新增: copy.chmod(0o700)
51新增: shutil.copyfile(SCRIPTS / "macos-setup-bridge.h", copy / "cage_setup_bridge.h")
52新增: (copy / dylib.name).symlink_to(dylib)
53新增: binding = copy / "virtualization.go"
54新增: text = replace_once(binding.read_text(), '# include "virtualization_15.h"',
55新增: '# include "virtualization_15.h"\n# include "cage_setup_bridge.h"')
56新增: text = replace_once(text, "#cgo darwin LDFLAGS: -lobjc",
57新增: "#cgo darwin LDFLAGS: -L${SRCDIR} -lcagesetup -lobjc")
58新增: binding.chmod(0o600)
59新增: binding.write_text(replace_once(text, "C.startVirtualMachineWindow(", "C.CageRunSetupBridge("))
60新增:
61新增: driver = REPO / "third_party/lima/pkg/driver/vz/vz_driver_darwin.go"
62新增: contents = driver.read_text()
63新增: start = contents.index("func (l *LimaVzDriver) canRunGUI() bool {")
64新增: end = contents.index("\n}", start)
65新增: selected = json.dumps(str(instance), ensure_ascii=False)
66新增: hook = ("func (l *LimaVzDriver) canRunGUI() bool {\n"
67新增: f"\treturn l.Instance.Dir == {selected} && *l.Instance.Config.OS == limatype.DARWIN "
68新增: '&& *l.Instance.Config.Video.Display == "offscreen"')
69新增: modified = work / "driver.go"
70新增: modified.write_text(contents[:start] + hook + contents[end:])
71新增: runner = json.loads(subprocess.check_output(["go", "list", "-json", args.runner], cwd=REPO))
72新增: runner_dir = Path(runner["Dir"]).resolve()
73新增: if runner["Name"] != "main" or REPO not in runner_dir.parents:
74新增: parser.error("Choose a main package in this checkout.")
75新增: startup = work / "setup_thread.go"
76新增: startup.write_text('package main\nimport "runtime"\nfunc init() { runtime.LockOSThread() }\n')
77新增: overlay = work / "overlay.json"
78新增: overlay.write_text(json.dumps({"Replace": {
79新增: str(driver): str(modified), str(runner_dir / "cage_setup_qa_thread_darwin.go"): str(startup),
80新增: }}))
81新增: mod = work / "qa.mod"
82新增: shutil.copyfile(REPO / "go.mod", mod)
83新增: shutil.copyfile(REPO / "go.sum", work / "qa.sum")
84新增: run("go", "mod", "edit", "-modfile", mod, "-replace", f"{VZ}={copy}")
85新增: run("go", "build", "-modfile", mod, "-overlay", overlay, "-o", out / "qa-runner", args.runner)
86新增: run("codesign", "-f", "-s", "-", "--entitlements", REPO / "third_party/lima/vz.entitlements", out / "qa-runner")
87新增:
88新增:
89新增:if __name__ == "__main__":
90新增: main()
新增scripts/guest-os/build-macos-sshfs.sh+28 −0看文件
@@ -0,0 +1,28 @@
1新增:#!/bin/bash
2新增:# Build the FSKit-compatible SSHFS against the SDK from the signed macFUSE
3新增:# installer. Pass its extracted usr/local directory; no host driver is installed.
4新增:set -euo pipefail
5新增:[[ $# == 2 && $(uname -sm) == 'Darwin arm64' ]] || { echo 'Usage: build-macos-sshfs.sh /absolute/macfuse-sdk/usr/local /absolute/cage-sshfs' >&2; exit 2; }
6新增:sdk=$1
7新增:output=$2
8新增:[[ $sdk == /* && $output == /* && -f $sdk/include/fuse3/fuse.h && ! -e $output ]]
9新增:src=$(mktemp -d)
10新增:trap 'rm -rf "$src"' EXIT
11新增:commit=9b68e5f1b978c1d3c6ef7632b68d580a52ec0232
12新增:curl -fLsS --retry 2 "https://codeload.github.com/libfuse/sshfs/tar.gz/$commit" -o "$src/sshfs.tgz"
13新增:cd "$src"
14新增:echo '9be20256ac841c6e5b4cd8aefbf57c325f93e9ff01f7c7691edfe9f02700338b sshfs.tgz' | shasum -a 256 -c - >/dev/null
15新增:tar xzf sshfs.tgz --strip-components 1
16新增:cat > config.h <<'HEADER'
17新增:#define PACKAGE_VERSION "3.7.6"
18新增:#define IDMAP_DEFAULT "user"
19新增:HEADER
20新增:glib=$(brew --prefix glib)
21新增:intl=$(brew --prefix gettext)
22新增:pcre=$(brew --prefix pcre2)
23新增:clang -arch arm64 -O2 -D_REENTRANT -DHAVE_CONFIG_H -DFUSE_DARWIN_ENABLE_EXTENSIONS=0 -DFUSE_USE_VERSION=31 \
24新增: -I. -Icompat -I"$sdk/include/fuse3" -I"$glib/include/glib-2.0" -I"$glib/lib/glib-2.0/include" -I"$intl/include" \
25新增: sshfs.c cache.c compat/darwin_compat.c "$glib/lib/libgthread-2.0.a" "$glib/lib/libglib-2.0.a" "$intl/lib/libintl.a" "$pcre/lib/libpcre2-8.a" \
26新增: -L"$sdk/lib" -lfuse3 -liconv -framework Foundation -framework CoreFoundation -framework AppKit -framework Carbon -o cage-sshfs
27新增:codesign -s - --force cage-sshfs
28新增:install -m 755 cage-sshfs "$output"
新增scripts/guest-os/build-windows-workbench-payload.ps1+42 −0看文件
@@ -0,0 +1,42 @@
1新增:# Build Cage-owned assets only. Third-party Windows packages are fetched when
2新增:# Windows is selected, with the digests in windows-workbench-packages.json.
3新增:[CmdletBinding()]
4新增:param([Parameter(Mandatory)][string]$Destination)
5新增:$ErrorActionPreference='Stop'
6新增:$root=(Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
7新增:$dest=[IO.Path]::GetFullPath($Destination)
8新增:$null=New-Item -ItemType Directory -Force $dest
9新增:$build=Join-Path ([IO.Path]::GetTempPath()) ('cage-windows-publish-'+[guid]::NewGuid())
10新增:Push-Location $root
11新增:$oldOS=$env:GOOS; $oldArch=$env:GOARCH; $oldCGO=$env:CGO_ENABLED
12新增:try {
13新增: dotnet publish scripts/guest-os/guest-clipboard-windows/Cage.GuestClipboard.csproj -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -o $build
14新增: if ($LASTEXITCODE) {throw 'Could not publish the native Windows guest bridge.'}
15新增: Copy-Item -LiteralPath (Join-Path $build 'Cage.GuestClipboard.exe') -Destination $dest
16新增: $env:GOOS='windows'; $env:GOARCH='amd64'; $env:CGO_ENABLED='0'
17新增: go build -trimpath -o (Join-Path $dest 'cage-guest-files.exe') ./cmd/cage-guest-files
18新增: if ($LASTEXITCODE) {throw 'Could not build the Windows guest file helper.'}
19新增: go build -trimpath -o (Join-Path $dest 'cage-guest-boot.exe') ./cmd/cage-guest-boot
20新增: if ($LASTEXITCODE) {throw 'Could not build the Windows guest boot service.'}
21新增: go build -trimpath -o (Join-Path $dest 'Cage.HyperVManager.exe') ./cmd/cage-hyperv-manager
22新增: if ($LASTEXITCODE) {throw 'Could not build the scoped Windows host manager.'}
23新增: Push-Location (Join-Path $root 'tools/tailnet')
24新增: try { go build -trimpath -ldflags '-s -w' -o (Join-Path $dest 'cage-tailnet.exe') .; if ($LASTEXITCODE) { throw 'Could not build Cage Tailscale.' } } finally { Pop-Location }
25新增: Copy-Item -LiteralPath (Join-Path $root 'internal/cage/tailnet-client.mjs') -Destination $dest
26新增: foreach ($file in @('windows-browser.mjs','windows-browser-extensions.mjs','windows-phone-browser.mjs','windows-workbench-packages.json','install-windows-workbench-user-tools.ps1')) {
27新增: Copy-Item -LiteralPath (Join-Path $PSScriptRoot $file) -Destination $dest
28新增: }
29新增: foreach ($file in @('install-cli.ps1','cli-dependencies.json')) {
30新增: Copy-Item -LiteralPath (Join-Path $PSScriptRoot ('guest-clipboard-windows/'+$file)) -Destination $dest
31新增: }
32新增: $moduleDir=Join-Path $dest 'modules'
33新增: $null=New-Item -ItemType Directory -Force $moduleDir
34新增: foreach ($name in @('clipboard','uploads','downloads','cookies','extensions','vault','phone','phone-network')) {
35新增: Copy-Item -LiteralPath (Join-Path $root "internal/cage/browser-$name.mjs") -Destination $moduleDir
36新增: }
37新增: Copy-Item -LiteralPath (Join-Path $root 'internal/cage/split-extension') -Destination $dest -Recurse -Force
38新增:} finally {
39新增: $env:GOOS=$oldOS; $env:GOARCH=$oldArch; $env:CGO_ENABLED=$oldCGO
40新增: Pop-Location
41新增: if (Test-Path -LiteralPath $build) { Remove-Item -LiteralPath $build -Recurse -Force }
42新增:}
新增scripts/guest-os/cage-macos-editor+8 −0看文件
@@ -0,0 +1,8 @@
1新增:#!/bin/bash
2新增:# The project authorization helper starts this fixed executable inside the mount.
3新增:set -euo pipefail
4新增:project=${PWD##*/}
5新增:[[ $project =~ ^[a-f0-9]{24}$ && $PWD == "$HOME/Cage/Projects/$project" ]]
6新增:config="$HOME/Library/Application Support/Cage/EditorSessions/$project.yaml"
7新增:[[ -f $config && ! -L $config && $(/usr/bin/stat -f %u "$config") == "$(id -u)" ]]
8新增:exec /usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/editor/bin/code-server --config "$config" --disable-telemetry --disable-update-check "$PWD"
新增scripts/guest-os/claude-desktop-macos.sh+125 −0看文件
@@ -0,0 +1,125 @@
1新增:#!/bin/bash
2新增:# Run inside a Cage macOS guest. Install accepts a local official DMG.
3新增:set -euo pipefail
4新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin
5新增:
6新增:fail() { printf '%s\n' "$*" >&2; exit 1; }
7新增:
8新增:case "${1:-}" in
9新增: inspect|launch) [[ $# == 1 ]] || fail "Usage: $0 $1" ;;
10新增: install) [[ $# == 2 ]] || fail "Usage: $0 install /path/to/Claude.dmg" ;;
11新增: *) fail "Usage: $0 inspect | install /path/to/Claude.dmg | launch" ;;
12新增:esac
13新增:
14新增:[[ $(uname -s) == Darwin ]] || fail "This helper requires a Cage macOS guest."
15新增:model=$(sysctl -n hw.model)
16新增:[[ $model =~ ^VirtualMac[0-9]+,[0-9]+$ ]] || fail "This Mac is not a virtual Mac. Run this helper inside the Cage guest."
17新增:marker=/var/db/cage-guest-os
18新增:[[ -f $marker && ! -L $marker && $(stat -f '%u' "$marker") == 0 ]] ||
19新增: fail "Missing root-owned Cage guest marker."
20新增:mode=$(stat -f '%OLp' "$marker")
21新增:(( (8#$mode & 022) == 0 )) && [[ $(cat "$marker") == macos ]] ||
22新增: fail "Invalid Cage guest marker."
23新增:
24新增:app=/Applications/Claude.app
25新增:bundle_id=com.anthropic.claudefordesktop
26新增:team=Q6L2SF6YDW
27新增:requirement="anchor apple generic and identifier \"$bundle_id\" and certificate leaf[subject.OU] = \"$team\" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"
28新增:
29新增:info() {
30新增: plutil -extract "$2" raw -o - "$1/Contents/Info.plist"
31新增:}
32新增:
33新增:verify_app() {
34新增: [[ -d $1 && ! -L $1 ]] || fail "Expected a Claude.app directory at $1."
35新增: [[ $(info "$1" CFBundleIdentifier) == "$bundle_id" ]] || fail "Unexpected Claude bundle identifier."
36新增: codesign --verify --deep --strict "$1"
37新增: codesign --verify --strict -R "=$requirement" "$1"
38新增:}
39新增:
40新增:report() {
41新增: printf 'status=%s\nversion=%s\nbuild=%s\nbundle_id=%s\nteam=%s\n' \
42新增: "$1" "$(info "$app" CFBundleShortVersionString)" "$(info "$app" CFBundleVersion)" "$bundle_id" "$team"
43新增:}
44新增:
45新增:case "$1" in
46新增: inspect)
47新增: [[ -e $app || -L $app ]] || { printf 'status=absent\n'; exit 3; }
48新增: verify_app "$app"
49新增: report installed
50新增: ;;
51新增: install)
52新增: [[ $EUID == 0 ]] || fail "Run install as root inside the guest."
53新增: dmg=$2
54新增: [[ $dmg == /* && -f $dmg ]] || fail "Supply the absolute path of the downloaded Claude DMG."
55新增: exec 9>/var/run/cage-claude-install.lock
56新增: lockf -s -t 0 9 || fail "A Claude installation is in progress."
57新增: stage=$(mktemp -d /Applications/.cage-claude.XXXXXXXX)
58新增: mountdir="$stage/media"
59新增: mkdir "$mountdir"
60新增: cleanup() {
61新增: # Mounts are read-only. Keep the directory if the system cannot detach.
62新增: if [[ $(stat -f '%d' "$mountdir") != "$(stat -f '%d' "$stage")" ]]; then
63新增: hdiutil detach "$mountdir" >/dev/null || { printf 'Unable to detach %s\n' "$mountdir" >&2; return; }
64新增: fi
65新增: rm -rf "$stage"
66新增: }
67新增: trap cleanup EXIT
68新增: trap 'exit 1' HUP INT TERM
69新增: hdiutil attach -readonly -nobrowse -noautoopen -mountpoint "$mountdir" "$dmg" >/dev/null
70新增: source_app="$mountdir/Claude.app"
71新增: verify_app "$source_app"
72新增: # renamex_np publishes the verified copy on the same filesystem. With an
73新增: # existing app, RENAME_SWAP retains it in staging until the swap succeeds.
74新增: rename_flag=4 # RENAME_EXCL
75新增: if [[ -e $app || -L $app ]]; then
76新增: verify_app "$app"
77新增: if [[ $(info "$source_app" CFBundleVersion) == "$(info "$app" CFBundleVersion)" &&
78新增: $(info "$source_app" CFBundleShortVersionString) == "$(info "$app" CFBundleShortVersionString)" ]]; then
79新增: report installed
80新增: exit 0
81新增: fi
82新增: if pgrep -f '^/Applications/Claude\.app/Contents/MacOS/Claude([[:space:]]|$)' >/dev/null; then
83新增: fail "Quit the running guest Claude app before installing another version."
84新增: fi
85新增: rename_flag=2 # RENAME_SWAP
86新增: fi
87新增: staged_app="$stage/Claude.app"
88新增: ditto "$source_app" "$staged_app"
89新增: chown -R -P root:wheel "$staged_app"
90新增: verify_app "$staged_app"
91新增: /usr/bin/osascript -l JavaScript - "$staged_app" "$app" "$rename_flag" <<'JXA'
92新增:ObjC.bindFunction("renamex_np", ["int", ["char *", "char *", "uint32_t"]]);
93新增:function run(args) {
94新增: if ($.renamex_np(args[0], args[1], Number(args[2])) !== 0) {
95新增: throw Error("Could not publish Claude.app; previous installation preserved.");
96新增: }
97新增:}
98新增:JXA
99新增: report installed
100新增: ;;
101新增: launch)
102新增: verify_app "$app"
103新增: gui_uid=$(stat -f '%u' /dev/console)
104新增: if (( gui_uid < 500 )) || ! launchctl print "gui/$gui_uid" >/dev/null 2>&1; then
105新增: printf 'status=requires_gui_login\nLog in to the guest macOS desktop first.\n' >&2
106新增: exit 4
107新增: fi
108新增: if [[ $EUID == 0 ]]; then
109新增: launchctl asuser "$gui_uid" sudo -n -H -u "#$gui_uid" -- /usr/bin/open "$app"
110新增: elif [[ $EUID == "$gui_uid" ]]; then
111新增: /usr/bin/open "$app"
112新增: else
113新增: fail "Run launch as root or the guest console user."
114新增: fi
115新增: for ((attempt=0; attempt<20; attempt++)); do
116新增: if pid=$(pgrep -o -U "$gui_uid" -f '^/Applications/Claude\.app/Contents/MacOS/Claude([[:space:]]|$)'); then
117新增: report running
118新增: printf 'pid=%s\n' "$pid"
119新增: exit 0
120新增: fi
121新增: sleep 1
122新增: done
123新增: fail "The Claude application process did not start in the guest GUI session."
124新增: ;;
125新增:esac
新增scripts/guest-os/claude-desktop-windows.ps1+168 −0看文件
@@ -0,0 +1,168 @@
1新增:#requires -Version 5.1
2新增:<#
3新增:.SYNOPSIS
4新增:Inspect, install or launch the official x64 Claude Desktop MSIX as the current user.
5新增:.DESCRIPTION
6新增:Run with 64-bit Windows PowerShell inside the target VM. For Install and Launch,
7新增:pass the Id obtained independently from Get-VM on the Hyper-V host.
8新增:The full MSIX includes a service. Register it in an elevated session for the
9新增:target guest user, or provision it in the guest image before that user signs in.
10新增:Launch in the user's normal interactive session.
11新增:Download the local MSIX from https://support.claude.com/en/articles/12622703 .
12新增:#>
13新增:[CmdletBinding()]
14新增:param(
15新增: [ValidateSet('Inspect', 'Install', 'Launch')][string]$Action = 'Inspect',
16新增: [Guid]$ExpectedVMId = [Guid]::Empty,
17新增: [string]$MsixPath
18新增:)
19新增:$ErrorActionPreference = 'Stop'
20新增:
21新增:# Verified against AppxManifest.xml and AppxSignature.p7x in the official
22新增:# Windows x64 4.23118.0.0 MSIX. The package also contains helper applications.
23新增:$publisher = 'CN="Anthropic, PBC", O="Anthropic, PBC", L=San Francisco, S=California, C=US, SERIALNUMBER=4860621, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US'
24新增:$packageFamily = 'Claude_pzs8sxrjxfjjc'
25新增:
26新增:function Assert-TargetGuest([Guid]$expected) {
27新增: if ($expected -eq [Guid]::Empty) {
28新增: throw 'Pass -ExpectedVMId with the target VM Id from Get-VM on the Hyper-V host.'
29新增: }
30新增: $system = Get-CimInstance Win32_ComputerSystem
31新增: if ($system.Manufacturer -ne 'Microsoft Corporation' -or $system.Model -ne 'Virtual Machine') {
32新增: throw 'This operation requires a Hyper-V guest.'
33新增: }
34新增: $kvp = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters' -Name VirtualMachineId
35新增: $actual = [Guid]::Empty
36新增: if (![Guid]::TryParse($kvp.VirtualMachineId, [ref]$actual) -or $expected -ne $actual) {
37新增: throw 'The Hyper-V guest VM Id does not match the host-provided target.'
38新增: }
39新增:}
40新增:
41新增:function Assert-ClaudeManifest([xml]$manifest) {
42新增: $ns = [Xml.XmlNamespaceManager]::new($manifest.NameTable)
43新增: $ns.AddNamespace('m', 'http://schemas.microsoft.com/appx/manifest/foundation/windows10')
44新增: $identity = $manifest.SelectSingleNode('/m:Package/m:Identity', $ns)
45新增: $app = $manifest.SelectSingleNode('/m:Package/m:Applications/m:Application[@Id="Claude"]', $ns)
46新增: if (!$identity -or $identity.GetAttribute('Name') -cne 'Claude' -or
47新增: $identity.GetAttribute('Publisher') -cne $publisher -or
48新增: $identity.GetAttribute('ProcessorArchitecture') -ne 'x64' -or !$app -or
49新增: $app.GetAttribute('Executable') -ine 'app\Claude.exe' -or
50新增: $app.GetAttribute('EntryPoint') -cne 'Windows.FullTrustApplication') {
51新增: throw 'Unexpected Claude x64 package identity or application entry point.'
52新增: }
53新增: return [version]$identity.GetAttribute('Version')
54新增:}
55新增:
56新增:function Assert-ClaudeSignature($signature) {
57新增: if ($signature.Status -ne 'Valid' -or !$signature.SignerCertificate) {
58新增: throw 'Windows did not validate the MSIX signature.'
59新增: }
60新增: # Decode both subjects with the same Windows formatter, including the
61新增: # organization registration number. A matching common name alone is insufficient.
62新增: $expected = [Security.Cryptography.X509Certificates.X500DistinguishedName]::new($publisher)
63新增: $format = [Security.Cryptography.X509Certificates.X500DistinguishedNameFlags]::Reversed
64新增: if ($signature.SignerCertificate.SubjectName.Decode($format) -cne $expected.Decode($format)) {
65新增: throw 'The trusted signing certificate does not match the Anthropic publisher.'
66新增: }
67新增:}
68新增:
69新增:function Get-RegisteredClaude {
70新增: $packages = @(Get-AppxPackage -Name Claude | Where-Object PackageFamilyName -ceq $packageFamily)
71新增: if ($packages.Count -eq 0) { return }
72新增: if ($packages.Count -ne 1) { throw 'Multiple registrations found for the Claude package family.' }
73新增: $pkg = $packages[0]
74新增: if ($pkg.Publisher -cne $publisher -or $pkg.IsDevelopmentMode -or $pkg.IsPartiallyStaged -or
75新增: $pkg.SignatureKind -notin 'Developer','Store','Enterprise' -or $pkg.Status -ne 'Ok') {
76新增: throw 'The registered Claude package is unsigned, unhealthy or has an unexpected publisher.'
77新增: }
78新增: $version = Assert-ClaudeManifest (Get-AppxPackageManifest -Package $pkg.PackageFullName)
79新增: return [pscustomobject]@{
80新增: Registered = $true
81新增: Version = $version.ToString()
82新增: Aumid = "$packageFamily!Claude"
83新增: Executable = Join-Path $pkg.InstallLocation 'app\Claude.exe'
84新增: }
85新增:}
86新增:
87新增:function Get-VerifiedClaudeMsixVersion([IO.FileInfo]$file, [IO.Stream]$handle) {
88新增: Assert-ClaudeSignature (Get-AuthenticodeSignature -LiteralPath $file.FullName)
89新增: Add-Type -AssemblyName System.IO.Compression
90新增: $zip = [IO.Compression.ZipArchive]::new($handle, 'Read', $true)
91新增: try {
92新增: $entry = $zip.GetEntry('AppxManifest.xml')
93新增: if (!$entry) { throw 'The MSIX is missing AppxManifest.xml.' }
94新增: $stream = $entry.Open()
95新增: try {
96新增: $manifest = [xml]::new()
97新增: $manifest.XmlResolver = $null
98新增: $manifest.Load($stream)
99新增: return (Assert-ClaudeManifest $manifest)
100新增: } finally { $stream.Dispose() }
101新增: } finally { $zip.Dispose() }
102新增:}
103新增:
104新增:function Install-ClaudeMsix([string]$path) {
105新增: if (!$path) { throw 'Install requires -MsixPath with a locally downloaded x64 MSIX.' }
106新增: $file = Get-Item -LiteralPath $path
107新增: if ($file -isnot [IO.FileInfo] -or $file.Extension -ne '.msix' -or
108新增: $file.FullName.StartsWith('\\') -or
109新增: [IO.DriveInfo]::new($file.Directory.Root.FullName).DriveType -eq 'Network') {
110新增: throw 'Select a local .msix file on the guest.'
111新增: }
112新增: # Keep the file read-locked while Windows checks and registers the package.
113新增: $handle = [IO.File]::Open($file.FullName, 'Open', 'Read', 'Read')
114新增: try {
115新增: $version = Get-VerifiedClaudeMsixVersion $file $handle
116新增: $registered = Get-RegisteredClaude
117新增: if ($registered -and [version]$registered.Version -ge $version) { return $registered }
118新增: try { Add-AppxPackage -Path $file.FullName } catch {
119新增: if ($_.Exception.HResult.ToString('X8') -eq '80073D28' -or $_.ToString() -match '\b0x80073D28\b') {
120新增: throw '0x80073D28: The Claude MSIX service requires guest administrator rights. Register it elevated as this guest user, or provision it in the guest image for standard users.'
121新增: }
122新增: throw
123新增: }
124新增: $registered = Get-RegisteredClaude
125新增: if (!$registered -or [version]$registered.Version -lt $version) {
126新增: throw 'Windows did not register the expected version for this user.'
127新增: }
128新增: return $registered
129新增: } finally { $handle.Dispose() }
130新增:}
131新增:
132新增:function Open-ClaudeWindow($registered) {
133新增: if (!$registered) { throw 'Claude Desktop is not registered for this user.' }
134新增: $session = [Diagnostics.Process]::GetCurrentProcess().SessionId
135新增: $shell = Get-Process -Name explorer -ErrorAction SilentlyContinue | Where-Object SessionId -eq $session
136新增: if ($session -eq 0 -or !$shell -or ![Environment]::UserInteractive) {
137新增: throw 'Launch requires a signed-in desktop session. Open PowerShell in the guest console.'
138新增: }
139新增: $explorer = Join-Path ([Environment]::GetFolderPath('Windows')) 'explorer.exe'
140新增: Start-Process -FilePath $explorer -ArgumentList ('shell:AppsFolder\' + $registered.Aumid)
141新增: $timer = [Diagnostics.Stopwatch]::StartNew()
142新增: do {
143新增: $window = Get-Process -Name Claude -ErrorAction SilentlyContinue | Where-Object {
144新增: $_.SessionId -eq $session -and $_.MainWindowHandle -ne 0 -and $_.Path -eq $registered.Executable
145新增: } | Select-Object -First 1
146新增: if ($window) {
147新增: return [pscustomobject]@{ Aumid = $registered.Aumid; WindowProcessId = $window.Id }
148新增: }
149新增: Start-Sleep -Milliseconds 400
150新增: } while ($timer.Elapsed.TotalSeconds -lt 30)
151新增: throw 'Activation was requested, but no window from the registered Claude executable appeared within 30 seconds.'
152新增:}
153新增:
154新增:if ($MyInvocation.InvocationName -eq '.') { return } # Allow isolated validation tests to load the checks.
155新增:if ([Environment]::OSVersion.Platform -ne 'Win32NT' -or ![Environment]::Is64BitProcess) {
156新增: throw 'Run this script in 64-bit Windows PowerShell.'
157新增:}
158新增:if ($Action -ne 'Install' -and $MsixPath) { throw 'Only Install accepts -MsixPath.' }
159新增:if ($Action -ne 'Inspect') { Assert-TargetGuest $ExpectedVMId }
160新增:switch ($Action) {
161新增: 'Inspect' {
162新增: $registered = Get-RegisteredClaude
163新增: if (!$registered) { $registered = [pscustomobject]@{ Registered = $false } }
164新增: $registered | ConvertTo-Json
165新增: }
166新增: 'Install' { Install-ClaudeMsix $MsixPath | ConvertTo-Json }
167新增: 'Launch' { Open-ClaudeWindow (Get-RegisteredClaude) | ConvertTo-Json }
168新增:}
新增scripts/guest-os/claude-desktop-windows.tests.ps1+101 −0看文件
@@ -0,0 +1,101 @@
1新增:#requires -Version 5.1
2新增:# Run on any platform with PowerShell. The tests never call Windows deployment APIs.
3新增:$ErrorActionPreference = 'Stop'
4新增:. (Join-Path $PSScriptRoot 'claude-desktop-windows.ps1')
5新增:
6新增:function Expect-Failure([scriptblock]$action, [string]$reason) {
7新增: try { & $action } catch {
8新增: if ($_.Exception.Message.Contains($reason)) { return }
9新增: throw
10新增: }
11新增: throw "Expected rejection: $reason"
12新增:}
13新增:
14新增:$subject = [Security.Cryptography.X509Certificates.X500DistinguishedName]::new($publisher)
15新增:$signature = [pscustomobject]@{ Status = 'Valid'; SignerCertificate = @{ SubjectName = $subject } }
16新增:Assert-ClaudeSignature $signature
17新增:$signature.Status = 'HashMismatch'
18新增:Expect-Failure { Assert-ClaudeSignature $signature } 'did not validate'
19新增:$signature.Status = 'Valid'
20新增:$lookalike = $publisher.Replace('4860621', '1234567')
21新增:$signature.SignerCertificate.SubjectName = [Security.Cryptography.X509Certificates.X500DistinguishedName]::new($lookalike)
22新增:Expect-Failure { Assert-ClaudeSignature $signature } 'does not match'
23新增:
24新增:$manifest = [xml]@'
25新增:<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10">
26新增: <Identity Name="Claude" Version="4.23118.0.0" ProcessorArchitecture="x64"/>
27新增: <Applications>
28新增: <Application Id="SshProxy" Executable="app\resources\claude-ssh-proxy.exe"/>
29新增: <Application Id="Claude" Executable="app\Claude.exe" EntryPoint="Windows.FullTrustApplication"/>
30新增: </Applications>
31新增:</Package>
32新增:'@
33新增:$manifest.Package.Identity.SetAttribute('Publisher', $publisher)
34新增:if ((Assert-ClaudeManifest $manifest) -ne [version]'4.23118.0.0') { throw 'Version mismatch.' }
35新增:$wrongApp = $manifest.Clone()
36新增:$wrongApp.Package.Applications.Application[1].SetAttribute('Executable', 'app\helper.exe')
37新增:Expect-Failure { Assert-ClaudeManifest $wrongApp } 'entry point'
38新增:
39新增:function Get-AppxPackage { $pkg }
40新增:function Get-AppxPackageManifest { $manifest }
41新增:$pkg = [pscustomobject]@{
42新增: PackageFamilyName = 'OtherFamily'; IsDevelopmentMode = $false; IsPartiallyStaged = $false
43新增: SignatureKind = 'Developer'; Status = 'Ok'; Publisher = $publisher
44新增: PackageFullName = 'test-fixture'; InstallLocation = $PSScriptRoot
45新增:}
46新增:if (Get-RegisteredClaude) { throw 'An unrelated package was accepted.' }
47新增:$pkg.PackageFamilyName = $packageFamily
48新增:if ((Get-RegisteredClaude).Aumid -cne 'Claude_pzs8sxrjxfjjc!Claude') { throw 'Incorrect AUMID.' }
49新增:$pkg.IsDevelopmentMode = $true
50新增:Expect-Failure { Get-RegisteredClaude } 'registered Claude package'
51新增:
52新增:# Execute the actual install path against a local archive. Mock just the
53新增:# operating-system signature and registration results, never deploy this fixture.
54新增:$fixture = Join-Path ([IO.Path]::GetTempPath()) (([Guid]::NewGuid().ToString()) + '.msix')
55新增:$installedCount = 0
56新增:function Get-AuthenticodeSignature { $signature }
57新增:function Add-AppxPackage {
58新增: if ($deploymentError) { throw $deploymentError }
59新增: $script:installedCount++
60新增: $script:pkg.PackageFamilyName = $packageFamily
61新增:}
62新增:try {
63新增: Add-Type -AssemblyName System.IO.Compression
64新增: $handle = [IO.File]::Open($fixture, 'CreateNew', 'Write', 'None')
65新增: try {
66新增: $zip = [IO.Compression.ZipArchive]::new($handle, 'Create', $true)
67新增: try {
68新增: $stream = $zip.CreateEntry('AppxManifest.xml').Open()
69新增: try { $manifest.Save($stream) } finally { $stream.Dispose() }
70新增: } finally { $zip.Dispose() }
71新增: } finally { $handle.Dispose() }
72新增: $signature.Status = 'NotSigned'
73新增: Expect-Failure { Install-ClaudeMsix $fixture } 'did not validate'
74新增: $signature.Status = 'Valid'
75新增: Expect-Failure { Install-ClaudeMsix $fixture } 'does not match'
76新增: if ($installedCount -ne 0) { throw 'An untrusted package reached Add-AppxPackage.' }
77新增: $signature.SignerCertificate.SubjectName = $subject
78新增: $pkg.IsDevelopmentMode = $false
79新增: $pkg.PackageFamilyName = 'absent'
80新增: $deploymentError = 'Deployment failed: 0x80073D28'
81新增: Expect-Failure { Install-ClaudeMsix $fixture } 'requires guest administrator rights'
82新增: $deploymentError = 'Deployment failed: 0x80073CF6'
83新增: Expect-Failure { Install-ClaudeMsix $fixture } '0x80073CF6'
84新增: $deploymentError = $null
85新增: $first = Install-ClaudeMsix $fixture
86新增: $again = Install-ClaudeMsix $fixture
87新增: if (!$first.Registered -or !$again.Registered -or $installedCount -ne 1) {
88新增: throw 'Expected exactly one registration after two Install actions.'
89新增: }
90新增:} finally { if ([IO.File]::Exists($fixture)) { [IO.File]::Delete($fixture) } }
91新增:
92新增:$target = [Guid]::NewGuid()
93新增:$kvpId = $target.ToString()
94新增:$computer = @{ Manufacturer = 'Microsoft Corporation'; Model = 'Virtual Machine' }
95新增:function Get-CimInstance { $computer }
96新增:function Get-ItemProperty { @{ VirtualMachineId = $kvpId } }
97新增:Assert-TargetGuest $target
98新增:Expect-Failure { Assert-TargetGuest ([Guid]::NewGuid()) } 'does not match'
99新增:$computer.Model = 'Surface'
100新增:Expect-Failure { Assert-TargetGuest $target } 'requires a Hyper-V guest'
101新增:Write-Output 'Passed Claude manifest, signing, repeat install, registration and Hyper-V guest identity checks (simulated).'
新增scripts/guest-os/claude-window-macos.swift+140 −0看文件
@@ -0,0 +1,140 @@
1新增:// Capture one visible Claude Desktop window to stdout inside a Cage macOS VM.
2新增:// Build with swiftc -parse-as-library -target arm64-apple-macos14.0.
3新增:import AppKit
4新增:import ImageIO
5新增:import ScreenCaptureKit
6新增:import Security
7新增:import UniformTypeIdentifiers
8新增:
9新增:private let bundleID = "com.anthropic.claudefordesktop"
10新增:
11新增:struct Failure: Error {
12新增: let code: Int32
13新增: let message: String
14新增: init(_ code: Int32, _ message: String) {
15新增: self.code = code
16新增: self.message = message
17新增: }
18新增:}
19新增:
20新增:func requireGuest() throws {
21新增: var model = [CChar](repeating: 0, count: 256)
22新增: var count = model.count
23新增: guard sysctlbyname("hw.model", &model, &count, nil, 0) == 0,
24新增: String(cString: model).range(of: #"^VirtualMac[0-9]+,[0-9]+$"#, options: .regularExpression) != nil else {
25新增: throw Failure(2, "not_cage_guest: Run inside a Cage virtual Mac.")
26新增: }
27新增: let fd = open("/var/db/cage-guest-os", O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
28新增: guard fd >= 0 else { throw Failure(2, "not_cage_guest: Missing guest marker.") }
29新增: let marker = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
30新增: var metadata = stat()
31新增: guard fstat(fd, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFREG,
32新增: metadata.st_uid == 0, metadata.st_mode & 0o022 == 0,
33新增: (5...6).contains(metadata.st_size),
34新增: let bytes = try marker.read(upToCount: 6), [Data("macos".utf8), Data("macos\n".utf8)].contains(bytes) else {
35新增: throw Failure(2, "not_cage_guest: Invalid guest marker.")
36新增: }
37新增:}
38新增:
39新增:func claudeSigningRequirement() throws -> SecRequirement {
40新增: let expression = #"anchor apple generic and identifier "com.anthropic.claudefordesktop" and certificate leaf[subject.OU] = "Q6L2SF6YDW" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"#
41新增: var requirement: SecRequirement?
42新增: guard SecRequirementCreateWithString(expression as CFString, [], &requirement) == errSecSuccess, let requirement else {
43新增: throw Failure(5, "identity_error: Could not construct the Claude signing requirement.")
44新增: }
45新增: return requirement
46新增:}
47新增:
48新增:func claudePIDs() throws -> Set<pid_t> {
49新增: var console = stat()
50新增: var attributes: SessionAttributeBits = []
51新增: guard lstat("/dev/console", &console) == 0, console.st_uid >= 500, console.st_uid == geteuid(),
52新增: SessionGetInfo(callerSecuritySession, nil, &attributes) == errSecSuccess,
53新增: attributes.contains(.sessionHasGraphicAccess) else {
54新增: throw Failure(4, "requires_gui_login: Run as the logged-in guest desktop user in their GUI session.")
55新增: }
56新增: let path = URL(fileURLWithPath: "/Applications/Claude.app").resolvingSymlinksInPath()
57新增: let apps = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).filter {
58新增: $0.bundleURL?.resolvingSymlinksInPath() == path && !$0.isTerminated
59新增: }
60新增: guard !apps.isEmpty else { throw Failure(3, "not_running: Launch /Applications/Claude.app in the guest.") }
61新增: let requirement = try claudeSigningRequirement()
62新增: let validPIDs = apps.compactMap { app -> pid_t? in
63新增: let attributes = [kSecGuestAttributePid: app.processIdentifier] as CFDictionary
64新增: var code: SecCode?
65新增: guard SecCodeCopyGuestWithAttributes(nil, attributes, [], &code) == errSecSuccess, let code,
66新增: SecCodeCheckValidity(code, [], requirement) == errSecSuccess else { return nil }
67新增: return app.processIdentifier
68新增: }
69新增: guard !validPIDs.isEmpty else { throw Failure(5, "identity_error: The running app failed Anthropic signature verification.") }
70新增: return Set(validPIDs)
71新增:}
72新增:
73新增:func claudeWindow() async throws -> SCWindow {
74新增: try requireGuest()
75新增: let pids = try claudePIDs()
76新增: guard CGPreflightScreenCaptureAccess() else {
77新增: throw Failure(6, "screen_recording_permission: Authorize this capture tool in the guest's Privacy & Security settings.")
78新增: }
79新增: let content = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true)
80新增: let windows = content.windows.filter { window in
81新增: guard window.isOnScreen, window.windowLayer == 0, !window.frame.isEmpty,
82新增: let owner = window.owningApplication else { return false }
83新增: return owner.bundleIdentifier == bundleID && pids.contains(owner.processID)
84新增: }
85新增: guard let window = windows.max(by: { $0.frame.width * $0.frame.height < $1.frame.width * $1.frame.height }) else {
86新增: throw Failure(7, "no_visible_window: Open a Claude window on the guest desktop.")
87新增: }
88新增: return window
89新增:}
90新增:
91新增:func screenshot(_ window: SCWindow, filter selected: SCContentFilter? = nil) async throws -> Data {
92新增: let filter = selected ?? SCContentFilter(desktopIndependentWindow: window)
93新增: let config = SCStreamConfiguration()
94新增: config.width = max(1, Int((filter.contentRect.width * CGFloat(filter.pointPixelScale)).rounded()))
95新增: config.height = max(1, Int((filter.contentRect.height * CGFloat(filter.pointPixelScale)).rounded()))
96新增: config.ignoreShadowsSingleWindow = true
97新增: config.showsCursor = false
98新增: if #available(macOS 14.2, *) { config.includeChildWindows = false }
99新增: let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config)
100新增: return try pngData(image)
101新增:}
102新增:
103新增:func pngData(_ image: CGImage) throws -> Data {
104新增: try encodedImage(image, type: .png)
105新增:}
106新增:
107新增:func encodedImage(_ image: CGImage, type: UTType, properties: CFDictionary? = nil) throws -> Data {
108新增: let data = NSMutableData()
109新增: guard let encoder = CGImageDestinationCreateWithData(data, type.identifier as CFString, 1, nil) else {
110新增: throw Failure(8, "capture_failed: Could not create an image encoder.")
111新增: }
112新增: CGImageDestinationAddImage(encoder, image, properties)
113新增: guard CGImageDestinationFinalize(encoder) else { throw Failure(8, "capture_failed: Could not encode the window.") }
114新增: return data as Data
115新增:}
116新增:
117新增:#if !GUEST_WINDOW_APP
118新增:@main
119新增:struct ClaudeWindow {
120新增: static func main() async {
121新增: do {
122新增: let png = try await screenshot(claudeWindow())
123新增: try FileHandle.standardOutput.write(contentsOf: png)
124新增: } catch {
125新增: let failure: Failure
126新增: if let known = error as? Failure {
127新增: failure = known
128新增: } else if (error as NSError).domain == SCStreamErrorDomain &&
129新增: (error as NSError).code == SCStreamError.userDeclined.rawValue {
130新增: failure = Failure(6, "screen_recording_permission: The guest user declined screen capture.")
131新增: } else {
132新增: failure = Failure(8, "capture_failed: \(error.localizedDescription)")
133新增: }
134新增: FileHandle.standardError.write(Data("\(failure.message)\n".utf8))
135新增: exit(failure.code)
136新增: }
137新增: }
138新增:}
139新增:
140新增:#endif
新增scripts/guest-os/claude-window-windows.ps1+160 −0看文件
@@ -0,0 +1,160 @@
1新增:#requires -Version 5.1
2新增:<#
3新增:.SYNOPSIS
4新增:Save one PNG of the signed-in guest user's registered Claude Desktop window.
5新增:.DESCRIPTION
6新增:Run in 64-bit Windows PowerShell in an unlocked Hyper-V guest desktop session.
7新增:Pass the VM ID obtained independently on the host. OutputPath must name a new
8新增:.png directly inside this guest user's temporary directory. A failed capture
9新增:does not publish a PNG.
10新增:#>
11新增:[CmdletBinding()]
12新增:param([Guid]$ExpectedVMId = [Guid]::Empty, [string]$OutputPath)
13新增:$ErrorActionPreference = 'Stop'
14新增:. (Join-Path $PSScriptRoot 'claude-desktop-windows.ps1') -ExpectedVMId $ExpectedVMId
15新增:
16新增:$cageWindowSource = @'
17新增:using System;
18新增:using System.Collections.Generic;
19新增:using System.Drawing;
20新增:using System.Drawing.Imaging;
21新增:using System.IO;
22新增:using System.Runtime.InteropServices;
23新增:using System.Text;
24新增:using System.Threading.Tasks;
25新增:
26新增:public static class CageClaudeWindow {
27新增: [StructLayout(LayoutKind.Sequential)]
28新增: private struct Rect { public int left, top, right, bottom; }
29新增:
30新增: [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr window);
31新增: [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr window);
32新增: [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr window, out Rect rect);
33新增: [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window, out uint process);
34新增: [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags);
35新增: [DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr window, int attr, out int value, int bytes);
36新增: [DllImport("user32.dll")] private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
37新增: [DllImport("user32.dll")] private static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access);
38新增: [DllImport("user32.dll")] private static extern bool CloseDesktop(IntPtr desktop);
39新增: [DllImport("user32.dll", CharSet=CharSet.Unicode)]
40新增: private static extern bool GetUserObjectInformation(IntPtr obj, int index, StringBuilder name, int size, out int needed);
41新增:
42新增: public static bool IsDefaultInputDesktop() {
43新增: IntPtr desktop = OpenInputDesktop(0, false, 1); // DESKTOP_READOBJECTS
44新增: if (desktop == IntPtr.Zero) return false;
45新增: try {
46新增: var name = new StringBuilder(256);
47新增: int needed;
48新增: return GetUserObjectInformation(desktop, 2, name, name.Capacity * 2, out needed)
49新增: && String.Equals(name.ToString(), "Default", StringComparison.OrdinalIgnoreCase);
50新增: } finally { CloseDesktop(desktop); }
51新增: }
52新增:
53新增: private static bool IsClaudeWindow(IntPtr window, uint pid) {
54新增: uint owner;
55新增: int cloaked;
56新增: return GetWindowThreadProcessId(window, out owner) != 0 && owner == pid
57新增: && IsWindowVisible(window) && !IsIconic(window)
58新增: && DwmGetWindowAttribute(window, 14, out cloaked, 4) == 0 && cloaked == 0;
59新增: }
60新增:
61新增: public static string FrameProblem(int[] rgb) {
62新增: if (rgb.Length == 0) return "empty_frame";
63新增: int first = rgb[0];
64新增: bool black = true, varied = false;
65新增: foreach (int pixel in rgb) {
66新增: for (int shift = 0; shift <= 16; shift += 8) {
67新增: int value = (pixel >> shift) & 255;
68新增: if (value > 4) black = false;
69新增: if (Math.Abs(value - ((first >> shift) & 255)) > 4) varied = true;
70新增: }
71新增: }
72新增: return black ? "black_frame" : (varied ? null : "uniform_frame");
73新增: }
74新增:
75新增: private static byte[] Capture(IntPtr window, uint pid) {
76新增: if (!IsClaudeWindow(window, pid)) throw new InvalidOperationException("no_visible_window");
77新增: IntPtr previousDpi = SetThreadDpiAwarenessContext(new IntPtr(-4)); // Per-monitor aware V2
78新增: try {
79新增: Rect bounds;
80新增: if (!GetClientRect(window, out bounds) || bounds.right <= 0 || bounds.bottom <= 0)
81新增: throw new InvalidOperationException("no_visible_window");
82新增: using (var bitmap = new Bitmap(bounds.right, bounds.bottom, PixelFormat.Format24bppRgb)) {
83新增: using (var graphics = Graphics.FromImage(bitmap)) {
84新增: graphics.Clear(Color.Black);
85新增: IntPtr dc = graphics.GetHdc();
86新增: try {
87新增: // PW_CLIENTONLY | PW_RENDERFULLCONTENT, also used by Chromium
88新增: // for its DirectComposition windows. Never read the desktop DC.
89新增: if (!PrintWindow(window, dc, 3)) throw new InvalidOperationException("window_render_failed");
90新增: } finally { graphics.ReleaseHdc(dc); }
91新增: }
92新增: if (!IsClaudeWindow(window, pid) || !IsDefaultInputDesktop())
93新增: throw new InvalidOperationException("window_or_desktop_changed_during_capture");
94新增: var samples = new List<int>();
95新增: for (int y = bitmap.Height / 20; y < bitmap.Height - bitmap.Height / 20; y += Math.Max(1, bitmap.Height / 128))
96新增: for (int x = bitmap.Width / 20; x < bitmap.Width - bitmap.Width / 20; x += Math.Max(1, bitmap.Width / 128))
97新增: samples.Add(bitmap.GetPixel(x, y).ToArgb());
98新增: var problem = FrameProblem(samples.ToArray());
99新增: if (problem != null) throw new InvalidOperationException(problem);
100新增: using (var png = new MemoryStream()) {
101新增: bitmap.Save(png, ImageFormat.Png);
102新增: return png.ToArray();
103新增: }
104新增: }
105新增: } finally { if (previousDpi != IntPtr.Zero) SetThreadDpiAwarenessContext(previousDpi); }
106新增: }
107新增:
108新增: public static byte[] CaptureWithTimeout(IntPtr window, uint pid) {
109新增: // PrintWindow waits synchronously for the window owner. A late render
110新增: // has no filesystem side effects and cannot publish a stale PNG.
111新增: var task = Task.Run(() => Capture(window, pid));
112新增: if (Task.WaitAny(new Task[] { task }, 10000) < 0) throw new TimeoutException("window_render_timeout");
113新增: return task.GetAwaiter().GetResult();
114新增: }
115新增:}
116新增:'@
117新增:
118新增:function Get-ClaudeCapturePath([string]$path) {
119新增: if (!$path -or ![IO.Path]::IsPathRooted($path)) { throw 'Supply an absolute guest temporary .png path.' }
120新增: $full = [IO.Path]::GetFullPath($path)
121新增: $temp = [IO.Path]::GetTempPath().TrimEnd([IO.Path]::DirectorySeparatorChar)
122新增: if ([IO.Path]::GetDirectoryName($full) -ine $temp -or [IO.Path]::GetExtension($full) -ine '.png' -or
123新增: [IO.Path]::GetFileName($full).IndexOfAny([IO.Path]::GetInvalidFileNameChars()) -ge 0) {
124新增: throw 'OutputPath must be a PNG directly inside this guest user''s temporary directory.'
125新增: }
126新增: if (Test-Path -LiteralPath $full) { throw 'Select a new PNG path.' }
127新增: if ([Environment]::OSVersion.Platform -eq 'Win32NT' -and
128新增: [IO.DriveInfo]::new([IO.Path]::GetPathRoot($full)).DriveType -ne 'Fixed') {
129新增: throw 'Use the guest user''s local temporary drive.'
130新增: }
131新增: return $full
132新增:}
133新增:
134新增:if ($MyInvocation.InvocationName -eq '.') { return }
135新增:if ([Environment]::OSVersion.Platform -ne 'Win32NT' -or ![Environment]::Is64BitProcess -or $PSVersionTable.PSEdition -ne 'Desktop') {
136新增: throw 'Run this script in 64-bit Windows PowerShell 5.1 inside the guest.'
137新增:}
138新增:Assert-TargetGuest $ExpectedVMId
139新增:$file = Get-ClaudeCapturePath $OutputPath
140新增:$session = [Diagnostics.Process]::GetCurrentProcess().SessionId
141新增:if ($session -eq 0 -or ![Environment]::UserInteractive -or
142新增: !(Get-Process -Name explorer -ErrorAction SilentlyContinue | Where-Object SessionId -eq $session)) {
143新增: throw 'requires_gui_login: Run in the signed-in guest user''s desktop session.'
144新增:}
145新增:if (!('CageClaudeWindow' -as [type])) { Add-Type -TypeDefinition $cageWindowSource -ReferencedAssemblies System.Drawing }
146新增:if (![CageClaudeWindow]::IsDefaultInputDesktop()) { throw 'requires_gui_login: Unlock the guest desktop.' }
147新增:$registered = Get-RegisteredClaude
148新增:if (!$registered) { throw 'not_registered: Install the official x64 Claude MSIX for this guest user.' }
149新增:$target = Get-Process -Name Claude -ErrorAction SilentlyContinue | Where-Object {
150新增: $_.SessionId -eq $session -and $_.MainWindowHandle -ne 0 -and $_.Path -eq $registered.Executable
151新增:} | Select-Object -First 1
152新增:if (!$target) { throw 'no_visible_window: Open Claude Desktop for this guest user.' }
153新增:$png = [CageClaudeWindow]::CaptureWithTimeout($target.MainWindowHandle, $target.Id)
154新增:$staged = Join-Path ([IO.Path]::GetDirectoryName($file)) ([IO.Path]::GetRandomFileName())
155新增:$stream = [IO.File]::Open($staged, 'CreateNew', 'Write', 'None')
156新增:try {
157新增: try { $stream.Write($png, 0, $png.Length) } finally { $stream.Dispose() }
158新增: [IO.File]::Move($staged, $file)
159新增:} finally { [IO.File]::Delete($staged) }
160新增:[pscustomobject]@{ Path = $file; Bytes = $png.Length; ProcessId = $target.Id; Version = $registered.Version } | ConvertTo-Json
新增scripts/guest-os/claude-window-windows.tests.ps1+32 −0看文件
@@ -0,0 +1,32 @@
1新增:#requires -Version 5.1
2新增:# Test frame rejection and output handling without accessing any desktop.
3新增:$ErrorActionPreference = 'Stop'
4新增:. (Join-Path $PSScriptRoot 'claude-window-windows.ps1')
5新增:
6新增:if ($PSVersionTable.PSEdition -eq 'Desktop') {
7新增: Add-Type -TypeDefinition $cageWindowSource -ReferencedAssemblies System.Drawing
8新增:} else {
9新增: $references = @((Get-ChildItem "$PSHOME/ref/*.dll").FullName) + @([Drawing.Bitmap].Assembly.Location)
10新增: $references += @((Get-ChildItem "$PSHOME/System.Private.Windows.*.dll").FullName)
11新增: Add-Type -TypeDefinition $cageWindowSource -ReferencedAssemblies $references
12新增:}
13新增:
14新增:if ([CageClaudeWindow]::FrameProblem([int[]]@()) -ne 'empty_frame' -or
15新增: [CageClaudeWindow]::FrameProblem([int[]]@(0, 0x010204)) -ne 'black_frame' -or
16新增: [CageClaudeWindow]::FrameProblem([int[]]@(0xFAFAFA, 0xFBFBFB)) -ne 'uniform_frame' -or
17新增: [CageClaudeWindow]::FrameProblem([int[]]@(0xFAFAFA, 0x111111))) {
18新增: throw 'Blank or nonuniform frame classification failed.'
19新增:}
20新增:
21新增:$output = Join-Path ([IO.Path]::GetTempPath()) ("cage-window-" + [guid]::NewGuid() + ".png")
22新增:if ((Get-ClaudeCapturePath $output) -ne [IO.Path]::GetFullPath($output)) { throw 'Failed to accept a temporary PNG.' }
23新增:try {
24新增: [IO.File]::WriteAllText($output, 'preserve')
25新增: foreach ($bad in @($output, "$output.txt", [IO.Path]::Combine([IO.Path]::GetDirectoryName($output), '..', 'outside.png'))) {
26新增: $rejected = $false
27新增: try { $null = Get-ClaudeCapturePath $bad } catch { $rejected = $true }
28新增: if (!$rejected) { throw "Accepted invalid output: $bad" }
29新增: }
30新增: if ([IO.File]::ReadAllText($output) -cne 'preserve') { throw 'Existing output was changed.' }
31新增:} finally { [IO.File]::Delete($output) }
32新增:Write-Output 'Passed simulated Claude window frame and output-path checks.'
新增scripts/guest-os/complete-windows-guest.ps1+322 −0看文件
@@ -0,0 +1,322 @@
1新增:#requires -Version 5.1
2新增:#requires -RunAsAdministrator
3新增:[CmdletBinding()]
4新增:param(
5新增: [Parameter(Mandatory)][guid]$VMId,
6新增: [Parameter(Mandatory)][string]$InstanceDirectory,
7新增: [Parameter(Mandatory)][string]$HostProfileDirectory,
8新增: [pscredential]$GuestAdministrator,
9新增: [string]$HostUserSID = ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value),
10新增: [string]$StateDirectory,
11新增: [string]$ManifestPath,
12新增: [string]$ManifestSHA256,
13新增: [object]$HostEnrollment
14新增:)
15新增:$ErrorActionPreference = 'Stop'
16新增:$ProgressPreference = 'SilentlyContinue'
17新增:$payload = Join-Path $PSScriptRoot 'payload'
18新增:$bridgeScripts = Join-Path $PSScriptRoot 'guest-clipboard-windows'
19新增:$componentManifest=$null
20新增:if ($ManifestPath) {
21新增: $manifestFile=Get-Item -LiteralPath $ManifestPath -Force
22新增: if ($ManifestSHA256 -notmatch '^[a-fA-F0-9]{64}$' -or $manifestFile -isnot [IO.FileInfo] -or $manifestFile.Length -gt 4MB -or
23新增: $manifestFile.Attributes -band [IO.FileAttributes]::ReparsePoint -or (Get-FileHash -LiteralPath $ManifestPath).Hash -ne $ManifestSHA256) {
24新增: throw '组件清单无法核验,请从 Cage 重新继续安装。'
25新增: }
26新增: $componentManifest=Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json
27新增: if ($componentManifest.protocol -ne 1 -or $componentManifest.system -cne 'windows-11' -or $componentManifest.revision -notmatch '^[a-f0-9]{64}$') { throw '原生组件清单无效。' }
28新增: $kitRoot=[IO.Path]::GetFullPath($PSScriptRoot).TrimEnd('\')+'\'
29新增: foreach ($entry in $componentManifest.files) {
30新增: $source=[IO.Path]::GetFullPath((Join-Path $kitRoot $entry.source))
31新增: if (!$source.StartsWith($kitRoot,[StringComparison]::OrdinalIgnoreCase) -or (Get-FileHash -LiteralPath $source).Hash -ne $entry.sha256) {
32新增: throw '当前应用组件包已变化,请重新继续安装。'
33新增: }
34新增: }
35新增:}
36新增:
37新增:function Get-LocalDirectory([string]$Path) {
38新增: $dir = Get-Item -LiteralPath $Path -Force
39新增: if ($dir -isnot [IO.DirectoryInfo] -or $dir.FullName.StartsWith('\\') -or
40新增: [IO.DriveInfo]::new($dir.Root.FullName).DriveType -ne 'Fixed') { throw 'A local fixed-disk directory is required.' }
41新增: for ($parent=$dir; $parent; $parent=$parent.Parent) {
42新增: if ($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'The installation path crosses a filesystem link.' }
43新增: }
44新增: return $dir.FullName
45新增:}
46新增:
47新增:. (Join-Path $PSScriptRoot 'windows-workbench-packages.ps1')
48新增:. (Join-Path $PSScriptRoot 'windows-host-image.ps1')
49新增:
50新增:function Read-CageBinding([string]$Path) {
51新增: $item=Get-Item -LiteralPath $Path -Force
52新增: if ($item -isnot [IO.FileInfo] -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint -or $item.Length -gt 16384) { throw 'Invalid existing Windows guest binding.' }
53新增: $data=Get-Content -LiteralPath $item.FullName -Raw | ConvertFrom-Json
54新增: if ($data.version -ne 1 -or [guid]$data.vm_id -ne $VMId -or $data.instance_directory -ne $instance -or
55新增: $data.relay_executable -ne (Join-Path $pairDirectory 'Cage.GuestClipboard.exe') -or
56新增: $data.pairing_file -ne (Join-Path $pairDirectory 'pairing.dpapi') -or
57新增: ($data.network_pairing_file -and $data.network_pairing_file -ne (Join-Path $pairDirectory 'packet.dpapi'))) {
58新增: throw 'A different guest is already bound. Its disk and pairing were preserved.'
59新增: }
60新增: return $data
61新增:}
62新增:
63新增:# The current package's own relay performs the proof, regardless of the path
64新增:# stored in the staged profile. A cold bridge may need a few seconds after its
65新增:# logon task restarts. Never turn a missing registration into a ready profile.
66新增:function Ensure-HostManager {
67新增: $manager=Join-Path $payload 'Cage.HyperVManager.exe'
68新增: if(!(Test-Path -LiteralPath $manager -PathType Leaf)){throw 'The complete Windows host-manager payload is required.'}
69新增: & (Join-Path $PSScriptRoot 'install-windows-host-manager.ps1') -VMId $VMId -HostSID $HostUserSID -PayloadExecutable $manager -PayloadSHA256 (Get-FileHash -LiteralPath $manager -Algorithm SHA256).Hash -Confirm:$false | Out-Null
70新增:}
71新增:
72新增:function Restore-MissingHostEnrollmentKeys($Binding) {
73新增: if(!$HostEnrollment){return}
74新增: . (Join-Path $PSScriptRoot 'windows-host-enrollment.ps1')
75新增: foreach($kind in @('gui','packet')){
76新增: $path=if($kind -ceq 'gui'){$Binding.pairing_file}else{$Binding.network_pairing_file}
77新增: if(!$path -or (Test-Path -LiteralPath $path)){continue}
78新增: # Only this fresh VM's fixed Cage keys are recovered. Existing host
79新增: # DPAPI bytes and model credentials are never replaced or read here.
80新增: $key=Invoke-Command -Session $session -ArgumentList $VMId,$Binding.gui_user_sid,$kind -ScriptBlock {
81新增: param($expected,$sid,$kind)
82新增: if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'}
83新增: $name=if($kind -ceq 'gui'){'GuestBridge'}else{'GuestNetwork'}
84新增: $file=if($kind -ceq 'gui'){'pairing.bin'}else{'packet.bin'}
85新增: $path=Join-Path (Join-Path (Join-Path $env:ProgramData 'Cage') $name) ($expected.ToString('D')+'\'+$file)
86新增: $item=Get-Item -LiteralPath $path -Force
87新增: if($item -isnot [IO.FileInfo] -or $item.Length -ne 32 -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'fresh_pairing_invalid'}
88新增: [IO.File]::ReadAllBytes($path)
89新增: }
90新增: $bytes=[byte[]]$key
91新增: try{if($bytes.Length -ne 32){throw 'The retained fresh Cage pairing is invalid.'};Send-CageHostEnrollmentKey $HostEnrollment $kind $Binding.gui_user_sid $bytes}finally{[Array]::Clear($bytes,0,$bytes.Length)}
92新增: }
93新增:}
94新增:
95新增:function Complete-CloneSetup([string]$Binding) {
96新增: if ($choice.source.host.system -cne 'windows-11') { return }
97新增: $answerPath = Join-Path $instance 'windows-guest-tools.iso'
98新增: $vm | Hyper-V\Get-VMDvdDrive | Where-Object Path -eq $answerPath | Hyper-V\Remove-VMDvdDrive
99新增: [IO.File]::Delete($answerPath)
100新增: Remove-CageSetupCredential $VMId $GuestAdministrator $profile $installID $Binding
101新增:}
102新增:
103新增:function Publish-ReadyBinding {
104新增: $binding=Read-CageBinding $stageBinding
105新增: if (!$binding.network_pairing_file) { throw 'The protected packet pairing is unavailable.' }
106新增: if($HostEnrollment){
107新增: Ensure-HostManager
108新增: . (Join-Path $PSScriptRoot 'windows-host-enrollment.ps1')
109新增: Complete-CloneSetup $stageBinding
110新增: Complete-CageHostEnrollment $HostEnrollment $binding.gui_user_sid
111新增: return
112新增: }
113新增: $relay=Join-Path $payload 'Cage.GuestClipboard.exe'
114新增: $deadline=[DateTime]::UtcNow.AddSeconds(30)
115新增: $ready=$false
116新增: do {
117新增: # Windows PowerShell 5.1 turns native stderr into a terminating error
118新增: # under Stop, even when redirected. A cold relay must reach the retry.
119新增: $savedPreference=$ErrorActionPreference
120新增: try { $ErrorActionPreference='Continue'; $raw=& $relay --relay-profile $stageBinding status 2>$null }
121新增: finally { $ErrorActionPreference=$savedPreference }
122新增: if ($LASTEXITCODE -eq 0 -and $raw) {
123新增: $state=$raw | ConvertFrom-Json
124新增: if ($state.available -and [guid]$state.vm_id -eq $VMId -and $state.gui_user_sid -eq $binding.gui_user_sid -and
125新增: $state.browser.installed -and $state.browser.editor_installed -and
126新增: $state.capabilities -contains 'cli' -and $state.capabilities -contains 'project-mount' -and $state.capabilities -contains 'desktop') {
127新增: try { $ErrorActionPreference='Continue'; $raw='{"action":"status"}' | & $relay --relay-profile $stageBinding desktop 2>$null }
128新增: finally { $ErrorActionPreference=$savedPreference }
129新增: if ($LASTEXITCODE -eq 0 -and $raw -and ($raw | ConvertFrom-Json).installed) { $ready=$true; break }
130新增: }
131新增: }
132新增: Start-Sleep -Seconds 1
133新增: } while ([DateTime]::UtcNow -lt $deadline)
134新增: if (!$ready) { throw 'Sign out and sign back in to the paired standard guest account to finish Windows app registration. Resume setup from Cage.' }
135新增: # The ordinary host controller uses only this protected fixed-VM service.
136新增: # Host identity is distinct from the GUI account inside the Windows guest.
137新增: Ensure-HostManager
138新增: # Complete retirement before exposing a ready profile. The staged pairing
139新增: # proves an already retired account when a prior publish was interrupted.
140新增: Complete-CloneSetup $stageBinding
141新增: $tempBinding=Join-Path $profile ('windows-guest.'+[guid]::NewGuid()+'.tmp')
142新增: try {
143新增: [IO.File]::Copy($stageBinding,$tempBinding,$false)
144新增: Set-Acl -LiteralPath $tempBinding -AclObject (Get-Acl -LiteralPath $stageBinding)
145新增: [IO.File]::Move($tempBinding,$finalBinding)
146新增: } finally { if ([IO.File]::Exists($tempBinding)) { [IO.File]::Delete($tempBinding) } }
147新增:}
148新增:
149新增:$instance=Get-LocalDirectory $InstanceDirectory
150新增:$profile=Get-LocalDirectory $HostProfileDirectory
151新增:$null=Get-LocalDirectory $payload
152新增:$choice=Get-Content -LiteralPath (Join-Path $profile 'guest-install.json') -Raw | ConvertFrom-Json
153新增:$installID=[guid]$choice.id
154新增:$anchor=Get-Item -LiteralPath (Join-Path $profile 'state') -Force
155新增:if(!$StateDirectory){$StateDirectory=if($anchor.Attributes -band [IO.FileAttributes]::ReparsePoint){$targets=@($anchor.Target);if($targets.Count -ne 1){throw 'The selected physical state directory changed.'};$targets[0]}else{$anchor.FullName}}
156新增:$physicalState=Get-LocalDirectory $StateDirectory
157新增:if($anchor.Attributes -band [IO.FileAttributes]::ReparsePoint){$targets=@($anchor.Target);if($targets.Count -ne 1 -or [IO.Path]::GetFullPath($targets[0]) -ine $physicalState){throw 'The selected physical state directory changed.'}}
158新增:elseif($anchor.FullName -ine $physicalState){throw 'The selected physical state directory changed.'}
159新增:if ($installID -eq [guid]::Empty -or $choice.system -ne 'windows-11' -or $choice.editor_terms -ne $true -or
160新增: [guid][IO.File]::ReadAllText((Join-Path $profile 'windows-install-vm.txt')) -ne $VMId -or
161新增: $instance -ine (Join-Path $physicalState ('windows-'+$installID.ToString('N')))) {
162新增: throw 'Automatic boot sign-in is restricted to the new VM in this first-run installation.'
163新增:}
164新增:if($HostEnrollment -and ($HostEnrollment.HostSID -cne $HostUserSID -or [guid]$HostEnrollment.VMID -ne $VMId -or [guid]$HostEnrollment.InstallationID -ne $installID -or
165新增: [IO.Path]::GetFullPath($HostEnrollment.Profile) -ine $profile -or [IO.Path]::GetFullPath($HostEnrollment.State) -ine $physicalState)){throw 'Original user enrollment does not match this fixed installation.'}
166新增:$vm=Hyper-V\Get-VM -Id $VMId
167新增:if ($VMId -eq [guid]::Empty -or $vm.Name -cne ('Cage-'+$installID.ToString('N')) -or $vm.Id -ne $VMId -or $vm.State -ne 'Running' -or $vm.Generation -ne 2 -or
168新增: !($vm.ConfigurationLocation -eq $instance -or $vm.ConfigurationLocation.StartsWith($instance.TrimEnd('\')+'\',[StringComparison]::OrdinalIgnoreCase)) -or
169新增: @(Hyper-V\Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or @($vm | Hyper-V\Get-VMHardDiskDrive).Count -ne 1 -or
170新增: ($vm | Hyper-V\Get-VMHardDiskDrive).Path -ne (Join-Path $instance 'system.vhdx')) {
171新增: throw 'Start the selected, isolated Windows guest and finish Windows Setup in its console.'
172新增:}
173新增:
174新增:$workRoot=Join-Path $instance 'cage-workbench'
175新增:$pairDirectory=Join-Path $workRoot 'pair'
176新增:$stageBinding=Join-Path $pairDirectory 'windows-guest.json'
177新增:$completionMarker=Join-Path $pairDirectory 'workbench-components-ready'
178新增:$finalBinding=Join-Path $profile 'windows-guest.json'
179新增:if (Test-Path -LiteralPath $finalBinding) {
180新增: $existing=Read-CageBinding $finalBinding
181新增: if (!$existing.network_pairing_file) { throw 'The existing published profile is missing its network pairing.' }
182新增: if (Test-Path -LiteralPath (Join-Path $profile ('windows-setup-'+$installID.ToString('N')+'.dpapi'))) {
183新增: Complete-CloneSetup $finalBinding
184新增: }
185新增: Ensure-HostManager
186新增: return
187新增:}
188新增:if([Security.Principal.WindowsIdentity]::GetCurrent().User.Value -cne $HostUserSID -and !$HostEnrollment){throw 'Fresh setup for another host user requires the original user enrollment process.'}
189新增:
190新增:$null=New-Item -ItemType Directory -Force $workRoot
191新增:$null=Get-LocalDirectory $workRoot
192新增:$lockPath=Join-Path $workRoot 'setup.lock'
193新增:if ((Test-Path -LiteralPath $lockPath) -and ((Get-Item -LiteralPath $lockPath -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Invalid setup lock.' }
194新增:$lock=[IO.File]::Open($lockPath,'OpenOrCreate','ReadWrite','None')
195新增:$session=$null
196新增:$scratch=$null
197新增:try {
198新增: if ((Test-Path -LiteralPath $completionMarker) -and (Test-Path -LiteralPath $stageBinding)) {
199新增: Publish-ReadyBinding
200新增: return
201新增: }
202新增: if (!$GuestAdministrator) { $GuestAdministrator=Get-Credential -Message 'Cage: enter an administrator account of the selected virtual Windows machine.' }
203新增: if (!$GuestAdministrator) { throw 'Windows guest setup canceled.' }
204新增: $session=New-PSSession -VMId $VMId -Credential $GuestAdministrator
205新增: $target=Invoke-Command -Session $session -FilePath (Join-Path $PSScriptRoot 'initialize-windows-workbench-user.ps1') -ArgumentList $VMId
206新增: $firstBoot=Join-Path $pairDirectory 'first-account-boot'
207新增: if (!$target.AlreadySignedIn -and (Test-Path -LiteralPath $firstBoot) -and [IO.File]::ReadAllText($firstBoot) -ne $target.BootID) {
208新增: throw 'The guest has rebooted. Wait for the dedicated workbench account to sign in, or use the Windows sign-in screen if it was manually locked.'
209新增: }
210新增:
211新增: if (Test-Path -LiteralPath $stageBinding) {
212新增: $staged=Read-CageBinding $stageBinding
213新增: if ($staged.gui_user_sid -ne $target.SID) { throw 'Sign in to the already paired Windows guest account to resume.' }
214新增: }
215新增: $cache=Join-Path $workRoot 'downloads'
216新增: $null=New-Item -ItemType Directory -Force $cache
217新增: $null=Get-LocalDirectory $cache
218新增: $packages=Get-Content -LiteralPath (Join-Path $payload 'windows-workbench-packages.json') -Raw | ConvertFrom-Json
219新增: $cli=Get-Content -LiteralPath (Join-Path $payload 'cli-dependencies.json') -Raw | ConvertFrom-Json
220新增: $files=@{}
221新增: foreach ($spec in @($packages.PSObject.Properties)+@($cli.PSObject.Properties)) {
222新增: $files[$spec.Name]=Get-PinnedPackage $spec.Value $cache
223新增: }
224新增:
225新增: $scratch=Join-Path $workRoot ('stage-'+[guid]::NewGuid())
226新增: $null=New-Item -ItemType Directory $scratch
227新增: $core=Join-Path $scratch 'core'
228新增: $null=New-Item -ItemType Directory $core
229新增: foreach ($name in @('Cage.GuestClipboard.exe','cage-guest-files.exe','cage-guest-boot.exe')) { Copy-Item -LiteralPath (Join-Path $payload $name) -Destination $core }
230新增: if (!(Test-Path -LiteralPath $stageBinding)) {
231新增: $null=& (Join-Path $bridgeScripts 'install.ps1') -VMId $VMId -InstanceDirectory $instance -GUIUserSID $target.SID -GuestAdministrator $GuestAdministrator -PayloadDirectory $core -HostProfileDirectory $pairDirectory -HostUserSID $HostUserSID -HostEnrollment $HostEnrollment -Confirm:$false
232新增: }
233新增: $staged=Read-CageBinding $stageBinding
234新增: if ($staged.gui_user_sid -ne $target.SID) { throw 'The staged bridge belongs to another user.' }
235新增:
236新增: Add-Type -AssemblyName System.IO.Compression.FileSystem
237新增: if (!$staged.network_pairing_file) {
238新增: $driver=Join-Path $scratch 'driver'
239新增: [IO.Compression.ZipFile]::ExtractToDirectory($files.wintun,$driver)
240新增: $null=& (Join-Path $bridgeScripts 'install-network.ps1') -ProfilePath $stageBinding -GuestAdministrator $GuestAdministrator -AgentPath (Join-Path $core 'Cage.GuestClipboard.exe') -WintunPath (Join-Path $driver 'wintun/bin/amd64/wintun.dll') -WintunLicense (Join-Path $driver 'wintun/LICENSE.txt') -HostEnrollment $HostEnrollment -Confirm:$false
241新增: }
242新增: $staged=Read-CageBinding $stageBinding
243新增: Restore-MissingHostEnrollmentKeys $staged
244新增:
245新增: $extras=Join-Path $scratch 'extras'
246新增: $null=New-Item -ItemType Directory $extras
247新增: foreach ($name in @('modules','split-extension','windows-browser.mjs','windows-browser-extensions.mjs','windows-phone-browser.mjs','install-windows-workbench-user-tools.ps1','install-cli.ps1','cli-dependencies.json')) {
248新增: Copy-Item -LiteralPath (Join-Path $payload $name) -Destination $extras -Recurse
249新增: }
250新增: if ($componentManifest) {
251新增: foreach ($entry in $componentManifest.files) {
252新增: if (!$entry.target -or !$entry.target.StartsWith('bridge/')) { continue }
253新增: $relative=$entry.target.Substring(7)
254新增: if ($relative -in @('Cage.GuestClipboard.exe','cage-guest-files.exe','cage-guest-boot.exe')) { continue }
255新增: if ($entry.source -cne ('payload/'+$relative) -or $relative -match '(^|/)\.\.?(/|$)|[:\\]') { throw '组件安装位置无效。' }
256新增: $targetFile=Join-Path $extras $relative
257新增: $null=New-Item -ItemType Directory -Path ([IO.Path]::GetDirectoryName($targetFile)) -Force
258新增: Copy-Item -LiteralPath (Join-Path $PSScriptRoot $entry.source) -Destination $targetFile -Force
259新增: if ((Get-FileHash -LiteralPath $targetFile).Hash -ne $entry.installed_sha256) { throw '复制后的组件摘要不匹配。' }
260新增: }
261新增: }
262新增: $nodeArchive=[IO.Compression.ZipFile]::OpenRead($files.node)
263新增: try { [IO.Compression.ZipFileExtensions]::ExtractToFile($nodeArchive.GetEntry('node-v24.22.2-win-x64/node.exe'),(Join-Path $extras 'node.exe')) } finally { $nodeArchive.Dispose() }
264新增: Expand-PinnedTar $files.playwright (Join-Path $extras 'playwright')
265新增: Expand-PinnedTar $files.playwrightCore (Join-Path $extras 'playwright/node_modules/playwright-core')
266新增: [IO.Compression.ZipFile]::ExtractToDirectory($files.editorCLI,(Join-Path $extras 'vscode-cli'))
267新增: Expand-PinnedTar $files.editorServer (Join-Path $extras 'vscode-server')
268新增: [IO.File]::WriteAllText((Join-Path $extras 'editor-runtime.json'),'{"commit":"261c84cb1eddf11235f9e2c921425e9663fbe556"}')
269新增: [IO.File]::WriteAllText((Join-Path $extras 'guest-config.json'),'{"network_mode":"packet"}')
270新增: # Transfer large trees in one archive over the authenticated VM session.
271新增: $zipPath=Join-Path $scratch 'extras.zip'
272新增: & (Join-Path $env:SystemRoot 'System32/tar.exe') -a -cf $zipPath -C $extras .
273新增: if ($LASTEXITCODE -ne 0) { throw 'Could not stage the guest application archive.' }
274新增: $guestStage=Invoke-Command -Session $session -ArgumentList $target.Program -ScriptBlock {
275新增: param($program)
276新增: $path=Join-Path $program 'setup-packages'
277新增: if (Test-Path -LiteralPath $path) { if ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Invalid protected staging directory.' } }
278新增: else { $null=New-Item -ItemType Directory $path }
279新增: $path
280新增: }
281新增: foreach ($file in @($zipPath,$files.desktop,$files.winfsp,$files.sshfs,$files.uv,$files.python,$files.claude,$files.git)) {
282新增: Copy-Item -LiteralPath $file -Destination $guestStage -ToSession $session -Force
283新增: }
284新增: $installer=Join-Path $PSScriptRoot 'install-windows-workbench-components.ps1'
285新增: $options=@($VMId,$target.SID,$target.Program,$guestStage,($packages | ConvertTo-Json -Depth 6 -Compress),($cli | ConvertTo-Json -Depth 6 -Compress),(Get-FileHash -LiteralPath $zipPath).Hash)
286新增: $null=Invoke-Command -Session $session -FilePath $installer -ArgumentList ($options+@('Prepare'))
287新增: if (!$target.AlreadySignedIn) {
288新增: # Only this named new VM is rebooted, once. A later manual lock is
289新增: # never treated as a request to restart or unlock Windows.
290新增: [IO.File]::WriteAllText($firstBoot,$target.BootID)
291新增: Remove-PSSession $session; $session=$null
292新增: Hyper-V\Stop-VM -VM $vm -ErrorAction Stop
293新增: Hyper-V\Start-VM -VM $vm -ErrorAction Stop
294新增: $deadline=[DateTime]::UtcNow.AddMinutes(4)
295新增: do {
296新增: try {
297新增: $session=New-PSSession -VMId $VMId -Credential $GuestAdministrator -ErrorAction Stop
298新增: $logged=Invoke-Command -Session $session -ArgumentList $VMId,$target.Name -ScriptBlock {
299新增: param($expected,$name)
300新增: if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected) {throw 'wrong VM'}
301新增: (Get-CimInstance Win32_ComputerSystem).UserName -eq ($env:COMPUTERNAME+'\'+$name)
302新增: }
303新增: if ($logged) {break}
304新增: } catch { $logged=$false }
305新增: if ($session) { Remove-PSSession $session; $session=$null }
306新增: Start-Sleep -Seconds 2
307新增: } while ([DateTime]::UtcNow -lt $deadline)
308新增: if (!$session -or !$logged) { throw 'Windows did not finish its first sign-in to the dedicated workbench account. Its account and disk are preserved.' }
309新增: }
310新增: $null=Invoke-Command -Session $session -FilePath $installer -ArgumentList ($options+@('UserTools'))
311新增: if (@(Hyper-V\Get-VMNetworkAdapter -VM (Hyper-V\Get-VM -Id $VMId)).Count -ne 0) { throw 'The Windows guest networking has changed.' }
312新增: if ($componentManifest) {
313新增: $null=Invoke-Command -Session $session -FilePath (Join-Path $PSScriptRoot 'publish-windows-component-manifest.ps1') -ArgumentList $VMId,$target.SID,($componentManifest|ConvertTo-Json -Depth 8 -Compress)
314新增: }
315新增:
316新增: [IO.File]::WriteAllText($completionMarker,$target.SID)
317新增: Publish-ReadyBinding
318新增:} finally {
319新增: if ($session) { Remove-PSSession $session }
320新增: if ($scratch -and (Test-Path -LiteralPath $scratch)) { Remove-Item -LiteralPath $scratch -Recurse -Force }
321新增: $lock.Dispose()
322新增:}
新增scripts/guest-os/configure-macos-session.sh+75 −0看文件
@@ -0,0 +1,75 @@
1新增:#!/bin/bash
2新增:# Root configures only the installer-bound ordinary account inside a Cage VM.
3新增:set -euo pipefail
4新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin
5新增:[[ $# == 2 && $EUID == 0 && $(uname -sm) == 'Darwin arm64' && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]]
6新增:user=$1
7新增:installation=$2
8新增:[[ $user == cage ]]
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新增:receipt=/var/db/cage-initial-setup/account.json
11新增:[[ -f $receipt && ! -L $receipt && $(stat -f %u "$receipt") == 0 && $(plutil -extract installation raw "$receipt") == "$installation" ]]
12新增:phase=$(plutil -extract state raw "$receipt")
13新增:[[ $phase == ready ]]
14新增:[[ $(dscl . -read /Users/$user NFSHomeDirectory) == "NFSHomeDirectory: /Users/$user" && " $(id -Gn "$user") " != *' admin '* ]]
15新增:IFS= read -r password
16新增:[[ -n $password ]]
17新增:printf '%s\n' "$password" | dscl /Local/Default -authonly "$user" >/dev/null
18新增:# FileVault prevents system automatic login; retain its protection and report it.
19新增:if fdesetup status | grep -q 'FileVault is On'; then
20新增: echo 'FileVault 已启用,请使用客机密码登录。' >&2
21新增: exit 1
22新增:fi
23新增:existing=$(defaults read /Library/Preferences/com.apple.loginwindow autoLoginUser 2>/dev/null || true)
24新增:[[ -z $existing || $existing == "$user" ]]
25新增:umask 077
26新增:tmp=$(mktemp /etc/cage-autologin.XXXXXXXX)
27新增:trap 'rm -f "$tmp"' EXIT
28新增:# macOS's system auto-login record is reversible and root-readable. The host
29新增:# copy is separately encrypted with the Cage account key. No password argument.
30新增:printf '%s\n' "$password" | /usr/bin/perl -e '
31新增: use strict; use warnings;
32新增: my $password = <STDIN>; chomp $password;
33新增: my @key = (0x7d,0x89,0x52,0x23,0xd2,0xbc,0xdd,0xea,0xa3,0xb9,0x1f);
34新增: my $plain = $password . "\0";
35新增: $plain .= "\0" while length($plain) % 12;
36新增: print pack("C*", map { ord(substr($plain,$_,1)) ^ $key[$_ % @key] } 0..length($plain)-1);
37新增:' > "$tmp"
38新增:unset password
39新增:[[ ! -L /etc/kcpassword ]]
40新增:chmod 600 "$tmp"
41新增:mv -f "$tmp" /etc/kcpassword
42新增:defaults write /Library/Preferences/com.apple.loginwindow autoLoginUser -string "$user"
43新增:defaults write /Library/Preferences/com.apple.loginwindow autoLoginUserUID -int "$(id -u "$user")"
44新增:# Match Lima's first-login suppression for the ordinary account. Its generated
45新增:# plist contains the current OS build/version stamps and no credentials.
46新增:provision=cageprovision
47新增:source=/Users/$provision/Library/Preferences/com.apple.SetupAssistant.plist
48新增:if [[ -f $source && ! -L $source ]]; then
49新增: cat "$source" | sudo -Hu "$user" /bin/bash -ec '
50新增: umask 077
51新增: mkdir -p "$HOME/Library/Preferences"
52新增: target="$HOME/Library/Preferences/com.apple.SetupAssistant.plist"
53新增: [[ ! -L $target ]]
54新增: cat > "$target"
55新增: plutil -lint "$target" >/dev/null
56新增: '
57新增:fi
58新增:# Write the current OS stamps directly through the account's preference service.
59新增:sudo -Hu "$user" /bin/bash -ec '
60新增: domain=com.apple.SetupAssistant
61新增: version=$(sw_vers -productVersion)
62新增: build=$(sw_vers -buildVersion)
63新增: for key in DidSeeAccessibility DidSeeActivationLock DidSeeAppStore DidSeeAppearanceSetup DidSeeApplePaySetup DidSeeCloudSetup DidSeeLockdownMode DidSeePrivacy DidSeeScreenTime DidSeeSetupSequence DidSeeSiriSetup DidSeeSyncSetup DidSeeSyncSetup2 DidSeeTermsOfAddress DidSeeTouchIDSetup DidSeeiCloudLoginForStorageServices SkipExpressSettingsUpdating SkipFirstLoginOptimization; do
64新增: defaults write "$domain" "$key" -bool true
65新增: done
66新增: for key in LastPreLoginTasksPerformedBuild LastSeenBuddyBuildVersion; do defaults write "$domain" "$key" -string "$build"; done
67新增: for key in LastPreLoginTasksPerformedVersion LastSeenAgeRangeSelectionProductVersion LastSeenCloudProductVersion LastSeenDiagnosticsProductVersion; do defaults write "$domain" "$key" -string "$version"; done
68新增: defaults write "$domain" MiniBuddyLaunchReason -int 0
69新增: defaults write "$domain" MiniBuddyShouldLaunchToResumeSetup -bool false
70新增: defaults -currentHost write com.apple.screensaver idleTime -int 0
71新增:'
72新增:# Cage owns guest lifetime; the hidden desktop should not sleep while the
73新增:# workbench is running. These settings affect only this virtual Mac.
74新增:pmset -a sleep 0 displaysleep 0
75新增:echo '客机自动登录与首次设置已准备。'
新增scripts/guest-os/guest-clipboard-macos.swift+785 −0看文件
@@ -0,0 +1,785 @@
1新增:// Per-user GUI clipboard agent and its private SSH client for a Cage macOS guest.
2新增:import AppKit
3新增:import ApplicationServices
4新增:import ImageIO
5新增:import Security
6新增:import UniformTypeIdentifiers
7新增:
8新增:private let wireLimit = 30 * 1024 * 1024
9新增:private let textLimit = 2 * 1024 * 1024
10新增:private let imageLimit = 20 * 1024 * 1024
11新增:private let label = "dev.cage.GuestClipboard"
12新增:
13新增:private struct ClipboardFailure: Error {
14新增: let reason: String
15新增: init(_ reason: String) { self.reason = reason }
16新增:}
17新增:
18新增:private func requireGuest() throws {
19新增: var model = [CChar](repeating: 0, count: 256), size = 256
20新增: guard sysctlbyname("hw.model", &model, &size, nil, 0) == 0,
21新增: String(cString: model).range(of: #"^VirtualMac[0-9]+,[0-9]+$"#, options: .regularExpression) != nil,
22新增: getuid() >= 500 else { throw ClipboardFailure("not_guest") }
23新增: let fd = open("/var/db/cage-guest-os", O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
24新增: guard fd >= 0 else { throw ClipboardFailure("not_guest") }
25新增: defer { close(fd) }
26新增: var info = stat()
27新增: guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == 0,
28新增: info.st_mode & 0o022 == 0, (5...6).contains(info.st_size) else { throw ClipboardFailure("not_guest") }
29新增: let data = try FileHandle(fileDescriptor: fd, closeOnDealloc: false).read(upToCount: 6) ?? Data()
30新增: guard [Data("macos".utf8), Data("macos\n".utf8)].contains(data) else { throw ClipboardFailure("not_guest") }
31新增:}
32新增:
33新增:private func guiAvailable() -> Bool {
34新增: var info = stat(), attributes: SessionAttributeBits = []
35新增: return stat("/dev/console", &info) == 0 && info.st_uid == getuid() && info.st_uid >= 500 &&
36新增: SessionGetInfo(callerSecuritySession, nil, &attributes) == errSecSuccess && attributes.contains(.sessionHasGraphicAccess) &&
37新增: (CGSessionCopyCurrentDictionary() as? [String: Any])?["CGSSessionScreenIsLocked"] as? Bool != true
38新增:}
39新增:
40新增:private func onGUI<T>(_ body: () throws -> T) rethrows -> T {
41新增: if Thread.isMainThread { return try body() }
42新增: return try DispatchQueue.main.sync(execute: body)
43新增:}
44新增:
45新增:private func writeAll(_ fd: Int32, _ data: Data) throws {
46新增: try data.withUnsafeBytes { bytes in
47新增: var position = 0
48新增: while position < bytes.count {
49新增: let count = Darwin.write(fd, bytes.baseAddress!.advanced(by: position), bytes.count - position)
50新增: if count < 0 && errno == EINTR { continue }
51新增: guard count > 0 else { throw ClipboardFailure("connection_closed") }
52新增: position += count
53新增: }
54新增: }
55新增:}
56新增:
57新增:private final class Reader {
58新增: let fd: Int32
59新增: private var buffer = Data()
60新增: init(_ fd: Int32) { self.fd = fd }
61新增: func line(limit: Int = wireLimit) throws -> Data? {
62新增: while true {
63新增: if let newline = buffer.firstIndex(of: 10) {
64新增: let value = Data(buffer[..<newline])
65新增: buffer.removeSubrange(...newline)
66新增: guard value.count <= limit else { throw ClipboardFailure("message_too_large") }
67新增: return value
68新增: }
69新增: guard buffer.count <= limit else { throw ClipboardFailure("message_too_large") }
70新增: var bytes = [UInt8](repeating: 0, count: min(65536, limit + 1 - buffer.count))
71新增: let count = Darwin.read(fd, &bytes, bytes.count)
72新增: if count < 0 && errno == EINTR { continue }
73新增: if count == 0 { if buffer.isEmpty { return nil }; throw ClipboardFailure("incomplete_message") }
74新增: guard count > 0 else { throw ClipboardFailure("connection_closed") }
75新增: buffer.append(contentsOf: bytes.prefix(count))
76新增: }
77新增: }
78新增: func exact(_ length: Int) throws -> Data {
79新增: var output = Data()
80新增: if !buffer.isEmpty {
81新增: let count = min(length, buffer.count)
82新增: output.append(buffer.prefix(count)); buffer.removeFirst(count)
83新增: }
84新增: while output.count < length {
85新增: var bytes = [UInt8](repeating: 0, count: min(65536, length - output.count))
86新增: let count = Darwin.read(fd, &bytes, bytes.count)
87新增: if count < 0 && errno == EINTR { continue }
88新增: guard count > 0 else { throw ClipboardFailure("incomplete_message") }
89新增: output.append(contentsOf: bytes.prefix(count))
90新增: }
91新增: return output
92新增: }
93新增: func copy(to output: FileHandle) throws {
94新增: if !buffer.isEmpty { try output.write(contentsOf: buffer); buffer.removeAll() }
95新增: while true {
96新增: var bytes = [UInt8](repeating: 0, count: 65536)
97新增: let count = Darwin.read(fd, &bytes, bytes.count)
98新增: if count < 0 && errno == EINTR { continue }
99新增: if count == 0 { return }
100新增: guard count > 0 else { throw ClipboardFailure("connection_closed") }
101新增: try output.write(contentsOf: Data(bytes.prefix(count)))
102新增: }
103新增: }
104新增:}
105新增:
106新增:private func json(_ data: Data) throws -> [String: Any] {
107新增: guard let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw ClipboardFailure("invalid_message") }
108新增: return value
109新增:}
110新增:
111新增:private func jsonData(_ value: [String: Any]) throws -> Data {
112新增: var data = try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])
113新增: guard data.count <= wireLimit else { throw ClipboardFailure("message_too_large") }
114新增: data.append(10)
115新增: return data
116新增:}
117新增:
118新增:private func paths(_ value: Any?) throws -> [String] {
119新增: guard let values = value as? [String], (1...100).contains(values.count) else { throw ClipboardFailure("invalid_files") }
120新增: for path in values {
121新增: guard path.hasPrefix("/"), !path.contains("\0"), URL(fileURLWithPath: path).standardizedFileURL.path == path else { throw ClipboardFailure("invalid_files") }
122新增: }
123新增: return values
124新增:}
125新增:
126新增:private func image(_ data: Data, requirePNG: Bool = false) throws -> CGImage {
127新增: if requirePNG {
128新增: guard data.count <= imageLimit, data.starts(with: [137, 80, 78, 71, 13, 10, 26, 10]) else { throw ClipboardFailure("invalid_image") }
129新增: }
130新增: guard let source = CGImageSourceCreateWithData(data as CFData, nil),
131新增: let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
132新增: let width = properties[kCGImagePropertyPixelWidth] as? Int, let height = properties[kCGImagePropertyPixelHeight] as? Int,
133新增: width > 0, height > 0, width <= 40_000_000 / height,
134新增: let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw ClipboardFailure("invalid_image") }
135新增: return image
136新增:}
137新增:
138新增:private func png(_ image: CGImage) throws -> Data {
139新增: let data = NSMutableData()
140新增: guard let output = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil) else { throw ClipboardFailure("invalid_image") }
141新增: CGImageDestinationAddImage(output, image, nil)
142新增: guard CGImageDestinationFinalize(output), data.length <= imageLimit else { throw ClipboardFailure("image_too_large") }
143新增: return data as Data
144新增:}
145新增:
146新增:private func boardContent(_ board: NSPasteboard) throws -> [String: Any] {
147新增: if let urls = board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty {
148新增: guard urls.allSatisfy({ $0.isFileURL && ($0.host == nil || $0.host == "" || $0.host == "localhost") }) else { throw ClipboardFailure("invalid_files") }
149新增: return ["files": try paths(urls.map(\.path))]
150新增: }
151新增: if let value = board.data(forType: .png) {
152新增: _ = try image(value, requirePNG: true)
153新增: return ["png": value.base64EncodedString()]
154新增: }
155新增: if let value = board.data(forType: .tiff) { return ["png": try png(image(value)).base64EncodedString()] }
156新增: let value = board.string(forType: .string) ?? ""
157新增: guard value.utf8.count <= textLimit else { throw ClipboardFailure("text_too_large") }
158新增: return ["text": value]
159新增:}
160新增:
161新增:private func setBoard(_ board: NSPasteboard, _ value: [String: Any]) throws {
162新增: if let text = value["text"] as? String {
163新增: guard text.utf8.count <= textLimit else { throw ClipboardFailure("text_too_large") }
164新增: board.clearContents()
165新增: guard board.setString(text, forType: .string) else { throw ClipboardFailure("clipboard_write_failed") }
166新增: } else if value["png"] != nil {
167新增: guard let encoded = value["png"] as? String, let data = Data(base64Encoded: encoded) else { throw ClipboardFailure("invalid_image") }
168新增: let bitmap = try image(data, requirePNG: true)
169新增: let native = NSImage(cgImage: bitmap, size: .zero)
170新增: board.clearContents()
171新增: guard board.writeObjects([native]) else { throw ClipboardFailure("clipboard_write_failed") }
172新增: } else {
173新增: let files = try paths(value["files"])
174新增: board.clearContents()
175新增: guard board.writeObjects(files.map { NSURL(fileURLWithPath: $0) }) else { throw ClipboardFailure("clipboard_write_failed") }
176新增: }
177新增:}
178新增:
179新增:private final class Stream: @unchecked Sendable {
180新增: private struct Snapshot { let data: Data; let completed: (Bool) -> Void }
181新增: let fd: Int32
182新增: private let outputLock = NSLock()
183新增: private let stateLock = NSLock()
184新增: private var closed = false
185新增: private var publishing = false
186新增: private var pending: Snapshot?
187新增: var initialized = false // GUI-thread owned
188新增: init(_ fd: Int32) { self.fd = fd }
189新增: func send(_ value: [String: Any]) throws {
190新增: try sendData(jsonData(value))
191新增: }
192新增: private func sendData(_ data: Data) throws {
193新增: outputLock.lock(); defer { outputLock.unlock() }
194新增: stateLock.lock(); let ended = closed; stateLock.unlock()
195新增: guard !ended else { throw ClipboardFailure("connection_closed") }
196新增: try writeAll(fd, data)
197新增: }
198新增: // Keep only the latest unsent snapshot. A slow client cannot block the GUI
199新增: // thread or accumulate a queue of full-resolution clipboard images.
200新增: func publish(_ value: [String: Any], completed: @escaping (Bool) -> Void = { _ in }) {
201新增: guard let data = try? jsonData(value) else { completed(false); return }
202新增: stateLock.lock()
203新增: guard !closed else { stateLock.unlock(); completed(false); return }
204新增: let superseded = pending
205新增: pending = Snapshot(data: data, completed: completed)
206新增: let start = !publishing
207新增: publishing = true
208新增: stateLock.unlock()
209新增: superseded?.completed(false)
210新增: guard start else { return }
211新增: DispatchQueue.global(qos: .userInitiated).async {
212新增: while true {
213新增: self.stateLock.lock()
214新增: guard let next = self.pending, !self.closed else {
215新增: self.publishing = false; self.stateLock.unlock(); return
216新增: }
217新增: self.pending = nil
218新增: self.stateLock.unlock()
219新增: do { try self.sendData(next.data); next.completed(true) }
220新增: catch { next.completed(false); self.close(); return }
221新增: }
222新增: }
223新增: }
224新增: func close() {
225新增: outputLock.lock()
226新增: stateLock.lock()
227新增: let discarded = pending
228新增: if !closed { closed = true; pending = nil; shutdown(fd, SHUT_RDWR) }
229新增: stateLock.unlock()
230新增: outputLock.unlock()
231新增: discarded?.completed(false)
232新增: }
233新增:}
234新增:
235新增:private final class SnapshotDelivery: @unchecked Sendable {
236新增: var remaining: Int
237新增: var published = false
238新增: init(_ count: Int) { remaining = count }
239新增:}
240新增:
241新增:private final class ClipboardAgent: @unchecked Sendable {
242新增: private var streams: [Int32: Stream] = [:]
243新增: private var records: [[String]] = []
244新增: private var known = Set<String>()
245新增: private var owned = Set<String>()
246新增: private struct CachedCopy { let id: String; let paths: [String]; var pinned: Bool; let clipboard: Bool }
247新增: private var copies: [String: CachedCopy] = [:]
248新增: private var fileReaders: [UUID: [String]] = [:]
249新增: private var copiesLoaded = false
250新增: private var collectingCopies = false
251新增: private var copiesNeedCollection = false
252新增: private let cacheQueue = DispatchQueue(label: "cage.clipboard.cache")
253新增: private var session = UUID().uuidString.lowercased()
254新增: private let board: NSPasteboard
255新增: private let gui: () -> Bool
256新增: private let diagnostic: (String) -> Void
257新增: private var available: Bool
258新增: private var revision: Int
259新增: private var snapshotPending = false
260新增: private var transfers: [UUID: Process] = [:]
261新增: private let helper: URL
262新增: init(board: NSPasteboard = .general, gui: @escaping () -> Bool = guiAvailable,
263新增: diagnostic: @escaping (String) -> Void = { GuestDiagnostic.record("clipboard", $0) }) {
264新增: self.board = board
265新增: self.gui = gui
266新增: self.diagnostic = diagnostic
267新增: available = gui()
268新增: revision = board.changeCount
269新增: helper = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/cage-guest-files")
270新增: }
271新增: private func check(_ expectedSession: String? = nil) throws {
272新增: guard gui(), available, expectedSession == nil || expectedSession == session else { throw ClipboardFailure("requires_gui_login") }
273新增: guard FileManager.default.isExecutableFile(atPath: helper.path) else { throw ClipboardFailure("files_helper_missing") }
274新增: }
275新增: private func hello() -> [String: Any] {
276新增: let gui = self.gui()
277新增: let files = FileManager.default.isExecutableFile(atPath: helper.path)
278新增: return ["hello": ["version": 1, "os": "darwin", "session": session, "formats": ["text", "png", "files"],
279新增: "available": gui && files,
280新增: "file_release": true,
281新增: "reason": !gui ? "requires_gui_login" : (!files ? "files_helper_missing" : "")]]
282新增: }
283新增: private func record(_ files: [String], copied: Bool = false) {
284新增: records.append(files)
285新增: if records.count > 128 { records.removeFirst(); known = Set(records.flatMap { $0 }) }
286新增: else { known.formUnion(files) }
287新增: if copied { owned.formUnion(files) }
288新增: }
289新增: private func cacheControl(_ action: String, id: String = "") throws -> [String: Any] {
290新增: let process = Process(), output = Pipe()
291新增: process.executableURL = helper
292新增: process.arguments = ["cache", String(data: try JSONSerialization.data(withJSONObject: ["action": action, "cache_id": id]), encoding: .utf8)!]
293新增: process.standardInput = FileHandle.nullDevice; process.standardOutput = output; process.standardError = FileHandle.nullDevice
294新增: try process.run()
295新增: let data = try output.fileHandleForReading.readToEnd() ?? Data()
296新增: process.waitUntilExit()
297新增: guard process.terminationStatus == 0, data.count <= 1 << 20 else { throw ClipboardFailure("clipboard_cache_failed") }
298新增: return try json(data)
299新增: }
300新增: private func rememberCopy(_ result: [String: Any], clipboard: Bool) {
301新增: guard let id = result["cache_id"] as? String, let paths = result["paths"] as? [String], !paths.isEmpty else { return }
302新增: copies[id] = CachedCopy(id: id, paths: paths, pinned: true, clipboard: clipboard)
303新增: cacheQueue.async { _ = try? self.cacheControl("publish", id: id) }
304新增: }
305新增: private func retireCopies(_ paths: [String]) {
306新增: let selected = Set(paths)
307新增: for (id, copy) in copies where !selected.isDisjoint(with: copy.paths) { copies[id]?.pinned = false }
308新增: collectCopies()
309新增: }
310新增: private func collectCopies() {
311新增: guard !collectingCopies else { copiesNeedCollection = true; return }
312新增: collectingCopies = true
313新增: cacheQueue.async {
314新增: defer {
315新增: onGUI {
316新增: self.collectingCopies = false
317新增: if self.copiesNeedCollection { self.copiesNeedCollection = false; self.collectCopies() }
318新增: }
319新增: }
320新增: if !onGUI({ self.copiesLoaded }) {
321新增: let previous = try? self.cacheControl("list")
322新增: onGUI {
323新增: self.copiesLoaded = true
324新增: for item in previous?["selections"] as? [[String: Any]] ?? [] {
325新增: if let id = item["cache_id"] as? String, let paths = item["paths"] as? [String], !paths.isEmpty, self.copies[id] == nil {
326新增: self.copies[id] = CachedCopy(id: id, paths: paths, pinned: false, clipboard: true)
327新增: }
328新增: }
329新增: }
330新增: }
331新增: for copy in onGUI({ Array(self.copies.values) }) {
332新增: let retain = onGUI { () -> Bool in
333新增: guard self.copies[copy.id]?.pinned == false else { return true }
334新增: let selected = (self.board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []).map(\.path)
335新增: let root = URL(fileURLWithPath: copy.paths[0]).deletingLastPathComponent().standardizedFileURL.path
336新增: return (selected + self.fileReaders.values.flatMap { $0 }).contains { value in
337新增: let path = URL(fileURLWithPath: value).standardizedFileURL.path
338新增: return path == root || path.hasPrefix(root + "/") || root.hasPrefix(path + "/")
339新增: }
340新增: }
341新增: if retain { continue }
342新增: if (try? self.cacheControl("release", id: copy.id)) != nil {
343新增: onGUI { self.copies.removeValue(forKey: copy.id); self.owned.subtract(copy.paths); self.known.subtract(copy.paths) }
344新增: }
345新增: }
346新增: }
347新增: }
348新增: private func beginTransfer(_ operation: String, input: FileHandle?, name: String? = nil) throws -> (Process, Pipe, UUID, String) {
349新增: let epoch = try onGUI { () -> String in try check(); return session }
350新增: let process = Process(); process.executableURL = helper
351新增: process.arguments = [operation] + (name.map { [$0] } ?? (operation == "import" ? [] : ["--paths-stdin"]))
352新增: let output = Pipe(); process.standardOutput = output; process.standardError = FileHandle.nullDevice
353新增: process.standardInput = input ?? FileHandle.nullDevice
354新增: let id = UUID()
355新增: try onGUI {
356新增: try check(epoch); transfers[id] = process
357新增: do { try process.run() } catch { transfers.removeValue(forKey: id); throw error }
358新增: }
359新增: return (process, output, id, epoch)
360新增: }
361新增: private func finishTransfer(_ process: Process, id: UUID, epoch: String) throws {
362新增: process.waitUntilExit()
363新增: try onGUI { transfers.removeValue(forKey: id); try check(epoch) }
364新增: guard process.terminationStatus == 0 else { throw ClipboardFailure("file_transfer_failed") }
365新增: }
366新增: private func fileJSON(_ operation: String, values: [String]) throws -> [String] {
367新增: let reader = UUID()
368新增: onGUI { fileReaders[reader] = values }
369新增: defer { onGUI { fileReaders.removeValue(forKey: reader); collectCopies() } }
370新增: let input = Pipe()
371新增: let (process, output, id, epoch) = try beginTransfer(operation, input: input.fileHandleForReading)
372新增: defer { try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() }; onGUI { _ = transfers.removeValue(forKey: id) } }
373新增: try input.fileHandleForWriting.write(contentsOf: JSONSerialization.data(withJSONObject: values)); try input.fileHandleForWriting.close()
374新增: let data = try output.fileHandleForReading.readToEnd() ?? Data()
375新增: guard data.count <= 65536 else { throw ClipboardFailure("invalid_files") }
376新增: let response = try json(data)
377新增: let result = try paths(response["paths"])
378新增: onGUI { record(result, copied: true); rememberCopy(response, clipboard: operation == "copy") }
379新增: do { try finishTransfer(process, id: id, epoch: epoch) }
380新增: catch { onGUI { retireCopies(result) }; throw error }
381新增: return result
382新增: }
383新增: private func snapshot() throws -> [String: Any] {
384新增: let (epoch, captured, content) = try onGUI { () -> (String, Int, [String: Any]) in
385新增: try check(); return (session, board.changeCount, try boardContent(board))
386新增: }
387新增: var result = content
388新增: if let selected = content["files"] as? [String] {
389新增: onGUI { record(selected) }
390新增: // File snapshots are frozen in the GUI agent's readable cache.
391新增: result["files"] = try fileJSON("copy", values: selected)
392新增: }
393新增: do { try onGUI { try check(epoch); guard board.changeCount == captured else { throw ClipboardFailure("superseded") } } }
394新增: catch { if let files = result["files"] as? [String] { onGUI { retireCopies(files) } }; throw error }
395新增: result["revision"] = captured
396新增: result["source"] = "guest"
397新增: return result
398新增: }
399新增: private func apply(_ value: [String: Any], echo: Bool) throws -> [String: Any] {
400新增: try onGUI {
401新增: if value["release"] != nil { retireCopies(try paths(value["release"])); return ["released": true] }
402新增: try check()
403新增: if let expected = value["revision"] as? Int, expected != board.changeCount { throw ClipboardFailure("superseded") }
404新增: if value["files"] != nil {
405新增: let selected = try paths(value["files"])
406新增: guard selected.allSatisfy({ known.contains($0) }) else { throw ClipboardFailure("unregistered_files") }
407新增: }
408新增: try setBoard(board, value)
409新增: if !echo { revision = board.changeCount }
410新增: return ["ack": value["serial"] as? Int ?? 0, "revision": board.changeCount]
411新增: }
412新增: }
413新增: private func copiedText(_ request: [String: Any]) throws -> [String: Any] {
414新增: guard let expected = request["revision"] as? Int, let epoch = request["session"] as? String else { throw ClipboardFailure("invalid_copy_request") }
415新增: let deadline = Date().addingTimeInterval(2)
416新增: repeat {
417新增: let value = try onGUI { () -> [String: Any]? in
418新增: try check(epoch)
419新增: let captured = board.changeCount
420新增: guard captured != expected else { return nil }
421新增: guard let text = board.string(forType: .string), text.utf8.count <= textLimit else { throw ClipboardFailure("clipboard_text_unavailable") }
422新增: guard board.changeCount == captured else { return nil }
423新增: return ["text": text, "revision": captured, "session": session]
424新增: }
425新增: if let value { return value }
426新增: Thread.sleep(forTimeInterval: 0.025)
427新增: } while Date() < deadline
428新增: throw ClipboardFailure("clipboard_copy_not_observed")
429新增: }
430新增: func poll() {
431新增: collectCopies()
432新增: let current = gui()
433新增: if current != available {
434新增: available = current; session = UUID().uuidString.lowercased()
435新增: revision = board.changeCount
436新增: if !current { for process in transfers.values where process.isRunning { process.terminate() } }
437新增: // Reconnect under a fresh GUI-session hello. Unsent snapshots from
438新增: // the previous login must not cross the session transition.
439新增: for stream in streams.values { stream.close() }
440新增: }
441新增: guard current, !snapshotPending, streams.values.contains(where: { $0.initialized }), revision != board.changeCount else { return }
442新增: revision = board.changeCount
443新增: snapshotPending = true
444新增: let capturedSession = session
445新增: DispatchQueue.global(qos: .userInitiated).async {
446新增: let result: [String: Any]
447新增: do { result = try self.snapshot() }
448新增: catch { result = (error as? ClipboardFailure)?.reason == "superseded" ? [:] : ["error": (error as? ClipboardFailure)?.reason ?? "clipboard_read_failed"] }
449新增: onGUI {
450新增: self.snapshotPending = false
451新增: guard !result.isEmpty else { return }
452新增: let files = result["files"] as? [String] ?? []
453新增: let recipients = self.streams.values.filter { $0.initialized }
454新增: guard self.session == capturedSession, !recipients.isEmpty else { self.retireCopies(files); return }
455新增: let delivery = SnapshotDelivery(recipients.count)
456新增: for stream in recipients {
457新增: stream.publish(result) { sent in
458新增: DispatchQueue.main.async {
459新增: delivery.remaining -= 1
460新增: delivery.published = delivery.published || sent
461新增: if delivery.remaining == 0 && !delivery.published { self.retireCopies(files) }
462新增: }
463新增: }
464新增: }
465新增: }
466新增: }
467新增: }
468新增: func serve(_ fd: Int32) {
469新增: var stream: Stream?
470新增: defer {
471新增: stream?.close()
472新增: onGUI {
473新增: _ = streams.removeValue(forKey: fd)
474新增: if stream != nil && streams.isEmpty { for (id, copy) in copies where copy.clipboard { copies[id]?.pinned = false }; collectCopies() }
475新增: }
476新增: close(fd)
477新增: }
478新增: var user = uid_t(), group = gid_t()
479新增: guard getpeereid(fd, &user, &group) == 0, user == getuid() else { return }
480新增: var timeout = timeval(tv_sec: 1800, tv_usec: 0)
481新增: setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout)))
482新增: var outputTimeout = timeval(tv_sec: 2, tv_usec: 0)
483新增: setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &outputTimeout, socklen_t(MemoryLayout.size(ofValue: outputTimeout)))
484新增: let reader = Reader(fd)
485新增: do {
486新增: guard let first = try reader.line(), let operation = try json(first)["operation"] as? String else { return }
487新增: let request = try json(first)
488新增: switch operation {
489新增: case "copy-prepare":
490新增: let value = try onGUI { () -> [String: Any] in try check(); return ["revision": board.changeCount, "session": session] }
491新增: try writeAll(fd, jsonData(value))
492新增: case "copy-read":
493新增: try writeAll(fd, jsonData(copiedText(request)))
494新增: case "stream":
495新增: let connection = Stream(fd)
496新增: stream = connection
497新增: onGUI { streams[fd] = connection }
498新增: try connection.send(onGUI { hello() })
499新增: while let line = try reader.line() {
500新增: do {
501新增: let reply = try apply(json(line), echo: false)
502新增: onGUI { connection.initialized = true }
503新增: try connection.send(reply)
504新增: } catch { try connection.send(["error": (error as? ClipboardFailure)?.reason ?? "clipboard_write_failed"]) }
505新增: }
506新增: case "read":
507新增: let value = try snapshot()
508新增: do { try writeAll(fd, jsonData(value)) }
509新增: catch { if let files = value["files"] as? [String] { onGUI { retireCopies(files) } }; throw error }
510新增: case "write":
511新增: try writeAll(fd, jsonData(apply(request, echo: true)))
512新增: case "prepare-files":
513新增: let selected = try paths(request["files"])
514新增: try onGUI { try check(); guard selected.allSatisfy({ owned.contains($0) && known.contains($0) }) else { throw ClipboardFailure("unregistered_files") } }
515新增: let copied = try fileJSON("link-cached", values: selected)
516新增: do { try writeAll(fd, jsonData(["paths": copied])) }
517新增: catch { onGUI { retireCopies(copied) }; throw error }
518新增: case "discard":
519新增: let selected = try paths(request["files"])
520新增: try onGUI {
521新增: guard selected.allSatisfy({ owned.contains($0) }) else { throw ClipboardFailure("unregistered_files") }
522新增: retireCopies(selected)
523新增: let tracked = Set(copies.values.flatMap(\.paths))
524新增: for file in selected where !tracked.contains(file) {
525新增: try? FileManager.default.removeItem(atPath: file)
526新增: owned.remove(file); known.remove(file)
527新增: // Remove only an empty cache directory owned by this transfer.
528新增: _ = rmdir((file as NSString).deletingLastPathComponent)
529新增: }
530新增: }
531新增: try writeAll(fd, jsonData(["ok": true]))
532新增: case "import", "upload":
533新增: let name = operation == "upload" ? request["name"] as? String : nil
534新增: if operation == "upload" && (name == nil || name!.utf8.count > 255) { throw ClipboardFailure("invalid_files") }
535新增: let input = Pipe()
536新增: let (process, output, id, epoch) = try beginTransfer(operation == "upload" ? "save" : "import", input: input.fileHandleForReading, name: name)
537新增: defer { try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() }; onGUI { _ = transfers.removeValue(forKey: id) } }
538新增: try reader.copy(to: input.fileHandleForWriting); try input.fileHandleForWriting.close()
539新增: let data = try output.fileHandleForReading.readToEnd() ?? Data()
540新增: guard data.count <= 65536 else { throw ClipboardFailure("invalid_files") }
541新增: let response = try json(data)
542新增: let imported = try paths(response["paths"])
543新增: onGUI { record(imported, copied: true); rememberCopy(response, clipboard: operation == "import") }
544新增: do { try finishTransfer(process, id: id, epoch: epoch); try writeAll(fd, jsonData(["paths": imported])) }
545新增: catch { onGUI { retireCopies(imported) }; throw error }
546新增: case "export":
547新增: let selected = try paths(request["paths"])
548新增: let readerID = UUID()
549新增: try onGUI { try check(); guard selected.allSatisfy({ known.contains($0) }) else { throw ClipboardFailure("unregistered_files") }; fileReaders[readerID] = selected }
550新增: defer { onGUI { fileReaders.removeValue(forKey: readerID); collectCopies() } }
551新增: let input = Pipe()
552新增: let (process, output, id, epoch) = try beginTransfer("export", input: input.fileHandleForReading)
553新增: defer { if process.isRunning { process.terminate() }; onGUI { _ = transfers.removeValue(forKey: id) } }
554新增: try input.fileHandleForWriting.write(contentsOf: JSONSerialization.data(withJSONObject: selected)); try input.fileHandleForWriting.close()
555新增: while let data = try output.fileHandleForReading.read(upToCount: 65536), !data.isEmpty {
556新增: var count = UInt32(data.count).bigEndian
557新增: try writeAll(fd, Data(bytes: &count, count: 4)); try writeAll(fd, data)
558新增: }
559新增: var zero: UInt32 = 0
560新增: try writeAll(fd, Data(bytes: &zero, count: 4))
561新增: do { try finishTransfer(process, id: id, epoch: epoch); try writeAll(fd, jsonData(["ok": true])) }
562新增: catch { try writeAll(fd, jsonData(["error": "file_transfer_failed"])) }
563新增: default:
564新增: throw ClipboardFailure("unknown_operation")
565新增: }
566新增: } catch {
567新增: let reason = (error as? ClipboardFailure)?.reason ?? "clipboard_operation_failed"
568新增: diagnostic(reason)
569新增: try? writeAll(fd, jsonData(["error": reason]))
570新增: }
571新增: }
572新增:}
573新增:
574新增:private func connect() throws -> Int32 {
575新增: let folder = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Caches/" + label)
576新增: var info = stat()
577新增: guard lstat(folder.path, &info) == 0, info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFDIR, info.st_mode & 0o077 == 0 else { throw ClipboardFailure("clipboard_service_unavailable") }
578新增: let path = folder.appendingPathComponent("clipboard.sock").path
579新增: guard lstat(path, &info) == 0, info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFSOCK, info.st_mode & 0o077 == 0 else { throw ClipboardFailure("clipboard_service_unavailable") }
580新增: var address = sockaddr_un(); address.sun_family = sa_family_t(AF_UNIX)
581新增: let bytes = Array(path.utf8) + [UInt8(0)]
582新增: guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { throw ClipboardFailure("clipboard_service_unavailable") }
583新增: withUnsafeMutableBytes(of: &address.sun_path) { $0.copyBytes(from: bytes) }
584新增: let fd = socket(AF_UNIX, SOCK_STREAM, 0)
585新增: guard fd >= 0 else { throw ClipboardFailure("clipboard_service_unavailable") }
586新增: let result = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) } }
587新增: guard result == 0 else { close(fd); throw ClipboardFailure("clipboard_service_unavailable") }
588新增: return fd
589新增:}
590新增:
591新增:private func client(_ operation: String) throws {
592新增: try requireGuest()
593新增: let fd = try connect(); defer { close(fd) }
594新增: let reader = Reader(fd)
595新增: switch operation {
596新增: case "stream":
597新增: try writeAll(fd, jsonData(["operation": "stream"]))
598新增: DispatchQueue.global().async {
599新增: do { try Reader(fd).copy(to: .standardOutput); exit(0) }
600新增: catch { exit(1) }
601新增: }
602新增: try Reader(STDIN_FILENO).copy(to: FileHandle(fileDescriptor: fd, closeOnDealloc: false))
603新增: shutdown(fd, SHUT_WR)
604新增: dispatchMain()
605新增: case "import":
606新增: try writeAll(fd, jsonData(["operation": "import"]))
607新增: try Reader(STDIN_FILENO).copy(to: FileHandle(fileDescriptor: fd, closeOnDealloc: false)); shutdown(fd, SHUT_WR)
608新增: guard let line = try reader.line(), try json(line)["error"] == nil else { throw ClipboardFailure("file_transfer_failed") }
609新增: try writeAll(STDOUT_FILENO, line + Data([10]))
610新增: case "upload":
611新增: let input = Reader(STDIN_FILENO)
612新增: guard let line = try input.line(limit: 4096), let name = try json(line)["name"] as? String, name.utf8.count <= 255 else {
613新增: throw ClipboardFailure("invalid_files")
614新增: }
615新增: try writeAll(fd, jsonData(["operation": "upload", "name": name]))
616新增: try input.copy(to: FileHandle(fileDescriptor: fd, closeOnDealloc: false)); shutdown(fd, SHUT_WR)
617新增: guard let reply = try reader.line(), try json(reply)["error"] == nil else { throw ClipboardFailure("file_transfer_failed") }
618新增: try writeAll(STDOUT_FILENO, reply + Data([10]))
619新增: case "export":
620新增: var data = Data()
621新增: while let chunk = try FileHandle.standardInput.read(upToCount: 65536), !chunk.isEmpty {
622新增: data.append(chunk)
623新增: guard data.count <= 1 << 20 else { throw ClipboardFailure("invalid_files") }
624新增: }
625新增: let selected = try paths(JSONSerialization.jsonObject(with: data))
626新增: try writeAll(fd, jsonData(["operation": "export", "paths": selected])); shutdown(fd, SHUT_WR)
627新增: while true {
628新增: let length = try reader.exact(4).reduce(UInt32(0)) { ($0 << 8) | UInt32($1) }
629新增: if length == 0 { break }
630新增: guard length <= 65536 else { throw ClipboardFailure("file_transfer_failed") }
631新增: try writeAll(STDOUT_FILENO, reader.exact(Int(length)))
632新增: }
633新增: guard let line = try reader.line(), try json(line)["ok"] as? Bool == true else { throw ClipboardFailure("file_transfer_failed") }
634新增: case "request":
635新增: guard let line = try Reader(STDIN_FILENO).line(), let action = try json(line)["operation"] as? String, ["read", "write", "prepare-files", "discard", "copy-prepare", "copy-read"].contains(action) else { throw ClipboardFailure("unknown_operation") }
636新增: try writeAll(fd, line + Data([10])); shutdown(fd, SHUT_WR)
637新增: guard let reply = try reader.line() else { throw ClipboardFailure("clipboard_service_unavailable") }
638新增: try writeAll(STDOUT_FILENO, reply + Data([10]))
639新增: if try json(reply)["error"] != nil { throw ClipboardFailure("clipboard_operation_failed") }
640新增: default: throw ClipboardFailure("unknown_operation")
641新增: }
642新增:}
643新增:
644新增:private final class ClipboardTestState: @unchecked Sendable {
645新增: var available = true // Used only on the GUI thread.
646新增: let lock = NSLock()
647新增: var failure: Error?
648新增:}
649新增:
650新增:private func testAgentTransport(_ board: NSPasteboard) throws {
651新增: let root = FileManager.default.temporaryDirectory.appendingPathComponent("cage-clipboard-selftest-" + UUID().uuidString)
652新增: try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false)
653新增: let previousTemp = getenv("TMPDIR").map { String(cString: $0) }
654新增: setenv("TMPDIR", root.path, 1)
655新增: defer {
656新增: if let previousTemp { setenv("TMPDIR", previousTemp, 1) } else { unsetenv("TMPDIR") }
657新增: try? FileManager.default.removeItem(at: root)
658新增: }
659新增: let state = ClipboardTestState()
660新增: let agent = ClipboardAgent(board: board, gui: { state.available }, diagnostic: { _ in })
661新增: let done = DispatchGroup()
662新增: done.enter()
663新增: DispatchQueue.global(qos: .userInitiated).async {
664新增: defer { done.leave() }
665新增: func connection() throws -> (Int32, DispatchGroup) {
666新增: var sockets: [Int32] = [0, 0]
667新增: guard socketpair(AF_UNIX, SOCK_STREAM, 0, &sockets) == 0 else { throw ClipboardFailure("test_socket_failed") }
668新增: var timeout = timeval(tv_sec: 5, tv_usec: 0)
669新增: setsockopt(sockets[1], SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout)))
670新增: let ended = DispatchGroup()
671新增: ended.enter()
672新增: let server = sockets[0]
673新增: DispatchQueue.global().async { agent.serve(server); ended.leave() }
674新增: return (sockets[1], ended)
675新增: }
676新增: func rpc(_ value: [String: Any], bytes: Data = Data()) throws -> [String: Any] {
677新增: let (fd, ended) = try connection()
678新增: defer { close(fd); ended.wait() }
679新增: try writeAll(fd, jsonData(value))
680新增: try writeAll(fd, bytes)
681新增: shutdown(fd, SHUT_WR)
682新增: guard let line = try Reader(fd).line() else { throw ClipboardFailure("test_reply_missing") }
683新增: return try json(line)
684新增: }
685新增: do {
686新增: let prepared = try rpc(["operation": "copy-prepare"])
687新增: let unchanged = try rpc(["operation": "copy-read", "revision": prepared["revision"]!, "session": prepared["session"]!])
688新增: guard unchanged["error"] as? String == "clipboard_copy_not_observed" else { throw ClipboardFailure("test_old_text_returned") }
689新增: let largeText = String(repeating: "x", count: textLimit)
690新增: onGUI { board.clearContents(); board.setString(largeText, forType: .string) }
691新增: let fresh = try rpc(["operation": "copy-read", "revision": prepared["revision"]!, "session": prepared["session"]!])
692新增: guard fresh["text"] as? String == largeText, fresh["session"] as? String == prepared["session"] as? String else { throw ClipboardFailure("test_web_copy_failed") }
693新增: let (fd, ended) = try connection()
694新增: defer { close(fd); ended.wait() }
695新增: let reader = Reader(fd)
696新增: try writeAll(fd, jsonData(["operation": "stream"]))
697新增: guard let first = try reader.line(), let hello = try json(first)["hello"] as? [String: Any],
698新增: hello["os"] as? String == "darwin", hello["available"] as? Bool == true else { throw ClipboardFailure("test_hello_failed") }
699新增: try writeAll(fd, jsonData(["text": "stream text 中文", "serial": 9]))
700新增: guard let acknowledged = try reader.line(), try json(acknowledged)["ack"] as? Int == 9 else { throw ClipboardFailure("test_ack_failed") }
701新增: onGUI { board.clearContents(); board.setString("guest pushed text", forType: .string); agent.poll() }
702新增: guard let pushed = try reader.line(), try json(pushed)["text"] as? String == "guest pushed text" else { throw ClipboardFailure("test_push_failed") }
703新增:
704新增: var bytes = Data([0, 255, 128, 10])
705新增: var length = UInt32(bytes.count).littleEndian
706新增: bytes = Data(bytes: &length, count: 4) + bytes + Data(repeating: 0, count: 4)
707新增: let saved = try rpc(["operation": "upload", "name": "中文 ' .bin"], bytes: bytes)
708新增: guard let files = saved["paths"] as? [String], files.count == 1,
709新增: try Data(contentsOf: URL(fileURLWithPath: files[0])) == Data([0, 255, 128, 10]) else { throw ClipboardFailure("test_upload_failed") }
710新增: let accepted = try rpc(["operation": "write", "files": files, "serial": 10])
711新增: guard accepted["ack"] as? Int == 10 else { throw ClipboardFailure("test_file_paste_failed") }
712新增: let copied = try rpc(["operation": "prepare-files", "files": files])
713新增: guard let duplicates = copied["paths"] as? [String], duplicates.count == 1,
714新增: try Data(contentsOf: URL(fileURLWithPath: duplicates[0])) == Data([0, 255, 128, 10]) else { throw ClipboardFailure("test_copy_failed") }
715新增: let denied = try rpc(["operation": "write", "files": ["/etc/passwd"]])
716新增: guard denied["error"] as? String == "unregistered_files" else { throw ClipboardFailure("test_unregistered_file_accepted") }
717新增: let discarded = try rpc(["operation": "discard", "files": duplicates])
718新增: let cleanupDeadline = Date().addingTimeInterval(5)
719新增: while FileManager.default.fileExists(atPath: duplicates[0]), Date() < cleanupDeadline {
720新增: Thread.sleep(forTimeInterval: 0.01)
721新增: }
722新增: guard discarded["ok"] as? Bool == true, !FileManager.default.fileExists(atPath: duplicates[0]) else { throw ClipboardFailure("test_discard_failed") }
723新增: onGUI { state.available = false; agent.poll() }
724新增: guard try reader.line() == nil else { throw ClipboardFailure("test_old_session_survived") }
725新增: } catch {
726新增: state.lock.lock(); state.failure = error; state.lock.unlock()
727新增: }
728新增: }
729新增: let deadline = Date().addingTimeInterval(30)
730新增: while done.wait(timeout: .now()) != .success && Date() < deadline {
731新增: _ = RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.01))
732新增: }
733新增: guard done.wait(timeout: .now()) == .success else { throw ClipboardFailure("test_transport_timeout") }
734新增: state.lock.lock(); let error = state.failure; state.lock.unlock()
735新增: if let error { throw error }
736新增:}
737新增:
738新增:private func selfTest() throws {
739新增: let board = NSPasteboard(name: NSPasteboard.Name("cage-clipboard-qa-" + UUID().uuidString))
740新增: defer { board.releaseGlobally() }
741新增: let text = "中文🙂\nexact text"
742新增: try setBoard(board, ["text": text]); guard try boardContent(board)["text"] as? String == text else { throw ClipboardFailure("text_test_failed") }
743新增: let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 11, pixelsHigh: 7, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
744新增: let value = bitmap.representation(using: .png, properties: [:])!
745新增: try setBoard(board, ["png": value.base64EncodedString()]); let actual = try boardContent(board)
746新增: guard let encoded = actual["png"] as? String, let data = Data(base64Encoded: encoded), try image(data).width == 11 else { throw ClipboardFailure("image_test_failed") }
747新增: do { try setBoard(board, ["png": "not-png"]); throw ClipboardFailure("invalid_image_accepted") } catch let error as ClipboardFailure { guard error.reason == "invalid_image" else { throw error } }
748新增: do { _ = try paths(["/tmp/../escape"]); throw ClipboardFailure("invalid_files_accepted") } catch let error as ClipboardFailure { guard error.reason == "invalid_files" else { throw error } }
749新增: try testAgentTransport(board)
750新增: print("macOS clipboard: named pasteboard text/image, private socket stream, framed file upload, registered-file checks, cleanup and GUI-session revocation passed")
751新增:}
752新增:
753新增:@main
754新增:struct GuestClipboard {
755新增: static func main() {
756新增: _ = signal(SIGPIPE, SIG_IGN)
757新增: do {
758新增: if CommandLine.arguments.dropFirst() == ["--self-test"] { try selfTest(); return }
759新增: if CommandLine.arguments.count == 3 && CommandLine.arguments[1] == "--client" { try client(CommandLine.arguments[2]); return }
760新增: try requireGuest()
761新增: let storage = UnsafeMutablePointer<UnsafeMutablePointer<Int32>>.allocate(capacity: 1)
762新增: var count = 0
763新增: guard launch_activate_socket("Clipboard", storage, &count) == 0, count == 1 else { throw ClipboardFailure("clipboard_service_unavailable") }
764新增: let sockets = storage.pointee; storage.deallocate(); let listener = sockets[0]; free(sockets)
765新增: GuestDiagnostic.record("clipboard", "started")
766新增: NSApplication.shared.setActivationPolicy(.accessory)
767新增: let agent = ClipboardAgent()
768新增: let timer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: true) { _ in agent.poll() }
769新增: DispatchQueue.global(qos: .userInitiated).async {
770新增: let connections = DispatchSemaphore(value: 16)
771新增: while true {
772新增: connections.wait()
773新增: let fd = accept(listener, nil, nil)
774新增: if fd < 0 { connections.signal(); if errno == EINTR { continue }; exit(2) }
775新增: DispatchQueue.global(qos: .userInitiated).async { agent.serve(fd); connections.signal() }
776新增: }
777新增: }
778新增: NSApplication.shared.run(); timer.invalidate()
779新增: } catch {
780新增: GuestDiagnostic.record("clipboard", (error as? ClipboardFailure)?.reason ?? "clipboard_operation_failed")
781新增: try? writeAll(STDOUT_FILENO, jsonData(["error": (error as? ClipboardFailure)?.reason ?? "clipboard_operation_failed"]))
782新增: exit(1)
783新增: }
784新增: }
785新增:}
新增scripts/guest-os/guest-clipboard-windows/.gitignore+2 −0看文件
@@ -0,0 +1,2 @@
1新增:/bin/
2新增:/obj/
新增scripts/guest-os/guest-clipboard-windows/AttachmentsRpc.cs+156 −0看文件
@@ -0,0 +1,156 @@
1新增:using System.Runtime.CompilerServices;
2新增:using System.Collections.Concurrent;
3新增:using System.Security.AccessControl;
4新增:using System.Security.Principal;
5新增:using System.Text.Json.Nodes;
6新增:
7新增:namespace Cage.GuestClipboard;
8新增:
9新增:// Bytes enter a fixed directory owned by the logged-in guest user. Neither a
10新增:// guest path nor a command is accepted from the controller.
11新增:internal static class AttachmentsRpc
12新增:{
13新增: private static readonly SemaphoreSlim Slots = new(12, 12);
14新增: private sealed record Batch(string Directory, string Target, string Kind, double X, double Y)
15新增: {
16新增: internal readonly List<string> Paths = [];
17新增: internal readonly DateTimeOffset Created = DateTimeOffset.UtcNow;
18新增: internal readonly long Epoch = ClipboardAgent.Current?.SessionEpoch ?? 0;
19新增: internal bool Receiving;
20新增: internal Action? AssertChooser;
21新增: }
22新增: private static readonly ConcurrentDictionary<string, Batch> Batches = new();
23新增: internal const long FileLimit = 2L << 30;
24新增: [ModuleInitializer] internal static void Register() => GuestOperations.Register("attachments", Run);
25新增: internal static bool NameValid(string name) => name.Length is > 0 and <= 255 && name is not "." and not ".." &&
26新增: !name.EndsWith(' ') && !name.EndsWith('.') && name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 &&
27新增: !new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" }.Contains(name.Split('.')[0], StringComparer.OrdinalIgnoreCase);
28新增: internal static string NewDirectory()
29新增: {
30新增: var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
31新增: using var identity = WindowsIdentity.GetCurrent();
32新增: var parent = Path.Combine(home, "Cage", "Attachments");
33新增: var directory = Path.Combine(parent, Guid.NewGuid().ToString("N"));
34新增: foreach (var path in new[] { Path.Combine(home, "Cage"), parent, directory })
35新增: {
36新增: Directory.CreateDirectory(path);
37新增: var info = new DirectoryInfo(path);
38新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value != identity.User?.Value)
39新增: throw new InvalidDataException("attachment_directory_invalid");
40新增: }
41新增: return directory;
42新增: }
43新增: internal static JsonObject StartBatch(string target, string kind, double x, double y)
44新增: {
45新增: foreach(var pair in Batches.Where(pair=>DateTimeOffset.UtcNow-pair.Value.Created>TimeSpan.FromMinutes(30))) CancelBatch(pair.Key);
46新增: if(Batches.Count>=12 || kind is not ("paste" or "drop" or "image") || kind=="drop" && (!double.IsFinite(x) || !double.IsFinite(y) || x<0 || x>1 || y<0 || y>1))throw new InvalidDataException("attachment_request_invalid");
47新增: var id=Guid.NewGuid().ToString("D"); var batch=new Batch(NewDirectory(),target,kind,x,y);
48新增: if(!Batches.TryAdd(id,batch))throw new InvalidDataException("attachment_request_invalid");
49新增: return new JsonObject { ["ok"]=true,["id"]=id };
50新增: }
51新增: // Only the authenticated dialog broker can supply this capability. The
52新增: // JSON files-start endpoint continues to accept paste/drop alone.
53新增: internal static JsonObject StartChooserBatch(string target,Action assertChooser)
54新增: {
55新增: assertChooser();
56新增: foreach(var pair in Batches.Where(pair=>DateTimeOffset.UtcNow-pair.Value.Created>TimeSpan.FromMinutes(30)))CancelBatch(pair.Key);
57新增: if(Batches.Count>=12)throw new InvalidDataException("attachment_request_limit");
58新增: var id=Guid.NewGuid().ToString("D");var batch=new Batch(NewDirectory(),target,"chooser",0,0){AssertChooser=assertChooser};
59新增: if(!Batches.TryAdd(id,batch))throw new InvalidDataException("attachment_request_invalid");
60新增: try{assertChooser();return new JsonObject{["ok"]=true,["id"]=id};}catch{CancelBatch(id);throw;}
61新增: }
62新增: internal static void CancelBatch(string id)
63新增: {
64新增: if(!Batches.TryRemove(id,out var batch))return;
65新增: lock(batch) { if(!batch.Receiving) try { Directory.Delete(batch.Directory,true); } catch { } }
66新增: }
67新增: internal static async Task FinishBatch(string id, Func<string,string,string[],double,double,Task> deliver)
68新增: {
69新增: if(!Batches.TryGetValue(id,out var batch))throw new InvalidDataException("attachment_request_invalid");
70新增: string[] paths;
71新增: lock(batch) { if(batch.Receiving || batch.Paths.Count==0 || batch.Epoch!=ClipboardAgent.Current?.SessionEpoch)throw new InvalidDataException("attachment_incomplete");batch.AssertChooser?.Invoke(); batch.Receiving=true;paths=batch.Paths.ToArray(); }
72新增: try
73新增: {
74新增: await deliver(batch.Target,batch.Kind,paths,batch.X,batch.Y);
75新增: Batches.TryRemove(id,out _); // Completed attachments remain user data.
76新增: if(batch.Kind=="image")Directory.Delete(batch.Directory,true);
77新增: }
78新增: finally { lock(batch)batch.Receiving=false; }
79新增: }
80新增: private static async Task Run(Stream stream, CancellationToken token, Func<bool> available)
81新增: {
82新增: if (!available()) throw new InvalidDataException("requires_gui_login");
83新增: if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("attachment_limit");
84新增: string? directory = null; bool completed = false, ownsReceiving=false; Batch? batch=null;
85新增: try
86新增: {
87新增: var request = await Protocol.Read(stream, 4096, token) ?? throw new EndOfStreamException();
88新增: var name = request["name"]?.GetValue<string>() ?? "";
89新增: if (request["action"]?.GetValue<string>() != "save" || !NameValid(name)) throw new InvalidDataException("attachment_request_invalid");
90新增: var id=request["id"]?.GetValue<string>();
91新增: if(id!=null)
92新增: {
93新增: if(!Batches.TryGetValue(id,out batch))throw new InvalidDataException("attachment_request_invalid");
94新增: lock(batch) { if(batch.Receiving || batch.Paths.Count>=100)throw new InvalidDataException("attachment_limit");batch.AssertChooser?.Invoke();batch.Receiving=true;ownsReceiving=true; }
95新增: directory=batch.Directory;
96新增: }
97新增: else directory = NewDirectory();
98新增: var fileDirectory=directory;
99新增: if(batch?.Kind=="chooser")
100新增: {
101新增: // Different selected host folders may contain the same name.
102新增: // Each chooser file retains its original name in its own fixed
103新增: // child directory; no uploaded path controls this location.
104新增: fileDirectory=Path.Combine(directory,Guid.NewGuid().ToString("N"));
105新增: Directory.CreateDirectory(fileDirectory);
106新增: using var identity=WindowsIdentity.GetCurrent();var info=new DirectoryInfo(fileDirectory);
107新增: if(info.Attributes.HasFlag(FileAttributes.ReparsePoint)||info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value!=identity.User?.Value)
108新增: throw new InvalidDataException("attachment_directory_invalid");
109新增: batch.AssertChooser?.Invoke();
110新增: }
111新增: var path = Path.Combine(fileDirectory, name);
112新增: await using (var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 << 10, FileOptions.Asynchronous))
113新增: {
114新增: using var bounded = new LimitedWriteStream(file, FileLimit);
115新增: await Protocol.ReceiveFrames(stream, bounded, token);
116新增: if (!available()) throw new InvalidDataException("requires_gui_login");
117新增: await file.FlushAsync(token); file.Flush(true);
118新增: batch?.AssertChooser?.Invoke();
119新增: }
120新增: if(batch!=null)
121新增: {
122新增: if(!Batches.TryGetValue(id!,out var current) || !ReferenceEquals(batch,current))throw new InvalidDataException("attachment_cancelled");
123新增: lock(batch)batch.Paths.Add(path);
124新增: }
125新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true, ["scope"] = "attachments", ["path"] = path }, token);
126新增: completed = true;
127新增: }
128新增: finally
129新增: {
130新增: // This random directory was created for this transfer. Failed bytes
131新增: // cannot appear as a completed attachment or replace an older file.
132新增: if(ownsReceiving && batch!=null)lock(batch)batch.Receiving=false;
133新增: var cancelled=ownsReceiving && batch!=null && !Batches.Values.Any(current=>ReferenceEquals(current,batch));
134新增: if ((!completed || cancelled) && directory != null)
135新增: {
136新增: foreach(var pair in Batches.Where(pair=>ReferenceEquals(pair.Value,batch)))Batches.TryRemove(pair.Key,out _);
137新增: try { Directory.Delete(directory, true); } catch { }
138新增: }
139新增: Slots.Release();
140新增: }
141新增: }
142新增: internal sealed class LimitedWriteStream(Stream inner, long limit) : Stream
143新增: {
144新增: private long written;
145新增: public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true;
146新增: public override long Length => written; public override long Position { get => written; set => throw new NotSupportedException(); }
147新增: public override void Flush() => inner.Flush();
148新增: public override Task FlushAsync(CancellationToken token) => inner.FlushAsync(token);
149新增: public override void Write(byte[] buffer, int offset, int count) { Check(count); inner.Write(buffer, offset, count); }
150新增: public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken token = default) { Check(buffer.Length); await inner.WriteAsync(buffer, token); }
151新增: private void Check(int count) { if (count < 0 || written > limit - count) throw new InvalidDataException("attachment_size_limit"); written += count; }
152新增: public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
153新增: public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
154新增: public override void SetLength(long value) => throw new NotSupportedException();
155新增: }
156新增:}
新增scripts/guest-os/guest-clipboard-windows/BrowserPasteInput.cs+68 −0看文件
@@ -0,0 +1,68 @@
1新增:using System.Text.Json.Nodes;
2新增:
3新增:namespace Cage.GuestClipboard;
4新增:
5新增:// Browser clipboard staging. It accepts bytes and an already focused tab proof,
6新增:// never a filename, HWND, clipboard path or a general clipboard write command.
7新增:internal static class BrowserPasteInput
8新增:{
9新增: private sealed record Pending(string Tab,string Target,string Focus,uint Revision,int Length,DateTime Created,MemoryStream Bytes)
10新增: { internal int Sequence; internal string Mime = ""; internal readonly long Epoch = ClipboardAgent.Current?.SessionEpoch ?? 0; }
11新增: private static readonly Dictionary<string,Pending> Transfers = new(StringComparer.Ordinal);
12新增: internal static async Task<JsonObject> Start(JsonObject input,JsonObject proof,JsonObject focus)
13新增: {
14新增: Expire();
15新增: var tab=input["id"]?.GetValue<string>()??"";var length=input["length"]?.GetValue<int>()??0;
16新增: var mime=input["mime"]?.GetValue<string>()??"";
17新增: if(Transfers.Count>=4||tab!=proof["id"]?.GetValue<string>()||length<0||length>(mime=="text/plain"?Protocol.TextLimit:Protocol.PngLimit)||mime is not ("" or "text/plain" or "image/png"))throw new InvalidDataException("image_target_invalid");
18新增: var clipboard=ClipboardAgent.Current??throw new InvalidDataException("clipboard_unavailable");
19新增: var revision=await clipboard.Revision();
20新增: var id=Guid.NewGuid().ToString("N");
21新增: Transfers[id]=new Pending(tab,proof["target"]!.GetValue<string>(),focus["focus"]!.GetValue<string>(),revision,length,DateTime.UtcNow,new MemoryStream(Math.Min(length,64<<10))){Mime=mime};
22新增: return new JsonObject{["transfer"]=id};
23新增: }
24新增: internal static JsonObject Chunk(JsonObject input)
25新增: {
26新增: var pending=Get(input);var text=input["data"]?.GetValue<string>()??"";
27新增: if(pending.Sequence==0&&pending.Mime=="")pending.Mime=input["mime"]?.GetValue<string>()??"";
28新增: if(pending.Mime is not ("text/plain" or "image/png")||input["mime"] is not null&&input["mime"]!.GetValue<string>()!=pending.Mime)throw new InvalidDataException("image_chunk_invalid");
29新增: var limit=pending.Mime=="text/plain"?Protocol.TextLimit:Protocol.PngLimit;
30新增: if(pending.Length==0&&pending.Sequence==0)
31新增: {
32新增: var length=input["length"]?.GetValue<int>()??0;
33新增: if(length<1||length>limit)throw new InvalidDataException("image_chunk_invalid");
34新增: pending=pending with {Length=length};Transfers[input["transfer"]!.GetValue<string>()]=pending;
35新增: }
36新增: if(pending.Length>limit)throw new InvalidDataException("image_chunk_invalid");
37新增: if(text.Length>87384||text.Any(char.IsWhiteSpace))throw new InvalidDataException("image_chunk_invalid");
38新增: var bytes=Convert.FromBase64String(text);
39新增: if(bytes.Length is <1 or >65536||pending.Bytes.Length+bytes.Length>pending.Length)throw new InvalidDataException("image_chunk_invalid");
40新增: pending.Bytes.Write(bytes);pending.Sequence++;
41新增: return new JsonObject{["ack"]=pending.Sequence};
42新增: }
43新增: internal static async Task<JsonObject> Finish(JsonObject input,JsonObject proof,JsonObject focus,Func<Task<JsonObject>> paste)
44新增: {
45新增: var pending=Get(input);Transfers.Remove(input["transfer"]!.GetValue<string>());
46新增: using(pending.Bytes)
47新增: {
48新增: if(pending.Bytes.Length!=pending.Length||pending.Tab!=proof["id"]?.GetValue<string>()||pending.Target!=proof["target"]?.GetValue<string>()||pending.Focus!=focus["focus"]?.GetValue<string>())throw new InvalidDataException("image_target_changed");
49新增: var clipboard=ClipboardAgent.Current??throw new InvalidDataException("clipboard_unavailable");
50新增: var bytes=pending.Bytes.ToArray();
51新增: JsonObject receipt;
52新增: if(pending.Mime=="text/plain")receipt=await clipboard.WriteBrowserText(pending.Revision,Protocol.Utf8.GetString(bytes));
53新增: else {Protocol.Png(bytes);receipt=await clipboard.WriteBrowserPng(pending.Revision,bytes);}
54新增: await clipboard.PreparePaste();
55新增: var result=await paste();
56新增: if(result["error"] is not null)throw new InvalidDataException("image_paste_failed");
57新增: result["clipboard"]=receipt;return result;
58新增: }
59新增: }
60新增: internal static void Cancel(string id){if(Transfers.Remove(id,out var pending))pending.Bytes.Dispose();}
61新增: private static Pending Get(JsonObject input)
62新增: {
63新增: Expire();var id=input["transfer"]?.GetValue<string>()??"";
64新增: if(!Transfers.TryGetValue(id,out var pending)||input["sequence"]?.GetValue<int>()!=pending.Sequence||pending.Epoch!=ClipboardAgent.Current?.SessionEpoch)throw new InvalidDataException("image_transfer_changed");return pending;
65新增: }
66新增: private static void Expire(){foreach(var item in Transfers.ToArray())if(DateTime.UtcNow-item.Value.Created>TimeSpan.FromMinutes(2))Cancel(item.Key);}
67新增: internal static void Close(){foreach(var item in Transfers.Values)item.Bytes.Dispose();Transfers.Clear();}
68新增:}
新增scripts/guest-os/guest-clipboard-windows/BrowserRpc.cs+510 −0看文件
@@ -0,0 +1,510 @@
1新增:using System.Diagnostics;
2新增:using System.Collections.Concurrent;
3新增:using System.Runtime.CompilerServices;
4新增:using System.Security.AccessControl;
5新增:using System.Security.Principal;
6新增:using System.Text.Json.Nodes;
7新增:
8新增:namespace Cage.GuestClipboard;
9新增:
10新增:// A viewer connection owns its requests. The GUI agent owns the persistent
11新增:// browser process, so reconnecting or locking the desktop preserves its tabs.
12新增:internal static class BrowserRpc
13新增:{
14新增: private static readonly SemaphoreSlim Gate = new(1, 1);
15新增: private static Process? browser;
16新增: private static GuestProcessJob? browserJob;
17新增: private static Stream? replies;
18新增: private static Task? errors;
19新增: private static bool ready;
20新增: private static bool wirePending;
21新增: private static JsonObject? cachedPageFrame;
22新增: private static NativeInputCoordinator.Lease? pagePointerOwner;
23新增: private static bool pagePointerReleasePending;
24新增: private static JsonObject features = new();
25新增: private static Func<bool>? packetReadiness;
26新增: private static string active = "";
27新增: private static readonly ConcurrentDictionary<string, WindowsEditorServer.Connection> EditorTabs = new(StringComparer.Ordinal);
28新增: private static readonly ConcurrentDictionary<string, WindowsEditorServer.Connection> EditorConnections = new(StringComparer.Ordinal);
29新增: private static readonly ConcurrentDictionary<string, uint> CopyRevisions = new(StringComparer.Ordinal);
30新增: private static readonly HashSet<string> Routes = ["health", "tabs", "events", "frame", "new", "activate", "close", "navigate", "back", "forward", "reload", "homepage", "resize", "insert-text", "copy-context", "ime", "copy", "cut", "paste", "select-all", "key", "pointer", "click", "wheel", "input", "editor", "editor-restart", "upload-start", "upload-finish", "upload-cancel", "download-retry", "info", "cookies", "settings", "internal-page", "extensions", "split", "audit", "vault", "login-open", "login-finish", "file-open", "file-chunk", "file-finish", "file-read", "file-close", "image-start", "image-chunk", "image-finish", "image-cancel"];
31新增:
32新增: [ModuleInitializer]
33新增: internal static void Register()
34新增: {
35新增: Routes.UnionWith(["paste-start", "paste-chunk", "paste-finish", "paste-cancel", "tailnet", "phone-browser/open", "phone-browser/frame", "phone-browser/action", "phone-browser/close"]);
36新增: GuestOperations.Register("browser", Run);
37新增: ProjectRpc.Revoked += (project, grant) =>
38新增: {
39新增: WindowsEditorServer.Revoke(project, grant);
40新增: _ = RevokeNode(project, grant);
41新增: };
42新增: AppDomain.CurrentDomain.ProcessExit += (_, _) => { WindowsPhoneBrowser.Close(); WindowsEditorServer.Close(); Close(); };
43新增: }
44新增: // The packet runtime supplies its System-owned receipt verifier. A config
45新增: // string alone can never enable direct TCP access in a fresh browser.
46新增: internal static void RegisterPacketReadiness(Func<bool> verifier)
47新增: {
48新增: if (Interlocked.CompareExchange(ref packetReadiness, verifier, null) is not null) throw new InvalidOperationException("packet_verifier_already_registered");
49新增: }
50新增: private static bool PacketReady()
51新增: {
52新增: if (packetReadiness is not null) return packetReadiness();
53新增: try
54新增: {
55新增: var vm = GuestContext.VM;
56新增: if (vm == Guid.Empty || GuestContext.SID.Length == 0) return false;
57新增: var root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Cage Guest Network", vm.ToString("D"));
58新增: var file = new FileInfo(Path.Combine(root, "network-ready.json"));
59新增: if (!file.Exists || file.Length is < 1 or > 16384 || file.Attributes.HasFlag(FileAttributes.ReparsePoint) || new DirectoryInfo(root).Attributes.HasFlag(FileAttributes.ReparsePoint)) return false;
60新增: var acl = file.GetAccessControl();
61新增: var owner = acl.GetOwner(typeof(SecurityIdentifier))?.Value;
62新增: if (owner is not ("S-1-5-18" or "S-1-5-32-544")) return false;
63新增: const FileSystemRights writes = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteAttributes | FileSystemRights.WriteExtendedAttributes | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership;
64新增: foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(SecurityIdentifier)))
65新增: if (rule.AccessControlType == AccessControlType.Allow && (rule.FileSystemRights & writes) != 0 && rule.IdentityReference.Value is not ("S-1-5-18" or "S-1-5-32-544")) return false;
66新增: // The SYSTEM writer atomically replaces this file every second.
67新增: // Keep one immutable snapshot while permitting that replacement;
68新增: // File.ReadAllText's default sharing can block the writer on NTFS.
69新增: using var snapshot = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
70新增: if (snapshot.Length is < 1 or > 16384) return false;
71新增: using var reader = new StreamReader(snapshot);
72新增: var receipt = JsonNode.Parse(reader.ReadToEnd()) as JsonObject;
73新增: var updated = receipt?["updated_at"]?.GetValue<long>() ?? 0;
74新增: var age = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - updated;
75新增: return receipt?["version"]?.GetValue<int>() == 1 && Guid.TryParse(receipt["vm_id"]?.GetValue<string>(), out var receivedVM) && receivedVM == vm &&
76新增: receipt["gui_user_sid"]?.GetValue<string>() == GuestContext.SID && receipt["network"]?.GetValue<string>() == "packet" &&
77新增: receipt["adapter"]?.GetValue<string>() == "Cage-" + vm.ToString("N")[..8] && receipt["interface_index"]?.GetValue<int>() > 0 &&
78新增: receipt["session"]?.GetValue<string>() is { Length: > 0 and <= 128 } && age is >= -1000 and <= 5000;
79新增: }
80新增: catch { return false; }
81新增: }
82新增:
83新增: internal static async Task Run(Stream stream, CancellationToken token, Func<bool> sessionAvailable)
84新增: {
85新增: var lease=BrowserWindowCapture.OpenLease();Task<JsonObject>? transaction=null;
86新增: try
87新增: {
88新增: while (await Protocol.Read(stream, 128 << 10, token) is { } request)
89新增: {
90新增: if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login");
91新增: Validate(request);
92新增: // A canceled viewer leaves the reply drain running. Otherwise its
93新增: // pending reply could become the next viewer's browser response.
94新增: transaction = Exchange(request, token, lease);
95新增: JsonObject result;
96新增: try { result = await transaction.WaitAsync(token); }
97新增: catch (OperationCanceledException)
98新增: {
99新增: throw;
100新增: }
101新增: catch (InvalidDataException error)
102新增: {
103新增: var known = new HashSet<string> { "project_grant_unavailable", "editor_components_missing", "editor_start_failed", "editor_start_busy", "clipboard_copy_not_observed", "selection_not_authorized", "browser_network_unavailable", "browser_components_missing", "requires_gui_login", "editor_package_invalid", "browser_unavailable", "browser_response_timeout", "browser_target_changed", "browser_window_unavailable", "browser_process_unavailable", "browser_capture_surface_unavailable", "browser_focus_required", "browser_frame_limit", "desktop_target_changed", "desktop_empty_frame", "desktop_capture_buffer_invalid", "desktop_graphics_device_unavailable", "desktop_capture_permission_required", "desktop_capture_geometry_invalid" };
104新增: var code = known.Contains(error.Message) ? error.Message : "browser_operation_failed";
105新增: GuestDiagnostics.Record("browser", code);
106新增: result = new JsonObject { ["error"] = code, ["code"] = code };
107新增: }
108新增: if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login");
109新增: await Protocol.Write(stream, result, token);
110新增: }
111新增: }
112新增: finally
113新增: {
114新增: // No transaction may inject a late down after this lease is closed.
115新增: if(transaction is not null)await Observe(transaction);
116新增: await Gate.WaitAsync();
117新增: try
118新增: {
119新增: if (pagePointerOwner == lease)
120新增: {
121新增: pagePointerOwner = null;
122新增: pagePointerReleasePending = true;
123新增: if (sessionAvailable())
124新增: {
125新增: using var releaseTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
126新增: try { await ReleasePagePointer(releaseTimeout.Token); }
127新增: catch { Close(); }
128新增: }
129新增: }
130新增: BrowserWindowCapture.CloseLease(lease);
131新增: }
132新增: finally { Gate.Release(); }
133新增: await WindowsPhoneBrowser.Release(lease);
134新增: }
135新增: }
136新增:
137新增: private static void Validate(JsonObject value)
138新增: {
139新增: var method = value["method"]?.GetValue<string>();
140新增: var path = value["path"]?.GetValue<string>() ?? "";
141新增: if (value.ContainsKey("operation") || method is not ("GET" or "POST") ||
142新增: path.Length < 2 || !path.StartsWith('/') || !Routes.Contains(path[1..]) ||
143新增: value["input"] is not (null or JsonObject) ||
144新增: method == "GET" && path is not ("/health" or "/tabs" or "/events" or "/frame"))
145新增: throw new InvalidDataException("browser_request_invalid");
146新增: }
147新增:
148新增: private static void AssertEditorTab(string? id)
149新增: {
150新增: if(id is not null && EditorTabs.TryGetValue(id,out var bound) && ProjectRpc.Resolve(bound.Project,bound.Grant)!=bound.Folder)
151新增: throw new InvalidDataException("project_grant_unavailable");
152新增: }
153新增: private static void AssertFrameEditors(JsonObject frame)
154新增: {
155新增: AssertEditorTab(frame["id"]?.GetValue<string>());
156新增: AssertEditorTab((frame["native"] as JsonObject)?["id"]?.GetValue<string>());
157新增: if(frame["panes"] is JsonArray panes)foreach(var pane in panes.OfType<JsonObject>())AssertEditorTab(pane["id"]?.GetValue<string>());
158新增: }
159新增: private static void AssertRequestedTab(JsonObject input,JsonObject proof)
160新增: {AssertEditorTab(proof["id"]?.GetValue<string>());if(input["id"]?.GetValue<string>() is {Length:>0} id&&id!=proof["id"]?.GetValue<string>())throw new InvalidDataException("browser_target_changed");}
161新增:
162新增: private static async Task ReleasePagePointer(CancellationToken token)
163新增: {
164新增: if (browser is not null && !browser.HasExited)
165新增: await Control(new JsonObject { ["operation"] = "input-release-pointer" }, token);
166新增: pagePointerOwner = null;
167新增: pagePointerReleasePending = false;
168新增: }
169新增:
170新增: private static async Task<JsonObject> Exchange(JsonObject request, CancellationToken connection, NativeInputCoordinator.Lease lease)
171新增: {
172新增: if (request["path"]?.GetValue<string>()?.StartsWith("/phone-browser/", StringComparison.Ordinal) == true)
173新增: return await WindowsPhoneBrowser.Exchange(request, connection, lease);
174新增: await Gate.WaitAsync(connection);
175新增: try
176新增: {
177新增: // The connection token must not interrupt the child's reply drain.
178新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(35));
179新增: var route = request["path"]?.GetValue<string>() ?? "";
180新增: var input = request["input"] as JsonObject ?? new JsonObject();
181新增: if(route is "/paste-cancel" or "/image-cancel")
182新增: {
183新增: BrowserPasteInput.Cancel(input["transfer"]?.GetValue<string>() ?? "");
184新增: return new JsonObject { ["ok"] = true };
185新增: }
186新增: if(route=="/input"&&BrowserWindowCapture.ReleaseInput(lease,input))return new JsonObject { ["ok"] = true };
187新增: await Start(timeout.Token);
188新增: if (pagePointerReleasePending) await ReleasePagePointer(timeout.Token);
189新增: if (pagePointerOwner is not null && route is "/resize" or "/navigate" or "/new" or "/close" or "/activate" or "/split" or "/back" or "/forward" or "/reload" or "/paste" or "/cut" or "/copy" or "/select-all" or "/insert-text")
190新增: await ReleasePagePointer(timeout.Token);
191新增: connection.ThrowIfCancellationRequested();
192新增: WindowsEditorServer.Connection? editor = null;
193新增: if (route is "/editor" or "/editor-restart")
194新增: {
195新增: var project = input["project_id"]?.GetValue<string>() ?? "";
196新增: var grant = input["grant"]?.GetValue<string>() ?? "";
197新增: editor = await WindowsEditorServer.Open(project, grant, route == "/editor-restart", timeout.Token);
198新增: connection.ThrowIfCancellationRequested();
199新增: EditorConnections[editor.ID] = editor;
200新增: await Control(new JsonObject { ["operation"] = "editor-connect", ["input"] = new JsonObject
201新增: {
202新增: ["workspace"] = project, ["folder"] = editor.Folder, ["url"] = editor.URL, ["connection"] = editor.ID,
203新增: ["trust_default"] = editor.TrustDefault.HasValue ? JsonValue.Create(editor.TrustDefault.Value) : null,
204新增: } }, timeout.Token);
205新增: // Authorization uses only Resolve; a wire Workspace never selects
206新增: // an executable, path or browser URL.
207新增: input = new JsonObject { ["workspace"] = project };
208新增: request = new JsonObject { ["method"] = "POST", ["path"] = route, ["input"] = input };
209新增: }
210新增: var selected = input["id"]?.GetValue<string>() ?? active;
211新增: if (route is not ("/tabs" or "/events" or "/audit" or "/close" or "/new" or "/settings" or "/extensions" or "/internal-page" or "/editor" or "/editor-restart"))AssertEditorTab(selected);
212新增: if(route=="/split" && input["left"] is not null){AssertEditorTab(input["left"]?.GetValue<string>());AssertEditorTab(input["right"]?.GetValue<string>());}
213新增: if (route.StartsWith("/image-", StringComparison.Ordinal) || route.StartsWith("/paste-", StringComparison.Ordinal))
214新增: {
215新增: if(route=="/image-start")input["mime"]="image/png";
216新增: route=route.Replace("/paste-","/image-",StringComparison.Ordinal);
217新增: if (route == "/image-cancel") { BrowserPasteInput.Cancel(input["transfer"]?.GetValue<string>() ?? ""); return new JsonObject { ["ok"] = true }; }
218新增: if (route == "/image-chunk") return BrowserPasteInput.Chunk(input);
219新增: var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
220新增: AssertEditorTab(proof["id"]?.GetValue<string>());
221新增: var focus = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/focus-proof" }, timeout.Token);
222新增: if (route == "/image-start") return await BrowserPasteInput.Start(input, proof, focus);
223新增: if (route == "/image-finish") return await BrowserPasteInput.Finish(input, proof, focus, async () =>
224新增: {
225新增: var current = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
226新增: AssertEditorTab(current["id"]?.GetValue<string>());
227新增: var field = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/focus-proof" }, timeout.Token);
228新增: if (current["target"]?.GetValue<string>() != proof["target"]?.GetValue<string>() || current["id"]?.GetValue<string>() != proof["id"]?.GetValue<string>() || field["focus"]?.GetValue<string>() != focus["focus"]?.GetValue<string>()) throw new InvalidDataException("image_target_changed");
229新增: if (BrowserWindowCapture.Edit(browser!, proof, "paste")) return new JsonObject { ["ok"] = true };
230新增: return await Control(new JsonObject { ["method"] = "POST", ["path"] = "/paste", ["input"] = new JsonObject { ["id"] = proof["id"]!.DeepClone(), ["document"] = proof["document"]!.DeepClone() } }, timeout.Token);
231新增: });
232新增: throw new InvalidDataException("image_request_invalid");
233新增: }
234新增: var clipboard = ClipboardAgent.Current;
235新增: uint? previous = null;
236新增: if (clipboard is not null && route is "/copy" or "/cut" or "/copy-context") previous = await clipboard.Revision();
237新增: if (clipboard is not null && route == "/paste") await clipboard.PreparePaste();
238新增: if (route == "/copy-context" && previous.HasValue && input["context"]?.GetValue<string>() is { } copyContext)
239新增: {
240新增: if (CopyRevisions.Count > 200) CopyRevisions.Clear();
241新增: CopyRevisions[copyContext] = previous.Value;
242新增: }
243新增: connection.ThrowIfCancellationRequested();
244新增: if (route == "/input")
245新增: {
246新增: if (input["kind"]?.GetValue<string>() == "pointer" && pagePointerOwner is not null)
247新增: {
248新增: if (pagePointerOwner != lease) throw new InvalidDataException("browser_target_changed");
249新增: if (input["mask"]?.GetValue<int>() == 0)
250新增: {
251新增: await ReleasePagePointer(timeout.Token);
252新增: return new JsonObject{["ok"]=true};
253新增: }
254新增: }
255新增: var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
256新增: AssertEditorTab(proof["id"]?.GetValue<string>());
257新增: if(BrowserWindowCapture.FocusRenderer(browser!,proof))
258新增: {proof=await Control(new JsonObject{["method"]="GET",["path"]="/frame-proof"},timeout.Token);AssertEditorTab(proof["id"]?.GetValue<string>());}
259新增: if (pagePointerOwner != lease && BrowserWindowCapture.SelectPane(browser!, lease, input, proof))
260新增: {
261新增: await Control(new JsonObject { ["operation"] = "input-select-pane", ["input"] = new JsonObject { ["target"] = proof["target"]!.DeepClone(), ["x"] = input["x"]!.DeepClone() } }, timeout.Token);
262新增: proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
263新增: AssertEditorTab(proof["id"]?.GetValue<string>());
264新增: BrowserWindowCapture.Transition(browser!, proof);
265新增: }
266新增: if (BrowserWindowCapture.HandleInput(browser!, lease, input, proof, pagePointerOwner == lease))
267新增: {
268新增: if (input["kind"]?.GetValue<string>() == "pointer")
269新增: await Control(new JsonObject { ["operation"] = "input-reset" }, timeout.Token);
270新增: BrowserWindowCapture.Transition(browser!, await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token));
271新增: active = proof["id"]?.GetValue<string>() ?? active;
272新增: return new JsonObject { ["ok"] = true, ["active"] = active };
273新增: }
274新增: if (input["kind"]?.GetValue<string>() == "pointer" && ((input["mask"]?.GetValue<int>() ?? 0) & 7) != 0)
275新增: pagePointerOwner = lease;
276新增: }
277新增: if (route is "/paste" or "/copy" or "/cut" or "/select-all" or "/insert-text")
278新增: {
279新增: var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
280新增: AssertRequestedTab(input,proof);
281新增: if (BrowserWindowCapture.Edit(browser!, proof, route[1..], input["text"]?.GetValue<string>() ?? ""))
282新增: {
283新增: await Control(new JsonObject { ["operation"] = "input-reset" }, timeout.Token);
284新增: var receipt = new JsonObject { ["ok"] = true };
285新增: if (previous.HasValue && route is "/copy" or "/cut") receipt["clipboard"] = await clipboard!.Receipt(previous.Value, true);
286新增: return receipt;
287新增: }
288新增: }
289新增: if (route == "/ime")
290新增: {
291新增: var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
292新增: AssertRequestedTab(input,proof);
293新增: if (input["id"]?.GetValue<string>() != proof["id"]?.GetValue<string>()) throw new InvalidDataException("browser_target_changed");
294新增: var native = await BrowserWindowCapture.Ime(browser!, proof, input, timeout.Token);
295新增: if (native is not null) return native;
296新增: }
297新增: var afterFrame = route == "/frame" ? input["after"]?.GetValue<string>() : null;
298新增: if (route == "/frame")
299新增: {
300新增: // Cached page pixels and the current native-window proof have
301新增: // separate lifetimes. Native menus are inspected on every call.
302新增: input["after"] = cachedPageFrame?["sequence"]?.DeepClone();
303新增: input["nativeProof"] = true;
304新增: if (request["input"] is null) request["input"] = input;
305新增: }
306新增: var result = await Control(request, timeout.Token);
307新增: if (route == "/frame" && result["error"] is null)
308新增: {
309新增: if (result["unchanged"]?.GetValue<bool>() == true)
310新增: {
311新增: if (cachedPageFrame is null || result["sequence"]?.GetValue<string>() != cachedPageFrame["sequence"]?.GetValue<string>())
312新增: throw new InvalidDataException("browser_target_changed");
313新增: var proof = result["native"]?.DeepClone() ?? await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);
314新增: result = (JsonObject)cachedPageFrame.DeepClone();
315新增: result["native"] = proof;
316新增: }
317新增: else
318新增: {
319新增: AssertFrameEditors(result);
320新增: cachedPageFrame = (JsonObject)result.DeepClone();
321新增: }
322新增: AssertFrameEditors(result);
323新增: await BrowserWindowCapture.Decorate(browser!, result, async ()=>{var current=await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);AssertEditorTab(current["id"]?.GetValue<string>());return current;});
324新增: AssertFrameEditors(result);
325新增: result = BrowserWindowCapture.FrameReply(result, afterFrame);
326新增: }
327新增: if (result["error"] is null)
328新增: {
329新增: ready = true;
330新增: if (result["capabilities"] is JsonObject capability) features = (JsonObject)capability.DeepClone();
331新增: else if (result["state"]?["capabilities"] is JsonObject stateCapability) features = (JsonObject)stateCapability.DeepClone();
332新增: if (result["active"]?.GetValue<string>() is { } current) active = current;
333新增: if (route is "/activate" or "/new" or "/editor" or "/editor-restart") active = result["id"]?.GetValue<string>() ?? input["id"]?.GetValue<string>() ?? active;
334新增: if (editor is not null && result["id"]?.GetValue<string>() is { } tabID)
335新增: {
336新增: if (ProjectRpc.Resolve(editor.Project, editor.Grant) != editor.Folder) throw new InvalidDataException("project_grant_unavailable");
337新增: EditorTabs[tabID] = editor;
338新增: }
339新增: if (route == "/close") EditorTabs.TryRemove(selected, out _);
340新增: if (clipboard is not null && previous.HasValue && route is "/copy" or "/cut")
341新增: result["clipboard"] = await clipboard.Receipt(previous.Value, true);
342新增: if (clipboard is not null && result["events"] is JsonArray events)
343新增: {
344新增: foreach (var value in events.OfType<JsonObject>()) if (value["type"]?.GetValue<string>() == "clipboard")
345新增: {
346新增: var payload = value["value"] as JsonObject;
347新增: var context = payload?["context"]?.GetValue<string>() ?? "";
348新增: payload?.Remove("text"); value["type"] = "native-clipboard";
349新增: try
350新增: {
351新增: if (!CopyRevisions.TryGetValue(context, out var revision)) throw new InvalidDataException("copy_context_expired");
352新增: payload!["receipt"] = await clipboard.Receipt(revision, true);
353新增: }
354新增: catch { value["type"] = "copy-expired"; }
355新增: }
356新增: }
357新增: }
358新增: return result;
359新增: }
360新增: catch (OperationCanceledException)
361新增: { if (wirePending) Close(); throw new InvalidDataException("browser_response_timeout"); }
362新增: catch (EndOfStreamException) { Close(); throw new InvalidDataException("browser_unavailable"); }
363新增: finally { Gate.Release(); }
364新增: }
365新增:
366新增: internal static async Task<JsonObject> ReadConfiguration(CancellationToken token, bool packetOnly = false)
367新增: {
368新增: var root = AppContext.BaseDirectory;
369新增: var configPath = Path.Combine(root, "guest-config.json");
370新增: var info = new FileInfo(configPath);
371新增: if (!info.Exists || info.Length is <= 0 or > 16384 || info.Attributes.HasFlag(FileAttributes.ReparsePoint))
372新增: throw new InvalidDataException("browser_network_unavailable");
373新增: using var snapshot = OpenPublishedFile(configPath);
374新增: using var reader = new StreamReader(snapshot);
375新增: var config = JsonNode.Parse(await reader.ReadToEndAsync(token)) as JsonObject
376新增: ?? throw new InvalidDataException("browser_network_unavailable");
377新增: var packet = config["network_mode"]?.GetValue<string>() == "packet";
378新增: if (packetOnly && !packet) throw new InvalidDataException("browser_network_unavailable");
379新增: var proxy = config["browser_proxy"]?.GetValue<string>();
380新增: Uri? address = null;
381新增: if (packet ? !PacketReady() : !Uri.TryCreate(proxy, UriKind.Absolute, out address) || address.Scheme != "http" ||
382新增: address.Host != "127.0.0.1" || address.IsDefaultPort || address.UserInfo != "" ||
383新增: address.AbsolutePath != "/" || address.Query != "" || address.Fragment != "")
384新增: throw new InvalidDataException("browser_network_unavailable");
385新增: var settings = packet ? new JsonObject { ["networkMode"] = "packet" } : new JsonObject { ["proxy"] = address!.GetLeftPart(UriPartial.Authority) };
386新增: if (config["timezone"] is JsonValue zone) settings["timezone"] = zone.DeepClone();
387新增: if (config["language"] is JsonValue lang) settings["language"] = lang.DeepClone();
388新增: return settings;
389新增: }
390新增: private static async Task Start(CancellationToken token)
391新增: {
392新增: if (browser is { HasExited: false }) return;
393新增: Close();
394新增: var root = AppContext.BaseDirectory;
395新增: var executable = Path.Combine(root, "node.exe");
396新增: var script = Path.Combine(root, "windows-browser.mjs");
397新增: if (!File.Exists(executable) || !File.Exists(script)) throw new InvalidDataException("browser_components_missing");
398新增: var settings = await ReadConfiguration(token);
399新增: var start = new ProcessStartInfo(executable)
400新增: {
401新增: UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true,
402新增: RedirectStandardError = true, CreateNoWindow = true, WorkingDirectory = root,
403新增: StandardInputEncoding = Protocol.Utf8, StandardOutputEncoding = Protocol.Utf8, StandardErrorEncoding = Protocol.Utf8,
404新增: };
405新增: start.ArgumentList.Add(script);
406新增: browser = Process.Start(start) ?? throw new InvalidDataException("browser_unavailable");
407新增: var process = browser;
408新增: try { browserJob = new GuestProcessJob(process); }
409新增: catch { Close(); throw new InvalidDataException("browser_process_unavailable"); }
410新增: replies = new ReadAheadStream(process.StandardOutput.BaseStream);
411新增: errors = Task.Run(async () =>
412新增: {
413新增: var discard = new char[4096];
414新增: try { while (await process.StandardError.ReadAsync(discard) != 0) { } }
415新增: catch (ObjectDisposedException) { }
416新增: });
417新增: var result = await Control(new JsonObject
418新增: {
419新增: ["operation"] = "configure", ["input"] = settings,
420新增: }, token);
421新增: if (result?["ok"]?.GetValue<bool>() != true) { Close(); throw new InvalidDataException("browser_network_unavailable"); }
422新增: }
423新增:
424新增: private static async Task<JsonObject> Control(JsonObject value, CancellationToken token)
425新增: {
426新增: wirePending = true;
427新增: await Protocol.Write(browser!.StandardInput.BaseStream, value, token);
428新增: var result = await Protocol.Read(replies!, Protocol.WireLimit, token) ?? throw new EndOfStreamException();
429新增: wirePending = false;
430新增: return result;
431新增: }
432新增:
433新增: private static async Task RevokeNode(string project, string grant)
434新增: {
435新增: await Gate.WaitAsync();
436新增: try
437新增: {
438新增: if (browser is not { HasExited: false }) return;
439新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
440新增: foreach (var editor in EditorConnections.Values.Where(e => e.Project == project && e.Grant == grant))
441新增: {
442新增: await Control(new JsonObject { ["operation"] = "editor-revoke", ["input"] = new JsonObject { ["workspace"] = project, ["connection"] = editor.ID } }, timeout.Token);
443新增: EditorConnections.TryRemove(editor.ID, out _);
444新增: }
445新增: }
446新增: catch { /* Every editor request also checks the live project resolver. */ }
447新增: finally { Gate.Release(); }
448新增: }
449新增:
450新增: internal static bool BrowserExecutableInstalled() =>
451新增: File.Exists(Path.Combine(AppContext.BaseDirectory, "chrome", "chrome.exe")) ||
452新增: new[] { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) }
453新增: .Any(basePath => new[] { "Google/Chrome/Application/chrome.exe", "Microsoft/Edge/Application/msedge.exe" }.Any(relative => File.Exists(Path.Combine(basePath, relative))));
454新增:
455新增: internal static JsonObject Status()
456新增: {
457新增: var root = AppContext.BaseDirectory;
458新增: var installed = new[] { "node.exe", "windows-browser.mjs", "windows-browser-extensions.mjs", "playwright/index.mjs", "modules/browser-clipboard.mjs", "modules/browser-uploads.mjs", "modules/browser-downloads.mjs", "modules/browser-cookies.mjs", "modules/browser-extensions.mjs", "modules/browser-vault.mjs", "split-extension/manifest.json", "split-extension/control.html", "split-extension/control.js" }.All(file => File.Exists(Path.Combine(root, file)));
459新增: installed &= BrowserExecutableInstalled();
460新增: var network = false;var phoneNetwork = false;
461新增: try
462新增: {
463新增: var file = new FileInfo(Path.Combine(root, "guest-config.json"));
464新增: JsonObject? config = null;
465新增: if (file.Exists && file.Length is > 0 and <= 16384)
466新增: {
467新增: using var snapshot = OpenPublishedFile(file.FullName);
468新增: using var reader = new StreamReader(snapshot);
469新增: config = JsonNode.Parse(reader.ReadToEnd()) as JsonObject;
470新增: }
471新增: phoneNetwork = config?["network_mode"]?.GetValue<string>() == "packet" && PacketReady();
472新增: network = config?["network_mode"]?.GetValue<string>() == "packet" ? phoneNetwork : Uri.TryCreate(config?["browser_proxy"]?.GetValue<string>(), UriKind.Absolute, out var proxy) && proxy.Scheme == "http" && proxy.Host == "127.0.0.1" && !proxy.IsDefaultPort && proxy.UserInfo == "" && proxy.AbsolutePath == "/" && proxy.Query == "" && proxy.Fragment == "";
473新增: }
474新增: catch { }
475新增: return new JsonObject { ["installed"] = installed, ["network_configured"] = network, ["ready"] = ready && browser is { HasExited: false } && SessionGuard.Available(), ["editor_installed"] = WindowsEditorServer.Installed(), ["phone_installed"] = WindowsPhoneBrowser.Installed(), ["phone_network_configured"] = phoneNetwork, ["capabilities"] = features.DeepClone() };
476新增: }
477新增:
478新增: private static async Task Observe(Task task) { try { await task; } catch { /* reply drain owns cleanup */ } }
479新增:
480新增: private static FileStream OpenPublishedFile(string path)
481新增: {
482新增: var snapshot = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
483新增: if (snapshot.Length is > 0 and <= 16384) return snapshot;
484新增: snapshot.Dispose();
485新增: throw new InvalidDataException("browser_network_unavailable");
486新增: }
487新增:
488新增: internal static void Close()
489新增: {
490新增: ready = false;
491新增: wirePending = false;
492新增: cachedPageFrame = null;
493新增: pagePointerOwner = null;
494新增: pagePointerReleasePending = false;
495新增: BrowserWindowCapture.Close();
496新增: BrowserPasteInput.Close();
497新增: var process = Interlocked.Exchange(ref browser, null);
498新增: if (process is null) return;
499新增: try
500新增: {
501新增: process.StandardInput.Close();
502新增: if (!process.WaitForExit(2000)) process.Kill(true);
503新增: process.WaitForExit(2000);
504新增: }
505新增: catch (InvalidOperationException) { }
506新增: finally { browserJob?.Dispose(); browserJob = null; replies?.Dispose(); replies = null; process.Dispose(); }
507新增: if (errors is { IsCompleted: true }) { try { errors.GetAwaiter().GetResult(); } catch { } }
508新增: errors = null;
509新增: }
510新增:}
新增scripts/guest-os/guest-clipboard-windows/BrowserWindowCapture.cs+436 −0看文件
@@ -0,0 +1,436 @@
1新增:using System.Diagnostics;
2新增:using System.Drawing.Drawing2D;
3新增:using System.Drawing.Imaging;
4新增:using System.Runtime.InteropServices;
5新增:using System.Security.Cryptography;
6新增:using System.Security.Principal;
7新增:using System.Text;
8新增:using System.Text.Json.Nodes;
9新增:using InputLease = Cage.GuestClipboard.NativeInputCoordinator.Lease;
10新增:
11新增:namespace Cage.GuestClipboard;
12新增:
13新增:// Only the current Node child's Chrome UI is eligible. Public requests never
14新增:// supply a PID, HWND, screen rectangle or executable path.
15新增:internal static class BrowserWindowCapture
16新增:{
17新增: private static readonly SemaphoreSlim Captures = new(1, 1);
18新增: private static readonly Dictionary<int, Pin> Windows = new();
19新增: private static View? last;
20新增: private static string publicTarget="";
21新增: private sealed record OverlayCache(byte[] Pixels, Rectangle Crop, Rectangle Destination, JsonObject Image);
22新增: private static OverlayCache? cachedOverlay;
23新增: private static JsonObject? lastFrame;
24新增: private static string lastSequence = "";
25新增: private static readonly HashSet<InputLease> browserLeases = [];
26新增: internal static InputLease OpenLease(){var lease=NativeGuestInput.OpenLease();lock(browserLeases)browserLeases.Add(lease);return lease;}
27新增: internal static void CloseLease(InputLease lease){lock(browserLeases)browserLeases.Remove(lease);NativeGuestInput.CloseLease(lease);}
28新增: internal static bool ReleaseInput(InputLease lease,JsonObject input)
29新增: {
30新增: if(input["kind"]?.GetValue<string>()=="key"&&input["down"]?.GetValue<bool>()==false)
31新增: {
32新增: if(lease.Symbols.Remove(input["keysym"]?.GetValue<uint>()??0,out var strokes))NativeGuestInput.ReleaseInputs(lease,strokes);
33新增: return true;
34新增: }
35新增: var buttons=NativeGuestInput.PressedButtons(lease);
36新增: if(buttons!=0&&input["kind"]?.GetValue<string>()=="pointer"&&input["mask"]?.GetValue<int>()==0)
37新增: {
38新增: NativeGuestInput.ReleaseInputs(lease,new[]{1,2,4}.Where(bit=>(buttons&bit)!=0).Select(bit=>InputStroke.Button(bit,true)).ToArray());return true;
39新增: }
40新增: return false;
41新增: }
42新增: internal static bool FocusRenderer(Process node,JsonObject proof)
43新增: {var view=Resolve(node,proof);if(view.NativeUI)return false;Focus(view);return true;}
44新增: private sealed record Pin(Process Process, DateTime Started, string Executable, IntPtr Window);
45新增: private sealed record Popup(IntPtr Window, Rectangle Bounds, Rectangle Client);
46新增: private sealed record View(Pin Pin, Rectangle Window, Rectangle Client, Rectangle Surface, Popup[] Popups, bool NativeUI, bool InlineUI,
47新增: string NodeTarget, string Document, string ID, string Token, int X, int Y, int Width, int Height);
48新增: [StructLayout(LayoutKind.Sequential)] private struct Rect { internal int Left, Top, Right, Bottom; internal readonly Rectangle Box => Rectangle.FromLTRB(Left, Top, Right, Bottom); }
49新增: [StructLayout(LayoutKind.Sequential)] private struct Point { internal int X,Y; }
50新增: [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] private struct ProcessEntry { internal uint Size,Usage,ID;internal nuint Heap;internal uint Module,Threads,Parent;internal int Priority;internal uint Flags;[MarshalAs(UnmanagedType.ByValTStr,SizeConst=260)]internal string File; }
51新增: [StructLayout(LayoutKind.Sequential)] private struct GuiThread { internal uint Size,Flags;internal IntPtr Active,Focus,Capture,MenuOwner,MoveSize,Caret;internal Rect CaretRect; }
52新增: private delegate bool Enumerate(IntPtr window, IntPtr data);
53新增:
54新增: private static void ValidateNode(Process node)
55新增: { if (!SessionGuard.Available() || node.HasExited || node.SessionId != Process.GetCurrentProcess().SessionId) throw new InvalidDataException("browser_target_changed"); }
56新增: private static void Validate(Pin pin)
57新增: {
58新增: if (!SessionGuard.Available() || pin.Process.HasExited || pin.Process.StartTime.ToUniversalTime() != pin.Started || !IsWindowVisible(pin.Window) || IsIconic(pin.Window) ||
59新增: GetWindowThreadProcessId(pin.Window,out var pid)==0 || pid!=pin.Process.Id || !string.Equals(pin.Process.MainModule?.FileName,pin.Executable,StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("browser_target_changed");
60新增: }
61新增: private static Process Chrome(Process node)
62新增: {
63新增: ValidateNode(node);
64新增: var choices = new[] {
65新增: Path.Combine(AppContext.BaseDirectory,"chrome","chrome.exe"),
66新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"Google","Chrome","Application","chrome.exe"),
67新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),"Google","Chrome","Application","chrome.exe"),
68新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"Microsoft","Edge","Application","msedge.exe"),
69新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),"Microsoft","Edge","Application","msedge.exe"),
70新增: };
71新增: var snapshot=CreateToolhelp32Snapshot(2,0);
72新增: if(snapshot==new IntPtr(-1))throw new InvalidDataException("browser_process_unavailable");
73新增: var found=new List<Process>();
74新增: try
75新增: {
76新增: var entry=new ProcessEntry{Size=(uint)Marshal.SizeOf<ProcessEntry>(),File=""};
77新增: if(Process32First(snapshot,ref entry))do
78新增: {
79新增: if(entry.Parent!=node.Id)continue;
80新增: Process? process=null;
81新增: try
82新增: {
83新增: process=Process.GetProcessById((int)entry.ID);
84新增: var executable=process.MainModule?.FileName;
85新增: if(process.SessionId!=node.SessionId || process.StartTime<node.StartTime || executable is null || !choices.Contains(executable,StringComparer.OrdinalIgnoreCase))continue;
86新增: if(!SessionGuard.OwnsProcess(process))continue;
87新增: found.Add(process);process=null;
88新增: }
89新增: catch { }
90新增: finally {process?.Dispose();}
91新增: }while(Process32Next(snapshot,ref entry));
92新增: }
93新增: finally {CloseHandle(snapshot);}
94新增: if(found.Count!=1){foreach(var p in found)p.Dispose();throw new InvalidDataException("browser_process_unavailable");}
95新增: return found[0];
96新增: }
97新增: private static Rectangle Client(IntPtr window)
98新增: {
99新增: if(!GetClientRect(window,out var client))throw new InvalidDataException("browser_target_changed");
100新增: var point=new Point();if(!ClientToScreen(window,ref point))throw new InvalidDataException("browser_target_changed");
101新增: return new Rectangle(point.X,point.Y,client.Right-client.Left,client.Bottom-client.Top);
102新增: }
103新增: private static string Class(IntPtr window){var text=new StringBuilder(128);return GetClassName(window,text,text.Capacity)>0?text.ToString():"";}
104新增: private static Rectangle RendererSurface(IntPtr window,Rectangle client)
105新增: {
106新增: // Chrome can retain visible renderer HWNDs for background documents.
107新增: // Hit testing follows native child z-order; the largest old rectangle
108新增: // is not evidence that its document is the one on screen.
109新增: var screen=new Point{X=client.X+client.Width/2,Y=client.Y+client.Height/2};
110新增: var parent=window;Rectangle surface=default;
111新增: for(var depth=0;depth<32;depth++)
112新增: {
113新增: var point=screen;if(!ScreenToClient(parent,ref point))throw new InvalidDataException("browser_target_changed");
114新增: // Chromium's legacy renderer HWND can be transparent/disabled
115新增: // while still representing the visible compositor surface.
116新增: var child=ChildWindowFromPointEx(parent,point,1);
117新增: if(child==IntPtr.Zero||child==parent)break;
118新增: if(!IsWindowVisible(child)||GetAncestor(child,2)!=window)throw new InvalidDataException("browser_target_changed");
119新增: // CDP can render a viewport larger than the native window. Keep
120新增: // that complete surface for coordinate conversion and clip only
121新增: // the native pixels we actually capture below.
122新增: if(Class(child)=="Chrome_RenderWidgetHostHWND"&&GetWindowRect(child,out var rect))surface=rect.Box;
123新增: parent=child;
124新增: }
125新增: if(surface.Width<1||surface.Height<1)throw new InvalidDataException("browser_capture_surface_unavailable");
126新增: return surface;
127新增: }
128新增: private static bool Matches(IntPtr window,JsonObject bounds)
129新增: {
130新增: if(!GetWindowRect(window,out var rectangle))return false;
131新增: var box=rectangle.Box;
132新增: foreach(var scale in new[]{1.0,GetDpiForWindow(window)/96.0})
133新增: {
134新增: int left=(int)Math.Round((bounds["left"]?.GetValue<double>()??double.NaN)*scale),top=(int)Math.Round((bounds["top"]?.GetValue<double>()??double.NaN)*scale);
135新增: int width=(int)Math.Round((bounds["width"]?.GetValue<double>()??0)*scale),height=(int)Math.Round((bounds["height"]?.GetValue<double>()??0)*scale);
136新增: if(Math.Abs(box.Left-left)<=12 && Math.Abs(box.Top-top)<=12 && Math.Abs(box.Width-width)<=24 && Math.Abs(box.Height-height)<=24)return true;
137新增: }
138新增: return false;
139新增: }
140新增: private static View Resolve(Process node,JsonObject proof)
141新增: {
142新增: ValidateNode(node);
143新增: var old=SetThreadDpiAwarenessContext(new IntPtr(-4));
144新增: try
145新增: {
146新增: var windowInfo=proof["window"] as JsonObject??throw new InvalidDataException("browser_window_proof_invalid");
147新增: var id=windowInfo["windowId"]?.GetValue<int>()??0;
148新增: var bounds=windowInfo["bounds"] as JsonObject??throw new InvalidDataException("browser_window_proof_invalid");
149新增: Pin? pin=null;
150新增: if(Windows.TryGetValue(id,out var existing))
151新增: {
152新增: try {Validate(existing);if(Matches(existing.Window,bounds))pin=existing;else{Windows.Remove(id);existing.Process.Dispose();}}
153新增: catch {Windows.Remove(id);existing.Process.Dispose();}
154新增: }
155新增: if(pin is null)
156新增: {
157新增: var process=Chrome(node);var candidates=new List<IntPtr>();
158新增: EnumWindows((window,_)=>{if(GetWindowThreadProcessId(window,out var pid)!=0 && pid==process.Id && IsWindowVisible(window) && !IsIconic(window) && GetWindow(window,4)==IntPtr.Zero && Class(window)=="Chrome_WidgetWin_1" && Matches(window,bounds))candidates.Add(window);return true;},IntPtr.Zero);
159新增: var foreground=GetAncestor(GetForegroundWindow(),3);
160新增: if(proof["documentFocused"]?.GetValue<bool>()==true && candidates.Contains(foreground))candidates=[foreground];
161新增: if(candidates.Count!=1){process.Dispose();throw new InvalidDataException("browser_window_unavailable");}
162新增: pin=new Pin(process,process.StartTime.ToUniversalTime(),process.MainModule!.FileName,candidates[0]);Windows[id]=pin;
163新增: }
164新增: Validate(pin);
165新增: if(!GetWindowRect(pin.Window,out var outside))throw new InvalidDataException("browser_target_changed");
166新增: var client=Client(pin.Window);var surface=RendererSurface(pin.Window,client);
167新增: var popups=new List<Popup>();
168新增: EnumWindows((window,_)=>{if(window!=pin.Window && GetWindowThreadProcessId(window,out var pid)!=0 && pid==pin.Process.Id && GetAncestor(window,3)==pin.Window && IsWindowVisible(window) && !IsIconic(window) && GetWindowRect(window,out var rect))
169新增: {var c=Client(window);if(c.Width>0&&c.Height>0&&(long)c.Width*c.Height<=40_000_000)popups.Add(new Popup(window,rect.Box,c));}return true;},IntPtr.Zero);
170新增: var thread=GetWindowThreadProcessId(pin.Window,out _);var info=new GuiThread{Size=(uint)Marshal.SizeOf<GuiThread>()};
171新增: var inlineUI=GetGUIThreadInfo(thread,ref info) && info.Focus!=IntPtr.Zero && GetAncestor(info.Focus,2)==pin.Window && proof["documentFocused"]?.GetValue<bool>()!=true && Class(info.Focus)!="Chrome_RenderWidgetHostHWND";
172新增: var ui=popups.Count>0 || inlineUI;
173新增: var target=proof["target"]?.GetValue<string>()??"";var document=proof["document"]?.GetValue<string>()??"";
174新增: var signature=new JsonArray(target,document,id,pin.Window.ToInt64(),outside.Left,outside.Top,outside.Right,outside.Bottom,surface.X,surface.Y,surface.Width,surface.Height,ui,inlineUI,
175新增: new JsonArray(popups.Select(p=>(JsonNode)new JsonArray(p.Window.ToInt64(),p.Bounds.X,p.Bounds.Y,p.Bounds.Width,p.Bounds.Height)).ToArray())).ToJsonString();
176新增: var opaque=Convert.ToHexString(SHA256.HashData(Protocol.Utf8.GetBytes(signature))).ToLowerInvariant()[..32];
177新增: return new View(pin,outside.Box,client,surface,popups.ToArray(),ui,inlineUI,target,document,proof["id"]?.GetValue<string>()??"",opaque,
178新增: proof["x"]?.GetValue<int>()??0,proof["y"]?.GetValue<int>()??0,proof["width"]?.GetValue<int>()??0,proof["height"]?.GetValue<int>()??0);
179新增: }
180新增: finally {if(old!=IntPtr.Zero)SetThreadDpiAwarenessContext(old);}
181新增: }
182新增: internal static async Task Decorate(Process node,JsonObject frame,Func<Task<JsonObject>> currentProof)
183新增: {
184新增: var proof=frame["native"] as JsonObject??throw new InvalidDataException("browser_window_proof_invalid");
185新增: if(proof["target"]?.GetValue<string>()!=frame["target"]?.GetValue<string>())throw new InvalidDataException("browser_target_changed");
186新增: var view=Resolve(node,proof);
187新增: var overlays=new JsonArray();
188新增: if(view.NativeUI)
189新增: {
190新增: await Captures.WaitAsync();
191新增: try
192新增: {
193新增: // An independent popup has its own validated capture below.
194新增: // Keep the underlying CDP page instead of duplicating Edge's
195新增: // window controls and tab strip inside the Cage browser pane.
196新增: if (view.Popups.Length == 0)
197新增: {
198新增: var bytes=await GuestWindowCapture.Capture(view.Pin.Window,view.Pin.Process.Id,view.Client.Width,view.Client.Height,
199新增: ()=>Validate(view.Pin),allowSolid:proof["blankDocument"]?.GetValue<bool>()==true);
200新增: var visible = Rectangle.Intersect(view.Surface, view.Client);
201新增: var crop = new Rectangle(visible.X - view.Client.X, visible.Y - view.Client.Y, visible.Width, visible.Height);
202新增: var sx = (double)view.Width / view.Surface.Width;
203新增: var sy = (double)view.Height / view.Surface.Height;
204新增: overlays.Add(Image(bytes, crop,
205新增: view.X + (int)Math.Round((visible.X - view.Surface.X) * sx),
206新增: view.Y + (int)Math.Round((visible.Y - view.Surface.Y) * sy),
207新增: (int)Math.Round(visible.Width * sx), (int)Math.Round(visible.Height * sy)));
208新增: }
209新增: foreach(var popup in view.Popups.Reverse())
210新增: {
211新增: void Check(){Validate(view.Pin);if(GetWindowThreadProcessId(popup.Window,out var pid)==0||pid!=view.Pin.Process.Id||GetAncestor(popup.Window,3)!=view.Pin.Window||!GetWindowRect(popup.Window,out var rect)||rect.Box!=popup.Bounds||Client(popup.Window)!=popup.Client)throw new InvalidDataException("browser_target_changed");}
212新增: var png=await GuestWindowCapture.Capture(popup.Window,view.Pin.Process.Id,popup.Client.Width,popup.Client.Height,Check,preserveAlpha:true);
213新增: var sx=(double)view.Width/view.Surface.Width;var sy=(double)view.Height/view.Surface.Height;
214新增: var destination=new Rectangle(view.X+(int)Math.Round((popup.Client.X-view.Surface.X)*sx),view.Y+(int)Math.Round((popup.Client.Y-view.Surface.Y)*sy),(int)Math.Round(popup.Client.Width*sx),(int)Math.Round(popup.Client.Height*sy));
215新增: var clipped=Rectangle.Intersect(destination,new Rectangle(0,0,frame["width"]!.GetValue<int>(),frame["height"]!.GetValue<int>()));
216新增: if(clipped.Width<1||clipped.Height<1)continue;
217新增: var sectionX=(int)Math.Round((clipped.X-destination.X)/sx);var sectionY=(int)Math.Round((clipped.Y-destination.Y)/sy);
218新增: var section=new Rectangle(sectionX,sectionY,Math.Min(popup.Client.Width-sectionX,(int)Math.Round(clipped.Width/sx)),Math.Min(popup.Client.Height-sectionY,(int)Math.Round(clipped.Height/sy)));
219新增: overlays.Add(Image(png,section,clipped.X,clipped.Y,clipped.Width,clipped.Height));
220新增: }
221新增: var after=Resolve(node,await currentProof());if(after.Token!=view.Token)throw new InvalidDataException("browser_target_changed");
222新增: }
223新增: finally {Captures.Release();}
224新增: }
225新增: last=view;publicTarget=view.Token;frame["target"]=view.Token;frame.Remove("native");if(overlays.Count>0)frame["overlays"]=overlays;
226新增: }
227新增: internal static JsonObject FrameReply(JsonObject frame, string? after)
228新增: {
229新增: frame.Remove("sequence");
230新增: if (lastFrame is null || !JsonNode.DeepEquals(lastFrame, frame))
231新增: {
232新增: var bytes = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(frame);
233新增: if (bytes.Length > Protocol.WireLimit) throw new InvalidDataException("browser_frame_limit");
234新增: lastSequence = Convert.ToHexString(SHA256.HashData(bytes));
235新增: lastFrame = (JsonObject)frame.DeepClone();
236新增: }
237新增: var sequence = lastSequence;
238新增: if (sequence == after) return new JsonObject { ["unchanged"] = true, ["sequence"] = sequence };
239新增: frame["sequence"] = sequence;
240新增: return frame;
241新增: }
242新增:
243新增: private static JsonObject Image(byte[] pixels,Rectangle region,int x,int y,int width,int height)
244新增: {
245新增: var destination = new Rectangle(x, y, width, height);
246新增: if (cachedOverlay is { } cached && ReferenceEquals(cached.Pixels, pixels) && cached.Crop == region && cached.Destination == destination)
247新增: return (JsonObject)cached.Image.DeepClone();
248新增: using var input = new MemoryStream(pixels, false);
249新增: using var source = new Bitmap(input);
250新增: if(width<1||height<1||(long)width*height>40_000_000||region.X<0||region.Y<0||region.Right>source.Width||region.Bottom>source.Height)throw new InvalidDataException("browser_frame_limit");
251新增: using var output=new Bitmap(width,height,PixelFormat.Format32bppArgb);using(var g=Graphics.FromImage(output)){g.InterpolationMode=InterpolationMode.HighQualityBicubic;g.DrawImage(source,new Rectangle(0,0,width,height),region,GraphicsUnit.Pixel);}
252新增: using var bytes=new MemoryStream();output.Save(bytes,ImageFormat.Png);if(bytes.Length>Protocol.PngLimit)throw new InvalidDataException("browser_frame_limit");
253新增: var image = new JsonObject{["png"]=Convert.ToBase64String(bytes.ToArray()),["x"]=x,["y"]=y,["width"]=width,["height"]=height};
254新增: cachedOverlay = new OverlayCache(pixels, region, destination, (JsonObject)image.DeepClone());
255新增: return image;
256新增: }
257新增: internal static bool HandleInput(Process node,InputLease lease,JsonObject input,JsonObject proof,bool pagePointerHeld=false)
258新增: {
259新增: var prior=SetThreadDpiAwarenessContext(new IntPtr(-4));
260新增: try{return HandleInputCore(node,lease,input,proof,pagePointerHeld);}finally{if(prior!=IntPtr.Zero)SetThreadDpiAwarenessContext(prior);}
261新增: }
262新增: private static bool HandleInputCore(Process node,InputLease lease,JsonObject input,JsonObject proof,bool pagePointerHeld)
263新增: {
264新增: var before=last??throw new InvalidDataException("browser_target_changed");var now=Resolve(node,proof);
265新增: if(pagePointerHeld && now.InlineUI && input["kind"]?.GetValue<string>()=="pointer")throw new InvalidDataException("browser_target_changed");
266新增: if(proof["focusAmbiguous"]?.GetValue<bool>()==true)throw new InvalidDataException("browser_target_changed");
267新增: if(!now.NativeUI&&proof["documentFocused"]?.GetValue<bool>()!=true)throw new InvalidDataException("browser_target_changed");
268新增: var mouseMask=NativeGuestInput.PressedButtons(lease);
269新增: var released=input["kind"]?.GetValue<string>()=="key"&&input["down"]?.GetValue<bool>()==false || mouseMask!=0&&input["kind"]?.GetValue<string>()=="pointer"&&input["mask"]?.GetValue<int>()==0;
270新增: if(input["target"]?.GetValue<string>()!=publicTarget || now.Token!=before.Token && !released)throw new InvalidDataException("browser_target_changed");
271新增: input["target"]=now.NodeTarget;
272新增: if(input["kind"]?.GetValue<string>()=="pointer")
273新增: {
274新增: var x=input["x"]?.GetValue<int>()??-1;var y=input["y"]?.GetValue<int>()??-1;
275新增: if(x<now.X||x>=now.X+now.Width||y<now.Y||y>=now.Y+now.Height)
276新增: {
277新增: if(mouseMask!=0){input["x"]=Math.Clamp(x,now.X,now.X+now.Width-1);input["y"]=Math.Clamp(y,now.Y,now.Y+now.Height-1);}
278新增: else
279新增: {
280新增: // A click into another split pane first dismisses our own
281新增: // chrome UI, then lets CDP activate that existing webpage.
282新增: if(now.NativeUI){Focus(now);Tap(now,[InputStroke.Key(27,false),InputStroke.Key(27,true)]);}
283新增: var modifiers=(NativeGuestInput.PressedKey(18)?1:0)|(NativeGuestInput.PressedKey(17)?2:0)|(NativeGuestInput.PressedKey(91)||NativeGuestInput.PressedKey(92)?4:0)|(NativeGuestInput.PressedKey(16)?8:0);
284新增: input["modifiers"]=modifiers;return false;
285新增: }
286新增: }
287新增: }
288新增: Focus(now);
289新增: if(input["kind"]?.GetValue<string>()=="pointer" && !now.InlineUI && mouseMask==0)
290新增: {
291新增: var x=input["x"]?.GetValue<int>()??-1;
292新增: var y=input["y"]?.GetValue<int>()??-1;
293新增: var screenX=now.Surface.X+(int)Math.Round((x-now.X)*(double)now.Surface.Width/now.Width);
294新增: var screenY=now.Surface.Y+(int)Math.Round((y-now.Y)*(double)now.Surface.Height/now.Height);
295新增: if(pagePointerHeld || !now.Popups.Any(p=>p.Client.Contains(screenX,screenY)))
296新增: {
297新增: // CDP page coordinates remain valid beyond the guest desktop.
298新增: input["modifiers"]=(NativeGuestInput.PressedKey(18)?1:0)|(NativeGuestInput.PressedKey(17)?2:0)|(NativeGuestInput.PressedKey(91)||NativeGuestInput.PressedKey(92)?4:0)|(NativeGuestInput.PressedKey(16)?8:0);
299新增: return false;
300新增: }
301新增: }
302新增: if(input["kind"]?.GetValue<string>()=="pointer")Pointer(now,lease,input);
303新增: else if(input["kind"]?.GetValue<string>()=="key")Keyboard(now,lease,input);
304新增: else throw new InvalidDataException("browser_input_invalid");
305新增: return true;
306新增: }
307新增: internal static bool SelectPane(Process node,InputLease lease,JsonObject input,JsonObject proof)
308新增: {
309新增: if(input["kind"]?.GetValue<string>()!="pointer"||NativeGuestInput.PressedButtons(lease)!=0||((input["mask"]?.GetValue<int>()??0)&7)==0)return false;
310新增: var view=Resolve(node,proof);if(last is null||input["target"]?.GetValue<string>()!=publicTarget||view.Token!=last.Token)throw new InvalidDataException("browser_target_changed");
311新增: var x=input["x"]?.GetValue<int>()??-1;
312新增: if(x>=view.X&&x<view.X+view.Width)return false;
313新增: if(view.NativeUI){Focus(view);Tap(view,[InputStroke.Key(27,false),InputStroke.Key(27,true)]);}
314新增: return true;
315新增: }
316新增: internal static void Transition(Process node,JsonObject proof)
317新增: {
318新增: var view=Resolve(node,proof);
319新增: if(last is not null&&last.NodeTarget==view.NodeTarget&&last.Pin.Window==view.Pin.Window&&last.Pin.Started==view.Pin.Started)last=view;
320新增: }
321新增: internal static bool Edit(Process node,JsonObject proof,string action,string text="")
322新增: {
323新增: var view=Resolve(node,proof);if(!view.NativeUI)return false;Focus(view);
324新增: if(action=="insert-text")
325新增: {if(Protocol.Utf8.GetByteCount(text)>8192)throw new InvalidDataException("browser_input_invalid");Tap(view,text.SelectMany(c=>new[]{InputStroke.Key(c,false,true),InputStroke.Key(c,true,true)}).ToArray());}
326新增: else
327新增: {
328新增: ushort key=action switch{"paste"=>86,"copy"=>67,"cut"=>88,"select-all"=>65,_=>throw new InvalidDataException("browser_input_invalid")};
329新增: Tap(view,[InputStroke.Key(17,false),InputStroke.Key(key,false),InputStroke.Key(key,true),InputStroke.Key(17,true)]);
330新增: }
331新增: return true;
332新增: }
333新增: internal static async Task<JsonObject?> Ime(Process node,JsonObject proof,JsonObject input,CancellationToken token)
334新增: {
335新增: var view=Resolve(node,proof);if(!view.NativeUI)return null;Focus(view);
336新增: var result=await WindowsIme.Handle(input,view.Pin.Process.Id,view.Token,view.Surface.X,view.Surface.Y,
337新增: text=>Tap(view,text.SelectMany(c=>new[]{InputStroke.Key(c,false,true),InputStroke.Key(c,true,true)}).ToArray()),token);
338新增: if(result["rect"] is JsonArray rect && rect.Count==4)
339新增: {
340新增: var sx=(double)view.Width/view.Surface.Width;var sy=(double)view.Height/view.Surface.Height;
341新增: result["rect"]=new JsonArray(view.X+rect[0]!.GetValue<double>()*sx,view.Y+rect[1]!.GetValue<double>()*sy,rect[2]!.GetValue<double>()*sx,rect[3]!.GetValue<double>()*sy);
342新增: }
343新增: return result;
344新增: }
345新增: private static void Focus(View view)
346新增: {
347新增: Validate(view.Pin);if(GetAncestor(GetForegroundWindow(),3)!=view.Pin.Window)SetForegroundWindow(view.Pin.Window);
348新增: if(GetAncestor(GetForegroundWindow(),3)!=view.Pin.Window)throw new InvalidDataException("browser_focus_required");
349新增: }
350新增: private static Func<bool> ReleaseAllowed(View view)
351新增: {
352新增: var pid=view.Pin.Process.Id;var started=view.Pin.Started;var executable=view.Pin.Executable;var window=view.Pin.Window;var session=view.Pin.Process.SessionId;
353新增: return ()=>
354新增: {
355新增: if(!SessionGuard.Available())return false;
356新增: try
357新增: {
358新增: using var process=Process.GetProcessById(pid);
359新增: if(process.HasExited)return true;
360新增: if(process.StartTime.ToUniversalTime()!=started||process.SessionId!=session||!string.Equals(process.MainModule?.FileName,executable,StringComparison.OrdinalIgnoreCase))return false;
361新增: return !IsWindow(window)||GetWindowThreadProcessId(window,out var owner)!=0&&owner==pid;
362新增: }
363新增: catch(ArgumentException){return true;} // The verified owning process has exited.
364新增: catch(InvalidOperationException){return true;}
365新增: catch{return false;}
366新增: };
367新增: }
368新增: private static void Emit(View view,InputLease lease,InputStroke[] strokes)
369新增: {
370新增: NativeGuestInput.Emit(lease,strokes,()=>{Validate(view.Pin);if(GetAncestor(GetForegroundWindow(),3)!=view.Pin.Window)throw new InvalidDataException("browser_focus_required");},ReleaseAllowed(view));
371新增: }
372新增: private static void Tap(View view,InputStroke[] strokes)
373新增: {
374新增: var lease=NativeGuestInput.OpenLease();try{Emit(view,lease,strokes);}finally{NativeGuestInput.CloseLease(lease);}
375新增: }
376新增: private static void Pointer(View view,InputLease lease,JsonObject input)
377新增: {
378新增: var x=input["x"]?.GetValue<int>()??-1;var y=input["y"]?.GetValue<int>()??-1;var mask=input["mask"]?.GetValue<int>()??-1;
379新增: if(mask<0||mask>127||x<0||y<0)throw new InvalidDataException("browser_input_invalid");
380新增: var screenX=view.Surface.X+(int)Math.Round((x-view.X)*(double)view.Surface.Width/view.Width);var screenY=view.Surface.Y+(int)Math.Round((y-view.Y)*(double)view.Surface.Height/view.Height);
381新增: if(!view.Client.Contains(screenX,screenY)&&!view.Popups.Any(p=>p.Client.Contains(screenX,screenY)))throw new InvalidDataException("browser_input_invalid");
382新增: if(!SetCursorPos(screenX,screenY))throw new InvalidDataException("browser_input_failed");
383新增: var mouseMask=NativeGuestInput.PressedButtons(lease);var inputs=new List<InputStroke>();
384新增: foreach(var bit in new[]{1,2,4})if((mask&bit)!=(mouseMask&bit))inputs.Add(InputStroke.Button(bit,(mask&bit)==0));
385新增: if((mask&24)!=0)inputs.Add(InputStroke.Wheel((mask&8)!=0?120:-120));
386新增: if((mask&96)!=0)inputs.Add(InputStroke.Wheel((mask&32)!=0?-120:120,true));
387新增: if(inputs.Count>0)Emit(view,lease,inputs.ToArray());
388新增: }
389新增: private static void Keyboard(View view,InputLease lease,JsonObject input)
390新增: {
391新增: var sym=input["keysym"]?.GetValue<uint>()??0;var down=input["down"]?.GetValue<bool>()??false;
392新增: var special=new Dictionary<uint,ushort>{{0xff08,8},{0xff09,9},{0xff0d,13},{0xff1b,27},{0xff50,36},{0xff51,37},{0xff52,38},{0xff53,39},{0xff54,40},{0xff55,33},{0xff56,34},{0xff57,35},{0xffff,46},{0xffe1,16},{0xffe2,16},{0xffe3,17},{0xffe4,17},{0xffe9,18},{0xffea,18},{0xffe7,91},{0xffe8,92},{0xffeb,91},{0xffec,92}};
393新增: if(sym>=0xffbe&&sym<=0xffc9)special[sym]=(ushort)(112+sym-0xffbe);
394新增: if(!down)
395新增: {
396新增: if(lease.Symbols.Remove(sym,out var prior))Emit(view,lease,prior.Select(stroke=>stroke with{Up=true}).ToArray());
397新增: return;
398新增: }
399新增: if(lease.Symbols.TryGetValue(sym,out var repeated)){Emit(view,lease,repeated);return;}
400新增: if(special.TryGetValue(sym,out var key)){var strokes=new[]{InputStroke.Key(key,false)};lease.Symbols[sym]=strokes;Emit(view,lease,strokes);return;}
401新增: var cp=(sym&0xff000000)==0x01000000?sym&0xffffff:sym;
402新增: if(cp<32||cp>0x10ffff||cp is >=0xd800 and <=0xdfff)throw new InvalidDataException("browser_input_invalid");
403新增: InputStroke[] characters;
404新增: if(cp<=0xffff && (NativeGuestInput.PressedKey(17)||NativeGuestInput.PressedKey(18)))
405新增: {var mapped=VkKeyScan((char)cp);if(mapped<0)throw new InvalidDataException("browser_input_invalid");characters=[InputStroke.Key((ushort)(mapped&255),false)];}
406新增: else characters=char.ConvertFromUtf32((int)cp).Select(c=>InputStroke.Key(c,false,true)).ToArray();
407新增: lease.Symbols[sym]=characters;Emit(view,lease,characters);
408新增: }
409新增: internal static void Close(){InputLease[] leases;lock(browserLeases)leases=browserLeases.ToArray();foreach(var lease in leases)NativeGuestInput.ResetLease(lease);foreach(var p in Windows.Values)p.Process.Dispose();Windows.Clear();last=null;publicTarget="";cachedOverlay=null;lastFrame=null;lastSequence="";}
410新增:
411新增: [DllImport("kernel32.dll",SetLastError=true)]private static extern IntPtr CreateToolhelp32Snapshot(uint flags,uint process);
412新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode,EntryPoint="Process32FirstW")]private static extern bool Process32First(IntPtr snapshot,ref ProcessEntry entry);
413新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode,EntryPoint="Process32NextW")]private static extern bool Process32Next(IntPtr snapshot,ref ProcessEntry entry);
414新增: [DllImport("kernel32.dll")]private static extern bool CloseHandle(IntPtr handle);
415新增: [DllImport("user32.dll")]private static extern bool EnumWindows(Enumerate callback,IntPtr data);
416新增: [DllImport("user32.dll")]private static extern bool EnumChildWindows(IntPtr window,Enumerate callback,IntPtr data);
417新增: [DllImport("user32.dll")]private static extern uint GetWindowThreadProcessId(IntPtr window,out uint process);
418新增: [DllImport("user32.dll")]private static extern bool GetWindowRect(IntPtr window,out Rect rectangle);
419新增: [DllImport("user32.dll")]private static extern bool GetClientRect(IntPtr window,out Rect rectangle);
420新增: [DllImport("user32.dll")]private static extern bool ClientToScreen(IntPtr window,ref Point point);
421新增: [DllImport("user32.dll")]private static extern bool ScreenToClient(IntPtr window,ref Point point);
422新增: [DllImport("user32.dll")]private static extern IntPtr ChildWindowFromPointEx(IntPtr parent,Point point,uint flags);
423新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,EntryPoint="GetClassNameW")]private static extern int GetClassName(IntPtr window,StringBuilder name,int length);
424新增: [DllImport("user32.dll")]private static extern IntPtr GetWindow(IntPtr window,uint command);
425新增: [DllImport("user32.dll")]private static extern IntPtr GetAncestor(IntPtr window,uint flags);
426新增: [DllImport("user32.dll")]private static extern bool IsWindowVisible(IntPtr window);
427新增: [DllImport("user32.dll")]private static extern bool IsIconic(IntPtr window);
428新增: [DllImport("user32.dll")]private static extern IntPtr GetForegroundWindow();
429新增: [DllImport("user32.dll")]private static extern bool SetForegroundWindow(IntPtr window);
430新增: [DllImport("user32.dll")]private static extern uint GetDpiForWindow(IntPtr window);
431新增: [DllImport("user32.dll")]private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
432新增: [DllImport("user32.dll")]private static extern bool GetGUIThreadInfo(uint thread,ref GuiThread info);
433新增: [DllImport("user32.dll")]private static extern bool SetCursorPos(int x,int y);
434新增: [DllImport("user32.dll")]private static extern bool IsWindow(IntPtr window);
435新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,EntryPoint="VkKeyScanW")]private static extern short VkKeyScan(char key);
436新增:}
新增scripts/guest-os/guest-clipboard-windows/Cage.GuestClipboard.csproj+25 −0看文件
@@ -0,0 +1,25 @@
1新增:<Project Sdk="Microsoft.NET.Sdk">
2新增: <PropertyGroup>
3新增: <OutputType>Exe</OutputType>
4新增: <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
5新增: <UseWindowsForms>true</UseWindowsForms>
6新增: <UseWPF>true</UseWPF>
7新增: <EnableWindowsTargeting>true</EnableWindowsTargeting>
8新增: <Nullable>enable</Nullable>
9新增: <ImplicitUsings>enable</ImplicitUsings>
10新增: <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
11新增: <RuntimeIdentifier>win-x64</RuntimeIdentifier>
12新增: <SelfContained>true</SelfContained>
13新增: <PublishSingleFile>true</PublishSingleFile>
14新增: <AssemblyName>Cage.GuestClipboard</AssemblyName>
15新增: </PropertyGroup>
16新增: <ItemGroup>
17新增: <EmbeddedResource Include="../../../internal/workbench/cli_channel.py" LogicalName="Cage.CliChannel" />
18新增: <EmbeddedResource Include="../../../internal/cage/claude-account.py" LogicalName="Cage.CliAccount" />
19新增: <EmbeddedResource Include="../../../internal/workbench/windows_cli_platform.py" LogicalName="Cage.CliPlatform" />
20新增: <EmbeddedResource Include="../../../internal/workbench/windows_ccs_launch.cjs" LogicalName="Cage.CliCCS" />
21新增: <EmbeddedResource Include="../../../internal/workbench/mobile_cli_identity.py" LogicalName="Cage.CliIdentity" />
22新增: <EmbeddedResource Include="../../../internal/workbench/cli_channel.resume.md" LogicalName="Cage.CliResume" />
23新增: <EmbeddedResource Include="../../../internal/workbench/claude_account_resume.md" LogicalName="Cage.CliAccountResume" />
24新增: </ItemGroup>
25新增:</Project>
新增scripts/guest-os/guest-clipboard-windows/ClaudeGraphicsCapture.cs+323 −0看文件
@@ -0,0 +1,323 @@
1新增:using System.Runtime.InteropServices;
2新增:using Windows.Foundation;
3新增:using Windows.Graphics.Capture;
4新增:using Windows.Graphics.DirectX;
5新增:using Windows.Graphics.DirectX.Direct3D11;
6新增:using Windows.Graphics.Imaging;
7新增:using Windows.Storage.Streams;
8新增:using WinRT;
9新增:
10新增:namespace Cage.GuestClipboard;
11新增:
12新增:// Capture items are created exclusively for the caller's validated Claude HWND.
13新增:// No monitor item, desktop duplication or screen BitBlt is available here.
14新增:internal static class ClaudeGraphicsCapture
15新增:{
16新增: private static readonly Guid ItemInterop = new("3628e81b-3cac-4c60-b7f4-23ce0e0c3356");
17新增: private static readonly Guid ItemInterface = new("79c3f95b-31f7-4ec2-a464-632ef5d30760");
18新增: private static readonly Guid DxgiDevice = new("54ec77fa-1377-44e6-8c32-88fd5f44c84c");
19新增: private static readonly SemaphoreSlim CaptureGate = new(1, 1);
20新增: private static readonly System.Threading.Timer Idle = new(state => { _ = Expire(); });
21新增: private static CaptureSession? current;
22新增:
23新增: private static async Task Expire()
24新增: {
25新增: if (!await CaptureGate.WaitAsync(0)) return;
26新增: try { current?.Dispose(); current = null; }
27新增: finally { CaptureGate.Release(); }
28新增: }
29新增:
30新增: internal static async Task<byte[]> Capture(IntPtr window, int pid, int width, int height, Action validate, bool allowSolid = false, bool preserveAlpha = false)
31新增: {
32新增: await CaptureGate.WaitAsync();
33新增: Idle.Change(Timeout.Infinite, Timeout.Infinite);
34新增: try
35新增: {
36新增: validate();
37新增: try { if (!GraphicsCaptureSession.IsSupported()) throw new InvalidDataException("desktop_graphics_capture_unavailable"); }
38新增: catch (COMException error) when ((uint)error.HResult == 0x80070005)
39新增: { throw new InvalidDataException("desktop_capture_permission_required", error); }
40新增: Exception? hardware = null;
41新增: foreach (uint driver in new uint[] { 1, 5 }) // hardware, then WARP
42新增: {
43新增: try { return await CaptureDevice(window, pid, width, height, validate, driver, allowSolid, preserveAlpha); }
44新增: catch (COMException error) when ((uint)error.HResult == 0x80070005)
45新增: { throw new InvalidDataException("desktop_capture_permission_required", error); }
46新增: catch (Exception error) when (error is COMException || error is TimeoutException || error is InvalidDataException { Message: "desktop_empty_frame" })
47新增: {
48新增: current?.Dispose();
49新增: current = null;
50新增: hardware = error;
51新增: }
52新增: }
53新增: throw new InvalidDataException(hardware is InvalidDataException ? "desktop_empty_frame" : "desktop_graphics_device_unavailable", hardware);
54新增: }
55新增: finally { Idle.Change(1500, Timeout.Infinite); CaptureGate.Release(); }
56新增: }
57新增: private static async Task<byte[]> CaptureDevice(IntPtr window, int pid, int width, int height, Action validate, uint driver, bool allowSolid, bool preserveAlpha)
58新增: {
59新增: if (current is null || !current.Matches(window, pid, width, height, allowSolid, preserveAlpha))
60新增: {
61新增: current?.Dispose(); current = null;
62新增: current = new CaptureSession(window, pid, width, height, driver, allowSolid, preserveAlpha);
63新增: }
64新增: return await current.Read(validate);
65新增: }
66新增:
67新增: private sealed class CaptureSession : IDisposable
68新增: {
69新增: private readonly IntPtr window;
70新增: private readonly int pid, width, height;
71新增: private readonly bool allowSolid, preserveAlpha;
72新增: private readonly GraphicsCaptureItem item;
73新增: private readonly IDirect3DDevice device;
74新增: private Direct3D11CaptureFramePool? pool;
75新增: private GraphicsCaptureSession? capture;
76新增: private readonly object frames = new();
77新增: private TaskCompletionSource<bool> arrived = new(TaskCreationOptions.RunContinuationsAsynchronously);
78新增: private Direct3D11CaptureFrame? latest;
79新增: private byte[]? encoded;
80新增: private Windows.Storage.Streams.Buffer? pixelBuffer;
81新增: private byte[] pixelsRead = [];
82新增: private byte[]? previousPixels;
83新增: private TimeSpan? timestamp;
84新增: private bool closed;
85新增:
86新增: internal CaptureSession(IntPtr window, int pid, int width, int height, uint driver, bool allowSolid, bool preserveAlpha)
87新增: {
88新增: this.window = window; this.pid = pid; this.width = width; this.height = height; this.allowSolid = allowSolid; this.preserveAlpha = preserveAlpha;
89新增: item = Item(window);
90新增: if (item.Size.Width < width || item.Size.Height < height || (long)item.Size.Width * item.Size.Height > 40_000_000)
91新增: throw new InvalidDataException("desktop_target_changed");
92新增: device = Device(driver);
93新增: try
94新增: {
95新增: pool = Direct3D11CaptureFramePool.CreateFreeThreaded(device, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, item.Size);
96新增: capture = pool.CreateCaptureSession(item);
97新增: capture.IsCursorCaptureEnabled = false;
98新增: pool.FrameArrived += OnFrame;
99新增: item.Closed += OnClosed;
100新增: capture.StartCapture();
101新增: }
102新增: catch { Dispose(); throw; }
103新增: }
104新增:
105新增: internal bool Matches(IntPtr handle, int process, int w, int h, bool solid, bool alpha)
106新增: {
107新增: lock (frames) return !closed && window == handle && pid == process && width == w && height == h && allowSolid == solid && preserveAlpha == alpha;
108新增: }
109新增:
110新增: private void OnFrame(Direct3D11CaptureFramePool sender, object args)
111新增: {
112新增: try
113新增: {
114新增: var frame = sender.TryGetNextFrame();
115新增: if (frame is null) return;
116新增: lock (frames)
117新增: {
118新增: if (closed) { frame.Dispose(); return; }
119新增: latest?.Dispose();
120新增: latest = frame;
121新增: arrived.TrySetResult(true);
122新增: }
123新增: }
124新增: catch (Exception error)
125新增: {
126新增: lock (frames)
127新增: {
128新增: closed = true;
129新增: latest?.Dispose(); latest = null;
130新增: arrived.TrySetException(error);
131新增: }
132新增: }
133新增: }
134新增:
135新增: private void OnClosed(GraphicsCaptureItem sender, object args)
136新增: {
137新增: lock (frames) { closed = true; arrived.TrySetException(new InvalidDataException("desktop_target_changed")); }
138新增: }
139新增:
140新增: internal async Task<byte[]> Read(Action validate)
141新增: {
142新增: validate();
143新增: var geometry = Geometry(window, pid, width, height);
144新增: Task ready;
145新增: lock (frames)
146新增: {
147新增: if (closed) throw new InvalidDataException("desktop_target_changed");
148新增: if (latest is null && encoded is not null) return encoded;
149新增: ready = arrived.Task;
150新增: }
151新增: await ready.WaitAsync(TimeSpan.FromSeconds(3));
152新增: Direct3D11CaptureFrame frame;
153新增: lock (frames)
154新增: {
155新增: if (closed || latest is null) throw new InvalidDataException("desktop_target_changed");
156新增: frame = latest; latest = null;
157新增: arrived = new(TaskCreationOptions.RunContinuationsAsynchronously);
158新增: }
159新增: using (frame)
160新增: {
161新增: if (encoded is not null && timestamp == frame.SystemRelativeTime) return encoded;
162新增: using var bitmap = await SoftwareBitmap.CreateCopyFromSurfaceAsync(frame.Surface, preserveAlpha ? BitmapAlphaMode.Premultiplied : BitmapAlphaMode.Ignore);
163新增: validate();
164新增: var after = Geometry(window, pid, width, height);
165新增: if (after != geometry) throw new InvalidDataException("desktop_target_changed");
166新增: var source = geometry.Source(frame.ContentSize.Width, frame.ContentSize.Height);
167新增: using var pixels = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, preserveAlpha ? BitmapAlphaMode.Straight : BitmapAlphaMode.Ignore);
168新增: var byteCount = checked(pixels.PixelWidth * pixels.PixelHeight * 4);
169新增: if (pixelsRead.Length != byteCount)
170新增: {
171新增: pixelsRead = new byte[byteCount];
172新增: pixelBuffer = new Windows.Storage.Streams.Buffer((uint)byteCount);
173新增: }
174新增: pixels.CopyToBuffer(pixelBuffer!);
175新增: using (var reader = DataReader.FromBuffer(pixelBuffer!)) reader.ReadBytes(pixelsRead);
176新增: var rowBytes = checked(width * 4);
177新增: var identical = previousPixels is not null;
178新增: for (var row = 0; identical && row < height; row++)
179新增: {
180新增: var offset = ((source.Y + row) * pixels.PixelWidth + source.X) * 4;
181新增: identical = pixelsRead.AsSpan(offset, rowBytes).SequenceEqual(previousPixels!.AsSpan(row * rowBytes, rowBytes));
182新增: }
183新增: if (identical)
184新增: {
185新增: validate();
186新增: timestamp = frame.SystemRelativeTime;
187新增: return encoded!;
188新增: }
189新增: var png = await EncodeClient(pixels, source.X, source.Y, width, height);
190新增: validate();
191新增: using var input = new MemoryStream(png, false);
192新增: using var client = new Bitmap(input);
193新增: if (client.Width != width || client.Height != height || (!allowSolid && !HasContent(client))) throw new InvalidDataException("desktop_empty_frame");
194新增: // Publish the comparison pixels only after encoding and target
195新增: // validation succeed, so a failed frame cannot reuse old PNGs.
196新增: previousPixels ??= new byte[checked(rowBytes * height)];
197新增: for (var row = 0; row < height; row++)
198新增: {
199新增: var offset = ((source.Y + row) * pixels.PixelWidth + source.X) * 4;
200新增: pixelsRead.AsSpan(offset, rowBytes).CopyTo(previousPixels.AsSpan(row * rowBytes, rowBytes));
201新增: }
202新增: timestamp = frame.SystemRelativeTime;
203新增: encoded = png;
204新增: return png;
205新增: }
206新增: }
207新增:
208新增: public void Dispose()
209新增: {
210新增: lock (frames)
211新增: {
212新增: closed = true;
213新增: latest?.Dispose(); latest = null;
214新增: arrived.TrySetCanceled();
215新增: }
216新增: if (pool is not null) pool.FrameArrived -= OnFrame;
217新增: item.Closed -= OnClosed;
218新增: capture?.Dispose(); pool?.Dispose(); device.Dispose();
219新增: }
220新增: }
221新增: internal static bool HasContent(Bitmap bitmap)
222新增: {
223新增: // A white/black client plus custom title buttons is still an empty frame.
224新增: int left = bitmap.Width / 12, right = bitmap.Width - left;
225新增: int top = bitmap.Height * 15 / 100, bottom = bitmap.Height * 95 / 100;
226新增: var first = bitmap.GetPixel(left, top); int varied = 0;
227新增: for (int y = top; y < bottom; y += Math.Max(1, (bottom-top)/64))
228新增: for (int x = left; x < right; x += Math.Max(1, (right-left)/64))
229新增: {
230新增: var pixel = bitmap.GetPixel(x, y);
231新增: if (Math.Abs(pixel.R-first.R)>8 || Math.Abs(pixel.G-first.G)>8 || Math.Abs(pixel.B-first.B)>8) varied++;
232新增: }
233新增: return varied >= 8;
234新增: }
235新增: private static async Task<byte[]> EncodeClient(SoftwareBitmap source, int x, int y, int width, int height)
236新增: {
237新增: if (x < 0 || y < 0 || x + width > source.PixelWidth || y + height > source.PixelHeight)
238新增: throw new InvalidDataException("desktop_target_changed");
239新增: using var output = new InMemoryRandomAccessStream();
240新增: var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, output);
241新增: encoder.SetSoftwareBitmap(source);
242新增: encoder.BitmapTransform.Bounds = new BitmapBounds { X = (uint)x, Y = (uint)y, Width = (uint)width, Height = (uint)height };
243新增: await encoder.FlushAsync();
244新增: if (output.Size is 0 or > Protocol.PngLimit) throw new InvalidDataException("desktop_frame_limit");
245新增: using var input = output.GetInputStreamAt(0);
246新增: using var reader = new DataReader(input);
247新增: var length = checked((uint)output.Size);
248新增: if (await reader.LoadAsync(length) != length) throw new InvalidDataException("desktop_capture_buffer_invalid");
249新增: var bytes = new byte[length];
250新增: reader.ReadBytes(bytes);
251新增: return bytes;
252新增: }
253新增:
254新增: private static GraphicsCaptureItem Item(IntPtr window)
255新增: {
256新增: using var factory = ActivationFactory.Get("Windows.Graphics.Capture.GraphicsCaptureItem", ItemInterop);
257新增: var function = Marshal.ReadIntPtr(Marshal.ReadIntPtr(factory.ThisPtr),3*IntPtr.Size);
258新增: var create = Marshal.GetDelegateForFunctionPointer<CreateWindow>(function);
259新增: var iid = ItemInterface;
260新增: Marshal.ThrowExceptionForHR(create(factory.ThisPtr,window,ref iid,out var value));
261新增: try { return MarshalInterface<GraphicsCaptureItem>.FromAbi(value); } finally { Marshal.Release(value); }
262新增: }
263新增: private static IDirect3DDevice Device(uint driver)
264新增: {
265新增: IntPtr native=IntPtr.Zero, context=IntPtr.Zero, dxgi=IntPtr.Zero, wrapped=IntPtr.Zero;
266新增: try
267新增: {
268新增: Marshal.ThrowExceptionForHR(D3D11CreateDevice(IntPtr.Zero,driver,IntPtr.Zero,0x20,IntPtr.Zero,0,7,out native,out _,out context));
269新增: var iid=DxgiDevice;Marshal.ThrowExceptionForHR(Marshal.QueryInterface(native,in iid,out dxgi));
270新增: Marshal.ThrowExceptionForHR(CreateDirect3D11DeviceFromDXGIDevice(dxgi,out wrapped));
271新增: return MarshalInterface<IDirect3DDevice>.FromAbi(wrapped);
272新增: }
273新增: finally
274新增: {
275新增: if(wrapped!=IntPtr.Zero)Marshal.Release(wrapped);if(dxgi!=IntPtr.Zero)Marshal.Release(dxgi);
276新增: if(context!=IntPtr.Zero)Marshal.Release(context);if(native!=IntPtr.Zero)Marshal.Release(native);
277新增: }
278新增: }
279新增: private readonly record struct Snapshot(Rect Window,Rect Visible,int ClientX,int ClientY,int Width,int Height)
280新增: {
281新增: internal Point Source(int width,int height)
282新增: {
283新增: Rect frame;
284新增: if(Visible.Right-Visible.Left==width && Visible.Bottom-Visible.Top==height)frame=Visible;
285新增: else if(Window.Right-Window.Left==width && Window.Bottom-Window.Top==height)frame=Window;
286新增: else throw new InvalidDataException("desktop_target_changed");
287新增: return new(ClientX-frame.Left,ClientY-frame.Top);
288新增: }
289新增: }
290新增: private static Snapshot Geometry(IntPtr window,int pid,int width,int height)
291新增: {
292新增: var prior=SetThreadDpiAwarenessContext(new IntPtr(-4));
293新增: try
294新增: {
295新增: if(!SessionGuard.Available() || GetWindowThreadProcessId(window,out var actual)==0 || actual!=pid ||
296新增: !GetWindowRect(window,out var rectangle) || !GetClientRect(window,out var client) || client.Right!=width || client.Bottom!=height)
297新增: throw new InvalidDataException("desktop_target_changed");
298新增: var visible=rectangle;if(DwmGetWindowAttribute(window,9,out var drawn,Marshal.SizeOf<Rect>())==0)visible=drawn;
299新增: var origin=new Point();if(!ClientToScreen(window,ref origin))throw new InvalidDataException("desktop_target_changed");
300新增: return new(rectangle,visible,origin.X,origin.Y,width,height);
301新增: }
302新增: finally {if(prior!=IntPtr.Zero)SetThreadDpiAwarenessContext(prior);}
303新增: }
304新增: [StructLayout(LayoutKind.Sequential)] private readonly record struct Rect(int Left,int Top,int Right,int Bottom);
305新增: [StructLayout(LayoutKind.Sequential)] private struct Point {internal int X,Y;internal Point(int x,int y){X=x;Y=y;}}
306新增: [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CreateWindow(IntPtr factory,IntPtr window,ref Guid iid,out IntPtr item);
307新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
308新增: [DllImport("d3d11.dll")] private static extern int D3D11CreateDevice(IntPtr adapter,uint driver,IntPtr software,uint flags,IntPtr features,uint featureCount,uint sdk,out IntPtr device,out uint level,out IntPtr context);
309新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
310新增: [DllImport("d3d11.dll")] private static extern int CreateDirect3D11DeviceFromDXGIDevice(IntPtr dxgi,out IntPtr device);
311新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
312新增: [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window,out uint pid);
313新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
314新增: [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr window,out Rect rect);
315新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
316新增: [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr window,out Rect rect);
317新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
318新增: [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr window,ref Point point);
319新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
320新增: [DllImport("user32.dll")] private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
321新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
322新增: [DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr window,uint attribute,out Rect rect,int size);
323新增:}
新增scripts/guest-os/guest-clipboard-windows/ClaudeWindowRpc.cs+526 −0看文件
@@ -0,0 +1,526 @@
1新增:using System.Diagnostics;
2新增:using System.Drawing.Imaging;
3新增:using System.Runtime.CompilerServices;
4新增:using System.Runtime.InteropServices;
5新增:using System.Security.Cryptography;
6新增:using System.Text.Json.Nodes;
7新增:using System.Xml.Linq;
8新增:using System.Windows.Automation;
9新增:using Windows.Management.Deployment;
10新增:
11新增:namespace Cage.GuestClipboard;
12新增:
13新增:// This endpoint contains one registered Claude app window. It never captures
14新增:// the desktop or accepts a path, process ID or window handle from its client.
15新增:internal static class ClaudeWindowRpc
16新增:{
17新增: private const string Family = "Claude_pzs8sxrjxfjjc";
18新增: private const string Publisher = "CN=\"Anthropic, PBC\", O=\"Anthropic, PBC\", L=San Francisco, S=California, C=US, SERIALNUMBER=4860621, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US";
19新增: private static readonly SemaphoreSlim Operations = new(1, 1);
20新增: private static readonly SemaphoreSlim Captures = new(1, 1);
21新增: [ModuleInitializer] internal static void Register() => GuestOperations.Register("desktop", Run);
22新增:
23新增: private sealed record Registration(string Executable, string Version);
24新增: private sealed record Window(Process Process, IntPtr Handle, Rect Bounds, string Executable);
25新增: [StructLayout(LayoutKind.Sequential)] private struct Rect { public int Left, Top, Right, Bottom; }
26新增: [StructLayout(LayoutKind.Sequential)] private struct Point { public int X, Y; }
27新增: [StructLayout(LayoutKind.Sequential)] private struct Keyboard { public ushort Key, Scan; public uint Flags, Time; public UIntPtr Extra; }
28新增: [StructLayout(LayoutKind.Sequential)] private struct Mouse { public int X, Y; public uint Data, Flags, Time; public UIntPtr Extra; }
29新增: [StructLayout(LayoutKind.Explicit)] private struct InputData { [FieldOffset(0)] public Keyboard Keyboard; [FieldOffset(0)] public Mouse Mouse; }
30新增: [StructLayout(LayoutKind.Sequential)] private struct Input { public uint Type; public InputData Data; }
31新增: [DllImport("user32.dll")] private static extern short VkKeyScanW(char key);
32新增: [DllImport("user32.dll")] private static extern bool PostMessageW(IntPtr window, uint message, IntPtr wparam, IntPtr lparam);
33新增: [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr window, out Rect rect);
34新增: [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr window, ref Point point);
35新增: [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr window);
36新增: [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr window);
37新增: [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
38新增: [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
39新增: [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr window);
40新增: [DllImport("user32.dll")] private static extern bool SetCursorPos(int x, int y);
41新增: [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags);
42新增: [DllImport("user32.dll")] private static extern uint SendInput(uint count, Input[] input, int size);
43新增: [DllImport("user32.dll")] private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
44新增: [DllImport("user32.dll")] private static extern uint GetDpiForWindow(IntPtr window);
45新增: [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr window, out Rect rect);
46新增: [DllImport("user32.dll")] private static extern bool GetCursorPos(out Point point);
47新增: [DllImport("user32.dll")] private static extern IntPtr MonitorFromWindow(IntPtr window, uint flags);
48新增: [StructLayout(LayoutKind.Sequential)] private struct MonitorInfo { public uint Size; public Rect Monitor, Work; public uint Flags; }
49新增: [DllImport("user32.dll", EntryPoint="GetMonitorInfoW", ExactSpelling=true)] private static extern bool GetMonitorInfo(IntPtr monitor, ref MonitorInfo info);
50新增: [DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int width, int height, uint flags);
51新增: [DllImport("user32.dll",CharSet=CharSet.Unicode)] private static extern int GetWindowTextW(IntPtr window,System.Text.StringBuilder text,int count);
52新增: [DllImport("user32.dll")] private static extern IntPtr WindowFromPoint(Point point);
53新增: [DllImport("user32.dll")] private static extern IntPtr GetAncestor(IntPtr window,uint flags);
54新增: [ComVisible(true),Guid("00000121-0000-0000-C000-000000000046"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
55新增: private interface IDropSource
56新增: {
57新增: [PreserveSig] int QueryContinueDrag([MarshalAs(UnmanagedType.Bool)] bool escape,uint state);
58新增: [PreserveSig] int GiveFeedback(uint effect);
59新增: }
60新增: [ComVisible(true),ClassInterface(ClassInterfaceType.None)]
61新增: private sealed class DropSource(Action guard) : IDropSource
62新增: {
63新增: public int QueryContinueDrag(bool escape,uint state) { try { guard();return escape?0x40101:0x40100; } catch { return 0x40101; } }
64新增: public int GiveFeedback(uint effect)=>0x40102;
65新增: }
66新增: [DllImport("ole32.dll")] private static extern int DoDragDrop([MarshalAs(UnmanagedType.Interface)] System.Runtime.InteropServices.ComTypes.IDataObject data,IDropSource source,uint effects,out uint effect);
67新增: [DllImport("ole32.dll")] private static extern int OleInitialize(IntPtr reserved);
68新增: [DllImport("ole32.dll")] private static extern void OleUninitialize();
69新增:
70新增: private static Registration? RegisteredExecutable()
71新增: {
72新增: var packages = new PackageManager().FindPackagesForUser("").Where(p => p.Id.FamilyName == Family).ToArray();
73新增: if (packages.Length == 0) return null;
74新增: if (packages.Length != 1) throw new InvalidDataException("desktop_registration_invalid");
75新增: var p = packages[0];
76新增: if (p.Id.Name != "Claude" || p.Id.Publisher != Publisher || p.IsDevelopmentMode || !p.Status.VerifyIsOK() ||
77新增: p.SignatureKind is not (Windows.ApplicationModel.PackageSignatureKind.Developer or Windows.ApplicationModel.PackageSignatureKind.Store or Windows.ApplicationModel.PackageSignatureKind.Enterprise))
78新增: throw new InvalidDataException("desktop_registration_invalid");
79新增: var manifest = XDocument.Load(Path.Combine(p.InstalledPath, "AppxManifest.xml"));
80新增: var app = manifest.Descendants().SingleOrDefault(e => e.Name.LocalName == "Application" && (string?)e.Attribute("Id") == "Claude");
81新增: if (app is null || (string?)app.Attribute("Executable") != "app\\Claude.exe" || (string?)app.Attribute("EntryPoint") != "Windows.FullTrustApplication")
82新增: throw new InvalidDataException("desktop_registration_invalid");
83新增: var version = p.Id.Version;
84新增: return new Registration(Path.Combine(p.InstalledPath, "app", "Claude.exe"), $"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");
85新增: }
86新增:
87新增: private static Window Find(string executable)
88新增: {
89新增: var session = Process.GetCurrentProcess().SessionId;
90新增: foreach (var p in Process.GetProcessesByName("Claude"))
91新增: {
92新增: try
93新增: {
94新增: if (p.SessionId != session || !string.Equals(p.MainModule?.FileName, executable, StringComparison.OrdinalIgnoreCase)) { p.Dispose(); continue; }
95新增: var handle = p.MainWindowHandle;
96新增: var w = new Window(p, handle, default, executable);
97新增: Validate(w, false);
98新增: if (!GetClientRect(handle, out var bounds) || bounds.Right < 1 || bounds.Bottom < 1 || (long)bounds.Right * bounds.Bottom > 40_000_000)
99新增: throw new InvalidDataException("desktop_size_invalid");
100新增: return w with { Bounds = bounds };
101新增: }
102新增: catch { p.Dispose(); }
103新增: }
104新增: throw new InvalidDataException("desktop_not_running");
105新增: }
106新增:
107新增: internal static JsonObject ComponentStatus()
108新增: {
109新增: try
110新增: {
111新增: var registration=RegisteredExecutable();
112新增: return new JsonObject{["installed"]=registration!=null,["ready"]=registration!=null,["reason"]=registration==null?"desktop_not_installed":""};
113新增: }
114新增: catch{return new JsonObject{["installed"]=false,["ready"]=false,["reason"]="desktop_registration_unavailable"};}
115新增: }
116新增:
117新增: private static void Validate(Window w, bool focus)
118新增: {
119新增: if (!SessionGuard.Available() || !SessionGuard.OwnsProcess(w.Process) || !IsWindowVisible(w.Handle) || IsIconic(w.Handle) ||
120新增: GetWindowThreadProcessId(w.Handle, out var pid) == 0 || pid != w.Process.Id ||
121新增: !string.Equals(w.Process.MainModule?.FileName, w.Executable, StringComparison.OrdinalIgnoreCase) ||
122新增: focus && GetForegroundWindow() != w.Handle) throw new InvalidDataException("desktop_target_changed");
123新增: }
124新增:
125新增: // WGC can capture the part of our own window outside the guest monitor,
126新增: // whereas SendInput clamps the system pointer to its physical screen.
127新增: // Bring only the requested part of this window into the guest work area.
128新增: private static Point PositionPointer(Window w, int x, int y)
129新增: {
130新增: Validate(w,true);
131新增: var point=new Point {X=x, Y=y};
132新增: var monitor=new MonitorInfo {Size=(uint)Marshal.SizeOf<MonitorInfo>()};
133新增: if (!ClientToScreen(w.Handle,ref point) || !GetMonitorInfo(MonitorFromWindow(w.Handle,2),ref monitor) ||
134新增: monitor.Work.Right<=monitor.Work.Left || monitor.Work.Bottom<=monitor.Work.Top)
135新增: throw new InvalidDataException("desktop_pointer_failed");
136新增: var dx=Math.Clamp(point.X,monitor.Work.Left,monitor.Work.Right-1)-point.X;
137新增: var dy=Math.Clamp(point.Y,monitor.Work.Top,monitor.Work.Bottom-1)-point.Y;
138新增: if(dx!=0 || dy!=0)
139新增: {
140新增: if(!GetWindowRect(w.Handle,out var outer) ||
141新增: !SetWindowPos(w.Handle,IntPtr.Zero,outer.Left+dx,outer.Top+dy,0,0,0x0001|0x0004|0x0010))
142新增: throw new InvalidDataException("desktop_pointer_failed");
143新增: point=new Point {X=x,Y=y};
144新增: if(!ClientToScreen(w.Handle,ref point)) throw new InvalidDataException("desktop_pointer_failed");
145新增: }
146新增: Validate(w,true);
147新增: if(!SetCursorPos(point.X,point.Y) || !GetCursorPos(out var actual) || actual.X!=point.X || actual.Y!=point.Y ||
148新增: GetAncestor(WindowFromPoint(actual),2)!=w.Handle) throw new InvalidDataException("desktop_target_changed");
149新增: return actual;
150新增: }
151新增:
152新增: // A cropped WGC window can display an onboarding button beneath the
153新增: // guest taskbar or another guest app. UI Automation invokes only the
154新增: // authenticated app's visible button without using the global pointer.
155新增: private static AutomationElement? WelcomeButton(Window w, int x, int y)
156新增: {
157新增: Validate(w,false);
158新增: var point=new Point {X=x,Y=y};
159新增: if(!ClientToScreen(w.Handle,ref point)) return null;
160新增: var root=AutomationElement.FromHandle(w.Handle);
161新增: if(root.Current.ProcessId!=w.Process.Id) return null;
162新增: var buttons=root.FindAll(TreeScope.Descendants,new PropertyCondition(AutomationElement.ControlTypeProperty,ControlType.Button));
163新增: if(buttons.Count>128) return null;
164新增: AutomationElement? selected=null;
165新增: foreach(AutomationElement element in buttons)
166新增: {
167新增: var current=element.Current;
168新增: if(current.ProcessId!=w.Process.Id || !current.IsEnabled || current.IsOffscreen ||
169新增: !current.BoundingRectangle.Contains(point.X,point.Y)) continue;
170新增: if(selected!=null || current.Name is not ("Get started" or "开始使用" or "開始使用")) return null;
171新增: if(!element.TryGetCurrentPattern(InvokePattern.Pattern,out _)) return null;
172新增: selected=element;
173新增: }
174新增: return selected;
175新增: }
176新增:
177新增: internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available)
178新增: {
179新增: int mask = 0;
180新增: AutomationElement? welcomeDown = null;
181新增: var inputLease = NativeGuestInput.OpenLease();
182新增: try
183新增: {
184新增: while (await Protocol.Read(stream, Protocol.WireLimit, token) is { } value)
185新增: {
186新增: await Operations.WaitAsync(token);
187新增: var dpi = SetThreadDpiAwarenessContext(new IntPtr(-4));
188新增: try
189新增: {
190新增: if (!available()) throw new InvalidDataException("requires_gui_login");
191新增: var action = value["action"]?.GetValue<string>() ?? "";
192新增: if (action is "files-download-open" or "files-download-read" or "files-download-close" or "files-download-retry")
193新增: {
194新增: await Protocol.Write(stream, WindowsDesktopDownloads.Read(value), token); continue;
195新增: }
196新增: if (action is "files-open-claim" or "files-open-complete")
197新增: {
198新增: await Protocol.Write(stream, WindowsDesktopFiles.OpenAction(value["id"]?.GetValue<string>() ?? "", action == "files-open-complete"), token); continue;
199新增: }
200新增: var registered = RegisteredExecutable();
201新增: var executable = registered?.Executable;
202新增: if (action == "status")
203新增: {
204新增: bool running = false; double density = 1;
205新增: if (executable is not null) { try { var window = Find(executable); using var owner = window.Process; density = GetDpiForWindow(window.Handle) / 96.0; running = true; } catch (InvalidDataException) { } }
206新增: await Protocol.Write(stream, new JsonObject { ["installed"] = executable is not null, ["running"] = running, ["version"] = registered?.Version ?? "", ["native_user_session"] = true, ["display_scale"] = density, ["phone_supported"] = true }, token); continue;
207新增: }
208新增: if(action=="files-cancel")
209新增: {
210新增: WindowsDesktopFiles.Cancel(value["id"]?.GetValue<string>() ?? "");
211新增: AttachmentsRpc.CancelBatch(value["id"]?.GetValue<string>() ?? "");
212新增: await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue;
213新增: }
214新增: if(action=="files-poll" && executable is null)
215新增: {
216新增: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot()},token);continue;
217新增: }
218新增: if (executable is null) throw new InvalidDataException("desktop_not_installed");
219新增: if (action == "start")
220新增: {
221新增: Process.Start(new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe"), "shell:AppsFolder\\" + Family + "!Claude") { UseShellExecute = false });
222新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue;
223新增: }
224新增: if(action=="files-poll")
225新增: {
226新增: Window? found = null;
227新增: try { found = Find(executable); }
228新增: catch (InvalidDataException) { }
229新增: if (found is null)
230新增: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot()},token);
231新增: else
232新增: {
233新增: using var owner = found.Process;
234新增: var binding = new WindowsFileDialogNative.Owner(owner.Id, owner.StartTime.ToUniversalTime().Ticks,
235新增: owner.SessionId, found.Handle, executable, process => SessionGuard.Available() && SessionGuard.OwnsProcess(process));
236新增: await Protocol.Write(stream, WindowsDesktopFiles.Poll(binding), token);
237新增: }
238新增: continue;
239新增: }
240新增: var w = Find(executable);
241新增: using var process = w.Process;
242新增: if(action=="files-start")
243新增: {
244新增: Validate(w,true);
245新增: var kind=value["kind"]?.GetValue<string>() ?? "";
246新增: var binding=await AttachmentTarget(w,kind,token);
247新增: var result=AttachmentsRpc.StartBatch(binding,kind,value["x"]?.GetValue<double>() ?? 0,value["y"]?.GetValue<double>() ?? 0);
248新增: await Protocol.Write(stream,result,token);continue;
249新增: }
250新增: if(action is "files-finish" or "files-finish-image")
251新增: {
252新增: var id = value["id"]?.GetValue<string>() ?? "";
253新增: if (WindowsDesktopFiles.Contains(id))
254新增: {
255新增: await AttachmentsRpc.FinishBatch(id, (_, kind, paths, _, _) =>
256新增: {
257新增: if (kind != "chooser") throw new InvalidDataException("file_dialog_selection_invalid");
258新增: return WindowsDesktopFiles.Finish(id, paths, token);
259新增: });
260新增: await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue;
261新增: }
262新增: await AttachmentsRpc.FinishBatch(value["id"]?.GetValue<string>() ?? "",async(binding,kind,paths,x,y)=>
263新增: {
264新增: Validate(w,true);
265新增: if(binding!=await AttachmentTarget(w,kind,token))throw new InvalidDataException("desktop_target_changed");
266新增: var agent=ClipboardAgent.Current ?? throw new InvalidDataException("clipboard_agent_unavailable");
267新增: if(action=="files-finish-image")
268新增: {
269新增: if(kind!="image"||paths.Length!=1)throw new InvalidDataException("attachment_request_invalid");
270新增: await using var file=new FileStream(paths[0],FileMode.Open,FileAccess.Read,FileShare.Read);
271新增: if(file.Length<33||file.Length>Protocol.PngLimit)throw new InvalidDataException("image_limit");
272新增: var bytes=new byte[checked((int)file.Length)];await file.ReadExactlyAsync(bytes,token);Protocol.Png(bytes);
273新增: if(binding!=await AttachmentTarget(w,kind,token))throw new InvalidDataException("desktop_target_changed");
274新增: await agent.PasteImage(bytes,()=>Emit(w,[KeyInput(0x11,true),KeyInput(0x56,true),KeyInput(0x56,false),KeyInput(0x11,false)]));
275新增: }
276新增: else if(kind=="paste")await agent.PasteFiles(paths,()=>Emit(w,[KeyInput(0x11,true),KeyInput(0x56,true),KeyInput(0x56,false),KeyInput(0x11,false)]));
277新增: else if(kind=="image")throw new InvalidDataException("attachment_request_invalid");
278新增: else await agent.GUI(()=>{DropFiles(w,paths,x,y);return true;});
279新增: });
280新增: await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue;
281新增: }
282新增: if (action == "files-directory")
283新增: {
284新增: var id = value["id"]?.GetValue<string>() ?? "";
285新增: var folder = ProjectRpc.Resolve(value["project_id"]?.GetValue<string>() ?? "", value["grant"]?.GetValue<string>() ?? "");
286新增: await WindowsDesktopFiles.Finish(id, [folder], token);
287新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue;
288新增: }
289新增: if (action == "paste-image")
290新增: {
291新增: Validate(w, true);
292新增: var bytes = Convert.FromBase64String(value["png"]?.GetValue<string>() ?? ""); Protocol.Png(bytes);
293新增: var agent = ClipboardAgent.Current ?? throw new InvalidDataException("clipboard_agent_unavailable");
294新增: await agent.PasteImage(bytes, () => Emit(w, [KeyInput(0x11, true), KeyInput(0x56, true), KeyInput(0x56, false), KeyInput(0x11, false)]));
295新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue;
296新增: }
297新增: if (action == "ime")
298新增: {
299新增: Validate(w, true);
300新增: var origin = new Point();
301新增: if (!ClientToScreen(w.Handle, ref origin)) throw new InvalidDataException("desktop_target_changed");
302新增: var result = await WindowsIme.Handle(value, w.Process.Id, Target(w), origin.X, origin.Y,
303新增: content => Emit(w, content.SelectMany(c => new[] { Unicode(c, false), Unicode(c, true) }).ToArray()), token);
304新增: await Protocol.Write(stream, result, token); continue;
305新增: }
306新增: if (action == "frame")
307新增: {
308新增: if (!await Captures.WaitAsync(0, token)) throw new InvalidDataException("desktop_capture_busy");
309新增: // A driver timeout retains one capture slot until its native
310新增: // copy finishes. Later requests do not accumulate workers.
311新增: Process? retainedProcess=null;
312新增: Window retained;
313新增: try{
314新增: retainedProcess=Process.GetProcessById(w.Process.Id);
315新增: if(retainedProcess.StartTime!=w.Process.StartTime)throw new InvalidDataException("desktop_target_changed");
316新增: retained=w with { Process=retainedProcess };
317新增: }catch{retainedProcess?.Dispose();Captures.Release();throw;}
318新增: var capture = Task.Run(() => {
319新增: using var owner=retained.Process;
320新增: try { return Capture(retained); } finally { Captures.Release(); }
321新增: });
322新增: var bytes = await capture.WaitAsync(TimeSpan.FromSeconds(10), token);
323新增: var target = Target(w);
324新增: var sequence = target + Convert.ToHexString(SHA256.HashData(bytes));
325新增: if (value["after"]?.GetValue<string>() == sequence)
326新增: await Protocol.Write(stream, new JsonObject { ["unchanged"] = true, ["sequence"] = sequence }, token);
327新增: else
328新增: await Protocol.Write(stream, new JsonObject { ["png"] = Convert.ToBase64String(bytes), ["sequence"] = sequence, ["width"] = w.Bounds.Right, ["height"] = w.Bounds.Bottom, ["target"] = target, ["density"] = GetDpiForWindow(w.Handle) / 96.0 }, token);
329新增: continue;
330新增: }
331新增: if (action == "resize")
332新增: {
333新增: int width = value["width"]?.GetValue<int>() ?? 0, height = value["height"]?.GetValue<int>() ?? 0;
334新增: if (width < 320 || height < 240 || width > 8192 || height > 8192 || (long)width * height > 40_000_000) throw new InvalidDataException("desktop_size_invalid");
335新增: // Electron's custom title bar occupies its client area. Measure
336新增: // the actual window decorations instead of assuming stock chrome.
337新增: if (!GetWindowRect(w.Handle,out var outer) ||
338新增: !SetWindowPos(w.Handle,IntPtr.Zero,0,0,width+outer.Right-outer.Left-w.Bounds.Right,
339新增: height+outer.Bottom-outer.Top-w.Bounds.Bottom,0x0002|0x0004|0x0010))
340新增: throw new InvalidDataException("desktop_resize_failed");
341新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue;
342新增: }
343新增: if (action == "stop") {
344新增: Validate(w, false);
345新增: if (!PostMessageW(w.Handle, 0x0010, IntPtr.Zero, IntPtr.Zero)) throw new InvalidDataException("desktop_close_failed");
346新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue;
347新增: }
348新增: if (value["target"]?.GetValue<string>() != Target(w)) throw new InvalidDataException("desktop_target_changed");
349新增: await WindowsIme.RequirePhoneFocus(value, w.Process.Id, Target(w), token);
350新增: if (action == "pointer")
351新增: {
352新增: int x = value["x"]?.GetValue<int>() ?? -1, y = value["y"]?.GetValue<int>() ?? -1, next = value["mask"]?.GetValue<int>() ?? -1;
353新增: if (x < 0 || y < 0 || x >= w.Bounds.Right || y >= w.Bounds.Bottom || next < 0 || next > 127) throw new InvalidDataException("desktop_pointer_invalid");
354新增: if (welcomeDown!=null)
355新增: {
356新增: var down=welcomeDown;
357新增: if(next!=1) welcomeDown=null;
358新增: if(next==0)
359新增: {
360新增: var up=WelcomeButton(w,x,y);
361新增: if(up==null || !Automation.Compare(down,up) || !up.TryGetCurrentPattern(InvokePattern.Pattern,out var command))
362新增: throw new InvalidDataException("desktop_target_changed");
363新增: Validate(w,false);
364新增: ((InvokePattern)command).Invoke();
365新增: await Protocol.Write(stream,new JsonObject{["ok"]=true,["invoked"]=true},token);continue;
366新增: }
367新增: await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue;
368新增: }
369新增: if(next==1 && mask==0)
370新增: {
371新增: try { welcomeDown=WelcomeButton(w,x,y); }
372新增: catch(ElementNotAvailableException) { welcomeDown=null; }
373新增: if(welcomeDown!=null) {await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue;}
374新增: }
375新增: if (GetForegroundWindow() != w.Handle && next == 0)
376新增: {
377新增: Validate(w,false);
378新增: NativeGuestInput.ResetLease(inputLease);
379新增: mask=NativeGuestInput.PressedButtons(inputLease);
380新增: await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue;
381新增: }
382新增: if (GetForegroundWindow() != w.Handle && next != 0) SetForegroundWindow(w.Handle);
383新增: Validate(w, true);
384新增: PositionPointer(w, x, y);
385新增: var inputs = new List<Input>();
386新增: uint[] downs = [2, 0x20, 8], ups = [4, 0x40, 0x10];
387新增: for (int i=0; i<3; i++) if (((mask ^ next) & (1 << i)) != 0) inputs.Add(new Input { Data = new InputData { Mouse = new Mouse { Flags = (next & (1 << i)) != 0 ? downs[i] : ups[i] } } });
388新增: if ((next & 8) != 0) inputs.Add(Wheel(120)); if ((next & 16) != 0) inputs.Add(Wheel(-120));
389新增: if ((next & 32) != 0) inputs.Add(Wheel(-120, true)); if ((next & 64) != 0) inputs.Add(Wheel(120, true));
390新增: Emit(w, inputs.ToArray(), inputLease); mask = NativeGuestInput.PressedButtons(inputLease);
391新增: }
392新增: else if (action == "key")
393新增: {
394新增: var keysym = value["keysym"]?.GetValue<uint>() ?? 0; var down = value["down"]?.GetValue<bool>() ?? false;
395新增: ushort key = Key(keysym);
396新增: if (key == 0) throw new InvalidDataException("desktop_key_invalid");
397新增: var stroke=InputStroke.Key(key,!down);
398新增: if(down)inputLease.Symbols[keysym]=[stroke];
399新增: else if(inputLease.Symbols.TryGetValue(keysym,out var original))stroke=original[0] with {Up=true};
400新增: EmitStrokes(w,[stroke],inputLease);
401新增: if(!down)inputLease.Symbols.Remove(keysym);
402新增: }
403新增: else if (action == "text")
404新增: {
405新增: var text = value["text"]?.GetValue<string>() ?? "";
406新增: if (Protocol.Utf8.GetByteCount(text) > 8192) throw new InvalidDataException("desktop_text_limit");
407新增: var inputs = text.SelectMany(c => new[] { Unicode(c, false), Unicode(c, true) }).ToArray(); Emit(w, inputs);
408新增: }
409新增: else throw new InvalidDataException("desktop_request_invalid");
410新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token);
411新增: }
412新增: catch (Exception e) when (e is not OperationCanceledException)
413新增: {
414新增: // Only a type and HRESULT cross the trust boundary. Exception
415新增: // messages from Windows can include user-controlled strings.
416新增: await Protocol.Write(stream, new JsonObject {
417新增: ["error"] = e is InvalidDataException ? e.Message : "desktop_operation_failed",
418新增: ["exception_type"] = e.GetType().Name, ["native_code"] = e.HResult.ToString("X8"),
419新增: }, token);
420新增: }
421新增: finally { if (dpi != IntPtr.Zero) SetThreadDpiAwarenessContext(dpi); Operations.Release(); }
422新增: }
423新增: }
424新增: finally
425新增: {
426新增: NativeGuestInput.CloseLease(inputLease);
427新增: }
428新增: }
429新增: private static string Target(Window w) {
430新增: Validate(w, false);
431新增: var title=new System.Text.StringBuilder(4096);GetWindowTextW(w.Handle,title,title.Capacity);
432新增: var data = Protocol.Utf8.GetBytes($"{w.Process.Id}:{w.Process.StartTime.ToUniversalTime().Ticks}:{w.Handle.ToInt64()}:{w.Bounds.Right}:{w.Bounds.Bottom}:{GetDpiForWindow(w.Handle)}:{title}");
433新增: return Convert.ToHexString(SHA256.HashData(data).AsSpan(0,16)).ToLowerInvariant();
434新增: }
435新增: private static async Task<string> AttachmentTarget(Window w,string kind,CancellationToken token)
436新增: {
437新增: var target=Target(w);if(kind=="drop")return target;
438新增: if(kind is not ("paste" or "image"))throw new InvalidDataException("attachment_request_invalid");
439新增: var origin=new Point();if(!ClientToScreen(w.Handle,ref origin))throw new InvalidDataException("desktop_target_changed");
440新增: var focus=await WindowsIme.Handle(new JsonObject{["mode"]="status"},w.Process.Id,target,origin.X,origin.Y,_=>throw new InvalidDataException("attachment_request_invalid"),token);
441新增: if(focus["available"]?.GetValue<bool>()!=true)throw new InvalidDataException("desktop_input_not_focused");
442新增: return target+":"+focus["context"]!.GetValue<string>();
443新增: }
444新增: private static void DropFiles(Window w,string[] paths,double x,double y)
445新增: {
446新增: Validate(w,true);
447新增: var point=PositionPointer(w,Math.Clamp((int)(x*w.Bounds.Right),0,w.Bounds.Right-1),Math.Clamp((int)(y*w.Bounds.Bottom),0,w.Bounds.Bottom-1));
448新增: void Guard(){Validate(w,true);if(GetAncestor(WindowFromPoint(point),2)!=w.Handle)throw new InvalidDataException("desktop_target_changed");}
449新增: Guard();
450新增: var initialized=OleInitialize(IntPtr.Zero);Marshal.ThrowExceptionForHR(initialized);
451新增: try
452新增: {
453新增: var data=new DataObject();data.SetData(DataFormats.FileDrop,true,paths);
454新增: using var release=new System.Windows.Forms.Timer{Interval=100};
455新增: release.Tick+=(_,_)=>{try{Emit(w,[KeyInput(17,true),KeyInput(17,false)]);}catch{release.Stop();}};
456新增: release.Start();
457新增: var result=DoDragDrop((System.Runtime.InteropServices.ComTypes.IDataObject)data,new DropSource(Guard),1,out var effect);
458新增: if(result!=0x40100 || (effect&1)==0)throw new InvalidDataException("desktop_drop_not_accepted");
459新增: }
460新增: finally{OleUninitialize();}
461新增: }
462新增: internal static WindowsAudioRpc.Target? AudioTarget()
463新增: {
464新增: if (!SessionGuard.Available()) throw new InvalidDataException("requires_gui_login");
465新增: var registered = RegisteredExecutable(); if (registered is null) return null;
466新增: var session = Process.GetCurrentProcess().SessionId; WindowsAudioRpc.Target? first = null;
467新增: foreach (var process in Process.GetProcessesByName("Claude"))
468新增: {
469新增: var owned = false;
470新增: try
471新增: {
472新增: if (process.SessionId != session || !string.Equals(process.MainModule?.FileName, registered.Executable, StringComparison.OrdinalIgnoreCase)) continue;
473新增: var target = new WindowsAudioRpc.Target(process, registered.Executable); owned = true;
474新增: if (first is null || target.Started < first.Started) { first?.Dispose(); first = target; }
475新增: else target.Dispose();
476新增: }
477新增: catch (Exception e) when (e is InvalidDataException or InvalidOperationException or System.ComponentModel.Win32Exception) { }
478新增: finally { if (!owned) process.Dispose(); }
479新增: }
480新增: return first;
481新增: }
482新增: private static byte[] Capture(Window w) => ClaudeGraphicsCapture.Capture(w.Handle,w.Process.Id,w.Bounds.Right,w.Bounds.Bottom,()=>Validate(w,false)).GetAwaiter().GetResult();
483新增: private static Input Wheel(int amount, bool horizontal = false) => new() { Data = new InputData { Mouse = new Mouse { Flags = horizontal ? 0x1000u : 0x800u, Data = unchecked((uint)amount) } } };
484新增: private static Input Unicode(char c, bool up) => new() { Type = 1, Data = new InputData { Keyboard = new Keyboard { Scan = c, Flags = 4u | (up ? 2u : 0u) } } };
485新增: private static Input KeyInput(ushort key, bool down) => new() { Type = 1, Data = new InputData { Keyboard = new Keyboard { Key = key, Flags = down ? 0u : 2u } } };
486新增: private static void Emit(Window w, Input[] inputs, NativeInputCoordinator.Lease? lease=null)
487新增: {
488新增: var strokes=inputs.Select(input=>input.Type==1
489新增: ? InputStroke.Key((input.Data.Keyboard.Flags&4)!=0?input.Data.Keyboard.Scan:input.Data.Keyboard.Key,(input.Data.Keyboard.Flags&2)!=0,(input.Data.Keyboard.Flags&4)!=0)
490新增: : input.Data.Mouse.Flags switch
491新增: {
492新增: 2=>InputStroke.Button(1,false),4=>InputStroke.Button(1,true),32=>InputStroke.Button(2,false),64=>InputStroke.Button(2,true),8=>InputStroke.Button(4,false),16=>InputStroke.Button(4,true),
493新增: 0x800=>InputStroke.Wheel(unchecked((int)input.Data.Mouse.Data)),0x1000=>InputStroke.Wheel(unchecked((int)input.Data.Mouse.Data),true),
494新增: _=>throw new InvalidDataException("desktop_input_failed")
495新增: }).ToArray();
496新增: var own=lease is null;lease??=NativeGuestInput.OpenLease();
497新增: try{EmitStrokes(w,strokes,lease);}finally{if(own)NativeGuestInput.CloseLease(lease);}
498新增: }
499新增: private static void EmitStrokes(Window w,InputStroke[] strokes,NativeInputCoordinator.Lease lease)
500新增: {
501新增: var id=w.Process.Id;var started=w.Process.StartTime.ToUniversalTime();var session=w.Process.SessionId;var handle=w.Handle;var executable=w.Executable;
502新增: bool ReleaseAllowed()
503新增: {
504新增: if(!SessionGuard.Available() || Process.GetCurrentProcess().SessionId!=session)return false;
505新增: try
506新增: {
507新增: using var process=Process.GetProcessById(id);
508新增: if(process.HasExited)return true;
509新增: if(process.StartTime.ToUniversalTime()!=started || process.SessionId!=session || !string.Equals(process.MainModule?.FileName,executable,StringComparison.OrdinalIgnoreCase))return false;
510新增: var thread=GetWindowThreadProcessId(handle,out var current);
511新增: return thread==0 || current==id;
512新增: }
513新增: catch(ArgumentException){return true;}
514新增: catch{return false;}
515新增: }
516新增: NativeGuestInput.Emit(lease,strokes,()=>Validate(w,true),ReleaseAllowed);
517新增: }
518新增: private static ushort Key(uint sym) => sym switch
519新增: {
520新增: 0xff08 => 8, 0xff09 => 9, 0xff0d => 13, 0xff1b => 27, 0xffff => 46,
521新增: 0xff50 => 36, 0xff51 => 37, 0xff52 => 38, 0xff53 => 39, 0xff54 => 40, 0xff55 => 33, 0xff56 => 34, 0xff57 => 35, 0xff63 => 45,
522新增: 0xffe1 or 0xffe2 => 16, 0xffe3 or 0xffe4 => 17, 0xffe9 or 0xffea => 18, 0xffe7 or 0xffe8 or 0xffeb or 0xffec => 91,
523新增: >= 0xffbe and <= 0xffc9 => (ushort)(112 + sym - 0xffbe),
524新增: >= 32 and <= 126 => (ushort)(VkKeyScanW((char)sym) & 0xff), _ => 0
525新增: };
526新增:}
新增scripts/guest-os/guest-clipboard-windows/ClipboardAgent.cs+387 −0看文件
@@ -0,0 +1,387 @@
1新增:using System.Collections.Specialized;
2新增:using System.Diagnostics;
3新增:using System.Drawing.Imaging;
4新增:using System.Runtime.InteropServices;
5新增:using System.Text.Json;
6新增:using System.Text.Json.Nodes;
7新增:using System.Threading.Channels;
8新增:
9新增:namespace Cage.GuestClipboard;
10新增:
11新增:internal sealed class ClipboardAgent : Control
12新增:{
13新增: internal static ClipboardAgent? Current { get; private set; }
14新增: [DllImport("user32.dll")] static extern bool AddClipboardFormatListener(IntPtr window);
15新增: [DllImport("user32.dll")] static extern bool RemoveClipboardFormatListener(IntPtr window);
16新增: [DllImport("user32.dll")] static extern uint GetClipboardSequenceNumber();
17新增: [DllImport("wtsapi32.dll", SetLastError = true)] private static extern bool WTSRegisterSessionNotification(IntPtr window, uint flags);
18新增: [DllImport("wtsapi32.dll")] private static extern bool WTSUnRegisterSessionNotification(IntPtr window);
19新增: internal readonly string Session = Guid.NewGuid().ToString("N");
20新增: private long sessionEpoch = 1;
21新增: internal long SessionEpoch => Interlocked.Read(ref sessionEpoch);
22新增: internal bool SessionEventsRegistered { get; private set; }
23新增: readonly string helper;
24新增: readonly HashSet<string> approved = new(StringComparer.OrdinalIgnoreCase);
25新增: readonly Queue<string[]> selections = new();
26新增: sealed class CachedCopy(string id, string[] paths, bool pinned)
27新增: {
28新增: internal readonly string ID = id;
29新增: internal readonly string[] Paths = paths;
30新增: internal bool Pinned = pinned;
31新增: }
32新增: readonly Dictionary<string, CachedCopy> copies = new();
33新增: readonly Dictionary<Guid, string[]> fileReaders = new();
34新增: bool copiesLoaded, collectingCopies;
35新增: DateTime nextCacheCheck;
36新增: readonly System.Windows.Forms.Timer timer = new() { Interval = 250 };
37新增: Channel<JsonObject>? subscriber;
38新增: uint observed;
39新增: bool seeded, reading, lastAvailable;
40新增: CancellationTokenSource? selectionCopy;
41新增: internal ClipboardAgent(string filesHelper)
42新增: {
43新增: Current = this;
44新增: helper = filesHelper;
45新增: CreateControl(); _ = Handle;
46新增: if (!File.Exists(helper) || !AddClipboardFormatListener(Handle)) throw new InvalidOperationException("clipboard_agent_unavailable");
47新增: SessionEventsRegistered = WTSRegisterSessionNotification(Handle, 0);
48新增: lastAvailable = SessionGuard.Available(); observed = GetClipboardSequenceNumber();
49新增: timer.Tick += (_, _) => Tick(); timer.Start();
50新增: }
51新增: protected override void WndProc(ref Message m)
52新增: {
53新增: if (m.Msg == 0x031D) Tick(); // WM_CLIPBOARDUPDATE
54新增: if (m.Msg == 0x02B1) { Interlocked.Increment(ref sessionEpoch); Tick(); }
55新增: base.WndProc(ref m);
56新增: }
57新增: protected override void Dispose(bool disposing)
58新增: {
59新增: if (disposing) { timer.Stop(); timer.Dispose(); RemoveClipboardFormatListener(Handle); if (SessionEventsRegistered) WTSUnRegisterSessionNotification(Handle); subscriber?.Writer.TryComplete(); }
60新增: base.Dispose(disposing);
61新增: }
62新增: internal Task<T> GUI<T>(Func<T> action)
63新增: {
64新增: var result = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
65新增: BeginInvoke(() => { try { result.SetResult(action()); } catch (Exception ex) { result.SetException(ex); } });
66新增: return result.Task;
67新增: }
68新增: internal Task<uint> Revision() => GUI(() => { SessionGuard.Assert(); return GetClipboardSequenceNumber(); });
69新增: internal Task<bool> PasteImage(byte[] bytes, Action paste) => GUI(() =>
70新增: {
71新增: SessionGuard.Assert(); Protocol.Png(bytes);
72新增: using var input = new MemoryStream(bytes); using var image = Image.FromStream(input, false, true);
73新增: using var bitmap = new Bitmap(image);
74新增: var data = new DataObject(); data.SetData("PNG", false, new MemoryStream(bytes)); data.SetImage(bitmap);
75新增: Clipboard.SetDataObject(data, true); paste(); return true;
76新增: });
77新增: internal Task<bool> PasteFiles(string[] paths, Action paste) => GUI(() =>
78新增: {
79新增: SessionGuard.Assert(); Protocol.Paths(JsonSerializer.SerializeToNode(paths));
80新增: Approve(paths); var list=new StringCollection();list.AddRange(paths);
81新增: Clipboard.SetFileDropList(list);paste();return true;
82新增: });
83新增: // Private browser receipts confirm native Windows clipboard ownership.
84新增: // Content still travels through the single observer, preserving PNG and
85新增: // file selections instead of rewriting a browser's text-only result.
86新增: internal Task<JsonObject> Receipt(uint previous, bool requireChange) => GUI(() =>
87新增: {
88新增: SessionGuard.Assert(); var revision = GetClipboardSequenceNumber();
89新增: if (requireChange && revision == previous) throw new InvalidDataException("clipboard_copy_not_observed");
90新增: return new JsonObject { ["revision"] = revision, ["changed"] = revision != previous, ["available"] = true };
91新增: });
92新增: internal Task<JsonObject> PreparePaste() => GUI(() =>
93新增: {
94新增: SessionGuard.Assert(); var revision = GetClipboardSequenceNumber();
95新增: if (Clipboard.ContainsFileDropList()) { var paths = Protocol.Paths(JsonSerializer.SerializeToNode(Clipboard.GetFileDropList().Cast<string>().ToArray())); AssertApproved(paths); }
96新增: else if (Clipboard.TryGetData<MemoryStream>("PNG", out var png) && png != null) Protocol.Png(png.ToArray());
97新增: else if (Clipboard.ContainsImage())
98新增: {
99新增: using var image = Clipboard.GetImage() ?? throw new InvalidDataException("clipboard_image_unavailable");
100新增: if ((long)image.Width * image.Height > 40_000_000) throw new InvalidDataException("image_limit");
101新增: using var bytes = new MemoryStream(); image.Save(bytes, ImageFormat.Png); Protocol.Png(bytes.ToArray());
102新增: }
103新增: else if (Clipboard.ContainsText() && Protocol.Utf8.GetByteCount(Clipboard.GetText(TextDataFormat.UnicodeText)) > Protocol.TextLimit) throw new InvalidDataException("text_limit");
104新增: if (GetClipboardSequenceNumber() != revision) throw new InvalidDataException("clipboard_selection_changed");
105新增: return new JsonObject { ["revision"] = revision, ["available"] = true };
106新增: });
107新增: internal Task<JsonObject> WriteBrowserPng(uint expectedRevision, byte[] png) => GUI(() =>
108新增: {
109新增: SessionGuard.Assert(); Protocol.Png(png);
110新增: if (GetClipboardSequenceNumber() != expectedRevision) throw new InvalidDataException("clipboard_selection_changed");
111新增: using var input = new MemoryStream(png); using var image = Image.FromStream(input, false, true); using var bitmap = new Bitmap(image);
112新增: if (GetClipboardSequenceNumber() != expectedRevision) throw new InvalidDataException("clipboard_selection_changed");
113新增: var data = new DataObject(); data.SetData("PNG", false, new MemoryStream(png)); data.SetImage(bitmap); Clipboard.SetDataObject(data, true);
114新增: observed = GetClipboardSequenceNumber(); seeded = true;
115新增: Publish(new JsonObject { ["png"] = Convert.ToBase64String(png), ["source"] = "guest" });
116新增: return new JsonObject { ["revision"] = observed, ["available"] = true };
117新增: });
118新增: internal Task<JsonObject> WriteBrowserText(uint expectedRevision, string text) => GUI(() =>
119新增: {
120新增: SessionGuard.Assert();
121新增: if (Protocol.Utf8.GetByteCount(text) > Protocol.TextLimit) throw new InvalidDataException("text_limit");
122新增: if (GetClipboardSequenceNumber() != expectedRevision) throw new InvalidDataException("clipboard_selection_changed");
123新增: if (text.Length == 0) Clipboard.Clear(); else Clipboard.SetText(text, TextDataFormat.UnicodeText);
124新增: observed = GetClipboardSequenceNumber(); seeded = true;
125新增: Publish(new JsonObject { ["text"] = text, ["source"] = "guest" });
126新增: return new JsonObject { ["revision"] = observed, ["available"] = true };
127新增: });
128新增: internal JsonObject Hello() => new() { ["version"] = 1, ["os"] = "windows", ["session"] = Session, ["formats"] = new JsonArray("text", "png", "files"), ["available"] = SessionGuard.Available(), ["file_release"] = true };
129新增: internal Task<ChannelReader<JsonObject>> Subscribe() => GUI(() =>
130新增: {
131新增: if (subscriber != null) throw new InvalidOperationException("clipboard_busy");
132新增: subscriber = Channel.CreateBounded<JsonObject>(new BoundedChannelOptions(16) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
133新增: seeded = false; observed = GetClipboardSequenceNumber();
134新增: return subscriber.Reader;
135新增: });
136新增: internal Task<bool> Unsubscribe() => GUI(() => {
137新增: subscriber?.Writer.TryComplete(); subscriber = null; seeded = false;
138新增: foreach (var copy in copies.Values) copy.Pinned = false;
139新增: CollectCopies(); return true;
140新增: });
141新增: void Publish(JsonObject message)
142新增: {
143新增: if (subscriber != null && subscriber.Writer.TryWrite(message)) return;
144新增: if (message["files"] is not null) RetireCopies(Protocol.Paths(message["files"]));
145新增: subscriber?.Writer.TryComplete(new IOException("clipboard_consumer_slow"));
146新增: }
147新增: internal void ReportError() => Publish(new() { ["error"] = SessionGuard.Available() ? "clipboard_selection_unavailable" : "requires_gui_login" });
148新增: void Tick()
149新增: {
150新增: if (DateTime.UtcNow >= nextCacheCheck) { nextCacheCheck = DateTime.UtcNow.AddSeconds(1); CollectCopies(); }
151新增: var available = SessionGuard.Available();
152新增: if (available != lastAvailable) { Interlocked.Increment(ref sessionEpoch); lastAvailable = available; Publish(Protocol.PublicHello(Hello())); }
153新增: if (!available) selectionCopy?.Cancel();
154新增: if (!available || !seeded || subscriber == null || reading) return;
155新增: var sequence = GetClipboardSequenceNumber();
156新增: if (sequence == observed) return;
157新增: ReadSelection(sequence);
158新增: }
159新增: async void ReadSelection(uint sequence)
160新增: {
161新增: reading = true;
162新增: var capturedSubscriber = subscriber;
163新增: var capturedSession = SessionEpoch;
164新增: try
165新增: {
166新增: SessionGuard.Assert();
167新增: JsonObject payload;
168新增: if (Clipboard.ContainsFileDropList())
169新增: {
170新增: var paths = Clipboard.GetFileDropList().Cast<string>().ToArray();
171新增: Protocol.Paths(JsonSerializer.SerializeToNode(paths));
172新增: Approve(paths); // The native GUI selection itself is an explicit source grant.
173新增: // This child inherits the actual GUI token, never Session0 or a
174新增: // management administrator's access to the selected files.
175新增: using var copying = new CancellationTokenSource(TimeSpan.FromMinutes(30)); selectionCopy = copying;
176新增: string[] copied;
177新增: try { copied = await FilePaths("copy", paths, copying.Token); }
178新增: finally { if (selectionCopy == copying) selectionCopy = null; }
179新增: if (!SessionGuard.Available() || GetClipboardSequenceNumber() != sequence || subscriber != capturedSubscriber || SessionEpoch != capturedSession || !seeded) { RetireCopies(copied); return; }
180新增: Approve(copied);
181新增: payload = new() { ["files"] = JsonSerializer.SerializeToNode(copied) };
182新增: }
183新增: else if (Clipboard.ContainsData("PNG") || Clipboard.ContainsImage())
184新增: {
185新增: byte[] bytes;
186新增: if (Clipboard.TryGetData<MemoryStream>("PNG", out var png) && png != null) bytes = png.ToArray();
187新增: else
188新增: {
189新增: using var image = Clipboard.GetImage() ?? throw new InvalidDataException("clipboard_image_unavailable");
190新增: if ((long)image.Width * image.Height > 40_000_000) throw new InvalidDataException("image_limit");
191新增: using var output = new MemoryStream(); image.Save(output, ImageFormat.Png); bytes = output.ToArray();
192新增: }
193新增: Protocol.Png(bytes); payload = new() { ["png"] = Convert.ToBase64String(bytes) };
194新增: }
195新增: else
196新增: {
197新增: var text = Clipboard.ContainsText() ? Clipboard.GetText(TextDataFormat.UnicodeText) : "";
198新增: if (Protocol.Utf8.GetByteCount(text) > Protocol.TextLimit) throw new InvalidDataException("text_limit");
199新增: payload = new() { ["text"] = text };
200新增: }
201新增: if (!SessionGuard.Available() || GetClipboardSequenceNumber() != sequence) return;
202新增: observed = sequence; payload["source"] = "guest"; Publish(payload);
203新增: }
204新增: catch { if (SessionGuard.Available()) { observed = sequence; Publish(new() { ["error"] = "clipboard_selection_unavailable" }); } }
205新增: finally { reading = false; }
206新增: }
207新增: internal Task<bool> Apply(JsonObject message) => GUI(() =>
208新增: {
209新增: if (message["release"] is not null) { RetireCopies(Protocol.Paths(message["release"])); return true; }
210新增: SessionGuard.Assert();
211新增: selectionCopy?.Cancel();
212新增: var serial = message["serial"]?.GetValue<long>() ?? 0;
213新增: if (serial < 1 || new[] { "text", "png", "files" }.Count(message.ContainsKey) != 1) throw new InvalidDataException("clipboard_message_invalid");
214新增: if (message["files"] != null)
215新增: {
216新增: var paths = Protocol.Paths(message["files"]); AssertApproved(paths);
217新增: var list = new StringCollection(); list.AddRange(paths); Clipboard.SetFileDropList(list);
218新增: }
219新增: else if (message["png"] != null)
220新增: {
221新增: var bytes = Convert.FromBase64String(message["png"]!.GetValue<string>()); Protocol.Png(bytes);
222新增: using var input = new MemoryStream(bytes); using var image = Image.FromStream(input, false, true);
223新增: using var bitmap = new Bitmap(image);
224新增: var data = new DataObject(); data.SetData("PNG", false, new MemoryStream(bytes)); data.SetImage(bitmap);
225新增: Clipboard.SetDataObject(data, true);
226新增: }
227新增: else
228新增: {
229新增: var text = message["text"]!.GetValue<string>();
230新增: if (Protocol.Utf8.GetByteCount(text) > Protocol.TextLimit) throw new InvalidDataException("text_limit");
231新增: if (text.Length == 0) Clipboard.Clear(); else Clipboard.SetText(text, TextDataFormat.UnicodeText);
232新增: }
233新增: // The revision is saved on the STA before queued clipboard notifications
234新增: // run. Only a completed host write receives an acknowledgement.
235新增: observed = GetClipboardSequenceNumber(); seeded = true; Publish(new() { ["ack"] = serial }); return true;
236新增: });
237新增: void RememberCopy(JsonObject result)
238新增: {
239新增: var id = result["cache_id"]?.GetValue<string>();
240新增: if (string.IsNullOrEmpty(id)) return;
241新增: var paths = Protocol.Paths(result["paths"]);
242新增: copies[id] = new CachedCopy(id, paths, true);
243新增: _ = PublishCopy(id);
244新增: }
245新增: async Task PublishCopy(string id)
246新增: {
247新增: try { await Cache("publish", id); } catch { }
248新增: }
249新增: void RetireCopies(string[] paths)
250新增: {
251新增: foreach (var copy in copies.Values)
252新增: if (copy.Paths.Any(path => paths.Contains(path, StringComparer.OrdinalIgnoreCase))) copy.Pinned = false;
253新增: CollectCopies();
254新增: }
255新增: static bool References(string[] paths, string[] owned)
256新增: {
257新增: var root = Path.GetDirectoryName(owned[0])!;
258新增: return paths.Any(path => Path.GetFullPath(path).Equals(root, StringComparison.OrdinalIgnoreCase)
259新增: || Path.GetFullPath(path).StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
260新增: || root.StartsWith(Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase));
261新增: }
262新增: async Task<JsonObject> Cache(string action, string id = "")
263新增: {
264新增: var start = new ProcessStartInfo(helper) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true };
265新增: start.ArgumentList.Add("cache"); start.ArgumentList.Add(JsonSerializer.Serialize(new { action, cache_id = id }));
266新增: using var child = Process.Start(start) ?? throw new IOException("clipboard_cache_unavailable");
267新增: child.StandardInput.Close();
268新增: _ = child.StandardError.BaseStream.CopyToAsync(Stream.Null);
269新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
270新增: using var cancellation = timeout.Token.Register(() => { try { child.Kill(true); } catch { } });
271新增: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, timeout.Token) ?? throw new IOException("clipboard_cache_failed");
272新增: await child.WaitForExitAsync(timeout.Token);
273新增: if (child.ExitCode != 0) throw new IOException("clipboard_cache_failed");
274新增: return result;
275新增: }
276新增: async void CollectCopies()
277新增: {
278新增: if (collectingCopies || IsDisposed) return;
279新增: collectingCopies = true;
280新增: try
281新增: {
282新增: if (!copiesLoaded)
283新增: {
284新增: copiesLoaded = true;
285新增: var previous = await Cache("list");
286新增: foreach (var item in previous["selections"]!.AsArray())
287新增: {
288新增: var id = item!["cache_id"]!.GetValue<string>();
289新增: copies.TryAdd(id, new CachedCopy(id, Protocol.Paths(item["paths"]), false));
290新增: }
291新增: }
292新增: foreach (var copy in copies.Values.ToArray())
293新增: {
294新增: var selected = Clipboard.ContainsFileDropList() ? Clipboard.GetFileDropList().Cast<string>().ToArray() : [];
295新增: if (copy.Pinned || References(selected, copy.Paths) || fileReaders.Values.Any(paths => References(paths, copy.Paths))) continue;
296新增: try
297新增: {
298新增: await Cache("release", copy.ID);
299新增: copies.Remove(copy.ID);
300新增: foreach (var path in copy.Paths) approved.Remove(path);
301新增: }
302新增: catch { /* Keep its creation receipt for an ownership-change retry. */ }
303新增: }
304新增: }
305新增: catch { /* An unreadable clipboard retains its currently referenced files. */ }
306新增: finally { collectingCopies = false; }
307新增: }
308新增: void Approve(string[] paths)
309新增: {
310新增: selections.Enqueue(paths);
311新增: foreach (var path in paths) approved.Add(Path.GetFullPath(path));
312新增: while (selections.Count > 100)
313新增: {
314新增: var old = selections.Dequeue();
315新增: foreach (var path in old) if (!selections.Any(s => s.Contains(path, StringComparer.OrdinalIgnoreCase))) approved.Remove(Path.GetFullPath(path));
316新增: }
317新增: }
318新增: void AssertApproved(string[] paths)
319新增: {
320新增: if (paths.Any(path => !approved.Contains(Path.GetFullPath(path)))) throw new InvalidDataException("selection_not_authorized");
321新增: }
322新增: Process StartHelper(string operation)
323新增: {
324新增: SessionGuard.Assert();
325新增: var start = new ProcessStartInfo(helper) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true };
326新增: start.ArgumentList.Add(operation); if (operation != "import") start.ArgumentList.Add("--paths-stdin");
327新增: var process = Process.Start(start) ?? throw new IOException("file_helper_unavailable");
328新增: _ = process.StandardError.BaseStream.CopyToAsync(Stream.Null); return process;
329新增: }
330新增: internal async Task<string[]> FilePaths(string operation, string[]? paths, CancellationToken token)
331新增: {
332新增: var reader = Guid.NewGuid();
333新增: if (paths != null) await GUI(() => { fileReaders[reader] = paths; return true; });
334新增: string[]? created = null;
335新增: try
336新增: {
337新增: using var child = StartHelper(operation);
338新增: using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } });
339新增: if (paths != null) await JsonSerializer.SerializeAsync(child.StandardInput.BaseStream, paths, cancellationToken: token);
340新增: child.StandardInput.Close();
341新增: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, token) ?? throw new IOException("file_helper_failed");
342新增: created = Protocol.Paths(result["paths"]);
343新增: await GUI(() => { RememberCopy(result); return true; });
344新增: await child.WaitForExitAsync(token);
345新增: if (child.ExitCode != 0) throw new IOException("file_helper_failed");
346新增: return created;
347新增: }
348新增: catch
349新增: {
350新增: if (created != null) await GUI(() => { RetireCopies(created); return true; });
351新增: throw;
352新增: }
353新增: finally { await GUI(() => { fileReaders.Remove(reader); CollectCopies(); return true; }); }
354新增: }
355新增: internal async Task Import(Stream stream, CancellationToken token)
356新增: {
357新增: using var child = StartHelper("import");
358新增: using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } });
359新增: await Protocol.ReceiveFrames(stream, child.StandardInput.BaseStream, token); child.StandardInput.Close();
360新增: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, token) ?? throw new IOException("file_helper_failed");
361新增: var paths = Protocol.Paths(result["paths"]);
362新增: await GUI(() => { RememberCopy(result); return true; });
363新增: try
364新增: {
365新增: await child.WaitForExitAsync(token);
366新增: if (child.ExitCode != 0) throw new IOException("file_helper_failed");
367新增: await GUI(() => { SessionGuard.Assert(); Approve(paths); return true; });
368新增: await Protocol.Write(stream, new() { ["paths"] = JsonSerializer.SerializeToNode(paths) }, token);
369新增: } catch { await GUI(() => { RetireCopies(paths); return true; }); throw; }
370新增: }
371新增: internal async Task Export(Stream stream, JsonNode? selection, CancellationToken token)
372新增: {
373新增: var paths = Protocol.Paths(selection);
374新增: var reader = Guid.NewGuid();
375新增: await GUI(() => { SessionGuard.Assert(); AssertApproved(paths); fileReaders[reader] = paths; return true; });
376新增: try
377新增: {
378新增: using var child = StartHelper("export");
379新增: using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } });
380新增: await JsonSerializer.SerializeAsync(child.StandardInput.BaseStream, paths, cancellationToken: token); child.StandardInput.Close();
381新增: await Protocol.SendFrames(child.StandardOutput.BaseStream, stream, token);
382新增: await child.WaitForExitAsync(token); SessionGuard.Assert();
383新增: await Protocol.Write(stream, new() { ["complete"] = child.ExitCode == 0 }, token);
384新增: }
385新增: finally { await GUI(() => { fileReaders.Remove(reader); CollectCopies(); return true; }); }
386新增: }
387新增:}
新增scripts/guest-os/guest-clipboard-windows/GlobalUsings.cs+1 −0看文件
@@ -0,0 +1 @@
1新增:global using System.IO;
新增scripts/guest-os/guest-clipboard-windows/GuestDiagnostics.cs+121 −0看文件
@@ -0,0 +1,121 @@
1新增:using System.Security.AccessControl;
2新增:using System.Runtime.CompilerServices;
3新增:using System.Security.Principal;
4新增:using System.Text.Json;
5新增:using System.Text.RegularExpressions;
6新增:
7新增:namespace Cage.GuestClipboard;
8新增:
9新增:internal static class GuestDiagnostics
10新增:{
11新增: private const long FileBytes = 1 << 20;
12新增: private static readonly object Sync = new();
13新增: private static readonly Regex Code = new("^[a-zA-Z][a-zA-Z0-9_]{0,95}$", RegexOptions.CultureInvariant);
14新增: private static string last = "";
15新增: private static DateTime lastAt;
16新增:
17新增: private static IEnumerable<string> Files(string directory) => Enumerable.Range(0, 10)
18新增: .Select(index => Path.Combine(directory, index == 0 ? "events.jsonl" : $"events-{index}.jsonl"))
19新增: .Where(File.Exists);
20新增:
21新增: [ModuleInitializer]
22新增: internal static void Register() => GuestOperations.Register("diagnostics", Read);
23新增:
24新增: private static string DirectoryPath()
25新增: {
26新增: var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Cage", "Diagnostics");
27新增: foreach (var current in new[] { Path.GetDirectoryName(directory)!, directory })
28新增: {
29新增: Directory.CreateDirectory(current);
30新增: if (new DirectoryInfo(current).Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new IOException("diagnostic_path_invalid");
31新增: }
32新增: using var identity = WindowsIdentity.GetCurrent();
33新增: var acl = new DirectorySecurity();
34新增: acl.SetAccessRuleProtection(true, false);
35新增: foreach (var sid in new[] { identity.User!, new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null) })
36新增: acl.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl,
37新增: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
38新增: new DirectoryInfo(directory).SetAccessControl(acl);
39新增: return directory;
40新增: }
41新增:
42新增: private static void Clean(string directory)
43新增: {
44新增: foreach (var file in Files(directory))
45新增: {
46新增: var info = new FileInfo(file);
47新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new IOException("diagnostic_path_invalid");
48新增: if (info.LastWriteTimeUtc < DateTime.UtcNow.AddDays(-14)) File.Delete(file);
49新增: }
50新增: }
51新增:
52新增: internal static void Record(string source, string reason)
53新增: {
54新增: if (!Code.IsMatch(source) || !Code.IsMatch(reason)) return;
55新增: try
56新增: {
57新增: lock (Sync)
58新增: {
59新增: var now = DateTime.UtcNow;
60新增: var key = source + "/" + reason;
61新增: if (key == last && now - lastAt < TimeSpan.FromSeconds(5)) return;
62新增: var directory = DirectoryPath();
63新增: Clean(directory);
64新增: var file = Path.Combine(directory, "events.jsonl");
65新增: var entry = JsonSerializer.Serialize(new { time = now, source, reason }) + "\n";
66新增: if (File.Exists(file) && (new FileInfo(file).Length + Protocol.Utf8.GetByteCount(entry) > FileBytes || File.GetCreationTimeUtc(file).Date != now.Date))
67新增: {
68新增: for (var index = 9; index >= 1; index--)
69新增: {
70新增: var old = Path.Combine(directory, index == 1 ? "events.jsonl" : $"events-{index - 1}.jsonl");
71新增: var target = Path.Combine(directory, $"events-{index}.jsonl");
72新增: if (File.Exists(old)) File.Move(old, target, true);
73新增: }
74新增: }
75新增: File.AppendAllText(file, entry, Protocol.Utf8);
76新增: last = key;
77新增: lastAt = now;
78新增: }
79新增: }
80新增: catch { /* Diagnostic storage failure must preserve the original operation. */ }
81新增: }
82新增:
83新增: internal static void Failure(string source, Exception error) => Record(source, error.GetType().Name);
84新增:
85新增: private static async Task Read(Stream stream, CancellationToken token, Func<bool> available)
86新增: {
87新增: var request = await Protocol.Read(stream, 1024, token);
88新增: if (request?["action"]?.GetValue<string>() != "read") throw new InvalidDataException("diagnostic_request_invalid");
89新增: var lines = new Queue<string>();
90新增: var bytes = 0;
91新增: lock (Sync)
92新增: {
93新增: var directory = DirectoryPath();
94新增: Clean(directory);
95新增: // Rotation numbers preserve the write order even when file timestamps tie.
96新增: foreach (var file in Files(directory).Reverse())
97新增: {
98新增: if (new FileInfo(file).Length > FileBytes + 4096) continue;
99新增: foreach (var line in File.ReadLines(file, Protocol.Utf8))
100新增: {
101新增: if (line.Length > 4096) continue;
102新增: try
103新增: {
104新增: using var item = JsonDocument.Parse(line);
105新增: var value = item.RootElement;
106新增: var source = value.GetProperty("source").GetString() ?? "";
107新增: var reason = value.GetProperty("reason").GetString() ?? "";
108新增: var time = value.GetProperty("time").GetDateTime();
109新增: if (!Code.IsMatch(source) || !Code.IsMatch(reason) || time < DateTime.UtcNow.AddDays(-14)) continue;
110新增: var safe = JsonSerializer.Serialize(new { time, source, reason }) + "\n";
111新增: lines.Enqueue(safe);
112新增: bytes += Protocol.Utf8.GetByteCount(safe);
113新增: while (lines.Count > 150 || bytes > 48 << 10) bytes -= Protocol.Utf8.GetByteCount(lines.Dequeue());
114新增: }
115新增: catch (Exception error) when (error is JsonException or InvalidOperationException or KeyNotFoundException or FormatException) { }
116新增: }
117新增: }
118新增: }
119新增: await Protocol.Write(stream, new() { ["version"] = 1, ["lines"] = string.Concat(lines) }, token);
120新增: }
121新增:}
新增scripts/guest-os/guest-clipboard-windows/GuestProcessJob.cs+31 −0看文件
@@ -0,0 +1,31 @@
1新增:using System.ComponentModel;
2新增:using System.Diagnostics;
3新增:using System.Runtime.InteropServices;
4新增:
5新增:namespace Cage.GuestClipboard;
6新增:
7新增:// Attach before the controller sends its first request. Chrome and editor
8新增:// children then inherit this non-inheritable, kill-on-owner-exit job.
9新增:internal sealed class GuestProcessJob : IDisposable
10新增:{
11新增: private IntPtr handle;
12新增: internal GuestProcessJob(Process process)
13新增: {
14新增: handle=CreateJobObject(IntPtr.Zero,null);
15新增: if(handle==IntPtr.Zero)throw new Win32Exception();
16新增: try
17新增: {
18新增: var limits=new Limits();limits.Basic.Flags=0x2000;
19新增: if(!SetInformationJobObject(handle,9,ref limits,(uint)Marshal.SizeOf<Limits>())||!AssignProcessToJobObject(handle,process.Handle))throw new Win32Exception();
20新增: }
21新增: catch{Dispose();throw;}
22新增: }
23新增: public void Dispose(){var job=Interlocked.Exchange(ref handle,IntPtr.Zero);if(job!=IntPtr.Zero)CloseHandle(job);}
24新增: [StructLayout(LayoutKind.Sequential)]private struct Basic{internal long ProcessTime,JobTime;internal uint Flags;internal nuint MinWorking,MaxWorking;internal uint Active;internal nuint Affinity;internal uint Priority,Scheduling;}
25新增: [StructLayout(LayoutKind.Sequential)]private struct IO{internal ulong ReadOperations,WriteOperations,OtherOperations,ReadBytes,WriteBytes,OtherBytes;}
26新增: [StructLayout(LayoutKind.Sequential)]private struct Limits{internal Basic Basic;internal IO IO;internal nuint ProcessMemory,JobMemory,PeakProcessMemory,PeakJobMemory;}
27新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode,EntryPoint="CreateJobObjectW",SetLastError=true)]private static extern IntPtr CreateJobObject(IntPtr attributes,string? name);
28新增: [DllImport("kernel32.dll",SetLastError=true)]private static extern bool SetInformationJobObject(IntPtr job,int type,ref Limits limits,uint size);
29新增: [DllImport("kernel32.dll",SetLastError=true)]private static extern bool AssignProcessToJobObject(IntPtr job,IntPtr process);
30新增: [DllImport("kernel32.dll")]private static extern bool CloseHandle(IntPtr handle);
31新增:}
新增scripts/guest-os/guest-clipboard-windows/GuestVersions.cs+154 −0看文件
@@ -0,0 +1,154 @@
1新增:using System.Diagnostics;
2新增:using System.Runtime.CompilerServices;
3新增:using System.Security.AccessControl;
4新增:using System.Security.Cryptography;
5新增:using System.Security.Principal;
6新增:using System.Text.Json.Nodes;
7新增:
8新增:namespace Cage.GuestClipboard;
9新增:
10新增:internal static class GuestVersions
11新增:{
12新增: [ModuleInitializer]
13新增: internal static void Register() => GuestOperations.Register("versions", Read);
14新增:
15新增: private static async Task Read(Stream stream, CancellationToken token, Func<bool> available)
16新增: {
17新增: var result = Snapshot();
18新增: var tools = new JsonObject();
19新增: tools["node"] = await Version(Path.Combine(AppContext.BaseDirectory, "node.exe"), token);
20新增: tools["code_server"] = await Version(Path.Combine(AppContext.BaseDirectory, "vscode-cli", "code.exe"), token);
21新增: var chrome = new[] {
22新增: Path.Combine(AppContext.BaseDirectory, "chrome", "chrome.exe"),
23新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Google", "Chrome", "Application", "chrome.exe"),
24新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Microsoft", "Edge", "Application", "msedge.exe")
25新增: }.FirstOrDefault(File.Exists);
26新增: tools["chromium"] = chrome is null ? "" : FileVersionInfo.GetVersionInfo(chrome).ProductVersion ?? "";
27新增: try
28新增: {
29新增: var receipt = Path.Combine(AppContext.BaseDirectory, "cli-tools.json");
30新增: Pairing.PrivateFile(receipt);
31新增: var cli = JsonNode.Parse(File.ReadAllBytes(receipt)) as JsonObject;
32新增: foreach (var name in new[] { "python", "claude", "git_bash" })
33新增: {
34新增: var filename = cli?[name]?.GetValue<string>();
35新增: var expected = cli?[name + "_sha256"]?.GetValue<string>();
36新增: if (filename is null || expected is null || !Path.IsPathRooted(filename)) continue;
37新增: using (var file = File.OpenRead(filename))
38新增: if (!Convert.ToHexString(SHA256.HashData(file)).Equals(expected, StringComparison.OrdinalIgnoreCase)) continue;
39新增: if (name == "git_bash")
40新增: tools["git"] = await Version(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(filename))!, "cmd", "git.exe"), token);
41新增: else tools[name] = await Version(filename, token);
42新增: }
43新增: }
44新增: catch (IOException) { }
45新增: catch (UnauthorizedAccessException) { }
46新增: catch (System.Text.Json.JsonException) { }
47新增: result["tools"] = tools;
48新增: await Protocol.Write(stream, result, token);
49新增: }
50新增:
51新增: internal static JsonObject Snapshot()
52新增: {
53新增: var result = new JsonObject { ["manifest"] = null, ["installed"] = false, ["missing"] = new JsonArray() };
54新增: try
55新增: {
56新增: var path = Path.Combine(AppContext.BaseDirectory, "native-components.json");
57新增: CheckReceipt(path);
58新增: var manifest = JsonNode.Parse(File.ReadAllText(path)) as JsonObject;
59新增: if (manifest?["protocol"]?.GetValue<int>() != 1 || manifest["system"]?.GetValue<string>() != "windows-11" || manifest["files"] is not JsonArray files || files.Count > 10000)
60新增: throw new InvalidDataException("component_manifest_invalid");
61新增: var missing = new JsonArray();
62新增: foreach (var entry in files.OfType<JsonObject>())
63新增: {
64新增: var target = entry["target"]?.GetValue<string>() ?? "";
65新增: if (target.Length == 0) continue;
66新增: var filename = Target(target);
67新增: try
68新增: {
69新增: using var file = File.OpenRead(filename);
70新增: var hash = Convert.ToHexString(SHA256.HashData(file));
71新增: if (!hash.Equals(entry["installed_sha256"]?.GetValue<string>(), StringComparison.OrdinalIgnoreCase) && missing.Count < 20) missing.Add(target);
72新增: }
73新增: catch (IOException) { if (missing.Count < 20) missing.Add(target); }
74新增: }
75新增: result["manifest"] = new JsonObject {
76新增: ["protocol"] = 1, ["revision"] = missing.Count == 0 ? manifest["revision"]?.DeepClone() : "",
77新增: ["app_version"] = manifest["app_version"]?.DeepClone()
78新增: };
79新增: result["installed"] = missing.Count == 0;
80新增: result["missing"] = missing;
81新增: }
82新增: catch (Exception error) when (error is IOException or UnauthorizedAccessException or System.Text.Json.JsonException or InvalidOperationException)
83新增: {
84新增: result["error"] = "客机尚无可核验的组件记录,请同步环境组件。";
85新增: }
86新增: return result;
87新增: }
88新增:
89新增: private static void CheckReceipt(string path)
90新增: {
91新增: var file = new FileInfo(path);
92新增: if (!file.Exists || file.Length is < 1 or > 4 << 20 || file.Attributes.HasFlag(FileAttributes.ReparsePoint))
93新增: throw new InvalidDataException("component_manifest_invalid");
94新增: for (var parent = file.Directory; parent is not null; parent = parent.Parent)
95新增: if (parent.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("component_manifest_invalid");
96新增: var acl = file.GetAccessControl();
97新增: var administrators = new HashSet<string> { "S-1-5-18", "S-1-5-32-544" };
98新增: var owner = acl.GetOwner(typeof(SecurityIdentifier))?.Value;
99新增: if (!acl.AreAccessRulesProtected || owner is null || !administrators.Contains(owner))
100新增: throw new InvalidDataException("component_permissions_invalid");
101新增: var read = FileSystemRights.ReadAndExecute | FileSystemRights.Synchronize;
102新增: foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(SecurityIdentifier)))
103新增: {
104新增: if (rule.AccessControlType != AccessControlType.Allow || administrators.Contains(rule.IdentityReference.Value)) continue;
105新增: if (rule.IdentityReference.Value != GuestContext.SID || (rule.FileSystemRights & ~read) != 0)
106新增: throw new InvalidDataException("component_permissions_invalid");
107新增: }
108新增: }
109新增:
110新增: private static string Target(string target)
111新增: {
112新增: var parts = target.Split('/');
113新增: if (parts.Length < 2 || parts.Any(part => part.Length == 0 || part is "." or ".." || part.Contains('\\') || part.Contains(':')))
114新增: throw new InvalidDataException("component_target_invalid");
115新增: var root = parts[0] switch {
116新增: "bridge" => AppContext.BaseDirectory,
117新增: "network" => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Cage Guest Network", GuestContext.VM.ToString("D")),
118新增: _ => throw new InvalidDataException("component_target_invalid")
119新增: };
120新增: return Path.Combine([root, .. parts.Skip(1)]);
121新增: }
122新增:
123新增: private static async Task<string> Version(string executable, CancellationToken parent)
124新增: {
125新增: if (!File.Exists(executable)) return "";
126新增: using var timeout = CancellationTokenSource.CreateLinkedTokenSource(parent);
127新增: timeout.CancelAfter(TimeSpan.FromSeconds(3));
128新增: var start = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true };
129新增: start.ArgumentList.Add("--version");
130新增: start.Environment["DISABLE_AUTOUPDATER"] = "1";
131新增: Process? launched;
132新增: try { launched = Process.Start(start); }
133新增: catch (Exception error) when (error is System.ComponentModel.Win32Exception or IOException) { return ""; }
134新增: using var process = launched;
135新增: if (process is null) return "";
136新增: process.StandardInput.Close();
137新增: using var cancel = timeout.Token.Register(() => {
138新增: try { process.Kill(true); }
139新增: catch (Exception error) when (error is InvalidOperationException or System.ComponentModel.Win32Exception) { }
140新增: });
141新增: try
142新增: {
143新增: var errors = process.StandardError.BaseStream.CopyToAsync(Stream.Null, timeout.Token);
144新增: var output = new char[512];
145新增: var count = await process.StandardOutput.ReadAsync(output, timeout.Token);
146新增: await process.StandardOutput.BaseStream.CopyToAsync(Stream.Null, timeout.Token);
147新增: await process.WaitForExitAsync(timeout.Token);
148新增: await errors;
149新增: var line = new string(output, 0, count).Split('\n')[0].Trim();
150新增: return process.ExitCode == 0 ? line[..Math.Min(line.Length, 200)] : "";
151新增: }
152新增: catch (OperationCanceledException) { return ""; }
153新增: }
154新增:}
新增scripts/guest-os/guest-clipboard-windows/GuestWindowCapture.cs+9 −0看文件
@@ -0,0 +1,9 @@
1新增:namespace Cage.GuestClipboard;
2新增:
3新增:// The caller pins one owned HWND/PID and supplies its lifetime validation.
4新增:// The shared worker provides only WGC CreateForWindow, never monitor capture.
5新增:internal static class GuestWindowCapture
6新增:{
7新增: internal static Task<byte[]> Capture(IntPtr window, int pid, int width, int height, Action validate, bool allowSolid = false, bool preserveAlpha = false)
8新增: => ClaudeGraphicsCapture.Capture(window, pid, width, height, validate, allowSolid, preserveAlpha);
9新增:}
新增scripts/guest-os/guest-clipboard-windows/NativeGuestInput.cs+112 −0看文件
@@ -0,0 +1,112 @@
1新增:using System.Runtime.InteropServices;
2新增:
3新增:namespace Cage.GuestClipboard;
4新增:
5新增:internal readonly record struct InputStroke(ushort Value, bool Up, bool Unicode = false, int MouseButton = 0, int WheelDelta = 0, bool Horizontal = false)
6新增:{
7新增: internal static InputStroke Key(ushort value, bool up, bool unicode = false) => new(value, up, unicode);
8新增: internal static InputStroke Button(int bit, bool up) => new(0, up, false, bit);
9新增: internal static InputStroke Wheel(int delta, bool horizontal = false) => new(0, false, false, 0, delta, horizontal);
10新增: internal InputStroke Press => this with { Up = false };
11新增:}
12新增:
13新增:// One coordinator covers the GUI process's kernel input state. A lease never
14新增:// appears on the wire. Callbacks contain immutable, server-verified ownership;
15新增:// release callbacks must not acquire an RPC lock or focus a window.
16新增:internal sealed class NativeInputCoordinator(Func<InputStroke, bool> inject)
17新增:{
18新增: internal sealed class Lease
19新增: {
20新增: internal readonly Dictionary<InputStroke, Func<bool>> Pressed = [];
21新增: internal readonly Dictionary<uint, InputStroke[]> Symbols = [];
22新增: internal readonly HashSet<InputStroke> Releasing = [];
23新增: internal bool Closed, Resetting;
24新增: }
25新增: private readonly object sync = new();
26新增: private readonly HashSet<Lease> leases = [];
27新增: private readonly Dictionary<InputStroke, HashSet<Lease>> owners = [];
28新增: internal Lease Open() { lock(sync) { var lease = new Lease(); leases.Add(lease); return lease; } }
29新增: internal bool KeyHeld(ushort key) { lock(sync) return owners.ContainsKey(InputStroke.Key(key, false)); }
30新增: internal int Buttons(Lease lease) { lock(sync) return lease.Pressed.Keys.Aggregate(0, (mask, key) => mask | key.MouseButton); }
31新增: internal bool Owns(Lease lease, InputStroke stroke) { lock(sync) return lease.Pressed.ContainsKey(stroke.Press); }
32新增: internal void Emit(Lease lease, InputStroke[] strokes, Action validate, Func<bool> releaseAllowed)
33新增: {
34新增: lock(sync)
35新增: {
36新增: if(!leases.Contains(lease) || lease.Closed || lease.Resetting) throw new InvalidDataException("native_input_lease_closed");
37新增: validate();
38新增: foreach(var stroke in strokes)
39新增: {
40新增: var key = stroke.Press;
41新增: if(stroke.WheelDelta == 0 && stroke.Up)
42新增: {
43新增: // A viewer cannot release another viewer's input. When both
44新增: // pressed the same key, the last owner sends the physical up.
45新增: if(!lease.Pressed.ContainsKey(key)) continue;
46新增: if(owners[key].Count > 1) { Forget(lease, key); continue; }
47新增: }
48新增: if(!inject(stroke)) throw new InvalidDataException("native_input_failed");
49新增: if(stroke.WheelDelta != 0) continue;
50新增: if(stroke.Up) Forget(lease, key);
51新增: else
52新增: {
53新增: if(!owners.TryGetValue(key, out var set)) owners[key] = set = [];
54新增: set.Add(lease); lease.Pressed[key] = releaseAllowed; lease.Releasing.Remove(key);
55新增: }
56新增: }
57新增: validate();
58新增: }
59新增: }
60新增: internal void Close(Lease lease) { lock(sync) { lease.Closed = true; Release(lease); } }
61新增: internal void Reset(Lease lease) { lock(sync) { lease.Resetting = true; Release(lease); } }
62新增: internal void ReleaseInputs(Lease lease,InputStroke[] strokes){lock(sync){foreach(var stroke in strokes)if(lease.Pressed.ContainsKey(stroke.Press))lease.Releasing.Add(stroke.Press);Release(lease);}}
63新增: internal void Retry() { lock(sync) foreach(var lease in leases.Where(l => l.Closed || l.Resetting || l.Releasing.Count>0).ToArray()) Release(lease); }
64新增: internal void CloseAll() { lock(sync) foreach(var lease in leases.ToArray()) { lease.Closed = true; Release(lease); } }
65新增: private void Release(Lease lease)
66新增: {
67新增: foreach(var item in lease.Pressed.Where(item=>lease.Closed||lease.Resetting||lease.Releasing.Contains(item.Key)).ToArray())
68新增: {
69新增: if(owners[item.Key].Count > 1) { Forget(lease, item.Key); continue; }
70新增: try { if(item.Value() && inject(item.Key with { Up = true })) Forget(lease, item.Key); }
71新增: catch { /* Keep the successful down until this GUI can release it. */ }
72新增: }
73新增: if(lease.Pressed.Count == 0)
74新增: {
75新增: lease.Symbols.Clear(); lease.Resetting = false;
76新增: if(lease.Closed) leases.Remove(lease);
77新增: }
78新增: }
79新增: private void Forget(Lease lease, InputStroke key)
80新增: {
81新增: lease.Pressed.Remove(key);lease.Releasing.Remove(key);
82新增: if(owners.TryGetValue(key, out var set) && set.Remove(lease) && set.Count == 0) owners.Remove(key);
83新增: }
84新增:}
85新增:
86新增:internal static class NativeGuestInput
87新增:{
88新增: private static readonly NativeInputCoordinator State = new(Inject);
89新增: private static readonly System.Threading.Timer Retry = new(_ => State.Retry(), null, 250, 250);
90新增: static NativeGuestInput() => AppDomain.CurrentDomain.ProcessExit += (_, _) => { Retry.Dispose(); State.CloseAll(); };
91新增: internal static NativeInputCoordinator.Lease OpenLease() => State.Open();
92新增: internal static void CloseLease(NativeInputCoordinator.Lease lease) => State.Close(lease);
93新增: internal static void ResetLease(NativeInputCoordinator.Lease lease) => State.Reset(lease);
94新增: internal static void ReleaseInputs(NativeInputCoordinator.Lease lease,InputStroke[] strokes)=>State.ReleaseInputs(lease,strokes);
95新增: internal static bool PressedKey(ushort key) => State.KeyHeld(key);
96新增: internal static int PressedButtons(NativeInputCoordinator.Lease lease) => State.Buttons(lease);
97新增: internal static bool Owns(NativeInputCoordinator.Lease lease, InputStroke stroke) => State.Owns(lease, stroke);
98新增: internal static void Emit(NativeInputCoordinator.Lease lease, InputStroke[] strokes, Action validateBeforeAfter, Func<bool> releaseAllowed) => State.Emit(lease, strokes, validateBeforeAfter, releaseAllowed);
99新增: private static bool Inject(InputStroke stroke)
100新增: {
101新增: var input = new Input();
102新增: if(stroke.WheelDelta != 0) input.Data.Mouse = new Mouse { Flags = stroke.Horizontal ? 0x1000u : 0x800u, Data = unchecked((uint)stroke.WheelDelta) };
103新增: else if(stroke.MouseButton != 0) input.Data.Mouse = new Mouse { Flags = (stroke.MouseButton, stroke.Up) switch { (1,false) => 2u, (1,true) => 4u, (2,false) => 32u, (2,true) => 64u, (4,false) => 8u, (4,true) => 16u, _ => throw new InvalidDataException("native_input_invalid") } };
104新增: else { input.Type = 1; input.Data.Key = new Key { Virtual = stroke.Unicode ? (ushort)0 : stroke.Value, Scan = stroke.Unicode ? stroke.Value : (ushort)0, Flags = (stroke.Unicode ? 4u : 0) | (stroke.Up ? 2u : 0) }; }
105新增: return SendInput(1, [input], Marshal.SizeOf<Input>()) == 1;
106新增: }
107新增: [StructLayout(LayoutKind.Sequential)] private struct Mouse { internal int X,Y; internal uint Data,Flags,Time; internal UIntPtr Extra; }
108新增: [StructLayout(LayoutKind.Sequential)] private struct Key { internal ushort Virtual,Scan; internal uint Flags,Time; internal UIntPtr Extra; }
109新增: [StructLayout(LayoutKind.Explicit)] private struct Data { [FieldOffset(0)] internal Mouse Mouse; [FieldOffset(0)] internal Key Key; }
110新增: [StructLayout(LayoutKind.Sequential)] private struct Input { internal uint Type; internal Data Data; }
111新增: [DllImport("user32.dll")] private static extern uint SendInput(uint count, Input[] inputs, int size);
112新增:}
新增scripts/guest-os/guest-clipboard-windows/NativeSafetyRpc.cs+114 −0看文件
@@ -0,0 +1,114 @@
1新增:using System.Globalization;
2新增:using System.Net;
3新增:using System.Net.Http;
4新增:using System.Net.NetworkInformation;
5新增:using System.Net.Sockets;
6新增:using System.Runtime.CompilerServices;
7新增:using System.Runtime.InteropServices;
8新增:using System.Security.Cryptography;
9新增:using System.Text.Json.Nodes;
10新增:
11新增:namespace Cage.GuestClipboard;
12新增:
13新增:// Bounded probes use fixed destinations. The host accepts their results only
14新增:// alongside the current packet gate's own denial and diagnostic counters.
15新增:internal static class NativeSafetyRpc
16新增:{
17新增: [ModuleInitializer] internal static void Register() => GuestOperations.Register("safety",Run);
18新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode)] private static extern int GetSystemDefaultLocaleName(char[] value,int capacity);
19新增: private sealed class Progress { internal string Stage="request"; }
20新增: internal static async Task Run(Stream stream,CancellationToken token,Func<bool> available)
21新增: {
22新增: var progress=new Progress();
23新增: try{await RunCore(stream,token,available,progress);}
24新增: catch(Exception error) when(error is not OperationCanceledException)
25新增: {
26新增: var code=error switch { InvalidDataException=>"invalid_probe",UnauthorizedAccessException=>"access_denied",IOException=>"file_io",SocketException=>"socket",_=>"probe_failed" };
27新增: await Protocol.Write(stream,new JsonObject{["error"]="safety_probe_failed",["stage"]=progress.Stage,["error_code"]=code,["hresult"]=unchecked((uint)error.HResult).ToString("x8"),["native_code"]=error is SocketException socket ? socket.NativeErrorCode : 0},token);
28新增: }
29新增: }
30新增: private static async Task RunCore(Stream stream,CancellationToken token,Func<bool> available,Progress progress)
31新增: {
32新增: var input=await Protocol.Read(stream,16384,token) ?? throw new EndOfStreamException();
33新增: if(!available())throw new InvalidDataException("requires_gui_login");
34新增: var stage=input["stage"]?.GetValue<string>();
35新增: if(stage is not ("environment" or "boundary" or "network"))throw new InvalidDataException("safety_request_invalid");
36新增: progress.Stage="environment";TimeZoneInfo.ClearCachedData();
37新增: var timezone=ObservedTimezone(TimeZoneInfo.Local.Id,input["timezone"]?.GetValue<string>());
38新增: var system=new char[85];var count=GetSystemDefaultLocaleName(system,system.Length);
39新增: var result=new JsonObject{["tz"]=timezone,["system_timezone"]=timezone,["process_locale"]=CultureInfo.CurrentCulture.Name,["system_locale"]=count>0 ? new string(system,0,count-1) : "",["locale_valid"]=count>0};
40新增: if(stage=="network")
41新增: {
42新增: progress.Stage="network";
43新增: result["egress"]=await Probe("egress",token);result["dns"]=await Probe("dns",token);
44新增: }
45新增: if(stage=="boundary")
46新增: {
47新增: var port=input["control_port"]?.GetValue<int>() ?? 0;
48新增: if(port is <1 or >65535)throw new InvalidDataException("safety_request_invalid");
49新增: progress.Stage="public-tcp";result["public_connected"]=await Connect("1.1.1.1",443,AddressFamily.InterNetwork,token);
50新增: result["management_connected"]=await Connect("192.168.5.2",port,AddressFamily.InterNetwork,token);
51新增: result["ipv6_connected"]=await Connect("2606:4700:4700::1111",443,AddressFamily.InterNetworkV6,token);
52新增: result["ipv6_default_routes"]=NetworkInterface.GetAllNetworkInterfaces().Sum(n=>n.GetIPProperties().GatewayAddresses.Count(g=>g.Address.AddressFamily==AddressFamily.InterNetworkV6));
53新增: var nonce=Convert.ToHexString(RandomNumberGenerator.GetBytes(8)).ToLowerInvariant();
54新增: progress.Stage="udp";
55新增: using(var udp=new UdpClient(AddressFamily.InterNetwork))
56新增: {
57新增: await udp.SendAsync(new byte[]{1,2,3},new IPEndPoint(IPAddress.Parse("8.8.8.8"),53),token);result["udp_attempted"]=true;
58新增: }
59新增: progress.Stage="dns";result["public_dns_answered"]=await PublicDNS(nonce,token);
60新增: var id=input["project_id"]?.GetValue<string>() ?? "";var grant=input["grant"]?.GetValue<string>() ?? "";
61新增: progress.Stage="project-grant";var directory=ProjectRpc.Resolve(id,grant);
62新增: var name=input["shared_name"]?.GetValue<string>() ?? "";
63新增: var challenge=input["challenge"]?.GetValue<string>() ?? "";
64新增: if(name.Length is <1 or >255 || Path.GetFileName(name)!=name || !name.StartsWith(".cage-share-probe-",StringComparison.Ordinal) || challenge.Length!=64 || challenge.Any(c=>!char.IsAsciiHexDigit(c)))throw new InvalidDataException("safety_file_invalid");
65新增: var file=Path.Combine(directory,name);
66新增: progress.Stage="shared-read";var original=await File.ReadAllTextAsync(file,token);
67新增: result["shared_file"]=original==challenge;
68新增: progress.Stage="shared-write";if(original==challenge)await File.WriteAllTextAsync(file,challenge+":guest",token);
69新增: // Probe the host's private sibling through the confined virtual root.
70新增: // The client can select no absolute path or content to retrieve.
71新增: progress.Stage="private-scope";var privateName=input["private_name"]?.GetValue<string>() ?? "";
72新增: if(Path.GetFileName(privateName)!=privateName || !privateName.StartsWith(".cage-private-probe-",StringComparison.Ordinal))throw new InvalidDataException("safety_file_invalid");
73新增: result["private_file"]=File.Exists(Path.Combine(directory,privateName)) ? "reachable" : "unreachable";
74新增: }
75新增: if(!available())throw new InvalidDataException("requires_gui_login");
76新增: await Protocol.Write(stream,result,token);
77新增: }
78新增: internal static string ObservedTimezone(string windowsZone,string? requested)
79新增: {
80新增: // Several IANA names share one Windows zone. Keep the requested label
81新增: // only when it maps to the zone that the OS actually reports.
82新增: if(requested is { Length: >0 and <=128 } && TimeZoneInfo.TryConvertIanaIdToWindowsId(requested,out var expected) && string.Equals(expected,windowsZone,StringComparison.OrdinalIgnoreCase))return requested;
83新增: return TimeZoneInfo.TryConvertWindowsIdToIanaId(windowsZone,out var iana) ? iana! : windowsZone;
84新增: }
85新增: private static async Task<bool> Connect(string host,int port,AddressFamily family,CancellationToken token)
86新增: {
87新增: using var timeout=CancellationTokenSource.CreateLinkedTokenSource(token);timeout.CancelAfter(TimeSpan.FromSeconds(3));
88新增: using var client=new TcpClient(family);
89新增: try{await client.ConnectAsync(IPAddress.Parse(host),port,timeout.Token);return true;}catch(SocketException){return false;}catch(OperationCanceledException)when(!token.IsCancellationRequested){return false;}
90新增: }
91新增: private static async Task<JsonObject> Probe(string path,CancellationToken token)
92新增: {
93新增: using var handler=new HttpClientHandler{UseProxy=false,AllowAutoRedirect=false};using var client=new HttpClient(handler){Timeout=TimeSpan.FromSeconds(15)};
94新增: try
95新增: {
96新增: using var response=await client.GetAsync("http://198.18.0.254/"+path,HttpCompletionOption.ResponseHeadersRead,token);
97新增: using var body=await response.Content.ReadAsStreamAsync(token);using var buffer=new MemoryStream();var chunk=new byte[1024];int n;
98新增: while((n=await body.ReadAsync(chunk,token))!=0){if(buffer.Length+n>4096)throw new InvalidDataException("safety_response_limit");buffer.Write(chunk,0,n);}
99新增: var data=JsonNode.Parse(buffer.ToArray()) as JsonObject;
100新增: return new JsonObject{["status"]=(int)response.StatusCode,["ip"]=data?["ip"]?.GetValue<string>() ?? ""};
101新增: }
102新增: catch(HttpRequestException){return new JsonObject{["status"]=0,["ip"]=""};}
103新增: catch(TaskCanceledException)when(!token.IsCancellationRequested){return new JsonObject{["status"]=0,["ip"]=""};}
104新增: }
105新增: private static async Task<bool> PublicDNS(string nonce,CancellationToken token)
106新增: {
107新增: using var timeout=CancellationTokenSource.CreateLinkedTokenSource(token);timeout.CancelAfter(TimeSpan.FromSeconds(2));
108新增: using var client=new UdpClient(AddressFamily.InterNetwork);var query=new List<byte>{1,2,1,0,0,1,0,0,0,0,0,0};
109新增: foreach(var label in (nonce+".example.com").Split('.')){query.Add((byte)label.Length);query.AddRange(Protocol.Utf8.GetBytes(label));}query.AddRange(new byte[]{0,0,1,0,1});
110新增: await client.SendAsync(query.ToArray(),new IPEndPoint(IPAddress.Parse("192.168.127.1"),53),token);
111新增: try{var reply=await client.ReceiveAsync(timeout.Token);return reply.Buffer.Length>=12 && (reply.Buffer[6]!=0 || reply.Buffer[7]!=0);}
112新增: catch(SocketException){return false;}catch(OperationCanceledException)when(!token.IsCancellationRequested){return false;}
113新增: }
114新增:}
新增scripts/guest-os/guest-clipboard-windows/NetworkRuntime.cs+255 −0看文件
@@ -0,0 +1,255 @@
1新增:using System.Buffers.Binary;
2新增:using System.ComponentModel;
3新增:using System.Diagnostics;
4新增:using System.Net.Sockets;
5新增:using System.Runtime.InteropServices;
6新增:using System.Security.Cryptography;
7新增:using System.Security.Principal;
8新增:using System.Text.Json.Nodes;
9新增:
10新增:namespace Cage.GuestClipboard;
11新增:
12新增:// This SYSTEM process owns only the Cage virtual packet interface. The GUI
13新增:// clipboard, browser, files and input endpoints run in the ordinary user agent.
14新增:internal static class NetworkRuntime
15新增:{
16新增: internal static readonly Guid Service = new("f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fb");
17新增: internal const string IP = "192.168.127.2", Gateway = "192.168.127.1";
18新增: private static readonly SemaphoreSlim PacketSlot = new(1,1);
19新增: private static readonly byte[] GuestMac = [0x5a,0x94,0xef,0xe4,0x0c,0xee], GatewayMac = [0x5a,0x94,0xef,0xe4,0x0c,0xdd];
20新增: internal static async Task Run(Guid vm, string sid, string keyPath, CancellationToken token)
21新增: {
22新增: if (WindowsIdentity.GetCurrent().User?.Value != "S-1-5-18") throw new InvalidDataException("network_requires_system");
23新增: var parameters = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters");
24新增: if (!Guid.TryParse(parameters?.GetValue("VirtualMachineId")?.ToString(), out var actual) || actual != vm || !sid.StartsWith("S-1-5-21-",StringComparison.Ordinal)) throw new InvalidDataException("network_vm_invalid");
25新增: var secret = Pairing.Load(keyPath,vm,sid,false);
26新增: using var listener = HyperVEndPoint.Socket();
27新增: using var interrupt = token.Register(listener.Dispose);
28新增: listener.Bind(new HyperVEndPoint(Protocol.Parent,Service)); listener.Listen(1);
29新增: using var slots = new SemaphoreSlim(4,4);
30新增: var active = new HashSet<Task>();
31新增: try
32新增: {
33新增: while (!token.IsCancellationRequested)
34新增: {
35新增: await slots.WaitAsync(token);
36新增: Socket socket;
37新增: try { socket = await Task.Run(listener.Accept,CancellationToken.None).WaitAsync(token); }
38新增: catch { slots.Release();throw; }
39新增: lock(active)
40新增: {
41新增: Task? task = null;
42新增: task = Task.Run(async()=>{
43新增: try { await Connection(socket,vm,sid,secret,token); }
44新增: catch(Exception error) {
45新增: // Stage-free native code only: never serialize request,
46新增: // packet bytes, paths, identity secrets or exception text.
47新增: try { File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"network-error.json"),new JsonObject { ["error_type"]=error.GetType().Name,["hresult"]=error.HResult.ToString("X8"),["stage"]=(error as NetworkFailure)?.Stage ?? "handshake-or-stream",["native_code"]=(error.InnerException as Win32Exception)?.NativeErrorCode ?? (error as Win32Exception)?.NativeErrorCode ?? 0,["updated_at"]=DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString()); } catch { }
48新增: }
49新增: finally { socket.Dispose();slots.Release();lock(active)active.Remove(task!); }
50新增: },CancellationToken.None);
51新增: active.Add(task);
52新增: }
53新增: }
54新增: }
55新增: catch(OperationCanceledException)when(token.IsCancellationRequested){ }
56新增: catch(ObjectDisposedException)when(token.IsCancellationRequested){ }
57新增: finally { Task[] pending;lock(active)pending=active.ToArray();await Task.WhenAll(pending);CryptographicOperations.ZeroMemory(secret); }
58新增: }
59新增:
60新增: private static async Task Connection(Socket socket,Guid vm,string sid,byte[] secret,CancellationToken token)
61新增: {
62新增: using var connection = CancellationTokenSource.CreateLinkedTokenSource(token);
63新增: using var cancel = connection.Token.Register(socket.Dispose);
64新增: using var network = new NetworkStream(socket,false);
65新增: using var stream = new ReadAheadStream(network);
66新增: using var handshake = CancellationTokenSource.CreateLinkedTokenSource(connection.Token); handshake.CancelAfter(TimeSpan.FromSeconds(10));
67新增: var nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); var session = Guid.NewGuid().ToString("N");
68新增: await Protocol.Write(stream,new JsonObject { ["nonce"] = nonce,["vm_id"] = vm.ToString("D"),["sid"] = sid,["session"] = session,["proof"] = Protocol.Proof(secret,"server",nonce,vm,sid,session,"",null) },handshake.Token);
69新增: var request = await Protocol.Read(stream,4096,handshake.Token) ?? throw new EndOfStreamException();
70新增: var operation = request["operation"]?.GetValue<string>() ?? "";
71新增: if (operation is not ("network-stream" or "network-settings") || request["paths"] is not null || request["vm_id"]?.GetValue<string>() != vm.ToString("D") || request["sid"]?.GetValue<string>() != sid ||
72新增: !Protocol.EqualProof(Protocol.Proof(secret,"client",nonce,vm,sid,session,operation,null),request["proof"]?.GetValue<string>())) throw new InvalidDataException("pairing_invalid");
73新增: if (operation == "network-settings")
74新增: {
75新增: await Protocol.Write(stream,new JsonObject { ["version"] = 1,["session"] = session,["available"] = true },handshake.Token);
76新增: var settings = await Protocol.Read(stream,4096,handshake.Token) ?? throw new EndOfStreamException();
77新增: await WindowsSystemSettings.Apply(settings,vm,sid,connection.Token);
78新增: await Protocol.Write(stream,new JsonObject { ["ok"] = true },connection.Token); return;
79新增: }
80新增: if(!await PacketSlot.WaitAsync(0,connection.Token))throw new InvalidDataException("network_stream_already_connected");
81新增: try {
82新增: handshake.CancelAfter(TimeSpan.FromSeconds(20));
83新增: using var tun = new Wintun(vm);
84新增: // Adapter configuration is part of the bounded admission handshake.
85新增: // A stalled PowerShell operation must release this packet slot so a
86新增: // later authenticated host connection can retry.
87新增: await tun.Configure(handshake.Token);
88新增: await Protocol.Write(stream,new JsonObject { ["version"] = 1,["os"] = "windows",["vm_id"] = vm.ToString("D"),["gui_user_sid"] = sid,["session"] = session,["available"] = true,["network"] = "packet" },handshake.Token);
89新增: using var writes = new SemaphoreSlim(1,1);
90新增: async Task Send(byte[] frame)
91新增: {
92新增: await writes.WaitAsync(connection.Token);
93新增: try { var length = new byte[4]; BinaryPrimitives.WriteUInt32BigEndian(length,(uint)frame.Length); await stream.WriteAsync(length,connection.Token); await stream.WriteAsync(frame,connection.Token); await stream.FlushAsync(connection.Token); }
94新增: finally { writes.Release(); }
95新增: }
96新增: var readyPath = Path.Combine(AppContext.BaseDirectory,"network-ready.json");
97新增: var receipt = Task.Run(async () =>
98新增: {
99新增: while(!connection.IsCancellationRequested)
100新增: {
101新增: var data = new JsonObject { ["version"] = 1,["vm_id"] = vm.ToString("D"),["gui_user_sid"] = sid,["adapter"] = tun.Name,["interface_index"] = tun.Index,["session"] = session,["updated_at"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),["network"] = "packet" };
102新增: var stage = readyPath+"."+session;
103新增: await PublishReceipt(stage,readyPath,data.ToJsonString(),connection.Token);
104新增: await Task.Delay(1000,connection.Token);
105新增: }
106新增: },connection.Token);
107新增: var outgoing = Task.Run(async () =>
108新增: {
109新增: while(!connection.IsCancellationRequested)
110新增: {
111新增: var packet = tun.Receive();
112新增: if (packet is null) { await Task.Delay(5,connection.Token); continue; }
113新增: var frame = new byte[14+packet.Length]; GatewayMac.CopyTo(frame,0); GuestMac.CopyTo(frame,6);
114新增: frame[12] = packet[0]>>4 == 6 ? (byte)0x86 : (byte)0x08; frame[13] = packet[0]>>4 == 6 ? (byte)0xdd : (byte)0;
115新增: packet.CopyTo(frame,14); await Send(frame);
116新增: }
117新增: },connection.Token);
118新增: var incoming = Task.Run(async () =>
119新增: {
120新增: var header = new byte[4];
121新增: while(!connection.IsCancellationRequested)
122新增: {
123新增: await stream.ReadExactlyAsync(header,connection.Token); var size = BinaryPrimitives.ReadUInt32BigEndian(header);
124新增: if (size is < 14 or > 65549) throw new InvalidDataException("network_packet_invalid");
125新增: var frame = new byte[size]; await stream.ReadExactlyAsync(frame,connection.Token);
126新增: if (frame[12]==8 && frame[13]==6)
127新增: {
128新增: var response = Arp(frame); if (response is not null) await Send(response); continue;
129新增: }
130新增: if (!(frame[12]==8 && frame[13]==0 || frame[12]==0x86 && frame[13]==0xdd)) continue;
131新增: if (!frame.AsSpan(0,6).SequenceEqual(GuestMac) && !frame.AsSpan(0,6).SequenceEqual(new byte[]{255,255,255,255,255,255})) continue;
132新增: tun.Send(frame.AsSpan(14));
133新增: }
134新增: },connection.Token);
135新增: Task completed;
136新增: try { completed = await Task.WhenAny(incoming,outgoing,receipt); }
137新增: finally
138新增: {
139新增: connection.Cancel(); socket.Dispose();
140新增: try { await Task.WhenAll(incoming,outgoing,receipt); } catch { }
141新增: try { if (JsonNode.Parse(File.ReadAllText(readyPath))?["session"]?.GetValue<string>()==session) File.Delete(readyPath); } catch { }
142新增: try { File.Delete(readyPath+"."+session); } catch { }
143新增: }
144新增: // Retire all workers before reporting the worker that ended the stream.
145新增: // Awaiting WhenAny alone would discard its exception and leave only an
146新增: // old diagnostic from an unrelated admission failure.
147新增: if (!token.IsCancellationRequested)
148新增: {
149新增: var stage = completed == incoming ? "stream-incoming" : completed == outgoing ? "stream-outgoing" : "stream-receipt";
150新增: try { await completed; }
151新增: catch (NetworkFailure) { throw; }
152新增: catch (Exception error) { throw new NetworkFailure(stage,error); }
153新增: throw new NetworkFailure(stage,new EndOfStreamException());
154新增: }
155新增: } finally { PacketSlot.Release(); }
156新增: }
157新增:
158新增: internal static async Task PublishReceipt(string stage,string destination,string contents,CancellationToken token)
159新增: {
160新增: try { await File.WriteAllTextAsync(stage,contents,token); }
161新增: catch (Exception error) when (!token.IsCancellationRequested) { throw new NetworkFailure("receipt-write",error); }
162新增: try { await WindowsFilePublication.Replace(stage,destination,token); }
163新增: catch(Exception error) when(!token.IsCancellationRequested) { throw new NetworkFailure("receipt-replace",error); }
164新增: }
165新增:
166新增: private static byte[]? Arp(byte[] frame)
167新增: {
168新增: if (frame.Length < 42 || frame[14]!=0 || frame[15]!=1 || frame[16]!=8 || frame[17]!=0 || frame[18]!=6 || frame[19]!=4 || frame[20]!=0 || frame[21]!=1 || !frame.AsSpan(38,4).SequenceEqual(new byte[]{192,168,127,2})) return null;
169新增: var result = new byte[42]; frame.AsSpan(6,6).CopyTo(result); GuestMac.CopyTo(result,6); result[12]=8; result[13]=6;
170新增: frame.AsSpan(14,8).CopyTo(result.AsSpan(14)); result[21]=2; GuestMac.CopyTo(result,22); new byte[]{192,168,127,2}.CopyTo(result,28);
171新增: frame.AsSpan(22,10).CopyTo(result.AsSpan(32)); return result;
172新增: }
173新增:
174新增: private sealed class Wintun : IDisposable
175新增: {
176新增: [UnmanagedFunctionPointer(CallingConvention.Winapi,CharSet=CharSet.Unicode,SetLastError=true)] private delegate IntPtr Create(string name,string type,ref Guid id);
177新增: [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate void Close(IntPtr handle);
178新增: [UnmanagedFunctionPointer(CallingConvention.Winapi,SetLastError=true)] private delegate IntPtr Start(IntPtr adapter,uint capacity);
179新增: [UnmanagedFunctionPointer(CallingConvention.Winapi,SetLastError=true)] private delegate IntPtr ReceivePacket(IntPtr session,out uint size);
180新增: [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate void ReleasePacket(IntPtr session,IntPtr packet);
181新增: [UnmanagedFunctionPointer(CallingConvention.Winapi,SetLastError=true)] private delegate IntPtr AllocatePacket(IntPtr session,uint size);
182新增: [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate void Luid(IntPtr adapter,out ulong luid);
183新增: [DllImport("iphlpapi.dll")] private static extern uint ConvertInterfaceLuidToIndex(ref ulong luid,out uint index);
184新增: private readonly IntPtr library,adapter,session;
185新增: private readonly Close close,end; private readonly ReceivePacket receive; private readonly ReleasePacket release,send; private readonly AllocatePacket allocate;
186新增: internal string Name { get; }
187新增: internal uint Index { get; }
188新增: private T Load<T>(string name) where T:Delegate => Marshal.GetDelegateForFunctionPointer<T>(NativeLibrary.GetExport(library,name));
189新增: internal Wintun(Guid vm)
190新增: {
191新增: Name = "Cage-"+vm.ToString("N")[..8];
192新增: library = NativeLibrary.Load(Path.Combine(AppContext.BaseDirectory,"wintun.dll"));
193新增: close = Load<Close>("WintunCloseAdapter"); end = Load<Close>("WintunEndSession"); receive = Load<ReceivePacket>("WintunReceivePacket"); release = Load<ReleasePacket>("WintunReleaseReceivePacket"); send = Load<ReleasePacket>("WintunSendPacket"); allocate = Load<AllocatePacket>("WintunAllocateSendPacket");
194新增: try
195新增: {
196新增: adapter = Load<Create>("WintunCreateAdapter")(Name,"Cage",ref vm);
197新增: if (adapter==IntPtr.Zero) throw new Win32Exception(Marshal.GetLastPInvokeError());
198新增: Load<Luid>("WintunGetAdapterLUID")(adapter,out var luid);
199新增: if (ConvertInterfaceLuidToIndex(ref luid,out var index)!=0 || index==0) throw new InvalidDataException("network_adapter_invalid"); Index=index;
200新增: session = Load<Start>("WintunStartSession")(adapter,4<<20);
201新增: if (session==IntPtr.Zero) throw new Win32Exception(Marshal.GetLastPInvokeError());
202新增: }
203新增: catch(Exception error) { Dispose(); throw new NetworkFailure("driver",error); }
204新增: }
205新增: internal async Task Configure(CancellationToken token)
206新增: {
207新增: var script = $"$ErrorActionPreference='Stop';$stage='adapter';try{{$i={Index};$a=Get-NetAdapter -Name '{Name}';if($a.ifIndex -ne $i -or $a.Name -cne '{Name}'){{throw 'network_adapter_invalid'}};$stage='ip';New-NetIPAddress -InterfaceIndex $i -IPAddress '{IP}' -PrefixLength 24 -DefaultGateway '{Gateway}' -AddressFamily IPv4 | Out-Null;$stage='dns';Set-DnsClientServerAddress -InterfaceIndex $i -ServerAddresses '{Gateway}';$stage='interface';Set-NetIPInterface -InterfaceIndex $i -AddressFamily IPv4 -InterfaceMetric 1 -NlMtuBytes 1500";
208新增: // New-NetIPAddress returns before Windows completes duplicate
209新增: // address detection. A tentative address cannot send the probes.
210新增: // Admit this exact adapter only when its real address and route
211新增: // are usable; a timer by itself is never readiness evidence.
212新增: script += $";$stage='preferred';$until=[DateTime]::UtcNow.AddSeconds(10);$ready=$false;while([DateTime]::UtcNow -lt $until){{$ip=Get-NetIPAddress -InterfaceIndex $i -AddressFamily IPv4 -IPAddress '{IP}' -ErrorAction SilentlyContinue;if($ip.AddressState -eq 'Duplicate'){{throw 'network_address_duplicate'}};$route=Get-NetRoute -InterfaceIndex $i -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue;$dns=Get-DnsClientServerAddress -InterfaceIndex $i -AddressFamily IPv4;$ready=($ip.AddressState -eq 'Preferred' -and (Get-NetAdapter -Name '{Name}').Status -eq 'Up' -and @($route|Where-Object {{$_.NextHop -eq '{Gateway}'}}).Count -gt 0 -and $dns.ServerAddresses -contains '{Gateway}');if($ready){{break}};Start-Sleep -Milliseconds 100}};if(!$ready){{throw 'network_address_not_ready'}}}}catch{{[Console]::Out.WriteLine((@{{stage=$stage;hresult=[int]$_.Exception.HResult;category=[string]$_.CategoryInfo.Category}}|ConvertTo-Json -Compress));exit 1}}";
213新增: var info = 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 };
214新增: foreach(var argument in new[]{"-NoLogo","-NoProfile","-NonInteractive","-Command","-"}) info.ArgumentList.Add(argument);
215新增: using var process = Process.Start(info) ?? throw new InvalidDataException("network_configuration_failed");
216新增: using var cancel = token.Register(()=>{try{process.Kill(true);}catch{}});
217新增: var output = process.StandardOutput.ReadToEndAsync(token); var errors = process.StandardError.BaseStream.CopyToAsync(Stream.Null,token);
218新增: await process.StandardInput.WriteLineAsync(script); process.StandardInput.Close(); await process.WaitForExitAsync(token); await Task.WhenAll(output,errors);
219新增: if (process.ExitCode!=0)
220新增: {
221新增: var diagnostic=await output;
222新增: try
223新增: {
224新增: if(diagnostic.Length>4096)throw new InvalidDataException("network_diagnostic_invalid");
225新增: var detail=JsonNode.Parse(diagnostic) as JsonObject;
226新增: var stage=detail?["stage"]?.GetValue<string>();
227新增: if(stage is "adapter" or "ip" or "dns" or "interface" or "preferred")
228新增: {
229新增: var failure=new NetworkConfigurationFailure(detail?["hresult"]?.GetValue<int>() ?? 0);
230新增: throw new NetworkFailure("configure-"+stage,failure);
231新增: }
232新增: }
233新增: catch(NetworkFailure){throw;}
234新增: catch(Exception error) when(error is System.Text.Json.JsonException or InvalidDataException or InvalidOperationException){ }
235新增: throw new NetworkFailure("configure",new Win32Exception(process.ExitCode));
236新增: }
237新增: }
238新增: internal byte[]? Receive()
239新增: {
240新增: var pointer = receive(session,out var size);
241新增: if(pointer==IntPtr.Zero) return null;
242新增: try { if(size is <20 or >65535) throw new InvalidDataException("network_packet_invalid"); var data=new byte[size];Marshal.Copy(pointer,data,0,(int)size);return data; }
243新增: finally { release(session,pointer); }
244新增: }
245新增: internal void Send(ReadOnlySpan<byte> data)
246新增: {
247新增: if(data.Length is <20 or >65535) throw new InvalidDataException("network_packet_invalid");
248新增: var pointer=allocate(session,(uint)data.Length);if(pointer==IntPtr.Zero)return;
249新增: Marshal.Copy(data.ToArray(),0,pointer,data.Length);send(session,pointer);
250新增: }
251新增: public void Dispose() { if(session!=IntPtr.Zero)end(session);if(adapter!=IntPtr.Zero)close(adapter);NativeLibrary.Free(library); }
252新增: }
253新增: private sealed class NetworkConfigurationFailure:Exception{internal NetworkConfigurationFailure(int hresult):base("network_configuration_failed"){HResult=hresult;}}
254新增: private sealed class NetworkFailure:Exception{internal NetworkFailure(string stage,Exception error):base("network_stage_failed",error){Stage=stage;HResult=error.HResult;}internal string Stage{get;}}
255新增:}
新增scripts/guest-os/guest-clipboard-windows/Program.cs+194 −0看文件
@@ -0,0 +1,194 @@
1新增:using System.Net.Sockets;
2新增:using System.ComponentModel;
3新增:using System.Security.Cryptography;
4新增:using System.Runtime.InteropServices;
5新增:using System.Text.Json;
6新增:using System.Text.Json.Nodes;
7新增:
8新增:namespace Cage.GuestClipboard;
9新增:
10新增:internal static class GuestOperations
11新增:{
12新增: internal static readonly HashSet<string> Names = ["stream", "status", "import", "export", "terminal", "cli", "browser", "desktop", "attachments", "audio", "resources", "diagnostics", "versions", "safety", "project-mount", "network-stream", "network-settings"];
13新增: static readonly Dictionary<string, Func<Stream, CancellationToken, Func<bool>, Task>> handlers = new(StringComparer.Ordinal);
14新增: internal static void Register(string name, Func<Stream, CancellationToken, Func<bool>, Task> handler)
15新增: {
16新增: if (!Names.Contains(name) || name is "stream" or "status" or "import" or "export" || !handlers.TryAdd(name, handler))
17新增: throw new InvalidOperationException("guest_operation_registration_invalid");
18新增: }
19新增: internal static string[] Capabilities() => ["clipboard", .. handlers.Keys.Order()];
20新增: internal static Task Run(string name, Stream stream, CancellationToken token) => handlers.TryGetValue(name, out var handler)
21新增: ? handler(stream, token, SessionGuard.Available) : throw new InvalidOperationException("guest_operation_unavailable");
22新增:}
23新增:
24新增:internal static class Program
25新增:{
26新增: [DllImport("kernel32.dll")] static extern bool FreeConsole();
27新增: [STAThread]
28新增: static int Main(string[] args)
29新增: {
30新增: try
31新增: {
32新增: if (args is ["self-test"]) { SelfTest.Run(); Console.WriteLine("Windows guest protocol tests passed."); return 0; }
33新增: if (args.Length > 1 && args[0] == "--relay-profile") { Relay.Run(args).GetAwaiter().GetResult(); return 0; }
34新增: if (args is ["pair", "--vm-id", var pairVM, "--sid", var pairSID, "--token-file", var source, "--output", var destination])
35新增: { Pairing.Protect(source, destination, Guid.Parse(pairVM), pairSID); return 0; }
36新增: if (args is ["serve-network", "--vm-id", var networkVM, "--sid", var networkSID, "--token-file", var networkKey])
37新增: {
38新增: using var networkLifetime = new CancellationTokenSource();
39新增: Console.CancelKeyPress += (_, e) => { e.Cancel = true; networkLifetime.Cancel(); };
40新增: NetworkRuntime.Run(Guid.Parse(networkVM), networkSID, networkKey, networkLifetime.Token).GetAwaiter().GetResult(); return 0;
41新增: }
42新增: if (args is not ["serve", "--vm-id", var vmText, "--sid", var sid, "--token-file", var tokenFile]) throw new InvalidDataException("command_invalid");
43新增: var vm = Guid.Parse(vmText); SessionGuard.Target(vm, sid); GuestContext.VM = vm; GuestContext.SID = sid;
44新增: FreeConsole();
45新增: var secret = Pairing.Load(tokenFile, vm, sid, false);
46新增: Application.SetHighDpiMode(HighDpiMode.SystemAware);
47新增: using var lifetime = new CancellationTokenSource();
48新增: using var agent = new ClipboardAgent(Path.Combine(AppContext.BaseDirectory, "cage-guest-files.exe"));
49新增: using var listener = HyperVEndPoint.Socket();
50新增: listener.Bind(new HyperVEndPoint(Protocol.Parent, Protocol.Service)); listener.Listen(64);
51新增: GuestDiagnostics.Record("lifecycle", "started");
52新增: Application.ApplicationExit += (_, _) => { lifetime.Cancel(); listener.Dispose(); CryptographicOperations.ZeroMemory(secret); };
53新增: _ = Accept(listener, agent, vm, sid, secret, lifetime.Token);
54新增: Application.Run(); return 0;
55新增: }
56新增: catch (Exception ex)
57新增: {
58新增: if (args.Length > 0 && args[0] is "serve" or "serve-network") GuestDiagnostics.Failure("startup", ex);
59新增: var reason = ex switch
60新增: {
61新增: SocketException socketError => "socket_" + socketError.NativeErrorCode,
62新增: Win32Exception nativeError => "win32_" + nativeError.NativeErrorCode,
63新增: _ => ex.GetType().Name
64新增: };
65新增: Console.Error.WriteLine("Windows guest channel unavailable (" + Relay.Phase + ":" + reason + "); check the bound VM, GUI login, pairing and deployed tools."); return 1;
66新增: }
67新增: }
68新增: static async Task Accept(Socket listener, ClipboardAgent agent, Guid vm, string sid, byte[] secret, CancellationToken token)
69新增: {
70新增: using var slots = new SemaphoreSlim(64);
71新增: try
72新增: {
73新增: while (!token.IsCancellationRequested)
74新增: {
75新增: await slots.WaitAsync(token);
76新增: var socket = await Task.Run(listener.Accept, CancellationToken.None).WaitAsync(token);
77新增: _ = Task.Run(async () => { try { await Connection(socket, agent, vm, sid, secret, token); } finally { socket.Dispose(); slots.Release(); } }, CancellationToken.None);
78新增: }
79新增: }
80新增: catch (OperationCanceledException) { }
81新增: catch (ObjectDisposedException) { }
82新增: catch { Application.Exit(); }
83新增: }
84新增: static JsonObject Status(ClipboardAgent agent, Guid vm, string sid)
85新增: {
86新增: var status = agent.Hello(); status["vm_id"] = vm.ToString("D"); status["gui_user_sid"] = sid;
87新增: status["reason"] = SessionGuard.Available() ? "" : "requires_gui_login";
88新增: status["capabilities"] = JsonSerializer.SerializeToNode(GuestOperations.Capabilities());
89新增: status["setup_account_disabled"] = SetupAccount.Disabled();
90新增: var browser=BrowserRpc.Status();status["browser"]=browser;
91新增: status["components"]=WindowsComponentStatus.Snapshot(browser);return status;
92新增: }
93新增: static async Task Connection(Socket socket, ClipboardAgent agent, Guid vm, string sid, byte[] secret, CancellationToken lifetime)
94新增: {
95新增: using var network = new NetworkStream(socket, false);
96新增: using var stream = new ReadAheadStream(network);
97新增: using var handshake = CancellationTokenSource.CreateLinkedTokenSource(lifetime); handshake.CancelAfter(TimeSpan.FromSeconds(10));
98新增: var authenticated = false; var operation = "";
99新增: try
100新增: {
101新增: var nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
102新增: await Protocol.Write(stream, new() { ["nonce"] = nonce, ["vm_id"] = vm.ToString("D"), ["sid"] = sid, ["session"] = agent.Session,
103新增: ["proof"] = Protocol.Proof(secret, "server", nonce, vm, sid, agent.Session, "", null) }, handshake.Token);
104新增: var request = await Protocol.Read(stream, Protocol.PathLimit + 4096, handshake.Token) ?? throw new EndOfStreamException();
105新增: operation = request["operation"]?.GetValue<string>() ?? "";
106新增: if (!GuestOperations.Names.Contains(operation) || request["vm_id"]?.GetValue<string>() != vm.ToString("D") || request["sid"]?.GetValue<string>() != sid ||
107新增: !Protocol.EqualProof(Protocol.Proof(secret, "client", nonce, vm, sid, agent.Session, operation, request["paths"]), request["proof"]?.GetValue<string>()))
108新增: throw new InvalidDataException("pairing_invalid");
109新增: authenticated = true;
110新增: if (operation == "status") { await Protocol.Write(stream, Status(agent, vm, sid), lifetime); return; }
111新增: await Protocol.Write(stream, agent.Hello(), lifetime);
112新增: if (operation == "diagnostics") { await GuestOperations.Run(operation, stream, lifetime); return; }
113新增: if (operation == "stream") { await ClipboardStream(stream, agent, lifetime); return; }
114新增: SessionGuard.Assert();
115新增: using var activity = CancellationTokenSource.CreateLinkedTokenSource(lifetime);
116新增: var guard = Task.Run(async () => { try { while (true) { await Task.Delay(100, activity.Token); if (!SessionGuard.Available()) { activity.Cancel(); return; } } } catch (OperationCanceledException) { } });
117新增: try
118新增: {
119新增: if (operation == "import") await agent.Import(stream, activity.Token);
120新增: else if (operation == "export") await agent.Export(stream, request["paths"], activity.Token);
121新增: else await GuestOperations.Run(operation, stream, activity.Token);
122新增: }
123新增: finally { activity.Cancel(); await guard; }
124新增: }
125新增: catch (Exception error)
126新增: {
127新增: if (authenticated && operation != "diagnostics") GuestDiagnostics.Failure(operation, error);
128新增: // Export is framed: an early EOF is a failure. Never write an error
129新增: // JSON object into the middle of its binary frame stream.
130新增: if (authenticated && operation != "export")
131新增: try { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(1)); await Protocol.Write(stream, new() { ["error"] = SessionGuard.Available() ? "guest_operation_failed" : "requires_gui_login" }, timeout.Token); } catch { }
132新增: }
133新增: }
134新增: static async Task ClipboardStream(Stream stream, ClipboardAgent agent, CancellationToken lifetime)
135新增: {
136新增: using var channel = CancellationTokenSource.CreateLinkedTokenSource(lifetime);
137新增: var events = await agent.Subscribe();
138新增: var writer = Task.Run(async () =>
139新增: {
140新增: try { await foreach (var message in events.ReadAllAsync(channel.Token)) await Protocol.Write(stream, message, channel.Token); }
141新增: finally { channel.Cancel(); }
142新增: });
143新增: try
144新增: {
145新增: while (await Protocol.Read(stream, Protocol.WireLimit, channel.Token) is { } request)
146新增: try { await agent.Apply(request); }
147新增: catch { await agent.GUI(() => { agent.ReportError(); return true; }); }
148新增: }
149新增: finally { channel.Cancel(); await agent.Unsubscribe(); try { await writer; } catch (OperationCanceledException) { } }
150新增: }
151新增:}
152新增:
153新增:internal static class GuestContext
154新增:{
155新增: internal static Guid VM { get; set; }
156新增: internal static string SID { get; set; } = "";
157新增:}
158新增:
159新增:// Read buffering is independent from writes, which is essential for a duplex
160新增:// socket carrying JSON lines followed by binary archive frames.
161新增:internal sealed class ReadAheadStream(Stream inner) : Stream
162新增:{
163新增: readonly byte[] buffer = new byte[64 << 10]; int position, count;
164新增: internal async Task<byte[]?> Line(int limit, CancellationToken token)
165新增: {
166新增: using var line = new MemoryStream();
167新增: while (true)
168新增: {
169新增: if (position == count)
170新增: {
171新增: count = await inner.ReadAsync(buffer, token); position = 0;
172新增: if (count == 0) { if (line.Length == 0) return null; throw new EndOfStreamException(); }
173新增: }
174新增: var newline = buffer.AsSpan(position, count - position).IndexOf((byte)10);
175新增: var n = newline < 0 ? count - position : newline;
176新增: if (line.Length + n > limit) throw new InvalidDataException("message_limit");
177新增: line.Write(buffer, position, n); position += n;
178新增: if (newline >= 0) { position++; return line.ToArray(); }
179新增: }
180新增: }
181新增: public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => true;
182新增: public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
183新增: public override async ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken token = default)
184新增: {
185新增: if (destination.Length == 0) return 0;
186新增: if (position == count) { count = await inner.ReadAsync(buffer, token); position = 0; if (count == 0) return 0; }
187新增: var n = Math.Min(destination.Length, count - position); buffer.AsMemory(position, n).CopyTo(destination); position += n; return n;
188新增: }
189新增: public override int Read(byte[] bytes, int offset, int size) => ReadAsync(bytes.AsMemory(offset, size)).AsTask().GetAwaiter().GetResult();
190新增: public override ValueTask WriteAsync(ReadOnlyMemory<byte> bytes, CancellationToken token = default) => inner.WriteAsync(bytes, token);
191新增: public override void Write(byte[] bytes, int offset, int size) => inner.Write(bytes, offset, size);
192新增: public override void Flush() => inner.Flush(); public override Task FlushAsync(CancellationToken token) => inner.FlushAsync(token);
193新增: public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long length) => throw new NotSupportedException();
194新增:}
新增scripts/guest-os/guest-clipboard-windows/ProjectRpc.cs+154 −0看文件
@@ -0,0 +1,154 @@
1新增:using System.Collections.Concurrent;
2新增:using System.Diagnostics;
3新增:using System.Runtime.CompilerServices;
4新增:using System.Security.Principal;
5新增:using System.Text.Json.Nodes;
6新增:using System.Text.RegularExpressions;
7新增:using Microsoft.Win32;
8新增:
9新增:namespace Cage.GuestClipboard;
10新增:
11新增:internal static class ProjectRpc
12新增:{
13新增: private static readonly ConcurrentDictionary<string, Mount> Mounts = new(StringComparer.Ordinal);
14新增: private static readonly SemaphoreSlim Slots = new(32, 32);
15新增: internal static event Action<string, string>? Revoked;
16新增: private static readonly Regex ID = new("^[a-f0-9]{16}$", RegexOptions.CultureInvariant);
17新增: private static readonly Regex Grant = new("^[a-f0-9]{64}$", RegexOptions.CultureInvariant);
18新增: private static readonly Regex Probe = new("^\\.cage-mount-probe-[A-Za-z0-9_-]{1,100}$", RegexOptions.CultureInvariant);
19新增: [ModuleInitializer]
20新增: internal static void Register() { if (ToolsPresent()) GuestOperations.Register("project-mount", Run); }
21新增: internal static bool ToolsPresent()
22新增: {
23新增: try
24新增: {
25新增: using var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
26新增: using var key = registry.OpenSubKey(@"SOFTWARE\WinFsp");
27新增: var install = key?.GetValue("InstallDir") as string;
28新增: return install is not null && File.Exists(Path.Combine(install, "bin", "winfsp-x64.dll")) &&
29新增: File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "SSHFS-Win", "bin", "sshfs-win.exe"));
30新增: }
31新增: catch { return false; }
32新增: }
33新增: internal static string Resolve(string id, string grant)
34新增: {
35新增: if (!ID.IsMatch(id) || !Grant.IsMatch(grant) || !Mounts.TryGetValue(id, out var mount) ||
36新增: mount.Grant != grant || !mount.Ready || mount.Child.HasExited || mount.Lifetime.IsCancellationRequested)
37新增: throw new InvalidDataException("project_grant_unavailable");
38新增: return mount.Path;
39新增: }
40新增: internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available)
41新增: {
42新增: if (!available()) throw new InvalidDataException("requires_gui_login");
43新增: var value = await Protocol.Read(stream, 16384, token) ?? throw new EndOfStreamException();
44新增: var id = value["id"]?.GetValue<string>() ?? "";
45新增: var grant = value["grant"]?.GetValue<string>() ?? "";
46新增: if (!ID.IsMatch(id) || !Grant.IsMatch(grant)) throw new InvalidDataException("project_grant_invalid");
47新增: switch (value["action"]?.GetValue<string>())
48新增: {
49新增: case "mount": await Start(stream, id, grant, token, available); break;
50新增: case "probe":
51新增: if (!Mounts.TryGetValue(id, out var mount) || mount.Grant != grant || mount.Child.HasExited)
52新增: throw new InvalidDataException("project_grant_unavailable");
53新增: var name = value["probe_name"]?.GetValue<string>() ?? "";
54新增: if (!Probe.IsMatch(name)) throw new InvalidDataException("project_probe_invalid");
55新增: try
56新增: {
57新增: using var file = File.OpenRead(Path.Combine(mount.Path, name));
58新增: if (file.Length is < 1 or > 4096) throw new InvalidDataException("project_probe_invalid");
59新增: using var reader = new StreamReader(file, Protocol.Utf8);
60新增: var proof = await reader.ReadToEndAsync(token);
61新增: if (!available() || mount.Lifetime.IsCancellationRequested || mount.Child.HasExited) throw new InvalidDataException("requires_gui_login");
62新增: mount.Ready = true;
63新增: await Protocol.Write(stream, new() { ["mounted"] = true, ["id"] = id, ["path"] = mount.Path, ["proof"] = proof }, token);
64新增: }
65新增: catch (IOException) { await Protocol.Write(stream, new() { ["mounted"] = false }, token); }
66新增: break;
67新增: case "unmount":
68新增: if (!Mounts.TryGetValue(id, out var selected) || selected.Grant != grant) throw new InvalidDataException("project_grant_unavailable");
69新增: Revoke(id, selected);
70新增: selected.Lifetime.Cancel();
71新增: await selected.Done.Task.WaitAsync(token);
72新增: await Protocol.Write(stream, new() { ["unmounted"] = true }, token); break;
73新增: default: throw new InvalidDataException("project_operation_invalid");
74新增: }
75新增: }
76新增: private static async Task Start(Stream stream, string id, string grant, CancellationToken token, Func<bool> available)
77新增: {
78新增: if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("project_limit");
79新增: try { await StartCore(stream, id, grant, token, available); } finally { Slots.Release(); }
80新增: }
81新增: private static async Task StartCore(Stream stream, string id, string grant, CancellationToken token, Func<bool> available)
82新增: {
83新增: if (Mounts.TryGetValue(id, out var previous))
84新增: {
85新增: if (previous.Grant == grant) throw new InvalidDataException("project_mount_busy");
86新增: Revoke(id, previous); previous.Lifetime.Cancel();
87新增: await previous.Done.Task.WaitAsync(token);
88新增: }
89新增: var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
90新增: using var identity = WindowsIdentity.GetCurrent();
91新增: var parent = Path.Combine(home, "Cage", "Projects");
92新增: foreach (var directory in new[] { Path.Combine(home, "Cage"), parent })
93新增: {
94新增: Directory.CreateDirectory(directory);
95新增: var info = new DirectoryInfo(directory);
96新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value != identity.User?.Value)
97新增: throw new InvalidDataException("project_mount_parent_invalid");
98新增: }
99新增: var path = Path.Combine(parent, id);
100新增: // WinFsp owns mount-point creation and removal; never replace user files.
101新增: if (Path.Exists(path)) throw new InvalidDataException("project_mount_path_exists");
102新增: var executable = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "SSHFS-Win", "bin", "sshfs-win.exe");
103新增: if (!File.Exists(executable)) throw new InvalidDataException("project_tools_missing");
104新增: var start = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true };
105新增: foreach (var arg in new[] { "cmd", ":/", CygwinPath(path), "-f", "-o", "slave,uid=-1,gid=-1,cache=no,nodev,nosuid" }) start.ArgumentList.Add(arg);
106新增: using var child = new Process { StartInfo = start };
107新增: using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(token);
108新增: var mount = new Mount(grant, path, child, lifetime);
109新增: if (!Mounts.TryAdd(id, mount)) throw new InvalidDataException("project_mount_busy");
110新增: Task? input = null, output = null, stderr = null, exited = null;
111新增: try
112新增: {
113新增: if (!available() || !child.Start()) throw new InvalidDataException("requires_gui_login");
114新增: using var stop = lifetime.Token.Register(() => { try { child.Kill(true); } catch { } });
115新增: await Protocol.Write(stream, new() { ["started"] = true, ["id"] = id, ["path"] = path }, lifetime.Token);
116新增: input = stream.CopyToAsync(child.StandardInput.BaseStream, lifetime.Token);
117新增: output = child.StandardOutput.BaseStream.CopyToAsync(stream, lifetime.Token);
118新增: stderr = child.StandardError.BaseStream.CopyToAsync(Stream.Null, lifetime.Token);
119新增: exited = child.WaitForExitAsync(lifetime.Token);
120新增: await Task.WhenAny(input, output, exited);
121新增: }
122新增: finally
123新增: {
124新增: Revoke(id, mount);
125新增: lifetime.Cancel();
126新增: try { child.StandardInput.Close(); } catch { }
127新增: try { if (!child.HasExited) child.Kill(true); await child.WaitForExitAsync(); } catch { }
128新增: foreach (var task in new[] { input, output, stderr, exited }) if (task is not null) try { await task; } catch { }
129新增: mount.Done.TrySetResult();
130新增: }
131新增: }
132新增: private static void Revoke(string id, Mount mount)
133新增: {
134新增: mount.Ready = false;
135新增: if (!((ICollection<KeyValuePair<string, Mount>>)Mounts).Remove(new(id, mount))) return;
136新增: if (Revoked is { } handlers)
137新增: foreach (Action<string, string> handler in handlers.GetInvocationList())
138新增: try { handler(id, mount.Grant); } catch { /* all consumers must receive revocation */ }
139新增: }
140新增: private static string CygwinPath(string path)
141新增: {
142新增: if (path.Length < 4 || !char.IsAsciiLetter(path[0]) || path[1] != ':' || path[2] != '\\') throw new InvalidDataException("project_mount_path_invalid");
143新增: return "/cygdrive/" + char.ToLowerInvariant(path[0]) + path[2..].Replace('\\', '/');
144新增: }
145新增: private sealed class Mount(string grant, string path, Process child, CancellationTokenSource lifetime)
146新增: {
147新增: internal string Grant { get; } = grant;
148新增: internal string Path { get; } = path;
149新增: internal Process Child { get; } = child;
150新增: internal CancellationTokenSource Lifetime { get; } = lifetime;
151新增: internal readonly TaskCompletionSource Done = new(TaskCreationOptions.RunContinuationsAsynchronously);
152新增: internal volatile bool Ready;
153新增: }
154新增:}
新增scripts/guest-os/guest-clipboard-windows/Protocol.cs+137 −0看文件
@@ -0,0 +1,137 @@
1新增:using System.Buffers.Binary;
2新增:using System.Net;
3新增:using System.Net.Sockets;
4新增:using System.Security.Cryptography;
5新增:using System.Text;
6新增:using System.Text.Json;
7新增:using System.Text.Json.Nodes;
8新增:
9新增:namespace Cage.GuestClipboard;
10新增:
11新增:internal static class Protocol
12新增:{
13新增: internal static readonly Guid Service = new("f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fa");
14新增: internal static readonly Guid Parent = new("a42e7cda-d03f-480c-9cc2-a4de20abb878");
15新增: internal const int WireLimit = 30 << 20, PathLimit = 1 << 20, TextLimit = 2 << 20, PngLimit = 20 << 20;
16新增: internal static readonly UTF8Encoding Utf8 = new(false, true);
17新增: internal static JsonObject PublicHello(JsonObject hello) => new() { ["hello"] = hello };
18新增:
19新增: // Do not use StreamReader here: its read-ahead would consume archive frames
20新增: // following a JSON handshake on the same bidirectional stream.
21新增: internal static async Task<JsonObject?> Read(Stream input, int limit, CancellationToken token)
22新增: {
23新增: if (input is ReadAheadStream buffered)
24新增: {
25新增: var bytes = await buffered.Line(limit, token);
26新增: if (bytes == null) return null;
27新增: return JsonNode.Parse(Utf8.GetString(bytes)) as JsonObject ?? throw new InvalidDataException("message_invalid");
28新增: }
29新增: using var line = new MemoryStream();
30新增: var one = new byte[1];
31新增: while (true)
32新增: {
33新增: if (await input.ReadAsync(one, token) == 0)
34新增: {
35新增: if (line.Length == 0) return null;
36新增: throw new EndOfStreamException();
37新增: }
38新增: if (one[0] == 10) break;
39新增: if (line.Length >= limit) throw new InvalidDataException("message_limit");
40新增: line.WriteByte(one[0]);
41新增: }
42新增: return JsonNode.Parse(Utf8.GetString(line.GetBuffer(), 0, (int)line.Length)) as JsonObject
43新增: ?? throw new InvalidDataException("message_invalid");
44新增: }
45新增:
46新增: internal static async Task Write(Stream output, JsonObject data, CancellationToken token)
47新增: {
48新增: var bytes = Utf8.GetBytes(data.ToJsonString());
49新增: if (bytes.Length > WireLimit) throw new InvalidDataException("message_limit");
50新增: await output.WriteAsync(bytes, token);
51新增: await output.WriteAsync(new byte[] { 10 }, token);
52新增: await output.FlushAsync(token);
53新增: }
54新增:
55新增: internal static string[] Paths(JsonNode? value)
56新增: {
57新增: if (value is not JsonArray a || a.Count is < 1 or > 100) throw new InvalidDataException("selection_invalid");
58新增: var paths = a.Select(x => x?.GetValue<string>() ?? "").ToArray();
59新增: if (paths.Any(x => string.IsNullOrWhiteSpace(x) || x.Contains('\0') || !Path.IsPathFullyQualified(x)) ||
60新增: Utf8.GetByteCount(a.ToJsonString()) > PathLimit)
61新增: throw new InvalidDataException("selection_invalid");
62新增: return paths;
63新增: }
64新增:
65新增: internal static void Png(byte[] data)
66新增: {
67新增: ReadOnlySpan<byte> signature = [137, 80, 78, 71, 13, 10, 26, 10];
68新增: if (data.Length is < 33 or > PngLimit || !data.AsSpan(0, 8).SequenceEqual(signature) ||
69新增: !data.AsSpan(12, 4).SequenceEqual("IHDR"u8)) throw new InvalidDataException("image_invalid");
70新增: var w = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(16, 4));
71新增: var h = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(20, 4));
72新增: if (w == 0 || h == 0 || (ulong)w * h > 40_000_000) throw new InvalidDataException("image_limit");
73新增: }
74新增:
75新增: internal static string Proof(byte[] secret, string role, string nonce, Guid vm, string sid, string session, string operation, JsonNode? paths)
76新增: {
77新增: var content = new JsonArray(role, nonce, vm.ToString("D"), sid, session, operation, paths?.ToJsonString() ?? "").ToJsonString();
78新增: return Convert.ToBase64String(HMACSHA256.HashData(secret, Utf8.GetBytes(content)));
79新增: }
80新增:
81新增: internal static bool EqualProof(string expected, string? actual)
82新增: {
83新增: try { return CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(expected), Convert.FromBase64String(actual ?? "")); }
84新增: catch (FormatException) { return false; }
85新增: }
86新增:
87新增: // Archives use bounded frames internally. The zero frame is followed by a
88新增: // result object, so a closed connection is never mistaken for a complete tar.
89新增: internal static async Task SendFrames(Stream input, Stream output, CancellationToken token)
90新增: {
91新增: var buffer = new byte[64 << 10]; var header = new byte[4];
92新增: int n;
93新增: while ((n = await input.ReadAsync(buffer, token)) != 0)
94新增: {
95新增: BinaryPrimitives.WriteUInt32LittleEndian(header, (uint)n);
96新增: await output.WriteAsync(header, token); await output.WriteAsync(buffer.AsMemory(0, n), token);
97新增: }
98新增: Array.Clear(header); await output.WriteAsync(header, token); await output.FlushAsync(token);
99新增: }
100新增:
101新增: internal static async Task ReceiveFrames(Stream input, Stream output, CancellationToken token)
102新增: {
103新增: var buffer = new byte[64 << 10]; var header = new byte[4];
104新增: while (true)
105新增: {
106新增: await input.ReadExactlyAsync(header, token);
107新增: var n = BinaryPrimitives.ReadUInt32LittleEndian(header);
108新增: if (n == 0) break;
109新增: if (n > buffer.Length) throw new InvalidDataException("frame_invalid");
110新增: await input.ReadExactlyAsync(buffer.AsMemory(0, (int)n), token);
111新增: await output.WriteAsync(buffer.AsMemory(0, (int)n), token);
112新增: }
113新增: await output.FlushAsync(token);
114新增: }
115新增:}
116新增:
117新增:internal sealed class HyperVEndPoint(Guid vm, Guid service) : EndPoint
118新增:{
119新增: internal Guid VM { get; } = vm;
120新增: internal Guid Service { get; } = service;
121新增: public override AddressFamily AddressFamily => (AddressFamily)34;
122新增: public override SocketAddress Serialize()
123新增: {
124新增: var address = new SocketAddress(AddressFamily, 36);
125新增: var bytes = VM.ToByteArray().Concat(Service.ToByteArray()).ToArray();
126新增: for (var i = 0; i < bytes.Length; i++) address[i + 4] = bytes[i];
127新增: return address;
128新增: }
129新增: public override EndPoint Create(SocketAddress address)
130新增: {
131新增: if (address.Family != AddressFamily || address.Size != 36) throw new InvalidDataException("endpoint_invalid");
132新增: var vmBytes = new byte[16]; var serviceBytes = new byte[16];
133新增: for (var i = 0; i < 16; i++) { vmBytes[i] = address[i + 4]; serviceBytes[i] = address[i + 20]; }
134新增: return new HyperVEndPoint(new Guid(vmBytes), new Guid(serviceBytes));
135新增: }
136新增: internal static Socket Socket() => new((AddressFamily)34, SocketType.Stream, (ProtocolType)1);
137新增:}
新增scripts/guest-os/guest-clipboard-windows/Relay.cs+110 −0看文件
@@ -0,0 +1,110 @@
1新增:using System.Net.Sockets;
2新增:using System.Security.Cryptography;
3新增:using System.Text.Json;
4新增:using System.Text.Json.Nodes;
5新增:using System.Text.Json.Serialization;
6新增:
7新增:namespace Cage.GuestClipboard;
8新增:
9新增:internal sealed class WindowsProfile
10新增:{
11新增: [JsonPropertyName("version")] public int Version { get; set; }
12新增: [JsonPropertyName("vm_id")] public Guid VM { get; set; }
13新增: [JsonPropertyName("gui_user_sid")] public string SID { get; set; } = "";
14新增: [JsonPropertyName("gui_user")] public string? User { get; set; }
15新增: [JsonPropertyName("instance_directory")] public string Directory { get; set; } = "";
16新增: [JsonPropertyName("relay_executable")] public string Executable { get; set; } = "";
17新增: [JsonPropertyName("pairing_file")] public string Pairing { get; set; } = "";
18新增: [JsonPropertyName("network_pairing_file")] public string? NetworkPairing { get; set; }
19新增: internal static WindowsProfile Load(string file)
20新增: {
21新增: PairingPrivate(file);
22新增: var p = JsonSerializer.Deserialize<WindowsProfile>(File.ReadAllBytes(file), new JsonSerializerOptions { UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow }) ?? throw new InvalidDataException();
23新增: if (p.Version != 1 || p.VM == Guid.Empty || !p.SID.StartsWith("S-1-5-21-", StringComparison.Ordinal) ||
24新增: new[] { p.Directory, p.Executable, p.Pairing }.Any(path => !Path.IsPathFullyQualified(path) || path.IndexOfAny(['\0', '\r', '\n']) >= 0)) throw new InvalidDataException("profile_invalid");
25新增: if (p.NetworkPairing != null && (!Path.IsPathFullyQualified(p.NetworkPairing) || p.NetworkPairing.IndexOfAny(['\0', '\r', '\n']) >= 0)) throw new InvalidDataException("profile_invalid");
26新增: return p;
27新增: }
28新增: static void PairingPrivate(string file) => GuestClipboard.Pairing.PrivateFile(file);
29新增:}
30新增:
31新增:internal static class Relay
32新增:{
33新增: internal static string Phase { get; private set; } = "startup";
34新增: internal static async Task Run(string[] args)
35新增: {
36新增: if (args.Length is < 3 or > 4 || !GuestOperations.Names.Contains(args[2]) || args.Length == 4 && !(args[2] == "export" && args[3] == "--paths-stdin")) throw new InvalidDataException("command_invalid");
37新增: Phase = "profile"; var profile = WindowsProfile.Load(args[1]); var operation = args[2];
38新增: Phase = "pairing";
39新增: var privilegedNetwork = operation is "network-stream" or "network-settings";
40新增: var pairing = privilegedNetwork ? profile.NetworkPairing ?? throw new InvalidDataException("network_pairing_unavailable") : profile.Pairing;
41新增: var service = privilegedNetwork ? NetworkRuntime.Service : Protocol.Service;
42新增: var secret = Pairing.Load(pairing, profile.VM, profile.SID, true);
43新增: using var socket = HyperVEndPoint.Socket();
44新增: using var lifetime = new CancellationTokenSource();
45新增: Console.CancelKeyPress += (_, e) => { e.Cancel = true; lifetime.Cancel(); socket.Dispose(); };
46新增: using var connect = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); connect.CancelAfter(TimeSpan.FromSeconds(10));
47新增: try
48新增: {
49新增: Phase = "connect";
50新增: // ConnectEx used by Socket.ConnectAsync is not supported by the
51新增: // Hyper-V provider. Basic Winsock Connect supports AF_HYPERV; close
52新增: // the socket to interrupt the bounded connect when canceled.
53新增: using (connect.Token.Register(socket.Dispose))
54新增: await Task.Run(() => socket.Connect(new HyperVEndPoint(profile.VM, service)), CancellationToken.None).WaitAsync(connect.Token);
55新增: using var network = new NetworkStream(socket, false); using var stream = new ReadAheadStream(network);
56新增: Phase = "server_proof"; var challenge = await Protocol.Read(stream, 4096, connect.Token) ?? throw new EndOfStreamException();
57新增: var nonce = challenge["nonce"]?.GetValue<string>() ?? ""; var session = challenge["session"]?.GetValue<string>() ?? "";
58新增: if (challenge["vm_id"]?.GetValue<string>() != profile.VM.ToString("D") || challenge["sid"]?.GetValue<string>() != profile.SID ||
59新增: !Protocol.EqualProof(Protocol.Proof(secret, "server", nonce, profile.VM, profile.SID, session, "", null), challenge["proof"]?.GetValue<string>())) throw new InvalidDataException("pairing_invalid");
60新增: JsonNode? paths = null;
61新增: if (operation == "export")
62新增: {
63新增: using var input = new MemoryStream(); var buffer = new byte[64 << 10]; int n;
64新增: var source = Console.OpenStandardInput();
65新增: while ((n = await source.ReadAsync(buffer, lifetime.Token)) > 0)
66新增: { if (input.Length + n > Protocol.PathLimit) throw new InvalidDataException("selection_limit"); input.Write(buffer, 0, n); }
67新增: paths = JsonNode.Parse(input.ToArray()); Protocol.Paths(paths);
68新增: }
69新增: Phase = "client_proof"; await Protocol.Write(stream, new() { ["vm_id"] = profile.VM.ToString("D"), ["sid"] = profile.SID, ["operation"] = operation,
70新增: ["paths"] = paths, ["proof"] = Protocol.Proof(secret, "client", nonce, profile.VM, profile.SID, session, operation, paths) }, connect.Token);
71新增: if (operation == "network-stream") connect.CancelAfter(TimeSpan.FromSeconds(20));
72新增: Phase = "hello"; var hello = await Protocol.Read(stream, 16384, connect.Token) ?? throw new EndOfStreamException();
73新增: if (hello["error"] != null || hello["version"]?.GetValue<int>() != 1 || hello["session"]?.GetValue<string>() != session) throw new IOException("guest_unavailable");
74新增: Phase = "transfer"; if (operation == "status") { await Protocol.Write(Console.OpenStandardOutput(), hello, lifetime.Token); return; }
75新增: if (operation != "stream" && operation != "diagnostics" && hello["available"]?.GetValue<bool>() != true) throw new IOException("requires_gui_login");
76新增: if (operation == "import")
77新增: {
78新增: await Protocol.SendFrames(Console.OpenStandardInput(), stream, lifetime.Token);
79新增: var result = await Protocol.Read(stream, Protocol.PathLimit, lifetime.Token) ?? throw new EndOfStreamException();
80新增: Protocol.Paths(result["paths"]); await Protocol.Write(Console.OpenStandardOutput(), result, lifetime.Token);
81新增: }
82新增: else if (operation == "export")
83新增: {
84新增: await Protocol.ReceiveFrames(stream, Console.OpenStandardOutput(), lifetime.Token);
85新增: var result = await Protocol.Read(stream, 4096, lifetime.Token) ?? throw new EndOfStreamException();
86新增: if (result["complete"]?.GetValue<bool>() != true) throw new IOException("archive_incomplete");
87新增: }
88新增: else
89新增: {
90新增: if (operation == "stream") await Protocol.Write(Console.OpenStandardOutput(), Protocol.PublicHello(hello), lifetime.Token);
91新增: // Packet stdout stays exclusively binary. The host consumes
92新增: // this bounded receipt before it publishes network readiness.
93新增: // It follows the authenticated service's completed TUN setup.
94新增: if (operation == "network-stream")
95新增: {
96新增: if (hello["os"]?.GetValue<string>() != "windows" || hello["network"]?.GetValue<string>() != "packet" ||
97新增: hello["vm_id"]?.GetValue<string>() != profile.VM.ToString("D") || hello["gui_user_sid"]?.GetValue<string>() != profile.SID)
98新增: throw new IOException("network_identity_invalid");
99新增: await Protocol.Write(Console.OpenStandardError(), new() { ["network_ready"] = true, ["version"] = 1,
100新增: ["vm_id"] = profile.VM.ToString("D"), ["gui_user_sid"] = profile.SID,
101新增: ["session"] = session, ["network"] = "packet", ["available"] = true }, lifetime.Token);
102新增: }
103新增: var input = Task.Run(async () => { await Console.OpenStandardInput().CopyToAsync(stream, lifetime.Token); socket.Shutdown(SocketShutdown.Send); });
104新增: var output = stream.CopyToAsync(Console.OpenStandardOutput(), lifetime.Token);
105新增: await output; lifetime.Cancel(); try { await input; } catch (OperationCanceledException) { }
106新增: }
107新增: }
108新增: finally { CryptographicOperations.ZeroMemory(secret); }
109新增: }
110新增:}
新增scripts/guest-os/guest-clipboard-windows/ResourcesRpc.cs+41 −0看文件
@@ -0,0 +1,41 @@
1新增:using System.Diagnostics;
2新增:using System.Runtime.CompilerServices;
3新增:using System.Runtime.InteropServices;
4新增:using System.Text.Json.Nodes;
5新增:
6新增:namespace Cage.GuestClipboard;
7新增:
8新增:internal static class ResourcesRpc
9新增:{
10新增: [ModuleInitializer]
11新增: internal static void Register() { if (GuestOperations.Names.Contains("resources")) GuestOperations.Register("resources", Run); }
12新增: internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available)
13新增: {
14新增: if (!available()) throw new InvalidDataException("requires_gui_login");
15新增: var input = await Protocol.Read(stream, 4096, token) ?? throw new EndOfStreamException();
16新增: if (input["action"]?.GetValue<string>() != "sample") throw new InvalidDataException("resource_operation_invalid");
17新增: if (!GetSystemTimes(out var idleBefore, out var kernelBefore, out var userBefore)) throw new InvalidDataException("resource_sample_failed");
18新增: await Task.Delay(150, token);
19新增: if (!available() || !GetSystemTimes(out var idle, out var kernel, out var user)) throw new InvalidDataException("requires_gui_login");
20新增: var state = new MemoryStatus { Length = (uint)Marshal.SizeOf<MemoryStatus>() };
21新增: if (!GlobalMemoryStatusEx(ref state) || state.AvailablePhysical > state.TotalPhysical) throw new InvalidDataException("resource_sample_failed");
22新增: var total = kernel + user - kernelBefore - userBefore;
23新增: var idleDelta = idle - idleBefore;
24新增: var cpu = total == 0 ? 0 : Math.Clamp(100.0 * (total - Math.Min(total, idleDelta)) / total, 0, 100);
25新增: var now = DateTimeOffset.UtcNow;
26新增: await Protocol.Write(stream, new()
27新增: {
28新增: ["version"] = 1, ["pid"] = Environment.ProcessId, ["cpus"] = Environment.ProcessorCount,
29新增: ["updated_at"] = now.ToString("O"), ["observed_at"] = now.ToString("O"), ["cpu_percent"] = cpu,
30新增: ["guest"] = new JsonObject { ["total_bytes"] = state.TotalPhysical, ["available_bytes"] = state.AvailablePhysical },
31新增: ["unavailable_observations"] = new JsonArray("oom_kills", "memory_stall_percent", "swap_total_bytes", "swap_free_bytes", "host_pressure")
32新增: }, token);
33新增: }
34新增: [StructLayout(LayoutKind.Sequential)] private struct MemoryStatus
35新增: {
36新增: internal uint Length, Load;
37新增: internal ulong TotalPhysical, AvailablePhysical, TotalPageFile, AvailablePageFile, TotalVirtual, AvailableVirtual, AvailableExtendedVirtual;
38新增: }
39新增: [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GlobalMemoryStatusEx(ref MemoryStatus status);
40新增: [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetSystemTimes(out ulong idle, out ulong kernel, out ulong user);
41新增:}
新增scripts/guest-os/guest-clipboard-windows/Security.cs+208 −0看文件
@@ -0,0 +1,208 @@
1新增:using System.ComponentModel;
2新增:using System.Diagnostics;
3新增:using System.Runtime.InteropServices;
4新增:using System.Security.AccessControl;
5新增:using System.Security.Cryptography;
6新增:using System.Security.Principal;
7新增:using Microsoft.Win32;
8新增:
9新增:namespace Cage.GuestClipboard;
10新增:
11新增:internal static class SetupAccount
12新增:{
13新增: [StructLayout(LayoutKind.Sequential)]
14新增: private struct UserInfo20
15新增: {
16新增: public IntPtr Name, FullName, Comment;
17新增: public uint Flags, UserID;
18新增: }
19新增:
20新增: [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
21新增: private static extern uint NetUserGetInfo(string? server, string user, uint level, out IntPtr buffer);
22新增: [DllImport("netapi32.dll")]
23新增: private static extern uint NetApiBufferFree(IntPtr buffer);
24新增:
25新增: // The authenticated guest status reports only the fixed setup account's
26新增: // disable flag. A failed query stays unknown and cannot complete cleanup.
27新增: internal static bool? Disabled()
28新增: {
29新增: uint result = NetUserGetInfo(null, "cagesetup", 20, out var buffer);
30新增: try
31新增: {
32新增: if (result != 0 || buffer == IntPtr.Zero) return null;
33新增: return (Marshal.PtrToStructure<UserInfo20>(buffer).Flags & 0x2) != 0;
34新增: }
35新增: finally { if (buffer != IntPtr.Zero) NetApiBufferFree(buffer); }
36新增: }
37新增:}
38新增:
39新增:internal static class SessionGuard
40新增:{
41新增: private static readonly (int Session, SecurityIdentifier? User, bool Unprivileged) ProcessIdentity = ReadProcessIdentity();
42新增:
43新增: private static (int Session, SecurityIdentifier? User, bool Unprivileged) ReadProcessIdentity()
44新增: {
45新增: using var identity = WindowsIdentity.GetCurrent();
46新增: using var process = Process.GetCurrentProcess();
47新增: return (process.SessionId, identity.User,
48新增: !identity.IsSystem && !new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator));
49新增: }
50新增: [DllImport("user32.dll")] static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access);
51新增: [DllImport("user32.dll")] static extern bool CloseDesktop(IntPtr desktop);
52新增: [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern bool GetUserObjectInformation(IntPtr handle, int index, char[] value, int bytes, out int needed);
53新增: [DllImport("wtsapi32.dll", EntryPoint="WTSQuerySessionInformationW", ExactSpelling=true)] static extern bool WTSQuerySessionInformation(IntPtr server, int session, int field, out IntPtr buffer, out int bytes);
54新增: [DllImport("wtsapi32.dll")] static extern void WTSFreeMemory(IntPtr buffer);
55新增: [DllImport("advapi32.dll",SetLastError=true)] static extern bool OpenProcessToken(IntPtr process,uint access,out IntPtr token);
56新增: [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
57新增: [DllImport("kernel32.dll", SetLastError=true)] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
58新增: [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
59新增: [DllImport("advapi32.dll", SetLastError=true)] static extern bool GetTokenInformation(IntPtr token, int field, IntPtr buffer, int size, out int needed);
60新增: [DllImport("advapi32.dll")] static extern bool IsWellKnownSid(IntPtr sid, int kind);
61新增: [StructLayout(LayoutKind.Sequential)] private struct Group { public IntPtr Sid; public uint Flags; }
62新增:
63新增: // Query only. Constructing WindowsIdentity from a TOKEN_QUERY-only foreign
64新增: // handle requests a duplicate internally and can reject a standard user's
65新增: // own window. Never duplicate or impersonate a process token here.
66新增: private static bool InspectToken(IntPtr token, int field, Func<IntPtr, int, bool> inspect)
67新增: {
68新增: GetTokenInformation(token, field, IntPtr.Zero, 0, out int size);
69新增: if (size <= 0 || size > 65536) return false;
70新增: var buffer = Marshal.AllocHGlobal(size);
71新增: try { return GetTokenInformation(token, field, buffer, size, out var used) && used > 0 && used <= size && inspect(buffer, used); }
72新增: finally { Marshal.FreeHGlobal(buffer); }
73新增: }
74新增:
75新增: internal static bool OwnsProcess(Process process)
76新增: {
77新增: try
78新增: {
79新增: if (process.HasExited || process.SessionId != ProcessIdentity.Session) return false;
80新增: var handle = OpenProcess(0x1000, false, process.Id); // PROCESS_QUERY_LIMITED_INFORMATION
81新增: if (handle == IntPtr.Zero) return false;
82新增: try
83新增: {
84新增: if (!GetProcessTimes(handle, out var created, out _, out _, out _) ||
85新增: created != process.StartTime.ToUniversalTime().ToFileTimeUtc() || !OpenProcessToken(handle, 8, out var token)) return false;
86新增: try
87新增: {
88新增: var user = ProcessIdentity.User;
89新增: if (user == null || !InspectToken(token, 1, (p,n) => n >= IntPtr.Size &&
90新增: user.Equals(new SecurityIdentifier(Marshal.ReadIntPtr(p)))) ||
91新增: !InspectToken(token, 20, (p,n) => n == sizeof(int) && Marshal.ReadInt32(p) == 0)) return false;
92新增: return InspectToken(token, 2, (p,n) => {
93新增: var count = Marshal.ReadInt32(p);
94新增: var offset = IntPtr.Size;
95新增: var stride = Marshal.SizeOf<Group>();
96新增: if (count < 0 || count > (n-offset)/stride) return false;
97新增: for (int i=0; i<count; i++) {
98新增: var group=Marshal.PtrToStructure<Group>(p+offset+i*stride);
99新增: if ((group.Flags & 4) != 0 && (group.Flags & 16) == 0 && IsWellKnownSid(group.Sid,26)) return false;
100新增: }
101新增: return true;
102新增: });
103新增: }
104新增: finally { CloseHandle(token); }
105新增: }
106新增: finally { CloseHandle(handle); }
107新增: }
108新增: catch { return false; }
109新增: }
110新增: internal static bool Available()
111新增: {
112新增: // Process identity is fixed at startup. Session and input-desktop
113新增: // availability are still queried for each operation below.
114新增: if (!Environment.UserInteractive || ProcessIdentity.Session == 0 || !ProcessIdentity.Unprivileged) return false;
115新增: int session = ProcessIdentity.Session;
116新增: // A locked Windows 11 console can remain WTSActive and its user
117新增: // process can still see Default. Require explicit OS unlock as well.
118新增: if (!WTSQuerySessionInformation(IntPtr.Zero, session, 25, out var state, out int bytes)) return false; // WTSSessionInfoEx
119新增: try
120新增: {
121新增: // WTSINFOEXW.Data is 8-byte aligned on the win-x64 guest. Read
122新增: // only the level-1 SessionId, SessionState and SessionFlags prefix.
123新增: if (state == IntPtr.Zero || bytes < 20 || Marshal.ReadInt32(state) != 1 ||
124新增: Marshal.ReadInt32(state, 8) != session || Marshal.ReadInt32(state, 12) != 0 ||
125新增: Marshal.ReadInt32(state, 16) != 1) return false; // WTS_SESSIONSTATE_UNLOCK
126新增: }
127新增: finally { WTSFreeMemory(state); }
128新增: var desktop = OpenInputDesktop(0, false, 1);
129新增: if (desktop == IntPtr.Zero) return false;
130新增: try { var name = new char[256]; return GetUserObjectInformation(desktop, 2, name, name.Length * 2, out _) && new string(name).TrimEnd('\0') == "Default"; }
131新增: finally { CloseDesktop(desktop); }
132新增: }
133新增: internal static void Assert() { if (!Available()) throw new InvalidOperationException("requires_gui_login"); }
134新增: internal static void Target(Guid expected, string sid)
135新增: {
136新增: using var identity = WindowsIdentity.GetCurrent();
137新增: if (identity.User?.Value != sid || !sid.StartsWith("S-1-5-21-", StringComparison.Ordinal)) throw new InvalidOperationException("gui_identity_mismatch");
138新增: using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters");
139新增: if (!Guid.TryParse(key?.GetValue("VirtualMachineId") as string, out var actual) || actual != expected || actual == Guid.Empty)
140新增: throw new InvalidOperationException("guest_identity_mismatch");
141新增: Assert();
142新增: }
143新增:}
144新增:
145新增:internal static class Pairing
146新增:{
147新增: [StructLayout(LayoutKind.Sequential)] struct Blob { internal int Size; internal IntPtr Data; }
148新增: [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool CryptProtectData(ref Blob input, string? description, ref Blob entropy, IntPtr reserved, IntPtr prompt, uint flags, out Blob output);
149新增: [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool CryptUnprotectData(ref Blob input, IntPtr description, ref Blob entropy, IntPtr reserved, IntPtr prompt, uint flags, out Blob output);
150新增: [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr memory);
151新增:
152新增: internal static byte[] Crypt(byte[] data, Guid vm, string sid, bool protect)
153新增: {
154新增: var entropyBytes = SHA256.HashData(Protocol.Utf8.GetBytes("Cage.HyperV.v1:" + vm.ToString("D") + ":" + sid));
155新增: var input = new Blob { Size = data.Length, Data = Marshal.AllocHGlobal(data.Length) };
156新增: var entropy = new Blob { Size = entropyBytes.Length, Data = Marshal.AllocHGlobal(entropyBytes.Length) };
157新增: Blob output = default;
158新增: try
159新增: {
160新增: Marshal.Copy(data, 0, input.Data, data.Length); Marshal.Copy(entropyBytes, 0, entropy.Data, entropyBytes.Length);
161新增: var ok = protect ? CryptProtectData(ref input, "Cage guest pairing", ref entropy, IntPtr.Zero, IntPtr.Zero, 1, out output)
162新增: : CryptUnprotectData(ref input, IntPtr.Zero, ref entropy, IntPtr.Zero, IntPtr.Zero, 1, out output);
163新增: if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error(), "pairing_unavailable");
164新增: var result = new byte[output.Size]; Marshal.Copy(output.Data, result, 0, result.Length); return result;
165新增: }
166新增: finally { if (output.Data != IntPtr.Zero) LocalFree(output.Data); Marshal.FreeHGlobal(input.Data); Marshal.FreeHGlobal(entropy.Data); }
167新增: }
168新增:
169新增: internal static void PrivateFile(string path)
170新增: {
171新增: var file = new FileInfo(path);
172新增: if (!file.Exists || file.Length is < 1 or > 16384 || file.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("pairing_file_invalid");
173新增: using var identity = WindowsIdentity.GetCurrent();
174新增: var allowed = new HashSet<string> { identity.User!.Value, "S-1-5-18", "S-1-5-32-544" };
175新增: var acl = file.GetAccessControl();
176新增: if (!acl.AreAccessRulesProtected) throw new InvalidDataException("pairing_permissions_invalid");
177新增: foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(SecurityIdentifier)))
178新增: if (rule.AccessControlType == AccessControlType.Allow && !allowed.Contains(rule.IdentityReference.Value)) throw new InvalidDataException("pairing_permissions_invalid");
179新增: }
180新增:
181新增: internal static byte[] Load(string path, Guid vm, string sid, bool encrypted)
182新增: {
183新增: PrivateFile(path);
184新增: var bytes = File.ReadAllBytes(path);
185新增: var secret = encrypted ? Crypt(bytes, vm, sid, false) : bytes;
186新增: if (secret.Length != 32) throw new InvalidDataException("pairing_invalid");
187新增: return secret;
188新增: }
189新增:
190新增: internal static void Protect(string source, string destination, Guid vm, string sid)
191新增: {
192新增: PrivateFile(source);
193新增: var secret = File.ReadAllBytes(source); if (secret.Length != 32) throw new InvalidDataException("pairing_invalid");
194新增: try
195新增: {
196新增: var encrypted = Crypt(secret, vm, sid, true);
197新增: using var file = new FileStream(destination, FileMode.CreateNew, FileAccess.Write, FileShare.None);
198新增: var acl = new FileSecurity(); acl.SetAccessRuleProtection(true, false);
199新增: using var identity = WindowsIdentity.GetCurrent();
200新增: acl.SetOwner(identity.User!);
201新增: foreach (var owner in new[] { identity.User!.Value, "S-1-5-18", "S-1-5-32-544" })
202新增: acl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(owner), FileSystemRights.FullControl, AccessControlType.Allow));
203新增: new FileInfo(destination).SetAccessControl(acl);
204新增: file.Write(encrypted); file.Flush(true);
205新增: }
206新增: finally { CryptographicOperations.ZeroMemory(secret); }
207新增: }
208新增:}
新增scripts/guest-os/guest-clipboard-windows/SelfTest.cs+110 −0看文件
@@ -0,0 +1,110 @@
1新增:using System.Buffers.Binary;
2新增:using System.Security.Cryptography;
3新增:using System.Runtime.InteropServices;
4新增:using System.Text.Json.Nodes;
5新增:
6新增:namespace Cage.GuestClipboard;
7新增:
8新增:internal static class SelfTest
9新增:{
10新增: static void Assert(bool value) { if (!value) throw new Exception("self_test_failed"); }
11新增: static void Reject(Action action) { try { action(); } catch { return; } throw new Exception("self_test_failed"); }
12新增: internal static void Run()
13新增: {
14新增: ReceiptPublication();
15新增: var driver = Path.Combine(AppContext.BaseDirectory, "wintun.dll");
16新增: if (File.Exists(driver))
17新增: {
18新增: var library = NativeLibrary.Load(driver);
19新增: try
20新增: {
21新增: foreach (var symbol in new[] { "WintunCreateAdapter", "WintunCloseAdapter", "WintunGetAdapterLUID", "WintunStartSession", "WintunEndSession", "WintunReceivePacket", "WintunReleaseReceivePacket", "WintunAllocateSendPacket", "WintunSendPacket" })
22新增: Assert(NativeLibrary.GetExport(library, symbol) != IntPtr.Zero);
23新增: }
24新增: finally { NativeLibrary.Free(library); }
25新增: }
26新增: var vm = Guid.NewGuid(); var endpoint = new HyperVEndPoint(vm, Protocol.Service);
27新增: Assert(WindowsSystemSettings.BrowserLanguage(new JsonObject { ["locale"]="zh_CN.UTF-8",["browser_language"]="en-GB" })=="en-GB");
28新增: Reject(()=>WindowsSystemSettings.BrowserLanguage(new JsonObject { ["browser_language"]="en-US';exit" }));
29新增: Reject(()=>WindowsSystemSettings.BrowserLanguage(new JsonObject { ["locale"]="en_US.UTF-8" }));
30新增: Assert(NativeSafetyRpc.ObservedTimezone("China Standard Time","Asia/Hong_Kong")=="Asia/Hong_Kong");
31新增: Assert(NativeSafetyRpc.ObservedTimezone("China Standard Time","America/New_York")!="America/New_York");
32新增: var publicHello = Protocol.PublicHello(new JsonObject { ["version"] = 1, ["os"] = "windows", ["available"] = true });
33新增: Assert(publicHello["hello"]?["os"]?.GetValue<string>() == "windows" && !publicHello.ContainsKey("version"));
34新增: using var native = HyperVEndPoint.Socket();
35新增: var roundtrip = (HyperVEndPoint)endpoint.Create(endpoint.Serialize()); Assert(roundtrip.VM == vm && roundtrip.Service == Protocol.Service && endpoint.Serialize().Size == 36);
36新增: var secret = RandomNumberGenerator.GetBytes(32); var sid = "S-1-5-21-1-2-3-1001";
37新增: var proof = Protocol.Proof(secret, "server", "nonce", vm, sid, "session", "", null);
38新增: Assert(Protocol.EqualProof(proof, proof)); Assert(!Protocol.EqualProof(proof, "invalid"));
39新增: Assert(!Protocol.EqualProof(proof, Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "", null)));
40新增: Assert(!Protocol.EqualProof(proof, Protocol.Proof(secret, "server", "nonce", Guid.NewGuid(), sid, "session", "", null)));
41新增: Assert(!Protocol.EqualProof(proof, Protocol.Proof(secret, "server", "nonce", vm, sid + "2", "session", "", null)));
42新增: var selection = new JsonArray(@"C:\test\中文😀.txt");
43新增: var first = Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "export", selection);
44新增: Assert(!Protocol.EqualProof(first, Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "import", selection)));
45新增: Assert(!Protocol.EqualProof(first, Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "export", new JsonArray(@"C:\other.txt"))));
46新增: Reject(() => Protocol.Paths(new JsonArray())); Reject(() => Protocol.Paths(new JsonArray("relative.txt")));
47新增: Assert(Protocol.Paths(selection).Length == 1);
48新增: var image = new byte[33]; new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }.CopyTo(image, 0); "IHDR"u8.CopyTo(image.AsSpan(12));
49新增: BinaryPrimitives.WriteUInt32BigEndian(image.AsSpan(16, 4), 8000); BinaryPrimitives.WriteUInt32BigEndian(image.AsSpan(20, 4), 5000); Protocol.Png(image);
50新增: BinaryPrimitives.WriteUInt32BigEndian(image.AsSpan(20, 4), 5001); Reject(() => Protocol.Png(image));
51新增: var data = RandomNumberGenerator.GetBytes(200_000); using var encoded = new MemoryStream();
52新增: Protocol.SendFrames(new MemoryStream(data), encoded, default).GetAwaiter().GetResult();
53新增: encoded.Position = 0; using var decoded = new MemoryStream(); Protocol.ReceiveFrames(encoded, decoded, default).GetAwaiter().GetResult(); Assert(data.SequenceEqual(decoded.ToArray()));
54新增: Reject(() => Protocol.ReceiveFrames(new MemoryStream(encoded.ToArray()[..^1]), Stream.Null, default).GetAwaiter().GetResult());
55新增: Assert(AttachmentsRpc.NameValid("中文 O'Brien.txt"));
56新增: foreach (var name in new[] { "../outside.txt", "CON.txt", "file.txt:stream", "trailing.", "C:\\private.txt", "bad\nname" }) Assert(!AttachmentsRpc.NameValid(name));
57新增: using (var limited = new AttachmentsRpc.LimitedWriteStream(Stream.Null, 3))
58新增: { limited.Write([1, 2, 3], 0, 3); Reject(() => limited.Write([4], 0, 1)); }
59新增: using var json = new ReadAheadStream(new MemoryStream("{\"text\":\"中文😀\\nsecond\"}\n{\"ack\":2}\n"u8.ToArray()));
60新增: Assert(Protocol.Read(json, 1024, default).GetAwaiter().GetResult()!["text"]!.GetValue<string>() == "中文😀\nsecond");
61新增: Assert(Protocol.Read(json, 1024, default).GetAwaiter().GetResult()!["ack"]!.GetValue<int>() == 2);
62新增: using var blank=new Bitmap(240,240);
63新增: using(var paint=Graphics.FromImage(blank)){paint.Clear(Color.White);paint.FillRectangle(Brushes.Black,210,0,25,16);}
64新增: Assert(!ClaudeGraphicsCapture.HasContent(blank));
65新增: using(var paint=Graphics.FromImage(blank)){paint.FillRectangle(Brushes.Black,70,110,100,30);}
66新增: Assert(ClaudeGraphicsCapture.HasContent(blank));
67新增: var browserFrame = new JsonObject { ["jpeg"] = "page-pixels", ["target"] = "native-window", ["sequence"] = "cdp-first", ["width"] = 800, ["height"] = 600 };
68新增: var published = BrowserWindowCapture.FrameReply((JsonObject)browserFrame.DeepClone(), null);
69新增: var sequence = published["sequence"]!.GetValue<string>();
70新增: Assert(published["target"]!.GetValue<string>() == "native-window");
71新增: browserFrame["sequence"] = "cdp-next";
72新增: Assert(BrowserWindowCapture.FrameReply((JsonObject)browserFrame.DeepClone(), sequence)["unchanged"]?.GetValue<bool>() == true);
73新增: browserFrame["overlays"] = new JsonArray(new JsonObject { ["png"] = "native-menu-pixels", ["x"] = 20, ["y"] = 30, ["width"] = 50, ["height"] = 60 });
74新增: var menu = BrowserWindowCapture.FrameReply((JsonObject)browserFrame.DeepClone(), sequence);
75新增: Assert(menu["unchanged"] is null && menu["sequence"]!.GetValue<string>() != sequence);
76新增: var withoutMenu = (JsonObject)browserFrame.DeepClone(); withoutMenu.Remove("overlays");
77新增: Assert(BrowserWindowCapture.FrameReply(withoutMenu, menu["sequence"]!.GetValue<string>())["unchanged"] is null);
78新增: browserFrame["target"] = "resized-native-window";
79新增: Assert(BrowserWindowCapture.FrameReply(browserFrame, menu["sequence"]!.GetValue<string>())["unchanged"] is null);
80新增: CryptographicOperations.ZeroMemory(secret);
81新增: }
82新增:
83新增: private static void ReceiptPublication()
84新增: {
85新增: var directory=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N"));
86新增: Directory.CreateDirectory(directory);
87新增: var destination=Path.Combine(directory,"receipt.json");var stage=Path.Combine(directory,"receipt.stage");
88新增: try
89新增: {
90新增: File.WriteAllText(destination,"old-complete");
91新增: using(var snapshot=new FileStream(destination,FileMode.Open,FileAccess.Read,FileShare.Read|FileShare.Delete))
92新增: {
93新增: NetworkRuntime.PublishReceipt(stage,destination,"new-complete",default).GetAwaiter().GetResult();
94新增: using var reader=new StreamReader(snapshot);
95新增: Assert(reader.ReadToEnd()=="old-complete" && File.ReadAllText(destination)=="new-complete");
96新增: }
97新增: using(var blocker=File.OpenRead(destination))
98新增: {
99新增: var release=Task.Run(async()=>{await Task.Delay(100);blocker.Dispose();});
100新增: try { NetworkRuntime.PublishReceipt(stage,destination,"after-short-reader",default).GetAwaiter().GetResult(); }
101新增: finally { release.GetAwaiter().GetResult(); }
102新增: }
103新增: Assert(File.ReadAllText(destination)=="after-short-reader");
104新增: using(var blocker=File.OpenRead(destination))
105新增: Reject(()=>NetworkRuntime.PublishReceipt(stage,destination,"must-not-publish",default).GetAwaiter().GetResult());
106新增: Assert(File.ReadAllText(destination)=="after-short-reader");
107新增: }
108新增: finally { Directory.Delete(directory,true); }
109新增: }
110新增:}
新增scripts/guest-os/guest-clipboard-windows/TerminalRpc.cs+241 −0看文件
@@ -0,0 +1,241 @@
1新增:using System.ComponentModel;
2新增:using System.Runtime.InteropServices;
3新增:using System.Runtime.CompilerServices;
4新增:using System.Text;
5新增:using System.Text.Json.Nodes;
6新增:using Microsoft.Win32.SafeHandles;
7新增:
8新增:namespace Cage.GuestClipboard;
9新增:
10新增:// The authenticated GUI relay owns this terminal. Commands and project paths are
11新增:// never accepted from the wire; a future project grant must be resolved here.
12新增:internal static class TerminalRpc
13新增:{
14新增: internal sealed record Launch(string Executable, string[] Arguments, string Directory, Dictionary<string, string> Environment);
15新增: private static readonly SemaphoreSlim Slots = new(12, 12);
16新增: [ModuleInitializer]
17新增: internal static void Register() => GuestOperations.Register("terminal", Run);
18新增: internal static string PowerShellPath()
19新增: {
20新增: var pwsh=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"PowerShell","7","pwsh.exe");
21新增: return File.Exists(pwsh)?pwsh:Path.Combine(Environment.SystemDirectory,"WindowsPowerShell","v1.0","powershell.exe");
22新增: }
23新增: internal static Task Run(Stream stream, CancellationToken token, Func<bool> sessionAvailable) => RunCore(stream, token, sessionAvailable, null);
24新增: internal static Task RunWithLaunch(Stream stream, CancellationToken token, Func<bool> sessionAvailable, Launch launch) => RunCore(stream, token, sessionAvailable, launch);
25新增: private static async Task RunCore(Stream stream, CancellationToken token, Func<bool> sessionAvailable, Launch? launch)
26新增: {
27新增: if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login");
28新增: if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("terminal_limit");
29新增: using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(token);
30新增: using var writes = new SemaphoreSlim(1, 1);
31新增: NativeTerminal? terminal = null;
32新增: Task? output = null, inputs = null, guard = null;
33新增: Task<int>? exited = null;
34新增: Action<string, string>? revoked = null;
35新增: Action? projectAvailable = null;
36新增: async Task Send(JsonObject value)
37新增: {
38新增: await writes.WaitAsync(lifetime.Token);
39新增: try { await Protocol.Write(stream, value, lifetime.Token); } finally { writes.Release(); }
40新增: }
41新增: try
42新增: {
43新增: var open = await Protocol.Read(stream, 65536, lifetime.Token) ?? throw new EndOfStreamException();
44新增: if (open["action"]?.GetValue<string>() != "open" || open["shell"]?.GetValue<string>() != (launch is null ? "powershell" : "claude") || !sessionAvailable())
45新增: throw new InvalidDataException("terminal_request_invalid");
46新增: var directory = open["workspace"]?.GetValue<string>() switch
47新增: {
48新增: "home" => Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
49新增: "project" => ProjectRpc.Resolve(open["project_id"]?.GetValue<string>() ?? "", open["grant"]?.GetValue<string>() ?? ""),
50新增: _ => throw new InvalidDataException("terminal_request_invalid")
51新增: };
52新增: if (launch is not null && !Path.GetFullPath(launch.Directory).Equals(Path.GetFullPath(directory), StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("terminal_directory_invalid");
53新增: if (open["workspace"]?.GetValue<string>() == "project")
54新增: {
55新增: var id = open["project_id"]!.GetValue<string>(); var grant = open["grant"]!.GetValue<string>();
56新增: revoked = (removed, oldGrant) => { if (removed == id && oldGrant == grant) lifetime.Cancel(); };
57新增: ProjectRpc.Revoked += revoked;
58新增: projectAvailable = () => ProjectRpc.Resolve(id, grant);
59新增: projectAvailable();
60新增: }
61新增: terminal = new NativeTerminal(Size(open, "cols"), Size(open, "rows"), directory, launch);
62新增: await Send(new JsonObject { ["ready"] = true });
63新增: output = Task.Run(async () =>
64新增: {
65新增: var buffer = new byte[32 << 10]; int count;
66新增: // ConPTY shutdown needs a live drain even after the viewer stops.
67新增: while ((count = await terminal.Output.ReadAsync(buffer, CancellationToken.None)) != 0)
68新增: {
69新增: if (lifetime.IsCancellationRequested) continue;
70新增: try { await Send(new JsonObject { ["data"] = Convert.ToBase64String(buffer, 0, count) }); }
71新增: catch { lifetime.Cancel(); }
72新增: }
73新增: });
74新增: inputs = Task.Run(async () =>
75新增: {
76新增: while (await Protocol.Read(stream, 100 << 10, lifetime.Token) is { } value)
77新增: {
78新增: if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login");
79新增: lifetime.Token.ThrowIfCancellationRequested(); projectAvailable?.Invoke();
80新增: switch (value["action"]?.GetValue<string>())
81新增: {
82新增: case "input":
83新增: var bytes = Convert.FromBase64String(value["data"]?.GetValue<string>() ?? "");
84新增: if (bytes.Length > 64 << 10) throw new InvalidDataException("terminal_input_limit");
85新增: await terminal.Input.WriteAsync(bytes, lifetime.Token); await terminal.Input.FlushAsync(lifetime.Token); break;
86新增: case "resize": terminal.Resize(Size(value, "cols"), Size(value, "rows")); break;
87新增: case "close": return;
88新增: default: throw new InvalidDataException("terminal_request_invalid");
89新增: }
90新增: }
91新增: }, lifetime.Token);
92新增: guard = Task.Run(async () =>
93新增: {
94新增: while (!lifetime.IsCancellationRequested)
95新增: {
96新增: await Task.Delay(100, lifetime.Token);
97新增: if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login");
98新增: }
99新增: }, lifetime.Token);
100新增: exited = Task.Run(terminal.Wait);
101新增: var first = await Task.WhenAny(inputs, exited, guard, output);
102新增: if (first == exited || first == output)
103新增: {
104新增: if (first == output) { await output; terminal.KillOwnJob(); }
105新增: var code = await exited;
106新增: terminal.KillOwnJob();
107新增: terminal.CloseConsole();
108新增: await output;
109新增: await Send(new JsonObject { ["exit"] = code });
110新增: }
111新增: else await first;
112新增: }
113新增: finally
114新增: {
115新增: lifetime.Cancel(); terminal?.Stop();
116新增: if (revoked is not null) ProjectRpc.Revoked -= revoked;
117新增: foreach (var task in new Task?[] { inputs, output, guard, exited })
118新增: if (task is not null) try { await task; } catch { /* teardown observes every worker */ }
119新增: terminal?.Dispose(); Slots.Release();
120新增: }
121新增: }
122新增: private static short Size(JsonObject value, string name)
123新增: {
124新增: var size = value[name]?.GetValue<int>() ?? 0;
125新增: var maximum = name == "cols" ? 599 : 500;
126新增: if (size < 1 || size > maximum) throw new InvalidDataException("terminal_size_invalid");
127新增: return (short)size;
128新增: }
129新增:
130新增: private sealed class NativeTerminal : IDisposable
131新增: {
132新增: internal FileStream Input { get; }
133新增: internal FileStream Output { get; }
134新增: private nint console, process, job;
135新增: private readonly object gate = new();
136新增: private int disposed;
137新增: internal NativeTerminal(short cols, short rows, string directory, Launch? launch)
138新增: {
139新增: SafeFileHandle? inputRead = null, inputWrite = null, outputRead = null, outputWrite = null;
140新增: nint attributes = 0, environment = 0;
141新增: try
142新增: {
143新增: Check(CreatePipe(out inputRead, out inputWrite, 0, 0));
144新增: Check(CreatePipe(out outputRead, out outputWrite, 0, 0));
145新增: Marshal.ThrowExceptionForHR(CreatePseudoConsole(new Coord(cols, rows), inputRead, outputWrite, 0, out console));
146新增: nuint bytes = 0; InitializeProcThreadAttributeList(0, 1, 0, ref bytes);
147新增: attributes = Marshal.AllocHGlobal((nint)bytes);
148新增: Check(InitializeProcThreadAttributeList(attributes, 1, 0, ref bytes));
149新增: Check(UpdateProcThreadAttribute(attributes, 0, 0x00020016, console, (nuint)IntPtr.Size, 0, 0));
150新增: var startup = new StartupInfoEx(); startup.Startup.cb = Marshal.SizeOf<StartupInfoEx>();
151新增: startup.Startup.flags = 0x100; startup.Attributes = attributes;
152新增: var shell = PowerShellPath();
153新增: var arguments = new[] { "-NoLogo" };
154新增: if (launch is not null)
155新增: {
156新增: shell = launch.Executable; arguments = launch.Arguments;
157新增: environment = Marshal.StringToHGlobalUni(string.Join('\0', launch.Environment.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase).Select(x => x.Key + "=" + x.Value)) + "\0\0");
158新增: }
159新增: if (!File.Exists(shell)) throw new InvalidDataException("terminal_shell_missing");
160新增: job = CreateJobObject(0, null); Check(job != 0);
161新增: var limits = new JobLimits(); limits.Basic.flags = 0x2000; // KILL_ON_JOB_CLOSE
162新增: Check(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf<JobLimits>()));
163新增: Check(CreateProcess(shell, new StringBuilder(string.Join(' ', new[] { shell }.Concat(arguments).Select(QuoteArgument))), 0, 0, false,
164新增: 0x00080000 | 0x00000400 | 0x00000004, environment, directory, ref startup, out var created));
165新增: process = created.Process;
166新增: try
167新增: {
168新增: Check(AssignProcessToJobObject(job, process));
169新增: if (ResumeThread(created.Thread) == uint.MaxValue) throw new Win32Exception();
170新增: }
171新增: catch { TerminateProcess(process, 1); throw; }
172新增: finally { CloseHandle(created.Thread); }
173新增: Input = new FileStream(inputWrite, FileAccess.Write, 65536, false); inputWrite = null;
174新增: Output = new FileStream(outputRead, FileAccess.Read, 65536, false); outputRead = null;
175新增: }
176新增: catch { Dispose(); throw; }
177新增: finally
178新增: {
179新增: inputRead?.Dispose(); inputWrite?.Dispose(); outputRead?.Dispose(); outputWrite?.Dispose();
180新增: if (attributes != 0) { DeleteProcThreadAttributeList(attributes); Marshal.FreeHGlobal(attributes); }
181新增: if (environment != 0) Marshal.FreeHGlobal(environment);
182新增: }
183新增: }
184新增: internal void Resize(short cols, short rows) { lock (gate) { if (console == 0) throw new ObjectDisposedException(nameof(NativeTerminal)); Marshal.ThrowExceptionForHR(ResizePseudoConsole(console, new Coord(cols, rows))); } }
185新增: internal int Wait()
186新增: {
187新增: var handle = process;
188新增: if (handle == 0 || WaitForSingleObject(handle, uint.MaxValue) != 0 || !GetExitCodeProcess(handle, out var code)) throw new Win32Exception();
189新增: return unchecked((int)code);
190新增: }
191新增: internal void CloseConsole() { lock (gate) { if (console != 0) { ClosePseudoConsole(console); console = 0; } } }
192新增: internal void KillOwnJob() { lock (gate) { if (job != 0) { CloseHandle(job); job = 0; } } }
193新增: internal void Stop()
194新增: {
195新增: if (Interlocked.Exchange(ref disposed, 1) != 0) return;
196新增: KillOwnJob();
197新增: Input?.Dispose();
198新增: // Keep output readable until ConPTY flushes; the active output pump drains it.
199新增: CloseConsole(); Output?.Dispose();
200新增: }
201新增: public void Dispose()
202新增: {
203新增: Stop();
204新增: if (process != 0) { CloseHandle(process); process = 0; }
205新增: }
206新增: private static void Check(bool value) { if (!value) throw new Win32Exception(Marshal.GetLastWin32Error()); }
207新增: }
208新增: internal static string QuoteArgument(string value)
209新增: {
210新增: var result = new StringBuilder("\""); int slashes = 0;
211新增: foreach (var c in value)
212新增: {
213新增: if (c == '\\') { slashes++; continue; }
214新增: result.Append('\\', c == '"' ? slashes * 2 + 1 : slashes); result.Append(c); slashes = 0;
215新增: }
216新增: return result.Append('\\', slashes * 2).Append('"').ToString();
217新增: }
218新增: [StructLayout(LayoutKind.Sequential)] private readonly struct Coord(short x, short y) { internal readonly short X = x, Y = y; }
219新增: [StructLayout(LayoutKind.Sequential)] private struct StartupInfo { internal int cb; internal nint reserved, desktop, title; internal int x,y,xSize,ySize,xChars,yChars,fill,flags; internal short show,reserved2Size; internal nint reserved2,input,output,error; }
220新增: [StructLayout(LayoutKind.Sequential)] private struct StartupInfoEx { internal StartupInfo Startup; internal nint Attributes; }
221新增: [StructLayout(LayoutKind.Sequential)] private struct ProcessInfo { internal nint Process, Thread; internal uint ProcessId, ThreadId; }
222新增: [StructLayout(LayoutKind.Sequential)] private struct BasicLimits { internal long processTime,jobTime; internal uint flags; internal nuint minWorkingSet,maxWorkingSet; internal uint activeProcessLimit; internal nuint affinity; internal uint priority,scheduling; }
223新增: [StructLayout(LayoutKind.Sequential)] private struct IoCounters { internal ulong readOperations,writeOperations,otherOperations,readBytes,writeBytes,otherBytes; }
224新增: [StructLayout(LayoutKind.Sequential)] private struct JobLimits { internal BasicLimits Basic; internal IoCounters Io; internal nuint processMemory,jobMemory,peakProcessMemory,peakJobMemory; }
225新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool CreatePipe(out SafeFileHandle read,out SafeFileHandle write,nint attributes,uint size);
226新增: [DllImport("kernel32.dll")] private static extern int CreatePseudoConsole(Coord size,SafeFileHandle input,SafeFileHandle output,uint flags,out nint console);
227新增: [DllImport("kernel32.dll")] private static extern int ResizePseudoConsole(nint console,Coord size);
228新增: [DllImport("kernel32.dll")] private static extern void ClosePseudoConsole(nint console);
229新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool InitializeProcThreadAttributeList(nint list,int count,uint flags,ref nuint size);
230新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool UpdateProcThreadAttribute(nint list,uint flags,nuint attribute,nint value,nuint size,nint previous,nint returned);
231新增: [DllImport("kernel32.dll")] private static extern void DeleteProcThreadAttributeList(nint list);
232新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool CreateProcess(string app,StringBuilder command,nint processAttributes,nint threadAttributes,bool inherit,uint flags,nint environment,string directory,ref StartupInfoEx startup,out ProcessInfo process);
233新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] private static extern nint CreateJobObject(nint attributes,string? name);
234新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool SetInformationJobObject(nint job,int kind,ref JobLimits limits,uint size);
235新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool AssignProcessToJobObject(nint job,nint process);
236新增: [DllImport("kernel32.dll",SetLastError=true)] private static extern uint ResumeThread(nint thread);
237新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool TerminateProcess(nint process,uint code);
238新增: [DllImport("kernel32.dll",SetLastError=true)] private static extern uint WaitForSingleObject(nint handle,uint milliseconds);
239新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool GetExitCodeProcess(nint process,out uint code);
240新增: [DllImport("kernel32.dll")] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(nint handle);
241新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsAudioRpc.cs+294 −0看文件
@@ -0,0 +1,294 @@
1新增:using System.Buffers.Binary;
2新增:using System.Diagnostics;
3新增:using System.Runtime.CompilerServices;
4新增:using System.Runtime.InteropServices;
5新增:using System.Text.Json.Nodes;
6新增:
7新增:namespace Cage.GuestClipboard;
8新增:
9新增:// Output-only PCM for the paired GUI agent's tree and the registered Claude
10新增:// app. It never activates a microphone or system/endpoint-wide loopback.
11新增:internal static class WindowsAudioRpc
12新增:{
13新增: private static readonly SemaphoreSlim Slots = new(4, 4);
14新增: private const int SampleRate = 48000, Channels = 2, Samples = 960 * Channels;
15新增: [ModuleInitializer] internal static void Register()
16新增: {
17新增: if (GuestOperations.Names.Contains("audio") && Environment.OSVersion.Version.Build >= 20348)
18新增: GuestOperations.Register("audio", Run);
19新增: }
20新增: internal sealed class Target : IDisposable
21新增: {
22新增: internal Process Process { get; }
23新增: internal long Started { get; }
24新增: private readonly string executable;
25新增: private readonly int session;
26新增: internal Target(Process process, string path)
27新增: {
28新增: Process = process; Started = process.StartTime.ToUniversalTime().Ticks; executable = path;
29新增: using var current = System.Diagnostics.Process.GetCurrentProcess(); session = current.SessionId;
30新增: try { Validate(); } catch { Process.Dispose(); throw; }
31新增: }
32新增: internal void Validate()
33新增: {
34新增: if (!SessionGuard.Available() || !SessionGuard.OwnsProcess(Process) || Process.HasExited || Process.StartTime.ToUniversalTime().Ticks != Started ||
35新增: Process.SessionId != session ||
36新增: !string.Equals(Process.MainModule?.FileName, executable, StringComparison.OrdinalIgnoreCase))
37新增: throw new InvalidDataException("audio_target_changed");
38新增: }
39新增: public void Dispose() => Process.Dispose();
40新增: }
41新增: internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available)
42新增: {
43新增: var request = await Protocol.Read(stream, 4096, token) ?? throw new EndOfStreamException();
44新增: if (request.Count != 1 || request["action"]?.GetValue<string>() is not ("status" or "capture")) throw new InvalidDataException("audio_request_invalid");
45新增: if (!available()) throw new InvalidDataException("requires_gui_login");
46新增: if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("audio_capture_limit");
47新增: var began = false;
48新增: try
49新增: {
50新增: // A native activation can finish late. This bounded worker retains
51新增: // its slot and callback/parameters until Windows actually completes.
52新增: await Task.Factory.StartNew(() => Worker(stream, request["action"]!.GetValue<string>(), token, available, () => began = true),
53新增: CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
54新增: }
55新增: catch (Exception) when (began) { /* Close PCM without appending a JSON error as sound. */ }
56新增: finally { Slots.Release(); }
57新增: }
58新增: private static void Worker(Stream output, string action, CancellationToken token, Func<bool> available, Action began)
59新增: {
60新增: if(action=="status"){StatusDiagnostic(output,token,available);return;}
61新增: Marshal.ThrowExceptionForHR(CoInitializeEx(0, 0));
62新增: try
63新增: {
64新增: token.ThrowIfCancellationRequested(); if (!available()) throw new InvalidDataException("requires_gui_login");
65新增: var endpoints = RenderEndpoints();
66新增: using var process = Process.GetCurrentProcess();
67新增: using var owner = new Target(Process.GetProcessById(process.Id), process.MainModule!.FileName!);
68新增: var sources = new List<Source>();
69新增: try
70新增: {
71新增: sources.Add(new Source(new Target(Process.GetProcessById(owner.Process.Id), owner.Process.MainModule!.FileName!), token));
72新增: RefreshClaude(sources, owner, token);
73新增: Protocol.Write(output, new JsonObject { ["ready"] = true, ["format"] = "s16le", ["sample_rate"] = SampleRate,
74新增: ["channels"] = Channels, ["render_endpoints"] = endpoints, ["requires_render_stream"] = true }, token).GetAwaiter().GetResult();
75新增: began();
76新增: var clock = Stopwatch.StartNew(); var next = 20L; var refresh = 1000L;
77新增: var mixed = new int[Samples]; var packet = new byte[Samples * 2];
78新增: while (true)
79新增: {
80新增: token.ThrowIfCancellationRequested(); if (!available()) throw new InvalidDataException("requires_gui_login"); owner.Validate();
81新增: for (var i = sources.Count - 1; i >= 0; i--)
82新增: {
83新增: try { sources[i].Drain(); }
84新增: catch (InvalidDataException) when (i != 0) { sources[i].Dispose(); sources.RemoveAt(i); refresh = 0; }
85新增: }
86新增: if (clock.ElapsedMilliseconds >= refresh) { RefreshClaude(sources, owner, token); refresh = clock.ElapsedMilliseconds + 1000; }
87新增: var remaining = next - clock.ElapsedMilliseconds;
88新增: if (remaining > 0 && token.WaitHandle.WaitOne((int)Math.Min(remaining, 20))) token.ThrowIfCancellationRequested();
89新增: if (clock.ElapsedMilliseconds < next) continue;
90新增: Array.Clear(mixed);
91新增: foreach (var source in sources) { source.Target.Validate(); source.Mix(mixed); }
92新增: for (var i = 0; i < Samples; i++) BinaryPrimitives.WriteInt16LittleEndian(packet.AsSpan(i * 2), (short)Math.Clamp(mixed[i], short.MinValue, short.MaxValue));
93新增: owner.Validate(); output.WriteAsync(packet, token).GetAwaiter().GetResult();
94新增: next += 20; if (next < clock.ElapsedMilliseconds - 100) next = clock.ElapsedMilliseconds + 20;
95新增: }
96新增: }
97新增: finally { foreach (var source in sources) source.Dispose(); }
98新增: }
99新增: finally { CoUninitialize(); }
100新增: }
101新增: private static void StatusDiagnostic(Stream output,CancellationToken token,Func<bool> available)
102新增: {
103新增: var stage="com_initialize";bool initialized=false;
104新增: object? enumerator=null;IMMDeviceCollection? devices=null;
105新增: try
106新增: {
107新增: Marshal.ThrowExceptionForHR(CoInitializeEx(0,0));initialized=true;
108新增: token.ThrowIfCancellationRequested();if(!available())throw new InvalidDataException("requires_gui_login");
109新增: stage="render_activate";enumerator=Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"))!);
110新增: stage="render_enumerate";Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)enumerator!).EnumAudioEndpoints(0,1,out devices));
111新增: stage="render_count";Marshal.ThrowExceptionForHR(devices.GetCount(out var count));
112新增: stage="audio_service";var audio=ServiceState("Audiosrv",out var audioCode);
113新增: stage="endpoint_service";var endpoint=ServiceState("AudioEndpointBuilder",out var endpointCode);
114新增: token.ThrowIfCancellationRequested();if(!available())throw new InvalidDataException("requires_gui_login");
115新增: stage="status_emit";
116新增: Protocol.Write(output,new JsonObject { ["supported"]=Environment.OSVersion.Version.Build>=20348,["format"]="s16le",["sample_rate"]=SampleRate,["channels"]=Channels,["render_endpoints"]=checked((int)count),["audio_service"]=audio,["endpoint_service"]=endpoint,["audio_service_native_code"]=audioCode.ToString("X8"),["endpoint_service_native_code"]=endpointCode.ToString("X8"),["requires_render_stream"]=true },token).GetAwaiter().GetResult();
117新增: }
118新增: catch(Exception error) when(error is not OperationCanceledException)
119新增: {
120新增: Protocol.Write(output,new JsonObject { ["error"]="audio_status_unavailable",["stage"]=stage,["native_code"]=unchecked((uint)error.HResult).ToString("X8"),["exception_type"]=error.GetType().Name },token).GetAwaiter().GetResult();
121新增: }
122新增: finally
123新增: {
124新增: if(devices!=null)Marshal.ReleaseComObject(devices);
125新增: if(enumerator!=null)Marshal.ReleaseComObject(enumerator);
126新增: if(initialized)CoUninitialize();
127新增: }
128新增: }
129新增: internal static JsonObject ComponentStatus()
130新增: {
131新增: var supported=Environment.OSVersion.Version.Build>=20348;
132新增: if(!supported)return new JsonObject{["supported"]=false,["installed"]=false,["ready"]=false,["reason"]="audio_os_unsupported"};
133新增: using var memory=new MemoryStream();StatusDiagnostic(memory,CancellationToken.None,SessionGuard.Available);
134新增: var state=JsonNode.Parse(memory.ToArray())as JsonObject??throw new InvalidDataException("audio_status_unavailable");
135新增: var result=new JsonObject{["supported"]=true,["installed"]=true,["ready"]=false,["reason"]="audio_status_unavailable"};
136新增: foreach(var field in new[]{"stage","native_code","audio_service_native_code","endpoint_service_native_code"})
137新增: if(state[field]!=null)result[field]=state[field]!.DeepClone();
138新增: if(state["supported"]?.GetValue<bool>()==true)
139新增: {
140新增: var services=state["audio_service"]?.GetValue<string>()=="running"&&state["endpoint_service"]?.GetValue<string>()=="running";
141新增: var endpoints=(state["render_endpoints"]?.GetValue<int>()??0)>0;
142新增: result["ready"]=services&&endpoints;result["reason"]=!services?"audio_services_unavailable":!endpoints?"no_active_render_endpoint":"";
143新增: }
144新增: return result;
145新增: }
146新增: private static void RefreshClaude(List<Source> sources, Target owner, CancellationToken token)
147新增: {
148新增: var target = ClaudeWindowRpc.AudioTarget();
149新增: if (target is null) return;
150新增: try
151新增: {
152新增: if (IsDescendant(target.Process, owner.Process) || sources.Any(s => s.Target.Process.Id == target.Process.Id && s.Target.Started == target.Started)) return;
153新增: for (var i = sources.Count - 1; i > 0; i--) { sources[i].Dispose(); sources.RemoveAt(i); }
154新增: sources.Add(new Source(target, token)); target = null;
155新增: }
156新增: finally { target?.Dispose(); }
157新增: }
158新增: private static bool IsDescendant(Process child, Process ancestor)
159新增: {
160新增: var seen = new HashSet<int>(); var pid = child.Id; var started = child.StartTime.ToUniversalTime();
161新增: while (seen.Add(pid))
162新增: {
163新增: if (pid == ancestor.Id) return started == ancestor.StartTime.ToUniversalTime();
164新增: using var current = Process.GetProcessById(pid);
165新增: if (NtQueryInformationProcess(current.Handle, 0, out var basic, (uint)Marshal.SizeOf<ProcessBasic>(), out _) != 0) throw new InvalidDataException("audio_target_ancestry_unavailable");
166新增: pid = checked((int)basic.Parent.ToInt64()); if (pid < 1) return false;
167新增: try { using var parent = Process.GetProcessById(pid); if (parent.StartTime.ToUniversalTime() > started) throw new InvalidDataException("audio_target_ancestry_unavailable"); started = parent.StartTime.ToUniversalTime(); }
168新增: catch (ArgumentException) { throw new InvalidDataException("audio_target_ancestry_unavailable"); }
169新增: }
170新增: return false;
171新增: }
172新增: private sealed class Source : IDisposable
173新增: {
174新增: internal Target Target { get; }
175新增: private IAudioClient? client; private IAudioCaptureClient? capture;
176新增: private readonly EventWaitHandle ready = new(false, EventResetMode.AutoReset);
177新增: private readonly short[] ring = new short[SampleRate * Channels / 5];
178新增: private int read, count; private bool started;
179新增: internal Source(Target target, CancellationToken token)
180新增: {
181新增: Target = target;
182新增: try
183新增: {
184新增: target.Validate(); client = Activate(target.Process.Id);
185新增: token.ThrowIfCancellationRequested(); target.Validate();
186新增: var format = new WaveFormat { Tag = 1, Channels = Channels, Rate = SampleRate, Average = SampleRate * Channels * 2, Align = Channels * 2, Bits = 16, Extra = 0 };
187新增: Check(client.Initialize(0, 0x80000000u | 0x00020000u | 0x00040000u, 0, 0, ref format, 0));
188新增: Check(client.SetEventHandle(ready.SafeWaitHandle.DangerousGetHandle()));
189新增: Check(client.GetBufferSize(out var frames)); if (frames is < 1 or > SampleRate) throw new InvalidDataException("audio_buffer_invalid");
190新增: var id = typeof(IAudioCaptureClient).GUID; Check(client.GetService(ref id, out var service)); capture = (IAudioCaptureClient)service;
191新增: target.Validate(); Check(client.Start()); started = true;
192新增: }
193新增: catch { Dispose(); throw; }
194新增: }
195新增: internal void Drain()
196新增: {
197新增: Target.Validate(); ready.WaitOne(0); var batches = 0;
198新增: while (true)
199新增: {
200新增: Check(capture!.GetNextPacketSize(out var next)); if (next == 0) return;
201新增: if (++batches > 100 || next > SampleRate) throw new InvalidDataException("audio_buffer_invalid");
202新增: Check(capture.GetBuffer(out var data, out var frames, out var flags, out _, out _));
203新增: try
204新增: {
205新增: if (frames > SampleRate || (data == 0 && (flags & 2) == 0)) throw new InvalidDataException("audio_buffer_invalid");
206新增: Target.Validate(); if ((flags & 1) != 0) { read = count = 0; }
207新增: var values = new short[checked((int)frames * Channels)]; if ((flags & 2) == 0) Marshal.Copy(data, values, 0, values.Length);
208新增: Target.Validate();
209新增: foreach (var value in values) { if (count == ring.Length) { read = (read + 1) % ring.Length; count--; } ring[(read + count++) % ring.Length] = value; }
210新增: }
211新增: finally { Check(capture.ReleaseBuffer(frames)); }
212新增: }
213新增: }
214新增: internal void Mix(int[] output)
215新增: {
216新增: for (var i = 0; i < output.Length && count != 0; i++) { output[i] += ring[read]; read = (read + 1) % ring.Length; count--; }
217新增: }
218新增: public void Dispose()
219新增: {
220新增: if (started) { client?.Stop(); started = false; }
221新增: if (capture is not null) { Marshal.ReleaseComObject(capture); capture = null; }
222新增: if (client is not null) { Marshal.ReleaseComObject(client); client = null; }
223新增: ready.Dispose(); Target.Dispose();
224新增: }
225新增: }
226新增: private static IAudioClient Activate(int pid)
227新增: {
228新增: var data = Marshal.AllocHGlobal(12); IActivateOperation? operation = null;
229新增: var callback = new Completion();
230新增: try
231新增: {
232新增: Marshal.WriteInt32(data, 1); Marshal.WriteInt32(data, 4, pid); Marshal.WriteInt32(data, 8, 0); // include target tree only
233新增: var value = new Variant { Type = 65, Bytes = 12, Data = data }; var iid = typeof(IAudioClient).GUID;
234新增: Check(ActivateAudioInterfaceAsync("VAD\\Process_Loopback", ref iid, ref value, callback, out operation));
235新增: var result = callback.Done.Task.GetAwaiter().GetResult(); Check(result.Result); return result.Client ?? throw new InvalidDataException("audio_activation_failed");
236新增: }
237新增: finally { GC.KeepAlive(callback); if (operation is not null) Marshal.ReleaseComObject(operation); Marshal.FreeHGlobal(data); }
238新增: }
239新增: [ComVisible(true), ClassInterface(ClassInterfaceType.None)] private sealed class Completion : ICompletion, IAgile
240新增: {
241新增: internal readonly TaskCompletionSource<(int Result, IAudioClient? Client)> Done = new(TaskCreationOptions.RunContinuationsAsynchronously);
242新增: public int ActivateCompleted(IActivateOperation operation)
243新增: {
244新增: try { var result = operation.GetActivateResult(out var activated, out var audio); if (result >= 0) result = activated; Done.TrySetResult((result, result >= 0 ? (IAudioClient)audio : null)); }
245新增: catch (Exception e) { Done.TrySetResult((Marshal.GetHRForException(e), null)); }
246新增: return 0;
247新增: }
248新增: }
249新增: private static int RenderEndpoints()
250新增: {
251新增: object? enumerator = null; IMMDeviceCollection? devices = null;
252新增: try { enumerator = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"))!); Check(((IMMDeviceEnumerator)enumerator!).EnumAudioEndpoints(0, 1, out devices)); Check(devices.GetCount(out var count)); return checked((int)count); }
253新增: catch (COMException) { return -1; }
254新增: finally { if (devices is not null) Marshal.ReleaseComObject(devices); if (enumerator is not null) Marshal.ReleaseComObject(enumerator); }
255新增: }
256新增: private static string ServiceState(string name,out uint code)
257新增: {
258新增: code=0;var manager = OpenSCManagerW(null, null, 1); if (manager == 0) { code=Win32Code();return "unknown"; }
259新增: try { var service = OpenServiceW(manager, name, 4); if (service == 0) { code=Win32Code();return "unknown"; } try { if(!QueryServiceStatusEx(service, 0, out var state, (uint)Marshal.SizeOf<ServiceStatus>(), out _)){code=Win32Code();return "unknown";}return state.Current==4?"running":"stopped"; } finally { CloseServiceHandle(service); } }
260新增: finally { CloseServiceHandle(manager); }
261新增: }
262新增: private static uint Win32Code() {var error=unchecked((uint)Marshal.GetLastWin32Error());return error==0?0x80004005:error|0x80070000;}
263新增: private static void Check(int hr) { if (hr < 0) throw new InvalidDataException("audio_native_" + unchecked((uint)hr).ToString("x8")); }
264新增: [StructLayout(LayoutKind.Sequential, Pack = 2)] private struct WaveFormat { public ushort Tag, Channels; public uint Rate, Average; public ushort Align, Bits, Extra; }
265新增: [StructLayout(LayoutKind.Explicit, Size = 24)] private struct Variant { [FieldOffset(0)] public ushort Type; [FieldOffset(8)] public uint Bytes; [FieldOffset(16)] public nint Data; }
266新增: [StructLayout(LayoutKind.Sequential)] private struct ProcessBasic { public nint Exit, Peb, Affinity, Priority, ID, Parent; }
267新增: [StructLayout(LayoutKind.Sequential)] private struct ServiceStatus { public uint Type, Current, Controls, Exit, ServiceExit, Checkpoint, Hint, PID, Flags; }
268新增: [ComImport, Guid("1CB9AD4C-DBFA-4C32-B178-C2F568A703B2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAudioClient
269新增: {
270新增: [PreserveSig] int Initialize(int mode, uint flags, long duration, long period, ref WaveFormat format, nint session);
271新增: [PreserveSig] int GetBufferSize(out uint frames); [PreserveSig] int GetStreamLatency(out long latency); [PreserveSig] int GetCurrentPadding(out uint padding);
272新增: [PreserveSig] int IsFormatSupported(int mode, nint format, out nint closest); [PreserveSig] int GetMixFormat(out nint format); [PreserveSig] int GetDevicePeriod(out long normal, out long minimum);
273新增: [PreserveSig] int Start(); [PreserveSig] int Stop(); [PreserveSig] int Reset(); [PreserveSig] int SetEventHandle(nint handle);
274新增: [PreserveSig] int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object service);
275新增: }
276新增: [ComImport, Guid("C8ADBD64-E71E-48A0-A4DE-185C395CD317"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAudioCaptureClient
277新增: { [PreserveSig] int GetBuffer(out nint data, out uint frames, out uint flags, out ulong device, out ulong clock); [PreserveSig] int ReleaseBuffer(uint frames); [PreserveSig] int GetNextPacketSize(out uint frames); }
278新增: [ComImport, Guid("72A22D78-CDE4-431D-B8CC-843A71199B6D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IActivateOperation
279新增: { [PreserveSig] int GetActivateResult(out int result, [MarshalAs(UnmanagedType.IUnknown)] out object audio); }
280新增: [ComVisible(true), Guid("41D949AB-9862-444A-80F6-C261334DA5EB"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface ICompletion
281新增: { [PreserveSig] int ActivateCompleted(IActivateOperation operation); }
282新增: [ComVisible(true), Guid("94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAgile { }
283新增: [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IMMDeviceEnumerator
284新增: { [PreserveSig] int EnumAudioEndpoints(int flow, uint state, out IMMDeviceCollection devices); }
285新增: [ComImport, Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IMMDeviceCollection
286新增: { [PreserveSig] int GetCount(out uint count); }
287新增: [DllImport("mmdevapi.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern int ActivateAudioInterfaceAsync(string device, ref Guid iid, ref Variant parameters, ICompletion callback, out IActivateOperation operation);
288新增: [DllImport("ole32.dll")] private static extern int CoInitializeEx(nint reserved, uint mode); [DllImport("ole32.dll")] private static extern void CoUninitialize();
289新增: [DllImport("ntdll.dll")] private static extern int NtQueryInformationProcess(nint process, int kind, out ProcessBasic basic, uint bytes, out uint returned);
290新增: [DllImport("advapi32.dll", ExactSpelling=true,CharSet = CharSet.Unicode,SetLastError=true)] private static extern nint OpenSCManagerW(string? machine, string? database, uint rights);
291新增: [DllImport("advapi32.dll", ExactSpelling=true,CharSet = CharSet.Unicode,SetLastError=true)] private static extern nint OpenServiceW(nint manager, string name, uint rights);
292新增: [DllImport("advapi32.dll", ExactSpelling=true,SetLastError=true)] private static extern bool QueryServiceStatusEx(nint service, int level, out ServiceStatus state, uint bytes, out uint needed);
293新增: [DllImport("advapi32.dll")] private static extern bool CloseServiceHandle(nint handle);
294新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsCliRpc.cs+300 −0看文件
@@ -0,0 +1,300 @@
1新增:using System.Reflection;
2新增:using System.Runtime.CompilerServices;
3新增:using System.Security.AccessControl;
4新增:using System.Security.Cryptography;
5新增:using System.Security.Principal;
6新增:using System.Text;
7新增:using System.Text.Json.Nodes;
8新增:using System.Text.RegularExpressions;
9新增:using System.Diagnostics;
10新增:
11新增:namespace Cage.GuestClipboard;
12新增:
13新增:internal static class WindowsCliRpc
14新增:{
15新增: private static readonly Regex ProfileID = new("^[a-f0-9]{16}$",RegexOptions.CultureInvariant);
16新增: private static readonly Regex AccountID = new("^(default|[a-f0-9]{24})$",RegexOptions.CultureInvariant);
17新增: private static readonly Regex Subject = new("^[a-f0-9]{64}$",RegexOptions.CultureInvariant);
18新增: private static readonly Regex CCSProfile = new("^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$",RegexOptions.CultureInvariant);
19新增: private static readonly HashSet<string> Modes=["discover","view","rpc","active","handoff","purge","account-switch","account-switch-cancel"];
20新增: private static readonly object Gate=new();
21新增: private static readonly Dictionary<string,int> Active=new(StringComparer.OrdinalIgnoreCase);
22新增: [ModuleInitializer] internal static void Register()
23新增: {
24新增: if(!GuestOperations.Names.Contains("cli"))return;
25新增: try{LoadTools();}catch(Exception){return;}
26新增: GuestOperations.Register("cli",Run);
27新增: }
28新增: private sealed record Tools(string Python,string Claude,string Bash);
29新增: private sealed record Layout(string Profile,string Root,string Accounts,string State,string Shared,string Code,Tools Tools);
30新增: internal static async Task Run(Stream stream,CancellationToken token,Func<bool> available)
31新增: {
32新增: if(!available())throw new InvalidDataException("requires_gui_login");
33新增: var request=await Protocol.Read(stream,4<<20,token)??throw new EndOfStreamException();
34新增: var profile=request["profile"]?.GetValue<string>()??"";
35新增: if(!ProfileID.IsMatch(profile))throw new InvalidDataException("cli_profile_invalid");
36新增: var layout=Prepare(profile);
37新增: var action=request["action"]?.GetValue<string>()??"";
38新增: if(action=="terminal")
39新增: {
40新增: var kind=request["kind"]?.GetValue<string>()??"";
41新增: if(kind is not ("claude" or "claude-login"))throw new InvalidDataException("cli_kind_invalid");
42新增: var account=request["account"]?.GetValue<string>()??"default";
43新增: if(!AccountID.IsMatch(account)||kind=="claude-login"&&account=="default")throw new InvalidDataException("cli_account_invalid");
44新增: var directory=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
45新增: var open=new JsonObject{["action"]="open",["cols"]=request["cols"]?.DeepClone()??100,["rows"]=request["rows"]?.DeepClone()??30,["workspace"]="home",["shell"]="claude"};
46新增: var arguments=new List<string>{"-X","utf8","-I"};
47新增: var env=EnvironmentFor(layout,account);
48新增: using var lease=AccountLease(layout,account);
49新增: if(kind=="claude-login")arguments.AddRange([Path.Combine(layout.Code,"cage-claude-account.py"),"login",account]);
50新增: else
51新增: {
52新增: var id=request["project_id"]?.GetValue<string>()??"";var grant=request["grant"]?.GetValue<string>()??"";
53新增: directory=ProjectRpc.Resolve(id,grant);open["workspace"]="project";open["project_id"]=id;open["grant"]=grant;
54新增: var payload=request["conversation"]?.DeepClone() as JsonObject??throw new InvalidDataException("cli_conversation_invalid");
55新增: Guid.Parse(payload["id"]?.GetValue<string>()??"");Guid.Parse(payload["session_id"]?.GetValue<string>()??"");
56新增: ValidatePaths(layout,payload);
57新增: var subject=request["subject"]?.GetValue<string>()??"";
58新增: if(subject!=""&&!Subject.IsMatch(subject))throw new InvalidDataException("cli_identity_invalid");
59新增: payload["account"]=account;payload["subject"]=subject;payload["prefix"]=new JsonArray(layout.Tools.Claude);
60新增: if(request["ccs_profile"] is JsonValue c&&c.TryGetValue<string>(out var ccs)&&ccs!="")
61新增: {
62新增: if(!CCSProfile.IsMatch(ccs)||account!="default"||subject!="")throw new InvalidDataException("ccs_profile_invalid");
63新增: var tools=LoadCCSTools();env["CAGE_CCS_NODE"]=tools.Node;env["CAGE_CCS_MAIN"]=tools.Main;
64新增: env["CAGE_CCS_PRELOAD"]=Path.Combine(layout.Code,"windows_ccs_launch.cjs");
65新增: env["CCS_CLAUDE_PATH"]=layout.Tools.Claude;
66新增: env["CCS_DIR"]=Path.Combine(layout.Root,"ccs");env["CCS_HOME"]=Path.Combine(layout.Root,"ccs-home");
67新增: PrivateDirectory(env["CCS_DIR"]);PrivateDirectory(env["CCS_HOME"]);payload["ccs_profile"]=ccs;
68新增: }
69新增: arguments.AddRange([Path.Combine(layout.Code,"cli_channel.py"),"launch",payload.ToJsonString()]);
70新增: }
71新增: if(!available())throw new InvalidDataException("requires_gui_login");
72新增: using var prefixed=new PrefixStream(stream,Protocol.Utf8.GetBytes(open.ToJsonString()+"\n"));
73新增: await TerminalRpc.RunWithLaunch(prefixed,token,available,new(layout.Tools.Python,arguments.ToArray(),directory,env));
74新增: return;
75新增: }
76新增: string script;string[] args;JsonNode? input=null;var selected="default";
77新增: if(action=="account")
78新增: {
79新增: var mode=request["mode"]?.GetValue<string>()??"";
80新增: if(mode is not ("snapshot" or "usage" or "quotas"))throw new InvalidDataException("cli_account_operation_invalid");
81新增: selected=request["account"]?.GetValue<string>()??"default";
82新增: if(!AccountID.IsMatch(selected))throw new InvalidDataException("cli_account_invalid");
83新增: args=[mode,selected];
84新增: if(mode=="usage"){var subject=request["subject"]?.GetValue<string>()??"";if(!Subject.IsMatch(subject))throw new InvalidDataException("cli_identity_invalid");args=[mode,selected,subject];}
85新增: if(mode=="quotas")
86新增: {
87新增: var ids=request["ids"] as JsonArray??throw new InvalidDataException("cli_account_invalid");
88新增: if(ids.Count is <1 or >100||ids.Any(x=>!AccountID.IsMatch(x?.GetValue<string>()??"")))throw new InvalidDataException("cli_account_invalid");
89新增: args=[mode,..ids.Select(x=>x!.GetValue<string>())];
90新增: }
91新增: script=Path.Combine(layout.Code,"cage-claude-account.py");
92新增: }
93新增: else if(action=="channel")
94新增: {
95新增: var mode=request["mode"]?.GetValue<string>()??"";if(!Modes.Contains(mode))throw new InvalidDataException("cli_channel_operation_invalid");
96新增: input=request["input"]?.DeepClone()??throw new InvalidDataException("cli_channel_input_invalid");
97新增: ValidatePaths(layout,input as JsonObject??throw new InvalidDataException("cli_channel_input_invalid"));
98新增: if(input["config"] is JsonValue c&&c.TryGetValue<string>(out var config)&&config!="")
99新增: {
100新增: var relative=Path.GetRelativePath(layout.Accounts,Path.GetFullPath(config)).Split(Path.DirectorySeparatorChar);
101新增: if(relative.Length==2&&AccountID.IsMatch(relative[0])&&relative[0]!="default"&&relative[1]=="config")selected=relative[0];
102新增: }
103新增: script=Path.Combine(layout.Code,"cli_channel.py");args=[mode,"-"];
104新增: }
105新增: else throw new InvalidDataException("cli_operation_invalid");
106新增: using var accountLease=AccountLease(layout,selected);
107新增: var result=await Invoke(layout,selected,script,args,input,token,available);
108新增: await Protocol.Write(stream,result,token);
109新增: }
110新增: private static Layout Prepare(string profile)
111新增: {
112新增: var tools=LoadTools();
113新增: var root=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),"Cage","CLI",profile);
114新增: var accounts=Path.Combine(root,"accounts");var state=Path.Combine(root,"channels");var shared=Path.Combine(root,"shared");
115新增: foreach(var path in new[]{root,accounts,state,shared})PrivateDirectory(path);
116新增: string Read(string resource){using var input=Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)??throw new InvalidDataException("cli_helper_missing");using var reader=new StreamReader(input,Protocol.Utf8);return reader.ReadToEnd();}
117新增: var files=new Dictionary<string,string>{{"cli_channel.py",Read("Cage.CliChannel")},{"cage-claude-account.py",Read("Cage.CliAccount")},{"windows_cli_platform.py",Read("Cage.CliPlatform")},{"windows_ccs_launch.cjs",Read("Cage.CliCCS")},{"mobile_cli_identity.py",Read("Cage.CliIdentity")},{"cli_channel.resume.md",Read("Cage.CliResume")},{"cli_channel.account-resume.md",Read("Cage.CliAccountResume")}};
118新增: var digest=Convert.ToHexString(SHA256.HashData(Protocol.Utf8.GetBytes(string.Join("\n",files.Values)))).ToLowerInvariant();
119新增: var code=Path.Combine(root,"code",digest);PrivateDirectory(code);
120新增: foreach(var file in files){var path=Path.Combine(code,file.Key);if(!File.Exists(path))File.WriteAllText(path,file.Value,Protocol.Utf8);else if(File.ReadAllText(path,Protocol.Utf8)!=file.Value)throw new InvalidDataException("cli_helper_changed");}
121新增: return new(profile,root,accounts,state,shared,code,tools);
122新增: }
123新增: private static readonly Dictionary<string,(long Size,DateTime Written,string Hash)> ToolHashes=new(StringComparer.OrdinalIgnoreCase);
124新增: private static Tools LoadTools()
125新增: {
126新增: var toolsFile=Path.Combine(AppContext.BaseDirectory,"cli-tools.json");Pairing.PrivateFile(toolsFile);
127新增: var tool=JsonNode.Parse(File.ReadAllBytes(toolsFile))as JsonObject??throw new InvalidDataException("cli_tools_invalid");
128新增: return new Tools(CheckTool(tool,"python"),CheckTool(tool,"claude"),CheckTool(tool,"git_bash"));
129新增: }
130新增: // Read only fixed tool receipts, without account preparation or execution.
131新增: internal static JsonObject ComponentStatus()
132新增: {
133新增: var dependencies=new JsonObject{["python"]=false,["claude"]=false,["git_bash"]=false};
134新增: try
135新增: {
136新增: var receipt=Path.Combine(AppContext.BaseDirectory,"cli-tools.json");Pairing.PrivateFile(receipt);
137新增: var info=new FileInfo(receipt);if(info.Length is <1 or >16384)throw new InvalidDataException("cli_tools_invalid");
138新增: var tools=JsonNode.Parse(File.ReadAllBytes(receipt))as JsonObject??throw new InvalidDataException("cli_tools_invalid");
139新增: foreach(var name in new[]{"python","claude","git_bash"})
140新增: try{CheckTool(tools,name);dependencies[name]=true;}catch{ }
141新增: }
142新增: catch{ }
143新增: var installed=dependencies.All(pair=>pair.Value!.GetValue<bool>());
144新增: return new JsonObject{["installed"]=installed,["ready"]=installed,["reason"]=installed?"":"cli_tools_missing_or_invalid",["dependencies"]=dependencies};
145新增: }
146新增: private static string CheckTool(JsonObject tool,string name)
147新增: {
148新增: var path=tool[name]?.GetValue<string>()??"";var hash=tool[name+"_sha256"]?.GetValue<string>()??"";
149新增: if(!Path.IsPathFullyQualified(path)||!Subject.IsMatch(hash)||!File.Exists(path)||new FileInfo(path).Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_tools_unverified");
150新增: var info=new FileInfo(path);
151新增: lock(Gate)
152新增: {
153新增: if(!ToolHashes.TryGetValue(path,out var known)||known.Size!=info.Length||known.Written!=info.LastWriteTimeUtc||known.Hash!=hash)
154新增: {
155新增: using var file=File.OpenRead(path);
156新增: if(Convert.ToHexString(SHA256.HashData(file)).ToLowerInvariant()!=hash)throw new InvalidDataException("cli_tools_unverified");
157新增: ToolHashes[path]=(info.Length,info.LastWriteTimeUtc,hash);
158新增: }
159新增: }
160新增: return Path.GetFullPath(path);
161新增: }
162新增: private sealed record CCSTools(string Node,string Main);
163新增: private static CCSTools LoadCCSTools()
164新增: {
165新增: var receipt=Path.Combine(AppContext.BaseDirectory,"ccs-tools.json");Pairing.PrivateFile(receipt);
166新增: var value=JsonNode.Parse(File.ReadAllBytes(receipt))as JsonObject??throw new InvalidDataException("ccs_tools_invalid");
167新增: string Check(string name)
168新增: {
169新增: var path=value[name]?.GetValue<string>()??"";var hash=value[name+"_sha256"]?.GetValue<string>()??"";
170新增: if(!Path.IsPathFullyQualified(path)||!Subject.IsMatch(hash)||!File.Exists(path)||new FileInfo(path).Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("ccs_tools_invalid");
171新增: using var data=File.OpenRead(path);if(Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant()!=hash)throw new InvalidDataException("ccs_tools_changed");
172新增: return Path.GetFullPath(path);
173新增: }
174新增: var node=Check("node");var main=Check("main");var manifest=Check("manifest");
175新增: if(new FileInfo(manifest).Length>2<<20)throw new InvalidDataException("ccs_manifest_invalid");
176新增: var files=System.Text.Json.JsonSerializer.Deserialize<Dictionary<string,string>>(File.ReadAllBytes(manifest))??throw new InvalidDataException("ccs_manifest_invalid");
177新增: if(files.Count is <1 or >20000)throw new InvalidDataException("ccs_manifest_invalid");
178新增: var root=Path.GetDirectoryName(manifest)!;
179新增: foreach(var item in files)
180新增: {
181新增: var path=Path.GetFullPath(Path.Combine(root,item.Key.Replace('/',Path.DirectorySeparatorChar)));
182新增: if(!path.StartsWith(root+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase)||!Subject.IsMatch(item.Value)||new FileInfo(path).Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("ccs_manifest_invalid");
183新增: using var data=File.OpenRead(path);if(Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant()!=item.Value)throw new InvalidDataException("ccs_tools_changed");
184新增: }
185新增: if(!main.StartsWith(root+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("ccs_tools_invalid");
186新增: return new(node,main);
187新增: }
188新增: private static Dictionary<string,string> EnvironmentFor(Layout layout,string account)
189新增: {
190新增: var env=Environment.GetEnvironmentVariables().Cast<System.Collections.DictionaryEntry>().ToDictionary(x=>(string)x.Key,x=>x.Value?.ToString()??"",StringComparer.OrdinalIgnoreCase);
191新增: env["CAGE_CLI_BINARY"]=layout.Tools.Claude;env["CAGE_CLI_STATE_ROOT"]=layout.State;env["CAGE_CLI_ACCOUNT_ROOT"]=layout.Accounts;env["CAGE_CLI_SHARED_ROOT"]=layout.Shared;
192新增: env["CAGE_CLI_ACCOUNT_HELPER"]=Path.Combine(layout.Code,"cage-claude-account.py");env["CLAUDE_CODE_GIT_BASH_PATH"]=layout.Tools.Bash;
193新增: env["CAGE_CLI_IDENTITY_HELPER"]=Path.Combine(layout.Code,"mobile_cli_identity.py");
194新增: env["CAGE_CLI_PYTHON"]=layout.Tools.Python;env["CAGE_CLI_SHELL"]=TerminalRpc.PowerShellPath();env["CAGE_CLAUDE_ACCOUNT_ID"]=account;
195新增: env["PATH"]=Path.GetDirectoryName(layout.Tools.Claude)+";"+Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(layout.Tools.Bash))!,"cmd")+";"+env.GetValueOrDefault("PATH");
196新增: if(account!="default")env["CLAUDE_CONFIG_DIR"]=Path.Combine(layout.Accounts,account,"config");
197新增: else env.Remove("CLAUDE_CONFIG_DIR");
198新增: return env;
199新增: }
200新增: private static void ValidatePaths(Layout layout,JsonObject value)
201新增: {
202新增: if(value["workspace"] is JsonValue w&&w.TryGetValue<string>(out var workspace)&&workspace!="")
203新增: {
204新增: var resolved=ProjectRpc.Resolve(value["project_id"]?.GetValue<string>()??"",value["grant"]?.GetValue<string>()??"");
205新增: if(!Path.GetFullPath(workspace).Equals(Path.GetFullPath(resolved),StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("cli_project_unregistered");
206新增: }
207新增: if(value["config"]is JsonValue c&&c.TryGetValue<string>(out var config)&&config!="")
208新增: {
209新增: var path=Path.GetFullPath(config);var home=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),".claude");
210新增: var relative=Path.GetRelativePath(layout.Accounts,path).Split(Path.DirectorySeparatorChar);
211新增: var ccs=Path.GetRelativePath(layout.Root,path);
212新增: var registeredCCS=(ccs.StartsWith("ccs-home"+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase)||ccs.StartsWith("ccs"+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))&&Directory.Exists(path);
213新增: if(!path.Equals(home,StringComparison.OrdinalIgnoreCase)&&!(relative.Length==2&&AccountID.IsMatch(relative[0])&&relative[0]!="default"&&relative[1]=="config")&&!registeredCCS)throw new InvalidDataException("cli_config_unregistered");
214新增: }
215新增: if(value["resume_transcript"] is JsonValue t&&t.TryGetValue<string>(out var transcript)&&transcript!="")
216新增: {
217新增: var id=Guid.Parse(value["switch_id"]?.GetValue<string>()??"");
218新增: var expected=Path.Combine(layout.Root,"cli-account-switches",id.ToString("D"),"history.jsonl");
219新增: if(!Path.GetFullPath(transcript).Equals(expected,StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("cli_history_unregistered");
220新增: }
221新增: }
222新增: private static async Task<JsonObject> Invoke(Layout layout,string account,string script,string[] args,JsonNode? input,CancellationToken token,Func<bool> available)
223新增: {
224新增: var start=new ProcessStartInfo(layout.Tools.Python){UseShellExecute=false,CreateNoWindow=true,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true};
225新增: foreach(var arg in new[]{"-X","utf8","-I",script}.Concat(args))start.ArgumentList.Add(arg);
226新增: foreach(var pair in EnvironmentFor(layout,account))start.Environment[pair.Key]=pair.Value;
227新增: start.WorkingDirectory=layout.Root;
228新增: using var child=Process.Start(start)??throw new InvalidDataException("cli_process_failed");
229新增: using var cancel=token.Register(()=>{try{child.Kill(true);}catch{}});
230新增: var stderr=child.StandardError.BaseStream.CopyToAsync(Stream.Null,token);
231新增: try
232新增: {
233新增: if(input is not null)await child.StandardInput.WriteLineAsync(input.ToJsonString().AsMemory(),token);child.StandardInput.Close();
234新增: using var output=new MemoryStream();var buffer=new byte[16384];int size;
235新增: while((size=await child.StandardOutput.BaseStream.ReadAsync(buffer,token))!=0)
236新增: {
237新增: if(output.Length+size>4<<20)throw new InvalidDataException("cli_status_limit");
238新增: output.Write(buffer,0,size);
239新增: }
240新增: var raw=Protocol.Utf8.GetString(output.GetBuffer(),0,(int)output.Length);await child.WaitForExitAsync(token);await stderr;
241新增: if(!available()||child.ExitCode!=0)throw new InvalidDataException("cli_status_unavailable");
242新增: var parsed=JsonNode.Parse(raw);
243新增: return new JsonObject{["result"]=parsed};
244新增: }
245新增: finally
246新增: {
247新增: if(!child.HasExited)try{child.Kill(true);}catch{}
248新增: await child.WaitForExitAsync(CancellationToken.None);
249新增: try{await stderr;}catch(OperationCanceledException){}
250新增: }
251新增: }
252新增: private static void PrivateDirectory(string path)
253新增: {
254新增: var home=Path.GetFullPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
255新增: if(!Path.GetFullPath(path).StartsWith(home+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("cli_directory_invalid");
256新增: for(var ancestor=new DirectoryInfo(path);ancestor.FullName!=home;ancestor=ancestor.Parent??throw new InvalidDataException("cli_directory_invalid"))
257新增: if(ancestor.Exists&&ancestor.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_directory_invalid");
258新增: Directory.CreateDirectory(path);var info=new DirectoryInfo(path);
259新增: if(info.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_directory_invalid");
260新增: using var user=WindowsIdentity.GetCurrent();var acl=new DirectorySecurity();acl.SetOwner(user.User!);acl.SetAccessRuleProtection(true,false);
261新增: foreach(var sid in new[]{user.User!,new SecurityIdentifier("S-1-5-18"),new SecurityIdentifier("S-1-5-32-544")})acl.AddAccessRule(new(sid,FileSystemRights.FullControl,InheritanceFlags.ContainerInherit|InheritanceFlags.ObjectInherit,PropagationFlags.None,AccessControlType.Allow));
262新增: info.SetAccessControl(acl);
263新增: }
264新增: private static byte[] PrivateData(string path)
265新增: {
266新增: var info=new FileInfo(path);
267新增: if(!info.Exists||info.Length is <1 or >16384||info.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_credentials_invalid");
268新增: using var user=WindowsIdentity.GetCurrent();var allowed=new HashSet<string>{user.User!.Value,"S-1-5-18","S-1-5-32-544"};
269新增: foreach(FileSystemAccessRule rule in info.GetAccessControl().GetAccessRules(true,true,typeof(SecurityIdentifier)))
270新增: if(rule.AccessControlType==AccessControlType.Allow&&!allowed.Contains(rule.IdentityReference.Value))throw new InvalidDataException("cli_credentials_permissions_invalid");
271新增: return File.ReadAllBytes(path);
272新增: }
273新增: private static IDisposable AccountLease(Layout layout,string account)
274新增: {
275新增: if(account=="default")return new Release(()=>{});
276新增: var folder=Path.Combine(layout.Accounts,account,"config");PrivateDirectory(folder);
277新增: var plain=Path.Combine(folder,".credentials.json");var encrypted=Path.Combine(folder,"credentials.dpapi");
278新增: lock(Gate)
279新增: {
280新增: if(!File.Exists(plain)&&File.Exists(encrypted))
281新增: {
282新增: var restored=Pairing.Crypt(PrivateData(encrypted),GuestContext.VM,GuestContext.SID+":cli:"+layout.Profile+":"+account,false);
283新增: try{using var file=new FileStream(plain,FileMode.CreateNew,FileAccess.Write,FileShare.None);file.Write(restored);file.Flush(true);}finally{CryptographicOperations.ZeroMemory(restored);}
284新增: }
285新增: Active[folder]=Active.GetValueOrDefault(folder)+1;
286新增: }
287新增: return new Release(()=>{lock(Gate){if(--Active[folder]!=0)return;Active.Remove(folder);if(File.Exists(plain)){var bytes=PrivateData(plain);try{var sealedBytes=Pairing.Crypt(bytes,GuestContext.VM,GuestContext.SID+":cli:"+layout.Profile+":"+account,true);var temporary=encrypted+"."+Guid.NewGuid().ToString("N");using(var file=new FileStream(temporary,FileMode.CreateNew,FileAccess.Write,FileShare.None)){file.Write(sealedBytes);file.Flush(true);}File.Move(temporary,encrypted,true);File.Delete(plain);}finally{CryptographicOperations.ZeroMemory(bytes);}}}});
288新增: }
289新增: private sealed class Release(Action action):IDisposable{private Action? close=action;public void Dispose()=>Interlocked.Exchange(ref close,null)?.Invoke();}
290新增: private sealed class PrefixStream(Stream inner,byte[] prefix):Stream
291新增: {
292新增: int position;
293新增: public override async ValueTask<int> ReadAsync(Memory<byte> buffer,CancellationToken token=default){if(position<prefix.Length){var n=Math.Min(buffer.Length,prefix.Length-position);prefix.AsMemory(position,n).CopyTo(buffer);position+=n;return n;}return await inner.ReadAsync(buffer,token);}
294新增: public override int Read(byte[] buffer,int offset,int count){if(position<prefix.Length){var n=Math.Min(count,prefix.Length-position);Array.Copy(prefix,position,buffer,offset,n);position+=n;return n;}return inner.Read(buffer,offset,count);}
295新增: public override Task WriteAsync(byte[] buffer,int offset,int count,CancellationToken token)=>inner.WriteAsync(buffer,offset,count,token);
296新增: public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer,CancellationToken token=default)=>inner.WriteAsync(buffer,token);
297新增: public override void Write(byte[] buffer,int offset,int count)=>inner.Write(buffer,offset,count);public override void Flush()=>inner.Flush();public override Task FlushAsync(CancellationToken token)=>inner.FlushAsync(token);
298新增: public override bool CanRead=>true;public override bool CanWrite=>true;public override bool CanSeek=>false;public override long Length=>throw new NotSupportedException();public override long Position{get=>throw new NotSupportedException();set=>throw new NotSupportedException();}public override long Seek(long a,SeekOrigin b)=>throw new NotSupportedException();public override void SetLength(long a)=>throw new NotSupportedException();
299新增: }
300新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsComponentStatus.cs+94 −0看文件
@@ -0,0 +1,94 @@
1新增:using System.Text.Json.Nodes;
2新增:
3新增:namespace Cage.GuestClipboard;
4新增:
5新增:// Readiness describes verified installed prerequisites for on-demand use. It
6新增:// does not start applications, inspect accounts, or record an audio sample.
7新增:internal static class WindowsComponentStatus
8新增:{
9新增: private sealed class Probe(Func<JsonObject> read)
10新增: {
11新增: internal readonly Func<JsonObject> Read=read;
12新增: internal JsonObject? Value;
13新增: internal bool Pending;
14新增: internal long Checked;
15新增: internal long CheckedTick;
16新增: }
17新增: private static readonly object Gate=new();
18新增: private static readonly Dictionary<string,Probe> Probes=new(StringComparer.Ordinal)
19新增: {
20新增: ["desktop"]=new(ClaudeWindowRpc.ComponentStatus),
21新增: ["cli"]=new(WindowsCliRpc.ComponentStatus),
22新增: ["audio"]=new(WindowsAudioRpc.ComponentStatus),
23新增: ["terminal"]=new(()=>State(File.Exists(TerminalRpc.PowerShellPath()),"terminal_components_missing")),
24新增: ["project-mount"]=new(()=>State(ProjectRpc.ToolsPresent(),"project_components_missing")),
25新增: };
26新增: private static JsonObject State(bool installed,string reason)=>new(){["installed"]=installed,["ready"]=installed,["reason"]=installed?"":reason};
27新增: internal static JsonObject Snapshot(JsonObject browser)
28新增: {
29新增: var available=SessionGuard.Available();
30新增: var registered=GuestOperations.Capabilities().ToHashSet(StringComparer.Ordinal);
31新增: var tick=Environment.TickCount64;
32新增: var result=new JsonObject();
33新增: lock(Gate)
34新增: {
35新增: foreach(var pair in Probes)
36新增: {
37新增: var probe=pair.Value;
38新增: if(available&&!probe.Pending&&(probe.Value==null||tick-probe.CheckedTick>=15000))
39新增: {
40新增: probe.Pending=true;
41新增: // Each category retains one worker until its native call
42新增: // finishes. A stalled COM provider cannot queue more work
43新增: // or block the authenticated GUI status reply.
44新增: _=Task.Factory.StartNew(()=>Refresh(pair.Key,probe),CancellationToken.None,TaskCreationOptions.LongRunning,TaskScheduler.Default);
45新增: }
46新增: var state=(JsonObject?)probe.Value?.DeepClone()??new JsonObject{["installed"]=false,["ready"]=false,["reason"]="component_check_pending"};
47新增: if(pair.Key=="audio")
48新增: {
49新增: var supported=Environment.OSVersion.Version.Build>=20348;
50新增: state["supported"]=supported;
51新增: if(probe.Value==null)state["installed"]=supported&&registered.Contains("audio");
52新增: }
53新增: state["registered"]=registered.Contains(pair.Key);state["checked_at_ms"]=probe.Checked;
54新增: if(probe.Value!=null&&tick-probe.CheckedTick>30000){state["ready"]=false;state["reason"]="component_check_pending";}
55新增: if(!registered.Contains(pair.Key)){state["ready"]=false;if(state["installed"]?.GetValue<bool>()==true)state["reason"]="component_restart_required";}
56新增: if(!available){state["ready"]=false;state["reason"]="requires_gui_login";}
57新增: result[pair.Key]=state;
58新增: }
59新增: }
60新增: result["clipboard"]=new JsonObject{["registered"]=true,["installed"]=true,["ready"]=available,["reason"]=available?"":"requires_gui_login"};
61新增: foreach(var name in new[]{"attachments","resources"})
62新增: result[name]=new JsonObject{["registered"]=registered.Contains(name),["installed"]=registered.Contains(name),["ready"]=available&&registered.Contains(name),["reason"]=available?"":"requires_gui_login"};
63新增: bool Flag(string name)=>browser[name]?.GetValue<bool>()==true;
64新增: var browserInstalled=Flag("installed");var browserReady=available&&registered.Contains("browser")&&browserInstalled&&Flag("network_configured");
65新增: result["browser"]=new JsonObject{["registered"]=registered.Contains("browser"),["installed"]=browserInstalled,["ready"]=browserReady,["reason"]=browserReady?"":!available?"requires_gui_login":!browserInstalled?"browser_components_missing":"browser_network_unavailable"};
66新增: var editorInstalled=Flag("editor_installed");
67新增: result["editor"]=new JsonObject{["registered"]=registered.Contains("browser"),["installed"]=editorInstalled,["ready"]=browserReady&&editorInstalled,["reason"]=!editorInstalled?"editor_components_missing":!browserReady?"browser_unavailable":""};
68新增: var phoneInstalled=Flag("phone_installed");var phoneReady=available&&registered.Contains("browser")&&phoneInstalled&&Flag("phone_network_configured");
69新增: result["phone-browser"]=new JsonObject{["supported"]=true,["registered"]=registered.Contains("browser"),["installed"]=phoneInstalled,["ready"]=phoneReady,["reason"]=!available?"requires_gui_login":!phoneInstalled?"phone_browser_components_missing":!Flag("phone_network_configured")?"browser_network_unavailable":!registered.Contains("browser")?"component_restart_required":""};
70新增: var phoneDesktop=(JsonObject)result["desktop"]!.DeepClone();
71新增: phoneDesktop["supported"]=true;
72新增: result["phone-desktop"]=phoneDesktop;
73新增: foreach (var name in new[] { "desktop-file-chooser", "desktop-downloads" })
74新增: {
75新增: var files = (JsonObject)result["desktop"]!.DeepClone();
76新增: files["supported"] = true;
77新增: if (files["ready"]?.GetValue<bool>() == true && ClipboardAgent.Current?.SessionEventsRegistered != true)
78新增: {
79新增: files["ready"] = false;
80新增: files["reason"] = "component_restart_required";
81新增: }
82新增: result[name] = files;
83新增: }
84新增: result["legacy-mobile-migration"]=new JsonObject{["registered"]=false,["installed"]=false,["ready"]=false,["reason"]="not_implemented"};
85新增: return result;
86新增: }
87新增: private static void Refresh(string name,Probe probe)
88新增: {
89新增: JsonObject value;
90新增: try{value=probe.Read();}
91新增: catch{value=new JsonObject{["installed"]=name=="audio"&&Environment.OSVersion.Version.Build>=20348,["ready"]=false,["reason"]=name+"_status_unavailable"};}
92新增: lock(Gate){probe.Value=value;probe.Checked=DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();probe.CheckedTick=Environment.TickCount64;probe.Pending=false;}
93新增: }
94新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsDesktopDownloads.cs+258 −0看文件
@@ -0,0 +1,258 @@
1新增:using System.Security.AccessControl;
2新增:using System.Security.Cryptography;
3新增:using System.Security.Principal;
4新增:using System.Runtime.InteropServices;
5新增:using System.Text;
6新增:using System.Text.Json;
7新增:using System.Text.Json.Nodes;
8新增:using Microsoft.Win32.SafeHandles;
9新增:
10新增:namespace Cage.GuestClipboard;
11新增:
12新增:// Only destinations reserved for a verified Claude Save dialog enter this
13新增:// catalog. A wire request names an opaque receipt, never a filesystem path.
14新增:internal static class WindowsDesktopDownloads
15新增:{
16新增: private sealed class Download
17新增: {
18新增: public string ID { get; set; } = "";
19新增: public string Name { get; set; } = "";
20新增: public string State { get; set; } = "downloading";
21新增: public string Error { get; set; } = "";
22新增: public long Size { get; set; }
23新增: public long Written { get; set; }
24新增: public DateTimeOffset Started { get; set; } = DateTimeOffset.UtcNow;
25新增: }
26新增: private sealed class Transfer(FileStream file, string session, long epoch)
27新增: {
28新增: internal readonly FileStream File = file;
29新增: internal bool SessionValid => ClipboardAgent.Current is { SessionEventsRegistered: true } agent && agent.Session == session && agent.SessionEpoch == epoch;
30新增: internal int Sequence;
31新增: internal DateTimeOffset Used = DateTimeOffset.UtcNow;
32新增: }
33新增: private static readonly object Gate = new();
34新增: private static readonly Dictionary<string, Download> Downloads = new();
35新增: private static readonly Dictionary<string, Transfer> Transfers = new();
36新增: private static readonly System.Threading.Timer TransferExpiry = new(_ =>
37新增: {
38新增: lock (Gate)
39新增: {
40新增: if (Transfers.Count == 0) return;
41新增: bool available;
42新增: try { available = SessionGuard.Available(); } catch { available = false; }
43新增: foreach (var pair in Transfers.ToArray())
44新增: if (!available || !pair.Value.SessionValid || DateTimeOffset.UtcNow - pair.Value.Used > TimeSpan.FromMinutes(2))
45新增: { pair.Value.File.Dispose(); Transfers.Remove(pair.Key); }
46新增: }
47新增: }, null, 2000, 2000);
48新增: private static string? directory;
49新增: [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
50新增: private static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder path, uint length, uint flags);
51新增:
52新增: private static FileStream OpenSource(Download item)
53新增: {
54新增: var path = Source(item);
55新增: var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
56新增: try
57新增: {
58新增: var actual = new StringBuilder(32768);
59新增: var length = GetFinalPathNameByHandleW(stream.SafeFileHandle, actual, (uint)actual.Capacity, 0);
60新增: if (length == 0 || length >= actual.Capacity ||
61新增: !string.Equals(actual.ToString(), @"\\?\" + Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase) ||
62新增: stream.Length > AttachmentsRpc.FileLimit)
63新增: throw new InvalidDataException("desktop_download_file_invalid");
64新增: return stream;
65新增: }
66新增: catch { stream.Dispose(); throw; }
67新增: }
68新增:
69新增: private static string DirectoryPath()
70新增: {
71新增: if (directory is not null) return directory;
72新增: var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
73新增: var root = Path.Combine(home, "Cage", "DesktopDownloads");
74新增: using var user = WindowsIdentity.GetCurrent();
75新增: foreach (var path in new[] { Path.Combine(home, "Cage"), root })
76新增: {
77新增: Directory.CreateDirectory(path);
78新增: var info = new DirectoryInfo(path);
79新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value != user.User?.Value)
80新增: throw new InvalidDataException("desktop_download_directory_invalid");
81新增: }
82新增: var manifest = Path.Combine(root, "downloads.json");
83新增: if (File.Exists(manifest))
84新增: {
85新增: var info = new FileInfo(manifest);
86新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.Length > 1 << 20) throw new InvalidDataException("desktop_download_catalog_invalid");
87新增: var saved = JsonSerializer.Deserialize<Download[]>(File.ReadAllBytes(manifest)) ?? [];
88新增: foreach (var item in saved.TakeLast(100))
89新增: {
90新增: if (!Guid.TryParseExact(item.ID, "D", out _) || !AttachmentsRpc.NameValid(item.Name)) continue;
91新增: if (item.State == "downloading") { item.State = "failed"; item.Error = "保存过程被中断,请从 Claude Desktop 重新下载。"; }
92新增: Downloads[item.ID] = item;
93新增: }
94新增: }
95新增: directory = root;
96新增: return root;
97新增: }
98新增: private static string Source(Download item) => Path.Combine(DirectoryPath(), item.ID, item.Name);
99新增: private static void Persist()
100新增: {
101新增: var file = Path.Combine(DirectoryPath(), "downloads.json");
102新增: var temporary = file + "." + Guid.NewGuid().ToString("N");
103新增: try
104新增: {
105新增: using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None))
106新增: {
107新增: JsonSerializer.Serialize(stream, Downloads.Values.TakeLast(100).ToArray());
108新增: stream.Flush(true);
109新增: }
110新增: File.Move(temporary, file, true);
111新增: }
112新增: finally { if (File.Exists(temporary)) File.Delete(temporary); }
113新增: }
114新增:
115新增: internal static string Reserve(string name, Action<string> submit)
116新增: {
117新增: if (!AttachmentsRpc.NameValid(name)) throw new InvalidDataException("desktop_download_name_invalid");
118新增: lock (Gate)
119新增: {
120新增: DirectoryPath();
121新增: if (Downloads.Values.Count(item => item.State == "downloading") >= 12) throw new InvalidDataException("desktop_download_limit");
122新增: var item = new Download { ID = Guid.NewGuid().ToString("D"), Name = name };
123新增: var folder = Path.GetDirectoryName(Source(item))!;
124新增: Directory.CreateDirectory(folder);
125新增: var watcher = new FileSystemWatcher(folder) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size };
126新增: var changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
127新增: var renamed = 0;
128新增: watcher.Changed += (_, eventArgs) => { if (eventArgs.Name == name) changed.TrySetResult(); };
129新增: watcher.Renamed += (_, eventArgs) => { if (eventArgs.Name == name) { Interlocked.Exchange(ref renamed, 1); changed.TrySetResult(); } };
130新增: watcher.Error += (_, _) => changed.TrySetException(new InvalidDataException("desktop_download_watch_failed"));
131新增: watcher.EnableRaisingEvents = true;
132新增: while (Downloads.Count >= 100)
133新增: {
134新增: var oldest = Downloads.Values.FirstOrDefault(value => value.State != "downloading");
135新增: if (oldest is null) break;
136新增: Downloads.Remove(oldest.ID);
137新增: }
138新增: Downloads.Add(item.ID, item);
139新增: Persist();
140新增: try { submit(Source(item)); }
141新增: catch
142新增: {
143新增: watcher.Dispose(); item.State = "failed"; item.Error = "客机保存窗口未接收文件位置,请重新下载。"; Persist(); throw;
144新增: }
145新增: _ = Task.Run(async () =>
146新增: {
147新增: using (watcher)
148新增: using (var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(30)))
149新增: {
150新增: try
151新增: {
152新增: await changed.Task.WaitAsync(timeout.Token);
153新增: while (true)
154新增: {
155新增: timeout.Token.ThrowIfCancellationRequested();
156新增: if (!File.Exists(Source(item) + ".crdownload"))
157新增: {
158新增: try
159新增: {
160新增: using var source = OpenSource(item);
161新增: if (source.Length == 0 && Volatile.Read(ref renamed) == 0) throw new IOException("empty reservation is waiting for completion");
162新增: lock (Gate)
163新增: {
164新增: item.Size = source.Length; item.Written = File.GetLastWriteTimeUtc(Source(item)).Ticks;
165新增: item.State = "saved"; Persist();
166新增: }
167新增: return;
168新增: }
169新增: catch (IOException) { }
170新增: }
171新增: await Task.Delay(100, timeout.Token);
172新增: }
173新增: }
174新增: catch
175新增: {
176新增: lock (Gate) { item.State = "failed"; item.Error = "未能确认文件保存完成,请从 Claude Desktop 重新下载。"; Persist(); }
177新增: }
178新增: }
179新增: });
180新增: return item.ID;
181新增: }
182新增: }
183新增:
184新增: internal static JsonArray Snapshot()
185新增: {
186新增: lock (Gate)
187新增: {
188新增: DirectoryPath();
189新增: return new JsonArray(Downloads.Values.TakeLast(100).Reverse().Select(item => (JsonNode)new JsonObject
190新增: {
191新增: ["id"] = item.ID, ["name"] = item.Name, ["state"] = item.State, ["target"] = "desktop",
192新增: ["receivedBytes"] = item.Size, ["totalBytes"] = item.Size, ["retryable"] = false,
193新增: ["error"] = item.Error, ["startedAt"] = item.Started.ToString("O"),
194新增: }).ToArray());
195新增: }
196新增: }
197新增:
198新增: internal static (string ID, bool Directory)? FindPath(string path)
199新增: {
200新增: lock (Gate)
201新增: {
202新增: DirectoryPath();
203新增: foreach (var item in Downloads.Values)
204新增: {
205新增: var source = Source(item);
206新增: if (string.Equals(path, source, StringComparison.OrdinalIgnoreCase)) return (item.ID, false);
207新增: if (string.Equals(path, Path.GetDirectoryName(source), StringComparison.OrdinalIgnoreCase)) return (item.ID, true);
208新增: }
209新增: return null;
210新增: }
211新增: }
212新增:
213新增: internal static JsonObject Read(JsonObject input)
214新增: {
215新增: lock (Gate)
216新增: {
217新增: SessionGuard.Assert(); DirectoryPath();
218新增: foreach (var pair in Transfers.ToArray())
219新增: if (!pair.Value.SessionValid || DateTimeOffset.UtcNow - pair.Value.Used > TimeSpan.FromMinutes(2)) { pair.Value.File.Dispose(); Transfers.Remove(pair.Key); }
220新增: var action = input["action"]?.GetValue<string>();
221新增: if (action == "files-download-retry")
222新增: {
223新增: var id = input["id"]?.GetValue<string>() ?? "";
224新增: if (!Downloads.TryGetValue(id, out var item) || item.State != "saved") throw new InvalidDataException("desktop_download_incomplete");
225新增: using var file = OpenSource(item);
226新增: if (file.Length != item.Size || File.GetLastWriteTimeUtc(Source(item)).Ticks != item.Written) throw new InvalidDataException("desktop_download_changed");
227新增: return new JsonObject { ["ok"] = true };
228新增: }
229新增: if (action == "files-download-open")
230新增: {
231新增: var agent = ClipboardAgent.Current;
232新增: if (agent is null || !agent.SessionEventsRegistered) throw new InvalidDataException("desktop_download_session_unavailable");
233新增: var id = input["id"]?.GetValue<string>() ?? "";
234新增: if (!Downloads.TryGetValue(id, out var item) || item.State != "saved" || Transfers.Count >= 12) throw new InvalidDataException("desktop_download_unavailable");
235新增: var file = OpenSource(item);
236新增: if (file.Length != item.Size || File.GetLastWriteTimeUtc(Source(item)).Ticks != item.Written)
237新增: { file.Dispose(); throw new InvalidDataException("desktop_download_changed"); }
238新增: var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
239新增: Transfers.Add(key, new Transfer(file, agent.Session, agent.SessionEpoch));
240新增: return new JsonObject { ["transfer"] = key, ["size"] = file.Length, ["name"] = item.Name };
241新增: }
242新增: var transfer = input["transfer"]?.GetValue<string>() ?? "";
243新增: if (action == "files-download-close")
244新增: {
245新增: if (Transfers.Remove(transfer, out var old)) old.File.Dispose();
246新增: return new JsonObject { ["ok"] = true };
247新增: }
248新增: if (action != "files-download-read" || !Transfers.TryGetValue(transfer, out var current) || current.Sequence != input["sequence"]?.GetValue<int>())
249新增: throw new InvalidDataException("desktop_download_transfer_invalid");
250新增: var data = new byte[64 << 10];
251新增: var count = current.File.Read(data);
252新增: current.Used = DateTimeOffset.UtcNow;
253新增: var result = new JsonObject { ["data"] = Convert.ToBase64String(data, 0, count), ["sequence"] = ++current.Sequence, ["eof"] = current.File.Position == current.File.Length };
254新增: if (current.File.Position == current.File.Length) { current.File.Dispose(); Transfers.Remove(transfer); }
255新增: return result;
256新增: }
257新增: }
258新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsDesktopFiles.cs+262 −0看文件
@@ -0,0 +1,262 @@
1新增:using System.Diagnostics;
2新增:using System.Runtime.InteropServices;
3新增:using System.Text.Json.Nodes;
4新增:using System.Windows.Automation;
5新增:
6新增:namespace Cage.GuestClipboard;
7新增:
8新增:internal static class WindowsDesktopFiles
9新增:{
10新增: private sealed record Chooser(WindowsFileDialogNative.Owner Owner, IntPtr Window, IntPtr Stamp,
11新增: bool Directory, bool Multiple, string Session, long Epoch, string SaveName = "")
12新增: {
13新增: internal string ID = "";
14新增: internal bool Submitting;
15新增: internal readonly DateTimeOffset Created = DateTimeOffset.UtcNow;
16新增: internal bool SessionValid => SessionGuard.Available() && ClipboardAgent.Current is { SessionEventsRegistered: true } agent && agent.Session == Session && agent.SessionEpoch == Epoch;
17新增: internal void Assert(bool foreground = false)
18新增: {
19新增: if (!SessionValid) throw new InvalidDataException("file_dialog_changed");
20新增: WindowsFileDialogNative.Assert(Owner, Window, Stamp, foreground);
21新增: }
22新增: internal void AcceptSelection()
23新增: {
24新增: Assert(true);
25新增: // Windows 11 can expose the native Open split button as a UIA
26新增: // Pane without InvokePattern. BM_CLICK addresses that exact button.
27新增: WindowsFileDialogNative.Accept(Owner, Window, Stamp);
28新增: }
29新增: }
30新增: private static readonly object Gate = new();
31新增: private static readonly Dictionary<string, Chooser> Choosers = new();
32新增: private sealed record OpenRequest(string Path, string Action, string Session, long Epoch, Action Validate)
33新增: {
34新增: internal readonly DateTimeOffset Created = DateTimeOffset.UtcNow;
35新增: internal bool Claimed;
36新增: }
37新增: private static readonly Dictionary<string, OpenRequest> Opens = new();
38新增: [DllImport("user32.dll", ExactSpelling = true)] private static extern bool PostMessageW(IntPtr window, uint message, IntPtr wparam, IntPtr lparam);
39新增:
40新增: private static string ButtonLabel(string name) => System.Text.RegularExpressions.Regex.Replace(name.Replace("&", ""), @"\s*\([A-Za-z]\)\s*$", "").Trim().TrimEnd('.', '…');
41新增:
42新增: private static bool FilenameControl(AutomationElement element, IntPtr dialog)
43新增: {
44新增: AutomationElement? current = element;
45新增: for (var depth = 0; current is not null && depth < 4; depth++, current = TreeWalker.ControlViewWalker.GetParent(current))
46新增: {
47新增: var handle = new IntPtr(current.Current.NativeWindowHandle);
48新增: if (handle == dialog) return false;
49新增: var id = handle == IntPtr.Zero ? 0 : WindowsFileDialogNative.GetDlgCtrlID(handle);
50新增: if (id is 1148 or 1152 || current.Current.AutomationId is "1148" or "1152" or "FileNameControlHost") return true;
51新增: }
52新增: return false;
53新增: }
54新增:
55新增: private static IntPtr FilenameHandle(Chooser chooser)
56新增: {
57新增: chooser.Assert(true);
58新增: // Windows Shell dialogs can replace their UIA edit provider
59新增: // while uploads are in flight. Reacquire it inside the stamped dialog.
60新增: var root = AutomationElement.FromHandle(chooser.Window);
61新增: var fields = root.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
62新增: var result = IntPtr.Zero;
63新增: foreach (AutomationElement element in fields)
64新增: {
65新增: var current = element.Current;
66新增: if (current.ProcessId != chooser.Owner.PID || current.IsOffscreen || !FilenameControl(element, chooser.Window) ||
67新增: !element.TryGetCurrentPattern(ValuePattern.Pattern, out var candidate) || ((ValuePattern)candidate).Current.IsReadOnly) continue;
68新增: if (result != IntPtr.Zero) throw new InvalidDataException("file_dialog_selection_invalid");
69新增: result = new IntPtr(current.NativeWindowHandle);
70新增: }
71新增: chooser.Assert(true);
72新增: return result != IntPtr.Zero ? result : throw new InvalidDataException("file_dialog_selection_invalid");
73新增: }
74新增:
75新增: private static Chooser? Inspect(WindowsFileDialogNative.Owner owner, IntPtr window)
76新增: {
77新增: var root = AutomationElement.FromHandle(window);
78新增: var elements = root.FindAll(TreeScope.Descendants, Condition.TrueCondition);
79新增: if (elements.Count > 4096) throw new InvalidDataException("file_dialog_control_limit");
80新增: AutomationElement? accept = null, field = null;
81新增: bool multiple = false;
82新增: foreach (AutomationElement element in elements)
83新增: {
84新增: var current = element.Current;
85新增: if (current.ProcessId != owner.PID || current.IsOffscreen) continue;
86新增: var controlID = current.NativeWindowHandle == 0 ? 0 : WindowsFileDialogNative.GetDlgCtrlID(new IntPtr(current.NativeWindowHandle));
87新增: if ((controlID == 1 || current.AutomationId == "1") &&
88新增: (element.TryGetCurrentPattern(InvokePattern.Pattern, out _) ||
89新增: controlID == 1 && current.ClassName == "Button")) accept = element;
90新增: if (current.ControlType == ControlType.Edit && FilenameControl(element, window) &&
91新增: element.TryGetCurrentPattern(ValuePattern.Pattern, out var editable) && !((ValuePattern)editable).Current.IsReadOnly) field = element;
92新增: if (current.ControlType is { } type && (type == ControlType.List || type == ControlType.DataGrid) &&
93新增: element.TryGetCurrentPattern(SelectionPattern.Pattern, out var selection)) multiple |= ((SelectionPattern)selection).Current.CanSelectMultiple;
94新增: }
95新增: if (accept is null || field is null) return null;
96新增: var label = ButtonLabel(accept.Current.Name);
97新增: bool directory = label is "Select Folder" or "Choose Folder" or "选择文件夹" or "選擇資料夾";
98新增: bool save = label is "Save" or "保存" or "儲存" or "Enregistrer" or "Speichern" or "Guardar" or "Salvar" or "Salva" or "Сохранить" or "저장";
99新增: if (!directory && !save && label is not ("Open" or "打开" or "開啟" or "Ouvrir" or "Öffnen" or "Abrir" or "Apri" or "Openen" or "開く" or "Открыть" or "열기")) return null;
100新增: var saveName = save ? ((ValuePattern)field.GetCurrentPattern(ValuePattern.Pattern)).Current.Value : "";
101新增: if (save && !AttachmentsRpc.NameValid(saveName)) return null;
102新增: var agent = ClipboardAgent.Current;
103新增: if (agent is null || !agent.SessionEventsRegistered) throw new InvalidDataException("file_dialog_session_unavailable");
104新增: var stamp = WindowsFileDialogNative.Stamp(owner, window);
105新增: return new Chooser(owner, window, stamp, directory, multiple && !directory, agent.Session, agent.SessionEpoch, saveName);
106新增: }
107新增:
108新增: internal static JsonObject Poll(WindowsFileDialogNative.Owner owner)
109新增: {
110新增: lock (Gate)
111新增: {
112新增: foreach (var pair in Choosers.ToArray())
113新增: if (DateTimeOffset.UtcNow - pair.Value.Created > TimeSpan.FromMinutes(30) ||
114新增: !pair.Value.SessionValid ||
115新增: !WindowsFileDialogNative.Alive(pair.Value.Owner, pair.Value.Window, pair.Value.Stamp)) Retire(pair.Key);
116新增: foreach (var window in WindowsFileDialogNative.Candidates(owner))
117新增: {
118新增: if (Choosers.Values.Any(value => value.Window == window)) continue;
119新增: if (Choosers.Count >= 12) throw new InvalidDataException("file_dialog_request_limit");
120新增: var chooser = Inspect(owner, window);
121新增: if (chooser is null) continue;
122新增: try
123新增: {
124新增: if (chooser.SaveName != "")
125新增: {
126新增: chooser.ID = WindowsDesktopDownloads.Reserve(chooser.SaveName, path =>
127新增: {
128新增: chooser.Assert(true);
129新增: var field = FilenameHandle(chooser);
130新增: WindowsFileDialogNative.SetFilename(chooser.Owner, chooser.Window, chooser.Stamp, field, path);
131新增: chooser.Assert(true);
132新增: chooser.AcceptSelection();
133新增: });
134新增: }
135新增: else chooser.ID = chooser.Directory ? Guid.NewGuid().ToString("D") :
136新增: AttachmentsRpc.StartChooserBatch(Guid.NewGuid().ToString("N"), () => chooser.Assert())["id"]!.GetValue<string>();
137新增: Choosers.Add(chooser.ID, chooser);
138新增: }
139新增: catch { WindowsFileDialogNative.Remove(window, chooser.Stamp); throw; }
140新增: }
141新增: return new JsonObject
142新增: {
143新增: ["available"] = true,
144新增: ["uploads"] = new JsonArray(Choosers.Values.Where(value => !value.Submitting && value.SaveName == "").Select(value => (JsonNode)new JsonObject
145新增: {
146新增: ["id"] = value.ID, ["target"] = "desktop", ["kind"] = "chooser", ["multiple"] = value.Multiple, ["directory"] = value.Directory,
147新增: }).ToArray()),
148新增: ["downloads"] = WindowsDesktopDownloads.Snapshot(), ["opens"] = OpenSnapshot(),
149新增: };
150新增: }
151新增: }
152新增:
153新增: private static void ExpireOpens()
154新增: {
155新增: var agent = ClipboardAgent.Current;
156新增: var available = SessionGuard.Available();
157新增: foreach (var pair in Opens.ToArray())
158新增: if (agent is null || !agent.SessionEventsRegistered || !available ||
159新增: pair.Value.Session != agent.Session || pair.Value.Epoch != agent.SessionEpoch ||
160新增: DateTimeOffset.UtcNow - pair.Value.Created >= (pair.Value.Claimed ? TimeSpan.FromMinutes(30) : TimeSpan.FromSeconds(60))) Opens.Remove(pair.Key);
161新增: }
162新增:
163新增: internal static void QueueOpen(string path, string action, Action validate)
164新增: {
165新增: if (!Path.IsPathFullyQualified(path) || path.Length > 32767 || path.Contains('\0') || action is not ("open" or "reveal"))
166新增: throw new InvalidDataException("file_open_request_invalid");
167新增: lock (Gate)
168新增: {
169新增: SessionGuard.Assert(); ExpireOpens(); validate();
170新增: var agent = ClipboardAgent.Current;
171新增: if (agent is null || !agent.SessionEventsRegistered || Opens.Count >= 32) throw new InvalidDataException("file_open_request_unavailable");
172新增: Opens.Add(Guid.NewGuid().ToString("D"), new OpenRequest(Path.GetFullPath(path), action, agent.Session, agent.SessionEpoch, validate));
173新增: }
174新增: }
175新增:
176新增: internal static JsonArray OpenSnapshot()
177新增: {
178新增: lock (Gate)
179新增: {
180新增: ExpireOpens();
181新增: return new JsonArray(Opens.Where(pair => !pair.Value.Claimed).Select(pair => (JsonNode)new JsonObject { ["id"] = pair.Key }).ToArray());
182新增: }
183新增: }
184新增:
185新增: internal static JsonObject OpenAction(string id, bool complete)
186新增: {
187新增: lock (Gate)
188新增: {
189新增: ExpireOpens();
190新增: if (!Opens.TryGetValue(id, out var request)) return new JsonObject { [complete ? "ok" : "handled"] = true };
191新增: if (complete)
192新增: {
193新增: Opens.Remove(id);
194新增: try { request.Validate(); } catch { }
195新增: return new JsonObject { ["ok"] = true };
196新增: }
197新增: if (request.Claimed) return new JsonObject { ["handled"] = true };
198新增: try { request.Validate(); }
199新增: catch { Opens.Remove(id); throw new InvalidDataException("file_open_target_changed"); }
200新增: var result = new JsonObject { ["id"] = id, ["action"] = request.Action };
201新增: if (WindowsDesktopDownloads.FindPath(request.Path) is { } download)
202新增: { result["download_id"] = download.ID; result["directory"] = download.Directory; }
203新增: else result["path"] = request.Path;
204新增: request.Claimed = true;
205新增: return result;
206新增: }
207新增: }
208新增:
209新增: private static void Retire(string id)
210新增: {
211新增: if (!Choosers.Remove(id, out var chooser)) return;
212新增: WindowsFileDialogNative.Remove(chooser.Window, chooser.Stamp);
213新增: if (!chooser.Submitting) AttachmentsRpc.CancelBatch(id);
214新增: }
215新增:
216新增: internal static bool Contains(string id) { lock (Gate) return Choosers.ContainsKey(id); }
217新增:
218新增: internal static void Cancel(string id)
219新增: {
220新增: lock (Gate)
221新增: {
222新增: if (!Choosers.TryGetValue(id, out var chooser)) return;
223新增: if (chooser.SessionValid && WindowsFileDialogNative.Alive(chooser.Owner, chooser.Window, chooser.Stamp))
224新增: PostMessageW(chooser.Window, 0x0111, new IntPtr(2), IntPtr.Zero);
225新增: Retire(id);
226新增: AttachmentsRpc.CancelBatch(id);
227新增: }
228新增: }
229新增:
230新增: internal static async Task Finish(string id, string[] paths, CancellationToken token)
231新增: {
232新增: Chooser chooser;
233新增: lock (Gate)
234新增: {
235新增: if (!Choosers.TryGetValue(id, out chooser!) || chooser.Submitting || paths.Length == 0 ||
236新增: paths.Length > (chooser.Multiple ? 100 : 1)) throw new InvalidDataException("file_dialog_selection_invalid");
237新增: chooser.Assert(true);
238新增: chooser.Submitting = true;
239新增: }
240新增: try
241新增: {
242新增: foreach (var path in paths)
243新增: if (!Path.IsPathFullyQualified(path) || path.Contains('"') || path.Contains('\0') ||
244新增: (chooser.Directory ? !Directory.Exists(path) : !File.Exists(path))) throw new InvalidDataException("file_dialog_selection_invalid");
245新增: string selection = paths.Length == 1 ? paths[0] : string.Join(" ", paths.Select(path => "\"" + path + "\""));
246新增: chooser.Assert(true);
247新增: var field = FilenameHandle(chooser);
248新增: WindowsFileDialogNative.SetFilename(chooser.Owner, chooser.Window, chooser.Stamp, field, selection);
249新增: chooser.Assert(true);
250新增: chooser.AcceptSelection();
251新增: var deadline = Stopwatch.StartNew();
252新增: while (WindowsFileDialogNative.Alive(chooser.Owner, chooser.Window, chooser.Stamp))
253新增: {
254新增: chooser.Assert();
255新增: if (deadline.Elapsed > TimeSpan.FromSeconds(4)) throw new InvalidDataException("file_dialog_still_open");
256新增: await Task.Delay(50, token);
257新增: }
258新增: lock (Gate) Retire(id);
259新增: }
260新增: finally { lock (Gate) chooser.Submitting = false; }
261新增: }
262新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsEditorPreferences.cs+53 −0看文件
@@ -0,0 +1,53 @@
1新增:using System.Text;
2新增:using System.Text.Json;
3新增:
4新增:namespace Cage.GuestClipboard;
5新增:
6新增:// Cage owns this preference file. Official serve-web does not consume disk
7新增:// User settings; the broker applies this one key as a low-priority web default.
8新增:internal static class WindowsEditorPreferences
9新增:{
10新增: internal const string TrustKey = "security.workspace.trust.enabled";
11新增: internal static bool? TrustDefault(string cageEditorHome)
12新增: {
13新增: var user = Path.Combine(cageEditorHome, "User");
14新增: if (Directory.Exists(cageEditorHome) && new DirectoryInfo(cageEditorHome).Attributes.HasFlag(FileAttributes.ReparsePoint) || Directory.Exists(user) && new DirectoryInfo(user).Attributes.HasFlag(FileAttributes.ReparsePoint))
15新增: throw new InvalidDataException("editor_package_invalid");
16新增: Directory.CreateDirectory(user);
17新增: var file = Path.Combine(user, "settings.json");
18新增: var original = "{}";
19新增: if (File.Exists(file))
20新增: {
21新增: var info = new FileInfo(file);
22新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.Length > 1 << 20) return null;
23新增: using var snapshot = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
24新增: if (snapshot.Length > 1 << 20) return null;
25新增: using var reader = new StreamReader(snapshot);
26新增: original = reader.ReadToEnd();
27新增: }
28新增: try
29新增: {
30新增: using var document = JsonDocument.Parse(original, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
31新增: if (document.RootElement.ValueKind != JsonValueKind.Object) return null;
32新增: if (document.RootElement.TryGetProperty(TrustKey, out var existing))
33新增: return existing.ValueKind is JsonValueKind.True or JsonValueKind.False ? existing.GetBoolean() : null;
34新增: // Insert after the opening brace, preserving comments, whitespace,
35新增: // trailing commas and every existing setting value.
36新增: var bytes = Encoding.UTF8.GetBytes(original);
37新增: var reader = new Utf8JsonReader(bytes, new JsonReaderOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
38新增: if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject) return null;
39新增: var offset = Encoding.UTF8.GetCharCount(bytes.AsSpan(0, (int)reader.BytesConsumed));
40新增: var property = "\n \"" + TrustKey + "\": false" + (document.RootElement.EnumerateObject().Any() ? "," : "") + "\n";
41新增: var updated = original.Insert(offset, property);
42新增: var temporary = file + "." + Guid.NewGuid().ToString("N") + ".tmp";
43新增: try
44新增: {
45新增: File.WriteAllText(temporary, updated, new UTF8Encoding(false));
46新增: WindowsFilePublication.Replace(temporary, file, default).GetAwaiter().GetResult();
47新增: }
48新增: finally { if (File.Exists(temporary)) File.Delete(temporary); }
49新增: return false;
50新增: }
51新增: catch (JsonException) { return null; } // Preserve a malformed user file rather than replacing it.
52新增: }
53新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsEditorServer.cs+146 −0看文件
@@ -0,0 +1,146 @@
1新增:using System.Collections.Concurrent;
2新增:using System.Diagnostics;
3新增:using System.Security.Cryptography;
4新增:using System.Text.Json.Nodes;
5新增:using System.Text.RegularExpressions;
6新增:
7新增:namespace Cage.GuestClipboard;
8新增:
9新增:// Only the authenticated project resolver supplies a folder. The official CLI
10新增:// serves a pinned, offline web-server package over authenticated loopback.
11新增:internal static class WindowsEditorServer
12新增:{
13新增: private static readonly ConcurrentDictionary<string, Editor> Editors = new(StringComparer.Ordinal);
14新增: private static readonly Regex Commit = new("^[a-f0-9]{40}$", RegexOptions.CultureInvariant);
15新增: private static readonly Regex Listening = new(@"Web UI available at (http://127\.0\.0\.1:[1-9][0-9]*)", RegexOptions.CultureInvariant);
16新增: internal sealed record Connection(string ID, string Project, string Grant, string Folder, string URL, bool? TrustDefault = null);
17新增:
18新增: internal static bool Installed()
19新增: {
20新增: try
21新增: {
22新增: var root = AppContext.BaseDirectory;
23新增: return File.Exists(Path.Combine(root, "vscode-cli", "code.exe")) &&
24新增: File.Exists(Path.Combine(root, "vscode-server", "bin", "code-server.cmd")) &&
25新增: Commit.IsMatch((JsonNode.Parse(File.ReadAllText(Path.Combine(root, "editor-runtime.json"))) as JsonObject)?["commit"]?.GetValue<string>() ?? "");
26新增: }
27新增: catch { return false; }
28新增: }
29新增:
30新增: internal static async Task<Connection> Open(string project, string grant, bool restart, CancellationToken token)
31新增: {
32新增: var folder = ProjectRpc.Resolve(project, grant);
33新增: if (!Installed()) throw new InvalidDataException("editor_components_missing");
34新增: var home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Cage", "Editors");
35新增: var trustDefault = WindowsEditorPreferences.TrustDefault(home);
36新增: if (Editors.TryGetValue(project, out var existing))
37新增: {
38新增: if (existing.Grant == grant && !existing.Process.HasExited && existing.Folder == folder && !restart) return existing.Connection with { TrustDefault = trustDefault };
39新增: if (Editors.TryRemove(project, out var old)) old.Dispose();
40新增: }
41新增: var root = AppContext.BaseDirectory;
42新增: var commit = (JsonNode.Parse(await File.ReadAllTextAsync(Path.Combine(root, "editor-runtime.json"), token)) as JsonObject)?["commit"]?.GetValue<string>() ?? "";
43新增: if (!Commit.IsMatch(commit)) throw new InvalidDataException("editor_components_missing");
44新增: var runtime = Path.Combine(home, "runtime");
45新增: var cached = Path.Combine(runtime, "serve-web", commit);
46新增: if (!Directory.Exists(cached))
47新增: {
48新增: var stage = cached + "." + Guid.NewGuid().ToString("N");
49新增: try { CopyPackage(Path.Combine(root, "vscode-server"), stage, token); Directory.Move(stage, cached); }
50新增: finally { if (Directory.Exists(stage)) Directory.Delete(stage, true); }
51新增: }
52新增: if (!File.Exists(Path.Combine(cached, "bin", "code-server.cmd"))) throw new InvalidDataException("editor_components_missing");
53新增: var profile = Path.Combine(home, "profiles", project);
54新增: Directory.CreateDirectory(profile);
55新增: var tokenFile = Path.Combine(profile, "connection-token");
56新增: var portFile = Path.Combine(profile, "port");
57新增: ushort port = 0;
58新增: if (File.Exists(portFile) && new FileInfo(portFile).Length <= 16) ushort.TryParse(await File.ReadAllTextAsync(portFile, token), out port);
59新增: var secret = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
60新增: await File.WriteAllTextAsync(tokenFile, secret, Protocol.Utf8, token);
61新增: var start = new ProcessStartInfo(Path.Combine(root, "vscode-cli", "code.exe"))
62新增: {
63新增: UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true,
64新增: RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = folder,
65新增: };
66新增: foreach (var arg in new[] { "serve-web", "--host", "127.0.0.1", "--port", port.ToString(System.Globalization.CultureInfo.InvariantCulture), "--connection-token-file", tokenFile,
67新增: "--default-folder", folder, "--server-data-dir", Path.Combine(home, "server"), "--cli-data-dir", runtime,
68新增: "--commit-id", commit, "--disable-telemetry", "--accept-server-license-terms" }) start.ArgumentList.Add(arg);
69新增: // An offline package and a pinned commit prevent the CLI's version
70新增: // updater. Browser assets/extensions still use Cage's controlled proxy.
71新增: var process = Process.Start(start) ?? throw new InvalidDataException("editor_start_failed");
72新增: var editor = new Editor(project, grant, folder, process);
73新增: try
74新增: {
75新增: editor.Job = new GuestProcessJob(process);
76新增: var address = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
77新增: editor.Output = Drain(process.StandardOutput, address);
78新增: editor.Errors = Drain(process.StandardError, address);
79新增: using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); timeout.CancelAfter(TimeSpan.FromSeconds(20));
80新增: var url = await address.Task.WaitAsync(timeout.Token);
81新增: var endpoint = new Uri(url);
82新增: await File.WriteAllTextAsync(portFile, endpoint.Port.ToString(System.Globalization.CultureInfo.InvariantCulture), Protocol.Utf8, token);
83新增: editor.Connection = new Connection(Guid.NewGuid().ToString("N"), project, grant, folder, "http://" + project + ".cage-editor.localhost:" + endpoint.Port + "/?tkn=" + Uri.EscapeDataString(secret), trustDefault);
84新增: if (ProjectRpc.Resolve(project, grant) != folder || process.HasExited) throw new InvalidDataException("project_grant_unavailable");
85新增: if (!Editors.TryAdd(project, editor)) throw new InvalidDataException("editor_start_busy");
86新增: return editor.Connection;
87新增: }
88新增: catch { editor.Dispose(); throw; }
89新增: }
90新增:
91新增: private static async Task Drain(StreamReader reader, TaskCompletionSource<string> listening)
92新增: {
93新增: try
94新增: {
95新增: // Read bounded chunks, never logging a CLI line which can contain
96新增: // the private connection token or an authorized project path.
97新增: var buffer = new char[4096]; var recent = ""; int count;
98新增: while ((count = await reader.ReadAsync(buffer)) != 0)
99新增: {
100新增: recent = (recent + new string(buffer, 0, count));
101新增: if (recent.Length > 8192) recent = recent[^8192..];
102新增: var match = Listening.Match(recent);
103新增: if (match.Success) listening.TrySetResult(match.Groups[1].Value);
104新增: }
105新增: listening.TrySetException(new InvalidDataException("editor_start_failed"));
106新增: }
107新增: catch { listening.TrySetException(new InvalidDataException("editor_start_failed")); }
108新增: }
109新增:
110新增: private static void CopyPackage(string source, string target, CancellationToken token)
111新增: {
112新增: var directory = new DirectoryInfo(source);
113新增: if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("editor_package_invalid");
114新增: Directory.CreateDirectory(target);
115新增: foreach (var file in directory.EnumerateFiles())
116新增: {
117新增: token.ThrowIfCancellationRequested();
118新增: if (file.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("editor_package_invalid");
119新增: file.CopyTo(Path.Combine(target, file.Name), false);
120新增: }
121新增: foreach (var child in directory.EnumerateDirectories()) CopyPackage(child.FullName, Path.Combine(target, child.Name), token);
122新增: }
123新增:
124新增: internal static void Revoke(string project, string grant)
125新增: {
126新增: if (Editors.TryGetValue(project, out var editor) && editor.Grant == grant &&
127新增: ((ICollection<KeyValuePair<string, Editor>>)Editors).Remove(new(project, editor))) editor.Dispose();
128新增: }
129新增: internal static void Close() { foreach (var entry in Editors) if (Editors.TryRemove(entry.Key, out var editor)) editor.Dispose(); }
130新增:
131新增: private sealed class Editor(string project, string grant, string folder, Process process) : IDisposable
132新增: {
133新增: internal string Grant { get; } = grant;
134新增: internal string Folder { get; } = folder;
135新增: internal Process Process { get; } = process;
136新增: internal Connection Connection { get; set; } = new("", project, grant, folder, "");
137新增: internal Task? Output, Errors;
138新增: internal GuestProcessJob? Job;
139新增: public void Dispose()
140新增: {
141新增: try { Process.StandardInput.Close(); if (!Process.HasExited) Process.Kill(true); Process.WaitForExit(2000); } catch (InvalidOperationException) { }
142新增: Job?.Dispose();Process.Dispose();
143新增: // Profiles, tokens and VS Code hot-exit backups remain intact.
144新增: }
145新增: }
146新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsFileDialogNative.cs+140 −0看文件
@@ -0,0 +1,140 @@
1新增:using System.Diagnostics;
2新增:using System.Collections.Concurrent;
3新增:using System.IO;
4新增:using System.Runtime.InteropServices;
5新增:using System.Security.Cryptography;
6新增:using System.Text;
7新增:
8新增:namespace Cage.GuestClipboard;
9新增:
10新增:// A private capability created from ClaudeWindowRpc's verified registration.
11新增:// No process, handle, path, or authorization predicate comes from JSON.
12新增:internal static class WindowsFileDialogNative
13新增:{
14新增: internal sealed record Owner(int PID,long Started,int Session,IntPtr Window,string Executable,Func<Process,bool> Authorized)
15新增: {
16新增: internal void Assert()
17新增: {
18新增: using var process=Process.GetProcessById(PID);
19新增: if(process.HasExited||process.StartTime.ToUniversalTime().Ticks!=Started||process.SessionId!=Session||
20新增: !string.Equals(process.MainModule?.FileName,Executable,StringComparison.OrdinalIgnoreCase)||!Authorized(process)||
21新增: !IsWindowVisible(Window)||GetWindowThreadProcessId(Window,out var pid)==0||pid!=PID)
22新增: throw new InvalidDataException("file_dialog_owner_changed");
23新增: }
24新增: }
25新增: private static readonly string Property="Cage.FileDialog."+Guid.NewGuid().ToString("N");
26新增: private static readonly ConcurrentDictionary<IntPtr,Observer> Observers=new();
27新增: [UnmanagedFunctionPointer(CallingConvention.Winapi)]
28新增: [return: MarshalAs(UnmanagedType.Bool)]
29新增: private delegate bool WindowCallback(IntPtr window, IntPtr parameter);
30新增: [DllImport("user32.dll")]
31新增: [return: MarshalAs(UnmanagedType.Bool)]
32新增: private static extern bool EnumWindows(WindowCallback callback,IntPtr parameter);
33新增: [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr window);
34新增: [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window,out uint pid);
35新增: [DllImport("user32.dll")] private static extern IntPtr GetWindow(IntPtr window,uint kind);
36新增: [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
37新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern int GetClassNameW(IntPtr window,StringBuilder value,int length);
38新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true,SetLastError=true)] private static extern bool SetPropW(IntPtr window,string name,IntPtr value);
39新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr GetPropW(IntPtr window,string name);
40新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr RemovePropW(IntPtr window,string name);
41新增: [DllImport("user32.dll")] internal static extern int GetDlgCtrlID(IntPtr window);
42新增: [DllImport("user32.dll")] internal static extern bool IsChild(IntPtr parent,IntPtr child);
43新增: [DllImport("user32.dll")] private static extern IntPtr GetDlgItem(IntPtr dialog,int id);
44新增: [DllImport("user32.dll")] private static extern bool IsWindowEnabled(IntPtr window);
45新增: [DllImport("user32.dll",ExactSpelling=true)] private static extern bool PostMessageW(IntPtr window,uint message,IntPtr parameter,IntPtr data);
46新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr SendMessageTimeoutW(IntPtr window,uint message,IntPtr parameter,string data,uint flags,uint timeout,out IntPtr result);
47新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr SendMessageTimeoutW(IntPtr window,uint message,IntPtr parameter,StringBuilder data,uint flags,uint timeout,out IntPtr result);
48新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr SendMessageTimeoutW(IntPtr window,uint message,IntPtr parameter,IntPtr data,uint flags,uint timeout,out IntPtr result);
49新增: private delegate void EventCallback(IntPtr hook,uint kind,IntPtr window,int objectID,int childID,uint thread,uint time);
50新增: [DllImport("user32.dll")] private static extern IntPtr SetWinEventHook(uint first,uint last,IntPtr module,EventCallback callback,uint process,uint thread,uint flags);
51新增: [DllImport("user32.dll")] private static extern bool UnhookWinEvent(IntPtr hook);
52新增: // Install on the GUI message thread. Keep the delegate rooted until the
53新增: // hook is removed; the callback only retires broker state, never clicks UI.
54新增: internal sealed class Observer : IDisposable
55新增: {
56新增: private IntPtr hook;
57新增: private readonly EventCallback callback;
58新增: private readonly int thread=Environment.CurrentManagedThreadId;
59新增: internal Observer(Owner owner,Action<IntPtr> destroyed)
60新增: {
61新增: owner.Assert();
62新增: callback=(_,kind,window,objectID,childID,_,_)=>{if(kind==0x8001&&objectID==0&&childID==0)destroyed(window);};
63新增: hook=SetWinEventHook(0x8001,0x8001,IntPtr.Zero,callback,(uint)owner.PID,0,0);
64新增: if(hook==IntPtr.Zero)throw new InvalidDataException("file_dialog_observer_unavailable");
65新增: Observers[hook]=this; // A failed unhook cannot release the native delegate.
66新增: }
67新增: public void Dispose()
68新增: {
69新增: if(hook==IntPtr.Zero)return;
70新增: if(Environment.CurrentManagedThreadId!=thread||!UnhookWinEvent(hook))throw new InvalidDataException("file_dialog_observer_cleanup_failed");
71新增: Observers.TryRemove(hook,out _);hook=IntPtr.Zero;GC.KeepAlive(callback);
72新增: }
73新增: }
74新增:
75新增: internal static bool Owned(Owner owner,IntPtr dialog)
76新增: {
77新增: if(!IsWindowVisible(dialog)||GetWindowThreadProcessId(dialog,out var pid)==0||pid!=owner.PID)return false;
78新增: var name=new StringBuilder(128);GetClassNameW(dialog,name,name.Capacity);if(name.ToString()!="#32770")return false;
79新增: var seen=new HashSet<IntPtr>();var parent=GetWindow(dialog,4);
80新增: while(parent!=IntPtr.Zero&&seen.Add(parent)&&seen.Count<=8){if(parent==owner.Window)return true;parent=GetWindow(parent,4);}
81新增: return false;
82新增: }
83新增: internal static IntPtr[] Candidates(Owner owner)
84新增: {
85新增: owner.Assert();var result=new List<IntPtr>();
86新增: EnumWindows((window,_)=>{if(Owned(owner,window))result.Add(window);return true;},IntPtr.Zero);
87新增: owner.Assert();return result.ToArray();
88新增: }
89新增: internal static IntPtr Stamp(Owner owner,IntPtr dialog)
90新增: {
91新增: owner.Assert();if(!Owned(owner,dialog))throw new InvalidDataException("file_dialog_owner_changed");
92新增: var bytes=RandomNumberGenerator.GetBytes(8);
93新增: var stamp=new IntPtr((long)(BitConverter.ToUInt64(bytes)&0x7fffffffffffffffUL));if(stamp==IntPtr.Zero)stamp=new IntPtr(1);
94新增: if(!SetPropW(dialog,Property,stamp))throw new InvalidDataException("file_dialog_binding_unavailable");
95新增: try{owner.Assert();if(!Owned(owner,dialog)||GetPropW(dialog,Property)!=stamp)throw new InvalidDataException("file_dialog_owner_changed");return stamp;}
96新增: catch{Remove(dialog,stamp);throw;}
97新增: }
98新增: internal static bool Alive(Owner owner,IntPtr dialog,IntPtr stamp)
99新增: {
100新增: try{owner.Assert();return Owned(owner,dialog)&&GetPropW(dialog,Property)==stamp;}
101新增: catch{return false;}
102新增: }
103新增: internal static void Assert(Owner owner,IntPtr dialog,IntPtr stamp,bool foreground)
104新增: {
105新增: if(!Alive(owner,dialog,stamp)||foreground&&GetForegroundWindow()!=dialog)throw new InvalidDataException("file_dialog_changed");
106新增: }
107新增: internal static void Remove(IntPtr dialog,IntPtr stamp)
108新增: {if(GetPropW(dialog,Property)==stamp)RemovePropW(dialog,Property);}
109新增:
110新增: internal static void Accept(Owner owner,IntPtr dialog,IntPtr stamp)
111新增: {
112新增: Assert(owner,dialog,stamp,true);
113新增: var button=GetDlgItem(dialog,1);
114新增: var name=new StringBuilder(128);GetClassNameW(button,name,name.Capacity);
115新增: if(button==IntPtr.Zero||!IsChild(dialog,button)||!IsWindowEnabled(button)||name.ToString()!="Button"||
116新增: GetWindowThreadProcessId(button,out var pid)==0||pid!=owner.PID||
117新增: !PostMessageW(button,0x00F5,IntPtr.Zero,IntPtr.Zero))throw new InvalidDataException("file_dialog_selection_invalid");
118新增: }
119新增:
120新增: internal static void SetFilename(Owner owner,IntPtr dialog,IntPtr stamp,IntPtr field,string text)
121新增: {
122新增: Assert(owner,dialog,stamp,true);
123新增: var name=new StringBuilder(128);GetClassNameW(field,name,name.Capacity);
124新增: if(text.Length>1<<20||field==IntPtr.Zero||!IsChild(dialog,field)||name.ToString()!="Edit"||
125新增: GetWindowThreadProcessId(field,out var pid)==0||pid!=owner.PID)
126新增: throw new InvalidDataException("file_dialog_selection_invalid");
127新增: // UIA ValuePattern rejects a multi-file value beyond the Edit control's
128新增: // typing limit. WM_SETTEXT supports the native selection buffer.
129新增: if(SendMessageTimeoutW(field,0x000C,IntPtr.Zero,text,0x22,2000,out var written)==IntPtr.Zero||written==IntPtr.Zero)
130新增: throw new InvalidDataException("file_dialog_input_failed");
131新增: Assert(owner,dialog,stamp,true);
132新增: if(SendMessageTimeoutW(field,0x000E,IntPtr.Zero,IntPtr.Zero,0x22,2000,out var textLength)==IntPtr.Zero||textLength.ToInt64()!=text.Length)
133新增: throw new InvalidDataException("file_dialog_selection_invalid");
134新增: var actual=new StringBuilder(text.Length+1);
135新增: if(SendMessageTimeoutW(field,0x000D,new IntPtr(actual.Capacity),actual,0x22,2000,out var length)==IntPtr.Zero||
136新增: length.ToInt64()!=text.Length||actual.ToString()!=text)
137新增: throw new InvalidDataException("file_dialog_selection_invalid");
138新增: Assert(owner,dialog,stamp,true);
139新增: }
140新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsFilePublication.cs+29 −0看文件
@@ -0,0 +1,29 @@
1新增:using System.Diagnostics;
2新增:
3新增:namespace Cage.GuestClipboard;
4新增:
5新增:// Callers own both paths and finish writing their protected stage first.
6新增:// Publish one complete snapshot while retaining the old reader and its ACL.
7新增:internal static class WindowsFilePublication
8新增:{
9新增: internal static async Task Replace(string stage,string destination,CancellationToken token)
10新增: {
11新增: var elapsed=Stopwatch.StartNew();
12新增: for(;;)
13新增: {
14新增: token.ThrowIfCancellationRequested();
15新增: try
16新增: {
17新增: if(File.Exists(destination))File.Replace(stage,destination,null);
18新增: else File.Move(stage,destination);
19新增: return;
20新增: }
21新增: catch(Exception error) when(error is IOException or UnauthorizedAccessException)
22新增: {
23新增: var code=error.HResult&0xffff;
24新增: if(code is not (5 or 32) || elapsed.Elapsed>=TimeSpan.FromSeconds(2))throw;
25新增: await Task.Delay(25,token);
26新增: }
27新增: }
28新增: }
29新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsIme.cs+85 −0看文件
@@ -0,0 +1,85 @@
1新增:using System.Security.Cryptography;
2新增:using System.Text.Json.Nodes;
3新增:using System.Windows.Automation;
4新增:
5新增:namespace Cage.GuestClipboard;
6新增:
7新增:// The Claude window owner supplies a verified process and a Unicode committer.
8新增:// UI Automation is read-only here; it never chooses an arbitrary application.
9新增:internal static class WindowsIme
10新增:{
11新增: private sealed record Focus(string Context, double[] Rect, bool Password);
12新增: private sealed record Composition(string ID, string Context, int Sequence, DateTime Updated);
13新增: private static readonly SemaphoreSlim Probes = new(1, 1);
14新增: private static Composition? composition;
15新增:
16新增: private static Focus? Probe(int process, string windowTarget, double x, double y)
17新增: {
18新增: var element = AutomationElement.FocusedElement;
19新增: if (element is null || element.Current.ProcessId != process || !element.Current.IsEnabled || element.Current.IsOffscreen)
20新增: return null;
21新增: bool editable = element.TryGetCurrentPattern(ValuePattern.Pattern, out var value) && !((ValuePattern)value).Current.IsReadOnly;
22新增: if (!editable && element.TryGetCurrentPattern(TextPattern.Pattern, out var text))
23新增: {
24新增: var readOnly = ((TextPattern)text).DocumentRange.GetAttributeValue(TextPattern.IsReadOnlyAttribute);
25新增: editable = readOnly is bool b && !b;
26新增: }
27新增: if (!editable) return null;
28新增: var bounds = element.Current.BoundingRectangle;
29新增: var rect = new double[] { bounds.X-x, bounds.Y-y, Math.Max(1,bounds.Width), Math.Max(1,bounds.Height) };
30新增: if (element.TryGetCurrentPattern(TextPattern.Pattern, out var caret))
31新增: {
32新增: var ranges = ((TextPattern)caret).GetSelection();
33新增: var geometry = ranges.Length == 1 ? ranges[0].GetBoundingRectangles() : [];
34新增: if (geometry.Length != 0) rect = [geometry[0].X-x,geometry[0].Y-y,Math.Max(1,geometry[0].Width),Math.Max(1,geometry[0].Height)];
35新增: }
36新增: var identity = windowTarget + ":" + string.Join(',',element.GetRuntimeId());
37新增: var context = Convert.ToHexString(SHA256.HashData(Protocol.Utf8.GetBytes(identity)).AsSpan(0,16)).ToLowerInvariant();
38新增: return new Focus(context,rect,element.Current.IsPassword);
39新增: }
40新增:
41新增: internal static async Task RequirePhoneFocus(JsonObject input, int process, string windowTarget, CancellationToken token)
42新增: {
43新增: if (!input.ContainsKey("phone_focus")) return;
44新增: var requested = input["phone_focus"]?.GetValue<string>() ?? "";
45新增: var focus = await Handle(new JsonObject { ["mode"] = "status" }, process, windowTarget, 0, 0,
46新增: _ => throw new InvalidDataException("desktop_phone_focus_changed"), token);
47新增: if (requested.Length == 0 || focus["available"]?.GetValue<bool>() != true ||
48新增: focus["password"]?.GetValue<bool>() == true || focus["context"]?.GetValue<string>() != requested)
49新增: throw new InvalidDataException("desktop_phone_focus_changed");
50新增: }
51新增:
52新增: internal static async Task<JsonObject> Handle(JsonObject input, int process, string windowTarget, double x, double y, Action<string> commit, CancellationToken token)
53新增: {
54新增: var mode = input["mode"]?.GetValue<string>() ?? "";
55新增: var id = input["session"]?.GetValue<string>() ?? "";
56新增: var sequence = input["sequence"]?.GetValue<int>() ?? 0;
57新增: if (mode is not ("status" or "begin" or "update" or "commit" or "cancel")) throw new InvalidDataException("input_mode_invalid");
58新增: if (mode != "status" && (id.Length != 32 || id.Any(c => !char.IsAsciiHexDigit(c)) || sequence < 0)) throw new InvalidDataException("input_session_invalid");
59新增: if (mode == "cancel")
60新增: {
61新增: if (composition?.ID == id && sequence > composition.Sequence) composition = null;
62新增: return new JsonObject { ["available"] = false };
63新增: }
64新增: if (!await Probes.WaitAsync(0,token)) return new JsonObject { ["available"] = false };
65新增: var probe = Task.Run(() => { try { return Probe(process,windowTarget,x,y); } finally { Probes.Release(); } });
66新增: Focus? focus;
67新增: try { focus = await probe.WaitAsync(TimeSpan.FromSeconds(2),token); }
68新增: catch (Exception e) when (e is not OperationCanceledException) { return new JsonObject { ["available"] = false }; }
69新增: if (focus is null || !SessionGuard.Available()) { composition = null; return new JsonObject { ["available"] = false }; }
70新增: if (composition is not null && (composition.Context != focus.Context || DateTime.UtcNow-composition.Updated > TimeSpan.FromSeconds(30))) composition = null;
71新增: JsonObject Snapshot() => new() { ["available"] = true, ["context"] = focus.Context, ["rect"] = new JsonArray(focus.Rect.Select(v => (JsonNode?)JsonValue.Create(v)).ToArray()), ["preedit_supported"] = false, ["password"] = focus.Password };
72新增: if (mode == "status") { if (composition?.ID == id) composition = composition with { Updated = DateTime.UtcNow }; return Snapshot(); }
73新增: if (mode == "begin")
74新增: {
75新增: if (input["context"]?.GetValue<string>() != focus.Context) return new JsonObject { ["available"] = false };
76新增: composition = new Composition(id,focus.Context,sequence,DateTime.UtcNow); return Snapshot();
77新增: }
78新增: if (composition?.ID != id || sequence <= composition.Sequence) return new JsonObject { ["available"] = false };
79新增: var content = input["text"]?.GetValue<string>() ?? "";
80新增: if (Protocol.Utf8.GetByteCount(content) > 8192) throw new InvalidDataException("input_text_limit");
81新增: if (mode == "commit") { commit(content); composition = null; }
82新增: else composition = composition with { Sequence = sequence, Updated = DateTime.UtcNow };
83新增: return Snapshot();
84新增: }
85新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsPhoneBrowser.cs+103 −0看文件
@@ -0,0 +1,103 @@
1新增:using System.Diagnostics;
2新增:using System.Text.Json.Nodes;
3新增:using System.Text.RegularExpressions;
4新增:using InputLease = Cage.GuestClipboard.NativeInputCoordinator.Lease;
5新增:
6新增:namespace Cage.GuestClipboard;
7新增:
8新增:// This subtree is separate from desktop Chrome. One enrollment owns the active
9新增:// phone ID; a disconnected connection never closes another ID or desktop tab.
10新增:internal static class WindowsPhoneBrowser
11新增:{
12新增: private static readonly SemaphoreSlim Gate = new(1, 1);
13新增: private static readonly Dictionary<InputLease, string> Owners = new();
14新增: private static readonly Regex ID = new("^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$", RegexOptions.CultureInvariant);
15新增: private static Process? process;
16新增: private static GuestProcessJob? job;
17新增: private static Stream? replies;
18新增: private static string current = "";
19新增: internal static bool Installed() => BrowserRpc.BrowserExecutableInstalled() && new[] { "node.exe", "windows-browser.mjs", "windows-browser-extensions.mjs", "windows-phone-browser.mjs", "playwright/index.mjs", "modules/browser-phone.mjs", "modules/browser-phone-network.mjs" }
20新增: .All(file => File.Exists(Path.Combine(AppContext.BaseDirectory, file)));
21新增:
22新增: private static JsonObject Error(int status) => new() { ["error"] = "phone_browser_unavailable", ["code"] = "phone_browser_error", ["status"] = status };
23新增: internal static async Task<JsonObject> Exchange(JsonObject request, CancellationToken connection, InputLease owner)
24新增: {
25新增: await Gate.WaitAsync(connection);
26新增: try
27新增: {
28新增: var route = request["path"]?.GetValue<string>() ?? "";
29新增: var input = request["input"] as JsonObject ?? new JsonObject();
30新增: var id = input["id"]?.GetValue<string>() ?? "";
31新增: if (!ID.IsMatch(id)) return Error(400);
32新增: if (route != "/phone-browser/open" && current != id) return Error(410);
33新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(35));
34新增: if (route == "/phone-browser/open")
35新增: {
36新增: if (!Installed()) return Error(501);
37新增: var settings = await BrowserRpc.ReadConfiguration(timeout.Token, packetOnly: true);
38新增: await Start(settings, timeout.Token);
39新增: }
40新增: if (process is not { HasExited: false }) return Error(410);
41新增: var result = await Control(request, timeout.Token);
42新增: if (result["error"] is null && route == "/phone-browser/open") { current = id; Owners[owner] = id; }
43新增: if (result["error"] is null && route == "/phone-browser/close") { current = ""; foreach (var key in Owners.Where(p => p.Value == id).Select(p => p.Key).ToArray()) Owners.Remove(key); }
44新增: return result;
45新增: }
46新增: catch (InvalidDataException) { return Error(503); }
47新增: catch (Exception error) when (error is OperationCanceledException or EndOfStreamException or IOException)
48新增: { Close(); return Error(503); }
49新增: finally { Gate.Release(); }
50新增: }
51新增: internal static async Task Release(InputLease owner)
52新增: {
53新增: await Gate.WaitAsync();
54新增: try
55新增: {
56新增: if (!Owners.Remove(owner, out var id) || Owners.Values.Contains(id) || current != id) return;
57新增: try
58新增: {
59新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
60新增: await Control(new JsonObject { ["method"] = "POST", ["path"] = "/phone-browser/close", ["input"] = new JsonObject { ["id"] = id } }, timeout.Token);
61新增: current = "";
62新增: }
63新增: catch { Close(); }
64新增: }
65新增: finally { Gate.Release(); }
66新增: }
67新增: private static async Task Start(JsonObject settings, CancellationToken token)
68新增: {
69新增: if (process is { HasExited: false }) return;
70新增: Close();
71新增: var start = new ProcessStartInfo(Path.Combine(AppContext.BaseDirectory, "node.exe"))
72新增: {
73新增: UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = AppContext.BaseDirectory,
74新增: RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true,
75新增: StandardInputEncoding = Protocol.Utf8, StandardOutputEncoding = Protocol.Utf8, StandardErrorEncoding = Protocol.Utf8,
76新增: };
77新增: start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "windows-phone-browser.mjs"));
78新增: process = Process.Start(start) ?? throw new InvalidDataException("browser_unavailable");
79新增: try
80新增: {
81新增: job = new GuestProcessJob(process);
82新增: replies = new ReadAheadStream(process.StandardOutput.BaseStream);
83新增: var source = process.StandardError;
84新增: _ = Task.Run(async () => { try { var buffer = new char[4096]; while (await source.ReadAsync(buffer) != 0) { } } catch (ObjectDisposedException) { } });
85新增: var result = await Control(new JsonObject { ["operation"] = "configure", ["input"] = settings }, token);
86新增: if (result["ok"]?.GetValue<bool>() != true) throw new InvalidDataException("browser_unavailable");
87新增: }
88新增: catch { Close(); throw; }
89新增: }
90新增: private static async Task<JsonObject> Control(JsonObject input, CancellationToken token)
91新增: {
92新增: await Protocol.Write(process!.StandardInput.BaseStream, input, token);
93新增: return await Protocol.Read(replies!, 3 << 20, token) ?? throw new EndOfStreamException();
94新增: }
95新增: internal static void Close()
96新增: {
97新增: var owned = Interlocked.Exchange(ref process, null); current = ""; Owners.Clear();
98新增: try { if (owned is not null) { owned.StandardInput.Close(); if (!owned.WaitForExit(3000)) owned.Kill(true); owned.WaitForExit(2000); } }
99新增: catch (InvalidOperationException) { }
100新增: finally { job?.Dispose(); job = null; replies?.Dispose(); replies = null; owned?.Dispose(); }
101新增: // Enrollment profile directories remain intact.
102新增: }
103新增:}
新增scripts/guest-os/guest-clipboard-windows/WindowsSystemSettings.cs+80 −0看文件
@@ -0,0 +1,80 @@
1新增:using System.Diagnostics;
2新增:using System.Globalization;
3新增:using System.Security.AccessControl;
4新增:using System.Security.Principal;
5新增:using System.Text.Json.Nodes;
6新增:using System.Text.RegularExpressions;
7新增:
8新增:namespace 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.
12新增:internal 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新增:}
新增scripts/guest-os/guest-clipboard-windows/ccs-runtime/package-lock.json+2222 −0看文件
@@ -0,0 +1,2222 @@
1新增:{
2新增: "name": "cage-windows-ccs-runtime",
3新增: "version": "1.0.0",
4新增: "lockfileVersion": 3,
5新增: "requires": true,
6新增: "packages": {
7新增: "": {
8新增: "name": "cage-windows-ccs-runtime",
9新增: "version": "1.0.0",
10新增: "dependencies": {
11新增: "@kaitranntt/ccs": "8.11.0"
12新增: }
13新增: },
14新增: "node_modules/@colors/colors": {
15新增: "version": "1.5.0",
16新增: "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
17新增: "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==",
18新增: "license": "MIT",
19新增: "optional": true,
20新增: "engines": {
21新增: "node": ">=0.1.90"
22新增: }
23新增: },
24新增: "node_modules/@fastify/busboy": {
25新增: "version": "2.1.1",
26新增: "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz",
27新增: "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==",
28新增: "license": "MIT",
29新增: "engines": {
30新增: "node": ">=14"
31新增: }
32新增: },
33新增: "node_modules/@kaitranntt/ccs": {
34新增: "version": "8.11.0",
35新增: "resolved": "https://registry.npmjs.org/@kaitranntt/ccs/-/ccs-8.11.0.tgz",
36新增: "integrity": "sha512-0NQs/rsLbFek7LVGL7a6cr+MTbdAwU9dBlHdMiXecB1dNyVKlEf8pBEko1ozkZv05jMaRcUYY+IaYDpS6n6YyQ==",
37新增: "hasInstallScript": true,
38新增: "license": "MIT",
39新增: "os": [
40新增: "darwin",
41新增: "linux",
42新增: "win32"
43新增: ],
44新增: "dependencies": {
45新增: "bcrypt": "^6.0.0",
46新增: "boxen": "^5.1.2",
47新增: "chalk": "^4.1.2",
48新增: "chokidar": "^3.6.0",
49新增: "cli-table3": "^0.6.5",
50新增: "express": "^4.18.2",
51新增: "express-rate-limit": "^8.2.1",
52新增: "express-session": "^1.18.2",
53新增: "get-port": "^5.1.1",
54新增: "gradient-string": "^2.0.2",
55新增: "http-proxy-agent": "^7.0.2",
56新增: "https-proxy-agent": "^7.0.6",
57新增: "js-yaml": "^4.1.1",
58新增: "listr2": "^3.14.0",
59新增: "open": "^8.4.2",
60新增: "ora": "^5.4.1",
61新增: "proper-lockfile": "^4.1.2",
62新增: "smol-toml": "^1.6.1",
63新增: "undici": "^5.29.0",
64新增: "ws": "^8.16.0"
65新增: },
66新增: "bin": {
67新增: "ccs": "dist/ccs.js",
68新增: "ccs-codex": "dist/bin/codex-runtime.js",
69新增: "ccs-droid": "dist/bin/droid-runtime.js",
70新增: "ccsd": "dist/bin/droid-runtime.js",
71新增: "ccsx": "dist/bin/codex-runtime.js",
72新增: "ccsxp": "dist/bin/ccsxp-runtime.js"
73新增: },
74新增: "engines": {
75新增: "bun": ">=1.0.0",
76新增: "node": ">=18.0.0"
77新增: }
78新增: },
79新增: "node_modules/@types/tinycolor2": {
80新增: "version": "1.4.6",
81新增: "resolved": "https://registry.npmjs.org/@types/tinycolor2/-/tinycolor2-1.4.6.tgz",
82新增: "integrity": "sha512-iEN8J0BoMnsWBqjVbWH/c0G0Hh7O21lpR2/+PrvAVgWdzL7eexIFm4JN/Wn10PTcmNdtS6U67r499mlWMXOxNw==",
83新增: "license": "MIT"
84新增: },
85新增: "node_modules/accepts": {
86新增: "version": "1.3.8",
87新增: "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
88新增: "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
89新增: "license": "MIT",
90新增: "dependencies": {
91新增: "mime-types": "~2.1.34",
92新增: "negotiator": "0.6.3"
93新增: },
94新增: "engines": {
95新增: "node": ">= 0.6"
96新增: }
97新增: },
98新增: "node_modules/agent-base": {
99新增: "version": "7.1.4",
100新增: "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
101新增: "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
102新增: "license": "MIT",
103新增: "engines": {
104新增: "node": ">= 14"
105新增: }
106新增: },
107新增: "node_modules/aggregate-error": {
108新增: "version": "3.1.0",
109新增: "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz",
110新增: "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==",
111新增: "license": "MIT",
112新增: "dependencies": {
113新增: "clean-stack": "^2.0.0",
114新增: "indent-string": "^4.0.0"
115新增: },
116新增: "engines": {
117新增: "node": ">=8"
118新增: }
119新增: },
120新增: "node_modules/ansi-align": {
121新增: "version": "3.0.1",
122新增: "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-3.0.1.tgz",
123新增: "integrity": "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==",
124新增: "license": "ISC",
125新增: "dependencies": {
126新增: "string-width": "^4.1.0"
127新增: }
128新增: },
129新增: "node_modules/ansi-escapes": {
130新增: "version": "4.3.2",
131新增: "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz",
132新增: "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==",
133新增: "license": "MIT",
134新增: "dependencies": {
135新增: "type-fest": "^0.21.3"
136新增: },
137新增: "engines": {
138新增: "node": ">=8"
139新增: },
140新增: "funding": {
141新增: "url": "https://github.com/sponsors/sindresorhus"
142新增: }
143新增: },
144新增: "node_modules/ansi-escapes/node_modules/type-fest": {
145新增: "version": "0.21.3",
146新增: "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz",
147新增: "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==",
148新增: "license": "(MIT OR CC0-1.0)",
149新增: "engines": {
150新增: "node": ">=10"
151新增: },
152新增: "funding": {
153新增: "url": "https://github.com/sponsors/sindresorhus"
154新增: }
155新增: },
156新增: "node_modules/ansi-regex": {
157新增: "version": "5.0.1",
158新增: "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
159新增: "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
160新增: "license": "MIT",
161新增: "engines": {
162新增: "node": ">=8"
163新增: }
164新增: },
165新增: "node_modules/ansi-styles": {
166新增: "version": "4.3.0",
167新增: "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
168新增: "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
169新增: "license": "MIT",
170新增: "dependencies": {
171新增: "color-convert": "^2.0.1"
172新增: },
173新增: "engines": {
174新增: "node": ">=8"
175新增: },
176新增: "funding": {
177新增: "url": "https://github.com/chalk/ansi-styles?sponsor=1"
178新增: }
179新增: },
180新增: "node_modules/anymatch": {
181新增: "version": "3.1.3",
182新增: "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
183新增: "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
184新增: "license": "ISC",
185新增: "dependencies": {
186新增: "normalize-path": "^3.0.0",
187新增: "picomatch": "^2.0.4"
188新增: },
189新增: "engines": {
190新增: "node": ">= 8"
191新增: }
192新增: },
193新增: "node_modules/argparse": {
194新增: "version": "2.0.1",
195新增: "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
196新增: "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
197新增: "license": "Python-2.0"
198新增: },
199新增: "node_modules/array-flatten": {
200新增: "version": "1.1.1",
201新增: "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
202新增: "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
203新增: "license": "MIT"
204新增: },
205新增: "node_modules/astral-regex": {
206新增: "version": "2.0.0",
207新增: "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz",
208新增: "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==",
209新增: "license": "MIT",
210新增: "engines": {
211新增: "node": ">=8"
212新增: }
213新增: },
214新增: "node_modules/base64-js": {
215新增: "version": "1.5.1",
216新增: "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
217新增: "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
218新增: "funding": [
219新增: {
220新增: "type": "github",
221新增: "url": "https://github.com/sponsors/feross"
222新增: },
223新增: {
224新增: "type": "patreon",
225新增: "url": "https://www.patreon.com/feross"
226新增: },
227新增: {
228新增: "type": "consulting",
229新增: "url": "https://feross.org/support"
230新增: }
231新增: ],
232新增: "license": "MIT"
233新增: },
234新增: "node_modules/bcrypt": {
235新增: "version": "6.0.0",
236新增: "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-6.0.0.tgz",
237新增: "integrity": "sha512-cU8v/EGSrnH+HnxV2z0J7/blxH8gq7Xh2JFT6Aroax7UohdmiJJlxApMxtKfuI7z68NvvVcmR78k2LbT6efhRg==",
238新增: "hasInstallScript": true,
239新增: "license": "MIT",
240新增: "dependencies": {
241新增: "node-addon-api": "^8.3.0",
242新增: "node-gyp-build": "^4.8.4"
243新增: },
244新增: "engines": {
245新增: "node": ">= 18"
246新增: }
247新增: },
248新增: "node_modules/binary-extensions": {
249新增: "version": "2.3.0",
250新增: "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
251新增: "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",
252新增: "license": "MIT",
253新增: "engines": {
254新增: "node": ">=8"
255新增: },
256新增: "funding": {
257新增: "url": "https://github.com/sponsors/sindresorhus"
258新增: }
259新增: },
260新增: "node_modules/bl": {
261新增: "version": "4.1.0",
262新增: "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
263新增: "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
264新增: "license": "MIT",
265新增: "dependencies": {
266新增: "buffer": "^5.5.0",
267新增: "inherits": "^2.0.4",
268新增: "readable-stream": "^3.4.0"
269新增: }
270新增: },
271新增: "node_modules/body-parser": {
272新增: "version": "1.20.9",
273新增: "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz",
274新增: "integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==",
275新增: "license": "MIT",
276新增: "dependencies": {
277新增: "bytes": "~3.1.2",
278新增: "content-type": "~1.0.5",
279新增: "debug": "2.6.9",
280新增: "depd": "2.0.0",
281新增: "destroy": "~1.2.0",
282新增: "http-errors": "~2.0.1",
283新增: "iconv-lite": "~0.4.24",
284新增: "on-finished": "~2.4.1",
285新增: "qs": "~6.16.0",
286新增: "raw-body": "~2.5.3",
287新增: "type-is": "~1.6.18",
288新增: "unpipe": "~1.0.0"
289新增: },
290新增: "engines": {
291新增: "node": ">= 0.8",
292新增: "npm": "1.2.8000 || >= 1.4.16"
293新增: }
294新增: },
295新增: "node_modules/boxen": {
296新增: "version": "5.1.2",
297新增: "resolved": "https://registry.npmjs.org/boxen/-/boxen-5.1.2.tgz",
298新增: "integrity": "sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ==",
299新增: "license": "MIT",
300新增: "dependencies": {
301新增: "ansi-align": "^3.0.0",
302新增: "camelcase": "^6.2.0",
303新增: "chalk": "^4.1.0",
304新增: "cli-boxes": "^2.2.1",
305新增: "string-width": "^4.2.2",
306新增: "type-fest": "^0.20.2",
307新增: "widest-line": "^3.1.0",
308新增: "wrap-ansi": "^7.0.0"
309新增: },
310新增: "engines": {
311新增: "node": ">=10"
312新增: },
313新增: "funding": {
314新增: "url": "https://github.com/sponsors/sindresorhus"
315新增: }
316新增: },
317新增: "node_modules/braces": {
318新增: "version": "3.0.3",
319新增: "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
320新增: "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
321新增: "license": "MIT",
322新增: "dependencies": {
323新增: "fill-range": "^7.1.1"
324新增: },
325新增: "engines": {
326新增: "node": ">=8"
327新增: }
328新增: },
329新增: "node_modules/buffer": {
330新增: "version": "5.7.1",
331新增: "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
332新增: "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
333新增: "funding": [
334新增: {
335新增: "type": "github",
336新增: "url": "https://github.com/sponsors/feross"
337新增: },
338新增: {
339新增: "type": "patreon",
340新增: "url": "https://www.patreon.com/feross"
341新增: },
342新增: {
343新增: "type": "consulting",
344新增: "url": "https://feross.org/support"
345新增: }
346新增: ],
347新增: "license": "MIT",
348新增: "dependencies": {
349新增: "base64-js": "^1.3.1",
350新增: "ieee754": "^1.1.13"
351新增: }
352新增: },
353新增: "node_modules/bytes": {
354新增: "version": "3.1.2",
355新增: "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
356新增: "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
357新增: "license": "MIT",
358新增: "engines": {
359新增: "node": ">= 0.8"
360新增: }
361新增: },
362新增: "node_modules/call-bind-apply-helpers": {
363新增: "version": "1.0.2",
364新增: "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
365新增: "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
366新增: "license": "MIT",
367新增: "dependencies": {
368新增: "es-errors": "^1.3.0",
369新增: "function-bind": "^1.1.2"
370新增: },
371新增: "engines": {
372新增: "node": ">= 0.4"
373新增: }
374新增: },
375新增: "node_modules/call-bound": {
376新增: "version": "1.0.4",
377新增: "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
378新增: "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
379新增: "license": "MIT",
380新增: "dependencies": {
381新增: "call-bind-apply-helpers": "^1.0.2",
382新增: "get-intrinsic": "^1.3.0"
383新增: },
384新增: "engines": {
385新增: "node": ">= 0.4"
386新增: },
387新增: "funding": {
388新增: "url": "https://github.com/sponsors/ljharb"
389新增: }
390新增: },
391新增: "node_modules/camelcase": {
392新增: "version": "6.3.0",
393新增: "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",
394新增: "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",
395新增: "license": "MIT",
396新增: "engines": {
397新增: "node": ">=10"
398新增: },
399新增: "funding": {
400新增: "url": "https://github.com/sponsors/sindresorhus"
401新增: }
402新增: },
403新增: "node_modules/chalk": {
404新增: "version": "4.1.2",
405新增: "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
406新增: "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
407新增: "license": "MIT",
408新增: "dependencies": {
409新增: "ansi-styles": "^4.1.0",
410新增: "supports-color": "^7.1.0"
411新增: },
412新增: "engines": {
413新增: "node": ">=10"
414新增: },
415新增: "funding": {
416新增: "url": "https://github.com/chalk/chalk?sponsor=1"
417新增: }
418新增: },
419新增: "node_modules/chokidar": {
420新增: "version": "3.6.0",
421新增: "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
422新增: "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
423新增: "license": "MIT",
424新增: "dependencies": {
425新增: "anymatch": "~3.1.2",
426新增: "braces": "~3.0.2",
427新增: "glob-parent": "~5.1.2",
428新增: "is-binary-path": "~2.1.0",
429新增: "is-glob": "~4.0.1",
430新增: "normalize-path": "~3.0.0",
431新增: "readdirp": "~3.6.0"
432新增: },
433新增: "engines": {
434新增: "node": ">= 8.10.0"
435新增: },
436新增: "funding": {
437新增: "url": "https://paulmillr.com/funding/"
438新增: },
439新增: "optionalDependencies": {
440新增: "fsevents": "~2.3.2"
441新增: }
442新增: },
443新增: "node_modules/clean-stack": {
444新增: "version": "2.2.0",
445新增: "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz",
446新增: "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==",
447新增: "license": "MIT",
448新增: "engines": {
449新增: "node": ">=6"
450新增: }
451新增: },
452新增: "node_modules/cli-boxes": {
453新增: "version": "2.2.1",
454新增: "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-2.2.1.tgz",
455新增: "integrity": "sha512-y4coMcylgSCdVinjiDBuR8PCC2bLjyGTwEmPb9NHR/QaNU6EUOXcTY/s6VjGMD6ENSEaeQYHCY0GNGS5jfMwPw==",
456新增: "license": "MIT",
457新增: "engines": {
458新增: "node": ">=6"
459新增: },
460新增: "funding": {
461新增: "url": "https://github.com/sponsors/sindresorhus"
462新增: }
463新增: },
464新增: "node_modules/cli-cursor": {
465新增: "version": "3.1.0",
466新增: "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz",
467新增: "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==",
468新增: "license": "MIT",
469新增: "dependencies": {
470新增: "restore-cursor": "^3.1.0"
471新增: },
472新增: "engines": {
473新增: "node": ">=8"
474新增: }
475新增: },
476新增: "node_modules/cli-spinners": {
477新增: "version": "2.9.2",
478新增: "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz",
479新增: "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==",
480新增: "license": "MIT",
481新增: "engines": {
482新增: "node": ">=6"
483新增: },
484新增: "funding": {
485新增: "url": "https://github.com/sponsors/sindresorhus"
486新增: }
487新增: },
488新增: "node_modules/cli-table3": {
489新增: "version": "0.6.5",
490新增: "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz",
491新增: "integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==",
492新增: "license": "MIT",
493新增: "dependencies": {
494新增: "string-width": "^4.2.0"
495新增: },
496新增: "engines": {
497新增: "node": "10.* || >= 12.*"
498新增: },
499新增: "optionalDependencies": {
500新增: "@colors/colors": "1.5.0"
501新增: }
502新增: },
503新增: "node_modules/cli-truncate": {
504新增: "version": "2.1.0",
505新增: "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz",
506新增: "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==",
507新增: "license": "MIT",
508新增: "dependencies": {
509新增: "slice-ansi": "^3.0.0",
510新增: "string-width": "^4.2.0"
511新增: },
512新增: "engines": {
513新增: "node": ">=8"
514新增: },
515新增: "funding": {
516新增: "url": "https://github.com/sponsors/sindresorhus"
517新增: }
518新增: },
519新增: "node_modules/clone": {
520新增: "version": "1.0.4",
521新增: "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz",
522新增: "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==",
523新增: "license": "MIT",
524新增: "engines": {
525新增: "node": ">=0.8"
526新增: }
527新增: },
528新增: "node_modules/color-convert": {
529新增: "version": "2.0.1",
530新增: "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
531新增: "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
532新增: "license": "MIT",
533新增: "dependencies": {
534新增: "color-name": "~1.1.4"
535新增: },
536新增: "engines": {
537新增: "node": ">=7.0.0"
538新增: }
539新增: },
540新增: "node_modules/color-name": {
541新增: "version": "1.1.4",
542新增: "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
543新增: "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
544新增: "license": "MIT"
545新增: },
546新增: "node_modules/colorette": {
547新增: "version": "2.0.20",
548新增: "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
549新增: "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
550新增: "license": "MIT"
551新增: },
552新增: "node_modules/content-disposition": {
553新增: "version": "0.5.4",
554新增: "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
555新增: "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
556新增: "license": "MIT",
557新增: "dependencies": {
558新增: "safe-buffer": "5.2.1"
559新增: },
560新增: "engines": {
561新增: "node": ">= 0.6"
562新增: }
563新增: },
564新增: "node_modules/content-type": {
565新增: "version": "1.0.5",
566新增: "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
567新增: "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
568新增: "license": "MIT",
569新增: "engines": {
570新增: "node": ">= 0.6"
571新增: }
572新增: },
573新增: "node_modules/cookie": {
574新增: "version": "0.7.2",
575新增: "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
576新增: "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
577新增: "license": "MIT",
578新增: "engines": {
579新增: "node": ">= 0.6"
580新增: }
581新增: },
582新增: "node_modules/cookie-signature": {
583新增: "version": "1.0.7",
584新增: "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
585新增: "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
586新增: "license": "MIT"
587新增: },
588新增: "node_modules/debug": {
589新增: "version": "2.6.9",
590新增: "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
591新增: "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
592新增: "license": "MIT",
593新增: "dependencies": {
594新增: "ms": "2.0.0"
595新增: }
596新增: },
597新增: "node_modules/defaults": {
598新增: "version": "1.0.4",
599新增: "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz",
600新增: "integrity": "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==",
601新增: "license": "MIT",
602新增: "dependencies": {
603新增: "clone": "^1.0.2"
604新增: },
605新增: "funding": {
606新增: "url": "https://github.com/sponsors/sindresorhus"
607新增: }
608新增: },
609新增: "node_modules/define-lazy-prop": {
610新增: "version": "2.0.0",
611新增: "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz",
612新增: "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==",
613新增: "license": "MIT",
614新增: "engines": {
615新增: "node": ">=8"
616新增: }
617新增: },
618新增: "node_modules/depd": {
619新增: "version": "2.0.0",
620新增: "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
621新增: "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
622新增: "license": "MIT",
623新增: "engines": {
624新增: "node": ">= 0.8"
625新增: }
626新增: },
627新增: "node_modules/destroy": {
628新增: "version": "1.2.0",
629新增: "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
630新增: "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
631新增: "license": "MIT",
632新增: "engines": {
633新增: "node": ">= 0.8",
634新增: "npm": "1.2.8000 || >= 1.4.16"
635新增: }
636新增: },
637新增: "node_modules/dunder-proto": {
638新增: "version": "1.0.1",
639新增: "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
640新增: "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
641新增: "license": "MIT",
642新增: "dependencies": {
643新增: "call-bind-apply-helpers": "^1.0.1",
644新增: "es-errors": "^1.3.0",
645新增: "gopd": "^1.2.0"
646新增: },
647新增: "engines": {
648新增: "node": ">= 0.4"
649新增: }
650新增: },
651新增: "node_modules/ee-first": {
652新增: "version": "1.1.1",
653新增: "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
654新增: "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
655新增: "license": "MIT"
656新增: },
657新增: "node_modules/emoji-regex": {
658新增: "version": "8.0.0",
659新增: "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
660新增: "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
661新增: "license": "MIT"
662新增: },
663新增: "node_modules/encodeurl": {
664新增: "version": "2.0.1",
665新增: "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.1.tgz",
666新增: "integrity": "sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==",
667新增: "license": "MIT",
668新增: "engines": {
669新增: "node": ">= 0.8"
670新增: },
671新增: "funding": {
672新增: "type": "opencollective",
673新增: "url": "https://opencollective.com/express"
674新增: }
675新增: },
676新增: "node_modules/es-define-property": {
677新增: "version": "1.0.1",
678新增: "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
679新增: "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
680新增: "license": "MIT",
681新增: "engines": {
682新增: "node": ">= 0.4"
683新增: }
684新增: },
685新增: "node_modules/es-errors": {
686新增: "version": "1.3.0",
687新增: "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
688新增: "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
689新增: "license": "MIT",
690新增: "engines": {
691新增: "node": ">= 0.4"
692新增: }
693新增: },
694新增: "node_modules/es-object-atoms": {
695新增: "version": "1.1.2",
696新增: "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
697新增: "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
698新增: "license": "MIT",
699新增: "dependencies": {
700新增: "es-errors": "^1.3.0"
701新增: },
702新增: "engines": {
703新增: "node": ">= 0.4"
704新增: }
705新增: },
706新增: "node_modules/escape-html": {
707新增: "version": "1.0.3",
708新增: "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
709新增: "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
710新增: "license": "MIT"
711新增: },
712新增: "node_modules/etag": {
713新增: "version": "1.8.1",
714新增: "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
715新增: "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
716新增: "license": "MIT",
717新增: "engines": {
718新增: "node": ">= 0.6"
719新增: }
720新增: },
721新增: "node_modules/express": {
722新增: "version": "4.22.3",
723新增: "resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz",
724新增: "integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==",
725新增: "license": "MIT",
726新增: "dependencies": {
727新增: "accepts": "~1.3.8",
728新增: "array-flatten": "1.1.1",
729新增: "body-parser": "~1.20.5",
730新增: "content-disposition": "~0.5.4",
731新增: "content-type": "~1.0.4",
732新增: "cookie": "~0.7.1",
733新增: "cookie-signature": "~1.0.6",
734新增: "debug": "2.6.9",
735新增: "depd": "2.0.0",
736新增: "encodeurl": "~2.0.0",
737新增: "escape-html": "~1.0.3",
738新增: "etag": "~1.8.1",
739新增: "finalhandler": "~1.3.1",
740新增: "fresh": "~0.5.2",
741新增: "http-errors": "~2.0.0",
742新增: "merge-descriptors": "1.0.3",
743新增: "methods": "~1.1.2",
744新增: "on-finished": "~2.4.1",
745新增: "parseurl": "~1.3.3",
746新增: "path-to-regexp": "~0.1.13",
747新增: "proxy-addr": "~2.0.7",
748新增: "qs": "~6.16.0",
749新增: "range-parser": "~1.2.1",
750新增: "safe-buffer": "5.2.1",
751新增: "send": "~0.19.0",
752新增: "serve-static": "~1.16.2",
753新增: "setprototypeof": "1.2.0",
754新增: "statuses": "~2.0.1",
755新增: "type-is": "~1.6.18",
756新增: "utils-merge": "1.0.1",
757新增: "vary": "~1.1.2"
758新增: },
759新增: "engines": {
760新增: "node": ">= 0.10.0"
761新增: },
762新增: "funding": {
763新增: "type": "opencollective",
764新增: "url": "https://opencollective.com/express"
765新增: }
766新增: },
767新增: "node_modules/express-rate-limit": {
768新增: "version": "8.7.3",
769新增: "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.3.tgz",
770新增: "integrity": "sha512-zPLqDI2f0gV2WmGnacLf9XSSqn4VldRyP5LCzOwx0BKH40mO6+2PCFkoSsRO2jePx87/Kf6NUF6P2QOTKXHbQA==",
771新增: "license": "MIT",
772新增: "dependencies": {
773新增: "debug": "^4.4.3",
774新增: "ip-address": "^10.2.0"
775新增: },
776新增: "engines": {
777新增: "node": ">= 16"
778新增: },
779新增: "funding": {
780新增: "url": "https://github.com/sponsors/express-rate-limit"
781新增: },
782新增: "peerDependencies": {
783新增: "express": ">= 4.11"
784新增: }
785新增: },
786新增: "node_modules/express-rate-limit/node_modules/debug": {
787新增: "version": "4.4.3",
788新增: "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
789新增: "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
790新增: "license": "MIT",
791新增: "dependencies": {
792新增: "ms": "^2.1.3"
793新增: },
794新增: "engines": {
795新增: "node": ">=6.0"
796新增: },
797新增: "peerDependenciesMeta": {
798新增: "supports-color": {
799新增: "optional": true
800新增: }
801新增: }
802新增: },
803新增: "node_modules/express-rate-limit/node_modules/ms": {
804新增: "version": "2.1.3",
805新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
806新增: "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
807新增: "license": "MIT"
808新增: },
809新增: "node_modules/express-session": {
810新增: "version": "1.19.0",
811新增: "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.19.0.tgz",
812新增: "integrity": "sha512-0csaMkGq+vaiZTmSMMGkfdCOabYv192VbytFypcvI0MANrp+4i/7yEkJ0sbAEhycQjntaKGzYfjfXQyVb7BHMA==",
813新增: "license": "MIT",
814新增: "dependencies": {
815新增: "cookie": "~0.7.2",
816新增: "cookie-signature": "~1.0.7",
817新增: "debug": "~2.6.9",
818新增: "depd": "~2.0.0",
819新增: "on-headers": "~1.1.0",
820新增: "parseurl": "~1.3.3",
821新增: "safe-buffer": "~5.2.1",
822新增: "uid-safe": "~2.1.5"
823新增: },
824新增: "engines": {
825新增: "node": ">= 0.8.0"
826新增: },
827新增: "funding": {
828新增: "type": "opencollective",
829新增: "url": "https://opencollective.com/express"
830新增: }
831新增: },
832新增: "node_modules/fill-range": {
833新增: "version": "7.1.1",
834新增: "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
835新增: "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
836新增: "license": "MIT",
837新增: "dependencies": {
838新增: "to-regex-range": "^5.0.1"
839新增: },
840新增: "engines": {
841新增: "node": ">=8"
842新增: }
843新增: },
844新增: "node_modules/finalhandler": {
845新增: "version": "1.3.2",
846新增: "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
847新增: "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
848新增: "license": "MIT",
849新增: "dependencies": {
850新增: "debug": "2.6.9",
851新增: "encodeurl": "~2.0.0",
852新增: "escape-html": "~1.0.3",
853新增: "on-finished": "~2.4.1",
854新增: "parseurl": "~1.3.3",
855新增: "statuses": "~2.0.2",
856新增: "unpipe": "~1.0.0"
857新增: },
858新增: "engines": {
859新增: "node": ">= 0.8"
860新增: }
861新增: },
862新增: "node_modules/forwarded": {
863新增: "version": "0.2.0",
864新增: "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
865新增: "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
866新增: "license": "MIT",
867新增: "engines": {
868新增: "node": ">= 0.6"
869新增: }
870新增: },
871新增: "node_modules/fresh": {
872新增: "version": "0.5.2",
873新增: "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
874新增: "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
875新增: "license": "MIT",
876新增: "engines": {
877新增: "node": ">= 0.6"
878新增: }
879新增: },
880新增: "node_modules/fsevents": {
881新增: "version": "2.3.3",
882新增: "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
883新增: "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
884新增: "hasInstallScript": true,
885新增: "license": "MIT",
886新增: "optional": true,
887新增: "os": [
888新增: "darwin"
889新增: ],
890新增: "engines": {
891新增: "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
892新增: }
893新增: },
894新增: "node_modules/function-bind": {
895新增: "version": "1.1.2",
896新增: "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
897新增: "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
898新增: "license": "MIT",
899新增: "funding": {
900新增: "url": "https://github.com/sponsors/ljharb"
901新增: }
902新增: },
903新增: "node_modules/get-intrinsic": {
904新增: "version": "1.3.0",
905新增: "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
906新增: "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
907新增: "license": "MIT",
908新增: "dependencies": {
909新增: "call-bind-apply-helpers": "^1.0.2",
910新增: "es-define-property": "^1.0.1",
911新增: "es-errors": "^1.3.0",
912新增: "es-object-atoms": "^1.1.1",
913新增: "function-bind": "^1.1.2",
914新增: "get-proto": "^1.0.1",
915新增: "gopd": "^1.2.0",
916新增: "has-symbols": "^1.1.0",
917新增: "hasown": "^2.0.2",
918新增: "math-intrinsics": "^1.1.0"
919新增: },
920新增: "engines": {
921新增: "node": ">= 0.4"
922新增: },
923新增: "funding": {
924新增: "url": "https://github.com/sponsors/ljharb"
925新增: }
926新增: },
927新增: "node_modules/get-port": {
928新增: "version": "5.1.1",
929新增: "resolved": "https://registry.npmjs.org/get-port/-/get-port-5.1.1.tgz",
930新增: "integrity": "sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==",
931新增: "license": "MIT",
932新增: "engines": {
933新增: "node": ">=8"
934新增: },
935新增: "funding": {
936新增: "url": "https://github.com/sponsors/sindresorhus"
937新增: }
938新增: },
939新增: "node_modules/get-proto": {
940新增: "version": "1.0.1",
941新增: "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
942新增: "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
943新增: "license": "MIT",
944新增: "dependencies": {
945新增: "dunder-proto": "^1.0.1",
946新增: "es-object-atoms": "^1.0.0"
947新增: },
948新增: "engines": {
949新增: "node": ">= 0.4"
950新增: }
951新增: },
952新增: "node_modules/glob-parent": {
953新增: "version": "5.1.2",
954新增: "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
955新增: "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
956新增: "license": "ISC",
957新增: "dependencies": {
958新增: "is-glob": "^4.0.1"
959新增: },
960新增: "engines": {
961新增: "node": ">= 6"
962新增: }
963新增: },
964新增: "node_modules/gopd": {
965新增: "version": "1.2.0",
966新增: "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
967新增: "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
968新增: "license": "MIT",
969新增: "engines": {
970新增: "node": ">= 0.4"
971新增: },
972新增: "funding": {
973新增: "url": "https://github.com/sponsors/ljharb"
974新增: }
975新增: },
976新增: "node_modules/graceful-fs": {
977新增: "version": "4.2.11",
978新增: "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
979新增: "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
980新增: "license": "ISC"
981新增: },
982新增: "node_modules/gradient-string": {
983新增: "version": "2.0.2",
984新增: "resolved": "https://registry.npmjs.org/gradient-string/-/gradient-string-2.0.2.tgz",
985新增: "integrity": "sha512-rEDCuqUQ4tbD78TpzsMtt5OIf0cBCSDWSJtUDaF6JsAh+k0v9r++NzxNEG87oDZx9ZwGhD8DaezR2L/yrw0Jdw==",
986新增: "license": "MIT",
987新增: "dependencies": {
988新增: "chalk": "^4.1.2",
989新增: "tinygradient": "^1.1.5"
990新增: },
991新增: "engines": {
992新增: "node": ">=10"
993新增: }
994新增: },
995新增: "node_modules/has-flag": {
996新增: "version": "4.0.0",
997新增: "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
998新增: "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
999新增: "license": "MIT",
1000新增: "engines": {
1001新增: "node": ">=8"
1002新增: }
1003新增: },
1004新增: "node_modules/has-symbols": {
1005新增: "version": "1.1.0",
1006新增: "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
1007新增: "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
1008新增: "license": "MIT",
1009新增: "engines": {
1010新增: "node": ">= 0.4"
1011新增: },
1012新增: "funding": {
1013新增: "url": "https://github.com/sponsors/ljharb"
1014新增: }
1015新增: },
1016新增: "node_modules/hasown": {
1017新增: "version": "2.0.4",
1018新增: "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
1019新增: "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
1020新增: "license": "MIT",
1021新增: "dependencies": {
1022新增: "function-bind": "^1.1.2"
1023新增: },
1024新增: "engines": {
1025新增: "node": ">= 0.4"
1026新增: }
1027新增: },
1028新增: "node_modules/http-errors": {
1029新增: "version": "2.0.1",
1030新增: "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
1031新增: "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
1032新增: "license": "MIT",
1033新增: "dependencies": {
1034新增: "depd": "~2.0.0",
1035新增: "inherits": "~2.0.4",
1036新增: "setprototypeof": "~1.2.0",
1037新增: "statuses": "~2.0.2",
1038新增: "toidentifier": "~1.0.1"
1039新增: },
1040新增: "engines": {
1041新增: "node": ">= 0.8"
1042新增: },
1043新增: "funding": {
1044新增: "type": "opencollective",
1045新增: "url": "https://opencollective.com/express"
1046新增: }
1047新增: },
1048新增: "node_modules/http-proxy-agent": {
1049新增: "version": "7.0.2",
1050新增: "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
1051新增: "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
1052新增: "license": "MIT",
1053新增: "dependencies": {
1054新增: "agent-base": "^7.1.0",
1055新增: "debug": "^4.3.4"
1056新增: },
1057新增: "engines": {
1058新增: "node": ">= 14"
1059新增: }
1060新增: },
1061新增: "node_modules/http-proxy-agent/node_modules/debug": {
1062新增: "version": "4.4.3",
1063新增: "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
1064新增: "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
1065新增: "license": "MIT",
1066新增: "dependencies": {
1067新增: "ms": "^2.1.3"
1068新增: },
1069新增: "engines": {
1070新增: "node": ">=6.0"
1071新增: },
1072新增: "peerDependenciesMeta": {
1073新增: "supports-color": {
1074新增: "optional": true
1075新增: }
1076新增: }
1077新增: },
1078新增: "node_modules/http-proxy-agent/node_modules/ms": {
1079新增: "version": "2.1.3",
1080新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
1081新增: "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
1082新增: "license": "MIT"
1083新增: },
1084新增: "node_modules/https-proxy-agent": {
1085新增: "version": "7.0.6",
1086新增: "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
1087新增: "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
1088新增: "license": "MIT",
1089新增: "dependencies": {
1090新增: "agent-base": "^7.1.2",
1091新增: "debug": "4"
1092新增: },
1093新增: "engines": {
1094新增: "node": ">= 14"
1095新增: }
1096新增: },
1097新增: "node_modules/https-proxy-agent/node_modules/debug": {
1098新增: "version": "4.4.3",
1099新增: "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
1100新增: "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
1101新增: "license": "MIT",
1102新增: "dependencies": {
1103新增: "ms": "^2.1.3"
1104新增: },
1105新增: "engines": {
1106新增: "node": ">=6.0"
1107新增: },
1108新增: "peerDependenciesMeta": {
1109新增: "supports-color": {
1110新增: "optional": true
1111新增: }
1112新增: }
1113新增: },
1114新增: "node_modules/https-proxy-agent/node_modules/ms": {
1115新增: "version": "2.1.3",
1116新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
1117新增: "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
1118新增: "license": "MIT"
1119新增: },
1120新增: "node_modules/iconv-lite": {
1121新增: "version": "0.4.24",
1122新增: "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
1123新增: "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
1124新增: "license": "MIT",
1125新增: "dependencies": {
1126新增: "safer-buffer": ">= 2.1.2 < 3"
1127新增: },
1128新增: "engines": {
1129新增: "node": ">=0.10.0"
1130新增: }
1131新增: },
1132新增: "node_modules/ieee754": {
1133新增: "version": "1.2.1",
1134新增: "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
1135新增: "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
1136新增: "funding": [
1137新增: {
1138新增: "type": "github",
1139新增: "url": "https://github.com/sponsors/feross"
1140新增: },
1141新增: {
1142新增: "type": "patreon",
1143新增: "url": "https://www.patreon.com/feross"
1144新增: },
1145新增: {
1146新增: "type": "consulting",
1147新增: "url": "https://feross.org/support"
1148新增: }
1149新增: ],
1150新增: "license": "BSD-3-Clause"
1151新增: },
1152新增: "node_modules/indent-string": {
1153新增: "version": "4.0.0",
1154新增: "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz",
1155新增: "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==",
1156新增: "license": "MIT",
1157新增: "engines": {
1158新增: "node": ">=8"
1159新增: }
1160新增: },
1161新增: "node_modules/inherits": {
1162新增: "version": "2.0.4",
1163新增: "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
1164新增: "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
1165新增: "license": "ISC"
1166新增: },
1167新增: "node_modules/ip-address": {
1168新增: "version": "10.7.6",
1169新增: "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz",
1170新增: "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==",
1171新增: "license": "MIT",
1172新增: "engines": {
1173新增: "node": ">= 12"
1174新增: }
1175新增: },
1176新增: "node_modules/ipaddr.js": {
1177新增: "version": "1.9.1",
1178新增: "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
1179新增: "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
1180新增: "license": "MIT",
1181新增: "engines": {
1182新增: "node": ">= 0.10"
1183新增: }
1184新增: },
1185新增: "node_modules/is-binary-path": {
1186新增: "version": "2.1.0",
1187新增: "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
1188新增: "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
1189新增: "license": "MIT",
1190新增: "dependencies": {
1191新增: "binary-extensions": "^2.0.0"
1192新增: },
1193新增: "engines": {
1194新增: "node": ">=8"
1195新增: }
1196新增: },
1197新增: "node_modules/is-docker": {
1198新增: "version": "2.2.1",
1199新增: "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
1200新增: "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",
1201新增: "license": "MIT",
1202新增: "bin": {
1203新增: "is-docker": "cli.js"
1204新增: },
1205新增: "engines": {
1206新增: "node": ">=8"
1207新增: },
1208新增: "funding": {
1209新增: "url": "https://github.com/sponsors/sindresorhus"
1210新增: }
1211新增: },
1212新增: "node_modules/is-extglob": {
1213新增: "version": "2.1.1",
1214新增: "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
1215新增: "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
1216新增: "license": "MIT",
1217新增: "engines": {
1218新增: "node": ">=0.10.0"
1219新增: }
1220新增: },
1221新增: "node_modules/is-fullwidth-code-point": {
1222新增: "version": "3.0.0",
1223新增: "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
1224新增: "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
1225新增: "license": "MIT",
1226新增: "engines": {
1227新增: "node": ">=8"
1228新增: }
1229新增: },
1230新增: "node_modules/is-glob": {
1231新增: "version": "4.0.3",
1232新增: "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
1233新增: "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
1234新增: "license": "MIT",
1235新增: "dependencies": {
1236新增: "is-extglob": "^2.1.1"
1237新增: },
1238新增: "engines": {
1239新增: "node": ">=0.10.0"
1240新增: }
1241新增: },
1242新增: "node_modules/is-interactive": {
1243新增: "version": "1.0.0",
1244新增: "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz",
1245新增: "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==",
1246新增: "license": "MIT",
1247新增: "engines": {
1248新增: "node": ">=8"
1249新增: }
1250新增: },
1251新增: "node_modules/is-number": {
1252新增: "version": "7.0.0",
1253新增: "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
1254新增: "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
1255新增: "license": "MIT",
1256新增: "engines": {
1257新增: "node": ">=0.12.0"
1258新增: }
1259新增: },
1260新增: "node_modules/is-unicode-supported": {
1261新增: "version": "0.1.0",
1262新增: "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz",
1263新增: "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==",
1264新增: "license": "MIT",
1265新增: "engines": {
1266新增: "node": ">=10"
1267新增: },
1268新增: "funding": {
1269新增: "url": "https://github.com/sponsors/sindresorhus"
1270新增: }
1271新增: },
1272新增: "node_modules/is-wsl": {
1273新增: "version": "2.2.0",
1274新增: "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
1275新增: "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
1276新增: "license": "MIT",
1277新增: "dependencies": {
1278新增: "is-docker": "^2.0.0"
1279新增: },
1280新增: "engines": {
1281新增: "node": ">=8"
1282新增: }
1283新增: },
1284新增: "node_modules/js-yaml": {
1285新增: "version": "4.3.2",
1286新增: "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
1287新增: "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",
1288新增: "funding": [
1289新增: {
1290新增: "type": "github",
1291新增: "url": "https://github.com/sponsors/puzrin"
1292新增: },
1293新增: {
1294新增: "type": "github",
1295新增: "url": "https://github.com/sponsors/nodeca"
1296新增: }
1297新增: ],
1298新增: "license": "MIT",
1299新增: "dependencies": {
1300新增: "argparse": "^2.0.1"
1301新增: },
1302新增: "bin": {
1303新增: "js-yaml": "bin/js-yaml.js"
1304新增: }
1305新增: },
1306新增: "node_modules/listr2": {
1307新增: "version": "3.14.0",
1308新增: "resolved": "https://registry.npmjs.org/listr2/-/listr2-3.14.0.tgz",
1309新增: "integrity": "sha512-TyWI8G99GX9GjE54cJ+RrNMcIFBfwMPxc3XTFiAYGN4s10hWROGtOg7+O6u6LE3mNkyld7RSLE6nrKBvTfcs3g==",
1310新增: "license": "MIT",
1311新增: "dependencies": {
1312新增: "cli-truncate": "^2.1.0",
1313新增: "colorette": "^2.0.16",
1314新增: "log-update": "^4.0.0",
1315新增: "p-map": "^4.0.0",
1316新增: "rfdc": "^1.3.0",
1317新增: "rxjs": "^7.5.1",
1318新增: "through": "^2.3.8",
1319新增: "wrap-ansi": "^7.0.0"
1320新增: },
1321新增: "engines": {
1322新增: "node": ">=10.0.0"
1323新增: },
1324新增: "peerDependencies": {
1325新增: "enquirer": ">= 2.3.0 < 3"
1326新增: },
1327新增: "peerDependenciesMeta": {
1328新增: "enquirer": {
1329新增: "optional": true
1330新增: }
1331新增: }
1332新增: },
1333新增: "node_modules/log-symbols": {
1334新增: "version": "4.1.0",
1335新增: "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz",
1336新增: "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==",
1337新增: "license": "MIT",
1338新增: "dependencies": {
1339新增: "chalk": "^4.1.0",
1340新增: "is-unicode-supported": "^0.1.0"
1341新增: },
1342新增: "engines": {
1343新增: "node": ">=10"
1344新增: },
1345新增: "funding": {
1346新增: "url": "https://github.com/sponsors/sindresorhus"
1347新增: }
1348新增: },
1349新增: "node_modules/log-update": {
1350新增: "version": "4.0.0",
1351新增: "resolved": "https://registry.npmjs.org/log-update/-/log-update-4.0.0.tgz",
1352新增: "integrity": "sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg==",
1353新增: "license": "MIT",
1354新增: "dependencies": {
1355新增: "ansi-escapes": "^4.3.0",
1356新增: "cli-cursor": "^3.1.0",
1357新增: "slice-ansi": "^4.0.0",
1358新增: "wrap-ansi": "^6.2.0"
1359新增: },
1360新增: "engines": {
1361新增: "node": ">=10"
1362新增: },
1363新增: "funding": {
1364新增: "url": "https://github.com/sponsors/sindresorhus"
1365新增: }
1366新增: },
1367新增: "node_modules/log-update/node_modules/slice-ansi": {
1368新增: "version": "4.0.0",
1369新增: "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz",
1370新增: "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==",
1371新增: "license": "MIT",
1372新增: "dependencies": {
1373新增: "ansi-styles": "^4.0.0",
1374新增: "astral-regex": "^2.0.0",
1375新增: "is-fullwidth-code-point": "^3.0.0"
1376新增: },
1377新增: "engines": {
1378新增: "node": ">=10"
1379新增: },
1380新增: "funding": {
1381新增: "url": "https://github.com/chalk/slice-ansi?sponsor=1"
1382新增: }
1383新增: },
1384新增: "node_modules/log-update/node_modules/wrap-ansi": {
1385新增: "version": "6.2.0",
1386新增: "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
1387新增: "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
1388新增: "license": "MIT",
1389新增: "dependencies": {
1390新增: "ansi-styles": "^4.0.0",
1391新增: "string-width": "^4.1.0",
1392新增: "strip-ansi": "^6.0.0"
1393新增: },
1394新增: "engines": {
1395新增: "node": ">=8"
1396新增: }
1397新增: },
1398新增: "node_modules/math-intrinsics": {
1399新增: "version": "1.1.0",
1400新增: "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
1401新增: "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
1402新增: "license": "MIT",
1403新增: "engines": {
1404新增: "node": ">= 0.4"
1405新增: }
1406新增: },
1407新增: "node_modules/media-typer": {
1408新增: "version": "0.3.0",
1409新增: "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
1410新增: "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
1411新增: "license": "MIT",
1412新增: "engines": {
1413新增: "node": ">= 0.6"
1414新增: }
1415新增: },
1416新增: "node_modules/merge-descriptors": {
1417新增: "version": "1.0.3",
1418新增: "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
1419新增: "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
1420新增: "license": "MIT",
1421新增: "funding": {
1422新增: "url": "https://github.com/sponsors/sindresorhus"
1423新增: }
1424新增: },
1425新增: "node_modules/methods": {
1426新增: "version": "1.1.2",
1427新增: "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
1428新增: "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
1429新增: "license": "MIT",
1430新增: "engines": {
1431新增: "node": ">= 0.6"
1432新增: }
1433新增: },
1434新增: "node_modules/mime": {
1435新增: "version": "1.6.0",
1436新增: "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
1437新增: "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
1438新增: "license": "MIT",
1439新增: "bin": {
1440新增: "mime": "cli.js"
1441新增: },
1442新增: "engines": {
1443新增: "node": ">=4"
1444新增: }
1445新增: },
1446新增: "node_modules/mime-db": {
1447新增: "version": "1.52.0",
1448新增: "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
1449新增: "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
1450新增: "license": "MIT",
1451新增: "engines": {
1452新增: "node": ">= 0.6"
1453新增: }
1454新增: },
1455新增: "node_modules/mime-types": {
1456新增: "version": "2.1.35",
1457新增: "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
1458新增: "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
1459新增: "license": "MIT",
1460新增: "dependencies": {
1461新增: "mime-db": "1.52.0"
1462新增: },
1463新增: "engines": {
1464新增: "node": ">= 0.6"
1465新增: }
1466新增: },
1467新增: "node_modules/mimic-fn": {
1468新增: "version": "2.1.0",
1469新增: "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
1470新增: "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",
1471新增: "license": "MIT",
1472新增: "engines": {
1473新增: "node": ">=6"
1474新增: }
1475新增: },
1476新增: "node_modules/ms": {
1477新增: "version": "2.0.0",
1478新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
1479新增: "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
1480新增: "license": "MIT"
1481新增: },
1482新增: "node_modules/negotiator": {
1483新增: "version": "0.6.3",
1484新增: "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
1485新增: "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
1486新增: "license": "MIT",
1487新增: "engines": {
1488新增: "node": ">= 0.6"
1489新增: }
1490新增: },
1491新增: "node_modules/node-addon-api": {
1492新增: "version": "8.9.2",
1493新增: "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz",
1494新增: "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==",
1495新增: "license": "MIT",
1496新增: "engines": {
1497新增: "node": "^18 || ^20 || >= 21"
1498新增: }
1499新增: },
1500新增: "node_modules/node-gyp-build": {
1501新增: "version": "4.8.4",
1502新增: "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
1503新增: "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
1504新增: "license": "MIT",
1505新增: "bin": {
1506新增: "node-gyp-build": "bin.js",
1507新增: "node-gyp-build-optional": "optional.js",
1508新增: "node-gyp-build-test": "build-test.js"
1509新增: }
1510新增: },
1511新增: "node_modules/normalize-path": {
1512新增: "version": "3.0.0",
1513新增: "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
1514新增: "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
1515新增: "license": "MIT",
1516新增: "engines": {
1517新增: "node": ">=0.10.0"
1518新增: }
1519新增: },
1520新增: "node_modules/object-inspect": {
1521新增: "version": "1.13.4",
1522新增: "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
1523新增: "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
1524新增: "license": "MIT",
1525新增: "engines": {
1526新增: "node": ">= 0.4"
1527新增: },
1528新增: "funding": {
1529新增: "url": "https://github.com/sponsors/ljharb"
1530新增: }
1531新增: },
1532新增: "node_modules/on-finished": {
1533新增: "version": "2.4.2",
1534新增: "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz",
1535新增: "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==",
1536新增: "license": "MIT",
1537新增: "dependencies": {
1538新增: "ee-first": "1.1.1"
1539新增: },
1540新增: "engines": {
1541新增: "node": ">= 0.8"
1542新增: },
1543新增: "funding": {
1544新增: "type": "opencollective",
1545新增: "url": "https://opencollective.com/express"
1546新增: }
1547新增: },
1548新增: "node_modules/on-headers": {
1549新增: "version": "1.1.0",
1550新增: "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz",
1551新增: "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==",
1552新增: "license": "MIT",
1553新增: "engines": {
1554新增: "node": ">= 0.8"
1555新增: }
1556新增: },
1557新增: "node_modules/onetime": {
1558新增: "version": "5.1.2",
1559新增: "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
1560新增: "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",
1561新增: "license": "MIT",
1562新增: "dependencies": {
1563新增: "mimic-fn": "^2.1.0"
1564新增: },
1565新增: "engines": {
1566新增: "node": ">=6"
1567新增: },
1568新增: "funding": {
1569新增: "url": "https://github.com/sponsors/sindresorhus"
1570新增: }
1571新增: },
1572新增: "node_modules/open": {
1573新增: "version": "8.4.2",
1574新增: "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz",
1575新增: "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==",
1576新增: "license": "MIT",
1577新增: "dependencies": {
1578新增: "define-lazy-prop": "^2.0.0",
1579新增: "is-docker": "^2.1.1",
1580新增: "is-wsl": "^2.2.0"
1581新增: },
1582新增: "engines": {
1583新增: "node": ">=12"
1584新增: },
1585新增: "funding": {
1586新增: "url": "https://github.com/sponsors/sindresorhus"
1587新增: }
1588新增: },
1589新增: "node_modules/ora": {
1590新增: "version": "5.4.1",
1591新增: "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz",
1592新增: "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==",
1593新增: "license": "MIT",
1594新增: "dependencies": {
1595新增: "bl": "^4.1.0",
1596新增: "chalk": "^4.1.0",
1597新增: "cli-cursor": "^3.1.0",
1598新增: "cli-spinners": "^2.5.0",
1599新增: "is-interactive": "^1.0.0",
1600新增: "is-unicode-supported": "^0.1.0",
1601新增: "log-symbols": "^4.1.0",
1602新增: "strip-ansi": "^6.0.0",
1603新增: "wcwidth": "^1.0.1"
1604新增: },
1605新增: "engines": {
1606新增: "node": ">=10"
1607新增: },
1608新增: "funding": {
1609新增: "url": "https://github.com/sponsors/sindresorhus"
1610新增: }
1611新增: },
1612新增: "node_modules/p-map": {
1613新增: "version": "4.0.0",
1614新增: "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz",
1615新增: "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==",
1616新增: "license": "MIT",
1617新增: "dependencies": {
1618新增: "aggregate-error": "^3.0.0"
1619新增: },
1620新增: "engines": {
1621新增: "node": ">=10"
1622新增: },
1623新增: "funding": {
1624新增: "url": "https://github.com/sponsors/sindresorhus"
1625新增: }
1626新增: },
1627新增: "node_modules/parseurl": {
1628新增: "version": "1.3.3",
1629新增: "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
1630新增: "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
1631新增: "license": "MIT",
1632新增: "engines": {
1633新增: "node": ">= 0.8"
1634新增: }
1635新增: },
1636新增: "node_modules/path-to-regexp": {
1637新增: "version": "0.1.13",
1638新增: "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
1639新增: "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
1640新增: "license": "MIT"
1641新增: },
1642新增: "node_modules/picomatch": {
1643新增: "version": "2.3.2",
1644新增: "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
1645新增: "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
1646新增: "license": "MIT",
1647新增: "engines": {
1648新增: "node": ">=8.6"
1649新增: },
1650新增: "funding": {
1651新增: "url": "https://github.com/sponsors/jonschlinkert"
1652新增: }
1653新增: },
1654新增: "node_modules/proper-lockfile": {
1655新增: "version": "4.1.2",
1656新增: "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",
1657新增: "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",
1658新增: "license": "MIT",
1659新增: "dependencies": {
1660新增: "graceful-fs": "^4.2.4",
1661新增: "retry": "^0.12.0",
1662新增: "signal-exit": "^3.0.2"
1663新增: }
1664新增: },
1665新增: "node_modules/proxy-addr": {
1666新增: "version": "2.0.8",
1667新增: "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
1668新增: "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
1669新增: "license": "MIT",
1670新增: "dependencies": {
1671新增: "forwarded": "0.2.0",
1672新增: "ipaddr.js": "1.9.1"
1673新增: },
1674新增: "engines": {
1675新增: "node": ">= 0.10"
1676新增: },
1677新增: "funding": {
1678新增: "type": "opencollective",
1679新增: "url": "https://opencollective.com/express"
1680新增: }
1681新增: },
1682新增: "node_modules/qs": {
1683新增: "version": "6.16.2",
1684新增: "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.2.tgz",
1685新增: "integrity": "sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==",
1686新增: "license": "BSD-3-Clause",
1687新增: "dependencies": {
1688新增: "es-define-property": "^1.0.1",
1689新增: "side-channel": "^1.1.1"
1690新增: },
1691新增: "engines": {
1692新增: "node": ">=0.6"
1693新增: },
1694新增: "funding": {
1695新增: "url": "https://github.com/sponsors/ljharb"
1696新增: }
1697新增: },
1698新增: "node_modules/random-bytes": {
1699新增: "version": "1.0.0",
1700新增: "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz",
1701新增: "integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==",
1702新增: "license": "MIT",
1703新增: "engines": {
1704新增: "node": ">= 0.8"
1705新增: }
1706新增: },
1707新增: "node_modules/range-parser": {
1708新增: "version": "1.2.1",
1709新增: "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
1710新增: "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
1711新增: "license": "MIT",
1712新增: "engines": {
1713新增: "node": ">= 0.6"
1714新增: }
1715新增: },
1716新增: "node_modules/raw-body": {
1717新增: "version": "2.5.3",
1718新增: "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
1719新增: "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
1720新增: "license": "MIT",
1721新增: "dependencies": {
1722新增: "bytes": "~3.1.2",
1723新增: "http-errors": "~2.0.1",
1724新增: "iconv-lite": "~0.4.24",
1725新增: "unpipe": "~1.0.0"
1726新增: },
1727新增: "engines": {
1728新增: "node": ">= 0.8"
1729新增: }
1730新增: },
1731新增: "node_modules/readable-stream": {
1732新增: "version": "3.6.2",
1733新增: "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
1734新增: "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
1735新增: "license": "MIT",
1736新增: "dependencies": {
1737新增: "inherits": "^2.0.3",
1738新增: "string_decoder": "^1.1.1",
1739新增: "util-deprecate": "^1.0.1"
1740新增: },
1741新增: "engines": {
1742新增: "node": ">= 6"
1743新增: }
1744新增: },
1745新增: "node_modules/readdirp": {
1746新增: "version": "3.6.0",
1747新增: "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
1748新增: "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
1749新增: "license": "MIT",
1750新增: "dependencies": {
1751新增: "picomatch": "^2.2.1"
1752新增: },
1753新增: "engines": {
1754新增: "node": ">=8.10.0"
1755新增: }
1756新增: },
1757新增: "node_modules/restore-cursor": {
1758新增: "version": "3.1.0",
1759新增: "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz",
1760新增: "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==",
1761新增: "license": "MIT",
1762新增: "dependencies": {
1763新增: "onetime": "^5.1.0",
1764新增: "signal-exit": "^3.0.2"
1765新增: },
1766新增: "engines": {
1767新增: "node": ">=8"
1768新增: }
1769新增: },
1770新增: "node_modules/retry": {
1771新增: "version": "0.12.0",
1772新增: "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
1773新增: "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
1774新增: "license": "MIT",
1775新增: "engines": {
1776新增: "node": ">= 4"
1777新增: }
1778新增: },
1779新增: "node_modules/rfdc": {
1780新增: "version": "1.4.1",
1781新增: "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
1782新增: "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
1783新增: "license": "MIT"
1784新增: },
1785新增: "node_modules/rxjs": {
1786新增: "version": "7.8.2",
1787新增: "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
1788新增: "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
1789新增: "license": "Apache-2.0",
1790新增: "dependencies": {
1791新增: "tslib": "^2.1.0"
1792新增: }
1793新增: },
1794新增: "node_modules/safe-buffer": {
1795新增: "version": "5.2.1",
1796新增: "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
1797新增: "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
1798新增: "funding": [
1799新增: {
1800新增: "type": "github",
1801新增: "url": "https://github.com/sponsors/feross"
1802新增: },
1803新增: {
1804新增: "type": "patreon",
1805新增: "url": "https://www.patreon.com/feross"
1806新增: },
1807新增: {
1808新增: "type": "consulting",
1809新增: "url": "https://feross.org/support"
1810新增: }
1811新增: ],
1812新增: "license": "MIT"
1813新增: },
1814新增: "node_modules/safer-buffer": {
1815新增: "version": "2.1.2",
1816新增: "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
1817新增: "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
1818新增: "license": "MIT"
1819新增: },
1820新增: "node_modules/send": {
1821新增: "version": "0.19.2",
1822新增: "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
1823新增: "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
1824新增: "license": "MIT",
1825新增: "dependencies": {
1826新增: "debug": "2.6.9",
1827新增: "depd": "2.0.0",
1828新增: "destroy": "1.2.0",
1829新增: "encodeurl": "~2.0.0",
1830新增: "escape-html": "~1.0.3",
1831新增: "etag": "~1.8.1",
1832新增: "fresh": "~0.5.2",
1833新增: "http-errors": "~2.0.1",
1834新增: "mime": "1.6.0",
1835新增: "ms": "2.1.3",
1836新增: "on-finished": "~2.4.1",
1837新增: "range-parser": "~1.2.1",
1838新增: "statuses": "~2.0.2"
1839新增: },
1840新增: "engines": {
1841新增: "node": ">= 0.8.0"
1842新增: }
1843新增: },
1844新增: "node_modules/send/node_modules/ms": {
1845新增: "version": "2.1.3",
1846新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
1847新增: "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
1848新增: "license": "MIT"
1849新增: },
1850新增: "node_modules/serve-static": {
1851新增: "version": "1.16.3",
1852新增: "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",
1853新增: "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
1854新增: "license": "MIT",
1855新增: "dependencies": {
1856新增: "encodeurl": "~2.0.0",
1857新增: "escape-html": "~1.0.3",
1858新增: "parseurl": "~1.3.3",
1859新增: "send": "~0.19.1"
1860新增: },
1861新增: "engines": {
1862新增: "node": ">= 0.8.0"
1863新增: }
1864新增: },
1865新增: "node_modules/setprototypeof": {
1866新增: "version": "1.2.0",
1867新增: "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
1868新增: "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
1869新增: "license": "ISC"
1870新增: },
1871新增: "node_modules/side-channel": {
1872新增: "version": "1.1.1",
1873新增: "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
1874新增: "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
1875新增: "license": "MIT",
1876新增: "dependencies": {
1877新增: "es-errors": "^1.3.0",
1878新增: "object-inspect": "^1.13.4",
1879新增: "side-channel-list": "^1.0.1",
1880新增: "side-channel-map": "^1.0.1",
1881新增: "side-channel-weakmap": "^1.0.2"
1882新增: },
1883新增: "engines": {
1884新增: "node": ">= 0.4"
1885新增: },
1886新增: "funding": {
1887新增: "url": "https://github.com/sponsors/ljharb"
1888新增: }
1889新增: },
1890新增: "node_modules/side-channel-list": {
1891新增: "version": "1.0.1",
1892新增: "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
1893新增: "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
1894新增: "license": "MIT",
1895新增: "dependencies": {
1896新增: "es-errors": "^1.3.0",
1897新增: "object-inspect": "^1.13.4"
1898新增: },
1899新增: "engines": {
1900新增: "node": ">= 0.4"
1901新增: },
1902新增: "funding": {
1903新增: "url": "https://github.com/sponsors/ljharb"
1904新增: }
1905新增: },
1906新增: "node_modules/side-channel-map": {
1907新增: "version": "1.0.1",
1908新增: "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
1909新增: "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
1910新增: "license": "MIT",
1911新增: "dependencies": {
1912新增: "call-bound": "^1.0.2",
1913新增: "es-errors": "^1.3.0",
1914新增: "get-intrinsic": "^1.2.5",
1915新增: "object-inspect": "^1.13.3"
1916新增: },
1917新增: "engines": {
1918新增: "node": ">= 0.4"
1919新增: },
1920新增: "funding": {
1921新增: "url": "https://github.com/sponsors/ljharb"
1922新增: }
1923新增: },
1924新增: "node_modules/side-channel-weakmap": {
1925新增: "version": "1.0.2",
1926新增: "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
1927新增: "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
1928新增: "license": "MIT",
1929新增: "dependencies": {
1930新增: "call-bound": "^1.0.2",
1931新增: "es-errors": "^1.3.0",
1932新增: "get-intrinsic": "^1.2.5",
1933新增: "object-inspect": "^1.13.3",
1934新增: "side-channel-map": "^1.0.1"
1935新增: },
1936新增: "engines": {
1937新增: "node": ">= 0.4"
1938新增: },
1939新增: "funding": {
1940新增: "url": "https://github.com/sponsors/ljharb"
1941新增: }
1942新增: },
1943新增: "node_modules/signal-exit": {
1944新增: "version": "3.0.7",
1945新增: "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
1946新增: "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
1947新增: "license": "ISC"
1948新增: },
1949新增: "node_modules/slice-ansi": {
1950新增: "version": "3.0.0",
1951新增: "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz",
1952新增: "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==",
1953新增: "license": "MIT",
1954新增: "dependencies": {
1955新增: "ansi-styles": "^4.0.0",
1956新增: "astral-regex": "^2.0.0",
1957新增: "is-fullwidth-code-point": "^3.0.0"
1958新增: },
1959新增: "engines": {
1960新增: "node": ">=8"
1961新增: }
1962新增: },
1963新增: "node_modules/smol-toml": {
1964新增: "version": "1.9.1",
1965新增: "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz",
1966新增: "integrity": "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==",
1967新增: "license": "BSD-3-Clause",
1968新增: "engines": {
1969新增: "node": ">= 18"
1970新增: },
1971新增: "funding": {
1972新增: "url": "https://github.com/sponsors/cyyynthia"
1973新增: }
1974新增: },
1975新增: "node_modules/statuses": {
1976新增: "version": "2.0.2",
1977新增: "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
1978新增: "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
1979新增: "license": "MIT",
1980新增: "engines": {
1981新增: "node": ">= 0.8"
1982新增: }
1983新增: },
1984新增: "node_modules/string_decoder": {
1985新增: "version": "1.3.0",
1986新增: "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
1987新增: "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
1988新增: "license": "MIT",
1989新增: "dependencies": {
1990新增: "safe-buffer": "~5.2.0"
1991新增: }
1992新增: },
1993新增: "node_modules/string-width": {
1994新增: "version": "4.2.3",
1995新增: "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
1996新增: "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
1997新增: "license": "MIT",
1998新增: "dependencies": {
1999新增: "emoji-regex": "^8.0.0",
2000新增: "is-fullwidth-code-point": "^3.0.0",
2001新增: "strip-ansi": "^6.0.1"
2002新增: },
2003新增: "engines": {
2004新增: "node": ">=8"
2005新增: }
2006新增: },
2007新增: "node_modules/strip-ansi": {
2008新增: "version": "6.0.1",
2009新增: "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
2010新增: "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
2011新增: "license": "MIT",
2012新增: "dependencies": {
2013新增: "ansi-regex": "^5.0.1"
2014新增: },
2015新增: "engines": {
2016新增: "node": ">=8"
2017新增: }
2018新增: },
2019新增: "node_modules/supports-color": {
2020新增: "version": "7.2.0",
2021新增: "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
2022新增: "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
2023新增: "license": "MIT",
2024新增: "dependencies": {
2025新增: "has-flag": "^4.0.0"
2026新增: },
2027新增: "engines": {
2028新增: "node": ">=8"
2029新增: }
2030新增: },
2031新增: "node_modules/through": {
2032新增: "version": "2.3.8",
2033新增: "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",
2034新增: "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==",
2035新增: "license": "MIT"
2036新增: },
2037新增: "node_modules/tinycolor2": {
2038新增: "version": "1.6.0",
2039新增: "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz",
2040新增: "integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==",
2041新增: "license": "MIT"
2042新增: },
2043新增: "node_modules/tinygradient": {
2044新增: "version": "1.1.5",
2045新增: "resolved": "https://registry.npmjs.org/tinygradient/-/tinygradient-1.1.5.tgz",
2046新增: "integrity": "sha512-8nIfc2vgQ4TeLnk2lFj4tRLvvJwEfQuabdsmvDdQPT0xlk9TaNtpGd6nNRxXoK6vQhN6RSzj+Cnp5tTQmpxmbw==",
2047新增: "license": "MIT",
2048新增: "dependencies": {
2049新增: "@types/tinycolor2": "^1.4.0",
2050新增: "tinycolor2": "^1.0.0"
2051新增: }
2052新增: },
2053新增: "node_modules/to-regex-range": {
2054新增: "version": "5.0.1",
2055新增: "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
2056新增: "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
2057新增: "license": "MIT",
2058新增: "dependencies": {
2059新增: "is-number": "^7.0.0"
2060新增: },
2061新增: "engines": {
2062新增: "node": ">=8.0"
2063新增: }
2064新增: },
2065新增: "node_modules/toidentifier": {
2066新增: "version": "1.0.1",
2067新增: "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
2068新增: "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
2069新增: "license": "MIT",
2070新增: "engines": {
2071新增: "node": ">=0.6"
2072新增: }
2073新增: },
2074新增: "node_modules/tslib": {
2075新增: "version": "2.9.1",
2076新增: "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
2077新增: "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
2078新增: "license": "0BSD"
2079新增: },
2080新增: "node_modules/type-fest": {
2081新增: "version": "0.20.2",
2082新增: "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz",
2083新增: "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==",
2084新增: "license": "(MIT OR CC0-1.0)",
2085新增: "engines": {
2086新增: "node": ">=10"
2087新增: },
2088新增: "funding": {
2089新增: "url": "https://github.com/sponsors/sindresorhus"
2090新增: }
2091新增: },
2092新增: "node_modules/type-is": {
2093新增: "version": "1.6.18",
2094新增: "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
2095新增: "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
2096新增: "license": "MIT",
2097新增: "dependencies": {
2098新增: "media-typer": "0.3.0",
2099新增: "mime-types": "~2.1.24"
2100新增: },
2101新增: "engines": {
2102新增: "node": ">= 0.6"
2103新增: }
2104新增: },
2105新增: "node_modules/uid-safe": {
2106新增: "version": "2.1.5",
2107新增: "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz",
2108新增: "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==",
2109新增: "license": "MIT",
2110新增: "dependencies": {
2111新增: "random-bytes": "~1.0.0"
2112新增: },
2113新增: "engines": {
2114新增: "node": ">= 0.8"
2115新增: }
2116新增: },
2117新增: "node_modules/undici": {
2118新增: "version": "5.29.0",
2119新增: "resolved": "https://registry.npmjs.org/undici/-/undici-5.29.0.tgz",
2120新增: "integrity": "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==",
2121新增: "license": "MIT",
2122新增: "dependencies": {
2123新增: "@fastify/busboy": "^2.0.0"
2124新增: },
2125新增: "engines": {
2126新增: "node": ">=14.0"
2127新增: }
2128新增: },
2129新增: "node_modules/unpipe": {
2130新增: "version": "1.0.0",
2131新增: "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
2132新增: "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
2133新增: "license": "MIT",
2134新增: "engines": {
2135新增: "node": ">= 0.8"
2136新增: }
2137新增: },
2138新增: "node_modules/util-deprecate": {
2139新增: "version": "1.0.2",
2140新增: "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
2141新增: "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
2142新增: "license": "MIT"
2143新增: },
2144新增: "node_modules/utils-merge": {
2145新增: "version": "1.0.1",
2146新增: "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
2147新增: "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
2148新增: "license": "MIT",
2149新增: "engines": {
2150新增: "node": ">= 0.4.0"
2151新增: }
2152新增: },
2153新增: "node_modules/vary": {
2154新增: "version": "1.1.2",
2155新增: "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
2156新增: "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
2157新增: "license": "MIT",
2158新增: "engines": {
2159新增: "node": ">= 0.8"
2160新增: }
2161新增: },
2162新增: "node_modules/wcwidth": {
2163新增: "version": "1.0.1",
2164新增: "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz",
2165新增: "integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==",
2166新增: "license": "MIT",
2167新增: "dependencies": {
2168新增: "defaults": "^1.0.3"
2169新增: }
2170新增: },
2171新增: "node_modules/widest-line": {
2172新增: "version": "3.1.0",
2173新增: "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-3.1.0.tgz",
2174新增: "integrity": "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg==",
2175新增: "license": "MIT",
2176新增: "dependencies": {
2177新增: "string-width": "^4.0.0"
2178新增: },
2179新增: "engines": {
2180新增: "node": ">=8"
2181新增: }
2182新增: },
2183新增: "node_modules/wrap-ansi": {
2184新增: "version": "7.0.0",
2185新增: "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
2186新增: "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
2187新增: "license": "MIT",
2188新增: "dependencies": {
2189新增: "ansi-styles": "^4.0.0",
2190新增: "string-width": "^4.1.0",
2191新增: "strip-ansi": "^6.0.0"
2192新增: },
2193新增: "engines": {
2194新增: "node": ">=10"
2195新增: },
2196新增: "funding": {
2197新增: "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
2198新增: }
2199新增: },
2200新增: "node_modules/ws": {
2201新增: "version": "8.22.1",
2202新增: "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz",
2203新增: "integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==",
2204新增: "license": "MIT",
2205新增: "engines": {
2206新增: "node": ">=10.0.0"
2207新增: },
2208新增: "peerDependencies": {
2209新增: "bufferutil": "^4.0.1",
2210新增: "utf-8-validate": ">=5.0.2"
2211新增: },
2212新增: "peerDependenciesMeta": {
2213新增: "bufferutil": {
2214新增: "optional": true
2215新增: },
2216新增: "utf-8-validate": {
2217新增: "optional": true
2218新增: }
2219新增: }
2220新增: }
2221新增: }
2222新增:}
新增scripts/guest-os/guest-clipboard-windows/ccs-runtime/package.json+8 −0看文件
@@ -0,0 +1,8 @@
1新增:{
2新增: "name": "cage-windows-ccs-runtime",
3新增: "private": true,
4新增: "version": "1.0.0",
5新增: "dependencies": {
6新增: "@kaitranntt/ccs": "8.11.0"
7新增: }
8新增:}
文件末尾没有换行
新增scripts/guest-os/guest-clipboard-windows/cli-dependencies.json+28 −0看文件
@@ -0,0 +1,28 @@
1新增:{
2新增: "uv": {
3新增: "version": "0.13.7",
4新增: "filename": "uv-x86_64-pc-windows-msvc.zip",
5新增: "url": "https://github.com/astral-sh/uv/releases/download/0.13.7/uv-x86_64-pc-windows-msvc.zip",
6新增: "sha256": "0cdc5b38fe5a8168ed6a25814f5ba43c21d313dd3187314fccb37b7cec46e021"
7新增: },
8新增: "python": {
9新增: "version": "3.13.18",
10新增: "key": "cpython-3.13.18-windows-x86_64-none",
11新增: "filename": "cpython-3.13.18+20261026-x86_64-pc-windows-msvc-install_only_stripped.tar.gz",
12新增: "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20261026/cpython-3.13.18%2B20261026-x86_64-pc-windows-msvc-install_only_stripped.tar.gz",
13新增: "sha256": "7369f7a35f261222a6ac8b3a87c1c88eeebee8af945d85346202591a64038dd3"
14新增: },
15新增: "claude": {
16新增: "version": "2.1.311",
17新增: "filename": "claude-2.1.311-win32-x64.exe",
18新增: "url": "https://downloads.claude.ai/claude-code-releases/2.1.311/win32-x64/claude.exe",
19新增: "manifest": "https://downloads.claude.ai/claude-code-releases/2.1.311/manifest.json",
20新增: "sha256": "966f4b2ce962298f5dee6a942e8c47c8f97392e69e728e622319a98b259c0680"
21新增: },
22新增: "git": {
23新增: "version": "2.56.0.4",
24新增: "filename": "PortableGit-2.56.0.4-64-bit.7z.exe",
25新增: "url": "https://github.com/git-for-windows/git/releases/download/v2.56.0.windows.4/PortableGit-2.56.0.4-64-bit.7z.exe",
26新增: "sha256": "b1f3e52216e2ed6882d1bebfd4d3fdf319bec40d2edbbf9fd26ec4fd3fce7ed1"
27新增: }
28新增:}
新增scripts/guest-os/guest-clipboard-windows/install-ccs.ps1+84 −0看文件
@@ -0,0 +1,84 @@
1新增:# Execute as the paired ordinary GUI user. Management copies only the validated
2新增:# receipt into the readonly bridge; no ProgramFiles write permission is added.
3新增:[CmdletBinding()]
4新增:param(
5新增: [Parameter(Mandatory)][string]$RuntimeArchive,
6新增: [Parameter(Mandatory)][string]$NodeArchive,
7新增: [Parameter(Mandatory)][string]$BridgeDirectory,
8新增: [string]$ExistingNode = '',
9新增: [string]$ReceiptDirectory = (Join-Path $env:USERPROFILE 'Cage\CLI\install-receipts')
10新增:)
11新增:$ErrorActionPreference='Stop'
12新增:Set-StrictMode -Version Latest
13新增:if (-not [Runtime.InteropServices.RuntimeInformation]::IsOSPlatform([Runtime.InteropServices.OSPlatform]::Windows)) { throw 'Native Windows is required.' }
14新增:$user=[Security.Principal.WindowsIdentity]::GetCurrent()
15新增:if ((New-Object Security.Principal.WindowsPrincipal($user)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Use the paired ordinary GUI user.' }
16新增:$bridge=[IO.Path]::GetFullPath($BridgeDirectory)
17新增:if (-not (Test-Path (Join-Path $bridge 'Cage.GuestClipboard.exe') -PathType Leaf)) { throw 'Install the paired bridge first.' }
18新增:function Assert-NoReparse([string]$Path) {
19新增: $item=Get-Item -LiteralPath $Path -Force
20新增: while ($null -ne $item) { if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'A native CCS path is a reparse point.' }; if ($item -is [IO.FileInfo]) { $item=$item.Directory } else { $item=$item.Parent } }
21新增:}
22新增:function Protect-Path([string]$Path,[bool]$Directory) {
23新增: if ($Directory) { $acl=New-Object Security.AccessControl.DirectorySecurity } else { $acl=New-Object Security.AccessControl.FileSecurity }
24新增: $acl.SetOwner($user.User);$acl.SetAccessRuleProtection($true,$false)
25新增: foreach ($sid in @($user.User,[Security.Principal.SecurityIdentifier]'S-1-5-18',[Security.Principal.SecurityIdentifier]'S-1-5-32-544')) {
26新增: if ($Directory) { $rule=New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow') }
27新增: else { $rule=New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','Allow') }
28新增: $acl.AddAccessRule($rule)
29新增: }
30新增: Set-Acl -LiteralPath $Path -AclObject $acl
31新增:}
32新增:function PrivateDirectory([string]$Path) {
33新增: $parent=[IO.DirectoryInfo]$Path
34新增: while (-not $parent.Exists) { $parent=$parent.Parent;if($null -eq $parent){throw 'Invalid native tool parent.'} }
35新增: Assert-NoReparse $parent.FullName
36新增: if(-not (Test-Path -LiteralPath $Path)){New-Item -ItemType Directory -Path $Path | Out-Null}
37新增: Assert-NoReparse $Path;Protect-Path $Path $true
38新增:}
39新增:Assert-NoReparse $RuntimeArchive;Assert-NoReparse $NodeArchive;Assert-NoReparse $bridge
40新增:if ((Get-FileHash $RuntimeArchive -Algorithm SHA256).Hash.ToLowerInvariant() -ne 'a0ab3bbac6b2c14ba53020474a4d6a6b307b9faf6f10998568b3200535c6b3e7') { throw 'CCS runtime archive checksum failed.' }
41新增:if ((Get-FileHash $NodeArchive -Algorithm SHA256).Hash.ToLowerInvariant() -ne 'ca1bff5d8ead13c9f2ea404a176db46bd430704d5b5113734049fa365e7799e2') { throw 'Official Node archive checksum failed.' }
42新增:$tools=Join-Path $env:USERPROFILE 'Cage\CLI\tools';PrivateDirectory $tools
43新增:$runtime=Join-Path $tools 'ccs\8.11.0'
44新增:if (-not (Test-Path -LiteralPath $runtime)) {
45新增: $parent=Split-Path $runtime -Parent;PrivateDirectory $parent
46新增: $stage=Join-Path $parent ('stage-'+[Guid]::NewGuid().ToString('N'));PrivateDirectory $stage
47新增: & (Join-Path $env:SystemRoot 'System32\tar.exe') -xzf $RuntimeArchive -C $stage
48新增: if($LASTEXITCODE -ne 0){throw 'CCS archive extraction failed; staged files were retained.'}
49新增: [IO.Directory]::Move($stage,$runtime)
50新增:}
51新增:Assert-NoReparse $runtime
52新增:$manifest=Join-Path $runtime 'runtime-files.json'
53新增:$files=Get-Content -LiteralPath $manifest -Raw | ConvertFrom-Json
54新增:foreach($entry in $files.PSObject.Properties) {
55新增: $file=[IO.Path]::GetFullPath((Join-Path $runtime $entry.Name))
56新增: if(-not $file.StartsWith($runtime+'\',[StringComparison]::OrdinalIgnoreCase)){throw 'CCS runtime contains an invalid path.'}
57新增: Assert-NoReparse $file
58新增: if((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() -ne $entry.Value){throw 'A CCS runtime file changed.'}
59新增:}
60新增:$nodeSha='1c331340fa6cac5e4294725959070a143fa0507195a78ad77eed7943f719aac9'
61新增:if ($ExistingNode -ne '') {
62新增: Assert-NoReparse $ExistingNode
63新增: if((Get-FileHash $ExistingNode -Algorithm SHA256).Hash.ToLowerInvariant() -ne $nodeSha){throw 'Existing Node does not match the fixed official version.'}
64新增: $node=[IO.Path]::GetFullPath($ExistingNode)
65新增:} else {
66新增: $nodeDir=Join-Path $tools 'node\24.22.2';PrivateDirectory $nodeDir
67新增: $node=Join-Path $nodeDir 'node-v24.22.2-win-x64\node.exe'
68新增: if(-not(Test-Path -LiteralPath $node)){Expand-Archive -LiteralPath $NodeArchive -DestinationPath $nodeDir}
69新增: Assert-NoReparse $node
70新增: if((Get-FileHash $node -Algorithm SHA256).Hash.ToLowerInvariant() -ne $nodeSha){throw 'Native Node changed.'}
71新增:}
72新增:$signature=Get-AuthenticodeSignature -FilePath $node
73新增:if($signature.Status -ne 'Valid'){throw 'Native Node signature is invalid.'}
74新增:$main=Join-Path $runtime 'node_modules\@kaitranntt\ccs\dist\ccs.js'
75新增:$receiptDir=[IO.Path]::GetFullPath($ReceiptDirectory)
76新增:$allowed=[IO.Path]::GetFullPath((Join-Path $env:USERPROFILE 'Cage\CLI'))
77新增:if(-not $receiptDir.StartsWith($allowed+'\',[StringComparison]::OrdinalIgnoreCase)){throw 'Receipt staging must stay in the current user Cage CLI directory.'}
78新增:PrivateDirectory $receiptDir
79新增:$receipt=[ordered]@{version=1;node=$node;node_version='24.22.2';node_sha256=$nodeSha;main=$main;main_sha256=(Get-FileHash $main -Algorithm SHA256).Hash.ToLowerInvariant();manifest=$manifest;manifest_sha256=(Get-FileHash $manifest -Algorithm SHA256).Hash.ToLowerInvariant();ccs_version='8.11.0'}
80新增:$temporary=Join-Path $receiptDir ('ccs-tools.'+[Guid]::NewGuid().ToString('N')+'.json')
81新增:[IO.File]::WriteAllText($temporary,($receipt | ConvertTo-Json),(New-Object Text.UTF8Encoding($false)))
82新增:Protect-Path $temporary $false
83新增:Move-Item -LiteralPath $temporary -Destination (Join-Path $receiptDir 'ccs-tools.json') -Force
84新增:Write-Output 'Native CCS runtime validated. Management must copy the staged ccs-tools.json into the readonly paired bridge. Existing CCS profiles and credentials were not imported or changed.'
新增scripts/guest-os/guest-clipboard-windows/install-cli.ps1+122 −0看文件
@@ -0,0 +1,122 @@
1新增:# Run as the already paired ordinary GUI user. All packages are staged offline;
2新增:# this installer changes only Cage-owned tool files and the bridge receipt.
3新增:[CmdletBinding()]
4新增:param(
5新增: [Parameter(Mandatory)][string]$BundleDirectory,
6新增: [Parameter(Mandatory)][string]$BridgeDirectory,
7新增: [string]$ReceiptDirectory = (Join-Path $env:USERPROFILE 'Cage\CLI\install-receipts'),
8新增: [switch]$WorkbenchSetup
9新增:)
10新增:$ErrorActionPreference = 'Stop'
11新增:Set-StrictMode -Version Latest
12新增:if (-not [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform([System.Runtime.InteropServices.OSPlatform]::Windows)) { throw 'Native Windows is required.' }
13新增:$user = [Security.Principal.WindowsIdentity]::GetCurrent()
14新增:if ((New-Object Security.Principal.WindowsPrincipal($user)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Use the paired ordinary GUI user.' }
15新增:$manifest = Get-Content (Join-Path $PSScriptRoot 'cli-dependencies.json') -Raw | ConvertFrom-Json
16新增:$bundle = [IO.Path]::GetFullPath($BundleDirectory)
17新增:$bridge = [IO.Path]::GetFullPath($BridgeDirectory)
18新增:if (-not (Test-Path (Join-Path $bridge 'Cage.GuestClipboard.exe') -PathType Leaf)) { throw 'The paired GUI bridge must be installed first.' }
19新增:function Assert-NoReparse([string]$Path) {
20新增: $item = Get-Item -LiteralPath $Path -Force
21新增: while ($null -ne $item) {
22新增: if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'A Cage tool path is a reparse point.' }
23新增: if ($item -is [IO.FileInfo]) { $item = $item.Directory } else { $item = $item.Parent }
24新增: }
25新增:}
26新增:function Protect-Path([string]$Path, [bool]$Directory) {
27新增: if ($Directory) { $acl = New-Object Security.AccessControl.DirectorySecurity } else { $acl = New-Object Security.AccessControl.FileSecurity }
28新增: $acl.SetOwner($user.User); $acl.SetAccessRuleProtection($true, $false)
29新增: foreach ($sid in @($user.User, [Security.Principal.SecurityIdentifier]'S-1-5-18', [Security.Principal.SecurityIdentifier]'S-1-5-32-544')) {
30新增: if ($Directory) { $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow') }
31新增: else { $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','Allow') }
32新增: $acl.AddAccessRule($rule)
33新增: }
34新增: Set-Acl -LiteralPath $Path -AclObject $acl
35新增:}
36新增:function New-PrivateDirectory([string]$Path) {
37新增: $parent = [IO.DirectoryInfo]$Path
38新增: while (-not $parent.Exists) { $parent = $parent.Parent; if ($null -eq $parent) { throw 'A Cage tool parent is invalid.' } }
39新增: Assert-NoReparse $parent.FullName
40新增: if (-not (Test-Path -LiteralPath $Path)) { New-Item -ItemType Directory -Path $Path | Out-Null }
41新增: Assert-NoReparse $Path; Protect-Path $Path $true
42新增:}
43新增:function Check-Package($Entry) {
44新增: $path = Join-Path $bundle $Entry.filename
45新增: Assert-NoReparse $path
46新增: if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -ne $Entry.sha256) { throw 'An offline native package failed its fixed checksum.' }
47新增: return $path
48新增:}
49新增:$packages = @{}
50新增:foreach ($name in @('uv','python','claude','git')) { $packages[$name] = Check-Package $manifest.$name }
51新增:foreach ($name in @('claude','git')) {
52新增: $signature = Get-AuthenticodeSignature -FilePath $packages[$name]
53新增: if ($signature.Status -ne 'Valid') { throw 'An official Windows executable has an invalid Authenticode signature.' }
54新增: if ($name -eq 'claude' -and $signature.SignerCertificate.Subject -notmatch 'Anthropic,? PBC') { throw 'The native Claude binary has the wrong signer.' }
55新增:}
56新增:$tools = Join-Path $env:USERPROFILE 'Cage\CLI\tools'
57新增:New-PrivateDirectory $tools
58新增:$uvDir = Join-Path $tools ('uv\' + $manifest.uv.version)
59新增:New-PrivateDirectory $uvDir
60新增:$uv = Join-Path $uvDir 'uv.exe'
61新增:if (-not (Test-Path -LiteralPath $uv)) { Expand-Archive -LiteralPath $packages.uv -DestinationPath $uvDir }
62新增:Assert-NoReparse $uv
63新增:Add-Type -AssemblyName System.IO.Compression.FileSystem
64新增:$zip = [IO.Compression.ZipFile]::OpenRead($packages.uv)
65新增:try {
66新增: $entry = $zip.Entries | Where-Object { $_.FullName -eq 'uv.exe' } | Select-Object -First 1
67新增: if ($null -eq $entry) { throw 'The fixed uv archive has no native executable.' }
68新增: $reader = $entry.Open(); $hasher = [Security.Cryptography.SHA256]::Create()
69新增: try { $expected = ([BitConverter]::ToString($hasher.ComputeHash($reader))).Replace('-','').ToLowerInvariant() } finally { $reader.Dispose(); $hasher.Dispose() }
70新增: if ((Get-FileHash $uv -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expected) { throw 'The Cage-owned uv executable changed.' }
71新增:} finally { $zip.Dispose() }
72新增:if ((& $uv --version) -notmatch ('^uv ' + [Regex]::Escape($manifest.uv.version) + '(?: |$)')) { throw 'The offline uv version does not match.' }
73新增:$pythonDir = Join-Path $tools 'python'
74新增:New-PrivateDirectory $pythonDir
75新增:$pythonMeta = Join-Path $tools ('python-' + $manifest.python.version + '.json')
76新增:$download = [ordered]@{name='cpython';arch=@{family='x86_64';variant=$null};os='windows';libc='none';major=3;minor=13;patch=18;prerelease='';url=([Uri]$packages.python).AbsoluteUri;sha256=$manifest.python.sha256;variant=$null;build='20261026'}
77新增:$metadata = @{}; $metadata[$manifest.python.key] = $download
78新增:[IO.File]::WriteAllText($pythonMeta, ($metadata | ConvertTo-Json -Depth 5), (New-Object Text.UTF8Encoding($false)))
79新增:Protect-Path $pythonMeta $false
80新增:$oldCache = [Environment]::GetEnvironmentVariable('UV_PYTHON_CACHE_DIR', 'Process')
81新增:try {
82新增: [Environment]::SetEnvironmentVariable('UV_PYTHON_CACHE_DIR', $null, 'Process')
83新增: & $uv python install $manifest.python.key --install-dir $pythonDir --no-bin --no-registry --no-config --offline --python-downloads-json-url $pythonMeta
84新增: if ($LASTEXITCODE -ne 0) { throw 'Offline uv Python installation failed.' }
85新增:} finally { [Environment]::SetEnvironmentVariable('UV_PYTHON_CACHE_DIR', $oldCache, 'Process') }
86新增:$python = Join-Path $pythonDir ($manifest.python.key + '\python.exe')
87新增:Assert-NoReparse $python
88新增:if ((& $python -X utf8 -I -c 'import platform; print(platform.python_version())') -ne $manifest.python.version) { throw 'The native Python version does not match.' }
89新增:$gitDir = Join-Path $tools ('git\' + $manifest.git.version)
90新增:if (-not (Test-Path (Join-Path $gitDir 'bin\bash.exe'))) {
91新增: New-PrivateDirectory $gitDir
92新增: $extract = Start-Process -FilePath $packages.git -ArgumentList @('-y', ('-o"' + $gitDir + '"')) -Wait -PassThru -NoNewWindow
93新增: if ($extract.ExitCode -ne 0) { throw 'Portable Git extraction failed.' }
94新增:}
95新增:$bash = Join-Path $gitDir 'bin\bash.exe'; Assert-NoReparse $bash
96新增:$claudeDir = Join-Path $tools ('claude\' + $manifest.claude.version)
97新增:New-PrivateDirectory $claudeDir
98新增:$claude = Join-Path $claudeDir 'claude.exe'
99新增:if (-not (Test-Path -LiteralPath $claude)) { [IO.File]::Copy($packages.claude, $claude, $false) }
100新增:if ((Get-FileHash -LiteralPath $claude -Algorithm SHA256).Hash.ToLowerInvariant() -ne $manifest.claude.sha256) { throw 'The Cage-owned native Claude binary changed.' }
101新增:# The official native binary is used as a versioned custom launcher. No default
102新增:# Claude account, existing installer, project, settings or history is replaced.
103新增:$receipt = [ordered]@{version=1;python=$python;python_version=$manifest.python.version;python_sha256=(Get-FileHash $python -Algorithm SHA256).Hash.ToLowerInvariant();claude=$claude;claude_version=$manifest.claude.version;claude_sha256=$manifest.claude.sha256;git_bash=$bash;git_bash_sha256=(Get-FileHash $bash -Algorithm SHA256).Hash.ToLowerInvariant();uv_version=$manifest.uv.version}
104新增:Assert-NoReparse $bridge
105新增:if ($WorkbenchSetup) {
106新增: # The provisioning process owns this file and its directory. The paired
107新增: # user can write the receipt, but cannot replace the file or change its ACL.
108新增: $staged = Join-Path $bridge 'setup-packages\cli-receipt.in'
109新增: Assert-NoReparse $staged
110新增: [IO.File]::WriteAllText($staged, ($receipt | ConvertTo-Json), (New-Object Text.UTF8Encoding($false)))
111新增: return
112新增:}
113新增:$receiptDir = [IO.Path]::GetFullPath($ReceiptDirectory)
114新增:$receiptRoot = [IO.Path]::GetFullPath((Join-Path $env:USERPROFILE 'Cage\CLI'))
115新增:if (-not $receiptDir.StartsWith($receiptRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'The receipt staging directory must be inside the current user Cage CLI directory.' }
116新增:New-PrivateDirectory $receiptDir
117新增:$target = Join-Path $receiptDir 'cli-tools.json'
118新增:$temporary = Join-Path $receiptDir ('cli-tools.' + [Guid]::NewGuid().ToString('N') + '.json')
119新增:[IO.File]::WriteAllText($temporary, ($receipt | ConvertTo-Json), (New-Object Text.UTF8Encoding($false)))
120新增:Protect-Path $temporary $false
121新增:Move-Item -LiteralPath $temporary -Destination $target -Force
122新增:Write-Output 'Native Cage CLI tools installed. Management must copy the staged receipt into the readonly paired bridge, then restart only that bridge. Official account login remains user-controlled.'
新增scripts/guest-os/guest-clipboard-windows/install-network.ps1+76 −0看文件
@@ -0,0 +1,76 @@
1新增:#requires -Version 5.1
2新增:#requires -RunAsAdministrator
3新增:[CmdletBinding(SupportsShouldProcess)]
4新增:param(
5新增: [Parameter(Mandatory)][string]$ProfilePath,
6新增: [Parameter(Mandatory)][pscredential]$GuestAdministrator,
7新增: [Parameter(Mandatory)][string]$AgentPath,
8新增: [Parameter(Mandatory)][string]$WintunPath,
9新增: [Parameter(Mandatory)][string]$WintunLicense,
10新增: [object]$HostEnrollment
11新增:)
12新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
13新增:$binding=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json
14新增:if($HostEnrollment -and [guid]$HostEnrollment.VMID -ne [guid]$binding.vm_id){throw 'Original host enrollment does not match this packet bridge.'}
15新增:$vm=Get-VM -Id ([guid]$binding.vm_id)
16新增:if($binding.version -ne 1 -or $vm.State -ne 'Running' -or $binding.gui_user_sid -notmatch '^S-1-5-21-' -or
17新增: @(Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or $binding.network_pairing_file){throw 'Use the existing running zero-NIC guest binding without a prior packet pairing.'}
18新增:if((Get-FileHash -LiteralPath $WintunPath -Algorithm SHA256).Hash -cne 'E5DA8447DC2C320EDC0FC52FA01885C103DE8C118481F683643CACC3220DAFCE'){throw 'Unexpected pinned Wintun payload.'}
19新增:if((Get-AuthenticodeSignature -LiteralPath $WintunPath).Status -ne 'Valid'){throw 'Windows did not validate the official Wintun signature.'}
20新增:if(!$PSCmdlet.ShouldProcess($vm.Id,'Install the separate SYSTEM packet bridge without adding a Hyper-V NIC')){return}
21新增:$session=New-PSSession -VMId $vm.Id -Credential $GuestAdministrator
22新增:try {
23新增: $target=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid -ScriptBlock {
24新增: param($id,$sid)
25新增: $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
26新增: if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $id){throw 'guest_identity_mismatch'}
27新增: $program=Join-Path $env:ProgramFiles ("Cage Guest Network\"+$id);$data=Join-Path $env:ProgramData ("Cage\PacketBridge\"+$id);$name="Cage-Packet-Bridge-$id"
28新增: if((Test-Path -LiteralPath $program) -or (Test-Path -LiteralPath $data) -or (Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue)){throw 'A packet deployment already exists; preserve its key and interface.'}
29新增: foreach($directory in @($program,$data)){
30新增: $current=$directory;while($current){if(Test-Path -LiteralPath $current){if((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Packet deployment paths must not traverse links.'}};$current=[IO.Path]::GetDirectoryName($current)}
31新增: $null=New-Item -ItemType Directory -Path $directory -Force
32新增: $acl=[Security.AccessControl.DirectorySecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))
33新增: foreach($owner in @('S-1-5-18','S-1-5-32-544')){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($owner),'FullControl','ContainerInherit,ObjectInherit','None','Allow'))}
34新增: if($directory -eq $program){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow'))}
35新增: Set-Acl -LiteralPath $directory -AclObject $acl
36新增: }
37新增: [pscustomobject]@{Program=$program;Data=$data;Task=$name}
38新增: }
39新增: Copy-Item -LiteralPath $AgentPath -Destination (Join-Path $target.Program 'Cage.GuestNetwork.exe') -ToSession $session
40新增: Copy-Item -LiteralPath $WintunPath -Destination (Join-Path $target.Program 'wintun.dll') -ToSession $session
41新增: Copy-Item -LiteralPath $WintunLicense -Destination (Join-Path $target.Program 'WINTUN-LICENSE.txt') -ToSession $session
42新增: $secret=New-Object byte[] 32;$random=[Security.Cryptography.RandomNumberGenerator]::Create();$random.GetBytes($secret);$random.Dispose()
43新增: try {
44新增: Invoke-Command -Session $session -ArgumentList $target.Program,$target.Data,$secret -ScriptBlock {
45新增: param($program,$data,[byte[]]$secret)
46新增: $ErrorActionPreference='Stop';$admin=[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
47新增: foreach($entry in (Get-ChildItem -LiteralPath $program -File)){$acl=Get-Acl -LiteralPath $entry.FullName;$acl.SetOwner($admin);Set-Acl -LiteralPath $entry.FullName -AclObject $acl}
48新增: $acl=[Security.AccessControl.FileSecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner($admin)
49新增: foreach($owner in @('S-1-5-18','S-1-5-32-544')){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($owner),'FullControl','Allow'))}
50新增: $stream=[IO.FileStream]::new((Join-Path $data 'packet.bin'),[IO.FileMode]::CreateNew,[Security.AccessControl.FileSystemRights]::Write,[IO.FileShare]::None,4096,[IO.FileOptions]::None,$acl)
51新增: try{$stream.Write($secret,0,$secret.Length);$stream.Flush($true)}finally{$stream.Dispose()}
52新增: if((Get-FileHash -LiteralPath (Join-Path $program 'wintun.dll') -Algorithm SHA256).Hash -cne 'E5DA8447DC2C320EDC0FC52FA01885C103DE8C118481F683643CACC3220DAFCE'){throw 'Guest Wintun transfer digest differs.'}
53新增: }
54新增: Add-Type -AssemblyName System.Security
55新增: $entropy=[Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes("Cage.HyperV.v1:$($vm.Id.ToString('D')):$($binding.gui_user_sid)"))
56新增: $pair=Join-Path ([IO.Path]::GetDirectoryName($ProfilePath)) 'packet.dpapi';if(Test-Path -LiteralPath $pair){throw 'A host packet pairing already exists.'}
57新增: if(!$HostEnrollment){[IO.File]::WriteAllBytes($pair,[Security.Cryptography.ProtectedData]::Protect($secret,$entropy,'CurrentUser'));Set-Acl -LiteralPath $pair -AclObject (Get-Acl -LiteralPath $binding.pairing_file)}
58新增: $service='f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fb';$key="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\GuestCommunicationServices\$service"
59新增: if(Test-Path -LiteralPath $key){if((Get-ItemProperty -LiteralPath $key).ElementName -cne 'Cage Packet Guest Bridge v1'){throw 'The packet service GUID is owned by another application.'}}
60新增: else{$null=New-Item -Path $key;New-ItemProperty -LiteralPath $key -Name ElementName -Value 'Cage Packet Guest Bridge v1' -PropertyType String|Out-Null}
61新增: Invoke-Command -Session $session -ArgumentList $target.Program,$target.Data,$target.Task,$vm.Id,$binding.gui_user_sid -ScriptBlock {
62新增: param($program,$data,$name,$vm,$sid)
63新增: $exe=Join-Path $program 'Cage.GuestNetwork.exe';$key=Join-Path $data 'packet.bin'
64新增: $action=New-ScheduledTaskAction -Execute $exe -Argument "serve-network --vm-id $vm --sid $sid --token-file `"$key`""
65新增: $principal=New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -LogonType ServiceAccount -RunLevel Highest
66新增: $settings=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew
67新增: $null=Register-ScheduledTask -TaskName $name -Action $action -Principal $principal -Trigger (New-ScheduledTaskTrigger -AtStartup) -Settings $settings -Description "Cage protected packet bridge $vm $sid"
68新增: }
69新增: $binding|Add-Member -NotePropertyName network_pairing_file -NotePropertyValue $pair
70新增: $stage=$ProfilePath+'.packet-stage';[IO.File]::WriteAllText($stage,($binding|ConvertTo-Json -Compress)+[Environment]::NewLine,[Text.UTF8Encoding]::new($false));Set-Acl -LiteralPath $stage -AclObject (Get-Acl -LiteralPath $ProfilePath);[IO.File]::Replace($stage,$ProfilePath,[Management.Automation.Language.NullString]::Value)
71新增: Invoke-Command -Session $session -ArgumentList $target.Task -ScriptBlock {param($name);Start-ScheduledTask -TaskName $name}
72新增: if($HostEnrollment){. (Join-Path $PSScriptRoot '../windows-host-enrollment.ps1');Send-CageHostEnrollmentKey $HostEnrollment 'packet' $binding.gui_user_sid $secret}
73新增: if(@(Get-VMNetworkAdapter -VM (Get-VM -Id $vm.Id)).Count -ne 0){throw 'Hyper-V networking changed during packet setup.'}
74新增: [pscustomobject]@{PacketTaskRegistered=$true;SystemKeyProtected=$true;IndependentHostPairing=$true;HyperVAdapters=0;NetworkConfigured=$false}
75新增: }finally{[Array]::Clear($secret,0,$secret.Length)}
76新增:}finally{Remove-PSSession $session}
新增scripts/guest-os/guest-clipboard-windows/install.ps1+124 −0看文件
@@ -0,0 +1,124 @@
1新增:#requires -Version 5.1
2新增:#requires -RunAsAdministrator
3新增:<#
4新增:.SYNOPSIS
5新增:Bind one existing offline Hyper-V guest and its existing interactive user.
6新增:.DESCRIPTION
7新增:PowerShell Direct is only the authenticated management transport. The agent is
8新增:registered as an InteractiveToken, Limited task for the supplied SID; it cannot
9新增:use a management/Session0 clipboard. This script does not log a user in, create
10新增:accounts, change VM networking, accept licenses or replace a running agent.
11新增:Supply a new protected host profile directory. The returned binding contains
12新增:only paths and identities; its separate pairing is DPAPI CurrentUser protected.
13新增:#>
14新增:[CmdletBinding(SupportsShouldProcess)]
15新增:param(
16新增: [Parameter(Mandatory)][guid]$VMId,
17新增: [Parameter(Mandatory)][string]$InstanceDirectory,
18新增: [Parameter(Mandatory)][ValidatePattern('^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+$')][string]$GUIUserSID,
19新增: [Parameter(Mandatory)][pscredential]$GuestAdministrator,
20新增: [Parameter(Mandatory)][string]$PayloadDirectory,
21新增: [Parameter(Mandatory)][string]$HostProfileDirectory,
22新增: [string]$HostUserSID = ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value),
23新增: [object]$HostEnrollment
24新增:)
25新增:$ErrorActionPreference='Stop'
26新增:$ProgressPreference='SilentlyContinue'
27新增:if($HostUserSID -notmatch '^S-1-(5-21|12-1)-(\d+-){3}\d+$' -or
28新增: ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value -cne $HostUserSID -and !$HostEnrollment)){throw 'Another host user requires the original enrollment process.'}
29新增:if($HostEnrollment -and ($HostEnrollment.HostSID -cne $HostUserSID -or [guid]$HostEnrollment.VMID -ne $VMId)){throw 'Original host enrollment does not match this bridge.'}
30新增:$service='f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fa'
31新增:function Assert-LocalAncestors([string]$Path){
32新增: if(![IO.Path]::IsPathRooted($Path) -or $Path.StartsWith('\\') -or [IO.DriveInfo]::new([IO.Path]::GetPathRoot($Path)).DriveType -ne 'Fixed'){throw 'A local fixed-disk path is required.'}
33新增: $current=$Path
34新增: while($current){if(Test-Path -LiteralPath $current){if((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Deployment paths must not traverse links.'}};$current=[IO.Path]::GetDirectoryName($current)}
35新增:}
36新增:$vm=Get-VM -Id $VMId
37新增:$instance=Get-Item -LiteralPath $InstanceDirectory
38新增:$payload=Get-Item -LiteralPath $PayloadDirectory
39新增:if ($VMId -eq [guid]::Empty -or $vm.State -ne 'Running' -or $instance -isnot [IO.DirectoryInfo] -or
40新增: $payload -isnot [IO.DirectoryInfo] -or $instance.Attributes -band [IO.FileAttributes]::ReparsePoint -or
41新增: !($vm.ConfigurationLocation -eq $instance.FullName -or $vm.ConfigurationLocation.StartsWith($instance.FullName.TrimEnd('\')+'\',[StringComparison]::OrdinalIgnoreCase)) -or
42新增: @(Get-VMNetworkAdapter -VM $vm).Count -ne 0) { throw 'Supply the exact running, retained zero-NIC guest and its private instance directory.' }
43新增:$profile=$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($HostProfileDirectory)
44新增:foreach($path in @($profile,$instance.FullName,$payload.FullName)){Assert-LocalAncestors $path}
45新增:if (!(Test-Path -LiteralPath ([IO.Path]::GetDirectoryName($profile))) -or (Test-Path -LiteralPath $profile)) { throw 'Supply a new host profile directory under an existing local parent.' }
46新增:foreach($file in @('Cage.GuestClipboard.exe','cage-guest-files.exe')) {
47新增: $entry=Get-Item -LiteralPath (Join-Path $payload.FullName $file)
48新增: if($entry -isnot [IO.FileInfo] -or $entry.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'The fixed GUI agent and file helper payloads are required.'}
49新增:}
50新增:if(!$PSCmdlet.ShouldProcess($VMId,'Install a protected GUI clipboard bridge and bind this host user')){return}
51新增:$session=New-PSSession -VMId $VMId -Credential $GuestAdministrator
52新增:try {
53新增: $checked=Invoke-Command -Session $session -ArgumentList $VMId,$GUIUserSID -ScriptBlock {
54新增: param($expected,$sid)
55新增: $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
56新增: $kvp=Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters' -Name VirtualMachineId
57新增: if([guid]$kvp.VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'}
58新增: $users=@(Get-LocalUser | Where-Object {$_.SID.Value -eq $sid -and $_.Enabled})
59新增: if($users.Count -ne 1){throw 'The independently selected GUI SID is not an enabled existing local user.'}
60新增: $name="Cage-GUI-Bridge-$expected-$sid"
61新增: if(Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue){throw 'A bridge task already exists; preserve the running user session and use its existing binding.'}
62新增: $program=Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$expected)
63新增: $data=Join-Path $env:ProgramData ("Cage\GuestBridge\"+$expected)
64新增: foreach($directory in @($program,$data)){$current=$directory;while($current){if(Test-Path -LiteralPath $current){if((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Guest deployment paths must not traverse links.'}};$current=[IO.Path]::GetDirectoryName($current)}}
65新增: if((Test-Path -LiteralPath $program) -or (Test-Path -LiteralPath $data)){throw 'A guest bridge deployment already exists; preserve it.'}
66新增: foreach($directory in @($program,$data)){
67新增: $null=New-Item -ItemType Directory -Path $directory -Force
68新增: $acl=[Security.AccessControl.DirectorySecurity]::new();$acl.SetAccessRuleProtection($true,$false)
69新增: foreach($owner in @('S-1-5-18','S-1-5-32-544')){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($owner),'FullControl','ContainerInherit,ObjectInherit','None','Allow'))}
70新增: $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow'))
71新增: Set-Acl -LiteralPath $directory -AclObject $acl
72新增: }
73新增: [pscustomobject]@{Program=$program;Data=$data;Task=$name;User=$users[0].Name}
74新增: }
75新增: # Copy only the caller-selected payload directory. Optional Node/browser
76新增: # dependencies remain local to this deployment and never need a guest NIC.
77新增: Get-ChildItem -LiteralPath $payload.FullName -File|ForEach-Object {
78新增: if($_.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Payload links are not allowed.'}
79新增: Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $checked.Program $_.Name) -ToSession $session
80新增: }
81新增: $secret=New-Object byte[] 32;$random=[Security.Cryptography.RandomNumberGenerator]::Create();$random.GetBytes($secret);$random.Dispose()
82新增: try {
83新增: Invoke-Command -Session $session -ArgumentList $checked.Data,$secret,$GUIUserSID -ScriptBlock {
84新增: param($data,[byte[]]$secret,$sid)
85新增: $file=Join-Path $data 'pairing.bin';[IO.File]::WriteAllBytes($file,$secret)
86新增: $acl=[Security.AccessControl.FileSecurity]::new();$acl.SetAccessRuleProtection($true,$false)
87新增: foreach($owner in @('S-1-5-18','S-1-5-32-544')){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($owner),'FullControl','Allow'))}
88新增: $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'Read','Allow'));Set-Acl -LiteralPath $file -AclObject $acl
89新增: }
90新增: $hostSID=[Security.Principal.SecurityIdentifier]::new($HostUserSID)
91新增: $hostOwner=if($HostEnrollment){[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')}else{$hostSID}
92新增: $acl=[Security.AccessControl.DirectorySecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner($hostOwner)
93新增: foreach($sid in @($hostSID,[Security.Principal.SecurityIdentifier]::new('S-1-5-18'),[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))}
94新增: $null=New-Item -ItemType Directory -Path $profile;Set-Acl -LiteralPath $profile -AclObject $acl
95新增: foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -File)){Copy-Item -LiteralPath $entry.FullName -Destination (Join-Path $profile $entry.Name)}
96新增: Add-Type -AssemblyName System.Security
97新增: $entropy=[Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes("Cage.HyperV.v1:$($VMId.ToString('D')):$GUIUserSID"))
98新增: $pairing=Join-Path $profile 'pairing.dpapi'
99新增: # The relay verifies protected file ACLs independently before decrypting.
100新增: $fileACL=[Security.AccessControl.FileSecurity]::new();$fileACL.SetAccessRuleProtection($true,$false);$fileACL.SetOwner($hostOwner)
101新增: foreach($sid in @($hostSID,[Security.Principal.SecurityIdentifier]::new('S-1-5-18'),[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))){$fileACL.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','Allow'))}
102新增: if(!$HostEnrollment){[IO.File]::WriteAllBytes($pairing,[Security.Cryptography.ProtectedData]::Protect($secret,$entropy,'CurrentUser'));Set-Acl -LiteralPath $pairing -AclObject $fileACL}
103新增: $key="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\GuestCommunicationServices\$service"
104新增: if(Test-Path -LiteralPath $key){if((Get-ItemProperty -LiteralPath $key).ElementName -cne 'Cage GUI Guest Bridge v1'){throw 'The fixed service GUID is owned by another application.'}}
105新增: else{$null=New-Item -Path $key;New-ItemProperty -LiteralPath $key -Name ElementName -Value 'Cage GUI Guest Bridge v1' -PropertyType String|Out-Null}
106新增: $task=Invoke-Command -Session $session -ArgumentList $checked.Program,$checked.Data,$checked.Task,$GUIUserSID,$VMId -ScriptBlock {
107新增: param($program,$data,$name,$sid,$vm)
108新增: $executable=Join-Path $program 'Cage.GuestClipboard.exe';$token=Join-Path $data 'pairing.bin'
109新增: $action=New-ScheduledTaskAction -Execute $executable -Argument "serve --vm-id $vm --sid $sid --token-file `"$token`""
110新增: $trigger=New-ScheduledTaskTrigger -AtLogOn -User $sid
111新增: $principal=New-ScheduledTaskPrincipal -UserId $sid -LogonType Interactive -RunLevel Limited
112新增: $settings=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew
113新增: $null=Register-ScheduledTask -TaskName $name -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "Cage protected GUI bridge $vm $sid"
114新增: $gui=@(Get-CimInstance Win32_Process -Filter "Name='explorer.exe'"|Where-Object {$_.SessionId -gt 0}|ForEach-Object {Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid}|Where-Object {$_.Sid -eq $sid}).Count -gt 0
115新增: if($gui){Start-ScheduledTask -TaskName $name}
116新增: [pscustomobject]@{Registered=$true;GUIAlreadyLoggedIn=$gui}
117新增: }
118新增: $binding=[ordered]@{version=1;vm_id=$VMId.ToString('D');gui_user_sid=$GUIUserSID;gui_user=$checked.User;instance_directory=$instance.FullName;relay_executable=(Join-Path $profile 'Cage.GuestClipboard.exe');pairing_file=$pairing}
119新增: $path=Join-Path $profile 'windows-guest.json';[IO.File]::WriteAllText($path,($binding|ConvertTo-Json -Compress)+[Environment]::NewLine,[Text.UTF8Encoding]::new($false));Set-Acl -LiteralPath $path -AclObject $fileACL
120新增: if($HostEnrollment){. (Join-Path $PSScriptRoot '../windows-host-enrollment.ps1');Send-CageHostEnrollmentKey $HostEnrollment 'gui' $GUIUserSID $secret}
121新增: if(@(Get-VMNetworkAdapter -VM (Get-VM -Id $VMId)).Count -ne 0){throw 'VM networking changed during deployment.'}
122新增: [pscustomobject]@{Profile=$path;VMId=$VMId;GUIUserSID=$GUIUserSID;TaskRegistered=$task.Registered;RequiresGUILogin=(!$task.GUIAlreadyLoggedIn)}
123新增: } finally { [Array]::Clear($secret,0,$secret.Length) }
124新增:} finally { Remove-PSSession $session }
新增scripts/guest-os/guest-clipboard-windows/qa-browser.ps1+184 −0看文件
@@ -0,0 +1,184 @@
1新增:#requires -Version 5.1
2新增:param(
3新增: [Parameter(Mandatory)][string]$ProfilePath,
4新增: [Parameter(Mandatory)][string]$CredentialFile,
5新增: [Parameter(Mandatory)][string]$FixturePath,
6新增: [Parameter(Mandatory)][string]$EvidenceDirectory,
7新增: [switch]$SplitOnly,
8新增: [switch]$PerfOnly
9新增:)
10新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
11新增:[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)
12新增:$utf8=[Text.UTF8Encoding]::new($false)
13新增:$copiedFixtureText=$utf8.GetString([Convert]::FromBase64String('Q2FnZSBuYXRpdmUgY29weSDkuK3mlofwn5mC'))
14新增:$binding=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json
15新增:$vm=Get-VM -Id ([guid]$binding.vm_id)
16新增:if($binding.version -ne 1 -or $vm.State -ne 'Running' -or @(Get-VMNetworkAdapter -VM $vm).Count -ne 0){throw 'The independently bound offline guest is not ready.'}
17新增:$credential=Import-Clixml -LiteralPath $CredentialFile
18新增:if(($credential.UserName -split '\\')[-1] -cne 'CageLabSetup'){throw 'The retained QA administrator identity does not match.'}
19新增:$credential=[pscredential]::new('CageLabSetup',$credential.Password)
20新增:$session=New-PSSession -VMId $vm.Id -Credential $credential
21新增:$owned=[Collections.Generic.List[Diagnostics.Process]]::new();$tabs=[Collections.Generic.List[string]]::new()
22新增:$results=[ordered]@{};$script:phase='starting'
23新增:function Bridge([string]$Operation){
24新增: $s=[Diagnostics.ProcessStartInfo]::new();$s.FileName=$binding.relay_executable
25新增: $s.Arguments='--relay-profile "'+$ProfilePath+'" '+$Operation
26新增: $s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardInput=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$s.StandardOutputEncoding=$utf8
27新增: $p=[Diagnostics.Process]::Start($s);$owned.Add($p);$null=$p.StandardError.ReadToEndAsync();return $p
28新增:}
29新增:function Send($p,$value){$bytes=$utf8.GetBytes((ConvertTo-Json -InputObject $value -Compress -Depth 12)+"`n");$p.StandardInput.BaseStream.Write($bytes,0,$bytes.Length);$p.StandardInput.BaseStream.Flush()}
30新增:function Read($p){$pending=$p.StandardOutput.ReadLineAsync();if(!$pending.Wait(45000) -or !$pending.Result){throw ('The owned browser response did not complete: '+$script:phase)};return $pending.Result|ConvertFrom-Json}
31新增:function Call([string]$Path,$Payload=@{},[string]$Method='POST'){Send $browser @{method=$Method;path=$Path;input=$Payload};$value=Read $browser;if($value.error){throw ($script:phase+': '+$value.error)};return $value}
32新增:function State {return Invoke-Command -Session $session -ArgumentList $guestDirectory -ScriptBlock {param($dir);$file=Join-Path $dir 'fixture-state.json';if(Test-Path -LiteralPath $file){foreach($report in (Get-Content -LiteralPath $file -Raw|ConvertFrom-Json)){$report}}}}
33新增:function Frame([string]$Name){
34新增: $f=Call '/frame' @{} 'GET';if($f.width -lt 1 -or $f.height -lt 1 -or !$f.target){throw 'The native frame receipt is invalid.'}
35新增: Add-Type -AssemblyName System.Drawing
36新增: $image=[Drawing.Bitmap]::new($f.width,$f.height);$g=[Drawing.Graphics]::FromImage($image)
37新增: try {
38新增: $parts=@();if($f.jpeg -or $f.png){$parts+=@([pscustomobject]@{jpeg=$f.jpeg;png=$f.png;x=0;y=0;width=$f.width;height=$f.height})};$parts+=@($f.panes);$parts+=@($f.overlays)
39新增: foreach($part in $parts){if(!$part){continue};$encoded=if($part.png){$part.png}else{$part.jpeg};$stream=[IO.MemoryStream]::new([Convert]::FromBase64String($encoded));$piece=[Drawing.Image]::FromStream($stream);try{$g.DrawImage($piece,[Drawing.Rectangle]::new($part.x,$part.y,$part.width,$part.height))}finally{$piece.Dispose();$stream.Dispose()}}
40新增: $image.Save((Join-Path $EvidenceDirectory ($Name+'.png')),[Drawing.Imaging.ImageFormat]::Png)
41新增: } finally {$g.Dispose();$image.Dispose()}
42新增: return $f
43新增:}
44新增:function Pointer($Frame,[int]$X,[int]$Y,[int]$Mask){$null=Call '/input' @{kind='pointer';target=$Frame.target;x=$X;y=$Y;mask=$Mask}}
45新增:function Click($Frame,[double]$X,[double]$Y,[int]$Mask=1){Pointer $Frame ([int]($X*$Frame.scale)) ([int]($Y*$Frame.scale)) $Mask;Pointer $Frame ([int]($X*$Frame.scale)) ([int]($Y*$Frame.scale)) 0}
46新增:function Key($Frame,[uint32]$Symbol,[bool]$Down){$null=Call '/input' @{kind='key';target=$Frame.target;keysym=$Symbol;down=$Down}}
47新增:function Text($Frame,[string]$Value){foreach($char in $Value.ToCharArray()){Key $Frame ([uint32][char]$char) $true;Key $Frame ([uint32][char]$char) $false}}
48新增:function ReadAck([long]$Serial){while($true){$r=Read $clipboard;if($r.error){throw 'The GUI clipboard write failed.'};if($r.ack -eq $Serial){return}}}
49新增:function NativeKeys {
50新增: $probe=Bridge 'terminal';Send $probe @{action='open';workspace='home';shell='powershell';cols=160;rows=25};if(!(Read $probe).ready){throw 'The GUI native key probe is unavailable.'}
51新增: $marker='__BN_'+[guid]::NewGuid().ToString('N').Substring(0,8)+'='
52新增: $code='Add-Type -TypeDefinition ''using System.Runtime.InteropServices; public static class BrowserKeyProbe { [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int key); }'';$ctrl=if(([BrowserKeyProbe]::GetAsyncKeyState(17)-band 32768)-ne 0){"held"}else{"released"};$mouse=if(([BrowserKeyProbe]::GetAsyncKeyState(1)-band 32768)-ne 0){"held"}else{"released"};[Console]::WriteLine("'+$marker+'"+$ctrl+"_"+$mouse)'
53新增: $command='powershell.exe -NoProfile -EncodedCommand '+[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))+"`r"
54新增: Send $probe @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes($command))};$output=''
55新增: while($true){$r=Read $probe;if($r.error -or $null -ne $r.exit){throw 'The GUI native key probe exited.'};if($r.data){$output+=$utf8.GetString([Convert]::FromBase64String($r.data));$match=[regex]::Match($output,[regex]::Escape($marker)+'(held|released)_(held|released)');if($match.Success){return @{ctrl=$match.Groups[1].Value;mouse=$match.Groups[2].Value}}}}
56新增:}
57新增:function NativeGeometry {
58新增: $probe=Bridge 'terminal';Send $probe @{action='open';workspace='home';shell='powershell';cols=160;rows=25};if(!(Read $probe).ready){throw 'The GUI geometry probe is unavailable.'}
59新增: $source=@'
60新增:using System;using System.Collections.Generic;using System.Runtime.InteropServices;using System.Text;using System.Diagnostics;
61新增:public static class BrowserGeometryProbe {
62新增: [StructLayout(LayoutKind.Sequential)]public struct Rect{public int Left,Top,Right,Bottom;}
63新增: [StructLayout(LayoutKind.Sequential)]public struct Gui{public uint Size,Flags;public IntPtr Active,Focus,Capture,Menu,Move,Caret;public Rect CaretRect;}
64新增: [DllImport("user32.dll")]static extern IntPtr GetForegroundWindow();
65新增: [DllImport("user32.dll")]static extern uint GetWindowThreadProcessId(IntPtr h,out int p);
66新增: [DllImport("user32.dll")]static extern bool GetWindowRect(IntPtr h,out Rect r);
67新增: [StructLayout(LayoutKind.Sequential)]public struct Point{public int X,Y;}
68新增: [DllImport("user32.dll")]static extern bool GetClientRect(IntPtr h,out Rect r);
69新增: [DllImport("user32.dll")]static extern bool ClientToScreen(IntPtr h,ref Point p);
70新增: [DllImport("user32.dll")]static extern bool ScreenToClient(IntPtr h,ref Point p);
71新增: [DllImport("user32.dll")]static extern IntPtr ChildWindowFromPointEx(IntPtr h,Point p,uint flags);
72新增: [DllImport("user32.dll")]static extern uint GetDpiForWindow(IntPtr h);
73新增: [DllImport("user32.dll")]static extern bool GetGUIThreadInfo(uint thread,ref Gui info);
74新增: [DllImport("user32.dll")]static extern IntPtr SetThreadDpiAwarenessContext(IntPtr c);
75新增: [DllImport("user32.dll",CharSet=CharSet.Unicode)]static extern int GetClassName(IntPtr h,StringBuilder s,int n);
76新增: delegate bool EnumFn(IntPtr h,IntPtr p);[DllImport("user32.dll")]static extern bool EnumChildWindows(IntPtr h,EnumFn f,IntPtr p);
77新增: public static string Read(){var old=SetThreadDpiAwarenessContext(new IntPtr(-4));try{var h=GetForegroundWindow();int p;var thread=GetWindowThreadProcessId(h,out p);using(var process=Process.GetProcessById(p)){var name=process.ProcessName;if(name!="msedge"&&name!="chrome")return "unowned_foreground";}Rect w;GetWindowRect(h,out w);var a=new List<string>();a.Add(GetDpiForWindow(h)+","+w.Left+","+w.Top+","+(w.Right-w.Left)+","+(w.Bottom-w.Top));var info=new Gui{Size=(uint)Marshal.SizeOf(typeof(Gui))};if(GetGUIThreadInfo(thread,ref info)){var cl=new StringBuilder(128);GetClassName(info.Focus,cl,128);Rect fr;GetWindowRect(info.Focus,out fr);a.Add("focus:"+cl+","+fr.Left+","+fr.Top+","+(fr.Right-fr.Left)+","+(fr.Bottom-fr.Top));}Rect cr;GetClientRect(h,out cr);var center=new Point{X=(cr.Right-cr.Left)/2,Y=(cr.Bottom-cr.Top)/2};ClientToScreen(h,ref center);foreach(uint flags in new uint[]{0,1,7}){var parent=h;for(int depth=0;depth<12;depth++){var pt=center;ScreenToClient(parent,ref pt);var child=ChildWindowFromPointEx(parent,pt,flags);if(child==IntPtr.Zero||child==parent){a.Add("hit"+flags+":none");break;}var cl=new StringBuilder(128);GetClassName(child,cl,128);Rect r;GetWindowRect(child,out r);a.Add("hit"+flags+":"+cl+","+r.Left+","+r.Top+","+(r.Right-r.Left)+","+(r.Bottom-r.Top));parent=child;}}EnumChildWindows(h,(c,_)=>{var s=new StringBuilder(128);GetClassName(c,s,128);Rect r;if(s.ToString()=="Chrome_RenderWidgetHostHWND"&&GetWindowRect(c,out r))a.Add(r.Left+","+r.Top+","+(r.Right-r.Left)+","+(r.Bottom-r.Top));return true;},IntPtr.Zero);return string.Join(";",a);}finally{SetThreadDpiAwarenessContext(old);}}
78新增:}
79新增:'@
80新增: $marker='__BG_'+[guid]::NewGuid().ToString('N').Substring(0,8)+'='
81新增: $geometryFile=Join-Path $guestDirectory ('geometry-'+[guid]::NewGuid().ToString('N')+'.txt')
82新增: $code='Add-Type -TypeDefinition ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("'+[Convert]::ToBase64String($utf8.GetBytes($source))+'")));[IO.File]::WriteAllText('''+$geometryFile+''',[BrowserGeometryProbe]::Read());[Console]::WriteLine("'+$marker+'done")'
83新增: Send $probe @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes('powershell.exe -NoProfile -EncodedCommand '+[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))+"`r"))};$output=''
84新增: while($true){$r=Read $probe;if($r.error -or $null -ne $r.exit){throw 'The GUI geometry probe exited.'};if($r.data){$output+=$utf8.GetString([Convert]::FromBase64String($r.data));if($output.Contains($marker+'done')){return Invoke-Command -Session $session -ArgumentList $geometryFile -ScriptBlock {param($path);Get-Content -LiteralPath $path -Raw}}}}
85新增:}
86新增:try {
87新增: $null=[IO.Directory]::CreateDirectory($EvidenceDirectory)
88新增: $guestDirectory=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid -ScriptBlock {
89新增: param($expected,$sid)
90新增: if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'}
91新增: $guiHome=(Get-ItemProperty -LiteralPath ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\'+$sid)).ProfileImagePath
92新增: $directory=Join-Path $guiHome ('AppData\Local\Temp\CageBrowserAcceptance-'+[guid]::NewGuid().ToString('N'));$null=[IO.Directory]::CreateDirectory($directory);return $directory
93新增: }
94新增: $copiedFixtureText+=' '+[IO.Path]::GetFileName($guestDirectory)
95新增: $copiedFixtureBytes=[Convert]::ToBase64String($utf8.GetBytes($copiedFixtureText))
96新增: Copy-Item -LiteralPath $FixturePath -Destination (Join-Path $guestDirectory 'fixture.mjs') -ToSession $session
97新增: $script:phase='gui_status';$statusProcess=Bridge 'status';$status=Read $statusProcess
98新增: if(!$status.available -or !$status.browser.installed -or !$status.browser.network_configured){throw 'The actual GUI browser dependencies or trusted network receipt are unavailable.'}
99新增: $script:phase='fixture_terminal';$terminal=Bridge 'terminal';Send $terminal @{action='open';workspace='home';shell='powershell';cols=160;rows=30};if(!(Read $terminal).ready){throw 'The GUI fixture terminal is unavailable.'}
100新增: $guestNode='C:\Program Files\Cage Guest Bridge\'+$vm.Id.ToString('D')+'\node.exe'
101新增: $launch='& '''+$guestNode+''' '''+(Join-Path $guestDirectory 'fixture.mjs')+''' '''+$guestDirectory+''''
102新增: $command='powershell.exe -NoProfile -EncodedCommand '+[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($launch))+"`r"
103新增: Send $terminal @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes($command))}
104新增: $output='';while($output -notmatch 'CAGE_NATIVE_FIXTURE_READY'){ $r=Read $terminal;if($r.error -or $null -ne $r.exit){throw 'The GUI fixture server exited.'};if($r.data){$output+=$utf8.GetString([Convert]::FromBase64String($r.data))}}
105新增: $port=Invoke-Command -Session $session -ArgumentList $guestDirectory -ScriptBlock {param($dir);[int](Get-Content -LiteralPath (Join-Path $dir 'fixture-port') -Raw)}
106新增: $browser=Bridge 'browser';$clipboard=Bridge 'stream';$null=Read $clipboard
107新增: # The production clipboard stream starts guest observation after the first
108新增: # host write ACK. Exercise that lifecycle instead of waiting on an unseeded reader.
109新增: Send $clipboard @{serial=1;text=('Cage fixture baseline '+[IO.Path]::GetFileName($guestDirectory))};ReadAck 1
110新增: if($PerfOnly){
111新增: $script:phase='native_capture_performance';$tab=Call '/new' @{url=('http://127.0.0.1:'+$port+'/perf')};$tabs.Add($tab.id);Start-Sleep -Milliseconds 300
112新增: $frame=Frame 'perf-01-page';Key $frame 65307 $true;Key $frame 65307 $false;$frame=Frame 'perf-02-native-ready'
113新增: function Dimensions($f){if($f.unchanged){return};$encoded=if($f.jpeg){$f.jpeg}else{$f.png};$memory=[IO.MemoryStream]::new([Convert]::FromBase64String($encoded));$picture=[Drawing.Image]::FromStream($memory);try{if($picture.Width -ne $f.width -or $picture.Height -ne $f.height){throw 'The actual encoded frame does not match its native HiDPI dimensions.'}}finally{$picture.Dispose();$memory.Dispose()}}
114新增: Dimensions $frame;$before=(Call '/health' @{} 'GET').capture;if(!$before){throw 'The actual capture counters are unavailable.'}
115新增: $static=[Collections.Generic.List[double]]::new();$unchanged=0
116新增: for($i=0;$i -lt 16;$i++){$watch=[Diagnostics.Stopwatch]::StartNew();$next=Call '/frame' @{after=$frame.sequence} 'GET';$watch.Stop();$static.Add($watch.Elapsed.TotalMilliseconds);if($next.unchanged){$unchanged++}else{Dimensions $next;$frame=$next};Start-Sleep -Milliseconds 80}
117新增: $still=(Call '/health' @{} 'GET').capture;$scroll=[Collections.Generic.List[double]]::new()
118新增: for($i=0;$i -lt 20;$i++){Pointer $frame ([int](100*$frame.scale)) ([int](600*$frame.scale)) 16;Pointer $frame ([int](100*$frame.scale)) ([int](600*$frame.scale)) 0;$watch=[Diagnostics.Stopwatch]::StartNew();$next=Call '/frame' @{after=$frame.sequence} 'GET';$watch.Stop();$scroll.Add($watch.Elapsed.TotalMilliseconds);if(!$next.unchanged){Dimensions $next;$frame=$next};Start-Sleep -Milliseconds 80}
119新增: $scrolled=(Call '/health' @{} 'GET').capture;if(!(@(State)|Where-Object {$_.type -eq 'scroll' -and $_.y -gt 0})){throw 'The actual native wheel did not scroll the fixture.'}
120新增: $summary=[ordered]@{static_polls=16;static_unchanged=$unchanged;static_screenshots=$still.screenshots-$before.screenshots;static_damage_events=$still.damage_frames-$before.damage_frames;static_latency_ms=@($static);scroll_polls=20;scroll_screenshots=$scrolled.screenshots-$still.screenshots;scroll_damage_events=$scrolled.damage_frames-$still.damage_frames;scroll_latency_ms=@($scroll);actual_native_pixels=@($frame.width,$frame.height);completed=$true}
121新增: [IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'capture-performance.json'),($summary|ConvertTo-Json -Depth 8),$utf8);[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'perf-events.json'),(@(State)|ConvertTo-Json -Depth 8),$utf8)
122新增: $summary|ConvertTo-Json -Compress;return
123新增: }
124新增: if(!$SplitOnly){
125新增: $script:phase='native_frame';$tab=Call '/new' @{url=('http://127.0.0.1:'+$port+'/one');incognito=$true};$tabs.Add($tab.id);Start-Sleep -Milliseconds 400
126新增: $frame=Frame '01-page';$results.native_frame=$true
127新增: $script:phase='native_text';Click $frame 100 130;Text $frame 'native-text';Start-Sleep -Milliseconds 200
128新增: if(!(@(State)|Where-Object {$_.type -eq 'text' -and $_.value -eq 'native-text'})){throw 'Native key input did not reach the fixture textarea.'};$results.native_text=$true
129新增: $frame=Frame '02-text';$script:phase='native_find';Key $frame 65507 $true;Key $frame 102 $true;Key $frame 102 $false;Key $frame 65507 $false;Start-Sleep -Milliseconds 200
130新增: $find=Frame '03-native-find';if(@($find.overlays).Count -eq 0){throw 'The native Find UI was not captured.'};Text $find 'cage-native-find-needle';Start-Sleep -Milliseconds 100
131新增: if(@(State|Where-Object {$_.type -eq 'text'})[-1].value -ne 'native-text'){throw 'Find input reached the webpage instead of native Chrome UI.'};$results.native_find=$true
132新增: $find=Frame '04-find-query';Key $find 65307 $true;Key $find 65307 $false
133新增: $frame=Frame '05-find-closed';$script:phase='native_context';Click $frame 100 130 4;Start-Sleep -Milliseconds 150
134新增: $menu=Frame '06-native-context';if(@($menu.overlays).Count -eq 0){throw 'The native context menu was not captured.'};$results.native_context_menu=$true;Key $menu 65307 $true;Key $menu 65307 $false
135新增: $frame=Frame '07-context-closed';$script:phase='page_copy';Click $frame 100 215
136新增: do {$r=Read $clipboard}while($r.source -ne 'guest' -or $r.text -cne $copiedFixtureText)
137新增: if([Convert]::ToBase64String($utf8.GetBytes($r.text)) -cne $copiedFixtureBytes){throw 'The actual clipboard text bytes differ from the fixture copy.'}
138新增: if(!(@(State)|Where-Object type -eq copied)){throw 'The actual fixture copy button did not complete.'};$results.page_copy_reaches_os_clipboard=$true
139新增: $script:phase='image_paste';$frame=Frame '08-before-png';Click $frame 100 295
140新增: $bitmap=[Drawing.Bitmap]::new(17,9);$graphics=[Drawing.Graphics]::FromImage($bitmap);$graphics.Clear([Drawing.Color]::Coral);$bytes=[IO.MemoryStream]::new();$bitmap.Save($bytes,[Drawing.Imaging.ImageFormat]::Png);$png=$bytes.ToArray();$bytes.Dispose();$graphics.Dispose();$bitmap.Dispose()
141新增: $started=Call '/image-start' @{id=$tab.id;length=$png.Length};$null=Call '/image-chunk' @{transfer=$started.transfer;sequence=0;data=[Convert]::ToBase64String($png)};$null=Call '/image-finish' @{transfer=$started.transfer;sequence=1};Start-Sleep -Milliseconds 250
142新增: if(!(@(State)|Where-Object {$_.type -eq 'png' -and $_.width -eq 17 -and $_.height -eq 9})){throw 'The native OS PNG did not reach the fixture paste event.'};$results.native_png_paste=$true;$null=Frame '09-png-pasted'
143新增: $script:phase='native_permission';$frame=Frame '10-before-permission';Click $frame 330 215;Start-Sleep -Milliseconds 250
144新增: $permission=Frame '11-native-permission';if(@($permission.overlays).Count -eq 0){throw 'The native permission prompt was not captured.'};$results.native_permission_prompt=$true;Key $permission 65307 $true;Key $permission 65307 $false
145新增: $script:phase='native_private_tabs';$frame=Frame '11a-private-one';Click $frame ($frame.width/$frame.scale-120) 36
146新增: $privateSecond=$null;for($i=0;$i-lt 40;$i++){$snapshot=Call '/tabs' @{} 'GET';$privateSecond=@($snapshot.tabs|Where-Object {$_.incognito -and $_.url -like '*/private-two'})[0];if($privateSecond){break};Start-Sleep -Milliseconds 50}
147新增: if(!$privateSecond){throw 'The native private popup was not registered.'};$tabs.Add($privateSecond.id)
148新增: $privateFrame=Frame '11b-private-two';if($privateFrame.id -ne $privateSecond.id){throw 'The private popup did not become the actual active page.'}
149新增: Key $privateFrame 65507 $true;Key $privateFrame 65289 $true;Key $privateFrame 65289 $false;Key $privateFrame 65507 $false;Start-Sleep -Milliseconds 200
150新增: $cycled=Frame '11c-native-ctrl-tab';if($cycled.id -ne $tab.id){throw 'Native Ctrl+Tab did not synchronize the known private document.'};$results.native_ctrl_tab=$true
151新增: $null=Call '/close' @{id=$tab.id};$snapshot=Call '/tabs' @{} 'GET';if(!(@($snapshot.tabs)|Where-Object id -eq $privateSecond.id)){throw 'Closing a private tab also closed its sibling.'};$results.private_sibling_retained=$true
152新增: }
153新增: # Split follows the common browser contract: two ordinary tabs in one
154新增: # context. Only these newly created fixture tabs are used and closed.
155新增: $script:phase='split';$left=Call '/new' @{url=('http://127.0.0.1:'+$port+'/split-one')};$tabs.Add($left.id)
156新增: $second=Call '/new' @{url=('http://127.0.0.1:'+$port+'/split-two')};$tabs.Add($second.id);$null=Call '/split' @{id=$left.id;left=$left.id;right=$second.id};Start-Sleep -Milliseconds 250
157新增: $split=Frame '12-split';if(@($split.panes).Count -ne 2){throw 'The real split frame does not contain both panes.'}
158新增: Pointer $split ([int]($split.panes[1].x+100*$split.scale)) ([int](130*$split.scale)) 1;Pointer $split ([int]($split.panes[1].x+100*$split.scale)) ([int](130*$split.scale)) 0;Text $split 'split-right';Start-Sleep -Milliseconds 250
159新增: if(!(@(State)|Where-Object {$_.page -eq '/split-two' -and $_.type -eq 'text' -and $_.value -eq 'split-right'})){$null=Frame '13-split-failed';[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'split-events.json'),(@(State)|ConvertTo-Json -Depth 8),$utf8);[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'split-native-geometry.txt'),(NativeGeometry),$utf8);throw 'The native split input did not reach the right pane.'};$results.native_split_input=$true;$null=Frame '13-split-input'
160新增: $null=Call '/split' @{}
161新增: $script:phase='native_disconnect';$baseline=NativeKeys;if($baseline.ctrl -ne 'released' -or $baseline.mouse -ne 'released'){throw 'The GUI already contains held input before this isolated disconnect test.'}
162新增: $primary=$browser;$viewerA=Bridge 'browser';$viewerB=Bridge 'browser'
163新增: $browser=$viewerA;$leaseFrame=Frame '14-before-disconnect';Key $leaseFrame 65507 $true;Pointer $leaseFrame ([int](100*$leaseFrame.scale)) ([int](130*$leaseFrame.scale)) 1
164新增: $browser=$viewerB;Key $leaseFrame 65507 $true
165新增: $viewerA.StandardInput.Close();if(!$viewerA.WaitForExit(3000)){$viewerA.Kill()};Start-Sleep -Milliseconds 250
166新增: $native=NativeKeys;if($native.ctrl -ne 'held' -or $native.mouse -ne 'released'){throw 'Disconnect did not release its own mouse while preserving the other viewer Ctrl.'};$results.disconnect_preserves_other_viewer=$true
167新增: $viewerB.StandardInput.Close();if(!$viewerB.WaitForExit(3000)){$viewerB.Kill()};Start-Sleep -Milliseconds 250
168新增: $native=NativeKeys;if($native.ctrl -ne 'released' -or $native.mouse -ne 'released'){throw 'The last viewer disconnect left native input held.'};$results.disconnect_native_keys_released=$true
169新增: $browser=$primary;$results.completed=$true
170新增: [IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'browser-result.json'),($results|ConvertTo-Json),$utf8)
171新增: $results|ConvertTo-Json -Compress
172新增:} catch {
173新增: try{[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'failure-native-geometry.txt'),(NativeGeometry),$utf8)}catch{}
174新增: $results.completed=$false;$results.failed_phase=$script:phase;$results.reason=$_.Exception.Message
175新增: if(Test-Path -LiteralPath $EvidenceDirectory){[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'browser-result.json'),($results|ConvertTo-Json),$utf8)}
176新增: $results|ConvertTo-Json -Compress
177新增: throw
178新增:} finally {
179新增: if($primary){$browser=$primary}
180新增: if($browser -and $frame){try{$cleanup=Call '/frame' @{} 'GET';foreach($symbol in @(65507,65505,65513)){Key $cleanup $symbol $false};Pointer $cleanup 1 1 0}catch{}}
181新增: if($browser){foreach($id in $tabs){try{$null=Call '/close' @{id=$id}}catch{}}}
182新增: foreach($p in $owned){try{$p.StandardInput.Close();if(!$p.WaitForExit(1000)){$p.Kill()};$p.Dispose()}catch{}}
183新增: if($session){Remove-PSSession $session}
184新增:}
新增scripts/guest-os/guest-clipboard-windows/qa-large-file.ps1+25 −0看文件
@@ -0,0 +1,25 @@
1新增:#requires -Version 5.1
2新增:param([Parameter(Mandatory)][string]$ProfilePath,[Parameter(Mandatory)][string]$EvidenceDirectory)
3新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
4新增:$profile=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json;$utf8=[Text.UTF8Encoding]::new($false)
5新增:$owned=[Collections.Generic.List[Diagnostics.Process]]::new()
6新增:function Start-Transfer([string]$Operation,[bool]$Helper=$false){
7新增: $s=[Diagnostics.ProcessStartInfo]::new();$s.FileName=if($Helper){Join-Path ([IO.Path]::GetDirectoryName($profile.relay_executable)) 'cage-guest-files.exe'}else{$profile.relay_executable}
8新增: $s.Arguments=if($Helper){$Operation}else{'--relay-profile "'+$ProfilePath+'" '+$Operation};if($Operation -eq 'export'){$s.Arguments+=' --paths-stdin'}
9新增: $s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardInput=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$s.StandardOutputEncoding=$utf8
10新增: $p=[Diagnostics.Process]::Start($s);$owned.Add($p);$null=$p.StandardError.ReadToEndAsync();$p
11新增:}
12新增:function Paths($P,$Selection){$bytes=$utf8.GetBytes((ConvertTo-Json -InputObject @($Selection) -Compress)+"`n");$P.StandardInput.BaseStream.Write($bytes,0,$bytes.Length);$P.StandardInput.Close()}
13新增:function Result($P){$read=$P.StandardOutput.ReadLineAsync();if(!$read.Wait(120000) -or !$read.Result -or !$P.WaitForExit(120000) -or $P.ExitCode -ne 0){throw 'The bounded archive stream did not complete.'};$read.Result|ConvertFrom-Json}
14新增:function Hash([string]$File){(Get-FileHash -LiteralPath $File -Algorithm SHA256).Hash}
15新增:try {
16新增: $directory=Join-Path $EvidenceDirectory ([guid]::NewGuid().ToString('N'));$null=[IO.Directory]::CreateDirectory($directory)
17新增: $source=Join-Path $directory 'stream-64MiB.bin';$file=[IO.File]::Open($source,'CreateNew','Write','None');$buffer=New-Object byte[] (64KB);for($i=0;$i -lt $buffer.Length;$i++){$buffer[$i]=[byte]($i%251)}
18新增: try{for($i=0;$i -lt 1024;$i++){$file.Write($buffer,0,$buffer.Length)}}finally{$file.Dispose()}
19新增: $write=Start-Transfer 'export' $true;Paths $write @($source);$import=Start-Transfer 'import';$write.StandardOutput.BaseStream.CopyTo($import.StandardInput.BaseStream);$import.StandardInput.Close();$guest=Result $import
20新增: if(!$write.WaitForExit(120000) -or $write.ExitCode -ne 0 -or @($guest.paths).Count -ne 1){throw 'The host archive source failed.'}
21新增: $export=Start-Transfer 'export';Paths $export @($guest.paths);$read=Start-Transfer 'import' $true;$export.StandardOutput.BaseStream.CopyTo($read.StandardInput.BaseStream);$read.StandardInput.Close();$returnedHost=Result $read
22新增: if(!$export.WaitForExit(120000) -or $export.ExitCode -ne 0 -or @($returnedHost.paths).Count -ne 1 -or (Get-Item -LiteralPath $returnedHost.paths[0]).Length -ne 64MB -or (Hash $source) -ne (Hash $returnedHost.paths[0])){throw 'The 64 MiB stream hash or completion status differs.'}
23新增: $result=[ordered]@{bytes=64MB;host_to_guest_complete=$true;guest_to_host_complete=$true;sha256_equal=$true;clipboard_unchanged=$true}
24新增: [IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'large-file-result.json'),($result|ConvertTo-Json),$utf8);$result|ConvertTo-Json -Compress
25新增:}finally{foreach($p in $owned){try{$p.StandardInput.Close();if(!$p.WaitForExit(1000)){$p.Kill()};$p.Dispose()}catch{}}}
新增scripts/guest-os/guest-clipboard-windows/qa-local-browser.ps1+100 −0看文件
@@ -0,0 +1,100 @@
1新增:#requires -Version 5.1
2新增:param(
3新增: [Parameter(Mandatory)][string]$ProfilePath,
4新增: [Parameter(Mandatory)][string]$CredentialFile,
5新增: [Parameter(Mandatory)][string]$AssetDirectory,
6新增: [Parameter(Mandatory)][string]$EvidenceDirectory,
7新增: [switch]$EditorOnly
8新增:)
9新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
10新增:$utf8=[Text.UTF8Encoding]::new($false);[Console]::OutputEncoding=$utf8
11新增:$binding=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json;$vm=Get-VM -Id ([guid]$binding.vm_id)
12新增:if($vm.State -ne 'Running' -or @(Get-VMNetworkAdapter -VM $vm).Count -ne 0){throw 'The bound local-only guest must have zero normal NICs.'}
13新增:$credential=Import-Clixml -LiteralPath $CredentialFile
14新增:if(($credential.UserName -split '\\')[-1] -cne 'CageLabSetup'){throw 'The retained QA administrator identity does not match.'}
15新增:$credential=[pscredential]::new('CageLabSetup',$credential.Password)
16新增:$session=New-PSSession -VMId $vm.Id -Credential $credential
17新增:$owned=[Collections.Generic.List[Diagnostics.Process]]::new();$changed=$false;$restored=$false
18新增:function Bridge([string]$Operation){$s=[Diagnostics.ProcessStartInfo]::new();$s.FileName=$binding.relay_executable;$s.Arguments='--relay-profile "'+$ProfilePath+'" '+$Operation;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardInput=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$s.StandardOutputEncoding=$utf8;$p=[Diagnostics.Process]::Start($s);$owned.Add($p);$null=$p.StandardError.ReadToEndAsync();return $p}
19新增:function Send($p,$v){$bytes=$utf8.GetBytes((ConvertTo-Json -InputObject $v -Depth 12 -Compress)+"`n");$p.StandardInput.BaseStream.Write($bytes,0,$bytes.Length);$p.StandardInput.BaseStream.Flush()}
20新增:function Read($p){$pending=$p.StandardOutput.ReadLineAsync();if(!$pending.Wait(45000) -or !$pending.Result){throw 'The owned local browser QA channel did not complete.'};return $pending.Result|ConvertFrom-Json}
21新增:function Call([string]$Path,$Payload=@{},[string]$Method='POST'){Send $browser @{method=$Method;path=$Path;input=$Payload};$r=Read $browser;if($r.error){throw $r.error};return $r}
22新增:try {
23新增: $null=New-Item -ItemType Directory -Path $EvidenceDirectory
24新增: $setup=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid -ScriptBlock {
25新增: param($expected,$sid)
26新增: if([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'}
27新增: $guiProfile=(Get-ItemProperty ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\'+$sid)).ProfileImagePath
28新增: $directory=Join-Path $guiProfile ('AppData\Local\Temp\CageLocalBrowserQA-'+[guid]::NewGuid().ToString('N'));$null=New-Item -ItemType Directory -Path $directory
29新增: $program=Join-Path $env:ProgramFiles ('Cage Guest Bridge\'+$expected);$config=Join-Path $program 'guest-config.json';$backup=Join-Path $program ('guest-config.browser-qa-'+[guid]::NewGuid().ToString('N')+'.backup')
30新增: if((Get-Item $config).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'config_link_rejected'}
31新增: Copy-Item -LiteralPath $config -Destination $backup
32新增: [pscustomobject]@{Directory=$directory;Program=$program;Config=$config;Backup=$backup;Hash=(Get-FileHash $config -Algorithm SHA256).Hash}
33新增: }
34新增: Copy-Item -LiteralPath (Join-Path $AssetDirectory 'windows-browser-deny-proxy.mjs') -Destination (Join-Path $setup.Directory 'deny.mjs') -ToSession $session
35新增: $terminal=Bridge 'terminal';Send $terminal @{action='open';workspace='home';shell='powershell';cols=160;rows=30};if(!(Read $terminal).ready){throw 'GUI ConPTY unavailable'}
36新增: $privateHost=@(Get-NetIPAddress -AddressFamily IPv4|Where-Object {$_.IPAddress -notlike '127.*' -and $_.IPAddress -notlike '169.254.*' -and $_.AddressState -eq 'Preferred'})[0].IPAddress
37新增: if(!$privateHost){throw 'An actual private host address is required for the denied request probe.'}
38新增: $launch='& '''+(Join-Path $setup.Program 'node.exe')+''' '''+(Join-Path $setup.Directory 'deny.mjs')+''' '''+$setup.Directory+''' '''+$privateHost+''''
39新增: Send $terminal @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes('powershell.exe -NoProfile -EncodedCommand '+[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($launch))+"`r"))}
40新增: $output='';while(!$output.Contains('CAGE_QA_DENY_PROXY_READY')){$r=Read $terminal;if($null -ne $r.exit -or $r.error){throw 'The local deny proxy exited.'};if($r.data){$output+=$utf8.GetString([Convert]::FromBase64String($r.data))}}
41新增: $port=Invoke-Command -Session $session -ArgumentList $setup.Directory -ScriptBlock {param($dir);[int](Get-Content (Join-Path $dir 'deny-proxy-port') -Raw)}
42新增: $changed=$true;$windowStartUtc=[DateTime]::UtcNow.ToString('o')
43新增: Invoke-Command -Session $session -ArgumentList $setup.Config,$port -ScriptBlock {
44新增: param($file,$port);$config=Get-Content -LiteralPath $file -Raw|ConvertFrom-Json
45新增: $config|Add-Member -NotePropertyName network_mode -NotePropertyValue 'proxy' -Force
46新增: $config|Add-Member -NotePropertyName browser_proxy -NotePropertyValue ('http://127.0.0.1:'+$port) -Force
47新增: [IO.File]::WriteAllText($file,($config|ConvertTo-Json -Depth 12),[Text.UTF8Encoding]::new($false))
48新增: }
49新增: [Console]::WriteLine('LOCAL_ONLY_QA_CONFIG_STARTED '+$windowStartUtc)
50新增: $browser=Bridge 'browser';$health=Call '/health' @{} 'GET';$version=Call '/info'
51新增: $audited=Call '/audit' @{network=$true;timezone='UTC'}
52新增: if($audited.network.status -ne 503){throw 'The actual browser request did not reach the rejecting local proxy.'}
53新增: $known=@((Call '/tabs' @{} 'GET').tabs|ForEach-Object {$_.id})
54新增: $null=Call '/new' @{url='http://example.com/'};$null=Call '/new' @{url=('http://'+$privateHost+'/')}
55新增: $connectDenied=$false;try{$null=Call '/new' @{url='https://example.com/'}}catch{$connectDenied=$true}
56新增: $counts=Invoke-Command -Session $session -ArgumentList $setup.Directory -ScriptBlock {param($dir);Get-Content (Join-Path $dir 'deny-proxy-counts.json') -Raw|ConvertFrom-Json}
57新增: if($counts.public_probe -lt 1 -or $counts.private_probe -lt 1 -or $counts.connect_probe -lt 1 -or !$connectDenied){throw 'The actual Chrome public/private host HTTP and HTTPS CONNECT probes were not all denied.'}
58新增: foreach($tab in (Call '/tabs' @{} 'GET').tabs){if($tab.id -notin $known){$null=Call '/close' @{id=$tab.id}}}
59新增: $tests=[ordered]@{local_only=$true;normal_nics=0;browser_version=$version.product;browser_audit_status=$audited.network.status;actual_public_http_denied=$true;actual_private_host_http_denied=$true;actual_https_connect_denied=$true;packet_network_verified=$false}
60新增: [IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'local-only-network.json'),($tests|ConvertTo-Json),$utf8)
61新增: if(!$EditorOnly){$perf=Join-Path $EvidenceDirectory 'performance'; & (Join-Path $AssetDirectory 'qa-browser.ps1') -ProfilePath $ProfilePath -CredentialFile $CredentialFile -FixturePath (Join-Path $AssetDirectory 'windows-native-browser-fixture.mjs') -EvidenceDirectory $perf -PerfOnly}
62新增: $env:CAGE_TEST_WINDOWS_WORKBENCH_PROFILE=Split-Path -Parent $ProfilePath;$env:CAGE_TEST_WINDOWS_BROWSER_ARTIFACTS=Join-Path $EvidenceDirectory 'editor';$env:CAGE_TEST_WINDOWS_BROWSER_NATIVE='1'
63新增: & (Join-Path $AssetDirectory 'browser-editor-tests.exe') '-test.run=^TestWindowsBrowserEditorNativeE2E$' '-test.v' '-test.count=1'
64新增: if($LASTEXITCODE -ne 0){throw 'The real local-only native editor test failed.'}
65新增: if(!$EditorOnly){& (Join-Path $AssetDirectory 'qa-browser.ps1') -ProfilePath $ProfilePath -CredentialFile $CredentialFile -FixturePath (Join-Path $AssetDirectory 'windows-native-browser-fixture.mjs') -EvidenceDirectory (Join-Path $EvidenceDirectory 'native-core')}
66新增:} finally {
67新增: try {
68新增: if($setup){
69新增: $restored=Invoke-Command -Session $session -ArgumentList $setup.Config,$setup.Backup,$setup.Hash,[bool]$changed,$vm.Id,$binding.gui_user_sid -ScriptBlock {
70新增: param($file,$backup,$hash,$changed,$vm,$sid)
71新增: if($changed){[IO.File]::WriteAllBytes($file,[IO.File]::ReadAllBytes($backup))}
72新增: if((Get-FileHash $file -Algorithm SHA256).Hash -cne $hash){throw 'The original guest configuration was not restored.'}
73新增: Remove-Item -LiteralPath $backup
74新增: if($changed){
75新增: $name='Cage-GUI-Bridge-'+$vm+'-'+$sid;$task=Get-ScheduledTask -TaskName $name
76新增: if($task.Description -cne ('Cage protected GUI bridge '+$vm+' '+$sid)){throw 'Owned GUI task mismatch'}
77新增: Stop-ScheduledTask -InputObject $task
78新增: $until=[DateTime]::UtcNow.AddSeconds(10)
79新增: while((Get-ScheduledTask -TaskName $name).State -eq 'Running' -and [DateTime]::UtcNow -lt $until){Start-Sleep -Milliseconds 100}
80新增: if((Get-ScheduledTask -TaskName $name).State -eq 'Running'){throw 'The owned GUI task did not stop.'}
81新增: Start-ScheduledTask -InputObject $task
82新增: $until=[DateTime]::UtcNow.AddSeconds(10)
83新增: while((Get-ScheduledTask -TaskName $name).State -ne 'Running' -and [DateTime]::UtcNow -lt $until){Start-Sleep -Milliseconds 100}
84新增: if((Get-ScheduledTask -TaskName $name).State -ne 'Running'){throw 'The owned GUI task did not restart.'}
85新增: }
86新增: return $true
87新增: }
88新增: }
89新增: if($restored -and $changed){
90新增: $until=[DateTime]::UtcNow.AddSeconds(10);$confirmed=$false
91新增: do{try{$status=Bridge 'status';$pending=$status.StandardOutput.ReadLineAsync();if($pending.Wait(2000) -and $pending.Result){$reply=$pending.Result|ConvertFrom-Json;$confirmed=$reply.available -eq $true -and $reply.vm_id -eq $binding.vm_id -and $reply.gui_user_sid -ceq $binding.gui_user_sid}}catch{};if(!$confirmed){Start-Sleep -Milliseconds 200}}while(!$confirmed -and [DateTime]::UtcNow -lt $until)
92新增: if(!$confirmed){throw 'Configuration restored, but the actual paired GUI status ACK is unavailable.'}
93新增: [Console]::WriteLine('LOCAL_ONLY_QA_GUI_ACK_CONFIRMED')
94新增: }
95新增: if($restored){$endUtc=[DateTime]::UtcNow.ToString('o');[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'configuration-window.json'),(@{start_utc=$windowStartUtc;end_utc=$endUtc;original_config_restored=$true;gui_ack_confirmed=$confirmed;network_mode='local-only-proxy';normal_nics=0}|ConvertTo-Json),$utf8);[Console]::WriteLine('LOCAL_ONLY_QA_CONFIG_RESTORED '+$endUtc)}
96新增: } finally {
97新增: foreach($p in $owned){try{$p.StandardInput.Close();if(!$p.WaitForExit(1000)){$p.Kill()};$p.Dispose()}catch{}}
98新增: if($session){Remove-PSSession $session}
99新增: }
100新增:}
新增scripts/guest-os/guest-clipboard-windows/qa.ps1+73 −0看文件
@@ -0,0 +1,73 @@
1新增:#requires -Version 5.1
2新增:param([Parameter(Mandatory)][string]$ProfilePath,[Parameter(Mandatory)][string]$EvidenceDirectory)
3新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
4新增:$profile=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json
5新增:$executable=$profile.relay_executable;$helper=Join-Path ([IO.Path]::GetDirectoryName($executable)) 'cage-guest-files.exe'
6新增:$utf8=[Text.UTF8Encoding]::new($false)
7新增:$owned=[Collections.Generic.List[Diagnostics.Process]]::new()
8新增:$script:phase='starting'
9新增:function Start-Bridge([string]$Operation,[bool]$Files=$false){
10新增: $s=[Diagnostics.ProcessStartInfo]::new();$s.FileName=if($Files){$helper}else{$executable}
11新增: $s.Arguments=if($Files){$Operation}else{'--relay-profile "'+$ProfilePath+'" '+$Operation}
12新增: if($Operation -eq 'export'){$s.Arguments+=' --paths-stdin'}
13新增: $s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardInput=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$s.StandardOutputEncoding=$utf8
14新增: $p=[Diagnostics.Process]::Start($s);$owned.Add($p);$null=$p.StandardError.ReadToEndAsync();return $p
15新增:}
16新增:function Send-JSON($Process,$Object){$b=$utf8.GetBytes((ConvertTo-Json -InputObject $Object -Compress -Depth 8)+"`n");$Process.StandardInput.BaseStream.Write($b,0,$b.Length);$Process.StandardInput.BaseStream.Flush()}
17新增:function Read-JSON($Process){$r=$Process.StandardOutput.ReadLineAsync();if(!$r.Wait(30000) -or !$r.Result){throw ('The GUI bridge response did not complete at '+$script:phase+'.')};return ($r.Result|ConvertFrom-Json)}
18新增:function Check-Exit($Process){if(!$Process.WaitForExit(30000) -or $Process.ExitCode -ne 0){throw 'The GUI bridge child failed.'}}
19新增:function SHA([byte[]]$Bytes){return [BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash($Bytes)).Replace('-','').ToLowerInvariant()}
20新增:$echoes=0
21新增:function Read-Ack([long]$Serial){
22新增: while($true){$value=Read-JSON $clipboard;if($value.error){throw 'Clipboard write failed.'};if($value.ack -eq $Serial){return};if($value.source -eq 'guest' -and $value.text -eq $seed){$script:echoes++}}
23新增:}
24新增:function Read-Guest([string]$Format){while($true){$v=Read-JSON $clipboard;if($v.error){throw 'Clipboard selection failed.'};if($v.source -eq 'guest' -and $null -ne $v.$Format){return $v}}}
25新增:function Invoke-Native([string]$Body){
26新增: $marker='__CQ_'+[guid]::NewGuid().ToString('N').Substring(0,8)+'='
27新增: $script='Add-Type -AssemblyName System.Windows.Forms;'+$Body+';[Console]::WriteLine("'+$marker+'"+$result)'
28新增: $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($script))
29新增: Send-JSON $terminal @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes('powershell.exe -Sta -NoProfile -EncodedCommand '+$encoded+"`r"))}
30新增: $output=''
31新增: while($true){$m=Read-JSON $terminal;if($m.error -or $null -ne $m.exit){throw 'The ordinary GUI ConPTY failed.'};if($m.data){$output+=$utf8.GetString([Convert]::FromBase64String($m.data));$match=[regex]::Match($output,[regex]::Escape($marker)+'([a-zA-Z0-9_-]+)[\r\n]');if($match.Success){return $match.Groups[1].Value}}}
32新增:}
33新增:try {
34新增: $script:phase='clipboard_public_hello';$clipboard=Start-Bridge 'stream';$hello=Read-JSON $clipboard
35新增: if($hello.hello.os -ne 'windows' -or !$hello.hello.available -or $hello.version){throw 'The public clipboard hello shape is invalid.'}
36新增: $script:phase='terminal_ready';$terminal=Start-Bridge 'terminal';Send-JSON $terminal @{action='open';cols=160;rows=35;workspace='home';shell='powershell'}
37新增: if(!(Read-JSON $terminal).ready){throw 'The ordinary GUI ConPTY did not become ready.'}
38新增: Send-JSON $terminal @{action='resize';cols=160;rows=40}
39新增: $script:phase='host_text_ack';$seed="Windows host 中文 😀`nsecond line";Send-JSON $clipboard @{serial=1;text=$seed};Read-Ack 1
40新增: $expected=SHA $utf8.GetBytes($seed)
41新增: $script:phase='host_text_native_read';$read=Invoke-Native '$b=[Text.Encoding]::UTF8.GetBytes([Windows.Forms.Clipboard]::GetText());$result=[BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash($b)).Replace("-","").ToLowerInvariant()'
42新增: if($read -ne $expected){throw 'Native GUI clipboard text does not match the host write.'}
43新增: $guest='Windows guest 中文 😀';$guest64=[Convert]::ToBase64String($utf8.GetBytes($guest))
44新增: $script:phase='guest_text_write';$null=Invoke-Native ('$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("'+$guest64+'"));[Windows.Forms.Clipboard]::SetText($text);$result="written"')
45新增: if((Read-Guest 'text').text -ne $guest){throw 'Native guest text did not reach the host.'}
46新增: # A small valid PNG fixture has stable bytes, dimensions and transparency.
47新增: Add-Type -AssemblyName System.Drawing
48新增: $image=[Drawing.Bitmap]::new(13,7);$g=[Drawing.Graphics]::FromImage($image);$g.Clear([Drawing.Color]::FromArgb(177,21,80,140));$bytes=[IO.MemoryStream]::new();$image.Save($bytes,[Drawing.Imaging.ImageFormat]::Png);$g.Dispose();$image.Dispose();$png=$bytes.ToArray();$bytes.Dispose()
49新增: $script:phase='host_png_ack';Send-JSON $clipboard @{serial=2;png=[Convert]::ToBase64String($png)};Read-Ack 2
50新增: $script:phase='host_png_native_read';$read=Invoke-Native '$b=([IO.MemoryStream][Windows.Forms.Clipboard]::GetData("PNG")).ToArray();$result=[BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash($b)).Replace("-","").ToLowerInvariant()'
51新增: if($read -ne (SHA $png)){throw 'Native PNG bytes do not match the host write.'}
52新增: $script:phase='guest_png_write';$null=Invoke-Native 'Add-Type -AssemblyName System.Drawing;$im=[Drawing.Bitmap]::new(9,5);$g=[Drawing.Graphics]::FromImage($im);$g.Clear([Drawing.Color]::Coral);$s=[IO.MemoryStream]::new();$im.Save($s,[Drawing.Imaging.ImageFormat]::Png);$d=[Windows.Forms.DataObject]::new();$d.SetData("PNG",$false,$s);$d.SetImage($im);[Windows.Forms.Clipboard]::SetDataObject($d,$true);$g.Dispose();$im.Dispose();$result="written"'
53新增: $returned=[Convert]::FromBase64String((Read-Guest 'png').png);$pngImage=[Drawing.Image]::FromStream([IO.MemoryStream]::new($returned));if($pngImage.Width -ne 9 -or $pngImage.Height -ne 5){throw 'Native guest PNG did not reach the host.'};$pngImage.Dispose()
54新增: $fixture=Join-Path $EvidenceDirectory ([guid]::NewGuid().ToString('N'));$null=[IO.Directory]::CreateDirectory($fixture)
55新增: $file=Join-Path $fixture '中文😀.txt';$content=$utf8.GetBytes('Host to guest file 中文😀');[IO.File]::WriteAllBytes($file,$content)
56新增: $script:phase='host_file_import';$writer=Start-Bridge 'export' $true;Send-JSON $writer @($file);$writer.StandardInput.Close()
57新增: $importer=Start-Bridge 'import';$writer.StandardOutput.BaseStream.CopyTo($importer.StandardInput.BaseStream);$importer.StandardInput.Close();$imported=Read-JSON $importer;Check-Exit $writer;Check-Exit $importer
58新增: if(@($imported.paths).Count -ne 1){throw 'The imported file selection is invalid.'}
59新增: $script:phase='host_file_ack';Send-JSON $clipboard @{serial=3;files=@($imported.paths)};Read-Ack 3
60新增: $script:phase='host_file_native_read';$read=Invoke-Native '$files=[Windows.Forms.Clipboard]::GetFileDropList();if($files.Count -ne 1){throw "selection_invalid"};$b=[IO.File]::ReadAllBytes($files[0]);$result=[BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash($b)).Replace("-","").ToLowerInvariant()'
61新增: if($read -ne (SHA $content)){throw 'The actual native GUI file-drop bytes do not match.'}
62新增: $guestContent=$utf8.GetBytes('Guest to host file 中文😀');$guest64=[Convert]::ToBase64String($guestContent)
63新增: $script:phase='guest_file_native_write';$null=Invoke-Native ('$dir=Join-Path ([IO.Path]::GetTempPath()) ("cage-clipboard-qa-"+[guid]::NewGuid().ToString("N"));$null=[IO.Directory]::CreateDirectory($dir);$f=Join-Path $dir "guest.txt";[IO.File]::WriteAllBytes($f,[Convert]::FromBase64String("'+$guest64+'"));$list=[Collections.Specialized.StringCollection]::new();$null=$list.Add($f);[Windows.Forms.Clipboard]::SetFileDropList($list);$result="written"')
64新增: $selected=Read-Guest 'files';$exporter=Start-Bridge 'export';Send-JSON $exporter @($selected.files);$exporter.StandardInput.Close()
65新增: $reader=Start-Bridge 'import' $true;$exporter.StandardOutput.BaseStream.CopyTo($reader.StandardInput.BaseStream);$reader.StandardInput.Close();$received=Read-JSON $reader;Check-Exit $exporter;Check-Exit $reader
66新增: if(@($received.paths).Count -ne 1 -or (SHA ([IO.File]::ReadAllBytes($received.paths[0]))) -ne (SHA $guestContent)){throw 'The native guest selection did not export completely.'}
67新增: # Host paths cannot bypass the GUI agent's recorded selection grants.
68新增: $rejected=Start-Bridge 'export';Send-JSON $rejected @('C:\Windows\win.ini');$rejected.StandardInput.Close();$rejected.StandardOutput.BaseStream.CopyTo([IO.Stream]::Null);if(!$rejected.WaitForExit(30000) -or $rejected.ExitCode -eq 0){throw 'An unselected guest path was exported.'}
69新增: if($echoes -ne 0){throw 'A host clipboard write was echoed as a guest selection.'}
70新增: $result=[ordered]@{public_hello=$true;ordinary_gui_conpty=$true;terminal_resize=$true;text_host_to_guest=$true;text_guest_to_host=$true;png_host_to_guest_bytes=$true;png_guest_to_host_dimensions=$true;files_host_to_guest_bytes=$true;files_guest_to_host_bytes=$true;unselected_export_denied=$true;host_echoes=0}
71新增: $null=[IO.Directory]::CreateDirectory($EvidenceDirectory);[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'clipboard-result.json'),($result|ConvertTo-Json -Depth 3),$utf8)
72新增: $result|ConvertTo-Json -Compress
73新增:} finally {foreach($p in $owned){try{$p.StandardInput.Close();if(!$p.WaitForExit(1000)){$p.Kill()};$p.Dispose()}catch{}}}
新增scripts/guest-os/guest-clipboard-windows/update.ps1+87 −0看文件
@@ -0,0 +1,87 @@
1新增:#requires -Version 5.1
2新增:#requires -RunAsAdministrator
3新增:[CmdletBinding(SupportsShouldProcess)]
4新增:param(
5新增: [Parameter(Mandatory)][string]$ProfilePath,
6新增: [Parameter(Mandatory)][string]$PayloadDirectory,
7新增: [Parameter(Mandatory)][pscredential]$GuestAdministrator,
8新增: [switch]$RestartActiveBridge,
9新增: [switch]$GuestOnly
10新增:)
11新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
12新增:$profile=Get-Item -LiteralPath $ProfilePath
13新增:if($profile -isnot [IO.FileInfo] -or $profile.Length -gt 16384 -or $profile.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Invalid protected guest binding.'}
14新增:$binding=Get-Content -LiteralPath $profile.FullName -Raw|ConvertFrom-Json
15新增:$vm=Get-VM -Id ([guid]$binding.vm_id)
16新增:if($binding.version -ne 1 -or $vm.State -ne 'Running' -or @(Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or
17新增: $profile.Directory.FullName -ne [IO.Path]::GetDirectoryName($binding.relay_executable) -or
18新增: !(Test-Path -LiteralPath $binding.pairing_file)){throw 'The existing VM/profile binding is not usable.'}
19新增:$payload=Get-Item -LiteralPath $PayloadDirectory
20新增:if($payload -isnot [IO.DirectoryInfo] -or $payload.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Select a local payload directory.'}
21新增:foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -Recurse -Force)){if($entry.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Payload links are not allowed.'}}
22新增:foreach($name in @('Cage.GuestClipboard.exe','cage-guest-files.exe')){if(!(Test-Path -LiteralPath (Join-Path $payload.FullName $name))){throw 'The fixed bridge payloads are required.'}}
23新增:if(!$GuestOnly){
24新增: # A running packet or clipboard relay maps this host executable. Detect
25新增: # that conflict before stopping the independent guest GUI agent.
26新增: $image=[IO.Path]::GetFileNameWithoutExtension($binding.relay_executable)
27新增: foreach($process in [Diagnostics.Process]::GetProcessesByName($image)){
28新增: try { if($process.MainModule.FileName -ieq $binding.relay_executable){throw 'The bound host relay is active. Close its associated workbench before a full update, or use GuestOnly with a compatible host relay.'} }
29新增: finally { $process.Dispose() }
30新增: }
31新增:}
32新增:if(!$PSCmdlet.ShouldProcess($vm.Id,'Update only the independently bound guest bridge application files')){return}
33新增:$session=New-PSSession -VMId $vm.Id -Credential $GuestAdministrator
34新增:$deployment=$null
35新增:try {
36新增: $deployment=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid,[bool]$RestartActiveBridge -ScriptBlock {
37新增: param($expected,$sid,$restart)
38新增: $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
39新增: if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'}
40新增: $name="Cage-GUI-Bridge-$expected-$sid";$task=Get-ScheduledTask -TaskName $name
41新增: $program=Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$expected)
42新增: $actualSID=([Security.Principal.NTAccount]::new($task.Principal.UserId)).Translate([Security.Principal.SecurityIdentifier]).Value
43新增: if($task.Description -cne "Cage protected GUI bridge $expected $sid" -or $actualSID -ne $sid -or
44新增: $task.Principal.RunLevel -ne 'Limited' -or $task.Principal.LogonType -ne 'Interactive' -or
45新增: $task.Actions.Count -ne 1 -or $task.Actions[0].Execute -ine (Join-Path $program 'Cage.GuestClipboard.exe')){throw 'The GUI task does not match the owned deployment.'}
46新增: $active=$task.State -eq 'Running'
47新增: if($active -and !$restart){throw 'The bridge is active. Close its workbench before updating, or explicitly request RestartActiveBridge.'}
48新增: if($active){
49新增: Stop-ScheduledTask -InputObject $task
50新增: $until=[DateTime]::UtcNow.AddSeconds(10)
51新增: while((Get-ScheduledTask -TaskName $name).State -eq 'Running' -and [DateTime]::UtcNow -lt $until){Start-Sleep -Milliseconds 100}
52新增: if((Get-ScheduledTask -TaskName $name).State -eq 'Running'){throw 'The owned bridge did not stop; preserved its application files.'}
53新增: }
54新增: [pscustomobject]@{Program=$program;Task=$name;WasActive=$active}
55新增: }
56新增: foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -Force)){Copy-Item -LiteralPath $entry.FullName -Destination $deployment.Program -Recurse -ToSession $session -Force}
57新增: if(!$GuestOnly){foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -Force)){Copy-Item -LiteralPath $entry.FullName -Destination $profile.Directory.FullName -Recurse -Force}}
58新增: $started=Invoke-Command -Session $session -ArgumentList $deployment.Task,$binding.gui_user_sid,$deployment.Program -ScriptBlock {
59新增: param($name,$sid,$program)
60新增: $administrators=[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
61新增: foreach($entry in @((Get-Item -LiteralPath $program)) + @(Get-ChildItem -LiteralPath $program -Recurse -Force)){
62新增: if($entry.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Guest application files must not traverse links.'}
63新增: $acl=Get-Acl -LiteralPath $entry.FullName;$acl.SetOwner($administrators);Set-Acl -LiteralPath $entry.FullName -AclObject $acl
64新增: }
65新增: $gui=@(Get-CimInstance Win32_Process -Filter "Name='explorer.exe'"|Where-Object {$_.SessionId -gt 0}|ForEach-Object{Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid}|Where-Object {$_.Sid -eq $sid}).Count -gt 0
66新增: if($gui){Start-ScheduledTask -TaskName $name};$gui
67新增: }
68新增: if(@(Get-VMNetworkAdapter -VM (Get-VM -Id $vm.Id)).Count -ne 0){throw 'VM networking changed during update.'}
69新增: [pscustomobject]@{Updated=$true;HostRelayUpdated=(!$GuestOnly);RequiresGUILogin=(!$started);PairingPreserved=$true;PersonalDataPreserved=$true}
70新增:} catch {
71新增: $failure=$_
72新增: if($deployment -and $deployment.WasActive -and $session.State -eq 'Opened'){
73新增: try {
74新增: Invoke-Command -Session $session -ArgumentList $deployment.Task,$deployment.Program -ScriptBlock {
75新增: param($name,$program)
76新增: $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
77新增: $exe=Join-Path $program 'Cage.GuestClipboard.exe'
78新增: if((Get-Item -LiteralPath $exe).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Bridge executable changed to a link.'}
79新增: # Do not launch a truncated executable after a failed copy.
80新增: & $exe self-test | Out-Null
81新增: if($LASTEXITCODE -ne 0){throw 'The copied bridge failed its self-test.'}
82新增: Start-ScheduledTask -TaskName $name
83新增: } | Out-Null
84新增: } catch { throw 'The bridge update failed and its GUI task could not be restored; preserve the binding and application files for recovery.' }
85新增: }
86新增: throw $failure
87新增:} finally { Remove-PSSession $session }
新增scripts/guest-os/initialize-windows-test-accounts.ps1+120 −0看文件
@@ -0,0 +1,120 @@
1新增:#requires -Version 5.1
2新增:<#
3新增:.SYNOPSIS
4新增:Create isolated QA accounts after an authorized guest administrator completes Windows OOBE.
5新增:.DESCRIPTION
6新增:Supply a guest administrator credential with Get-Credential. Both new accounts
7新增:get independent random passwords. On Windows, Export-Clixml protects the saved
8新增:credentials with DPAPI for this host user. Use the returned AdminCredentialFile
9新增:with Import-Clixml and New-PSSession -VMId for later PowerShell Direct sessions.
10新增:The standard user is intended for the interactive Claude Desktop session.
11新增:#>
12新增:[CmdletBinding()]
13新增:param(
14新增: [Parameter(Mandatory)][guid]$VMId,
15新增: [Parameter(Mandatory)][string]$InstanceDirectory,
16新增: [Parameter(Mandatory)][pscredential]$GuestAdministrator
17新增:)
18新增:$ErrorActionPreference = 'Stop'
19新增:if ([Environment]::OSVersion.Platform -ne 'Win32NT') { throw 'Run on the Hyper-V host in Windows PowerShell.' }
20新增:$root = Get-Item -LiteralPath $InstanceDirectory
21新增:$qa = Join-Path $root.FullName 'evaluation-setup'
22新增:$qaDir = Get-Item -LiteralPath $qa
23新增:if (($root.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($qaDir.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
24新增: throw 'The private QA directories cannot be redirected.'
25新增:}
26新增:$receipt = Get-Content -LiteralPath (Join-Path $qa 'receipt.json') -Raw | ConvertFrom-Json
27新增:$vm = Get-VM -Id $VMId
28新增:$disks = @(Get-VMHardDiskDrive -VM $vm)
29新增:if ([guid]$receipt.VMId -ne $VMId -or $receipt.InstanceDirectory -ne $root.FullName -or $vm.State -ne 'Running' -or
30新增: $disks.Count -ne 1 -or $disks[0].Path -ne $receipt.Disk -or @(Get-VMNetworkAdapter -VM $vm).Count) {
31新增: throw 'Select the running offline evaluation VM that owns this setup receipt.'
32新增:}
33新增:$session = New-PSSession -VMId $VMId -Credential $GuestAdministrator
34新增:try {
35新增: $guestComputer = Invoke-Command -Session $session -ArgumentList $VMId -ScriptBlock {
36新增: param($expected)
37新增: $ErrorActionPreference = 'Stop'
38新增: $identity = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters' -Name VirtualMachineId
39新增: $setup = Get-ItemProperty 'HKLM:\SYSTEM\Setup'
40新增: $imageState = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\State' -Name ImageState
41新增: $os = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name EditionID
42新增: $account = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
43新增: if ([guid]$identity.VirtualMachineId -ne $expected -or $os.EditionID -ne 'EnterpriseEval' -or
44新增: $setup.SystemSetupInProgress -ne 0 -or $setup.OOBEInProgress -eq 1 -or $imageState.ImageState -ne 'IMAGE_STATE_COMPLETE' -or
45新增: !$account.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
46新增: throw 'PowerShell Direct must reach the matching Enterprise Evaluation guest after OOBE with guest administrator rights.'
47新增: }
48新增: $env:COMPUTERNAME
49新增: }
50新增:
51新增: $credentials = @()
52新增: $secrets = Join-Path $qa 'credentials'
53新增: $owner = [Security.Principal.WindowsIdentity]::GetCurrent().User
54新增: $permitted = @($owner.Value, 'S-1-5-18', 'S-1-5-32-544')
55新增: if (!(Test-Path -LiteralPath $secrets)) {
56新增: $acl = [Security.AccessControl.DirectorySecurity]::new()
57新增: $acl.SetAccessRuleProtection($true, $false)
58新增: $acl.SetOwner($owner)
59新增: foreach ($value in $permitted) {
60新增: $sid = [Security.Principal.SecurityIdentifier]::new($value)
61新增: $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow'))
62新增: }
63新增: if ($PSVersionTable.PSEdition -eq 'Desktop') {
64新增: $null = [IO.Directory]::CreateDirectory($secrets, $acl)
65新增: } else { [IO.FileSystemAclExtensions]::Create([IO.DirectoryInfo]::new($secrets), $acl) }
66新增: }
67新增: $secretsDir = Get-Item -LiteralPath $secrets
68新增: $acl = Get-Acl -LiteralPath $secrets
69新增: $unexpected = @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) |
70新增: Where-Object { $_.AccessControlType -eq 'Allow' -and $_.IdentityReference.Value -notin $permitted })
71新增: if (($secretsDir.Attributes -band [IO.FileAttributes]::ReparsePoint) -or !$acl.AreAccessRulesProtected -or $unexpected.Count) {
72新增: throw 'The test credential directory must have a private, protected Windows ACL.'
73新增: }
74新增: foreach ($name in @('CageQaAdmin', 'CageQaUser')) {
75新增: $path = Join-Path $secrets "$name.credential.xml"
76新增: $qualified = "$guestComputer\$name"
77新增: if (Test-Path -LiteralPath $path) {
78新增: $credential = Import-Clixml -LiteralPath $path
79新增: if ($credential -isnot [pscredential] -or $credential.UserName -ne $qualified) { throw 'Unexpected saved QA credential identity.' }
80新增: } else {
81新增: $random = [byte[]]::new(32)
82新增: $generator = [Security.Cryptography.RandomNumberGenerator]::Create()
83新增: try { $generator.GetBytes($random) } finally { $generator.Dispose() }
84新增: $password = ConvertTo-SecureString ('Qa9!' + [Convert]::ToBase64String($random)) -AsPlainText -Force
85新增: $credential = [pscredential]::new($qualified, $password)
86新增: $credential | Export-Clixml -LiteralPath $path -NoClobber
87新增: }
88新增: $credentials += $credential
89新增: }
90新增: $provision = Invoke-Command -Session $session -ArgumentList $VMId,$credentials[0],$credentials[1] -ScriptBlock {
91新增: param($expected, [pscredential]$admin, [pscredential]$standard)
92新增: $ErrorActionPreference = 'Stop'
93新增: $tag = "Cage isolated test VM $expected"
94新增: $admins = Get-LocalGroup -SID ([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))
95新增: $users = Get-LocalGroup -SID ([Security.Principal.SecurityIdentifier]::new('S-1-5-32-545'))
96新增: foreach ($credential in @($admin,$standard)) {
97新增: $name = $credential.UserName.Split('\')[-1]
98新增: $u = Get-LocalUser -Name $name -ErrorAction SilentlyContinue
99新增: if ($u -and $u.Description -ne $tag) { throw "An unrelated guest account already uses the name $name." }
100新增: if (!$u) { $u = New-LocalUser -Name $name -Password $credential.Password -Description $tag }
101新增: $group = if ($name -eq 'CageQaAdmin') { $admins } else { $users }
102新增: if (!(Get-LocalGroupMember -Group $group | Where-Object { $_.SID -eq $u.SID })) {
103新增: Add-LocalGroupMember -Group $group -Member $u
104新增: }
105新增: if ($name -eq 'CageQaUser' -and (Get-LocalGroupMember -Group $admins | Where-Object { $_.SID -eq $u.SID })) {
106新增: throw 'The test desktop user is unexpectedly an administrator.'
107新增: }
108新增: }
109新增: [pscustomobject]@{ Computer = $env:COMPUTERNAME; Admin = 'CageQaAdmin'; DesktopUser = 'CageQaUser' }
110新增: }
111新增: # Authenticate a fresh VMBus session using the new administrator.
112新增: $verified = Invoke-Command -VMId $VMId -Credential $credentials[0] -ScriptBlock { [Security.Principal.WindowsIdentity]::GetCurrent().Name }
113新增: if ($verified -ne $credentials[0].UserName) { throw 'The independent PowerShell Direct login did not match the QA administrator.' }
114新增: [pscustomobject]@{
115新增: VMId = $VMId; Computer = $provision.Computer; Admin = $provision.Admin; StandardDesktopUser = $provision.DesktopUser
116新增: PowerShellDirectVerified = $true
117新增: AdminCredentialFile = Join-Path $secrets 'CageQaAdmin.credential.xml'
118新增: DesktopCredentialFile = Join-Path $secrets 'CageQaUser.credential.xml'
119新增: }
120新增:} finally { Remove-PSSession -Session $session }
新增scripts/guest-os/initialize-windows-workbench-user.ps1+126 −0看文件
@@ -0,0 +1,126 @@
1新增:# Invoked by the first-run installer inside its own VM through PowerShell Direct.
2新增:# No password is serialized, passed on a command line, or returned to the host.
3新增:param([Parameter(Mandatory)][guid]$VMId)
4新增:$ErrorActionPreference='Stop'
5新增:$machine=Get-CimInstance Win32_ComputerSystem
6新增:if ($VMId -eq [guid]::Empty -or $machine.Manufacturer -ne 'Microsoft Corporation' -or $machine.Model -ne 'Virtual Machine' -or
7新增: [guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $VMId) { throw 'This operation requires the exact fresh Cage guest.' }
8新增:$userName='Cage-'+$VMId.ToString('N').Substring(0,10)
9新增:$description='Cage '+$VMId.ToString('D')
10新增:$key='HKLM:\SOFTWARE\Cage\WorkbenchBoot\'+$VMId.ToString('D')
11新增:$logon='HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
12新增:$win=Get-Item -LiteralPath $logon
13新增:$user=Get-LocalUser -Name $userName -ErrorAction SilentlyContinue
14新增:$record=if(Test-Path -LiteralPath $key){Get-ItemProperty -LiteralPath $key}
15新增:if ($record -and ($record.VM -ne $VMId.ToString('D') -or $record.User -ne $userName)) { throw 'An existing boot-account registration was preserved.' }
16新增:if ($user -and (!$record -or $user.Description -cne $description -or ($record.SID -and $record.SID -ne $user.SID.Value))) { throw 'An existing Windows account cannot be used for automatic logon.' }
17新增:if ($win.GetValueNames() -contains 'DefaultPassword' -or $win.GetValue('ForceAutoLogon','0') -ne '0' -or
18新增: ($win.GetValue('AutoAdminLogon','0') -eq '1' -and (!$record -or $win.GetValue('DefaultUserName','') -ne $userName))) {
19新增: throw 'An existing Windows logon policy was preserved.'
20新增:}
21新增:if (!$record -or $record.Stage -ne 'ready') {
22新增: if (!$user -and $record -and $record.SID) { throw 'The dedicated account was removed. No replacement was created.' }
23新增: # Microsoft's Winlogon LSA API. Only the fixed DefaultPassword object may
24新增: # be tested for existence or created. Its contents cannot be read here.
25新增: if (!('CageWorkbenchBootSecret' -as [type])) {
26新增: Add-Type -TypeDefinition @'
27新增:using System;
28新增:using System.Runtime.InteropServices;
29新增:using System.Security;
30新增:using System.ComponentModel;
31新增:public static class CageWorkbenchBootSecret {
32新增: [StructLayout(LayoutKind.Sequential)]
33新增: struct Attributes { public uint length; public IntPtr root, name; public uint flags; public IntPtr descriptor, quality; }
34新增: [StructLayout(LayoutKind.Sequential)]
35新增: struct Unicode { public ushort length, maximum; public IntPtr text; }
36新增: [DllImport("advapi32.dll")] static extern int LsaOpenPolicy(IntPtr system,ref Attributes attr,uint access,out IntPtr policy);
37新增: [DllImport("advapi32.dll")] static extern int LsaOpenSecret(IntPtr policy,ref Unicode name,uint access,out IntPtr secret);
38新增: [DllImport("advapi32.dll")] static extern int LsaQuerySecret(IntPtr secret,out IntPtr current,IntPtr setTime,IntPtr previous,IntPtr previousSetTime);
39新增: [DllImport("advapi32.dll")] static extern int LsaFreeMemory(IntPtr memory);
40新增: [DllImport("advapi32.dll")] static extern int LsaStorePrivateData(IntPtr policy,ref Unicode name,ref Unicode data);
41新增: [DllImport("advapi32.dll")] static extern int LsaNtStatusToWinError(int code);
42新增: [DllImport("advapi32.dll")] static extern int LsaClose(IntPtr handle);
43新增: static bool CheckOrStore(SecureString password) {
44新增: var attr=new Attributes(); attr.length=(uint)Marshal.SizeOf(typeof(Attributes));
45新增: IntPtr policy; int code=LsaOpenPolicy(IntPtr.Zero,ref attr,0x24,out policy);
46新增: if(code!=0)throw new Win32Exception(LsaNtStatusToWinError(code));
47新增: const string fixedName="DefaultPassword"; var name=new Unicode();
48新增: name.length=(ushort)(fixedName.Length*2);name.maximum=(ushort)(name.length+2);name.text=Marshal.StringToHGlobalUni(fixedName);
49新增: try {
50新增: IntPtr existing; code=LsaOpenSecret(policy,ref name,2,out existing);
51新增: if(code==0){
52新增: // Fresh Windows can create the LSA object without assigning it
53新增: // a password. Inspect only the length field, never its buffer.
54新增: IntPtr valueHeader=IntPtr.Zero;
55新增: try {
56新增: code=LsaQuerySecret(existing,out valueHeader,IntPtr.Zero,IntPtr.Zero,IntPtr.Zero);
57新增: if(code!=0 && unchecked((uint)code)!=0xc0000034U)throw new Win32Exception(LsaNtStatusToWinError(code));
58新增: if(valueHeader!=IntPtr.Zero && Marshal.ReadInt16(valueHeader)!=0){
59新增: if(password==null)return true;
60新增: throw new InvalidOperationException("An existing Winlogon LSA secret was preserved.");
61新增: }
62新增: } finally {if(valueHeader!=IntPtr.Zero)LsaFreeMemory(valueHeader);LsaClose(existing);}
63新增: } else if(unchecked((uint)code)!=0xc0000034U)throw new Win32Exception(LsaNtStatusToWinError(code));
64新增: if(password==null)return false;
65新增: var value=new Unicode(); value.length=checked((ushort)(password.Length*2));value.maximum=(ushort)(value.length+2);
66新增: value.text=Marshal.SecureStringToGlobalAllocUnicode(password);
67新增: try {code=LsaStorePrivateData(policy,ref name,ref value);if(code!=0)throw new Win32Exception(LsaNtStatusToWinError(code));}
68新增: finally {Marshal.ZeroFreeGlobalAllocUnicode(value.text);}
69新增: return true;
70新增: } finally {Marshal.FreeHGlobal(name.text);LsaClose(policy);}
71新增: }
72新增: public static bool Exists() { return CheckOrStore(null); }
73新增: public static void StoreNew(SecureString password) { if(password==null)throw new ArgumentNullException();CheckOrStore(password); }
74新增:}
75新增:'@
76新增: }
77新增: $hasSecret=[CageWorkbenchBootSecret]::Exists()
78新增: if ($hasSecret -and (!$record -or $record.Stage -ne 'storing' -or !$user -or $record.SID -ne $user.SID.Value -or $user.LastLogon)) {
79新增: throw 'An existing Winlogon secret was preserved.'
80新增: }
81新增: if (!$record) {
82新增: $null=New-Item -Path $key -Force
83新增: $null=New-ItemProperty -LiteralPath $key -Name VM -Value $VMId.ToString('D') -PropertyType String
84新增: $null=New-ItemProperty -LiteralPath $key -Name User -Value $userName -PropertyType String
85新增: }
86新增: if (!$hasSecret) {
87新增: if ($user -and ($user.Enabled -or $user.LastLogon)) {throw 'The partially prepared user has already been used. Its password was preserved.'}
88新增: $random=[Security.Cryptography.RandomNumberGenerator]::Create()
89新增: $bytes=New-Object byte[] 48
90新增: $password=[Security.SecureString]::new()
91新增: try {
92新增: $random.GetBytes($bytes)
93新增: $alphabet='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
94新增: foreach ($b in $bytes) { $password.AppendChar($alphabet[[int]$b -band 63]) }
95新增: foreach ($c in 'a9Q!'.ToCharArray()) { $password.AppendChar($c) }
96新增: $password.MakeReadOnly()
97新增: if (!$user) {
98新增: $user=New-LocalUser -Name $userName -Password $password -Disabled -Description $description -PasswordNeverExpires -UserMayNotChangePassword
99新增: } else {
100新增: # Only our disabled, never-used account can reach this interrupted
101新增: # initial transaction. An enabled account never has its password reset.
102新增: Set-LocalUser -InputObject $user -Password $password
103新增: }
104新增: $null=New-ItemProperty -LiteralPath $key -Name SID -Value $user.SID.Value -PropertyType String -Force
105新增: $null=New-ItemProperty -LiteralPath $key -Name Stage -Value 'storing' -PropertyType String -Force
106新增: [CageWorkbenchBootSecret]::StoreNew($password)
107新增: } finally { $password.Dispose();$random.Dispose();[Array]::Clear($bytes,0,$bytes.Length) }
108新增: }
109新增: if (!$user.Enabled) { Enable-LocalUser -InputObject $user }
110新增: $user=Get-LocalUser -SID $user.SID
111新增: $null=New-ItemProperty -LiteralPath $key -Name Stage -Value 'ready' -PropertyType String -Force
112新增:}
113新增:if (!$user) {throw 'The dedicated workbench account was removed. No replacement was created.'}
114新增:if (!$user.Enabled -or $user.PrincipalSource -ne 'Local' -or $user.Description -cne $description) { throw 'The dedicated local account is unavailable.' }
115新增:$sid=$user.SID.Value
116新增:foreach ($group in Get-LocalGroup) {
117新增: $member=@(Get-LocalGroupMember -Group $group -ErrorAction Stop | Where-Object { $_.SID.Value -eq $sid })
118新增: if ($member.Count -and $group.SID.Value -ne 'S-1-5-32-545') { throw 'The workbench account belongs to a privileged or unexpected group.' }
119新增:}
120新增:$users=Get-LocalGroup -SID 'S-1-5-32-545'
121新增:if (!@(Get-LocalGroupMember -Group $users | Where-Object {$_.SID.Value -eq $sid}).Count) { Add-LocalGroupMember -Group $users -Member $user }
122新增:$null=New-ItemProperty -LiteralPath $key -Name SID -Value $sid -PropertyType String -Force
123新增:
124新增:# First boot is armed by the separate boot service only during a real shutdown.
125新增:# Windows logon UI is never sent a broad keyboard event or a cleartext value.
126新增:[pscustomobject]@{ SID=$sid; Name=$userName; BootID=(Get-CimInstance Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o'); Program=(Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$VMId)); AlreadySignedIn=($machine.UserName -eq ($env:COMPUTERNAME+'\'+$userName)) }
新增scripts/guest-os/install-guest-powershell.cmd+45 −0看文件
@@ -0,0 +1,45 @@
1新增:@echo off
2新增:setlocal EnableExtensions DisableDelayedExpansion
3新增:rem Windows Setup runs this command from Cage's read-only answer DVD as SYSTEM.
4新增:set "CAGE_PWSH_MEDIA=%~d0\"
5新增:set "CAGE_PWSH_HASH=__CAGE_PWSH_SHA256__"
6新增:set "CAGE_PWSH_VERSION=__CAGE_PWSH_VERSION__"
7新增:"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -Command ^
8新增: "$ErrorActionPreference = 'Stop';" ^
9新增: "$medium = [IO.DriveInfo]::new($env:CAGE_PWSH_MEDIA);" ^
10新增: "if ($medium.DriveType -ne 'CDRom' -or $medium.VolumeLabel -ne 'CAGE_ANSWER' -or ![Environment]::Is64BitProcess -or ![Security.Principal.WindowsIdentity]::GetCurrent().IsSystem) { throw 'PowerShell guest installation requires Windows Setup and the Cage answer DVD.' }" ^
11新增: "$system = Get-CimInstance Win32_ComputerSystem;" ^
12新增: "if ($system.Manufacturer -ne 'Microsoft Corporation' -or $system.Model -ne 'Virtual Machine') { throw 'Expected the Hyper-V guest.' }" ^
13新增: "$zip = Join-Path $medium.RootDirectory.FullName 'PowerShell.zip';" ^
14新增: "$base = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'PowerShell';" ^
15新增: "$target = Join-Path $base '7';" ^
16新增: "function Test-Runtime([string]$directory, [string]$expectedVersion) {" ^
17新增: " $exe = Join-Path $directory 'pwsh.exe';" ^
18新增: " $probe = @(& $exe -NoLogo -NoProfile -NonInteractive -Command '$PSVersionTable.PSVersion.ToString(); [Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture.ToString()');" ^
19新增: " if ($LASTEXITCODE -ne 0 -or $probe.Count -ne 2 -or $probe[0] -notmatch '^7\.[0-9]+\.[0-9]+$' -or $probe[1] -ne 'X64' -or ($expectedVersion -and $probe[0] -ne $expectedVersion)) { throw 'The installed shell did not report the expected x64 PowerShell 7 version.' }" ^
20新增: "}" ^
21新增: "if ((Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash -ne $env:CAGE_PWSH_HASH) { throw 'The offline PowerShell package does not match its pinned SHA-256.' }" ^
22新增: "$null = [IO.Directory]::CreateDirectory($base);" ^
23新增: "if ((Get-Item -LiteralPath $base).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'The PowerShell installation folder is redirected.' }" ^
24新增: "if (!(Test-Path -LiteralPath $target)) {" ^
25新增: " $stage = Join-Path $base ([guid]::NewGuid().ToString('N'));" ^
26新增: " try {" ^
27新增: " Add-Type -AssemblyName System.IO.Compression.FileSystem;" ^
28新增: " [IO.Compression.ZipFile]::ExtractToDirectory($zip, $stage);" ^
29新增: " Test-Runtime $stage $env:CAGE_PWSH_VERSION;" ^
30新增: " try { [IO.Directory]::Move($stage, $target) } catch [IO.IOException] { if (![IO.Directory]::Exists($target)) { throw } }" ^
31新增: " } finally { if ([IO.Directory]::Exists($stage)) { [IO.Directory]::Delete($stage, $true) } }" ^
32新增: "}" ^
33新增: "if ((Get-Item -LiteralPath $target).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'The installed PowerShell directory is redirected.' }" ^
34新增: "Test-Runtime $target '';" ^
35新增: "$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true);" ^
36新增: "try {" ^
37新增: " $raw = [string]$key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames);" ^
38新增: " $entries = @($raw.Split(';') | ForEach-Object { [Environment]::ExpandEnvironmentVariables($_.Trim().Trim([char]34)).TrimEnd('\') });" ^
39新增: " if ($target -notin $entries) {" ^
40新增: " $newPath = if ($raw) { $target + ';' + $raw } else { $target };" ^
41新增: " $kind = if ('Path' -in $key.GetValueNames()) { $key.GetValueKind('Path') } else { [Microsoft.Win32.RegistryValueKind]::ExpandString };" ^
42新增: " $key.SetValue('Path', $newPath, $kind);" ^
43新增: " }" ^
44新增: "} finally { $key.Close() }"
45新增:exit /b %errorlevel%
新增scripts/guest-os/install-guest-powershell.tests.ps1+93 −0看文件
@@ -0,0 +1,93 @@
1新增:#requires -Version 5.1
2新增:# Exercise the actual Setup command with an isolated filesystem and registry stand-in.
3新增:$ErrorActionPreference = 'Stop'
4新增:$file = Join-Path $PSScriptRoot 'install-guest-powershell.cmd'
5新增:$lines = @(Get-Content -LiteralPath $file | Where-Object { $_.StartsWith(' "') })
6新增:$parts = for ($i = 0; $i -lt $lines.Count; $i++) {
7新增: $suffix = if ($i -lt $lines.Count - 1) { '" ^' } else { '"' }
8新增: if (!$lines[$i].EndsWith($suffix)) { throw 'Broken CMD line continuation.' }
9新增: $lines[$i].Substring(3, $lines[$i].Length - 3 - $suffix.Length)
10新增:}
11新增:$command = $parts -join ' '
12新增:if ($command.Length -gt 7700 -or $command.Contains('"') -or $command.Contains('%')) {
13新增: throw 'The guest installer command may be truncated or expanded by cmd.exe.'
14新增:}
15新增:$errors = $null
16新增:$ast = [Management.Automation.Language.Parser]::ParseInput($command, [ref]$null, [ref]$errors)
17新增:if ($errors.Count) { throw $errors[0] }
18新增:$steps = $ast.EndBlock.Statements
19新增:$installStart = @($steps | Where-Object { $_.Extent.Text.StartsWith('if ((Get-FileHash ') })[0]
20新增:$regStart = @($steps | Where-Object { $_.Extent.Text.StartsWith('$key = ') })[0]
21新增:$install = [scriptblock]::Create($command.Substring($installStart.Extent.StartOffset, $regStart.Extent.StartOffset - $installStart.Extent.StartOffset))
22新增:$updatePath = [scriptblock]::Create($steps[-1].Extent.Text)
23新增:
24新增:function Assert-Failure([scriptblock]$run, [string]$message) {
25新增: try { & $run } catch {
26新增: if ($_.Exception.Message -like "*$message*") { return }
27新增: throw
28新增: }
29新增: throw "Expected failure: $message"
30新增:}
31新增:
32新增:# The archive, hash checks, staging, publication, cleanup and retry are real.
33新增:# Simulate the version response of a Windows executable on non-Windows hosts.
34新增:function Test-Runtime([string]$directory, [string]$expectedVersion) {
35新增: $version = [IO.File]::ReadAllText((Join-Path $directory 'pwsh.exe'))
36新增: if ($version -notmatch '^7\.[0-9]+\.[0-9]+$' -or ($expectedVersion -and $expectedVersion -ne $version)) {
37新增: throw 'Simulated incompatible runtime'
38新增: }
39新增:}
40新增:
41新增:$oldHash = $env:CAGE_PWSH_HASH
42新增:$oldVersion = $env:CAGE_PWSH_VERSION
43新增:$temp = [IO.Directory]::CreateDirectory((Join-Path ([IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString('N'))))
44新增:try {
45新增: $version = '7.6.0'
46新增: $env:CAGE_PWSH_VERSION = $version
47新增: $files = [IO.Directory]::CreateDirectory((Join-Path $temp 'source'))
48新增: [IO.File]::WriteAllText((Join-Path $files.FullName 'pwsh.exe'), $version)
49新增: $zip = Join-Path $temp.FullName 'PowerShell.zip'
50新增: Add-Type -AssemblyName System.IO.Compression.FileSystem
51新增: [IO.Compression.ZipFile]::CreateFromDirectory($files.FullName, $zip)
52新增: $base = Join-Path $temp.FullName 'Program Files'
53新增: $target = Join-Path $base '7'
54新增: $env:CAGE_PWSH_HASH = '00' * 32
55新增: Assert-Failure { & $install } 'pinned SHA-256'
56新增: if ([IO.Directory]::Exists($base)) { throw 'A hash mismatch changed the destination.' }
57新增:
58新增: $env:CAGE_PWSH_HASH = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash
59新增: $env:CAGE_PWSH_VERSION = '7.5.0'
60新增: Assert-Failure { & $install } 'incompatible runtime'
61新增: if (@([IO.Directory]::EnumerateFileSystemEntries($base)).Count) { throw 'Failed runtime left partial files.' }
62新增: $env:CAGE_PWSH_VERSION = $version
63新增: & $install
64新增: $exe = Join-Path $target 'pwsh.exe'
65新增: if ([IO.File]::ReadAllText($exe) -ne $version) { throw 'Verified shell was not published.' }
66新增: [IO.File]::WriteAllText($exe, '7.8.0')
67新增: & $install
68新增: if ([IO.File]::ReadAllText($exe) -ne '7.8.0') { throw 'A later installed release was overwritten.' }
69新增: [IO.File]::WriteAllText($exe, 'unexpected')
70新增: Assert-Failure { & $install } 'incompatible runtime'
71新增: if ([IO.File]::ReadAllText($exe) -ne 'unexpected') { throw 'Existing installation was modified on failure.' }
72新增:
73新增: $key = [pscustomobject]@{ Raw = '%SystemRoot%\System32'; Writes = 0 }
74新增: $key | Add-Member ScriptMethod GetValue { param($name,$fallback,$flags) $this.Raw }
75新增: $key | Add-Member ScriptMethod GetValueNames { @('Path') }
76新增: $key | Add-Member ScriptMethod GetValueKind { param($name) [Microsoft.Win32.RegistryValueKind]::ExpandString }
77新增: $key | Add-Member ScriptMethod SetValue {
78新增: param($name,$value,$kind)
79新增: if ($kind -ne [Microsoft.Win32.RegistryValueKind]::ExpandString) { throw 'Changed registry value kind.' }
80新增: $this.Raw = $value; $this.Writes++
81新增: }
82新增: $key | Add-Member ScriptMethod Close {}
83新增: & $updatePath
84新增: & $updatePath
85新增: if ($key.Writes -ne 1 -or $key.Raw -cne ($target + ';%SystemRoot%\System32')) {
86新增: throw 'PATH retry duplicated the entry or rewrote existing variables.'
87新增: }
88新增:} finally {
89新增: $env:CAGE_PWSH_HASH = $oldHash
90新增: $env:CAGE_PWSH_VERSION = $oldVersion
91新增: $temp.Delete($true)
92新增:}
93新增:Write-Output 'Passed offline ZIP verification, publication, retry, existing shell preservation and machine PATH checks (simulated guest).'
新增scripts/guest-os/install-macos-browser.sh+76 −0看文件
@@ -0,0 +1,76 @@
1新增:#!/bin/bash
2新增:# Run as the administrator inside the prepared virtual Mac. All media are local.
3新增:set -euo pipefail
4新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin
5新增:[[ ( $# == 1 || ( $# == 2 && $2 == --update-tools ) ) && $EUID == 0 && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]]
6新增:[[ -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 ]]
7新增:media=$(cd "$1" && pwd)
8新增:base=/usr/local/libexec
9新增:tools="$base/cage-workbench-browser-4.145.0-pw1.65.0"
10新增:mkdir -p "$base"
11新增:stage=$(mktemp -d "$base/.cage-browser.XXXXXXXX")
12新增:volume="$stage/volume"
13新增:trap 'if mount | grep -Fq " on $volume ("; then hdiutil detach "$volume" >/dev/null; fi; rm -rf "$stage"' EXIT
14新增:umask 022
15新增:verify() {
16新增: [[ $(shasum -a 256 "$1" | cut -d' ' -f1) == "$2" ]] || { echo "Unexpected package digest: $1" >&2; exit 1; }
17新增:}
18新增:if [[ ! -x $tools/editor/lib/node || ! -f $tools/playwright/package.json ]]; then
19新增: mkdir -p "$stage/tools/editor" "$stage/tools/playwright"
20新增: cp "$media/editor.tgz" "$media/playwright.tgz" "$stage/"
21新增: verify "$stage/editor.tgz" a79774d8d34eed785c1f831bc0125f7534bc21a0039bef8e8a2aa32463f9421a
22新增: verify "$stage/playwright.tgz" 315247c55a793ca760b2f05bdcee0e6a53fd65b1f22d1d3de8323c8c9395add3
23新增: tar -xzf "$stage/editor.tgz" -C "$stage/tools/editor" --no-same-owner --strip-components 1
24新增: tar -xzf "$stage/playwright.tgz" -C "$stage/tools/playwright" --no-same-owner --strip-components 1
25新增: "$stage/tools/editor/lib/node" --version
26新增: mkdir -p "$tools"
27新增: for component in editor playwright; do
28新增: [[ ! -L $tools/$component ]]
29新增: if [[ -e $tools/$component ]]; then mv "$tools/$component" "$stage/previous-$component"; fi
30新增: if ! mv "$stage/tools/$component" "$tools/$component"; then
31新增: if [[ -d $stage/previous-$component ]]; then mv "$stage/previous-$component" "$tools/$component"; fi
32新增: exit 1
33新增: fi
34新增: done
35新增:fi
36新增:app='/Applications/Google Chrome.app'
37新增:requirement='anchor apple generic and identifier "com.google.Chrome" and certificate leaf[subject.OU] = "EQHXZ8M8AV"'
38新增:if [[ ! -e $app || ${2:-} == --update-tools ]]; then
39新增: cp "$media/chrome.dmg" "$stage/chrome.dmg"
40新增: mkdir "$volume"
41新增: hdiutil attach -readonly -nobrowse -noautoopen -mountpoint "$volume" "$stage/chrome.dmg" >/dev/null
42新增: spctl --assess --type execute "$volume/Google Chrome.app"
43新增: ditto --norsrc "$volume/Google Chrome.app" "$stage/Google Chrome.app"
44新增: codesign --verify --strict --deep -R="$requirement" "$stage/Google Chrome.app"
45新增: spctl --assess --type execute "$stage/Google Chrome.app"
46新增: install_chrome=yes
47新增: if [[ -e $app ]]; then
48新增: [[ -d $app && ! -L $app ]]
49新增: codesign --verify --strict -R="$requirement" "$app"
50新增: current=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app/Contents/Info.plist")
51新增: incoming=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$stage/Google Chrome.app/Contents/Info.plist")
52新增: [[ $current =~ ^[0-9]+(\.[0-9]+)*$ && $incoming =~ ^[0-9]+(\.[0-9]+)*$ ]]
53新增: if ! /usr/bin/perl -e '@a=split(/\./,$ARGV[0]);@b=split(/\./,$ARGV[1]);for($i=0;$i<@a||$i<@b;$i++){exit(($a[$i]//0)>($b[$i]//0)?0:1) if ($a[$i]//0)!=($b[$i]//0)}exit 1' "$incoming" "$current"; then install_chrome=no; fi
54新增: fi
55新增: if [[ $install_chrome == yes ]]; then
56新增: if [[ -e $app ]]; then mv "$app" "$stage/previous-chrome.app"; fi
57新增: if ! mv "$stage/Google Chrome.app" "$app"; then
58新增: if [[ -d $stage/previous-chrome.app ]]; then mv "$stage/previous-chrome.app" "$app"; fi
59新增: exit 1
60新增: fi
61新增: fi
62新增:fi
63新增:codesign --verify --strict -R="$requirement" "$app"
64新增:sources=$(cd "$(dirname "$0")" && pwd)
65新增:install -m 644 "$sources/macos-browser.mjs" "$base/cage-macos-browser.mjs"
66新增:install -m 755 "$sources/cage-macos-editor" "$base/cage-macos-editor"
67新增:if [[ -f "$media/native-browser/macos-native-browser.mjs" ]]; then
68新增: cp -R "$media/native-browser" "$stage/controller"
69新增:else
70新增: "$sources/package-macos-browser.sh" "$stage/controller"
71新增:fi
72新增:install -d "$tools/controller" "$tools/controller/modules" "$tools/controller/split-extension"
73新增:install -m 644 "$stage/controller/"*.mjs "$tools/controller/"
74新增:install -m 755 "$stage/controller/cage-tailnet" "$tools/controller/cage-tailnet"
75新增:install -m 644 "$stage/controller/modules/"*.mjs "$tools/controller/modules/"
76新增:install -m 644 "$stage/controller/split-extension/"* "$tools/controller/split-extension/"
新增scripts/guest-os/install-macos-cli.sh+114 −0看文件
@@ -0,0 +1,114 @@
1新增:#!/bin/bash
2新增:# Offline installation. Only Cage-owned guest tools are published.
3新增:set -euo pipefail
4新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin
5新增:[[ ( $# == 1 || ( $# == 2 && $2 == --components ) ) && $1 == /* && $EUID == 0 && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]]
6新增:components=${2:-}
7新增:marker=/var/db/cage-guest-os
8新增:[[ ! -L $marker && -f $marker && $(stat -f %u "$marker") == 0 && $(cat "$marker") == macos ]]
9新增:mode=$(stat -f %OLp "$marker")
10新增:(( (8#$mode & 022) == 0 ))
11新增:kit=$(cd -P "$1" && pwd)
12新增:# Local helper sources are supplied by the trusted host, not by the GUI guest user.
13新增:[[ -z $(find "$kit" \( -type l -o ! -user root -o -perm -0020 -o -perm -0002 \) -print -quit) ]]
14新增:parent=$kit
15新增:while [[ $parent != / ]]; do
16新增: mode=$(stat -f %Op "$parent")
17新增: [[ $(stat -f %u "$parent") == 0 ]] || exit 1
18新增: (( (8#$mode & 022) == 0 || (8#$mode & 01000) != 0 )) || exit 1
19新增: parent=$(dirname "$parent")
20新增:done
21新增:umask 022
22新增:base=/usr/local/libexec
23新增:mkdir -p "$base" /usr/local/bin
24新增:work=$(mktemp -d "$base/.cage-cli-install.XXXXXXXX")
25新增:trap 'rm -rf "$work"' EXIT
26新增:cd "$work"
27新增:cp "$kit"/{macos-cli.py,cli_channel.py,cli_channel.resume.md,claude_account_resume.md,claude-account.py} .
28新增:runtime="$base/cage-cli-runtime-2.1.311-py3.13.18-git2.56.0"
29新增:if [[ $components == --components ]]; then
30新增: [[ -x $runtime/bin/python3 && -x $runtime/bin/claude && -x $runtime/bin/git ]] || { echo '请先更新环境工具,再同步组件。' >&2; exit 1; }
31新增:else
32新增:cp "$kit"/{claude,uv.tar.gz,python.tar.gz,git.tar.gz} .
33新增:check() { [[ $(shasum -a 256 "$2" | cut -d' ' -f1) == "$1" ]]; }
34新增:check 85d8c08707fcfd1e78ffa0204eefbc6ec9e4fe22f375fb2767ef85d957ed3161 claude
35新增:check 81b811b57e4624df7ed3aac148e0359100d9962f3d9dce00aec533dc2e086731 uv.tar.gz
36新增:check 8392b6ea51d94391befb2c31ebe75463f045d0b69dfcf5e1bb3234e1f5fa3405 python.tar.gz
37新增:check 1110de343de11cc6f469b782b60f36217b9199b5e06875dd65baa26dd60563c7 git.tar.gz
38新增:chmod 755 claude
39新增:codesign --verify --strict --architecture arm64 -R '=anchor apple generic and identifier "com.anthropic.claude-code" and certificate leaf[subject.OU] = "Q6L2SF6YDW"' claude
40新增:fi
41新增:# Use rename(2), which never nests the staged directory inside a
42新增:# concurrently completed installation.
43新增:publish_dir() {
44新增: /usr/bin/perl -e 'rename($ARGV[0], $ARGV[1]) || -d $ARGV[1] || die "publish: $!"' "$1" "$2"
45新增:}
46新增:if [[ ! -d $runtime ]]; then
47新增: tar -xzf uv.tar.gz --no-same-owner
48新增: mkdir -p tools/bin
49新增: # uv recognizes the distribution format from the archive filename.
50新增: mv python.tar.gz cpython-3.13.18-aarch64-apple-darwin.tar.gz
51新增: cat > python.json <<JSON
52新增:{"cpython-3.13.18-darwin-aarch64-none":{"name":"cpython","arch":{"family":"aarch64","variant":null},"os":"darwin","libc":"none","major":3,"minor":13,"patch":18,"prerelease":"","url":"file://$work/cpython-3.13.18-aarch64-apple-darwin.tar.gz","sha256":"8392b6ea51d94391befb2c31ebe75463f045d0b69dfcf5e1bb3234e1f5fa3405","variant":null,"build":"20261026"}}
53新增:JSON
54新增: UV_CACHE_DIR="$work/cache" ./uv-aarch64-apple-darwin/uv python install 3.13.18 --install-dir "$work/tools/python" --no-bin --no-config --offline --python-downloads-json-url "$work/python.json"
55新增: ln -s ../python/cpython-3.13.18-macos-aarch64-none/bin/python3.13 tools/bin/python3
56新增: tools/bin/python3 -I -c 'import sys, ssl; assert sys.version_info[:3] == (3,13,18)'
57新增: mv claude tools/bin/
58新增: mkdir tools/git
59新增: tar -xzf git.tar.gz -C tools/git --no-same-owner
60新增: [[ $(tools/git/bin/git --version) == 'git version 2.56.0' ]]
61新增: # This GitHub Desktop distribution is relocatable. Its remote helpers
62新增: # and templates must be resolved from the same pinned distribution.
63新增: cat > tools/bin/git <<GIT
64新增:#!/bin/sh
65新增:export GIT_EXEC_PATH="\${GIT_EXEC_PATH:-$runtime/git/libexec/git-core}"
66新增:export GIT_TEMPLATE_DIR="\${GIT_TEMPLATE_DIR:-$runtime/git/share/git-core/templates}"
67新增:export GIT_CONFIG_SYSTEM="\${GIT_CONFIG_SYSTEM:-$runtime/git/etc/gitconfig}"
68新增:exec "$runtime/git/bin/git" "\$@"
69新增:GIT
70新增: chmod 755 tools/bin/git
71新增: chmod -R a+rX,go-w tools
72新增: publish_dir tools "$runtime"
73新增:fi
74新增:revision=$(shasum -a 256 macos-cli.py cli_channel.py cli_channel.resume.md claude_account_resume.md claude-account.py | shasum -a 256 | cut -c1-16)
75新增:target="$base/cage-cli-2.1.311-git2.56.0-$revision"
76新增:if [[ -d $target ]]; then
77新增: intact=yes
78新增: for name in macos-cli.py cli_channel.py cli_channel.resume.md; do
79新增: if ! cmp -s "$name" "$target/$name"; then intact=no; fi
80新增: done
81新增: if ! cmp -s claude_account_resume.md "$target/cli_channel.account-resume.md" ||
82新增: ! cmp -s <(sed "1s@.*@#!$runtime/bin/python3 -I@" claude-account.py) "$target/bin/cage-claude-account"; then intact=no; fi
83新增: for name in python3 claude git; do
84新增: if [[ ! -L $target/bin/$name || $(readlink "$target/bin/$name") != "$runtime/bin/$name" ]]; then intact=no; fi
85新增: done
86新增: if [[ $intact == no ]]; then
87新增: # Keep the damaged directory available for rollback while publishing a
88新增: # fresh helper set for the same application revision.
89新增: target="$target-repair-${work##*.}"
90新增: fi
91新增:fi
92新增:if [[ ! -d $target ]]; then
93新增: mkdir -p helpers/bin
94新增: for name in python3 claude git; do ln -s "$runtime/bin/$name" "helpers/bin/$name"; done
95新增: install -m 644 macos-cli.py cli_channel.py cli_channel.resume.md helpers/
96新增: install -m 644 claude_account_resume.md helpers/cli_channel.account-resume.md
97新增: sed "1s@.*@#!$runtime/bin/python3 -I@" claude-account.py > helpers/bin/cage-claude-account
98新增: chmod 755 helpers/bin/cage-claude-account
99新增: ln -s cage-claude-account helpers/bin/cage-open
100新增: publish_dir helpers "$target"
101新增:fi
102新增:current="$base/cage-cli"
103新增:if [[ -e $current || -L $current ]]; then
104新增: [[ -L $current && $(readlink "$current") == "$base"/cage-cli-2.* ]]
105新增:fi
106新增:ln -s "$target" "$work/current"
107新增:mv -fh "$work/current" "$current"
108新增:account=/usr/local/bin/cage-claude-account
109新增:if [[ ! -e $account && ! -L $account ]]; then ln -s "$current/bin/cage-claude-account" "$account"; fi
110新增:[[ -L $account && $(readlink "$account") == "$current/bin/cage-claude-account" ]]
111新增:for name in claude git; do
112新增: if [[ ! -e /usr/local/bin/$name && ! -L /usr/local/bin/$name ]]; then ln -s "$current/bin/$name" "/usr/local/bin/$name"; fi
113新增:done
114新增:"$current/bin/claude" --version
新增scripts/guest-os/install-macos-node.sh+23 −0看文件
@@ -0,0 +1,23 @@
1新增:#!/bin/bash
2新增:# The runtime used by ordinary terminal and debugger sessions in the macOS guest.
3新增:set -euo pipefail
4新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin
5新增:[[ $# == 1 && $EUID == 0 && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]]
6新增:[[ -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 ]]
7新增:base=/usr/local/libexec
8新增:target="$base/cage-node-v24.22.2"
9新增:mkdir -p "$base" /usr/local/bin
10新增:stage=$(mktemp -d "$base/.cage-node.XXXXXXXX")
11新增:trap 'rm -rf "$stage"' EXIT
12新增:if [[ ! -e $target ]]; then
13新增: cp "$1" "$stage/node.tgz"
14新增: [[ $(shasum -a 256 "$stage/node.tgz" | cut -d' ' -f1) == aa9549349e47dffaa42dcf95d6e06ade8c4bdafc980979883b88767670df385a ]]
15新增: tar -xzf "$stage/node.tgz" -C "$stage" --no-same-owner
16新增: [[ $("$stage/node-v24.22.2-darwin-arm64/bin/node" -p 'process.platform + "/" + process.arch + "/" + process.version') == darwin/arm64/v24.22.2 ]]
17新增: mv "$stage/node-v24.22.2-darwin-arm64" "$target"
18新增:fi
19新增:for tool in node npm npx; do
20新增: if [[ ! -e /usr/local/bin/$tool && ! -L /usr/local/bin/$tool ]]; then
21新增: ln -s "$target/bin/$tool" "/usr/local/bin/$tool"
22新增: fi
23新增:done
新增scripts/guest-os/install-macos-project-tools.sh+94 −0看文件
@@ -0,0 +1,94 @@
1新增:#!/bin/bash
2新增:# Run as root inside a Cage macOS guest. The supplied directory contains the
3新增:# verified macFUSE 5.5.0 installer and the three project tools from this build.
4新增:set -euo pipefail
5新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin
6新增:fail() { printf '%s\n' "$*" >&2; exit 1; }
7新增:[[ $# == 1 && $1 == /* ]] || fail 'Usage: install-macos-project-tools.sh /path/to/root-owned-guest-project-kit'
8新增:[[ $(uname -sm) == 'Darwin arm64' && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ && $(id -u) == 0 ]] ||
9新增: fail 'Run this installer in the target arm64 Cage guest as administrator.'
10新增:marker=/var/db/cage-guest-os
11新增:[[ -f $marker && ! -L $marker && $(stat -f %u "$marker") == 0 && $(cat "$marker") == macos ]] ||
12新增: fail 'Missing the root-owned Cage guest marker.'
13新增:mode=$(stat -f %OLp "$marker")
14新增:(( (8#$mode & 022) == 0 )) || fail 'The guest marker is writable by another account.'
15新增:
16新增:# Copy before verification, so a source directory cannot change after checks.
17新增:# Root-owned inputs are required because unsigned development builds can use a
18新增:# local ad-hoc signature. No downloaded code is executed to verify identity.
19新增:kit=$(cd -P "$1" && pwd)
20新增:[[ $(stat -f %u "$kit") == 0 && -z $(find "$kit" \( -type l -o ! -user root -o -perm -0020 -o -perm -0002 \) -print -quit) ]] ||
21新增: fail 'Use a root-owned kit with no symlinks or group/other-writable members.'
22新增:parent=$(dirname "$kit")
23新增:while [[ $parent != / ]]; do
24新增: mode=$(stat -f %Op "$parent")
25新增: [[ $(stat -f %u "$parent") == 0 ]] && (( (8#$mode & 022) == 0 || (8#$mode & 01000) != 0 )) ||
26新增: fail 'The kit can be replaced through an untrusted parent directory.'
27新增: parent=$(dirname "$parent")
28新增:done
29新增:for file in macfuse.pkg cage-sshfs cage-macos-terminal; do [[ -f $kit/$file ]] || fail "Missing $file"; done
30新增:[[ -d $kit/CageProjectAccess.app ]] || fail 'Missing CageProjectAccess.app.'
31新增:umask 077
32新增:work=$(mktemp -d /private/var/tmp/cage-project-kit.XXXXXXXX)
33新增:trap 'rm -rf "$work"' EXIT
34新增:for file in macfuse.pkg cage-sshfs cage-macos-terminal; do cp "$kit/$file" "$work/$file"; done
35新增:ditto "$kit/CageProjectAccess.app" "$work/CageProjectAccess.app"
36新增:pkg="$work/macfuse.pkg"
37新增:[[ $(shasum -a 256 "$pkg" | cut -d' ' -f1) == 5acf9e30bab227707de8d15eb28472a0cc9ed45709846b3e067d283294dc7f9e ]] ||
38新增: fail 'The macFUSE installer SHA-256 does not match the pinned release.'
39新增:pkgutil --check-signature "$pkg" | grep -F 'Developer ID Installer: Benjamin Fleischer (3T5GSNBU6W)' >/dev/null ||
40新增: fail 'Unexpected macFUSE installer signer.'
41新增:for file in cage-sshfs cage-macos-terminal; do
42新增: codesign --verify --strict --architecture arm64 "$work/$file"
43新增:done
44新增:access_id=dev.cage.guest.project-access
45新增:codesign --verify --strict -R "=identifier \"$access_id\"" "$work/CageProjectAccess.app"
46新增:macfuse_requirement='anchor apple generic and identifier "io.macfuse.app" and certificate leaf[subject.OU] = "3T5GSNBU6W"'
47新增:driver=/Library/Filesystems/macfuse.fs
48新增:vendor_app="$driver/Contents/Resources/macfuse.app"
49新增:installed=''
50新增:if [[ -e $driver ]]; then
51新增: codesign --verify --strict -R "=$macfuse_requirement" "$vendor_app"
52新增: installed=$(plutil -extract CFBundleShortVersionString raw -o - "$driver/Contents/Info.plist")
53新增:fi
54新增:up_to_date=no
55新增:if [[ -n $installed ]]; then
56新增: [[ $installed =~ ^([0-9]+)\.([0-9]+)(\.[0-9]+)?$ ]] || fail 'Unrecognized installed macFUSE version.'
57新增: if (( 10#${BASH_REMATCH[1]} > 5 || (10#${BASH_REMATCH[1]} == 5 && 10#${BASH_REMATCH[2]} >= 5) )); then up_to_date=yes; fi
58新增:fi
59新增:if [[ $up_to_date == no ]]; then
60新增: installer -pkg "$pkg" -target /
61新增:fi
62新增:codesign --verify --strict -R "=$macfuse_requirement" "$vendor_app"
63新增:
64新增:install_app() {
65新增: local source=$1 target=$2 requirement=$3 stage
66新增: if [[ -e $target || -L $target ]]; then
67新增: [[ ! -L $target && -d $target ]] || fail "Unexpected application at $target"
68新增: codesign --verify --strict -R "=$requirement" "$target"
69新增: if diff -qr "$source" "$target" >/dev/null; then return; fi
70新增: fail "A different verified build is already installed at $target. Stop and update that application before retrying."
71新增: fi
72新增: stage=$(mktemp -d /Applications/.cage-project-install.XXXXXXXX)
73新增: if ditto "$source" "$stage/app" && chmod -R a+rX,go-w "$stage/app" &&
74新增: codesign --verify --strict -R "=$requirement" "$stage/app" && mv "$stage/app" "$target"; then
75新增: rmdir "$stage"
76新增: else
77新增: rm -rf "$stage"
78新增: fail "Could not install $target"
79新增: fi
80新增:}
81新增:install_app "$vendor_app" /Applications/macFUSE.app "$macfuse_requirement"
82新增:install_app "$work/CageProjectAccess.app" /Applications/CageProjectAccess.app "identifier \"$access_id\""
83新增:libexec=/usr/local/libexec
84新增:mkdir -p "$libexec"
85新增:for file in cage-sshfs cage-macos-terminal; do
86新增: [[ ! -L $libexec/$file ]] || fail "Refusing to replace a linked executable: $file"
87新增: if [[ -f $libexec/$file ]] && cmp -s "$work/$file" "$libexec/$file"; then continue; fi
88新增: stage=$(mktemp "$libexec/.cage-tool.XXXXXXXX")
89新增: if install -o root -g wheel -m 755 "$work/$file" "$stage" && mv -f "$stage" "$libexec/$file"; then :; else
90新增: rm -f "$stage"
91新增: fail "Could not install $file"
92新增: fi
93新增:done
94新增:printf '%s\n' 'Project tools are ready. In the guest user session, open macFUSE.app once, then enable both macFUSE and macFUSE (local) under By Category > File System Extensions.'
新增scripts/guest-os/install-windows-host-manager.ps1+99 −0看文件
@@ -0,0 +1,99 @@
1新增:#requires -Version 5.1
2新增:#requires -RunAsAdministrator
3新增:[CmdletBinding(SupportsShouldProcess)]
4新增:param(
5新增: [Parameter(Mandatory)][guid]$VMId,
6新增: [Parameter(Mandatory)][string]$HostSID,
7新增: [Parameter(Mandatory)][string]$PayloadExecutable,
8新增: [Parameter(Mandatory)][ValidatePattern('^[0-9a-fA-F]{64}$')][string]$PayloadSHA256
9新增:)
10新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue'
11新增:if($VMId -eq [guid]::Empty -or $HostSID -notmatch '^S-1-(5-21|12-1)-(\d+-){3}\d+$'){throw 'Select the exact VM and authorized host user.'}
12新增:# HostSID is the ordinary Cage user's identity carried across its UAC boundary.
13新增:# The administrator may be another account; its SID is never substituted here.
14新增:function Assert-NoLink([string]$Path){
15新增: $item=Get-Item -LiteralPath $Path -Force
16新增: while($item){if($item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Manager files cannot traverse links.'};if($item -is [IO.FileInfo]){$item=$item.Directory}else{$item=$item.Parent}}
17新增:}
18新增:function Protect-ManagerPath([string]$Path,[switch]$Shared){
19新增: $item=Get-Item -LiteralPath $Path -Force
20新增: if($item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Manager paths cannot be links.'}
21新增: if($item -is [IO.DirectoryInfo]){$acl=[Security.AccessControl.DirectorySecurity]::new()}else{$acl=[Security.AccessControl.FileSecurity]::new()}
22新增: $acl.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'));$acl.SetAccessRuleProtection($true,$false)
23新增: $reader=if($Shared){'S-1-5-32-545'}else{$HostSID}
24新增: foreach($id in @('S-1-5-18','S-1-5-32-544',$reader)){
25新增: $rights=if($id -ceq $reader){'ReadAndExecute'}else{'FullControl'}
26新增: if($item -is [IO.DirectoryInfo]){$rule=[Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($id),$rights,'ContainerInherit,ObjectInherit','None','Allow')}else{$rule=[Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($id),$rights,'Allow')}
27新增: $acl.AddAccessRule($rule)
28新增: }
29新增: Set-Acl -LiteralPath $Path -AclObject $acl
30新增:}
31新增:$payload=Get-Item -LiteralPath $PayloadExecutable
32新增:if($payload -isnot [IO.FileInfo]){throw 'Select the built manager executable.'};Assert-NoLink $payload.FullName
33新增:if((Get-FileHash $payload.FullName -Algorithm SHA256).Hash.ToLowerInvariant() -cne $PayloadSHA256.ToLowerInvariant()){throw 'Manager payload checksum does not match.'}
34新增:$programRoot=Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'Cage Host Manager'
35新增:$program=Join-Path $programRoot $VMId.ToString('D');$exe=Join-Path $program 'Cage.HyperVManager.exe'
36新增:$cageDataRoot=Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'Cage'
37新增:$dataRoot=Join-Path $cageDataRoot 'HyperVManager'
38新增:$data=Join-Path $dataRoot $VMId.ToString('D');$bindingPath=Join-Path $data 'binding.json'
39新增:$name='CageHV-'+$VMId.ToString('D');$binary='"'+$exe+'" service --binding "'+$bindingPath+'"'
40新增:if(!$PSCmdlet.ShouldProcess($VMId,'Install the protected local fixed-VM manager; keep VM, disks, accounts and host networking')){return}
41新增:foreach($path in @($programRoot,$program,$cageDataRoot,$dataRoot,$data)){
42新增: if(!(Test-Path -LiteralPath $path)){New-Item -ItemType Directory -Path $path|Out-Null};Assert-NoLink $path
43新增: Protect-ManagerPath $path -Shared:($path -in @($programRoot,$cageDataRoot,$dataRoot))
44新增:}
45新增:$prepare=Join-Path $program ('manager-prepare-'+[guid]::NewGuid().ToString('N')+'.exe')
46新增:try{
47新增: # Hash and execute the same protected copy. The caller's original payload
48新增: # may change while setup runs; it never becomes an execution authority.
49新增: Copy-Item -LiteralPath $payload.FullName -Destination $prepare
50新增: Protect-ManagerPath $prepare
51新增: if((Get-FileHash $prepare -Algorithm SHA256).Hash.ToLowerInvariant() -cne $PayloadSHA256.ToLowerInvariant()){throw 'Protected manager preparation checksum does not match.'}
52新增: $payload=Get-Item -LiteralPath $prepare
53新增:$service=Get-Service -Name $name -ErrorAction SilentlyContinue
54新增:if($service){
55新增: $existing=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'")
56新增: if($existing.PathName -cne $binary -or $existing.StartName -notin @('LocalSystem','NT AUTHORITY\SYSTEM')){throw 'An unrelated service already uses this name.'}
57新增:}
58新增:# Verify the retained VM before stopping the existing helper. Prepare uses the
59新增:# checked protected copy in the installing administrator's token.
60新增:$raw=& $payload.FullName prepare --vm-id $VMId.ToString('D') --host-sid $HostSID
61新增:if($LASTEXITCODE -ne 0){throw 'The exact VM/disk binding could not be verified.'}
62新增:$binding=$raw|ConvertFrom-Json
63新增:if($binding.version -ne 1 -or [guid]$binding.vm_id -ne $VMId -or $binding.host_sid -cne $HostSID){throw 'The prepared manager binding does not match.'}
64新增:if(Test-Path -LiteralPath $bindingPath){
65新增: Assert-NoLink $bindingPath;$old=Get-Content -LiteralPath $bindingPath -Raw|ConvertFrom-Json
66新增: foreach($key in @('version','vm_id','host_sid','disk_path','disk_volume','disk_file_id')){if([string]$old.$key -cne [string]$binding.$key){throw 'The existing protected VM/disk binding changed; preserved it.'}}
67新增:}
68新增:$rollback=$null;$cleanupRollback=$false;$wasRunning=$service -and $service.Status -eq 'Running'
69新增:try{
70新增: if($service){
71新增: Assert-NoLink $exe
72新增: $rollback=Join-Path $program ('manager-rollback-'+[guid]::NewGuid().ToString('N')+'.exe')
73新增: Copy-Item -LiteralPath $exe -Destination $rollback;Protect-ManagerPath $rollback
74新增: if($service.Status -ne 'Stopped'){Stop-Service -Name $name;$service.WaitForStatus('Stopped',[TimeSpan]::FromSeconds(30))}
75新增: }
76新增: Copy-Item -LiteralPath $payload.FullName -Destination $exe -Force;Protect-ManagerPath $exe
77新增: if((Get-FileHash $exe -Algorithm SHA256).Hash.ToLowerInvariant() -cne $PayloadSHA256.ToLowerInvariant()){throw 'The copied manager checksum does not match.'}
78新增: if(!(Test-Path -LiteralPath $bindingPath)){[IO.File]::WriteAllText($bindingPath,($binding|ConvertTo-Json -Depth 4),[Text.UTF8Encoding]::new($false))}
79新增: Protect-ManagerPath $bindingPath
80新增: if(!$service){New-Service -Name $name -BinaryPathName $binary -StartupType Automatic -DisplayName ('Cage fixed VM manager '+$VMId.ToString('D')) -Description ('Cage protected local VM manager '+$VMId.ToString('D'))|Out-Null}
81新增: $sddl='O:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;CCLCRP;;;'+$HostSID+')'
82新增: & ($env:windir+'\System32\sc.exe') sdset $name $sddl|Out-Null
83新增: if($LASTEXITCODE -ne 0){throw 'The manager service permission could not be protected.'}
84新增: & ($env:windir+'\System32\sc.exe') failure $name reset= 86400 actions= restart/5000/restart/15000/restart/60000|Out-Null
85新增: if($LASTEXITCODE -ne 0){throw 'The manager recovery policy could not be configured.'}
86新增: Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus('Running',[TimeSpan]::FromSeconds(30))
87新增: $cleanupRollback=$true
88新增:}catch{
89新增: if($rollback){
90新增: Stop-Service -Name $name -ErrorAction SilentlyContinue
91新增: (Get-Service -Name $name).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(30))
92新增: Copy-Item -LiteralPath $rollback -Destination $exe -Force;Protect-ManagerPath $exe
93新增: if($wasRunning){Start-Service -Name $name}
94新增: $cleanupRollback=$true
95新增: }
96新增: throw
97新增:}finally{if($rollback -and $cleanupRollback -and (Test-Path -LiteralPath $rollback)){Remove-Item -LiteralPath $rollback}}
98新增:[pscustomobject]@{Installed=$true;VMId=$VMId.ToString('D');HostSID=$HostSID;LocalPipeOnly=$true;VMDataPreserved=$true;HostGroupsUnchanged=$true;ServiceRunning=$true}
99新增:}finally{if(Test-Path -LiteralPath $prepare){Remove-Item -LiteralPath $prepare}}
新增scripts/guest-os/install-windows-workbench-components.ps1+127 −0看文件
@@ -0,0 +1,127 @@
1新增:# Used by complete-windows-guest.ps1 through an authenticated VM-only
2新增:# PowerShell Direct session, after the ordinary GUI SID has been pinned.
3新增:param([guid]$VMId,[string]$GUIUserSID,[string]$Bridge,[string]$Stage,[string]$PackagesJSON,[string]$CLIJSON,[string]$ExtrasSHA,[ValidateSet('Prepare','UserTools')][string]$Phase,[switch]$RuntimeInstalled)
4新增:$Packages=$PackagesJSON | ConvertFrom-Json
5新增:$CLI=$CLIJSON | ConvertFrom-Json
6新增:$ErrorActionPreference='Stop'
7新增:if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $VMId -or
8新增: $Bridge -ne (Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$VMId)) -or $Stage -ne (Join-Path $Bridge 'setup-packages')) {
9新增: throw 'Incorrect guest installation target.'
10新增:}
11新增:foreach ($file in @($Packages.desktop,$Packages.winfsp,$Packages.sshfs,$CLI.uv,$CLI.python,$CLI.claude,$CLI.git)) {
12新增: if ((Get-FileHash -LiteralPath (Join-Path $Stage $file.filename)).Hash -ne $file.sha256) { throw ('Guest package digest mismatch: '+$file.filename) }
13新增:}
14新增:$extras=Join-Path $Stage 'extras.zip'
15新增:if ((Get-FileHash -LiteralPath $extras).Hash -ne $ExtrasSHA) { throw 'Guest components digest mismatch.' }
16新增:$taskName="Cage-GUI-Bridge-$VMId-$GUIUserSID"
17新增:$bridgeTask=Get-ScheduledTask -TaskName $taskName
18新增:if ($bridgeTask.Description -cne "Cage protected GUI bridge $VMId $GUIUserSID" -or $bridgeTask.Principal.RunLevel -ne 'Limited' -or
19新增: $bridgeTask.Actions[0].Execute -ne (Join-Path $Bridge 'Cage.GuestClipboard.exe')) { throw 'The registered bridge does not match this guest.' }
20新增:
21新增:# All paths below are inside the administrator-owned bridge. Extraction and
22新增:# package operations never take a filename supplied by an ordinary guest user.
23新增:function Install-GuestComponents {
24新增: # Windows PowerShell 5.1 ZIP APIs and Copy-Item truncate long editor
25新增: # paths on a fresh Windows install. The OS-supplied archive tool supports
26新增: # long paths. Only the verified, Cage-assembled application archive is
27新增: # extracted into the administrator-owned guest bridge.
28新增: if (!$RuntimeInstalled) {
29新增: & (Join-Path $env:SystemRoot 'System32/tar.exe') -xf $extras -C $Bridge
30新增: if ($LASTEXITCODE -ne 0) { throw 'Could not unpack the verified guest application components.' }
31新增: }
32新增:
33新增: foreach ($package in @($Packages.winfsp,$Packages.sshfs)) {
34新增: $file=Join-Path $Stage $package.filename
35新增: $proc=Start-Process -FilePath (Join-Path $env:SystemRoot 'System32/msiexec.exe') -ArgumentList ('/i "'+$file+'" /qn /norestart') -Wait -PassThru
36新增: if ($proc.ExitCode -notin @(0,3010)) { throw ('Windows file-system driver install failed: '+$package.filename+' ('+$proc.ExitCode+')') }
37新增: }
38新增:
39新增: $msix=Join-Path $Stage $Packages.desktop.filename
40新增: $signature=Get-AuthenticodeSignature -LiteralPath $msix
41新增: if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'Anthropic,? PBC') { throw 'The official Claude Desktop package signature is invalid.' }
42新增: $provisioned=@(Get-AppxProvisionedPackage -Online | Where-Object DisplayName -ceq 'Claude')
43新增: if ($provisioned.Count -gt 1 -or ($provisioned.Count -eq 1 -and $provisioned[0].PackageName -notmatch '^Claude_[0-9.]+_x64__pzs8sxrjxfjjc$')) { throw 'An unexpected existing Claude registration was preserved.' }
44新增: if (!$provisioned.Count) {
45新增: $null=Add-AppxProvisionedPackage -Online -PackagePath $msix -SkipLicense -Regions 'all'
46新增: }
47新增: $name='Cage-Workbench-Boot-'+$VMId.ToString('D')
48新增: $image='"'+(Join-Path $Bridge 'cage-guest-boot.exe')+'" '+$VMId.ToString('D')
49新增: $service=Get-CimInstance Win32_Service -Filter "Name='$name'"
50新增: if (!$service) {
51新增: $service=New-Service -Name $name -BinaryPathName $image -StartupType Automatic -DisplayName 'Cage dedicated workbench boot sign-in'
52新增: } elseif ($service.PathName -cne $image -or $service.StartName -ne 'LocalSystem') { throw 'An unrelated boot service was preserved.' }
53新增: Start-Service -Name $name
54新增:}
55新增:if ($Phase -eq 'Prepare') { Install-GuestComponents; return }
56新增:
57新增:$receipt=Join-Path $Stage 'cli-receipt.in'
58新增:if (!(Test-Path -LiteralPath $receipt)) { $f=[IO.File]::Open($receipt,'CreateNew','Write','None'); $f.Dispose() }
59新增:$admin=[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
60新增:function Set-ReceiptAccess([string]$Path,[string]$UserRights) {
61新增: $acl=[Security.AccessControl.FileSecurity]::new()
62新增: $acl.SetAccessRuleProtection($true,$false)
63新增: $acl.SetOwner($admin)
64新增: foreach ($sid in @('S-1-5-18','S-1-5-32-544')) {
65新增: $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'FullControl','Allow'))
66新增: }
67新增: $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($GUIUserSID),$UserRights,'Allow'))
68新增: Set-Acl -LiteralPath $Path -AclObject $acl
69新增:}
70新增:Set-ReceiptAccess $receipt 'Read,Write'
71新增:$cliTask="Cage-Workbench-CLI-Setup-$VMId"
72新增:$description="Cage guest workbench tool install $VMId $GUIUserSID"
73新增:if ($old=Get-ScheduledTask -TaskName $cliTask -ErrorAction SilentlyContinue) {
74新增: if ($old.Description -cne $description -or $old.State -eq 'Running') { throw 'A workbench installation is already active.' }
75新增: Unregister-ScheduledTask -TaskName $cliTask -Confirm:$false
76新增:}
77新增:$action=New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32/WindowsPowerShell/v1.0/powershell.exe') -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "'+(Join-Path $Bridge 'install-windows-workbench-user-tools.ps1')+'" -BundleDirectory "'+$Stage+'" -BridgeDirectory "'+$Bridge+'"')
78新增:$principal=New-ScheduledTaskPrincipal -UserId $GUIUserSID -LogonType Interactive -RunLevel Limited
79新增:$settings=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 15)
80新增:$null=Register-ScheduledTask -TaskName $cliTask -Action $action -Principal $principal -Settings $settings -Description $description
81新增:try {
82新增: [IO.File]::WriteAllText($receipt,'')
83新增: Start-ScheduledTask -TaskName $cliTask
84新增: $deadline=[DateTime]::UtcNow.AddMinutes(15)
85新增: do {
86新增: Start-Sleep -Seconds 1
87新增: $task=Get-ScheduledTask -TaskName $cliTask
88新增: $info=Get-ScheduledTaskInfo -TaskName $cliTask
89新增: $ran=$info.LastRunTime.Year -gt 2000 -and $info.LastTaskResult -notin @(267008,267009,267011)
90新增: } while ((!$ran -or $task.State -eq 'Running') -and [DateTime]::UtcNow -lt $deadline)
91新增: if (!$ran -or $task.State -eq 'Running' -or $info.LastTaskResult -ne 0) { throw 'Claude Code tools did not finish for the signed-in standard guest user.' }
92新增: # Copy only the bounded allowlisted JSON fields from the file opened
93新增: # without write sharing. Never execute a user-supplied receipt path here.
94新增: $handle=[IO.File]::Open($receipt,'Open','Read','Read')
95新增: try {
96新增: if ($handle.Length -lt 2 -or $handle.Length -gt 16384) { throw 'Invalid Claude Code tools receipt.' }
97新增: $reader=[IO.StreamReader]::new($handle)
98新增: $value=$reader.ReadToEnd() | ConvertFrom-Json
99新增: } finally { $handle.Dispose() }
100新增: if ($value.version -ne 1 -or $value.claude_sha256 -ne $CLI.claude.sha256) { throw 'Invalid Claude Code version or hash.' }
101新增: $result=[ordered]@{version=1}
102新增: foreach ($name in @('python','claude','git_bash')) {
103新增: $hash=$name+'_sha256'
104新增: if (![IO.Path]::IsPathRooted($value.$name) -or $value.$hash -notmatch '^[a-fA-F0-9]{64}$') { throw 'Invalid Claude tool record.' }
105新增: $result[$name]=$value.$name
106新增: $result[$hash]=$value.$hash.ToLowerInvariant()
107新增: }
108新增: $target=Join-Path $Bridge 'cli-tools.json'
109新增: [IO.File]::WriteAllText($target,($result | ConvertTo-Json -Compress),[Text.UTF8Encoding]::new($false))
110新增: Set-ReceiptAccess $target 'Read'
111新增:} finally {
112新增: if ((Get-ScheduledTask -TaskName $cliTask).State -eq 'Running') { Stop-ScheduledTask -TaskName $cliTask }
113新增: Unregister-ScheduledTask -TaskName $cliTask -Confirm:$false
114新增:}
115新增:if ($bridgeTask.State -eq 'Running') {
116新增: Stop-ScheduledTask -TaskName $taskName
117新增: $deadline=[DateTime]::UtcNow.AddSeconds(15)
118新增: while ((Get-ScheduledTask -TaskName $taskName).State -eq 'Running' -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 250 }
119新增:}
120新增:Start-ScheduledTask -TaskName $taskName
121新增:
122新增:# Packages have been verified and installed. The instance-scoped host cache
123新增:# permits repairs; the guest does not need a second copy of the installers.
124新增:foreach ($package in @($Packages.desktop,$Packages.winfsp,$Packages.sshfs,$CLI.uv,$CLI.python,$CLI.claude,$CLI.git)) {
125新增: [IO.File]::Delete((Join-Path $Stage $package.filename))
126新增:}
127新增:[IO.File]::Delete($extras)
新增scripts/guest-os/install-windows-workbench-user-tools.ps1+10 −0看文件
@@ -0,0 +1,10 @@
1新增:# Runs once as the new, non-elevated Cage workbench user. The administrator
2新增:# already provisioned the verified MSIX machine-wide; finishing registration
3新增:# here makes Windows consider it usable in this particular user session.
4新增:[CmdletBinding()]
5新增:param([Parameter(Mandatory)][string]$BundleDirectory,[Parameter(Mandatory)][string]$BridgeDirectory)
6新增:$ErrorActionPreference='Stop'
7新增:$user=[Security.Principal.WindowsIdentity]::GetCurrent()
8新增:if ([Security.Principal.WindowsPrincipal]::new($user).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run as the dedicated standard guest user.' }
9新增:Add-AppxPackage -RegisterByFamilyName -MainPackage 'Claude_pzs8sxrjxfjjc' -ErrorAction Stop
10新增:& (Join-Path $PSScriptRoot 'install-cli.ps1') -BundleDirectory $BundleDirectory -BridgeDirectory $BridgeDirectory -WorkbenchSetup
新增scripts/guest-os/macos-audio.swift+241 −0看文件
@@ -0,0 +1,241 @@
1新增:// System-output audio for the already authorized per-user GUI window agent.
2新增:import AppKit
3新增:import AVFoundation
4新增:import ScreenCaptureKit
5新增:
6新增:private let audioSampleRate = 48000
7新增:private let audioChannels = 2
8新增:private let audioFrameBytes = 4
9新增:
10新增:private func audioGUIAvailable() -> Bool {
11新增: var info = stat()
12新增: return stat("/dev/console", &info) == 0 && info.st_uid == getuid() && info.st_uid >= 500 &&
13新增: (CGSessionCopyCurrentDictionary() as? [String: Any])?["CGSSessionScreenIsLocked"] as? Bool != true
14新增:}
15新增:
16新增:private func writeAudioBytes(_ fd: Int32, _ data: Data) throws {
17新增: try data.withUnsafeBytes { bytes in
18新增: var offset = 0
19新增: while offset < bytes.count {
20新增: let written = Darwin.write(fd, bytes.baseAddress!.advanced(by: offset), bytes.count - offset)
21新增: if written < 0 && errno == EINTR { continue }
22新增: guard written > 0 else { throw Failure(7, "audio_connection_closed") }
23新增: offset += written
24新增: }
25新增: }
26新增:}
27新增:
28新增:private final class AudioPCMConverter {
29新增: private let outputFormat = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: Double(audioSampleRate), channels: AVAudioChannelCount(audioChannels), interleaved: true)!
30新增: private var converter: AVAudioConverter?
31新增: private var inputFormat: AVAudioFormat?
32新增:
33新增: func convert(_ input: AVAudioPCMBuffer) throws -> Data {
34新增: guard input.format.sampleRate == Double(audioSampleRate), input.format.channelCount == audioChannels,
35新增: input.frameLength > 0, input.frameLength <= 16384 else { throw Failure(7, "audio_format_invalid") }
36新增: if inputFormat != input.format {
37新增: converter = AVAudioConverter(from: input.format, to: outputFormat)
38新增: inputFormat = input.format
39新增: }
40新增: guard let converter, let output = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: input.frameLength) else {
41新增: throw Failure(7, "audio_format_invalid")
42新增: }
43新增: try converter.convert(to: output, from: input)
44新增: let buffer = output.audioBufferList.pointee.mBuffers
45新增: let count = Int(output.frameLength) * audioFrameBytes
46新增: guard count <= Int(buffer.mDataByteSize), let data = buffer.mData else { throw Failure(7, "audio_format_invalid") }
47新增: return Data(bytes: data, count: count)
48新增: }
49新增:
50新增: func convert(_ sample: CMSampleBuffer) throws -> Data {
51新增: guard sample.isValid, let description = sample.formatDescription else { throw Failure(7, "audio_format_invalid") }
52新增: guard let basic = CMAudioFormatDescriptionGetStreamBasicDescription(description),
53新增: basic.pointee.mFormatID == kAudioFormatLinearPCM, basic.pointee.mBytesPerFrame > 0,
54新增: basic.pointee.mSampleRate == Double(audioSampleRate), basic.pointee.mChannelsPerFrame == audioChannels else {
55新增: throw Failure(7, "audio_format_invalid")
56新增: }
57新增: let format = AVAudioFormat(cmAudioFormatDescription: description)
58新增: var required = 0
59新增: var block: CMBlockBuffer?
60新增: let flags = UInt32(kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment)
61新增: _ = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sample, bufferListSizeNeededOut: &required,
62新增: bufferListOut: nil, bufferListSize: 0, blockBufferAllocator: kCFAllocatorDefault,
63新增: blockBufferMemoryAllocator: kCFAllocatorDefault, flags: flags, blockBufferOut: &block)
64新增: guard required > 0, required <= 4096 else { throw Failure(7, "audio_format_invalid") }
65新增: let memory = UnsafeMutableRawPointer.allocate(byteCount: required, alignment: 16)
66新增: defer { memory.deallocate() }
67新增: let list = memory.bindMemory(to: AudioBufferList.self, capacity: 1)
68新增: let status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sample, bufferListSizeNeededOut: nil,
69新增: bufferListOut: list, bufferListSize: required, blockBufferAllocator: kCFAllocatorDefault,
70新增: blockBufferMemoryAllocator: kCFAllocatorDefault, flags: flags, blockBufferOut: &block)
71新增: guard status == noErr, let input = AVAudioPCMBuffer(pcmFormat: format, bufferListNoCopy: list, deallocator: nil) else {
72新增: throw Failure(7, "audio_format_invalid")
73新增: }
74新增: return try withExtendedLifetime(block) { try convert(input) }
75新增: }
76新增:}
77新增:
78新增:private final class AudioSamples: NSObject, SCStreamOutput, SCStreamDelegate, @unchecked Sendable {
79新增: private let lock = NSLock()
80新增: private let converter = AudioPCMConverter() // Owned by the serial sample queue.
81新增: private var pending = Data()
82新增: private var failed = false
83新增: private let limit = audioSampleRate * audioChannels * 2 / 5 // At most 200 ms.
84新增:
85新增: func stream(_ stream: SCStream, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, of type: SCStreamOutputType) {
86新增: guard type == .audio, sampleBuffer.isValid, CMSampleBufferDataIsReady(sampleBuffer), CMSampleBufferGetNumSamples(sampleBuffer) > 0 else { return }
87新增: do {
88新增: append(try converter.convert(sampleBuffer))
89新增: } catch {
90新增: stop()
91新增: }
92新增: }
93新增:
94新增: func stream(_ stream: SCStream, didStopWithError error: Error) {
95新增: stop()
96新增: }
97新增:
98新增: func append(_ pcm: Data) {
99新增: lock.lock(); defer { lock.unlock() }
100新增: if !failed {
101新增: pending.append(pcm)
102新增: if pending.count > limit { pending.removeFirst(pending.count - limit) }
103新增: }
104新增: }
105新增:
106新增: func stop() {
107新增: lock.lock(); failed = true; pending.removeAll(); lock.unlock()
108新增: }
109新增:
110新增: func next() throws -> Data {
111新增: lock.lock(); defer { lock.unlock() }
112新增: guard !failed else { throw Failure(7, "audio_capture_failed") }
113新增: let count = min(pending.count, 3840) // 20 ms, whole interleaved frames.
114新增: let result = Data(pending.prefix(count))
115新增: pending.removeFirst(count)
116新增: return result
117新增: }
118新增:}
119新增:
120新增:enum MacAudioCapture {
121新增: static func status() -> [String: Any] {
122新增: let gui = audioGUIAvailable()
123新增: let permission = CGPreflightScreenCaptureAccess()
124新增: return ["supported": true, "available": gui && permission, "format": "s16le",
125新增: "sample_rate": audioSampleRate, "channels": audioChannels,
126新增: "reason": !gui ? "requires_gui_login" : (!permission ? "screen_recording_permission" : "")]
127新增: }
128新增:
129新增: static func respond(_ fd: Int32) async {
130新增: var stream: SCStream?
131新增: var ready = false
132新增: do {
133新增: try requireGuest()
134新增: let epoch = try await MacGUISession.shared.validate()
135新增: var timeout = timeval(tv_sec: 2, tv_usec: 0)
136新增: setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout)))
137新增: guard audioGUIAvailable() else { throw Failure(4, "requires_gui_login") }
138新增: // The existing setup-screen action opens the guest's system consent
139新增: // UI. Audio status and playback never approve or request it silently.
140新增: guard CGPreflightScreenCaptureAccess() else { throw Failure(6, "screen_recording_permission") }
141新增: let content = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true)
142新增: guard let display = content.displays.first else { throw Failure(7, "audio_display_unavailable") }
143新增: let filter = SCContentFilter(display: display, excludingApplications: [], exceptingWindows: [])
144新增: let configuration = SCStreamConfiguration()
145新增: configuration.capturesAudio = true
146新增: configuration.sampleRate = audioSampleRate
147新增: configuration.channelCount = audioChannels
148新增: configuration.width = 2
149新增: configuration.height = 2
150新增: configuration.minimumFrameInterval = CMTime(value: 1, timescale: 1)
151新增: configuration.queueDepth = 3
152新增: let samples = AudioSamples()
153新增: let capture = SCStream(filter: filter, configuration: configuration, delegate: samples)
154新增: stream = capture
155新增: try capture.addStreamOutput(samples, type: .audio, sampleHandlerQueue: DispatchQueue(label: "dev.cage.GuestAudio.samples"))
156新增: try await capture.startCapture()
157新增: guard audioGUIAvailable() else { throw Failure(4, "requires_gui_login") }
158新增: let header: [String: Any] = ["ready": true, "format": "s16le", "sample_rate": audioSampleRate, "channels": audioChannels]
159新增: try writeAudioBytes(fd, JSONSerialization.data(withJSONObject: header) + Data([10]))
160新增: ready = true
161新增: var checked = Date.distantPast
162新增: while !Task.isCancelled {
163新增: if Date().timeIntervalSince(checked) >= 0.5 {
164新增: guard audioGUIAvailable(), CGPreflightScreenCaptureAccess() else { break }
165新增: try await MacGUISession.shared.validate(epoch)
166新增: checked = Date()
167新增: }
168新增: var byte: UInt8 = 0
169新增: let incoming = recv(fd, &byte, 1, MSG_PEEK | MSG_DONTWAIT)
170新增: if incoming == 0 || incoming > 0 { break }
171新增: if errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR { break }
172新增: let packet = try samples.next()
173新增: if packet.isEmpty { try await Task.sleep(nanoseconds: 20_000_000) }
174新增: else { try writeAudioBytes(fd, packet) }
175新增: }
176新增: } catch {
177新增: GuestDiagnostic.record("window", (error as? Failure)?.message ?? "audio_capture_failed")
178新增: if !ready {
179新增: let reason = (error as? Failure)?.message ?? "audio_capture_failed"
180新增: if let data = try? JSONSerialization.data(withJSONObject: ["error": reason]) {
181新增: try? writeAudioBytes(fd, data + Data([10]))
182新增: }
183新增: }
184新增: }
185新增: if let stream { try? await stream.stopCapture() }
186新增: }
187新增:
188新增: static func selfTest() throws {
189新增: let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48000, channels: 2, interleaved: false)!
190新增: let input = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 4)!
191新增: input.frameLength = 4
192新增: let left: [Float] = [-0.75, 0, 0.5, 0.75]
193新增: let right: [Float] = [0.75, 0.5, 0, -0.75]
194新增: for index in 0..<4 {
195新增: input.floatChannelData![0][index] = left[index]
196新增: input.floatChannelData![1][index] = right[index]
197新增: }
198新增: let converter = AudioPCMConverter()
199新增: let bytes = try converter.convert(input)
200新增: guard bytes.count == 16 else { throw Failure(7, "audio_test_length") }
201新增: for index in 0..<8 {
202新增: let value = Int16(bitPattern: UInt16(bytes[index * 2]) | UInt16(bytes[index * 2 + 1]) << 8)
203新增: let expected = index % 2 == 0 ? left[index / 2] : right[index / 2]
204新增: guard abs(Double(value) / 32768 - Double(expected)) < 0.001 else { throw Failure(7, "audio_test_channels") }
205新增: }
206新增: let again = try converter.convert(input)
207新增: guard again == bytes else { throw Failure(7, "audio_test_continuity") }
208新增: var timing = CMSampleTimingInfo(duration: CMTime(value: 1, timescale: 48000), presentationTimeStamp: .zero, decodeTimeStamp: .invalid)
209新增: var sample: CMSampleBuffer?
210新增: let created = CMSampleBufferCreate(allocator: kCFAllocatorDefault, dataBuffer: nil, dataReady: false,
211新增: makeDataReadyCallback: nil, refcon: nil, formatDescription: format.formatDescription,
212新增: sampleCount: 4, sampleTimingEntryCount: 1, sampleTimingArray: &timing,
213新增: sampleSizeEntryCount: 0, sampleSizeArray: nil, sampleBufferOut: &sample)
214新增: guard created == noErr, let sample,
215新增: CMSampleBufferSetDataBufferFromAudioBufferList(sample, blockBufferAllocator: kCFAllocatorDefault,
216新增: blockBufferMemoryAllocator: kCFAllocatorDefault, flags: 0, bufferList: input.audioBufferList) == noErr else {
217新增: throw Failure(7, "audio_test_sample_creation")
218新增: }
219新增: CMSampleBufferSetDataReady(sample)
220新增: guard try converter.convert(sample) == bytes else { throw Failure(7, "audio_test_sample_conversion") }
221新增: let queued = AudioSamples()
222新增: queued.append(Data(repeating: 0, count: 10000))
223新增: queued.append(Data(repeating: 1, count: 40000))
224新增: var collected = Data()
225新增: while true {
226新增: let packet = try queued.next()
227新增: if packet.isEmpty { break }
228新增: guard packet.count <= 3840, packet.count % 4 == 0 else { throw Failure(7, "audio_test_packet_size") }
229新增: collected.append(packet)
230新增: }
231新增: guard collected == Data(repeating: 1, count: 38400) else { throw Failure(7, "audio_test_queue_limit") }
232新增: queued.stop()
233新增: do {
234新增: _ = try queued.next()
235新增: throw Failure(7, "audio_test_stop")
236新增: } catch let error as Failure {
237新增: guard error.message == "audio_capture_failed" else { throw error }
238新增: }
239新增: print("macOS audio: CoreMedia samples, 48 kHz stereo s16le, consecutive buffers, bounded queue and stopped capture passed")
240新增: }
241新增:}
新增scripts/guest-os/macos-browser-service.mjs+123 −0看文件
@@ -0,0 +1,123 @@
1新增:import net from "node:net";
2新增:import fs from "node:fs/promises";
3新增:import path from "node:path";
4新增:import { lines } from "./windows-browser.mjs";
5新增:
6新增:async function privateDirectory(directory) {
7新增: await fs.mkdir(directory, { recursive: true, mode: 0o700 });
8新增: const info = await fs.lstat(directory);
9新增: if (!info.isDirectory() || info.uid !== process.getuid() || (info.mode & 0o077))
10新增: throw new Error("Browser service directory is unavailable");
11新增: return path.join(directory, "browser.sock");
12新增:}
13新增:
14新增:async function socketInfo(address) {
15新增: const info = await fs.lstat(address);
16新增: if (!info.isSocket() || info.uid !== process.getuid() || (info.mode & 0o077))
17新增: throw new Error("Browser service socket is unavailable");
18新增: return info;
19新增:}
20新增:
21新增:function connect(address) {
22新增: return new Promise((resolve, reject) => {
23新增: const socket = net.createConnection({ path: address, allowHalfOpen: true });
24新增: socket.once("error", reject);
25新增: socket.once("connect", () => { socket.off("error", reject); resolve(socket); });
26新增: });
27新增:}
28新增:
29新增:export async function relayMacOSBrowser(directory, input = process.stdin, output = process.stdout) {
30新增: const address = await privateDirectory(directory);
31新增: await socketInfo(address);
32新增: const socket = await connect(address);
33新增: socket.on("error", () => {});
34新增: try {
35新增: const replies = lines(socket, 30 << 20)[Symbol.asyncIterator]();
36新增: for await (const line of lines(input)) {
37新增: await new Promise((resolve, reject) => socket.write(line + "\n", error => error ? reject(error) : resolve()));
38新增: const reply = await replies.next();
39新增: if (reply.done) throw new Error("Browser service connection closed");
40新增: await new Promise((resolve, reject) => output.write(reply.value + "\n", error => error ? reject(error) : resolve()));
41新增: }
42新增: socket.end();
43新增: } finally {
44新增: socket.destroy();
45新增: }
46新增:}
47新增:
48新增:// The ordinary guest user owns one browser service. Each caller owns only its
49新增:// connection and cancellation, while dispatch retains a single mutation order.
50新增:export async function serveMacOSBrowser({ directory, dispatch, close, disconnect }) {
51新增: const address = await privateDirectory(directory);
52新增: const previous = await fs.lstat(address).catch(error => { if (error.code !== "ENOENT") throw error; });
53新增: if (previous) {
54新增: await socketInfo(address);
55新增: let live;
56新增: try { live = await connect(address); }
57新增: catch (error) { if (error.code !== "ECONNREFUSED" && error.code !== "ENOENT") throw error; }
58新增: if (live) { live.destroy(); throw new Error("Browser service is already running"); }
59新增: const current = await fs.lstat(address).catch(error => { if (error.code !== "ENOENT") throw error; });
60新增: if (current && current.ino !== previous.ino) throw new Error("Browser service owner changed");
61新增: if (current) await fs.unlink(address);
62新增: }
63新增: const clients = new Set();
64新增: let queue = Promise.resolve(), stopping;
65新增: const request = (input, options = {}) => {
66新增: const pending = queue.then(() => {
67新增: if (stopping) throw new Error("Browser service is stopping");
68新增: options.signal?.throwIfAborted();
69新增: return dispatch(input, options);
70新增: });
71新增: queue = pending.catch(() => {});
72新增: return pending;
73新增: };
74新增: const server = net.createServer({ allowHalfOpen: true }, socket => {
75新增: if (stopping || clients.size >= 16) { socket.destroy(); return; }
76新增: clients.add(socket);
77新增: const cancellation = new AbortController();
78新增: socket.on("error", () => {});
79新增: socket.once("end", () => { cancellation.abort(); socket.end(); });
80新增: socket.once("close", () => {
81新增: cancellation.abort(); clients.delete(socket);
82新增: if (disconnect) {
83新增: const released = queue.then(() => disconnect(cancellation.signal));
84新增: queue = released.catch(() => {});
85新增: }
86新增: });
87新增: let pendingReply = false;
88新增: void (async () => {
89新增: try {
90新增: for await (const line of lines(socket)) {
91新增: if (pendingReply) throw new Error("Browser service caller has an unfinished request");
92新增: pendingReply = true;
93新增: const pending = request(JSON.parse(line), { signal: cancellation.signal });
94新增: void (async () => {
95新增: let result;
96新增: try { result = await pending; }
97新增: catch (error) { result = { error: error.safe ? error.message : "客机浏览器操作失败", code: error.safe ? error.code : "browser_operation_failed" }; }
98新增: if (socket.destroyed) return;
99新增: const data = JSON.stringify({ ...result, service: { version: 1, persistent: true } }) + "\n";
100新增: if (Buffer.byteLength(data) > 30 << 20) throw new Error("Browser service response is too large");
101新增: await new Promise((resolve, reject) => socket.write(data, error => error ? reject(error) : resolve()));
102新增: })().catch(() => socket.destroy()).finally(() => { pendingReply = false; });
103新增: }
104新增: } catch { socket.destroy(); }
105新增: })();
106新增: });
107新增: await new Promise((resolve, reject) => { server.once("error", reject); server.listen(address, resolve); });
108新增: await fs.chmod(address, 0o600);
109新增: const owned = await socketInfo(address);
110新增: const stop = async () => {
111新增: if (!stopping) stopping = (async () => {
112新增: const closed = new Promise(resolve => server.close(resolve));
113新增: for (const client of clients) client.destroy();
114新增: await close();
115新增: await queue;
116新增: await closed;
117新增: const current = await fs.lstat(address).catch(() => null);
118新增: if (current?.ino === owned.ino) await fs.unlink(address);
119新增: })();
120新增: return stopping;
121新增: };
122新增: return { request, close: stop };
123新增:}
新增scripts/guest-os/macos-browser.mjs+316 −0看文件
@@ -0,0 +1,316 @@
1新增:// This process runs over the standard user's pinned guest SSH session. Chrome's
2新增:// DevTools connection uses inherited pipes, and host WebKit receives only pixels.
3新增:import { chromium } from "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/playwright/index.mjs";
4新增:import { spawn } from "node:child_process";
5新增:import { randomBytes } from "node:crypto";
6新增:import { mkdir, rm, writeFile } from "node:fs/promises";
7新增:import { homedir } from "node:os";
8新增:import path from "node:path";
9新增:import { createInterface } from "node:readline";
10新增:import { once } from "node:events";
11新增:
12新增:const editorSessions = path.join(
13新增: homedir(),
14新增: "Library",
15新增: "Application Support",
16新增: "Cage",
17新增: "EditorSessions",
18新增:);
19新增:const profile = path.join(
20新增: homedir(),
21新增: "Library",
22新增: "Application Support",
23新增: "Cage",
24新增: "Browser",
25新增:);
26新增:let editorConfig;
27新增:let browser, page, editor, editorFolder, editorAddress, editorPassword, closing;
28新增:function close() {
29新增: return (closing ??= (async () => {
30新增: if (editor) editor.kill();
31新增: await browser?.close().catch(() => {});
32新增: if (editorConfig) await rm(editorConfig, { force: true });
33新增: })());
34新增:}
35新增:async function getPage() {
36新增: if (!browser) {
37新增: await mkdir(profile, { recursive: true, mode: 0o700 });
38新增: browser = await chromium.launchPersistentContext(profile, {
39新增: executablePath:
40新增: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
41新增: headless: true,
42新增: chromiumSandbox: true,
43新增: viewport: { width: 1140, height: 700 },
44新增: args: ["--disable-quic", "--no-default-browser-check"],
45新增: acceptDownloads: false,
46新增: timeout: 20000,
47新增: });
48新增: browser.setDefaultTimeout(7000);
49新增: page = browser.pages()[0] ?? (await browser.newPage());
50新增: browser.on("page", (p) => {
51新增: page = p;
52新增: });
53新增: browser.on("close", () => {
54新增: browser = undefined;
55新增: page = undefined;
56新增: });
57新增: }
58新增: if (!page || page.isClosed())
59新增: page = browser.pages().at(-1) ?? (await browser.newPage());
60新增: return page;
61新增:}
62新增:async function openEditor(folder) {
63新增: const p = await getPage();
64新增: if (
65新增: editorFolder !== folder ||
66新增: !editor ||
67新增: editor.exitCode !== null ||
68新增: !editorAddress
69新增: ) {
70新增: if (editor) editor.kill();
71新增: editorPassword = randomBytes(32).toString("hex");
72新增: const project = path.basename(folder);
73新增: if (
74新增: !/^[0-9a-f]{24}$/.test(project) ||
75新增: folder !== path.join(homedir(), "Cage", "Projects", project)
76新增: )
77新增: throw new Error("请选择已授权的客机项目");
78新增: await mkdir(editorSessions, { recursive: true, mode: 0o700 });
79新增: if (editorConfig) await rm(editorConfig, { force: true });
80新增: editorConfig = path.join(editorSessions, project + ".yaml");
81新增: await writeFile(
82新增: editorConfig,
83新增: "bind-addr: 127.0.0.1:0\nauth: password\npassword: " +
84新增: editorPassword +
85新增: "\ncert: false\n",
86新增: { mode: 0o600 },
87新增: );
88新增: const child = spawn(
89新增: "/usr/local/libexec/cage-macos-terminal",
90新增: ["--editor", folder],
91新增: {
92新增: stdio: ["pipe", "pipe", "pipe"],
93新增: },
94新增: );
95新增: editor = child;
96新增: child.stdin.on("error", () => {});
97新增: editorAddress = await new Promise((resolve, reject) => {
98新增: let recent = "";
99新增: const timer = setTimeout(
100新增: () => finish(new Error("客机编辑器未能启动,请检查项目授权")),
101新增: 12000,
102新增: );
103新增: const read = (data) => {
104新增: recent = (recent + data.toString()).slice(-6000);
105新增: const address = recent.match(
106新增: /HTTP server listening on (http:\/\/127\.0\.0\.1:[1-9][0-9]*)/,
107新增: );
108新增: if (address) finish(null, address[1]);
109新增: };
110新增: const failed = () =>
111新增: finish(new Error("请先在 Cage 授权此项目,再打开编辑器"));
112新增: function finish(error, address) {
113新增: clearTimeout(timer);
114新增: child.stdout.off("data", read);
115新增: child.stderr.off("data", read);
116新增: child.off("error", failed);
117新增: child.off("exit", failed);
118新增: if (error) {
119新增: child.kill();
120新增: reject(error);
121新增: } else {
122新增: child.stdout.resume();
123新增: child.stderr.resume();
124新增: resolve(address);
125新增: }
126新增: }
127新增: child.stdout.on("data", read);
128新增: child.stderr.on("data", read);
129新增: child.once("error", failed);
130新增: child.once("exit", failed);
131新增: });
132新增: editorFolder = folder;
133新增: child.once("exit", () => {
134新增: if (editor === child) {
135新增: editor = undefined;
136新增: editorAddress = undefined;
137新增: }
138新增: });
139新增: }
140新增: const login = await p.request.post(editorAddress + "/login", {
141新增: form: { password: editorPassword },
142新增: maxRedirects: 0,
143新增: timeout: 7000,
144新增: });
145新增: if (![302, 303].includes(login.status()))
146新增: throw new Error("客机编辑器登录失败");
147新增: await login.dispose();
148新增: await p.goto(editorAddress + "/?folder=" + encodeURIComponent(folder), {
149新增: waitUntil: "commit",
150新增: });
151新增:}
152新增:const keys = new Set([
153新增: "Tab",
154新增: "Enter",
155新增: "Backspace",
156新增: "Delete",
157新增: "Escape",
158新增: "ArrowLeft",
159新增: "ArrowRight",
160新增: "ArrowUp",
161新增: "ArrowDown",
162新增: "Home",
163新增: "End",
164新增: "PageUp",
165新增: "PageDown",
166新增: "Space",
167新增: "F5",
168新增: "F8",
169新增: "F9",
170新增: "F10",
171新增: "F11",
172新增:]);
173新增:// Observe a fresh document in the actual guest browser. The separate network
174新增:// context carries no workbench session cookies and can reach only the fixed diagnostic service.
175新增:async function audit(timezone, network) {
176新增: await getPage();
177新增: const previous = page;
178新增: const settingsPage = await browser.newPage();
179新增: let settings;
180新增: try {
181新增: settings = await settingsPage.evaluate(
182新增: (zone) => ({
183新增: timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
184新增: expected_timezone: new Intl.DateTimeFormat("en", {
185新增: timeZone: zone,
186新增: }).resolvedOptions().timeZone,
187新增: language: navigator.language,
188新增: platform: navigator.platform,
189新增: }),
190新增: timezone,
191新增: );
192新增: } finally {
193新增: await settingsPage.close();
194新增: page = previous;
195新增: }
196新增: if (!network) return settings;
197新增: const owner = browser.browser();
198新增: if (!owner) throw new Error("无法创建独立的浏览器诊断会话");
199新增: const isolated = await owner.newContext({ serviceWorkers: "block" });
200新增: try {
201新增: const test = await isolated.newPage();
202新增: await test.goto("http://198.18.0.254/", {
203新增: waitUntil: "domcontentloaded",
204新增: timeout: 12000,
205新增: });
206新增: settings.network = await test.evaluate(async () => {
207新增: if (location.origin !== "http://198.18.0.254")
208新增: throw new Error("无效的诊断地址");
209新增: try {
210新增: const r = await fetch("/egress", {
211新增: cache: "no-store",
212新增: credentials: "omit",
213新增: signal: AbortSignal.timeout(14000),
214新增: });
215新增: return { ...(await r.json()), status: r.status };
216新增: } catch {
217新增: return { status: 0 };
218新增: }
219新增: });
220新增: return settings;
221新增: } finally {
222新增: await isolated.close();
223新增: }
224新增:}
225新增:
226新增:async function handle(a) {
227新增: if (a.action === "audit") return audit(a.timezone, a.network);
228新增: const p = await getPage();
229新增: switch (a.action) {
230新增: case "frame": {
231新增: const data = await p.screenshot({
232新增: type: "jpeg",
233新增: quality: 70,
234新增: timeout: 5000,
235新增: });
236新增: return {
237新增: image: data.toString("base64"),
238新增: url: p.url(),
239新增: title: await p.title(),
240新增: width: p.viewportSize().width,
241新增: height: p.viewportSize().height,
242新增: };
243新增: }
244新增: case "editor":
245新增: await openEditor(a.folder);
246新增: break;
247新增: case "navigate": {
248新增: const u = new URL(a.url);
249新增: if (!["http:", "https:"].includes(u.protocol) || u.username || u.password)
250新增: throw new Error("请输入 HTTP 或 HTTPS 地址");
251新增: await p.goto(u.href, { waitUntil: "commit", timeout: 8000 });
252新增: break;
253新增: }
254新增: case "click":
255新增: await p.mouse.click(a.x, a.y, { clickCount: a.double ? 2 : 1 });
256新增: break;
257新增: case "wheel":
258新增: await p.mouse.move(a.x, a.y);
259新增: await p.mouse.wheel(a.dx, a.dy);
260新增: break;
261新增: case "text":
262新增: if (typeof a.text !== "string" || a.text.length > 4096)
263新增: throw new Error("输入过长");
264新增: await p.keyboard.insertText(a.text);
265新增: break;
266新增: case "key": {
267新增: if (!(keys.has(a.key) || /^[a-z0-9]$/i.test(a.key)))
268新增: throw new Error("不支持此键");
269新增: await p.keyboard.press(
270新增: [
271新增: a.meta && "Meta",
272新增: a.ctrl && "Control",
273新增: a.shift && "Shift",
274新增: a.alt && "Alt",
275新增: a.key,
276新增: ]
277新增: .filter(Boolean)
278新增: .join("+"),
279新增: );
280新增: break;
281新增: }
282新增: case "reload":
283新增: await p.reload({ waitUntil: "commit" });
284新增: break;
285新增: case "back":
286新增: await p.goBack({ waitUntil: "commit" });
287新增: break;
288新增: case "forward":
289新增: await p.goForward({ waitUntil: "commit" });
290新增: break;
291新增: default:
292新增: throw new Error("未知的客机浏览器操作");
293新增: }
294新增: return { ok: true };
295新增:}
296新增:process.once("SIGHUP", () => {
297新增: void close().finally(() => process.exit(0));
298新增:});
299新增:process.once("SIGTERM", () => {
300新增: void close().finally(() => process.exit(0));
301新增:});
302新增:try {
303新增: const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
304新增: for await (const line of lines) {
305新增: let result;
306新增: try {
307新增: result = await handle(JSON.parse(line));
308新增: } catch (error) {
309新增: result = { error: String(error.message).split("\n")[0].slice(0, 220) };
310新增: }
311新增: if (!process.stdout.write(JSON.stringify(result) + "\n"))
312新增: await once(process.stdout, "drain");
313新增: }
314新增:} finally {
315新增: await close();
316新增:}
新增scripts/guest-os/macos-claude-canvas.swift+169 −0看文件
@@ -0,0 +1,169 @@
1新增:// A geometry token describes only the signed Claude window actually captured.
2新增:// All coordinates used for presentation and input are measured in guest points.
3新增:import AppKit
4新增:import ScreenCaptureKit
5新增:import ImageIO
6新增:import UniformTypeIdentifiers
7新增:
8新增:struct ClaudeCanvas {
9新增: let id: CGWindowID
10新增: let pid: pid_t
11新增: let frame: CGRect
12新增: let cropTop: CGFloat
13新增: let scale: CGFloat
14新增: let resizable: Bool
15新增: var content: CGSize { CGSize(width: frame.width, height: frame.height - cropTop) }
16新增:
17新增: func matches(_ other: ClaudeCanvas) -> Bool {
18新增: id == other.id && pid == other.pid && frame == other.frame && cropTop == other.cropTop && scale == other.scale
19新增: }
20新增:}
21新增:
22新增:private func axAttribute(_ element: AXUIElement, _ attribute: String) -> CFTypeRef? {
23新增: var value: CFTypeRef?
24新增: guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else { return nil }
25新增: return value
26新增:}
27新增:
28新增:private func axRect(_ element: AXUIElement) -> CGRect? {
29新增: guard let p = axAttribute(element, kAXPositionAttribute), CFGetTypeID(p) == AXValueGetTypeID(),
30新增: let s = axAttribute(element, kAXSizeAttribute), CFGetTypeID(s) == AXValueGetTypeID() else { return nil }
31新增: var pos = CGPoint.zero, size = CGSize.zero
32新增: guard AXValueGetValue(p as! AXValue, .cgPoint, &pos), AXValueGetValue(s as! AXValue, .cgSize, &size) else { return nil }
33新增: return CGRect(origin: pos, size: size)
34新增:}
35新增:
36新增:private func liveBounds(_ id: CGWindowID, _ pid: pid_t) throws -> CGRect {
37新增: let windows = CGWindowListCopyWindowInfo(.optionIncludingWindow, id) as? [[String:Any]]
38新增: guard let info = windows?.first, info[kCGWindowOwnerPID as String] as? Int32 == pid,
39新增: info[kCGWindowIsOnscreen as String] as? Bool == true,
40新增: let box = info[kCGWindowBounds as String] as? NSDictionary,
41新增: let rect = CGRect(dictionaryRepresentation: box), !rect.isEmpty else { throw Failure(7, "window_changed") }
42新增: return rect
43新增:}
44新增:
45新增:private func owningAXWindow(_ pid: pid_t, _ frame: CGRect) -> AXUIElement? {
46新增: guard AXIsProcessTrusted(), NSWorkspace.shared.frontmostApplication?.processIdentifier == pid,
47新增: let raw = axAttribute(AXUIElementCreateApplication(pid), kAXFocusedWindowAttribute),
48新增: CFGetTypeID(raw) == AXUIElementGetTypeID() else { return nil }
49新增: let window = raw as! AXUIElement
50新增: guard let actual = axRect(window), abs(actual.minX-frame.minX)<1, abs(actual.minY-frame.minY)<1,
51新增: abs(actual.width-frame.width)<1, abs(actual.height-frame.height)<1 else { return nil }
52新增: return window
53新增:}
54新增:
55新增:private func canSet(_ window: AXUIElement, _ name: String) -> Bool {
56新增: var result = DarwinBoolean(false)
57新增: return AXUIElementIsAttributeSettable(window, name as CFString, &result) == .success && result.boolValue
58新增:}
59新增:
60新增:private func titleBarHeight(_ window: AXUIElement, _ frame: CGRect) -> CGFloat {
61新增: var bottom: CGFloat = 0
62新增: for name in [kAXCloseButtonAttribute, kAXMinimizeButtonAttribute, kAXZoomButtonAttribute] {
63新增: guard let raw = axAttribute(window, name), CFGetTypeID(raw) == AXUIElementGetTypeID(),
64新增: let button = axRect(raw as! AXUIElement), button.width > 2, button.height > 2,
65新增: frame.contains(button), button.minX-frame.minX < 100, button.maxY-frame.minY < 70 else { continue }
66新增: let margin = min(8, max(2, button.minY - frame.minY))
67新增: bottom = max(bottom, ceil(button.maxY - frame.minY + margin))
68新增: }
69新增: return bottom < frame.height / 3 ? bottom : 0
70新增:}
71新增:
72新增:@MainActor
73新增:final class ClaudeCanvasSession {
74新增: static let shared = ClaudeCanvasSession()
75新增: private var last: ClaudeCanvas?
76新增: private var token = ""
77新增: private var requested: (id: CGWindowID, pid: pid_t, size: CGSize, observed: CGSize, time: Date)?
78新增:
79新增: func layout(_ window: SCWindow, filter: SCContentFilter, width: Int, height: Int, scale: Double) async throws -> ClaudeCanvas {
80新增: guard let pid = window.owningApplication?.processID,
81新增: (320...2560).contains(width), (240...1600).contains(height),
82新增: scale.isFinite, (1...2).contains(scale) else { throw Failure(8, "invalid_input") }
83新增: var bounds = try liveBounds(window.windowID, pid)
84新增: var crop: CGFloat = 0, resized = false
85新增: if let ax = owningAXWindow(pid, bounds) {
86新增: crop = titleBarHeight(ax, bounds)
87新增: if canSet(ax, kAXSizeAttribute) {
88新增: let display = CGDisplayBounds(CGMainDisplayID())
89新增: let wanted = CGSize(width: min(CGFloat(width), display.width),
90新增: height: min(CGFloat(height) + crop, display.height))
91新增: let close = abs(bounds.width - wanted.width) < 2 && abs(bounds.height - wanted.height) < 2
92新增: let recent = requested.map { $0.id == window.windowID && $0.pid == pid && $0.size == wanted &&
93新增: $0.observed == bounds.size && Date().timeIntervalSince($0.time) < 3 } ?? false
94新增: if !close && !recent {
95新增: var size = wanted
96新增: if let value = AXValueCreate(.cgSize, &size),
97新增: AXUIElementSetAttributeValue(ax, kAXSizeAttribute as CFString, value) == .success {
98新增: try await Task.sleep(nanoseconds: 70_000_000)
99新增: bounds = try liveBounds(window.windowID, pid)
100新增: // Position only an enlarged guest window that would extend off its display.
101新增: var origin = CGPoint(x: max(display.minX, min(bounds.minX, display.maxX-bounds.width)),
102新增: y: max(display.minY, min(bounds.minY, display.maxY-bounds.height)))
103新增: if origin != bounds.origin, canSet(ax, kAXPositionAttribute),
104新增: let point = AXValueCreate(.cgPoint, &origin) {
105新增: _ = AXUIElementSetAttributeValue(ax, kAXPositionAttribute as CFString, point)
106新增: bounds = try liveBounds(window.windowID, pid)
107新增: }
108新增: }
109新增: requested = (window.windowID, pid, wanted, bounds.size, Date())
110新增: }
111新增: resized = abs(bounds.width-wanted.width) < 2 && abs(bounds.height-wanted.height) < 2
112新增: crop = titleBarHeight(ax, bounds)
113新增: }
114新增: }
115新增: return ClaudeCanvas(id: window.windowID, pid: pid, frame: bounds, cropTop: crop,
116新增: scale: min(max(1,CGFloat(filter.pointPixelScale)), CGFloat(scale)), resizable: resized)
117新增: }
118新增:
119新增: func record(_ value: ClaudeCanvas) -> String {
120新增: if last?.matches(value) != true { token = UUID().uuidString; last = value }
121新增: return token
122新增: }
123新增:
124新增: func inputGeometry(_ requested: String, window: SCWindow) throws -> ClaudeCanvas {
125新增: guard let last, token == requested, last.id == window.windowID, last.pid == window.owningApplication?.processID,
126新增: try liveBounds(last.id, last.pid) == last.frame,
127新增: let ax = owningAXWindow(last.pid, last.frame), titleBarHeight(ax,last.frame) == last.cropTop else {
128新增: throw Failure(7, "window_changed")
129新增: }
130新增: return last
131新增: }
132新增:
133新增: func capture(_ window: SCWindow, filter: SCContentFilter, layout: ClaudeCanvas, after: String? = nil, wait: Bool = false, binary: Bool = false, phoneJPEG: Bool = false) async throws -> [String:Any] {
134新增: let config = SCStreamConfiguration()
135新增: config.width = max(1, Int((layout.frame.width*layout.scale).rounded()))
136新增: config.height = max(1, Int((layout.frame.height*layout.scale).rounded()))
137新增: config.captureResolution = .best
138新增: config.ignoreShadowsSingleWindow = true; config.showsCursor = false
139新增: if #available(macOS 14.2, *) { config.includeChildWindows = false }
140新增: let geometry = record(layout)
141新增: let (updated, sequence) = try await MacWindowStream.shared.frame(filter: filter, configuration: config, identity: geometry, after: after, wait: wait)
142新增: guard try liveBounds(layout.id, layout.pid) == layout.frame,
143新增: try claudePIDs().contains(layout.pid) else { throw Failure(7, "window_changed") }
144新增: guard let image = updated else { return ["unchanged": true, "sequence": sequence, "geometry": geometry] }
145新增: let top = Int((layout.cropTop * CGFloat(image.height) / layout.frame.height).rounded())
146新增: guard top >= 0, top < image.height,
147新增: let content = image.cropping(to: CGRect(x:0,y:top,width:image.width,height:image.height-top)),
148新增: try liveBounds(layout.id, layout.pid) == layout.frame,
149新增: try claudePIDs().contains(layout.pid) else { throw Failure(7, "window_changed") }
150新增: var data = phoneJPEG ? try phoneDesktopJPEG(content) : try pngData(content)
151新增: var mime = phoneJPEG ? "image/jpeg" : "image/png"
152新增: if data.count >= 8<<20 {
153新增: // Preserve native glyph density and geometry even on photo-heavy windows.
154新增: mime = "image/jpeg"
155新增: for quality in [0.93, 0.84] {
156新增: data = try encodedImage(content, type:.jpeg, properties:[kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)
157新增: if data.count < 8<<20 { break }
158新增: }
159新增: }
160新增: guard data.count < 8<<20 else { throw Failure(8, "frame_limit") }
161新增: var reply: [String:Any] = ["window":layout.id,"pid":layout.pid,"mime":mime,"sequence":sequence,
162新增: "contentWidth":layout.content.width,"contentHeight":layout.content.height,
163新增: "pixelWidth":content.width,"pixelHeight":content.height,"cropTop":layout.cropTop,
164新增: "resizable":layout.resizable, "geometry":geometry]
165新增: if binary { reply["imageBytes"] = data }
166新增: else { reply["image"] = data.base64EncodedString() }
167新增: return reply
168新增: }
169新增:}
新增scripts/guest-os/macos-claude-window-app.swift+486 −0看文件
@@ -0,0 +1,486 @@
1新增:// GUI LaunchAgent for the macOS guest. launchd owns one private per-user socket.
2新增:import AppKit
3新增:import ApplicationServices
4新增:import ScreenCaptureKit
5新增:import Security
6新增:
7新增:private let appURL = URL(fileURLWithPath: "/Applications/Claude.app")
8新增:private let requirement = #"anchor apple generic and identifier "com.anthropic.claudefordesktop" and certificate leaf[subject.OU] = "Q6L2SF6YDW" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"#
9新增:
10新增:struct Request: Decodable {
11新增: let action: String
12新增: var window: UInt32?
13新增: var pid: Int32?
14新增: var x, y, delta: Double?
15新增: var deltaX: Double?
16新增: var key, text: String?
17新增: var code, phase, mode, context, session: String?
18新增: var down, control, alt: Bool?
19新增: var button, buttons, clicks: Int?
20新增: var shift, command: Bool?
21新增: var project, nonce, geometry: String?
22新增: var width, height: Int?
23新增: var scale: Double?
24新增: var after: String?
25新增: var keepAlive: Bool?
26新增: var refresh: Bool?
27新增: var wait, binary: Bool?
28新增: var id, kind: String?
29新增: var transfer: String?
30新增: var sequence: Int?
31新增: var path: String?
32新增: var error: String?
33新增: var files: [String]?
34新增: var length: Int?
35新增: var phone: MacPhoneDesktopInput?
36新增: var phone_token: String?
37新增:}
38新增:
39新增:func consoleUser() throws {
40新增: var info = stat()
41新增: guard stat("/dev/console", &info) == 0, info.st_uid >= 500, info.st_uid == getuid(),
42新增: (CGSessionCopyCurrentDictionary() as? [String:Any])?["CGSSessionScreenIsLocked"] as? Bool != true else {
43新增: throw Failure(4, "requires_gui_login")
44新增: }
45新增:}
46新增:
47新增:private func verifiedInstall() throws {
48新增: var rule: SecRequirement?
49新增: var code: SecStaticCode?
50新增: guard SecRequirementCreateWithString(requirement as CFString, [], &rule) == errSecSuccess, let rule,
51新增: SecStaticCodeCreateWithPath(appURL as CFURL, [], &code) == errSecSuccess, let code,
52新增: SecStaticCodeCheckValidity(code, [], rule) == errSecSuccess else {
53新增: throw Failure(5, "identity_error")
54新增: }
55新增:}
56新增:
57新增:// The system picker can authorize a single window without persistent guest
58新增:// screen-recording access. Never accept a display, another app, or a group.
59新增:@available(macOS 15.2, *)
60新增:@MainActor
61新增:private final class ClaudePicker: NSObject, SCContentSharingPickerObserver {
62新增: static let shared = ClaudePicker()
63新增: private(set) var selection: SCContentFilter?
64新增: func choose() {
65新增: let picker = SCContentSharingPicker.shared
66新增: picker.remove(self)
67新增: picker.add(self)
68新增: var config = SCContentSharingPickerConfiguration()
69新增: config.allowedPickerModes = [.singleWindow]
70新增: config.allowsChangingSelectedContent = false
71新增: picker.defaultConfiguration = config
72新增: picker.isActive = true
73新增: picker.present(using: .window)
74新增: }
75新增: nonisolated func contentSharingPicker(_ picker: SCContentSharingPicker, didUpdateWith filter: SCContentFilter, for stream: SCStream?) {
76新增: Task { @MainActor in
77新增: let window = filter.includedWindows.first
78新增: guard filter.style == .window, filter.includedWindows.count == 1,
79新增: let owner = window?.owningApplication,
80新增: owner.bundleIdentifier == "com.anthropic.claudefordesktop",
81新增: (try? claudePIDs().contains(owner.processID)) == true else { self.selection = nil; return }
82新增: self.selection = filter
83新增: }
84新增: }
85新增: nonisolated func contentSharingPicker(_ picker: SCContentSharingPicker, didCancelFor stream: SCStream?) {}
86新增: nonisolated func contentSharingPickerStartDidFailWithError(_ error: Error) {}
87新增:}
88新增:
89新增:@MainActor
90新增:func selectedWindow() async throws -> (SCWindow, SCContentFilter?) {
91新增: if #available(macOS 15.2, *), let filter = ClaudePicker.shared.selection, let window = filter.includedWindows.first {
92新增: let pids = try claudePIDs()
93新增: guard let owner = window.owningApplication, pids.contains(owner.processID) else { throw Failure(7, "window_changed") }
94新增: // Obtain current geometry by ID. This includes only window metadata.
95新增: let list = CGWindowListCopyWindowInfo([.optionIncludingWindow], window.windowID) as? [[String:Any]]
96新增: guard let exact = list?.first, exact[kCGWindowOwnerPID as String] as? Int32 == owner.processID,
97新增: exact[kCGWindowIsOnscreen as String] as? Bool == true else { throw Failure(7, "window_changed") }
98新增: return (window, filter)
99新增: }
100新增: return (try await claudeWindow(), nil)
101新增:}
102新增:
103新增:@MainActor
104新增:func sendInput(_ input: Request, window: SCWindow, canvas: ClaudeCanvas? = nil, maxTextBytes: Int = 8192, scrollX: Double = 0, maxScroll: Double = 1200, inputSession: MacWindowInputSession? = nil) throws {
105新增: let target = try checkedMacInputWindow(input, window: window)
106新增: try MacWindowInputSession.requirePointerOwner(inputSession)
107新增: let focused = target.focused, pid = target.pid
108新增: let origin = target.origin, extent = target.extent
109新增: let source = CGEventSource(stateID: .privateState)
110新增: func keyPair(_ key: CGKeyCode, flags: CGEventFlags = [], text: String? = nil) throws {
111新增: for down in [true, false] {
112新增: guard let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: down) else { throw Failure(8, "input_failed") }
113新增: event.flags = flags
114新增: if let text {
115新增: let chars = Array(text.utf16)
116新增: chars.withUnsafeBufferPointer { event.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: $0.baseAddress) }
117新增: }
118新增: event.postToPid(pid)
119新增: }
120新增: }
121新增: switch input.action {
122新增: case "text":
123新增: guard let text = input.text, !text.isEmpty, text.utf8.count <= maxTextBytes else { throw Failure(8, "invalid_input") }
124新增: for character in text { try keyPair(0, text: String(character)) }
125新增: case "key":
126新增: if input.code != nil {
127新增: guard let inputSession else { throw Failure(8, "input_connection_required") }
128新增: try inputSession.key(input, target: target, window: window)
129新增: return
130新增: }
131新增: let keys: [String: CGKeyCode] = ["Enter":36, "Tab":48, "Backspace":51, "Escape":53, "Delete":117, "ArrowLeft":123, "ArrowRight":124, "ArrowDown":125, "ArrowUp":126, "a":0, "z":6]
132新增: guard let key = input.key, let code = keys[key], (input.command == true) == ["a", "z"].contains(key) else { throw Failure(8, "invalid_input") }
133新增: var flags: CGEventFlags = []
134新增: if input.shift == true { flags.insert(.maskShift) }
135新增: if input.command == true { flags.insert(.maskCommand) }
136新增: try keyPair(code, flags: flags)
137新增: case "pointer":
138新增: guard let inputSession else { throw Failure(8, "input_connection_required") }
139新增: try inputSession.pointer(input, target: target, window: window, canvas: canvas)
140新增: case "click", "scroll", "project-click":
141新增: guard let x = input.x, let y = input.y, (0..<1).contains(x), (0..<1).contains(y) else { throw Failure(8, "invalid_input") }
142新增: let crop = canvas?.cropTop ?? 0
143新增: let point = CGPoint(x: origin.x + extent.width * x, y: origin.y + crop + (extent.height-crop) * y)
144新增: if input.action == "project-click" {
145新增: // NSOpenPanel's remote view returns the hosting AXWindow from
146新增: // point queries. Hit-test only its actual approval button, using
147新增: // its live accessibility bounds and the user's frame coordinates.
148新增: var visited = 0
149新增: func attribute(_ node: AXUIElement, _ name: String) -> CFTypeRef? {
150新增: var result: CFTypeRef?
151新增: guard AXUIElementCopyAttributeValue(node, name as CFString, &result) == .success else { return nil }
152新增: return result
153新增: }
154新增: func buttonAtPoint(_ node: AXUIElement, depth: Int) -> AXUIElement? {
155新增: guard depth <= 14, visited < 2048 else { return nil }
156新增: visited += 1
157新增: if attribute(node, kAXRoleAttribute) as? String == kAXButtonRole,
158新增: attribute(node, kAXTitleAttribute) as? String == "Use Project",
159新增: let pos = attribute(node, kAXPositionAttribute), CFGetTypeID(pos) == AXValueGetTypeID(),
160新增: let dim = attribute(node, kAXSizeAttribute), CFGetTypeID(dim) == AXValueGetTypeID() {
161新增: var p = CGPoint.zero, s = CGSize.zero
162新增: if AXValueGetValue(pos as! AXValue, .cgPoint, &p), AXValueGetValue(dim as! AXValue, .cgSize, &s),
163新增: CGRect(origin: p, size: s).contains(point) { return node }
164新增: }
165新增: for child in attribute(node, kAXChildrenAttribute) as? [AXUIElement] ?? [] {
166新增: if let match = buttonAtPoint(child, depth: depth + 1) { return match }
167新增: }
168新增: return nil
169新增: }
170新增: guard let button = buttonAtPoint(focused, depth: 0),
171新增: AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else {
172新增: throw Failure(8, "project_button_not_hit")
173新增: }
174新增: return
175新增: }
176新增: // An Electron NSView may ignore a CGEvent addressed to its process
177新增: // while accepting the accessibility press on the hit control. Never
178新增: // act on another window, a nearby control, or an arbitrary AX node.
179新增: if input.action == "click", let button = macPressTarget(target, point: point) {
180新增: guard AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else { throw Failure(8, "input_failed") }
181新增: return
182新增: }
183新增: let events: [CGEvent?]
184新增: if input.action == "scroll" {
185新增: let horizontal = input.deltaX ?? scrollX
186新增: guard let delta = input.delta, delta.isFinite, horizontal.isFinite,
187新增: (-maxScroll...maxScroll).contains(delta), (-maxScroll...maxScroll).contains(horizontal) else { throw Failure(8, "invalid_input") }
188新增: events = [CGEvent(scrollWheelEvent2Source: source, units: .pixel, wheelCount: horizontal == 0 ? 1 : 2, wheel1: Int32(-delta), wheel2: Int32(-horizontal), wheel3: 0)]
189新增: } else {
190新增: // Address the NSEvent to this window using its unflipped local
191新增: // coordinates. CGEvent's global position alone does not give an
192新增: // Electron NSView a locationInWindow when posting to a process.
193新增: let local = CGPoint(x: point.x-origin.x, y: extent.height-(point.y-origin.y))
194新增: let types: [NSEvent.EventType] = [.leftMouseDown, .leftMouseUp]
195新增: events = types.map { type in
196新增: NSEvent.mouseEvent(with: type, location: local, modifierFlags: [],
197新增: timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: Int(window.windowID),
198新增: context: nil, eventNumber: 0, clickCount: 1, pressure: type == .leftMouseDown ? 1 : 0)?.cgEvent
199新增: }
200新增: }
201新增: for item in events {
202新增: guard let event = item else { throw Failure(8, "input_failed") }
203新增: event.location = point
204新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(window.windowID))
205新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(window.windowID))
206新增: event.setIntegerValueField(.mouseEventClickState, value: 1)
207新增: event.postToPid(pid)
208新增: }
209新增: default: throw Failure(8, "invalid_input")
210新增: }
211新增:}
212新增:
213新增:@MainActor
214新增:func launchClaudeWindow() async throws {
215新增: try verifiedInstall()
216新增: let configuration = NSWorkspace.OpenConfiguration()
217新增: configuration.activates = true
218新增: let application = try await NSWorkspace.shared.openApplication(at: appURL, configuration: configuration)
219新增: if AXIsProcessTrusted(), try claudePIDs().contains(application.processIdentifier) {
220新增: let element = AXUIElementCreateApplication(application.processIdentifier)
221新增: _ = AXUIElementSetAttributeValue(element, "AXManualAccessibility" as CFString, kCFBooleanTrue)
222新增: }
223新增:}
224新增:
225新增:@MainActor
226新增:private func handle(_ input: Request, inputSession: MacWindowInputSession) async throws -> [String: Any] {
227新增: try requireGuest()
228新增: if input.action.hasPrefix("phone-") {
229新增: return try await MacPhoneDesktop.shared.handle(input)
230新增: }
231新增: try consoleUser()
232新增: switch input.action {
233新增: case "files-start":
234新增: let (window, _) = try await selectedWindow()
235新增: guard input.pid == window.owningApplication?.processID, input.window == window.windowID else { throw Failure(7, "window_changed") }
236新增: return try MacDesktopFiles.shared.start(window: window, kind: input.kind ?? "")
237新增: case "files-add":
238新增: return try MacDesktopFiles.shared.add(input.id ?? "", files: input.files ?? [])
239新增: case "files-validate":
240新增: return try MacDesktopFiles.shared.validate(input.id ?? "")
241新增: case "files-finish":
242新增: return try await MacDesktopFiles.shared.finish(input.id ?? "")
243新增: case "files-finish-image":
244新增: return try await MacDesktopFiles.shared.finishImage(input.id ?? "")
245新增: case "files-cancel":
246新增: return await MacDesktopFiles.shared.cancel(input.id ?? "")
247新增: case "files-poll":
248新增: return try await MacDesktopFiles.shared.poll()
249新增: case "files-download-open", "files-download-read", "files-download-close", "files-download-retry":
250新增: return try MacDesktopDownloads.shared.read(input)
251新增: case "files-open-claim", "files-open-complete":
252新增: return try MacDesktopFiles.shared.openAction(input.id ?? "", complete: input.action == "files-open-complete")
253新增: case "audio-status":
254新增: return MacAudioCapture.status()
255新增: case "setup-status":
256新增: return ["screen": CGPreflightScreenCaptureAccess(), "input": AXIsProcessTrusted()]
257新增: case "setup-password-focus":
258新增: guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication,
259新增: app.bundleIdentifier == "com.apple.authorizationhost" else { return ["focused":false] }
260新增: var code: SecCode?
261新增: var rule: SecRequirement?
262新增: guard SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributePid as String:app.processIdentifier] as CFDictionary, [], &code) == errSecSuccess,
263新增: SecRequirementCreateWithString("anchor apple and identifier com.apple.authorizationhost" as CFString, [], &rule) == errSecSuccess,
264新增: let code, let rule, SecCodeCheckValidity(code, [], rule) == errSecSuccess else { return ["focused":false] }
265新增: var value: CFTypeRef?
266新增: let element = AXUIElementCreateApplication(app.processIdentifier)
267新增: guard AXUIElementCopyAttributeValue(element,kAXFocusedUIElementAttribute as CFString,&value) == .success,
268新增: let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return ["focused":false] }
269新增: var subrole: CFTypeRef?
270新增: guard AXUIElementCopyAttributeValue(value as! AXUIElement,kAXSubroleAttribute as CFString,&subrole) == .success else { return ["focused":false] }
271新增: return ["focused":subrole as? String == kAXSecureTextFieldSubrole]
272新增: case "setup-screen", "setup-input", "setup-projects":
273新增: let pane: String
274新增: if input.action == "setup-screen" {
275新增: if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() }
276新增: pane = "com.apple.preference.security?Privacy_ScreenCapture"
277新增: } else if input.action == "setup-input" {
278新增: let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
279新增: _ = AXIsProcessTrustedWithOptions(options)
280新增: pane = "com.apple.preference.security?Privacy_Accessibility"
281新增: } else {
282新增: let vendor = URL(fileURLWithPath: "/Applications/macFUSE.app")
283新增: let configuration = NSWorkspace.OpenConfiguration()
284新增: configuration.activates = false
285新增: _ = try await NSWorkspace.shared.openApplication(at: vendor, configuration: configuration)
286新增: pane = "com.apple.LoginItems-Settings.extension"
287新增: }
288新增: guard let url = URL(string: "x-apple.systempreferences:" + pane), NSWorkspace.shared.open(url) else { throw Failure(7, "settings_unavailable") }
289新增: return ["ok":true]
290新增: case "status":
291新增: let installed = FileManager.default.fileExists(atPath: appURL.path)
292新增: let running = ((try? claudePIDs())?.isEmpty == false)
293新增: var screen = CGPreflightScreenCaptureAccess()
294新增: if #available(macOS 15.2, *) { screen = screen || ClaudePicker.shared.selection != nil }
295新增: return ["version": (Bundle(url: appURL)?.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String) ?? "", "installed": installed, "running": running, "screen": screen, "input": AXIsProcessTrusted(), "input_protocol": 1, "persistent": true, "push_frames": true]
296新增: case "launch":
297新增: try await launchClaudeWindow()
298新增: return ["ok": true]
299新增: case "stop":
300新增: for pid in try claudePIDs() {
301新增: guard let app = NSRunningApplication(processIdentifier: pid), app.terminate() else { throw Failure(7, "window_changed") }
302新增: }
303新增: return ["ok": true]
304新增: case "request-screen":
305新增: if #available(macOS 15.2, *) { ClaudePicker.shared.choose() } else { _ = CGRequestScreenCaptureAccess() }
306新增: return ["screen": CGPreflightScreenCaptureAccess()]
307新增: case "request-input":
308新增: let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
309新增: return ["input": AXIsProcessTrustedWithOptions(options)]
310新增: case "frame":
311新增: if input.wait != true && input.refresh != true && MacWindowStream.shared.unchanged(after: input.after) {
312新增: return ["unchanged": true, "sequence": input.after!]
313新增: }
314新增: let (window, filter) = try await selectedWindow()
315新增: if input.width != nil || input.height != nil || input.scale != nil {
316新增: guard let width=input.width, let height=input.height, let scale=input.scale else { throw Failure(8,"invalid_input") }
317新增: let capture = filter ?? SCContentFilter(desktopIndependentWindow: window)
318新增: let canvas = ClaudeCanvasSession.shared
319新增: let layout = try await canvas.layout(window, filter:capture, width:width, height:height, scale:scale)
320新增: // A window object from before AX resizing still describes the old
321新增: // surface. Reacquire that exact window before the first new frame.
322新增: var target = window, source = capture
323新增: if abs(window.frame.width - layout.frame.width) >= 1 || abs(window.frame.height - layout.frame.height) >= 1 {
324新增: let (fresh, selection) = try await selectedWindow()
325新增: guard fresh.windowID == layout.id, fresh.owningApplication?.processID == layout.pid else {
326新增: throw Failure(7, "window_changed")
327新增: }
328新增: target = fresh
329新增: source = selection ?? SCContentFilter(desktopIndependentWindow: fresh)
330新增: }
331新增: let reply = try await canvas.capture(target, filter:source, layout:layout, after:input.after, wait:input.wait == true, binary:input.binary == true)
332新增: try consoleUser()
333新增: return reply
334新增: }
335新增: let data = try await screenshot(window, filter: filter)
336新增: guard data.count < 8 << 20, let owner = window.owningApplication, try claudePIDs().contains(owner.processID) else {
337新增: throw Failure(7, "window_changed")
338新增: }
339新增: try consoleUser()
340新增: return ["image": data.base64EncodedString(), "window": window.windowID, "pid": owner.processID]
341新增: case "input-reset":
342新增: inputSession.reset()
343新增: return ["ok": true]
344新增: case "ime":
345新增: let (window, _) = try await selectedWindow()
346新增: let canvas = try input.geometry.map { try ClaudeCanvasSession.shared.inputGeometry($0, window: window) }
347新增: return try inputSession.ime(input, window: window, canvas: canvas) { value in
348新增: if value.isEmpty { return }
349新增: var text = Request(action: "text")
350新增: text.pid = input.pid; text.window = input.window; text.geometry = input.geometry; text.text = value
351新增: try sendInput(text, window: window, canvas: canvas, inputSession: inputSession)
352新增: }
353新增: case "text", "key", "click", "scroll", "pointer":
354新增: let (window, _) = try await selectedWindow()
355新增: let canvas = try input.geometry.map { try ClaudeCanvasSession.shared.inputGeometry($0, window:window) }
356新增: try sendInput(input, window: window, canvas:canvas, inputSession: inputSession)
357新增: return ["ok": true]
358新增: case "project-frame", "project-click":
359新增: guard let path = input.project else { throw Failure(7, "no_project_panel") }
360新增: let panel = try pendingProjectPanel(path)
361新增: let window = try await visibleProjectPanel(panel)
362新增: if input.action == "project-click" {
363新增: guard input.nonce == panel.nonce, try pendingProjectPanel(path) == panel else { throw Failure(7, "window_changed") }
364新增: try sendInput(input, window: window)
365新增: for _ in 0..<16 {
366新增: try await Task.sleep(nanoseconds: 100_000_000)
367新增: if (try? pendingProjectPanel(path)) != panel { return ["ok": true] }
368新增: }
369新增: throw Failure(8, "project_panel_still_open")
370新增: }
371新增: let data = try await screenshot(window)
372新增: guard data.count < 8 << 20, try pendingProjectPanel(path) == panel else { throw Failure(7, "window_changed") }
373新增: try consoleUser()
374新增: return ["image": data.base64EncodedString(), "window": panel.windowNumber, "pid": panel.pid, "nonce": panel.nonce]
375新增: default: throw Failure(8, "unknown_action")
376新增: }
377新增:}
378新增:
379新增:private func respond(_ fd: Int32) async {
380新增: let inputSession = await MainActor.run { MacWindowInputSession() }
381新增: await respondConnection(fd, inputSession: inputSession)
382新增: await MainActor.run { inputSession.reset() }
383新增:}
384新增:
385新增:private func respondConnection(_ fd: Int32, inputSession: MacWindowInputSession) async {
386新增: let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
387新增: var timeout = timeval(tv_sec: 6, tv_usec: 0)
388新增: setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout)))
389新增: setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout)))
390新增: var peer = uid_t(), group = gid_t()
391新增: guard getpeereid(fd, &peer, &group) == 0, peer == getuid() else { return }
392新增: var body = Data()
393新增: do {
394新增: repeat {
395新增: while !body.contains(10) {
396新增: var chunk = [UInt8](repeating: 0, count: (64 << 10) - body.count)
397新增: let count = Darwin.read(fd, &chunk, chunk.count)
398新增: if count < 0 && errno == EINTR { continue }
399新增: guard count > 0 else { return }
400新增: body.append(contentsOf: chunk.prefix(count))
401新增: guard body.count < (64 << 10) || body.contains(10) else { return }
402新增: }
403新增: let line = body.prefix(while: { $0 != 10 })
404新增: let request = try JSONDecoder().decode(Request.self, from: line)
405新增: body.removeFirst(line.count + 1)
406新增: if request.action == "audio-capture" {
407新增: guard body.isEmpty else { return }
408新增: await MacAudioCapture.respond(fd)
409新增: return
410新增: }
411新增: var reply: [String:Any]
412新增: do {
413新增: if request.action == "paste-image" {
414新增: guard let length = request.length, length > 0, length <= 20 * 1024 * 1024, body.count <= length else { throw Failure(8, "attachment_size_limit") }
415新增: let (window, _) = try await selectedWindow()
416新增: guard request.pid == window.owningApplication?.processID, request.window == window.windowID else { throw Failure(7, "window_changed") }
417新增: var image = body
418新增: body.removeAll()
419新增: while image.count < length {
420新增: guard let chunk = try file.read(upToCount: min(65536, length - image.count)), !chunk.isEmpty else { throw Failure(8, "attachment_incomplete") }
421新增: image.append(chunk)
422新增: }
423新增: reply = try await MacDesktopFiles.shared.pasteImage(image, window: window)
424新增: } else { reply = try await handle(request, inputSession: inputSession) }
425新增: }
426新增: catch {
427新增: let reason = (error as? Failure)?.message.components(separatedBy: ":").first ?? "window_unavailable"
428新增: GuestDiagnostic.record("window", reason)
429新增: reply = ["error": reason]
430新增: }
431新增: if request.binary == true && request.action == "frame" {
432新增: let pixels = reply.removeValue(forKey: "imageBytes") as? Data ?? Data()
433新增: reply["imageLength"] = pixels.count
434新增: let header = try JSONSerialization.data(withJSONObject: reply)
435新增: var length = UInt32(header.count).bigEndian
436新增: try file.write(contentsOf: withUnsafeBytes(of: &length) { Data($0) })
437新增: try file.write(contentsOf: header)
438新增: try file.write(contentsOf: pixels)
439新增: } else {
440新增: var data = try JSONSerialization.data(withJSONObject: reply)
441新增: data.append(10)
442新增: try file.write(contentsOf: data)
443新增: }
444新增: if request.keepAlive != true { return }
445新增: } while true
446新增: } catch {
447新增: let reason = (error as? Failure)?.message.components(separatedBy: ":").first ?? "window_unavailable"
448新增: GuestDiagnostic.record("window", reason)
449新增: if let data = try? JSONSerialization.data(withJSONObject: ["error": reason]) { try? file.write(contentsOf: data) }
450新增: }
451新增:}
452新增:
453新增:@main
454新增:struct ClaudeWindowService {
455新增: static func main() {
456新增: if CommandLine.arguments.dropFirst() == ["--phone-self-test"] {
457新增: do { try MacPhoneDesktop.selfTest(); return }
458新增: catch { fputs("macOS phone desktop self-test failed\n", stderr); exit(1) }
459新增: }
460新增: if CommandLine.arguments.dropFirst() == ["--audio-self-test"] {
461新增: do { try MacAudioCapture.selfTest(); return }
462新增: catch { fputs("macOS audio self-test failed\n", stderr); exit(1) }
463新增: }
464新增: guard (try? requireGuest()) != nil, (try? consoleUser()) != nil else { exit(2) }
465新增: _ = signal(SIGPIPE, SIG_IGN)
466新增: let storage = UnsafeMutablePointer<UnsafeMutablePointer<Int32>>.allocate(capacity: 1)
467新增: var count: Int = 0
468新增: guard launch_activate_socket("Window", storage, &count) == 0, count == 1 else { exit(3) }
469新增: let sockets = storage.pointee
470新增: storage.deallocate()
471新增: let listener = sockets[0]
472新增: free(sockets)
473新增: GuestDiagnostic.record("window", "started")
474新增: NSApplication.shared.setActivationPolicy(.accessory)
475新增: DispatchQueue.global(qos: .userInitiated).async {
476新增: let connections = DispatchSemaphore(value: 16)
477新增: while true {
478新增: connections.wait()
479新增: let fd = accept(listener, nil, nil)
480新增: if fd < 0 { connections.signal(); if errno == EINTR { continue }; exit(4) }
481新增: Task { await respond(fd); connections.signal() }
482新增: }
483新增: }
484新增: NSApplication.shared.run()
485新增: }
486新增:}
新增scripts/guest-os/macos-cli-browser.mjs+47 −0看文件
@@ -0,0 +1,47 @@
1新增:// Carries only Claude login links between processes owned by the ordinary guest user.
2新增:import net from "node:net";
3新增:import fs from "node:fs/promises";
4新增:import path from "node:path";
5新增:
6新增:export async function installMacOSCLIBrowser(data, dispatch) {
7新增: const directory = path.join(data, "Login");
8新增: await fs.mkdir(directory, { mode: 0o700, recursive: true });
9新增: const dir = await fs.lstat(directory);
10新增: if (!dir.isDirectory() || dir.uid !== process.getuid() || (dir.mode & 0o077)) throw new Error("Invalid login directory");
11新增: const address = path.join(directory, "open.sock");
12新增: const serve = net.createServer({ allowHalfOpen: true }, socket => {
13新增: let input = "", size = 0;
14新增: socket.setTimeout(15000, () => socket.destroy());
15新增: socket.on("error", () => {});
16新增: socket.setEncoding("utf8");
17新增: socket.on("data", chunk => {
18新增: size += Buffer.byteLength(chunk);
19新增: if (size > 12288) socket.destroy();
20新增: else input += chunk;
21新增: });
22新增: socket.on("end", async () => {
23新增: try {
24新增: const { action, login, url } = JSON.parse(input);
25新增: if (!["login-open", "login-finish"].includes(action) || !/^[0-9a-f]{24}$/.test(login)) throw new Error();
26新增: const result = await dispatch({ method: "POST", path: "/" + action, input: { login, url } });
27新增: socket.end(result?.error ? "ERR" : "OK");
28新增: } catch { socket.end("ERR"); }
29新增: });
30新增: });
31新增: // Publish a fresh socket after its permissions are set. A replaced process
32新增: // retains its own inode and cannot remove its successor's socket on exit.
33新增: const temporary = path.join(directory, ".open-" + process.pid);
34新增: await new Promise((resolve, reject) => { serve.once("error", reject); serve.listen(temporary, resolve); });
35新增: try {
36新增: await fs.chmod(temporary, 0o600);
37新增: const old = await fs.lstat(address).catch(e => { if (e.code !== "ENOENT") throw e; });
38新增: if (old && (!old.isSocket() || old.uid !== dir.uid)) throw new Error("Invalid login socket");
39新增: await fs.rename(temporary, address);
40新增: } catch (error) { serve.close(); throw error; }
41新增: const { ino } = await fs.lstat(address);
42新增: return async () => {
43新增: await new Promise(resolve => serve.close(resolve));
44新增: const current = await fs.lstat(address).catch(() => null);
45新增: if (current?.ino === ino) await fs.unlink(address);
46新增: };
47新增:}
新增scripts/guest-os/macos-cli.py+55 −0看文件
@@ -0,0 +1,55 @@
1新增:"""Run the common Claude session protocol in the ordinary macOS guest account."""
2新增:import importlib.util
3新增:import json
4新增:import os
5新增:from pathlib import Path
6新增:import re
7新增:import sys
8新增:
9新增:
10新增:source = Path(__file__).resolve().with_name("cli_channel.py")
11新增:spec = importlib.util.spec_from_file_location("cli_channel", source)
12新增:cli_channel = importlib.util.module_from_spec(spec)
13新增:spec.loader.exec_module(cli_channel)
14新增:os.environ["PATH"] = "/usr/local/libexec/cage-cli/bin:/usr/local/bin:" + os.environ.get("PATH", os.defpath)
15新增:
16新增:
17新增:def macos_launch(request):
18新增: prefix = request["prefix"]
19新增: managed = (len(prefix) == 5 and prefix[0] == "env" and re.fullmatch(r"CAGE_CLAUDE_SUBJECT=[a-f0-9]{64}", prefix[1])
20新增: and prefix[2:4] == ["/usr/local/bin/cage-claude-account", "run"]
21新增: and (prefix[4] == "default" or re.fullmatch("[a-f0-9]{24}", prefix[4])))
22新增: ccs = len(prefix) == 2 and prefix[0] == "ccs" and re.fullmatch("[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}", prefix[1])
23新增: if prefix != ["claude"] and not managed and not ccs:
24新增: raise ValueError("不支持的客机 Claude 启动命令")
25新增: # Adopt a nested transcript only inside the same approved mount, without
26新增: # traversing symbolic links or interpreting a saved path in a shell.
27新增: subdir = request.get("project_subdir")
28新增: if subdir:
29新增: directory = os.open(".", os.O_RDONLY | os.O_DIRECTORY)
30新增: try:
31新增: device = os.fstat(directory).st_dev
32新增: for part in subdir.split("/"):
33新增: if part in ("", ".", ".."):
34新增: raise ValueError("会话目录无效")
35新增: child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory)
36新增: os.close(directory)
37新增: directory = child
38新增: if os.fstat(directory).st_dev != device:
39新增: raise ValueError("会话目录不属于当前挂载")
40新增: os.fchdir(directory)
41新增: finally:
42新增: os.close(directory)
43新增: return cli_channel.launch(request)
44新增:
45新增:
46新增:if __name__ == "__main__":
47新增: if sys.argv[1] == "macos-launch":
48新增: # An ordinary CLI exit leaves an interactive guest shell in this
49新增: # project. Pass the launch JSON as a literal positional argument.
50新增: script = '"$1" -I "$2" macos-exec "$3"; exec /bin/zsh -i'
51新增: os.execv("/bin/zsh", ["zsh", "-c", script, "cage-claude", sys.executable, str(Path(__file__).resolve()), sys.argv[2]])
52新增: if sys.argv[1] == "macos-exec":
53新增: os.umask(0o077)
54新增: sys.exit(macos_launch(json.loads(sys.argv[2])) or 0)
55新增: sys.exit(cli_channel.main() or 0)
新增scripts/guest-os/macos-desktop-downloads.swift+256 −0看文件
@@ -0,0 +1,256 @@
1新增:import AppKit
2新增:import CoreServices
3新增:
4新增:@_silgen_name("cage_file_has_writer") private func cageFileHasWriter(_ pid: Int32, _ path: UnsafePointer<CChar>) -> Int32
5新增:
6新增:@MainActor
7新增:final class MacDesktopDownloads {
8新增: static let shared = MacDesktopDownloads(directory: FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support/dev.cage.DesktopDownloads", isDirectory: true))
9新增: private struct Record: Codable {
10新增: let id: String
11新增: let name: String
12新增: var state = "downloading"
13新增: var error = ""
14新增: var size: Int64 = 0
15新增: var modified: Int64 = 0
16新增: var started = Date()
17新增: }
18新增: private struct Transfer {
19新增: let fd: Int32
20新增: let record: Record
21新增: let epoch: UInt64
22新增: var sequence = 0
23新增: var offset: Int64 = 0
24新增: var used = Date()
25新增: }
26新增: private var records: [Record] = []
27新增: private var transfers: [String: Transfer] = [:]
28新增: private var watches: [String: MacDownloadWatch] = [:]
29新增: private var root: URL?
30新增: private let baseDirectory: URL
31新增: private var transferTimer: Timer?
32新增: private let timestamp = ISO8601DateFormatter()
33新增:
34新增: init(directory: URL) { baseDirectory = directory }
35新增: deinit {
36新增: for watch in watches.values { watch.stop() }
37新增: for transfer in transfers.values { close(transfer.fd) }
38新增: transferTimer?.invalidate()
39新增: }
40新增:
41新增: nonisolated static func validName(_ name: String) -> Bool {
42新增: !name.isEmpty && name.utf8.count <= 255 && name != "." && name != ".." &&
43新增: name.rangeOfCharacter(from: CharacterSet(charactersIn: "/\\").union(.controlCharacters)) == nil
44新增: }
45新增:
46新增: private func directory() throws -> URL {
47新增: if let root { return root }
48新增: try FileManager.default.createDirectory(at: baseDirectory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
49新增: var info = stat()
50新增: guard lstat(baseDirectory.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR, info.st_uid == getuid(),
51新增: info.st_mode & 0o022 == 0, let canonical = realpath(baseDirectory.path, nil) else { throw Failure(8, "desktop_download_directory_invalid") }
52新增: let root = URL(fileURLWithPath: String(cString: canonical), isDirectory: true)
53新增: free(canonical)
54新增: let manifest = root.appendingPathComponent("downloads.json")
55新增: if FileManager.default.fileExists(atPath: manifest.path) {
56新增: var stored = stat()
57新增: guard lstat(manifest.path, &stored) == 0, stored.st_mode & S_IFMT == S_IFREG, stored.st_uid == getuid(), stored.st_size <= 1 << 20 else {
58新增: throw Failure(8, "desktop_download_catalog_invalid")
59新增: }
60新增: let data = try Data(contentsOf: manifest, options: .mappedIfSafe)
61新增: guard data.count <= 1 << 20 else { throw Failure(8, "desktop_download_catalog_invalid") }
62新增: records = try JSONDecoder().decode([Record].self, from: data).suffix(100).filter { UUID(uuidString: $0.id) != nil && Self.validName($0.name) }
63新增: for index in records.indices where records[index].state == "downloading" {
64新增: records[index].state = "failed"
65新增: records[index].error = "保存过程被中断,请从 Claude Desktop 重新下载。"
66新增: }
67新增: }
68新增: self.root = root
69新增: return root
70新增: }
71新增: private func source(_ record: Record) throws -> URL { try directory().appendingPathComponent(record.id, isDirectory: true).appendingPathComponent(record.name) }
72新增: private func persist() throws {
73新增: let path = try directory().appendingPathComponent("downloads.json")
74新增: try JSONEncoder().encode(Array(records.suffix(100))).write(to: path, options: .atomic)
75新增: try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path.path)
76新增: }
77新增: private func openSource(_ record: Record) throws -> (Int32, stat) {
78新增: let path = try source(record).path
79新增: let fd = open(path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
80新增: guard fd >= 0 else { throw Failure(8, "desktop_download_unavailable") }
81新增: var info = stat(), actual = [CChar](repeating: 0, count: Int(MAXPATHLEN))
82新增: guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_size <= 2 * 1024 * 1024 * 1024,
83新增: fcntl(fd, F_GETPATH, &actual) == 0, String(cString: actual) == path else {
84新增: close(fd); throw Failure(8, "desktop_download_file_invalid")
85新增: }
86新增: return (fd, info)
87新增: }
88新增: private func modified(_ info: stat) -> Int64 { Int64(info.st_mtimespec.tv_sec) * 1_000_000_000 + Int64(info.st_mtimespec.tv_nsec) }
89新增:
90新增: private func expireTransfers() {
91新增: let epoch = try? MacGUISession.shared.validate()
92新增: for (key, transfer) in transfers where epoch != transfer.epoch || Date().timeIntervalSince(transfer.used) > 120 {
93新增: close(transfer.fd); transfers.removeValue(forKey: key)
94新增: }
95新增: if transfers.isEmpty { transferTimer?.invalidate(); transferTimer = nil }
96新增: }
97新增:
98新增: func reserve(name: String, pid: Int32, submit: (String) async throws -> Void) async throws {
99新增: _ = try directory()
100新增: guard Self.validName(name), records.filter({ $0.state == "downloading" }).count < 12 else { throw Failure(8, "desktop_download_limit") }
101新增: let record = Record(id: UUID().uuidString.lowercased(), name: name)
102新增: let path = try source(record)
103新增: try FileManager.default.createDirectory(at: path.deletingLastPathComponent(), withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
104新增: let watcher = try MacDownloadWatch(directory: path.deletingLastPathComponent().path, file: path.path) { [weak self] valid in
105新增: Task { @MainActor in
106新增: if valid { await self?.complete(record.id, pid: pid) }
107新增: else { self?.fail(record.id, message: "保存通知已中断,请从 Claude Desktop 重新下载。") }
108新增: }
109新增: }
110新增: while records.count >= 100, let oldest = records.firstIndex(where: { $0.state != "downloading" }) { records.remove(at: oldest) }
111新增: records.append(record); watches[record.id] = watcher
112新增: do { try persist(); try await submit(path.path) }
113新增: catch { fail(record.id, message: "客机保存窗口未接收文件位置,请重新下载。"); throw error }
114新增: watcher.expiry = Task { @MainActor [weak self] in
115新增: try? await Task.sleep(nanoseconds: 1800 * 1_000_000_000)
116新增: if self?.records.first(where: { $0.id == record.id })?.state == "downloading" {
117新增: self?.fail(record.id, message: "未能确认文件保存完成,请从 Claude Desktop 重新下载。")
118新增: }
119新增: }
120新增: }
121新增: private func fail(_ id: String, message: String) {
122新增: watches.removeValue(forKey: id)?.stop()
123新增: if let index = records.firstIndex(where: { $0.id == id }) {
124新增: records[index].state = "failed"; records[index].error = message
125新增: try? persist()
126新增: }
127新增: }
128新增: private func complete(_ id: String, pid: Int32) async {
129新增: guard let record = records.first(where: { $0.id == id && $0.state == "downloading" }),
130新增: let watch = watches[id], !watch.completing else { return }
131新增: watch.completing = true
132新增: defer { watch.completing = false }
133新增: while Date().timeIntervalSince(record.started) < 1800 {
134新增: guard records.first(where: { $0.id == id })?.state == "downloading" else { return }
135新增: do {
136新增: let path = try source(record).path
137新增: let writing = path.withCString { cageFileHasWriter(pid, $0) }
138新增: if writing == 0 && !FileManager.default.fileExists(atPath: path + ".crdownload") {
139新增: let (fd, info) = try openSource(record)
140新增: defer { close(fd) }
141新增: guard let index = records.firstIndex(where: { $0.id == id }) else { return }
142新增: records[index].size = info.st_size; records[index].modified = modified(info); records[index].state = "saved"
143新增: try persist(); watches.removeValue(forKey: id)?.stop(); return
144新增: }
145新增: } catch { }
146新增: try? await Task.sleep(nanoseconds: 250_000_000)
147新增: }
148新增: fail(id, message: "未能确认文件保存完成,请从 Claude Desktop 重新下载。")
149新增: }
150新增: func snapshot() throws -> [[String: Any]] {
151新增: _ = try directory()
152新增: return records.suffix(100).reversed().map { record in
153新增: ["id": record.id, "name": record.name, "target": "desktop", "state": record.state,
154新增: "receivedBytes": record.size, "totalBytes": record.size, "retryable": false,
155新增: "error": record.error, "startedAt": timestamp.string(from: record.started)]
156新增: }
157新增: }
158新增: func find(path: String) throws -> (id: String, directory: Bool)? {
159新增: _ = try directory()
160新增: for record in records {
161新增: let source = try source(record)
162新增: if source.path == path { return (record.id, false) }
163新增: if source.deletingLastPathComponent().path == path { return (record.id, true) }
164新增: }
165新增: return nil
166新增: }
167新增: func read(_ input: Request) throws -> [String: Any] {
168新增: let epoch = try MacGUISession.shared.validate()
169新增: _ = try directory()
170新增: for (key, transfer) in transfers where transfer.epoch != epoch || Date().timeIntervalSince(transfer.used) > 120 {
171新增: close(transfer.fd); transfers.removeValue(forKey: key)
172新增: }
173新增: if input.action == "files-download-retry" {
174新增: guard let record = records.first(where: { $0.id == input.id }), record.state == "saved" else { throw Failure(8, "desktop_download_incomplete") }
175新增: let (fd, info) = try openSource(record)
176新增: defer { close(fd) }
177新增: guard info.st_size == record.size, modified(info) == record.modified else { throw Failure(8, "desktop_download_changed") }
178新增: return ["ok": true]
179新增: }
180新增: if input.action == "files-download-open" {
181新增: guard let record = records.first(where: { $0.id == input.id && $0.state == "saved" }), transfers.count < 12 else { throw Failure(8, "desktop_download_unavailable") }
182新增: let (fd, info) = try openSource(record)
183新增: guard info.st_size == record.size, modified(info) == record.modified else { close(fd); throw Failure(8, "desktop_download_changed") }
184新增: let key = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
185新增: transfers[key] = Transfer(fd: fd, record: record, epoch: epoch)
186新增: if transferTimer == nil {
187新增: transferTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] timer in
188新增: Task { @MainActor in
189新增: guard let self else { timer.invalidate(); return }
190新增: self.expireTransfers()
191新增: }
192新增: }
193新增: }
194新增: return ["transfer": key, "size": record.size, "name": record.name]
195新增: }
196新增: let key = input.transfer ?? ""
197新增: if input.action == "files-download-close" {
198新增: if let transfer = transfers.removeValue(forKey: key) { close(transfer.fd) }
199新增: return ["ok": true]
200新增: }
201新增: guard input.action == "files-download-read", var transfer = transfers[key], transfer.sequence == input.sequence else { throw Failure(8, "desktop_download_transfer_invalid") }
202新增: var info = stat()
203新增: guard fstat(transfer.fd, &info) == 0, info.st_size == transfer.record.size, modified(info) == transfer.record.modified else {
204新增: close(transfer.fd); transfers.removeValue(forKey: key); throw Failure(8, "desktop_download_changed")
205新增: }
206新增: var data = Data(count: 64 << 10)
207新增: let count = data.withUnsafeMutableBytes { Darwin.read(transfer.fd, $0.baseAddress, $0.count) }
208新增: guard count >= 0 else { throw Failure(8, "desktop_download_read_failed") }
209新增: guard fstat(transfer.fd, &info) == 0, info.st_size == transfer.record.size, modified(info) == transfer.record.modified else {
210新增: close(transfer.fd); transfers.removeValue(forKey: key); throw Failure(8, "desktop_download_changed")
211新增: }
212新增: data.count = count; transfer.offset += Int64(count); transfer.sequence += 1; transfer.used = Date()
213新增: let eof = transfer.offset == transfer.record.size
214新增: if eof { close(transfer.fd); transfers.removeValue(forKey: key) } else { transfers[key] = transfer }
215新增: return ["data": data.base64EncodedString(), "sequence": transfer.sequence, "eof": eof]
216新增: }
217新增:}
218新增:
219新增:private final class MacDownloadWatch {
220新增: private var stream: FSEventStreamRef?
221新增: private let file: String
222新增: private let changed: (Bool) -> Void
223新增: var completing = false
224新增: var expiry: Task<Void, Never>?
225新增: init(directory: String, file: String, changed: @escaping (Bool) -> Void) throws {
226新增: self.file = file; self.changed = changed
227新增: var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(self).toOpaque(), retain: { raw in
228新增: guard let raw else { return nil }
229新增: _ = Unmanaged<MacDownloadWatch>.fromOpaque(raw).retain()
230新增: return raw
231新增: }, release: { raw in
232新增: if let raw { Unmanaged<MacDownloadWatch>.fromOpaque(raw).release() }
233新增: }, copyDescription: nil)
234新增: stream = FSEventStreamCreate(nil, { _, raw, count, paths, flags, _ in
235新增: guard let raw else { return }
236新增: let watcher = Unmanaged<MacDownloadWatch>.fromOpaque(raw).takeUnretainedValue()
237新增: let names = Unmanaged<NSArray>.fromOpaque(paths).takeUnretainedValue() as? [String] ?? []
238新增: let failure = FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs | kFSEventStreamEventFlagUserDropped | kFSEventStreamEventFlagKernelDropped | kFSEventStreamEventFlagRootChanged)
239新增: for index in 0..<count where flags[index] & failure != 0 { watcher.changed(false); return }
240新增: for index in 0..<min(count, names.count) where names[index] == watcher.file {
241新增: if flags[index] & FSEventStreamEventFlags(kFSEventStreamEventFlagItemModified | kFSEventStreamEventFlagItemRenamed) != 0 { watcher.changed(true) }
242新增: }
243新增: }, &context, [directory] as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 0.1,
244新增: FSEventStreamCreateFlags(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagWatchRoot))
245新增: guard let stream else { throw Failure(8, "desktop_download_watch_failed") }
246新增: FSEventStreamSetDispatchQueue(stream, DispatchQueue.main)
247新增: guard FSEventStreamStart(stream) else { stop(); throw Failure(8, "desktop_download_watch_failed") }
248新增: }
249新增: func stop() {
250新增: expiry?.cancel(); expiry = nil
251新增: guard let stream else { return }
252新增: self.stream = nil
253新增: FSEventStreamStop(stream); FSEventStreamInvalidate(stream); FSEventStreamRelease(stream)
254新增: }
255新增: deinit { stop() }
256新增:}
新增scripts/guest-os/macos-desktop-files.swift+557 −0看文件
@@ -0,0 +1,557 @@
1新增:// Attachments are bound to one verified Claude window and private guest caches.
2新增:import AppKit
3新增:import ScreenCaptureKit
4新增:
5新增:private func fileAttribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? {
6新增: var value: CFTypeRef?
7新增: return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil
8新增:}
9新增:
10新增:private func fileChildren(_ element: AXUIElement) -> [AXUIElement] {
11新增: (fileAttribute(element, kAXChildrenAttribute) as? [AXUIElement] ?? []) +
12新增: (fileAttribute(element, "AXSheets") as? [AXUIElement] ?? [])
13新增:}
14新增:
15新增:private func filePanelButton(_ panel: AXUIElement, cancel: Bool = false) -> AXUIElement? {
16新增: if let value = fileAttribute(panel, cancel ? kAXCancelButtonAttribute : kAXDefaultButtonAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() {
17新增: return (value as! AXUIElement)
18新增: }
19新增: var pending = fileChildren(panel), visited = 0
20新增: while visited < pending.count && visited < 1024 {
21新增: let element = pending[visited]; visited += 1
22新增: if fileAttribute(element, kAXRoleAttribute) as? String == kAXButtonRole,
23新增: fileAttribute(element, "AXIdentifier") as? String == (cancel ? "CancelButton" : "OKButton") { return element }
24新增: pending.append(contentsOf: fileChildren(element))
25新增: }
26新增: return nil
27新增:}
28新增:
29新增:private func filePanelPresent(_ panel: AXUIElement, pid: pid_t) -> Bool {
30新增: var pending = fileAttribute(AXUIElementCreateApplication(pid), kAXWindowsAttribute) as? [AXUIElement] ?? [], visited = 0
31新增: while visited < pending.count && visited < 1024 {
32新增: let element = pending[visited]; visited += 1
33新增: if CFEqual(element, panel) { return true }
34新增: pending.append(contentsOf: fileChildren(element))
35新增: }
36新增: return false
37新增:}
38新增:
39新增:private func filePanelFocused(_ panel: AXUIElement, pid: pid_t) -> Bool {
40新增: var current = fileAttribute(AXUIElementCreateApplication(pid), kAXFocusedUIElementAttribute)
41新增: for _ in 0..<32 {
42新增: guard let value = current, CFGetTypeID(value) == AXUIElementGetTypeID() else { return false }
43新增: let element = value as! AXUIElement
44新增: if CFEqual(element, panel) { return true }
45新增: current = fileAttribute(element, kAXParentAttribute)
46新增: }
47新增: return false
48新增:}
49新增:
50新增:private func containsFileBrowser(_ element: AXUIElement) -> Bool {
51新增: var pending = fileChildren(element)
52新增: var visited = 0
53新增: while !pending.isEmpty && visited < 1024 {
54新增: let child = pending.removeLast()
55新增: visited += 1
56新增: if [kAXOutlineRole, kAXBrowserRole, kAXTableRole].contains(fileAttribute(child, kAXRoleAttribute) as? String ?? "") { return true }
57新增: pending.append(contentsOf: fileChildren(child))
58新增: }
59新增: return false
60新增:}
61新增:
62新增:private func selectedFilePaths(_ panel: AXUIElement, expected: Set<String>) -> Set<String> {
63新增: var pending = [panel], selected: [AXUIElement] = []
64新增: var visited = 0
65新增: while !pending.isEmpty && visited < 2048 {
66新增: let element = pending.removeLast()
67新增: visited += 1
68新增: selected.append(contentsOf: fileAttribute(element, kAXSelectedRowsAttribute) as? [AXUIElement] ?? [])
69新增: selected.append(contentsOf: fileAttribute(element, kAXSelectedChildrenAttribute) as? [AXUIElement] ?? [])
70新增: pending.append(contentsOf: fileChildren(element))
71新增: }
72新增: var paths = Set<String>()
73新增: func selectedPath(_ value: String) {
74新增: let path: String
75新增: if let canonical = realpath(value, nil) {
76新增: path = String(cString: canonical); free(canonical)
77新增: } else { path = URL(fileURLWithPath: value).standardizedFileURL.path }
78新增: let prefix = path.hasSuffix("/") ? path : path + "/"
79新增: // Column view also selects each ancestor directory. Every other
80新增: // selected file must participate in the exact selection comparison.
81新增: if expected.contains(where: { $0.hasPrefix(prefix) }) { return }
82新增: paths.insert(path)
83新增: }
84新增: visited = 0
85新增: while !selected.isEmpty && visited < 4096 {
86新增: let element = selected.removeLast()
87新增: visited += 1
88新增: for attribute in [kAXURLAttribute, kAXValueAttribute] {
89新增: let raw = fileAttribute(element, attribute)
90新增: if let url = raw as? URL, url.isFileURL { selectedPath(url.path) }
91新增: if let value = raw as? String {
92新增: if value.hasPrefix("/") { selectedPath(value) }
93新增: if let url = URL(string: value), url.isFileURL { selectedPath(url.path) }
94新增: }
95新增: }
96新增: selected.append(contentsOf: fileChildren(element))
97新增: }
98新增: return paths
99新增:}
100新增:
101新增:private func openFilePanel(_ pid: pid_t) -> AXUIElement? {
102新增: var pending = fileAttribute(AXUIElementCreateApplication(pid), kAXWindowsAttribute) as? [AXUIElement] ?? []
103新增: var visited = 0
104新增: while !pending.isEmpty && visited < 2048 {
105新增: let element = pending.removeLast()
106新增: visited += 1
107新增: let role = fileAttribute(element, kAXRoleAttribute) as? String
108新增: let subrole = fileAttribute(element, kAXSubroleAttribute) as? String
109新增: if role == kAXSheetRole || subrole == kAXDialogSubrole,
110新增: let button = filePanelButton(element), filePanelButton(element, cancel: true) != nil,
111新增: let title = fileAttribute(button, kAXTitleAttribute) as? String,
112新增: ["Open", "Choose", "Select", "打开", "開啟", "选择", "選擇"].contains(title), containsFileBrowser(element) {
113新增: return element
114新增: }
115新增: pending.append(contentsOf: fileChildren(element))
116新增: }
117新增: return nil
118新增:}
119新增:
120新增:private func saveFilePanel(_ pid: pid_t) -> (AXUIElement, AXUIElement)? {
121新增: var pending = fileAttribute(AXUIElementCreateApplication(pid), kAXWindowsAttribute) as? [AXUIElement] ?? []
122新增: var visited = 0
123新增: while !pending.isEmpty && visited < 2048 {
124新增: let panel = pending.removeLast()
125新增: visited += 1
126新增: let role = fileAttribute(panel, kAXRoleAttribute) as? String
127新增: let subrole = fileAttribute(panel, kAXSubroleAttribute) as? String
128新增: if (role == kAXSheetRole || subrole == kAXDialogSubrole),
129新增: let button = filePanelButton(panel),
130新增: let title = fileAttribute(button, kAXTitleAttribute) as? String,
131新增: ["Save", "保存", "儲存", "Enregistrer", "Sichern", "Guardar", "Сохранить", "저장"].contains(title),
132新增: filePanelButton(panel, cancel: true) != nil {
133新增: var children = fileChildren(panel), count = 0
134新增: while count < children.count && count < 1024 {
135新增: let element = children[count]
136新增: count += 1
137新增: if fileAttribute(element, kAXRoleAttribute) as? String == kAXTextFieldRole,
138新增: fileAttribute(element, "AXIdentifier") as? String == "saveAsNameTextField",
139新增: let name = fileAttribute(element, kAXValueAttribute) as? String, MacDesktopDownloads.validName(name) {
140新增: return (panel, element)
141新增: }
142新增: children.append(contentsOf: fileChildren(element))
143新增: }
144新增: }
145新增: pending.append(contentsOf: fileChildren(panel))
146新增: }
147新增: return nil
148新增:}
149新增:
150新增:private func clipboardRequest(_ request: [String: Any]) async throws -> [String: Any] {
151新增: let data = try JSONSerialization.data(withJSONObject: request) + Data([10])
152新增: guard data.count <= 30 * 1024 * 1024 else { throw Failure(8, "attachment_size_limit") }
153新增: return try await withCheckedThrowingContinuation { continuation in
154新增: DispatchQueue.global(qos: .userInitiated).async {
155新增: let process = Process()
156新增: process.executableURL = URL(fileURLWithPath: "/Applications/Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard")
157新增: process.arguments = ["--client", "request"]
158新增: let input = Pipe(), output = Pipe()
159新增: process.standardInput = input
160新增: process.standardOutput = output
161新增: process.standardError = FileHandle.nullDevice
162新增: let timeout = DispatchWorkItem { if process.isRunning { process.terminate() } }
163新增: defer { timeout.cancel(); try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() } }
164新增: do {
165新增: try process.run()
166新增: DispatchQueue.global().asyncAfter(deadline: .now() + 15, execute: timeout)
167新增: try input.fileHandleForWriting.write(contentsOf: data)
168新增: try input.fileHandleForWriting.close()
169新增: var reply = Data()
170新增: while let chunk = try output.fileHandleForReading.read(upToCount: 4096), !chunk.isEmpty {
171新增: reply.append(chunk)
172新增: guard reply.count <= 65536 else { throw Failure(7, "clipboard_reply_invalid") }
173新增: }
174新增: process.waitUntilExit()
175新增: guard process.terminationStatus == 0,
176新增: let value = try JSONSerialization.jsonObject(with: reply) as? [String: Any], value["error"] == nil else {
177新增: throw Failure(7, "clipboard_operation_failed")
178新增: }
179新增: continuation.resume(returning: value)
180新增: } catch { continuation.resume(throwing: error) }
181新增: }
182新增: }
183新增:}
184新增:
185新增:@MainActor
186新增:final class MacDesktopFiles {
187新增: static let shared = MacDesktopFiles()
188新增: private final class Batch {
189新增: let pid: pid_t
190新增: let window: CGWindowID
191新增: let kind: String
192新增: let panel: AXUIElement?
193新增: let focusedWindow: AXUIElement?
194新增: let focusedElement: AXUIElement?
195新增: let epoch: UInt64
196新增: let created = Date()
197新增: var files: [String] = []
198新增: var busy = false
199新增: init(pid: pid_t, window: CGWindowID, kind: String, epoch: UInt64, panel: AXUIElement? = nil) {
200新增: self.pid = pid; self.window = window; self.kind = kind; self.panel = panel
201新增: self.epoch = epoch
202新增: if let value = fileAttribute(AXUIElementCreateApplication(pid), kAXFocusedWindowAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() {
203新增: focusedWindow = (value as! AXUIElement)
204新增: } else { focusedWindow = nil }
205新增: if let value = fileAttribute(AXUIElementCreateApplication(pid), kAXFocusedUIElementAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() {
206新增: focusedElement = (value as! AXUIElement)
207新增: } else { focusedElement = nil }
208新增: }
209新增: }
210新增: private var batches: [String: Batch] = [:]
211新增: private var savingPanel: AXUIElement?
212新增: private struct OpenRequest {
213新增: let path: String
214新增: let action: String
215新增: let epoch: UInt64
216新增: let validate: () throws -> Void
217新增: let created = Date()
218新增: var claimed = false
219新增: }
220新增: private var opens: [String: OpenRequest] = [:]
221新增:
222新增: private func expireOpens() {
223新增: let epoch = try? MacGUISession.shared.validate()
224新增: opens = opens.filter { _, request in
225新增: epoch == request.epoch && Date().timeIntervalSince(request.created) < (request.claimed ? 1800 : 60)
226新增: }
227新增: }
228新增:
229新增: func queueOpen(path: String, action: String, validate: @escaping () throws -> Void) throws {
230新增: try queueOpen(paths: [path], action: action, validate: validate)
231新增: }
232新增:
233新增: func queueOpen(paths: [String], action: String, validate: @escaping () throws -> Void) throws {
234新增: guard !paths.isEmpty, paths.count <= 32, paths.allSatisfy({ ($0 as NSString).isAbsolutePath && $0.utf8.count <= 32768 && !$0.contains("\0") }),
235新增: ["open", "reveal"].contains(action) else { throw Failure(8, "file_open_request_invalid") }
236新增: let epoch = try MacGUISession.shared.validate()
237新增: expireOpens(); try validate()
238新增: guard opens.count + paths.count <= 32 else { throw Failure(8, "file_open_request_limit") }
239新增: for path in paths {
240新增: opens[UUID().uuidString.lowercased()] = OpenRequest(path: URL(fileURLWithPath: path).standardizedFileURL.path, action: action, epoch: epoch, validate: validate)
241新增: }
242新增: }
243新增:
244新增: func openSnapshot() -> [[String: String]] {
245新增: expireOpens()
246新增: return opens.filter { !$0.value.claimed }.map { ["id": $0.key] }
247新增: }
248新增:
249新增: func openAction(_ id: String, complete: Bool) throws -> [String: Any] {
250新增: expireOpens()
251新增: guard var request = opens[id] else { return [complete ? "ok" : "handled": true] }
252新增: if complete {
253新增: opens.removeValue(forKey: id)
254新增: try? request.validate()
255新增: return ["ok": true]
256新增: }
257新增: if request.claimed { return ["handled": true] }
258新增: do { try request.validate() }
259新增: catch { opens.removeValue(forKey: id); throw Failure(7, "file_open_target_changed") }
260新增: var result: [String: Any] = ["id": id, "action": request.action]
261新增: if let download = try MacDesktopDownloads.shared.find(path: request.path) {
262新增: result["download_id"] = download.id; result["directory"] = download.directory
263新增: } else { result["path"] = request.path }
264新增: request.claimed = true; opens[id] = request
265新增: return result
266新增: }
267新增:
268新增: private func valid(_ batch: Batch) throws {
269新增: try consoleUser()
270新增: try MacGUISession.shared.validate(batch.epoch)
271新增: guard AXIsProcessTrusted() else { throw Failure(9, "accessibility_permission") }
272新增: guard Date().timeIntervalSince(batch.created) < 1800, try claudePIDs().contains(batch.pid),
273新增: NSWorkspace.shared.frontmostApplication?.processIdentifier == batch.pid else { throw Failure(7, "window_changed") }
274新增: if let panel = batch.panel {
275新增: guard filePanelPresent(panel, pid: batch.pid), filePanelFocused(panel, pid: batch.pid) else { throw Failure(7, "file_dialog_changed") }
276新增: } else {
277新增: let windows = CGWindowListCopyWindowInfo([.optionIncludingWindow], batch.window) as? [[String: Any]]
278新增: guard let window = windows?.first, window[kCGWindowOwnerPID as String] as? Int32 == batch.pid,
279新增: window[kCGWindowIsOnscreen as String] as? Bool == true else { throw Failure(7, "window_changed") }
280新增: guard let focused = fileAttribute(AXUIElementCreateApplication(batch.pid), kAXFocusedWindowAttribute),
281新增: let original = batch.focusedWindow, CFEqual(focused, original),
282新增: let input = fileAttribute(AXUIElementCreateApplication(batch.pid), kAXFocusedUIElementAttribute),
283新增: let originalInput = batch.focusedElement, CFEqual(input, originalInput),
284新增: let position = fileAttribute(original, kAXPositionAttribute), CFGetTypeID(position) == AXValueGetTypeID(),
285新增: let size = fileAttribute(original, kAXSizeAttribute), CFGetTypeID(size) == AXValueGetTypeID(),
286新增: let bounds = window[kCGWindowBounds as String] as? [String: Any],
287新增: let frame = CGRect(dictionaryRepresentation: bounds as CFDictionary) else { throw Failure(7, "window_changed") }
288新增: var origin = CGPoint.zero, extent = CGSize.zero
289新增: guard AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(size as! AXValue, .cgSize, &extent),
290新增: abs(origin.x - frame.minX) < 2, abs(origin.y - frame.minY) < 2,
291新增: abs(extent.width - frame.width) < 2, abs(extent.height - frame.height) < 2 else { throw Failure(7, "window_changed") }
292新增: }
293新增: }
294新增:
295新增: private func batch(_ id: String) throws -> Batch {
296新增: guard UUID(uuidString: id) != nil, let value = batches[id] else { throw Failure(8, "attachment_request_invalid") }
297新增: try valid(value)
298新增: return value
299新增: }
300新增:
301新增: private func key(_ pid: pid_t, _ code: CGKeyCode, flags: CGEventFlags = [], panel: AXUIElement? = nil, epoch: UInt64? = nil) throws {
302新增: guard AXIsProcessTrusted(), try claudePIDs().contains(pid), NSWorkspace.shared.frontmostApplication?.processIdentifier == pid else {
303新增: throw Failure(7, "window_changed")
304新增: }
305新增: let source = CGEventSource(stateID: .privateState)
306新增: for down in [true, false] {
307新增: try consoleUser()
308新增: try MacGUISession.shared.validate(epoch)
309新增: guard NSWorkspace.shared.frontmostApplication?.processIdentifier == pid,
310新增: panel.map({ filePanelPresent($0, pid: pid) && filePanelFocused($0, pid: pid) }) ?? true else { throw Failure(7, "file_dialog_changed") }
311新增: guard let event = CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: down) else { throw Failure(8, "input_failed") }
312新增: event.flags = flags
313新增: if panel != nil {
314新增: // AppKit's Open/Save panel runs in an XPC service. Events sent
315新增: // only to the application PID do not reach its focused panel.
316新增: guard CGPreflightPostEventAccess() else { throw Failure(9, "accessibility_permission") }
317新增: event.post(tap: .cghidEventTap)
318新增: } else { event.postToPid(pid) }
319新增: }
320新增: }
321新增:
322新增: func start(window: SCWindow, kind: String) throws -> [String: Any] {
323新增: guard ["paste", "drop", "image"].contains(kind), let pid = window.owningApplication?.processID else { throw Failure(8, "attachment_request_invalid") }
324新增: for (id, value) in batches where Date().timeIntervalSince(value.created) >= 1800 {
325新增: batches.removeValue(forKey: id)
326新增: if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } }
327新增: }
328新增: guard batches.count < 12 else { throw Failure(8, "attachment_limit") }
329新增: let value = Batch(pid: pid, window: window.windowID, kind: kind, epoch: try MacGUISession.shared.validate())
330新增: try valid(value)
331新增: let id = UUID().uuidString.lowercased()
332新增: batches[id] = value
333新增: return ["ok": true, "id": id]
334新增: }
335新增:
336新增: func add(_ id: String, files: [String]) throws -> [String: Any] {
337新增: let value = try batch(id)
338新增: guard !value.busy, !files.isEmpty, value.files.count + files.count <= 100 else { throw Failure(8, "attachment_limit") }
339新增: for path in files {
340新增: var info = stat()
341新增: let url = URL(fileURLWithPath: path)
342新增: guard url.standardizedFileURL.path == path, path.hasPrefix("/"), !path.contains("\0"),
343新增: url.deletingLastPathComponent().lastPathComponent.hasPrefix("cage-clipboard-"),
344新增: lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_size <= 2 * 1024 * 1024 * 1024 else {
345新增: throw Failure(8, "attachment_path_invalid")
346新增: }
347新增: }
348新增: value.files.append(contentsOf: files)
349新增: return ["ok": true, "id": id]
350新增: }
351新增:
352新增: func validate(_ id: String) throws -> [String: Any] {
353新增: let value = try batch(id)
354新增: guard !value.busy else { throw Failure(8, "attachment_busy") }
355新增: return ["ok": true]
356新增: }
357新增:
358新增: func cancel(_ id: String) async -> [String: Any] {
359新增: guard let value = batches.removeValue(forKey: id) else { return ["ok": true] }
360新增: if let panel = value.panel, (try? valid(value)) != nil,
361新增: let button = filePanelButton(panel, cancel: true) {
362新增: _ = AXUIElementPerformAction(button, kAXPressAction as CFString)
363新增: }
364新增: if !value.files.isEmpty { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) }
365新增: return ["ok": true]
366新增: }
367新增:
368新增: func finish(_ id: String) async throws -> [String: Any] {
369新增: let value = try batch(id)
370新增: guard value.kind != "image", !value.busy, !value.files.isEmpty else { throw Failure(8, "attachment_incomplete") }
371新增: value.busy = true
372新增: defer { value.busy = false }
373新增: if let panel = value.panel {
374新增: // The native panel's Go To Folder action selects the uploaded file
375新增: // without asking the guest to read a caller-selected arbitrary path.
376新增: let copied = try await clipboardRequest(["operation": "prepare-files", "files": value.files])
377新增: guard let files = copied["paths"] as? [String], files.count == value.files.count, !files.isEmpty else { throw Failure(7, "clipboard_reply_invalid") }
378新增: guard batches[id] === value else {
379新增: _ = try? await clipboardRequest(["operation": "discard", "files": files])
380新增: throw Failure(8, "attachment_cancelled")
381新增: }
382新增: let previous = value.files
383新增: value.files = files
384新增: _ = try? await clipboardRequest(["operation": "discard", "files": previous])
385新增: guard batches[id] === value else { throw Failure(8, "attachment_cancelled") }
386新增: try valid(value)
387新增: try key(value.pid, 5, flags: [.maskCommand, .maskShift], panel: panel, epoch: value.epoch)
388新增: let app = AXUIElementCreateApplication(value.pid)
389新增: var field: AXUIElement?
390新增: for _ in 0..<20 {
391新增: try await Task.sleep(nanoseconds: 100_000_000)
392新增: guard batches[id] === value else { throw Failure(8, "attachment_cancelled") }
393新增: try valid(value)
394新增: if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), CFGetTypeID(focus) == AXUIElementGetTypeID(),
395新增: [kAXTextFieldRole, kAXComboBoxRole].contains(fileAttribute(focus as! AXUIElement, kAXRoleAttribute) as? String ?? "") {
396新增: field = (focus as! AXUIElement); break
397新增: }
398新增: }
399新增: let destination = files.count == 1 ? files[0] : (files[0] as NSString).deletingLastPathComponent
400新增: guard let field, AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, destination as CFString) == .success else {
401新增: throw Failure(7, "file_dialog_navigation_failed")
402新增: }
403新增: try key(value.pid, 36, panel: panel, epoch: value.epoch)
404新增: var resolved = false
405新增: for _ in 0..<20 {
406新增: try await Task.sleep(nanoseconds: 100_000_000)
407新增: guard batches[id] === value else { throw Failure(8, "attachment_cancelled") }
408新增: try valid(value)
409新增: if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), !CFEqual(focus, field) { resolved = true; break }
410新增: }
411新增: guard resolved else { throw Failure(7, "file_dialog_navigation_failed") }
412新增: if files.count > 1 {
413新增: try key(value.pid, 0, flags: .maskCommand, panel: panel, epoch: value.epoch)
414新增: try await Task.sleep(nanoseconds: 150_000_000)
415新增: guard batches[id] === value else { throw Failure(8, "attachment_cancelled") }
416新增: try valid(value)
417新增: }
418新增: let expected = try Set(files.map { path -> String in
419新增: guard let resolved = realpath(path, nil) else { throw Failure(7, "file_dialog_selection_mismatch") }
420新增: defer { free(resolved) }
421新增: return String(cString: resolved)
422新增: })
423新增: guard selectedFilePaths(panel, expected: expected) == expected else { throw Failure(7, "file_dialog_selection_mismatch") }
424新增: guard let button = filePanelButton(panel),
425新增: fileAttribute(button, kAXEnabledAttribute) as? Bool == true,
426新增: AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else {
427新增: throw Failure(7, "file_dialog_navigation_failed")
428新增: }
429新增: var accepted = false
430新增: for _ in 0..<20 {
431新增: try await Task.sleep(nanoseconds: 100_000_000)
432新增: if let current = openFilePanel(value.pid), CFEqual(current, panel) { continue }
433新增: accepted = true; break
434新增: }
435新增: guard accepted else { throw Failure(7, "file_dialog_still_open") }
436新增: } else {
437新增: let written = try await clipboardRequest(["operation": "write", "files": value.files])
438新增: guard batches[id] === value, let revision = written["revision"] as? Int, NSPasteboard.general.changeCount == revision else {
439新增: throw Failure(8, "attachment_cancelled")
440新增: }
441新增: try valid(value)
442新增: try key(value.pid, 9, flags: .maskCommand)
443新增: }
444新增: batches.removeValue(forKey: id)
445新增: return ["ok": true]
446新增: }
447新增:
448新增: private func save(_ panel: AXUIElement, field: AXUIElement, pid: pid_t, path: String, epoch: UInt64) async throws {
449新增: func validate() throws {
450新增: try MacGUISession.shared.validate(epoch)
451新增: guard AXIsProcessTrusted(), try claudePIDs().contains(pid), NSWorkspace.shared.frontmostApplication?.processIdentifier == pid,
452新增: filePanelPresent(panel, pid: pid), filePanelFocused(panel, pid: pid) else { throw Failure(7, "file_dialog_changed") }
453新增: }
454新增: try validate()
455新增: try key(pid, 5, flags: [.maskCommand, .maskShift], panel: panel, epoch: epoch)
456新增: let app = AXUIElementCreateApplication(pid)
457新增: var location: AXUIElement?
458新增: for _ in 0..<20 {
459新增: try await Task.sleep(nanoseconds: 100_000_000)
460新增: try validate()
461新增: if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), CFGetTypeID(focus) == AXUIElementGetTypeID(),
462新增: !CFEqual(focus, field), [kAXTextFieldRole, kAXComboBoxRole].contains(fileAttribute(focus as! AXUIElement, kAXRoleAttribute) as? String ?? "") {
463新增: location = (focus as! AXUIElement); break
464新增: }
465新增: }
466新增: guard let location, AXUIElementSetAttributeValue(location, kAXValueAttribute as CFString, (path as NSString).deletingLastPathComponent as CFString) == .success else {
467新增: throw Failure(7, "file_dialog_navigation_failed")
468新增: }
469新增: try key(pid, 36, panel: panel, epoch: epoch)
470新增: var resolved = false
471新增: for _ in 0..<20 {
472新增: try await Task.sleep(nanoseconds: 100_000_000)
473新增: try validate()
474新增: if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), !CFEqual(focus, location) { resolved = true; break }
475新增: }
476新增: guard resolved, AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, (path as NSString).lastPathComponent as CFString) == .success,
477新增: let button = filePanelButton(panel),
478新增: fileAttribute(button, kAXEnabledAttribute) as? Bool == true else { throw Failure(7, "file_dialog_navigation_failed") }
479新增: try validate()
480新增: guard AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else { throw Failure(7, "file_dialog_navigation_failed") }
481新增: for _ in 0..<20 {
482新增: try await Task.sleep(nanoseconds: 100_000_000)
483新增: if let current = saveFilePanel(pid), CFEqual(current.0, panel) { continue }
484新增: return
485新增: }
486新增: throw Failure(7, "file_dialog_still_open")
487新增: }
488新增:
489新增: func poll() async throws -> [String: Any] {
490新增: let epoch = try MacGUISession.shared.validate()
491新增: for (id, value) in batches where value.epoch != epoch || Date().timeIntervalSince(value.created) >= 1800 {
492新增: batches.removeValue(forKey: id)
493新增: if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } }
494新增: }
495新增: guard AXIsProcessTrusted(), let pid = try? claudePIDs().first else {
496新增: return ["available": false, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()]
497新增: }
498新增: if let (panel, field) = saveFilePanel(pid) {
499新增: if savingPanel == nil || !CFEqual(savingPanel!, panel) {
500新增: savingPanel = panel
501新增: let name = fileAttribute(field, kAXValueAttribute) as? String ?? ""
502新增: try await MacDesktopDownloads.shared.reserve(name: name, pid: pid) { path in
503新增: try await self.save(panel, field: field, pid: pid, path: path, epoch: epoch)
504新增: }
505新增: }
506新增: } else { savingPanel = nil }
507新增: guard let panel = openFilePanel(pid) else {
508新增: for (id, value) in batches where value.panel != nil && !value.busy {
509新增: batches.removeValue(forKey: id)
510新增: if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } }
511新增: }
512新增: return ["available": true, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()]
513新增: }
514新增: let existing = batches.first { $0.value.pid == pid && $0.value.panel.map { CFEqual($0, panel) } == true }
515新增: let id: String
516新增: if let existing { id = existing.key }
517新增: else {
518新增: guard batches.count < 12 else { throw Failure(8, "attachment_limit") }
519新增: id = UUID().uuidString.lowercased()
520新增: batches[id] = Batch(pid: pid, window: 0, kind: "chooser", epoch: try MacGUISession.shared.validate(), panel: panel)
521新增: }
522新增: return ["available": true, "uploads": [["id": id, "kind": "chooser", "multiple": true, "directory": false, "target": "desktop"]], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()]
523新增: }
524新增:
525新增: func pasteImage(_ data: Data, window: SCWindow) async throws -> [String: Any] {
526新增: guard data.count <= 20 * 1024 * 1024, let pid = window.owningApplication?.processID else { throw Failure(8, "attachment_size_limit") }
527新增: let value = Batch(pid: pid, window: window.windowID, kind: "paste", epoch: try MacGUISession.shared.validate())
528新增: return try await deliverImage(data, batch: value)
529新增: }
530新增:
531新增: func finishImage(_ id: String) async throws -> [String: Any] {
532新增: let value = try batch(id)
533新增: guard value.kind == "image", !value.busy, value.files.count == 1 else { throw Failure(8, "attachment_incomplete") }
534新增: value.busy = true
535新增: do {
536新增: let file = try FileHandle(forReadingFrom: URL(fileURLWithPath: value.files[0]))
537新增: defer { try? file.close() }
538新增: let data = try file.read(upToCount: 20 * 1024 * 1024 + 1) ?? Data()
539新增: guard !data.isEmpty, data.count <= 20 * 1024 * 1024 else { throw Failure(8, "attachment_size_limit") }
540新增: let result = try await deliverImage(data, batch: value)
541新增: _ = await cancel(id)
542新增: return result
543新增: } catch {
544新增: _ = await cancel(id)
545新增: throw error
546新增: }
547新增: }
548新增:
549新增: private func deliverImage(_ data: Data, batch value: Batch) async throws -> [String: Any] {
550新增: try valid(value)
551新增: let written = try await clipboardRequest(["operation": "write", "png": data.base64EncodedString()])
552新增: guard let revision = written["revision"] as? Int, NSPasteboard.general.changeCount == revision else { throw Failure(8, "attachment_cancelled") }
553新增: try valid(value)
554新增: try key(value.pid, 9, flags: .maskCommand, epoch: value.epoch)
555新增: return ["ok": true]
556新增: }
557新增:}
新增scripts/guest-os/macos-diagnostics.swift+61 −0看文件
@@ -0,0 +1,61 @@
1新增:import Foundation
2新增:import Darwin
3新增:
4新增:enum GuestDiagnostic {
5新增: private static let limit = 1 << 20
6新增: private static let sources = ["window", "clipboard"]
7新增:
8新增: static func record(_ source: String, _ reason: String) {
9新增: guard sources.contains(source), reason.range(of: "^[a-zA-Z][a-zA-Z0-9_]{0,95}$", options: .regularExpression) != nil else { return }
10新增: let directory = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Logs/Cage")
11新增: try? append(source, reason, directory: directory)
12新增: }
13新增:
14新增: static func append(_ source: String, _ reason: String, directory: URL) throws {
15新增: guard sources.contains(source), reason.range(of: "^[a-zA-Z][a-zA-Z0-9_]{0,95}$", options: .regularExpression) != nil else { return }
16新增: try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
17新增: let root = open(directory.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW)
18新增: guard root >= 0 else { throw CocoaError(.fileReadNoPermission) }
19新增: defer { close(root) }
20新增: var info = stat()
21新增: guard fstat(root, &info) == 0, info.st_uid == getuid(), info.st_mode & 0o077 == 0 else { throw CocoaError(.fileReadNoPermission) }
22新增: let lock = openat(root, source + ".lock", O_CREAT | O_RDWR | O_NOFOLLOW, 0o600)
23新增: guard lock >= 0 else { throw CocoaError(.fileWriteNoPermission) }
24新增: defer { close(lock) }
25新增: guard fstat(lock, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_nlink == 1,
26新增: flock(lock, LOCK_EX) == 0 else { throw CocoaError(.fileWriteNoPermission) }
27新增: defer { flock(lock, LOCK_UN) }
28新增: let now = Date()
29新增: for index in 0...4 {
30新增: let name = index == 0 ? source + ".jsonl" : source + "-\(index).jsonl"
31新增: if fstatat(root, name, &info, AT_SYMLINK_NOFOLLOW) != 0 { continue }
32新增: guard info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_nlink == 1 else { throw CocoaError(.fileReadNoPermission) }
33新增: if Double(info.st_mtimespec.tv_sec) < now.addingTimeInterval(-14 * 86400).timeIntervalSince1970 { _ = unlinkat(root, name, 0) }
34新增: }
35新增: var data = try JSONSerialization.data(withJSONObject: ["time": ISO8601DateFormatter().string(from: now), "source": source, "reason": reason])
36新增: data.append(10)
37新增: let current = source + ".jsonl"
38新增: if fstatat(root, current, &info, AT_SYMLINK_NOFOLLOW) == 0,
39新增: info.st_size + Int64(data.count) > limit || info.st_birthtimespec.tv_sec / 86400 != Int(now.timeIntervalSince1970) / 86400 {
40新增: _ = unlinkat(root, source + "-4.jsonl", 0)
41新增: for index in stride(from: 3, through: 0, by: -1) {
42新增: let previous = index == 0 ? current : source + "-\(index).jsonl"
43新增: let next = source + "-\(index + 1).jsonl"
44新增: if renameat(root, previous, root, next) != 0, errno != ENOENT { throw CocoaError(.fileWriteUnknown) }
45新增: }
46新增: }
47新增: let fd = openat(root, current, O_WRONLY | O_CREAT | O_APPEND | O_NOFOLLOW, 0o600)
48新增: guard fd >= 0 else { throw CocoaError(.fileWriteNoPermission) }
49新增: defer { close(fd) }
50新增: guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_nlink == 1 else { throw CocoaError(.fileWriteNoPermission) }
51新增: try data.withUnsafeBytes { bytes in
52新增: var offset = 0
53新增: while offset < bytes.count {
54新增: let count = Darwin.write(fd, bytes.baseAddress!.advanced(by: offset), bytes.count - offset)
55新增: if count < 0 && errno == EINTR { continue }
56新增: guard count > 0 else { throw CocoaError(.fileWriteUnknown) }
57新增: offset += count
58新增: }
59新增: }
60新增: }
61新增:}
新增scripts/guest-os/macos-file-writers.c+52 −0看文件
@@ -0,0 +1,52 @@
1新增:#include <errno.h>
2新增:#include <libproc.h>
3新增:#include <stdlib.h>
4新增:#include <sys/file.h>
5新增:#include <sys/proc_info.h>
6新增:#include <sys/stat.h>
7新增:
8新增:// Return 1 while the verified application tree holds a writable descriptor,
9新增:// 0 after those descriptors close, and -1 when the observation is incomplete.
10新增:int cage_file_has_writer(int root, const char *path) {
11新增: struct stat target;
12新增: if (lstat(path, &target) != 0 || !S_ISREG(target.st_mode)) return -1;
13新增: int pids[256] = {root};
14新增: int count = 1;
15新增: for (int index = 0; index < count; index++) {
16新增: int children[256];
17新增: int child_count = proc_listchildpids(pids[index], children, sizeof(children));
18新增: if (child_count < 0 || child_count >= 256) return -1;
19新增: for (int child = 0; child < child_count; child++) {
20新增: int seen = 0;
21新增: for (int prior = 0; prior < count; prior++) seen |= pids[prior] == children[child];
22新增: if (!seen && children[child] > 0) {
23新增: if (count == 256) return -1;
24新增: pids[count++] = children[child];
25新增: }
26新增: }
27新增: int needed = proc_pidinfo(pids[index], PROC_PIDLISTFDS, 0, NULL, 0);
28新增: if (needed <= 0) {
29新增: if (errno == ESRCH) continue;
30新增: return -1;
31新增: }
32新增: if (needed > 32768 * (int)sizeof(struct proc_fdinfo)) return -1;
33新增: int capacity = needed + 128 * (int)sizeof(struct proc_fdinfo);
34新增: struct proc_fdinfo *fds = malloc((size_t)capacity);
35新增: if (!fds) return -1;
36新增: int received = proc_pidinfo(pids[index], PROC_PIDLISTFDS, 0, fds, capacity);
37新增: if (received <= 0 || received >= capacity) { free(fds); return -1; }
38新增: for (int fd = 0; fd < received / (int)sizeof(*fds); fd++) {
39新增: if (fds[fd].proc_fdtype != PROX_FDTYPE_VNODE) continue;
40新增: struct vnode_fdinfo info;
41新增: int size = proc_pidfdinfo(pids[index], fds[fd].proc_fd, PROC_PIDFDVNODEINFO, &info, sizeof(info));
42新增: if (size != sizeof(info)) {
43新增: if (errno == EBADF || errno == ESRCH || errno == ENOENT) continue;
44新增: free(fds); return -1;
45新增: }
46新增: if (info.pvi.vi_stat.vst_dev == (uint32_t)target.st_dev && info.pvi.vi_stat.vst_ino == target.st_ino &&
47新增: (info.pfi.fi_openflags & FWRITE) != 0) { free(fds); return 1; }
48新增: }
49新增: free(fds);
50新增: }
51新增: return 0;
52新增:}
新增scripts/guest-os/macos-fuse-media.sh+19 −0看文件
@@ -0,0 +1,19 @@
1新增:#!/bin/bash
2新增:# Extract the pinned vendor installer on the host. Nothing is installed here.
3新增:set -euo pipefail
4新增:[[ $# == 2 && $1 == /* && $2 == /* && ! -e $2 ]]
5新增:work=$(mktemp -d)
6新增:volume="$work/volume"
7新增:attached=0
8新增:cleanup() {
9新增: if [[ $attached == 1 ]]; then hdiutil detach "$volume" >/dev/null || return; fi
10新增: rm -rf "$work"
11新增:}
12新增:trap cleanup EXIT
13新增:mkdir "$volume"
14新增:[[ $(shasum -a 256 "$1" | cut -d' ' -f1) == 92c21ef2db4199bcf5bddc8e6efb57b23ecb9715f74ab38cba2c77ab226d3830 ]]
15新增:hdiutil attach -readonly -nobrowse -noautoopen -mountpoint "$volume" "$1" >/dev/null
16新增:attached=1
17新增:pkg="$volume/Install macFUSE.pkg"
18新增:[[ -n $pkg && $(shasum -a 256 "$pkg" | cut -d' ' -f1) == 5acf9e30bab227707de8d15eb28472a0cc9ed45709846b3e067d283294dc7f9e ]]
19新增:cp "$pkg" "$2"
新增scripts/guest-os/macos-gui-session.swift+39 −0看文件
@@ -0,0 +1,39 @@
1新增:// One GUI epoch is shared by delayed file delivery and remote window input.
2新增:import AppKit
3新增:
4新增:@MainActor
5新增:final class MacGUISession {
6新增: static let shared = MacGUISession()
7新增: private(set) var epoch: UInt64 = 1
8新增: private var available: Bool
9新增: private var timer: Timer?
10新增: private var observers: [NSObjectProtocol] = []
11新增:
12新增: private init() {
13新增: available = (try? consoleUser()) != nil
14新增: timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] _ in
15新增: Task { @MainActor in self?.refresh() }
16新增: }
17新增: let center = NSWorkspace.shared.notificationCenter
18新增: observers.append(center.addObserver(forName: NSWorkspace.sessionDidResignActiveNotification, object: nil, queue: .main) { [weak self] _ in
19新增: Task { @MainActor in
20新增: guard let self else { return }
21新增: self.epoch &+= 1
22新增: self.refresh()
23新增: }
24新增: })
25新增: }
26新增:
27新增: private func refresh() {
28新增: let current = (try? consoleUser()) != nil
29新增: if current != available { available = current; epoch &+= 1 }
30新增: }
31新增:
32新增: @discardableResult
33新增: func validate(_ expected: UInt64? = nil) throws -> UInt64 {
34新增: refresh()
35新增: guard available else { throw Failure(4, "requires_gui_login") }
36新增: guard expected == nil || expected == epoch else { throw Failure(7, "gui_session_changed") }
37新增: return epoch
38新增: }
39新增:}
新增scripts/guest-os/macos-ipv6-check.c+78 −0看文件
@@ -0,0 +1,78 @@
1新增:// Observe the guest kernel's IPv6 route selection for the fixed public probe.
2新增:// An interface-scoped default on Darwin is selectable by a process that
3新增:// requests IPV6_BOUND_IF, even when an ordinary route lookup returns no route.
4新增:#include <arpa/inet.h>
5新增:#include <errno.h>
6新增:#include <fcntl.h>
7新增:#include <ifaddrs.h>
8新增:#include <net/if.h>
9新增:#include <netinet/in.h>
10新增:#include <poll.h>
11新增:#include <stdio.h>
12新增:#include <string.h>
13新增:#include <sys/socket.h>
14新增:#include <unistd.h>
15新增:
16新增:static int unicastSource(const struct in6_addr *address) {
17新增: return !IN6_IS_ADDR_UNSPECIFIED(address) && !IN6_IS_ADDR_LOOPBACK(address)
18新增: && !IN6_IS_ADDR_LINKLOCAL(address) && !IN6_IS_ADDR_MULTICAST(address);
19新增:}
20新增:
21新增:// A link-local, one-hop datagram can leave the VM NIC even when the guest
22新增:// deliberately has no ordinary IPv6 default route. It never targets the internet.
23新增:static int sendProbe(const char *name, const char *run, const char *check) {
24新增: if (strlen(run)!=32 || strlen(check)!=32 || strspn(run,"0123456789abcdef")!=32 || strspn(check,"0123456789abcdef")!=32) return 2;
25新增: unsigned index=if_nametoindex(name); if(!index) return 1;
26新增: int fd=socket(AF_INET6,SOCK_DGRAM,0), hops=1;
27新增: if(fd<0 || setsockopt(fd,IPPROTO_IPV6,IPV6_BOUND_IF,&index,sizeof(index))!=0 ||
28新增: setsockopt(fd,IPPROTO_IPV6,IPV6_MULTICAST_IF,&index,sizeof(index))!=0 ||
29新增: setsockopt(fd,IPPROTO_IPV6,IPV6_MULTICAST_HOPS,&hops,sizeof(hops))!=0) return 1;
30新增: struct sockaddr_in6 dst={.sin6_family=AF_INET6,.sin6_len=sizeof(dst),.sin6_scope_id=index,.sin6_port=htons(49417)};
31新增: if(inet_pton(AF_INET6,"ff02::2",&dst.sin6_addr)!=1) return 1;
32新增: char payload[120];int len=snprintf(payload,sizeof(payload),"Cage IPv6 link probe v1 %s %s",run,check);
33新增: ssize_t sent=sendto(fd,payload,(size_t)len,0,(struct sockaddr *)&dst,sizeof(dst));
34新增: close(fd); if(sent!=len) return 1; puts("sent");return 0;
35新增:}
36新增:
37新增:int main(int argc, char **argv) {
38新增: if (argc==5 && strcmp(argv[1],"link")==0) return sendProbe(argv[2],argv[3],argv[4]);
39新增: if (argc != 2) return 2;
40新增: int bound = strcmp(argv[1], "default") != 0;
41新增: unsigned index = bound ? if_nametoindex(argv[1]) : 0;
42新增: if (bound && !index) return 2;
43新增: struct ifaddrs *interfaces;
44新增: if (getifaddrs(&interfaces) != 0) return 1;
45新增: int sources = 0, found = !bound;
46新增: for (struct ifaddrs *item = interfaces; item; item = item->ifa_next) {
47新增: if (bound && strcmp(item->ifa_name, argv[1])) continue;
48新增: found = 1;
49新增: if (item->ifa_addr && item->ifa_addr->sa_family == AF_INET6 && (item->ifa_flags & IFF_UP)) {
50新增: struct sockaddr_in6 *a = (struct sockaddr_in6 *)item->ifa_addr;
51新增: if (unicastSource(&a->sin6_addr)) sources++;
52新增: }
53新增: }
54新增: freeifaddrs(interfaces);
55新增: if (!found) return 1;
56新增: int fd = socket(AF_INET6, SOCK_STREAM, 0);
57新增: if (fd < 0 || fcntl(fd, F_SETFL, O_NONBLOCK) < 0) return 1;
58新增: if (bound && setsockopt(fd, IPPROTO_IPV6, IPV6_BOUND_IF, &index, sizeof(index)) != 0) return 1;
59新增: struct sockaddr_in6 dst = {.sin6_len = sizeof(dst), .sin6_family = AF_INET6, .sin6_port = htons(443)};
60新增: if (inet_pton(AF_INET6, "2606:4700:4700::1111", &dst.sin6_addr) != 1) return 1;
61新增: int error = connect(fd, (struct sockaddr *)&dst, sizeof(dst)) == 0 ? 0 : errno;
62新增: if (error == EINPROGRESS) {
63新增: struct pollfd pfd = {fd, POLLOUT, 0};
64新增: int ready = poll(&pfd, 1, 1500);
65新增: if (ready == 0) error = ETIMEDOUT;
66新增: else if (ready < 0) return 1;
67新增: else {
68新增: socklen_t len = sizeof(error);
69新增: if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) != 0) return 1;
70新增: }
71新增: }
72新增: close(fd);
73新增: const char *status = error == 0 ? "connected"
74新增: : (error == ENETUNREACH || error == EHOSTUNREACH || error == EADDRNOTAVAIL) ? "no-route"
75新增: : error == ETIMEDOUT ? "timeout" : "unknown";
76新增: printf("{\"globalSources\":%d,\"boundIndex\":%u,\"result\":\"%s\",\"errno\":%d}\n", sources, index, status, error);
77新增: return 0;
78新增:}
新增scripts/guest-os/macos-native-browser.mjs+126 −0看文件
@@ -0,0 +1,126 @@
1新增:// Started by Cage through the bound ordinary user's SSH connection.
2新增:import { installMacOSCLIBrowser } from "./macos-cli-browser.mjs";
3新增:import { spawn } from "node:child_process";
4新增:import { randomBytes } from "node:crypto";
5新增:import { mkdir, rm, writeFile } from "node:fs/promises";
6新增:import { homedir } from "node:os";
7新增:import path from "node:path";
8新增:import { chromium, request } from "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/playwright/index.mjs";
9新增:import { createNativeBrowserService } from "./windows-browser.mjs";
10新增:import { relayMacOSBrowser, serveMacOSBrowser } from "./macos-browser-service.mjs";
11新增:import { lstat, readFile } from "node:fs/promises";
12新增:
13新增:const data = path.join(homedir(), "Library", "Application Support", "Cage");
14新增:const editors = new Map();
15新增:
16新增:async function openEditor(id, restart) {
17新增: if (!/^[a-f0-9]{24}$/.test(id)) throw new Error("项目标识无效");
18新增: const folder = path.join(homedir(), "Cage", "Projects", id);
19新增: let editor = editors.get(id);
20新增: if (restart && editor) { editor.child.kill(); editor = null; }
21新增: if (!editor) {
22新增: const password = randomBytes(32).toString("hex");
23新增: const directory = path.join(data, "EditorSessions");
24新增: const config = path.join(directory, id + ".yaml");
25新增: await mkdir(directory, { mode: 0o700, recursive: true });
26新增: await writeFile(config, "bind-addr: 127.0.0.1:0\nauth: password\npassword: " + password + "\ncert: false\n", { mode: 0o600 });
27新增: const child = spawn("/usr/local/libexec/cage-macos-terminal", ["--editor", folder], { stdio: "pipe" });
28新增: child.stdin.on("error", () => {});
29新增: editor = { child, password, config };
30新增: editors.set(id, editor);
31新增: child.once("exit", () => {
32新增: if (editors.get(id) === editor) { editors.delete(id); void rm(config, { force: true }).catch(() => {}); }
33新增: });
34新增: editor.address = await new Promise((resolve, reject) => {
35新增: let recent = "";
36新增: const failed = () => finish();
37新增: const read = chunk => {
38新增: recent = (recent + chunk).slice(-6000);
39新增: const address = recent.match(/HTTP server listening on (http:\/\/127\.0\.0\.1:[1-9][0-9]*)/);
40新增: if (address) finish(address[1]);
41新增: };
42新增: const timer = setTimeout(failed, 15000);
43新增: function finish(address) {
44新增: clearTimeout(timer);
45新增: child.off("exit", failed); child.off("error", failed);
46新增: for (const stream of [child.stdout, child.stderr]) { stream.off("data", read); stream.resume(); }
47新增: if (address) resolve(address);
48新增: else { child.kill(); reject(new Error("项目编辑器启动失败")); }
49新增: }
50新增: child.stdout.on("data", read); child.stderr.on("data", read);
51新增: child.once("error", failed); child.once("exit", failed);
52新增: });
53新增: }
54新增: const client = await request.newContext();
55新增: try {
56新增: const login = await client.post(editor.address + "/login", { form: { password: editor.password }, maxRedirects: 0, timeout: 7000 });
57新增: if (![302, 303].includes(login.status())) throw new Error("客机编辑器登录失败");
58新增: const hostname = id + ".cage-editor.localhost";
59新增: const url = new URL(editor.address);
60新增: url.hostname = hostname;
61新增: url.searchParams.set("folder", folder);
62新增: const { cookies } = await client.storageState();
63新增: return { url: url.href, folder, cookies: cookies.map(cookie => ({ ...cookie, domain: hostname })) };
64新增: } finally { await client.dispose(); }
65新增:}
66新增:
67新增:async function audit(context, { timezone, network }) {
68新增: // Sample the real workbench tab in a fresh isolated world. Page scripts
69新增: // cannot replace navigator or Intl in this execution context.
70新增: const tab = context.pages().find(p => !p.url().startsWith("chrome-extension:"));
71新增: const cdp = await context.newCDPSession(tab);
72新增: let result;
73新增: try {
74新增: const {frameTree} = await cdp.send("Page.getFrameTree");
75新增: const {executionContextId} = await cdp.send("Page.createIsolatedWorld", {frameId: frameTree.frame.id, worldName: "cage-workbench-settings"});
76新增: const observed = await cdp.send("Runtime.evaluate", {contextId: executionContextId, returnByValue: true,
77新增: expression: `({timezone:Intl.DateTimeFormat().resolvedOptions().timeZone, expected_timezone:new Intl.DateTimeFormat("en",{timeZone:${JSON.stringify(timezone)}}).resolvedOptions().timeZone,language:navigator.language,platform:navigator.platform})`});
78新增: result = observed.result.value;
79新增: if (!result?.platform) throw new Error("无法读取客机浏览器设置");
80新增: } finally { await cdp.detach(); }
81新增: if (!network) return result;
82新增: const isolated = await context.browser().newContext({ serviceWorkers: "block" });
83新增: try {
84新增: const page = await isolated.newPage();
85新增: await page.goto("http://198.18.0.254/", { waitUntil: "domcontentloaded", timeout: 12000 });
86新增: result.network = await page.evaluate(async () => {
87新增: if (location.origin !== "http://198.18.0.254") throw new Error("无效的诊断地址");
88新增: try {
89新增: const response = await fetch("/egress", { cache: "no-store", credentials: "omit", signal: AbortSignal.timeout(14000) });
90新增: return { ...(await response.json()), status: response.status };
91新增: } catch { return { status: 0 }; }
92新增: });
93新增: return result;
94新增: } finally { await isolated.close(); }
95新增:}
96新增:
97新增:const marker = await lstat("/var/db/cage-guest-os");
98新增:if (process.platform !== "darwin" || process.getuid() < 500 || !marker.isFile() || marker.uid !== 0 || (marker.mode & 0o022) ||
99新增: (await readFile("/var/db/cage-guest-os", "utf8")).trim() !== "macos") throw new Error("Cage browser requires its bound guest user");
100新增:const directory = path.join(homedir(), "Library", "Caches", "dev.cage.GuestBrowser");
101新增:if (process.argv.length > 3 || process.argv[2] && process.argv[2] !== "--service" && process.argv[2] !== "--client")
102新增: throw new Error("Unknown browser service operation");
103新增:if (process.argv[2] !== "--service") {
104新增: // Older hosts invoke this file with no arguments. They attach to the same
105新增: // service and receive ownership capability metadata with the first reply.
106新增: await relayMacOSBrowser(directory);
107新增:} else {
108新增: const service = createNativeBrowserService({
109新增: platform: "darwin", chromium, editor: openEditor, audit,
110新增: directory: path.join(data, "BrowserWorkbench"),
111新增: profileDirectory: path.join(data, "Browser"),
112新增: executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
113新增: });
114新增: await service.request({ operation: "configure", input: { networkMode: "packet", displayScale: 1 } });
115新增: const closeBrowser = async () => {
116新增: for (const { child } of editors.values()) child.kill();
117新增: await service.close();
118新增: };
119新增: const server = await serveMacOSBrowser({ directory, dispatch: (request, options) => service.request(request, options), disconnect: signal => service.releaseInput(signal), close: closeBrowser });
120新增: let closeLogin;
121新增: try { closeLogin = await installMacOSCLIBrowser(data, message => server.request(message)); }
122新增: catch (error) { await server.close(); throw error; }
123新增: const shutdown = async () => { await server.close(); await closeLogin(); };
124新增: process.once("SIGTERM", () => { void shutdown().catch(() => { process.exitCode = 1; }); });
125新增: process.once("SIGINT", () => { void shutdown().catch(() => { process.exitCode = 1; }); });
126新增:}
新增scripts/guest-os/macos-phone-browser.mjs+78 −0看文件
@@ -0,0 +1,78 @@
1新增:// The phone owns a separate browser profile and the shared public-web policy.
2新增:import { homedir } from "node:os";
3新增:import path from "node:path";
4新增:import { pathToFileURL } from "node:url";
5新增:import { PhoneBrowser } from "./modules/browser-phone.mjs";
6新增:import { phoneError } from "./modules/browser-phone-network.mjs";
7新增:import { lines } from "./windows-browser.mjs";
8新增:
9新增:export async function runMacOSPhoneBrowser(input = process.stdin, output = process.stdout, options = {}) {
10新增: if (process.platform !== "darwin" && options.testing !== true) throw new Error("此浏览器需要 macOS 客机");
11新增: const phone = new PhoneBrowser({
12新增: binary: options.binary || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
13新增: directory: options.directory || path.join(homedir(), "Library", "Application Support", "Cage", "PhoneBrowser"),
14新增: language: options.language || Intl.DateTimeFormat().resolvedOptions().locale,
15新增: connect: options.connect,
16新增: });
17新增: // This controller is private to one paired phone. Keep its cold launch
18新增: // alive between frame polls, while close, SSH EOF and timeout can stop it.
19新增: let opening;
20新增: async function cancelOpen() {
21新增: if (opening) {
22新增: opening.abort.abort();
23新增: await opening.done;
24新增: opening = undefined;
25新增: }
26新增: await phone.dispose();
27新增: }
28新增: async function operate(operation, input) {
29新增: if (opening && input?.id !== opening.id) throw phoneError(410, "手机浏览器会话已结束");
30新增: if (opening && operation === "close") {
31新增: await cancelOpen();
32新增: return { id: input.id };
33新增: }
34新增: if (!opening && operation === "open") {
35新增: const entry = { id: input?.id, abort: new AbortController(), settled: false };
36新增: opening = entry;
37新增: const deadline = setTimeout(() => entry.abort.abort(), 75000);
38新增: entry.done = phone.run("open", input, entry.abort.signal).catch(error => {
39新增: entry.error = entry.abort.signal.aborted ? phoneError(503, "客机浏览器启动超时") : error;
40新增: }).finally(() => {
41新增: entry.settled = true;
42新增: clearTimeout(deadline);
43新增: });
44新增: // Return quick URL/parameter rejections on the original open request.
45新增: let timer;
46新增: try { await Promise.race([entry.done, new Promise(resolve => { timer = setTimeout(resolve, 200); })]); }
47新增: finally { clearTimeout(timer); }
48新增: }
49新增: if (opening) {
50新增: if (opening.settled) {
51新增: const { error } = opening;
52新增: opening = undefined;
53新增: if (error) throw error;
54新增: } else if (operation !== "open") {
55新增: throw phoneError(425, "正在启动虚拟 Mac 中的浏览器");
56新增: }
57新增: if (operation === "open") return { id: input.id };
58新增: }
59新增: return phone.run(operation, input);
60新增: }
61新增: try {
62新增: for await (const line of lines(input)) {
63新增: let result;
64新增: try {
65新增: const request = JSON.parse(line);
66新增: if (request.method !== "POST" || !/^\/phone-browser\/(open|frame|action|close)$/.test(request.path || "")) throw new Error("手机浏览器请求无效");
67新增: result = await operate(request.path.split("/").at(-1), request.input);
68新增: } catch (error) {
69新增: result = { error: "手机浏览器操作未完成,请核对授权和最新画面", code: "phone_browser_error", status: [403, 409, 410, 425, 503].includes(error.status) ? error.status : 400 };
70新增: }
71新增: await new Promise((resolve, reject) => output.write(JSON.stringify(result) + "\n", error => error ? reject(error) : resolve()));
72新增: }
73新增: } finally { await cancelOpen(); }
74新增:}
75新增:
76新增:if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) {
77新增: await runMacOSPhoneBrowser().catch(() => { process.exitCode = 1; });
78新增:}
新增scripts/guest-os/macos-phone-desktop.swift+253 −0看文件
@@ -0,0 +1,253 @@
1新增:// A phone sees the same signed Claude window as the computer. Its lease and
2新增:// input focus belong to one GUI login, window and captured geometry.
3新增:import AppKit
4新增:import ScreenCaptureKit
5新增:import ImageIO
6新增:
7新增:struct MacPhoneDesktopInput: Decodable {
8新增: let id: String
9新增: var width, height: Int?
10新增: var pixel_ratio: Double?
11新增: var type, document, focus, text, key: String?
12新增: var x, y, dx, dy: Double?
13新增:}
14新增:
15新增:func phoneDesktopJPEG(_ image: CGImage) throws -> Data {
16新增: for quality in [0.9, 0.78, 0.62, 0.45] {
17新增: let data = try encodedImage(image, type: .jpeg,
18新增: properties: [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)
19新增: // Leave room for base64 expansion and the complete phone frame metadata.
20新增: if data.count <= 2 << 20 { return data }
21新增: }
22新增: throw Failure(8, "frame_limit")
23新增:}
24新增:
25新增:private func matchesPhoneFocus(_ requested: String?, token: String, previous: AXUIElement?, current: AXUIElement?, password: Bool) -> Bool {
26新增: guard !token.isEmpty, requested == token, let previous, let current, !password else { return false }
27新增: return CFEqual(previous, current)
28新增:}
29新增:
30新增:@MainActor
31新增:final class MacPhoneDesktop {
32新增: static let shared = MacPhoneDesktop()
33新增:
34新增: @MainActor private final class Session {
35新增: let id, secret: String
36新增: let epoch: UInt64
37新增: let canvas = ClaudeCanvasSession()
38新增: var width: Int
39新增: var height: Int
40新增: var ratio: Double
41新增: var geometry = ""
42新增: var document = ""
43新增: var focus = ""
44新增: var focusedElement: AXUIElement?
45新增: var window: CGWindowID?
46新增: var pid: pid_t?
47新增: var touched = Date()
48新增:
49新增: init(_ input: MacPhoneDesktopInput, secret: String, epoch: UInt64) throws {
50新增: let size = try MacPhoneDesktop.viewport(input)
51新增: id = input.id
52新增: self.secret = secret
53新增: self.epoch = epoch
54新增: width = size.0; height = size.1; ratio = size.2
55新增: }
56新增: }
57新增:
58新增: private var current: Session?
59新增:
60新增: private static func viewport(_ input: MacPhoneDesktopInput) throws -> (Int, Int, Double) {
61新增: guard let width = input.width, let height = input.height,
62新增: (240...1440).contains(width), (160...1600).contains(height) else {
63新增: throw Failure(8, "invalid_input")
64新增: }
65新增: let ratio = input.pixel_ratio ?? 1
66新增: guard ratio.isFinite, (1...8).contains(ratio) else { throw Failure(8, "invalid_input") }
67新增: return (width, height, ratio)
68新增: }
69新增:
70新增: private func validate(_ session: Session) throws {
71新增: guard current === session, Date().timeIntervalSince(session.touched) < 120 else {
72新增: throw Failure(7, "phone_session_ended")
73新增: }
74新增: do { try MacGUISession.shared.validate(session.epoch) }
75新增: catch { current = nil; throw error }
76新增: session.touched = Date()
77新增: }
78新增:
79新增: func handle(_ request: Request) async throws -> [String: Any] {
80新增: guard let input = request.phone, UUID(uuidString: input.id) != nil,
81新增: let secret = request.phone_token, (32...128).contains(secret.utf8.count) else {
82新增: throw Failure(8, "invalid_input")
83新增: }
84新增: if request.action == "phone-close" {
85新增: if current?.id == input.id && current?.secret == secret { current = nil }
86新增: return ["id": input.id]
87新增: }
88新增: if request.action == "phone-open" {
89新增: let epoch = try MacGUISession.shared.validate()
90新增: let session = try Session(input, secret: secret, epoch: epoch)
91新增: current = session
92新增: do {
93新增: try await launchClaudeWindow()
94新增: try validate(session)
95新增: } catch {
96新增: if current === session { current = nil }
97新增: throw error
98新增: }
99新增: return ["id": session.id]
100新增: }
101新增: guard let session = current, session.id == input.id, session.secret == secret else {
102新增: throw Failure(7, "phone_session_ended")
103新增: }
104新增: try validate(session)
105新增: switch request.action {
106新增: case "phone-frame":
107新增: return try await frame(session)
108新增: case "phone-action":
109新增: if input.type == "resize" {
110新增: let (width, height, ratio) = try Self.viewport(input)
111新增: session.width = width; session.height = height; session.ratio = ratio
112新增: session.document = ""; session.focus = ""; session.focusedElement = nil
113新增: return ["id": session.id]
114新增: }
115新增: try await action(input, session: session)
116新增: return ["id": session.id]
117新增: default:
118新增: throw Failure(8, "unknown_action")
119新增: }
120新增: }
121新增:
122新增: private func frame(_ session: Session) async throws -> [String: Any] {
123新增: var (window, selection) = try await selectedWindow()
124新增: try validate(session)
125新增: let capture = selection ?? SCContentFilter(desktopIndependentWindow: window)
126新增: let layout = try await session.canvas.layout(window, filter: capture,
127新增: width: max(320, session.width), height: max(240, session.height), scale: min(2, session.ratio))
128新增: try validate(session)
129新增: if window.frame != layout.frame {
130新增: (window, selection) = try await selectedWindow()
131新增: guard window.windowID == layout.id, window.owningApplication?.processID == layout.pid else {
132新增: throw Failure(7, "window_changed")
133新增: }
134新增: }
135新增: let raw = try await session.canvas.capture(window,
136新增: filter: selection ?? SCContentFilter(desktopIndependentWindow: window),
137新增: layout: layout, binary: true, phoneJPEG: true)
138新增: try validate(session)
139新增: guard let data = raw["imageBytes"] as? Data, let geometry = raw["geometry"] as? String else {
140新增: throw Failure(8, "capture_failed")
141新增: }
142新增: if session.geometry != geometry || session.document.isEmpty {
143新增: session.document = UUID().uuidString
144新增: session.focus = ""; session.focusedElement = nil
145新增: }
146新增: session.geometry = geometry; session.window = layout.id; session.pid = layout.pid
147新增: let focus = editableFocus(window, session: session)
148新增: if let element = focus.element {
149新增: if session.focusedElement.map({ CFEqual($0, element) }) != true {
150新增: session.focus = UUID().uuidString
151新增: }
152新增: session.focusedElement = element
153新增: } else {
154新增: session.focusedElement = nil; session.focus = ""
155新增: }
156新增: let reply: [String: Any] = ["id": session.id, "document": session.document,
157新增: "image": data.base64EncodedString(), "width": session.width, "height": session.height,
158新增: "content_width": layout.content.width, "content_height": layout.content.height,
159新增: "pixel_width": raw["pixelWidth"] ?? 0, "pixel_height": raw["pixelHeight"] ?? 0,
160新增: "requested_pixel_ratio": session.ratio, "pixel_ratio_control": true,
161新增: "focus": session.focus, "password": focus.password, "window": "desktop", "shared": true,
162新增: "login_supported": false]
163新增: guard try JSONSerialization.data(withJSONObject: reply).count <= 3 << 20 else {
164新增: throw Failure(8, "frame_limit")
165新增: }
166新增: return reply
167新增: }
168新增:
169新增: private func editableFocus(_ window: SCWindow, session: Session) -> (element: AXUIElement?, password: Bool) {
170新增: guard (try? session.canvas.inputGeometry(session.geometry, window: window)) != nil,
171新增: let pid = window.owningApplication?.processID else { return (nil, false) }
172新增: func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? {
173新增: var value: CFTypeRef?
174新增: return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil
175新增: }
176新增: let application = AXUIElementCreateApplication(pid)
177新增: guard let raw = attribute(application, kAXFocusedUIElementAttribute), CFGetTypeID(raw) == AXUIElementGetTypeID(),
178新增: let owner = attribute(application, kAXFocusedWindowAttribute) else { return (nil, false) }
179新增: let element = raw as! AXUIElement
180新增: guard let elementWindow = attribute(element, kAXWindowAttribute), CFEqual(owner, elementWindow),
181新增: let role = attribute(element, kAXRoleAttribute) as? String,
182新增: [kAXTextFieldRole, kAXTextAreaRole, kAXComboBoxRole].contains(role) else { return (nil, false) }
183新增: let password = attribute(element, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole
184新增: return (element, password)
185新增: }
186新增:
187新增: private func action(_ input: MacPhoneDesktopInput, session: Session) async throws {
188新增: guard !session.document.isEmpty, input.document == session.document else { throw Failure(7, "phone_document_changed") }
189新增: let (window, _) = try await selectedWindow()
190新增: try validate(session)
191新增: guard window.windowID == session.window, window.owningApplication?.processID == session.pid else {
192新增: throw Failure(7, "window_changed")
193新增: }
194新增: let canvas = try session.canvas.inputGeometry(session.geometry, window: window)
195新增: var native = Request(action: "")
196新增: var scrollX: Double = 0
197新增: let typing = input.type == "text" || (input.type == "key" && !["Tab", "Escape", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].contains(input.key ?? ""))
198新增: if typing {
199新增: let fresh = editableFocus(window, session: session)
200新增: guard matchesPhoneFocus(input.focus, token: session.focus, previous: session.focusedElement,
201新增: current: fresh.element, password: fresh.password) else { throw Failure(7, "phone_focus_changed") }
202新增: }
203新增: switch input.type {
204新增: case "text":
205新增: native = Request(action: "text", text: input.text)
206新增: case "key":
207新增: if let key = input.key, key.utf8.count == 1, let scalar = key.unicodeScalars.first, (32...126).contains(scalar.value) {
208新增: native = Request(action: "text", text: key)
209新增: } else { native = Request(action: "key", key: input.key) }
210新增: case "tap", "scroll":
211新增: guard let x = input.x, let y = input.y, x.isFinite, y.isFinite,
212新增: (0..<Double(canvas.content.width)).contains(x), (0..<Double(canvas.content.height)).contains(y) else {
213新增: throw Failure(8, "invalid_input")
214新增: }
215新增: native = Request(action: input.type == "tap" ? "click" : "scroll",
216新增: x: x / Double(canvas.content.width), y: y / Double(canvas.content.height), delta: input.dy)
217新增: if input.type == "scroll" {
218新增: guard let dx = input.dx, let dy = input.dy, dx.isFinite, dy.isFinite,
219新增: (-3200...3200).contains(dx), (-3200...3200).contains(dy) else { throw Failure(8, "invalid_input") }
220新增: scrollX = dx
221新增: native.delta = dy
222新增: }
223新增: default:
224新增: throw Failure(8, "invalid_input")
225新增: }
226新增: native.window = window.windowID; native.pid = window.owningApplication?.processID
227新增: try sendInput(native, window: window, canvas: canvas, maxTextBytes: 8192, scrollX: scrollX, maxScroll: 32000)
228新增: }
229新增:
230新增: static func selfTest() throws {
231新增: let local = AXUIElementCreateApplication(getpid())
232新增: let other = AXUIElementCreateApplication(getpid() + 1)
233新增: let accepts = matchesPhoneFocus("focus", token: "focus", previous: local, current: local, password: false)
234新增: let rejects = [
235新增: matchesPhoneFocus("", token: "", previous: local, current: local, password: false),
236新增: matchesPhoneFocus("old", token: "focus", previous: local, current: local, password: false),
237新增: matchesPhoneFocus("focus", token: "focus", previous: local, current: other, password: false),
238新增: matchesPhoneFocus("focus", token: "focus", previous: local, current: nil, password: false),
239新增: matchesPhoneFocus("focus", token: "focus", previous: local, current: local, password: true)
240新增: ]
241新增: guard accepts, rejects.allSatisfy({ !$0 }) else { throw Failure(8, "focus_test_failed") }
242新增: guard let context = CGContext(data: nil, width: 640, height: 480, bitsPerComponent: 8,
243新增: bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { throw Failure(8, "image_test_failed") }
244新增: context.setFillColor(CGColor(red: 0.1, green: 0.2, blue: 0.3, alpha: 1))
245新增: context.fill(CGRect(x: 0, y: 0, width: 640, height: 480))
246新增: guard let image = context.makeImage() else { throw Failure(8, "image_test_failed") }
247新增: let jpeg = try phoneDesktopJPEG(image)
248新增: guard jpeg.starts(with: [0xff, 0xd8]), let source = CGImageSourceCreateWithData(jpeg as CFData, nil),
249新增: let decoded = CGImageSourceCreateImageAtIndex(source, 0, nil), decoded.width == 640, decoded.height == 480,
250新增: try JSONSerialization.data(withJSONObject: ["image": jpeg.base64EncodedString()]).count < 3 << 20 else { throw Failure(8, "jpeg_test_failed") }
251新增: print("phone desktop focus token and real AX identity checks passed; JPEG 640x480 encoding and total JSON limit passed")
252新增: }
253新增:}
新增scripts/guest-os/macos-project-access.m+502 −0看文件
@@ -0,0 +1,502 @@
1新增:// Per-user guest application. macOS grants only the project selected in the
2新增:// native Open panel. Terminal and editor children inherit that user selection.
3新增:#import <AppKit/AppKit.h>
4新增:#import <fcntl.h>
5新增:#import <poll.h>
6新增:#import <signal.h>
7新增:#import <spawn.h>
8新增:#import <sys/file.h>
9新增:#import <sys/ioctl.h>
10新增:#import <sys/mount.h>
11新增:#import <sys/socket.h>
12新增:#import <sys/stat.h>
13新增:#import <sys/un.h>
14新增:#import <sys/wait.h>
15新增:#import <termios.h>
16新增:#import <unistd.h>
17新增:
18新增:extern char **environ;
19新增:static NSString *socketPath(void) {
20新增: return [NSHomeDirectory()
21新增: stringByAppendingPathComponent:@"Library/Application Support/Cage/project-terminal.sock"];
22新增:}
23新增:static BOOL addressForSocket(struct sockaddr_un *address) {
24新增: const char *p = socketPath().fileSystemRepresentation;
25新增: memset(address, 0, sizeof(*address));
26新增: address->sun_family = AF_UNIX;
27新增: return strlcpy(address->sun_path, p, sizeof(address->sun_path)) < sizeof(address->sun_path);
28新增:}
29新增:static BOOL writeAll(int fd, const void *data, size_t count) {
30新增: const char *p = data;
31新增: while (count) {
32新增: ssize_t n = write(fd, p, count);
33新增: if (n < 0 && errno == EINTR)
34新增: continue;
35新增: if (n <= 0)
36新增: return NO;
37新增: p += n;
38新增: count -= n;
39新增: }
40新增: return YES;
41新增:}
42新增:static void reply(int fd, const char *message) { writeAll(fd, message, strlen(message)); }
43新增:static NSString *mountID(NSString *project) {
44新增: if (![project isKindOfClass:NSString.class] || ![project.stringByStandardizingPath isEqual:project])
45新增: return nil;
46新增: NSString *base = [NSHomeDirectory() stringByAppendingPathComponent:@"Cage/Projects"];
47新增: NSString *leaf = project.lastPathComponent;
48新增: if (![project.stringByDeletingLastPathComponent isEqual:base] || leaf.length != 24 ||
49新增: [leaf rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdef"]
50新增: .invertedSet]
51新增: .location != NSNotFound)
52新增: return nil;
53新增: struct statfs fs;
54新增: if (statfs(project.fileSystemRepresentation, &fs) ||
55新增: strcmp(fs.f_mntonname, project.fileSystemRepresentation) || strcmp(fs.f_fstypename, "macfuse") ||
56新增: fs.f_owner != getuid() || (fs.f_flags & (MNT_NOSUID | MNT_NODEV)) != (MNT_NOSUID | MNT_NODEV))
57新增: return nil;
58新增: return [NSString stringWithUTF8String:fs.f_mntfromname];
59新增:}
60新增:
61新增:@interface ProjectAccess : NSObject <NSApplicationDelegate, NSOpenSavePanelDelegate>
62新增:@end
63新增:@implementation ProjectAccess {
64新增: NSMutableDictionary<NSString *, NSURL *> *_scopes;
65新增: NSMutableDictionary<NSString *, NSString *> *_ready;
66新增: NSString *_requesting;
67新增: NSString *_nonce;
68新增: NSOpenPanel *_panel;
69新增: NSMutableDictionary<NSString *, NSDate *> *_declined;
70新增:}
71新增:- (void)applicationDidFinishLaunching:(NSNotification *)note {
72新增: _scopes = [NSMutableDictionary dictionary];
73新增: _ready = [NSMutableDictionary dictionary];
74新增: _declined = [NSMutableDictionary dictionary];
75新增: dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
76新增: [self serve];
77新增: });
78新增:}
79新增:// These state and UI methods run on the main thread.
80新增:- (BOOL)restore:(NSString *)project {
81新增: if (_scopes[project])
82新增: return YES;
83新增: NSData *saved = [[NSUserDefaults standardUserDefaults] dataForKey:project];
84新增: if (!saved)
85新增: return NO;
86新增: BOOL stale = NO;
87新增: NSURL *url = [NSURL
88新增: URLByResolvingBookmarkData:saved
89新增: options:NSURLBookmarkResolutionWithSecurityScope |
90新增: NSURLBookmarkResolutionWithoutUI | NSURLBookmarkResolutionWithoutMounting
91新增: relativeToURL:nil
92新增: bookmarkDataIsStale:&stale
93新增: error:nil];
94新增: if (![url.path isEqual:project] || ![url startAccessingSecurityScopedResource])
95新增: return NO;
96新增: _scopes[project] = url;
97新增: if (stale)
98新增: [self remember:url];
99新增: return YES;
100新增:}
101新增:- (void)remember:(NSURL *)url {
102新增: NSData *bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
103新增: includingResourceValuesForKeys:nil
104新增: relativeToURL:nil
105新增: error:nil];
106新增: if (bookmark)
107新增: [[NSUserDefaults standardUserDefaults] setObject:bookmark forKey:url.path];
108新增:}
109新增:- (void)request:(NSString *)project {
110新增: if (_requesting || (_declined[project] && [_declined[project] timeIntervalSinceNow] > 0))
111新增: return;
112新增: _requesting = project;
113新增: NSOpenPanel *panel = [NSOpenPanel openPanel];
114新增: panel.delegate = self;
115新增: panel.canChooseDirectories = YES;
116新增: panel.canChooseFiles = NO;
117新增: panel.allowsMultipleSelection = NO;
118新增: panel.directoryURL = [NSURL fileURLWithPath:project isDirectory:YES];
119新增: panel.message = @"Allow Cage to open this mounted project in the guest terminal and editor.";
120新增: panel.prompt = @"Use Project";
121新增: _nonce = NSUUID.UUID.UUIDString;
122新增: _panel = panel;
123新增: __block NSTimer *timer;
124新增: [NSApp activateIgnoringOtherApps:YES];
125新增: [panel beginWithCompletionHandler:^(NSModalResponse response) {
126新增: [timer invalidate];
127新增: self->_panel = nil;
128新增: self->_nonce = nil;
129新增: NSURL *url = panel.URL;
130新增: if (response == NSModalResponseOK && [url.path isEqual:project] && mountID(project) &&
131新增: [url startAccessingSecurityScopedResource]) {
132新增: self->_scopes[project] = url;
133新增: [self remember:url];
134新增: } else {
135新增: self->_declined[project] = [NSDate dateWithTimeIntervalSinceNow:30];
136新增: }
137新增: self->_requesting = nil;
138新增: }];
139新增: // The request must disappear if the mount is revoked while the panel is open.
140新增: timer =
141新增: [NSTimer scheduledTimerWithTimeInterval:.25
142新增: repeats:YES
143新增: block:^(NSTimer *t) {
144新增: if (!mountID(project) || ![self->_requesting isEqual:project]) {
145新增: [panel cancel:nil];
146新增: return;
147新增: }
148新增: }];
149新增:}
150新增:- (NSString *)probe:(NSDictionary *)req {
151新增: NSString *project = req[@"path"], *file = req[@"file"], *expected = req[@"expected"],
152新增: *identity = mountID(project);
153新增: if (!identity || ![file isKindOfClass:NSString.class] || ![file hasPrefix:@".cage-mount-probe-"] ||
154新增: ![file.lastPathComponent isEqual:file] || ![expected isKindOfClass:NSString.class] ||
155新增: expected.length < 1 || expected.length > 256)
156新增: return @"ERR";
157新增: if (_ready[project] && ![_ready[project] isEqual:identity]) {
158新增: [_ready removeObjectForKey:project];
159新增: [_scopes[project] stopAccessingSecurityScopedResource];
160新增: [_scopes removeObjectForKey:project];
161新增: }
162新增: if (![self restore:project]) {
163新增: [self request:project];
164新增: return @"PENDING";
165新增: }
166新增: NSString *filePath = [project stringByAppendingPathComponent:file];
167新增: // Bounded read of the host challenge. A link cannot be used for the proof.
168新增: char b[1024];
169新增: int fd = open(filePath.fileSystemRepresentation, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK);
170新增: if (fd < 0) {
171新增: if (errno == EPERM || errno == EACCES) {
172新增: [_ready removeObjectForKey:project];
173新增: [_scopes[project] stopAccessingSecurityScopedResource];
174新增: [_scopes removeObjectForKey:project];
175新增: [self request:project];
176新增: return @"PENDING";
177新增: }
178新增: return @"ERR";
179新增: }
180新增: struct stat st;
181新增: ssize_t n =
182新增: !fstat(fd, &st) && S_ISREG(st.st_mode) && st.st_size < sizeof(b) ? read(fd, b, sizeof(b)) : -1;
183新增: close(fd);
184新增: NSData *answer = [expected dataUsingEncoding:NSUTF8StringEncoding];
185新增: if (n < 0 || n != (ssize_t)answer.length || memcmp(b, answer.bytes, n) ||
186新增: ![identity isEqual:mountID(project)])
187新增: return @"ERR";
188新增: _ready[project] = identity;
189新增: return @"OK";
190新增:}
191新增:- (void)serve {
192新增: struct sockaddr_un address;
193新增: if (!addressForSocket(&address))
194新增: return;
195新增: NSString *dir = socketPath().stringByDeletingLastPathComponent;
196新增: NSFileManager *fm = [NSFileManager defaultManager];
197新增: if (![fm createDirectoryAtPath:dir
198新增: withIntermediateDirectories:YES
199新增: attributes:@{NSFilePosixPermissions : @0700}
200新增: error:nil])
201新增: return;
202新增: struct stat st;
203新增: if (lstat(dir.fileSystemRepresentation, &st) || !S_ISDIR(st.st_mode) || st.st_uid != getuid() ||
204新增: (st.st_mode & 0077))
205新增: return;
206新增: // The advisory lock distinguishes a dead listener from another running copy.
207新增: NSString *l = [dir stringByAppendingPathComponent:@"project-terminal.lock"];
208新增: int lock = open(l.fileSystemRepresentation, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600);
209新增: if (lock < 0 || flock(lock, LOCK_EX | LOCK_NB)) {
210新增: if (lock >= 0)
211新增: close(lock);
212新增: return;
213新增: }
214新增: if (!lstat(address.sun_path, &st) && !(S_ISSOCK(st.st_mode) && st.st_uid == getuid())) {
215新增: close(lock);
216新增: return;
217新增: }
218新增: unlink(address.sun_path);
219新增: int listener = socket(AF_UNIX, SOCK_STREAM, 0);
220新增: if (listener < 0 || bind(listener, (struct sockaddr *)&address, sizeof(address)) ||
221新增: chmod(address.sun_path, 0600) || listen(listener, 12)) {
222新增: if (listener >= 0)
223新增: close(listener);
224新增: close(lock);
225新增: return;
226新增: }
227新增: fcntl(listener, F_SETFD, FD_CLOEXEC);
228新增: for (;;) {
229新增: int fd = accept(listener, NULL, NULL);
230新增: if (fd < 0) {
231新增: if (errno == EINTR)
232新增: continue;
233新增: break;
234新增: }
235新增: fcntl(fd, F_SETFD, FD_CLOEXEC);
236新增: dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
237新增: @autoreleasepool {
238新增: [self handle:fd];
239新增: close(fd);
240新增: }
241新增: });
242新增: }
243新增: close(listener);
244新增: unlink(address.sun_path);
245新增: close(lock);
246新增:}
247新增:- (void)handle:(int)fd {
248新增: uid_t uid;
249新增: gid_t gid;
250新增: if (getpeereid(fd, &uid, &gid) || uid != getuid())
251新增: return;
252新增: struct timeval timeout = {4, 0};
253新增: setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
254新增: char bytes[8192], ancillary[CMSG_SPACE(8 * sizeof(int))];
255新增: int tty = -1;
256新增: size_t len = 0;
257新增: BOOL extra = NO;
258新增: struct iovec iov = {bytes, sizeof(bytes)};
259新增: struct msghdr msg = {0};
260新增: msg.msg_iov = &iov;
261新增: msg.msg_iovlen = 1;
262新增: msg.msg_control = ancillary;
263新增: msg.msg_controllen = sizeof(ancillary);
264新增: ssize_t n = recvmsg(fd, &msg, 0);
265新增: if (n <= 0)
266新增: return;
267新增: for (struct cmsghdr *c = CMSG_FIRSTHDR(&msg); c; c = CMSG_NXTHDR(&msg, c)) {
268新增: if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS)
269新增: continue;
270新增: size_t count = (c->cmsg_len - CMSG_LEN(0)) / sizeof(int);
271新增: int *fds = (int *)CMSG_DATA(c);
272新增: for (size_t i = 0; i < count; i++) {
273新增: if (tty < 0) {
274新增: tty = fds[i];
275新增: fcntl(tty, F_SETFD, FD_CLOEXEC);
276新增: } else {
277新增: close(fds[i]);
278新增: extra = YES;
279新增: }
280新增: }
281新增: }
282新增: @try {
283新增: if (extra || (msg.msg_flags & MSG_CTRUNC))
284新增: return;
285新增: len = (size_t)n;
286新增: while (!memchr(bytes, '\n', len) && len < sizeof(bytes)) {
287新增: n = read(fd, bytes + len, sizeof(bytes) - len);
288新增: if (n <= 0)
289新增: return;
290新增: len += n;
291新增: }
292新增: if (bytes[len - 1] != '\n')
293新增: return;
294新增: NSDictionary *req = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:bytes length:len]
295新增: options:0
296新增: error:nil];
297新增: if (![req isKindOfClass:NSDictionary.class])
298新增: return;
299新增: NSString *project = req[@"path"], *action = req[@"action"];
300新增: if (!mountID(project)) {
301新增: reply(fd, "ERR\n");
302新增: return;
303新增: }
304新增: // The authenticated window forwarder obtains the live NSWindow from the
305新增: // process that opened the panel. Closing it invalidates the nonce.
306新增: if ([action isEqual:@"panel"] && tty < 0) {
307新增: __block NSDictionary *state;
308新增: dispatch_sync(dispatch_get_main_queue(), ^{
309新增: if ([self->_requesting isEqual:project] && self->_nonce && self->_panel.visible &&
310新增: self->_panel.windowNumber > 0 &&
311新增: [self->_panel.directoryURL.URLByStandardizingPath.path isEqual:project])
312新增: state = @{
313新增: @"path" : project,
314新增: @"nonce" : self->_nonce,
315新增: @"pid" : @(getpid()),
316新增: @"windowNumber" : @(self->_panel.windowNumber)
317新增: };
318新增: });
319新增: if (!state) {
320新增: reply(fd, "ERR\n");
321新增: return;
322新增: }
323新增: NSData *json = [NSJSONSerialization dataWithJSONObject:state options:0 error:nil];
324新增: writeAll(fd, json.bytes, json.length);
325新增: reply(fd, "\n");
326新增: return;
327新增: }
328新增: if ([action isEqual:@"probe"] && tty < 0) {
329新增: __block NSString *status;
330新增: dispatch_sync(dispatch_get_main_queue(), ^{
331新增: status = [self probe:req];
332新增: });
333新增: reply(fd, [status stringByAppendingString:@"\n"].UTF8String);
334新增: return;
335新增: }
336新增: BOOL claude = [action isEqual:@"claude"];
337新增: NSString *launch = req[@"launch"];
338新增: if (tty < 0 || !([action isEqual:@"terminal"] || [action isEqual:@"editor"] || claude) ||
339新增: (claude && (![launch isKindOfClass:NSString.class] || !launch.length ||
340新增: [launch lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 4096))) {
341新增: reply(fd, "ERR\n");
342新增: return;
343新增: }
344新增: struct stat st;
345新增: char name[PATH_MAX];
346新增: if (fstat(tty, &st) || !S_ISCHR(st.st_mode) || st.st_uid != uid ||
347新增: ttyname_r(tty, name, sizeof(name)) || strncmp(name, "/dev/ttys", 9) || !isatty(tty)) {
348新增: reply(fd, "ERR\n");
349新增: return;
350新增: }
351新增: __block NSString *identity;
352新增: dispatch_sync(dispatch_get_main_queue(), ^{
353新增: identity = self->_ready[project];
354新增: });
355新增: if (!identity || ![identity isEqual:mountID(project)]) {
356新增: reply(fd, "ERR\n");
357新增: return;
358新增: }
359新增: NSString *exe = NSBundle.mainBundle.executableURL.path;
360新增: char *argv[] = {(char *)exe.fileSystemRepresentation, "--child",
361新增: (char *)project.fileSystemRepresentation, (char *)action.UTF8String,
362新增: claude ? (char *)launch.UTF8String : NULL, NULL};
363新增: posix_spawn_file_actions_t files;
364新增: posix_spawn_file_actions_init(&files);
365新增: posix_spawn_file_actions_adddup2(&files, tty, 3);
366新增: posix_spawnattr_t attr;
367新增: posix_spawnattr_init(&attr);
368新增: posix_spawnattr_setflags(&attr, POSIX_SPAWN_CLOEXEC_DEFAULT);
369新增: pid_t pid;
370新增: int err = posix_spawn(&pid, argv[0], &files, &attr, argv, environ);
371新增: posix_spawnattr_destroy(&attr);
372新增: posix_spawn_file_actions_destroy(&files);
373新增: if (err) {
374新增: reply(fd, "ERR\n");
375新增: return;
376新增: }
377新增: reply(fd, "OK\n");
378新增: for (;;) {
379新增: int childStatus;
380新增: pid_t done = waitpid(pid, &childStatus, WNOHANG);
381新增: if (done == pid || (done < 0 && errno != EINTR))
382新增: break;
383新增: struct pollfd pollfd = {fd, POLLIN, 0};
384新增: if (poll(&pollfd, 1, 500) > 0 || ![identity isEqual:mountID(project)]) {
385新增: kill(pid, SIGHUP);
386新增: kill(-pid, SIGHUP);
387新增: for (int i = 0; i < 15; i++) {
388新增: if (waitpid(pid, &childStatus, WNOHANG) == pid)
389新增: return;
390新增: usleep(20000);
391新增: }
392新增: kill(pid, SIGKILL);
393新增: kill(-pid, SIGKILL);
394新增: waitpid(pid, &childStatus, 0);
395新增: break;
396新增: }
397新增: }
398新增: } @finally {
399新增: if (tty >= 0)
400新增: close(tty);
401新增: }
402新增:}
403新增:- (void)panel:(id)sender didChangeToDirectoryURL:(NSURL *)url {
404新增: // The host offered exactly one mounted project, and must never preview
405新增: // guest directories reached through the dialog's sidebar.
406新增: if (sender == _panel && _requesting && url && ![url.URLByStandardizingPath.path isEqual:_requesting])
407新增: [_panel cancel:nil];
408新增:}
409新增:@end
410新增:
411新增:static int probeCLI(int argc, char **argv) {
412新增: if (argc != 5)
413新增: return 2;
414新增: struct sockaddr_un address;
415新增: if (!addressForSocket(&address))
416新增: return 1;
417新增: int fd = socket(AF_UNIX, SOCK_STREAM, 0);
418新增: if (fd < 0)
419新增: return 1;
420新增: struct timeval wait = {4, 0};
421新增: setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &wait, sizeof(wait));
422新增: if (connect(fd, (struct sockaddr *)&address, sizeof(address))) {
423新增: close(fd);
424新增: return 1;
425新增: }
426新增: uid_t peer;
427新增: gid_t group;
428新增: if (getpeereid(fd, &peer, &group) || peer != getuid()) {
429新增: close(fd);
430新增: return 1;
431新增: }
432新增: NSData *j = [NSJSONSerialization dataWithJSONObject:@{
433新增: @"action" : @"probe",
434新增: @"path" : @(argv[2]),
435新增: @"file" : @(argv[3]),
436新增: @"expected" : @(argv[4])
437新增: }
438新增: options:0
439新增: error:nil];
440新增: BOOL ok = writeAll(fd, j.bytes, j.length) && writeAll(fd, "\n", 1);
441新增: FILE *f = fdopen(fd, "r");
442新增: if (!f) {
443新增: close(fd);
444新增: return 1;
445新增: }
446新增: char line[32] = {0};
447新增: if (!ok || !fgets(line, sizeof(line), f)) {
448新增: fclose(f);
449新增: return 1;
450新增: }
451新增: fclose(f);
452新增: if (!strcmp(line, "OK\n")) {
453新增: puts("OK");
454新增: return 0;
455新增: }
456新增: if (!strcmp(line, "PENDING\n")) {
457新增: puts("PENDING");
458新增: return 75;
459新增: }
460新增: return 1;
461新增:}
462新增:
463新增:int main(int argc, char **argv) {
464新增: @autoreleasepool {
465新增: if (argc > 1 && !strcmp(argv[1], "probe"))
466新增: return probeCLI(argc, argv);
467新增: if ((argc == 4 || (argc == 5 && !strcmp(argv[3], "claude"))) && !strcmp(argv[1], "--child")) {
468新增: if (!mountID(@(argv[2])) || setsid() < 0 || ioctl(3, TIOCSCTTY, 0) < 0)
469新增: return 1;
470新增: for (int i = 0; i < 3; i++)
471新增: if (dup2(3, i) < 0)
472新增: return 1;
473新增: close(3);
474新增: signal(SIGPIPE, SIG_DFL);
475新增: if (chdir(argv[2]))
476新增: return 1;
477新增: setenv("TERM", "xterm-256color", 1);
478新增: setenv("PWD", argv[2], 1);
479新增: setenv("PATH", "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", 1);
480新增: if (argc == 5) {
481新增: execl("/usr/local/libexec/cage-cli/bin/python3", "python3", "-I",
482新增: "/usr/local/libexec/cage-cli/macos-cli.py", "macos-launch", argv[4], (char *)NULL);
483新增: return 1;
484新增: }
485新增: if (!strcmp(argv[3], "terminal"))
486新增: execl("/bin/zsh", "-zsh", (char *)NULL);
487新增: if (!strcmp(argv[3], "editor"))
488新增: execl("/usr/local/libexec/cage-macos-editor", "cage-macos-editor", (char *)NULL);
489新增: return 1;
490新增: }
491新增: if (argc != 1)
492新增: return 2;
493新增: signal(SIGPIPE, SIG_IGN);
494新增: umask(0077);
495新增: NSApplication *app = NSApplication.sharedApplication;
496新增: ProjectAccess *delegate = [[ProjectAccess alloc] init];
497新增: app.delegate = delegate;
498新增: [app setActivationPolicy:NSApplicationActivationPolicyAccessory];
499新增: [app run];
500新增: return 0;
501新增: }
502新增:}
新增scripts/guest-os/macos-project-panel.swift+80 −0看文件
@@ -0,0 +1,80 @@
1新增:// Only a currently pending panel, attested by the installed project access
2新增:// agent and addressed by the host's active project grant, may be displayed.
3新增:import AppKit
4新增:import ScreenCaptureKit
5新增:import Security
6新增:
7新增:struct ProjectPanel: Decodable, Equatable {
8新增: let path, nonce: String
9新增: let pid: pid_t
10新增: let windowNumber: CGWindowID
11新增:}
12新增:
13新增:private func matchesInstalledProjectApp(pid: pid_t) -> Bool {
14新增: let path = "/Applications/CageProjectAccess.app"
15新增: guard NSRunningApplication(processIdentifier: pid)?.bundleURL?.path == path else { return false }
16新增: let url = URL(fileURLWithPath: path)
17新增: var dynamic: SecCode?, installed: SecStaticCode?, running: SecStaticCode?, requirement: SecRequirement?
18新增: let attributes = [kSecGuestAttributePid: pid] as CFDictionary
19新增: var st = stat()
20新增: guard lstat(path, &st) == 0, st.st_uid == 0, st.st_mode & 0o022 == 0,
21新增: SecRequirementCreateWithString(#"identifier "dev.cage.guest.project-access""# as CFString, [], &requirement) == errSecSuccess,
22新增: let requirement,
23新增: SecCodeCopyGuestWithAttributes(nil, attributes, [], &dynamic) == errSecSuccess, let dynamic,
24新增: SecCodeCheckValidity(dynamic, [], requirement) == errSecSuccess,
25新增: SecCodeCopyStaticCode(dynamic, [], &running) == errSecSuccess, let running,
26新增: SecStaticCodeCreateWithPath(url as CFURL, [], &installed) == errSecSuccess, let installed,
27新增: SecStaticCodeCheckValidity(installed, [], requirement) == errSecSuccess else { return false }
28新增: func hash(_ code: SecStaticCode) -> Data? {
29新增: var info: CFDictionary?
30新增: guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess else { return nil }
31新增: return (info as? [String: Any])?[kSecCodeInfoUnique as String] as? Data
32新增: }
33新增: guard let digest = hash(installed) else { return false }
34新增: return digest == hash(running)
35新增:}
36新增:
37新增:func pendingProjectPanel(_ path: String) throws -> ProjectPanel {
38新增: let missing = Failure(7, "no_project_panel")
39新增: let directory = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Cage/Projects", isDirectory: true)
40新增: let leaf = (path as NSString).lastPathComponent
41新增: guard leaf.range(of: "^[a-f0-9]{24}$", options: .regularExpression) != nil,
42新增: path == directory.appendingPathComponent(leaf).path else { throw missing }
43新增: var addr = sockaddr_un()
44新增: addr.sun_family = sa_family_t(AF_UNIX)
45新增: let socketPath = NSHomeDirectory() + "/Library/Application Support/Cage/project-terminal.sock"
46新增: let maxPath = MemoryLayout.size(ofValue: addr.sun_path)
47新增: guard socketPath.utf8.count < maxPath else { throw missing }
48新增: withUnsafeMutableBytes(of: &addr.sun_path) { dst in socketPath.utf8CString.withUnsafeBytes { dst.copyBytes(from: $0) } }
49新增: let fd = socket(AF_UNIX, SOCK_STREAM, 0)
50新增: guard fd >= 0 else { throw missing }
51新增: let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
52新增: let connected = withUnsafePointer(to: &addr) { ptr in
53新增: ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
54新增: }
55新增: var user = uid_t(), group = gid_t(), peer = pid_t(), len = socklen_t(MemoryLayout<pid_t>.size)
56新增: guard connected == 0, getpeereid(fd, &user, &group) == 0, user == geteuid(),
57新增: getsockopt(fd, SOL_LOCAL, LOCAL_PEERPID, &peer, &len) == 0, matchesInstalledProjectApp(pid: peer) else { throw missing }
58新增: var timeout = timeval(tv_sec: 2, tv_usec: 0)
59新增: setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout)))
60新增: var request = try JSONSerialization.data(withJSONObject: ["action":"panel", "path":path])
61新增: request.append(10)
62新增: try file.write(contentsOf: request)
63新增: var body = Data()
64新增: while !body.contains(10), body.count < 4096, let chunk = try file.read(upToCount: 4096 - body.count), !chunk.isEmpty { body.append(chunk) }
65新增: guard let result = try? JSONDecoder().decode(ProjectPanel.self, from: body), result.path == path, result.pid == peer,
66新增: result.windowNumber > 0, UUID(uuidString: result.nonce) != nil else { throw missing }
67新增: return result
68新增:}
69新增:
70新增:@MainActor
71新增:func visibleProjectPanel(_ panel: ProjectPanel) async throws -> SCWindow {
72新增: guard CGPreflightScreenCaptureAccess() else { throw Failure(6, "project_screen_permission") }
73新增: let candidates = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true)
74新增: guard let window = candidates.windows.first(where: { $0.windowID == panel.windowNumber && $0.isOnScreen }),
75新增: let owner = window.owningApplication, NSWorkspace.shared.frontmostApplication?.processIdentifier == panel.pid,
76新增: owner.processID == panel.pid, owner.bundleIdentifier == "dev.cage.guest.project-access" else {
77新增: throw Failure(7, "no_project_panel")
78新增: }
79新增: return window
80新增:}
新增scripts/guest-os/macos-project-terminal.m+168 −0看文件
@@ -0,0 +1,168 @@
1新增:// Guest-side terminal client. The signed-in helper owns the selected folder's
2新增:// security scope. It gives a login shell our new slave PTY, while SSH owns
3新增:// the outer terminal. The outer controlling terminal never changes owners.
4新增:#import <Foundation/Foundation.h>
5新增:#include <sys/ioctl.h>
6新增:#include <sys/socket.h>
7新增:#include <sys/stat.h>
8新增:#include <sys/un.h>
9新增:#include <util.h>
10新增:#include <poll.h>
11新增:#include <signal.h>
12新增:#include <fcntl.h>
13新增:#include <errno.h>
14新增:#include <stdio.h>
15新增:#include <string.h>
16新增:#include <unistd.h>
17新增:
18新增:static volatile sig_atomic_t signalWrite = -1;
19新增:static struct termios original;
20新增:static int changedTerminal;
21新增:
22新增:static void restoreTerminal(void) {
23新增: if (changedTerminal) tcsetattr(STDIN_FILENO, TCSANOW, &original);
24新增:}
25新增:
26新增:static void signalHandler(int number) {
27新增: int saved = errno;
28新增: unsigned char value = number;
29新增: if (signalWrite >= 0) (void)write(signalWrite, &value, 1);
30新增: errno = saved;
31新增:}
32新增:
33新增:static int writeAll(int fd, const void *data, size_t size) {
34新增: const unsigned char *bytes = data;
35新增: while (size) {
36新增: ssize_t n = write(fd, bytes, size);
37新增: if (n < 0 && errno == EINTR) continue;
38新增: if (n <= 0) return -1;
39新增: bytes += n;
40新增: size -= (size_t)n;
41新增: }
42新增: return 0;
43新增:}
44新增:
45新增:static int sendTerminal(int control, int slave, NSData *request) {
46新增: struct iovec iov = {(void *)request.bytes, request.length};
47新增: union { struct cmsghdr align; char bytes[CMSG_SPACE(sizeof(int))]; } rights = {0};
48新增: struct msghdr msg = {0};
49新增: msg.msg_iov = &iov;
50新增: msg.msg_iovlen = 1;
51新增: msg.msg_control = rights.bytes;
52新增: msg.msg_controllen = sizeof(rights.bytes);
53新增: struct cmsghdr *header = CMSG_FIRSTHDR(&msg);
54新增: header->cmsg_level = SOL_SOCKET;
55新增: header->cmsg_type = SCM_RIGHTS;
56新增: header->cmsg_len = CMSG_LEN(sizeof(int));
57新增: memcpy(CMSG_DATA(header), &slave, sizeof(slave));
58新增: ssize_t n;
59新增: do { n = sendmsg(control, &msg, 0); } while (n < 0 && errno == EINTR);
60新增: if (n <= 0) return -1;
61新增: return writeAll(control, (const unsigned char *)request.bytes + n, request.length - (size_t)n);
62新增:}
63新增:
64新增:static int relay(int control, int master, int signals) {
65新增: struct pollfd fds[] = {{STDIN_FILENO, POLLIN, 0}, {master, POLLIN, 0},
66新增: {signals, POLLIN, 0}, {control, POLLIN, 0}};
67新增: char buffer[16384];
68新增: for (;;) {
69新增: if (poll(fds, 4, -1) < 0) {
70新增: if (errno == EINTR) continue;
71新增: return 1;
72新增: }
73新增: if (fds[2].revents) {
74新增: ssize_t n = read(signals, buffer, sizeof(buffer));
75新增: for (ssize_t j = 0; j < n; j++) {
76新增: if (buffer[j] != SIGWINCH) return 0;
77新增: }
78新增: struct winsize size;
79新增: if (ioctl(STDIN_FILENO, TIOCGWINSZ, &size) == 0)
80新增: ioctl(master, TIOCSWINSZ, &size);
81新增: }
82新增: if (fds[1].revents) {
83新增: ssize_t n = read(master, buffer, sizeof(buffer));
84新增: if (n < 0 && errno == EINTR) continue;
85新增: if (n <= 0) return (n == 0 || errno == EIO) ? 0 : 1;
86新增: if (writeAll(STDOUT_FILENO, buffer, (size_t)n) < 0) return 1;
87新增: // The shell can exit just after printing. Drain the PTY before
88新增: // treating an accompanying control-socket close as terminal EOF.
89新增: if (fds[3].revents) continue;
90新增: }
91新增: if (fds[3].revents) return 0;
92新增: if (fds[0].revents) {
93新增: ssize_t n = read(STDIN_FILENO, buffer, sizeof(buffer));
94新增: if (n < 0 && errno == EINTR) continue;
95新增: if (n <= 0) return 0;
96新增: if (writeAll(master, buffer, (size_t)n) < 0) return 1;
97新增: }
98新增: }
99新增:}
100新增:
101新增:int main(int argc, char **argv) {
102新增: @autoreleasepool {
103新增: BOOL editor = argc == 3 && strcmp(argv[1], "--editor") == 0;
104新增: BOOL claude = argc == 4 && strcmp(argv[1], "--claude") == 0;
105新增: BOOL interactive = isatty(STDIN_FILENO) && isatty(STDOUT_FILENO);
106新增: if ((argc != 2 && !editor && !claude) || (!editor && !interactive)) {
107新增: fprintf(stderr, "A project directory and an interactive guest terminal are required.\n");
108新增: return 2;
109新增: }
110新增: NSString *project = [NSString stringWithUTF8String:argv[editor || claude ? 2 : 1]];
111新增: if (!project || !project.isAbsolutePath) return 2;
112新增: NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/Cage/project-terminal.sock"];
113新增: struct sockaddr_un addr = {.sun_family = AF_UNIX};
114新增: if (strlcpy(addr.sun_path, path.fileSystemRepresentation, sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) return 2;
115新增: addr.sun_len = SUN_LEN(&addr);
116新增: int control = socket(AF_UNIX, SOCK_STREAM, 0);
117新增: if (control < 0 || connect(control, (struct sockaddr *)&addr, addr.sun_len) != 0) {
118新增: fprintf(stderr, "The project helper is unavailable in this guest login session.\n");
119新增: return 1;
120新增: }
121新增: uid_t peer; gid_t group;
122新增: if (getpeereid(control, &peer, &group) < 0 || peer != geteuid()) {
123新增: fprintf(stderr, "The project helper belongs to a different guest user.\n");
124新增: return 1;
125新增: }
126新增: signal(SIGPIPE, SIG_IGN);
127新增: int master, slave;
128新增: struct winsize size = {.ws_row = 32, .ws_col = 100};
129新增: if (interactive && (tcgetattr(STDIN_FILENO, &original) < 0 || ioctl(STDIN_FILENO, TIOCGWINSZ, &size) < 0)) return 1;
130新增: // The guest browser launches its fixed editor over pipes. Only the
131新增: // helper's child needs a controlling terminal in that case.
132新增: if (openpty(&master, &slave, NULL, interactive ? &original : NULL, &size) != 0 || fchmod(slave, 0600) < 0) return 1;
133新增: NSMutableDictionary *operation = [@{@"action": editor ? @"editor" : claude ? @"claude" : @"terminal", @"path": project} mutableCopy];
134新增: if (claude) {
135新增: NSString *launch = [NSString stringWithUTF8String:argv[3]];
136新增: if (!launch || [launch lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 4096) return 2;
137新增: operation[@"launch"] = launch;
138新增: }
139新增: NSMutableData *request = [[NSJSONSerialization dataWithJSONObject:operation options:0 error:nil] mutableCopy];
140新增: [request appendBytes:"\n" length:1];
141新增: if (sendTerminal(control, slave, request) < 0) return 1;
142新增: close(slave);
143新增: char reply[3];
144新增: if (recv(control, reply, sizeof(reply), MSG_WAITALL) != sizeof(reply) || memcmp(reply, "OK\n", 3) != 0) {
145新增: fprintf(stderr, "The guest user has not approved this mounted project.\n");
146新增: return 1;
147新增: }
148新增: int signals[2];
149新增: if (pipe(signals) < 0 || fcntl(signals[1], F_SETFL, O_NONBLOCK) < 0) return 1;
150新增: signalWrite = signals[1];
151新增: const int events[] = {SIGWINCH, SIGHUP, SIGINT, SIGTERM, SIGQUIT};
152新增: struct sigaction action = {.sa_handler = signalHandler};
153新增: sigemptyset(&action.sa_mask);
154新增: for (size_t i = 0; i < sizeof(events)/sizeof(events[0]); i++) sigaction(events[i], &action, NULL);
155新增: if (interactive) {
156新增: struct termios raw = original;
157新增: cfmakeraw(&raw);
158新增: atexit(restoreTerminal);
159新增: if (tcsetattr(STDIN_FILENO, TCSANOW, &raw) < 0) return 1;
160新增: changedTerminal = 1;
161新增: }
162新增: if (ioctl(STDIN_FILENO, TIOCGWINSZ, &size) == 0) ioctl(master, TIOCSWINSZ, &size);
163新增: int code = relay(control, master, signals[0]);
164新增: close(master);
165新增: close(control);
166新增: return code;
167新增: }
168新增:}
新增scripts/guest-os/macos-setup-account.m+170 −0看文件
@@ -0,0 +1,170 @@
1新增:// The only administrator created by the native installer. The durable receipt
2新增:// is root-only and binds both the directory service GUID and the numeric uid.
3新增:#import <Foundation/Foundation.h>
4新增:#import <OpenDirectory/OpenDirectory.h>
5新增:#include <pwd.h>
6新增:#include <sys/file.h>
7新增:#include <sys/stat.h>
8新增:#include <sys/sysctl.h>
9新增:#include <unistd.h>
10新增:
11新增:static NSString *const directory = @"/var/db/cage-initial-setup";
12新增:static NSString *const setup = @"cagesetup";
13新增:
14新增:static void require(BOOL ok, const char *reason) {
15新增: if (!ok) { fprintf(stderr, "%s\n", reason); exit(1); }
16新增:}
17新增:
18新增:static NSArray *users(ODNode *node, NSString *name) {
19新增: ODQuery *q = [ODQuery queryWithNode:node forRecordTypes:kODRecordTypeUsers
20新增: attribute:kODAttributeTypeRecordName matchType:kODMatchEqualTo queryValues:name
21新增: returnAttributes:@[kODAttributeTypeGUID, kODAttributeTypeUniqueID] maximumResults:2 error:NULL];
22新增: NSArray *results = [q resultsAllowingPartial:NO error:NULL];
23新增: require(results != nil && results.count <= 1, "Cannot identify the local guest user.");
24新增: return results;
25新增:}
26新增:
27新增:static void save(NSDictionary *d, NSURL *file) {
28新增: NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:NULL];
29新增: require(data && [data writeToURL:file options:NSDataWritingAtomic error:NULL], "Cannot persist the guest setup receipt.");
30新增:}
31新增:
32新增:static BOOL member(ODRecord *group, ODRecord *user) {
33新增: NSError *err = nil;
34新增: BOOL result = [group isMemberRecord:user error:&err];
35新增: require(!err, "Cannot inspect guest administrator privileges.");
36新增: return result;
37新增:}
38新增:
39新增:static BOOL disabled(ODRecord *record) {
40新增: NSError *error = nil;
41新增: BOOL allowed = [record authenticationAllowedAndReturnError:&error];
42新增: return !allowed && [error.domain isEqual:ODFrameworkErrorDomain] && error.code == kODErrorCredentialsAccountDisabled;
43新增:}
44新增:
45新增:static void retire(ODNode *node, ODRecord *admin, ODRecord *record) {
46新增: if (member(admin, record)) require([admin removeMemberRecord:record error:NULL], "Cannot revoke setup administrator privileges.");
47新增: require(!member(admin, record), "The setup user still has administrator privileges.");
48新增: if (!disabled(record)) {
49新增: // Invalidate the initial guest password before disabling the account.
50新增: // This replacement is never persisted or exposed to a caller.
51新增: NSString *replacement = [@"Z9!" stringByAppendingString:NSUUID.UUID.UUIDString];
52新增: require([record changePassword:nil toPassword:replacement error:NULL], "Cannot clear the temporary guest credential.");
53新增: require([record setValue:@"/usr/bin/false" forAttribute:kODAttributeTypeUserShell error:NULL], "Cannot close the temporary login shell.");
54新增: NSTask *task = [[NSTask alloc] init];
55新增: task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/pwpolicy"];
56新增: task.arguments = @[@"-n", @"/Local/Default", @"-u", setup, @"-disableuser"];
57新增: require([task launchAndReturnError:NULL], "Cannot invoke the guest account policy tool.");
58新增: [task waitUntilExit];
59新增: require(task.terminationStatus == 0, "Cannot disable the temporary guest user.");
60新增: }
61新增: ODRecord *current = users(node, setup).firstObject;
62新增: require(current && disabled(current) && !member(admin, current) &&
63新增: [[current valuesForAttribute:kODAttributeTypeUserShell error:NULL].firstObject isEqual:@"/usr/bin/false"],
64新增: "The temporary guest login remains available.");
65新增:}
66新增:
67新增:int main(int argc, const char **argv) {
68新增: @autoreleasepool {
69新增: BOOL prepare = argc == 3 && strcmp(argv[1], "prepare") == 0;
70新增: require(prepare || argc == 1, "Invalid first setup operation.");
71新增: char model[128] = {0};
72新增: size_t size = sizeof(model);
73新增: struct stat st;
74新增: require(getuid() == 0 && sysctlbyname("hw.model", model, &size, NULL, 0) == 0 &&
75新增: strncmp(model, "VirtualMac", 10) == 0 && lstat("/var/db/cage-guest-os", &st) == 0 &&
76新增: S_ISREG(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 022) &&
77新增: [[NSString stringWithContentsOfFile:@"/var/db/cage-guest-os" encoding:NSUTF8StringEncoding error:NULL] isEqual:@"macos\n"],
78新增: "Run as root in the selected Cage virtual Mac.");
79新增: umask(077);
80新增: if (prepare && mkdir(directory.fileSystemRepresentation, 0700) != 0) require(errno == EEXIST, "Cannot create private receipt directory.");
81新增: require(lstat(directory.fileSystemRepresentation, &st) == 0 && S_ISDIR(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 077),
82新增: "Invalid private setup directory.");
83新增: NSString *lockPath = [directory stringByAppendingPathComponent:@"lock"];
84新增: int lock = open(lockPath.fileSystemRepresentation, O_NOFOLLOW|O_CREAT|O_RDWR, 0600);
85新增: require(lock >= 0 && flock(lock, LOCK_EX|LOCK_NB) == 0, "Another first setup operation is running.");
86新增: NSURL *file = [NSURL fileURLWithPath:[directory stringByAppendingPathComponent:@"account.json"]];
87新增: NSData *data = nil;
88新增: if (lstat(file.fileSystemRepresentation, &st) == 0) {
89新增: require(S_ISREG(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 077) && st.st_size > 0 && st.st_size <= 2048,
90新增: "Invalid guest setup receipt.");
91新增: data = [NSData dataWithContentsOfURL:file]; require(data != nil,"Unreadable guest setup receipt.");
92新增: } else require(errno == ENOENT && prepare, "Missing guest setup receipt.");
93新增: ODNode *node = [ODNode nodeWithSession:[ODSession defaultSession] name:@"/Local/Default" error:NULL];
94新增: 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新增: 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.");
101新增: NSMutableDictionary *receipt;
102新增: if (data) {
103新增: receipt = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];
104新增: require([receipt isKindOfClass:NSMutableDictionary.class] &&
105新增: [[NSUUID alloc] initWithUUIDString:receipt[@"guid"]] && [receipt[@"uid"] intValue] >= 502 &&
106新增: [[NSUUID alloc] initWithUUIDString:receipt[@"installation"]] && (!prepare || [receipt[@"installation"] isEqual:install]),
107新增: "The setup account belongs to a different installation.");
108新增: } else {
109新增: require(!record && !getpwnam("cagesetup"), "A user already has the setup name; no account was modified.");
110新增: int uid = 502;
111新增: while (uid < 1000 && getpwuid(uid)) uid++;
112新增: require(uid < 1000, "No free local setup UID.");
113新增: receipt = [@{@"installation":install, @"guid":NSUUID.UUID.UUIDString, @"uid":@(uid), @"state":@"creating"} mutableCopy];
114新增: save(receipt, file);
115新增: }
116新增: NSString *uid = [receipt[@"uid"] stringValue];
117新增: if (record) {
118新增: NSString *guid = [record valuesForAttribute:kODAttributeTypeGUID error:NULL].firstObject;
119新增: NSString *actualUID = [record valuesForAttribute:kODAttributeTypeUniqueID error:NULL].firstObject;
120新增: require(guid && [guid caseInsensitiveCompare:receipt[@"guid"]] == NSOrderedSame && [actualUID isEqual:uid],
121新增: "Refusing to modify an unrelated guest user.");
122新增: }
123新增: NSString *phase = receipt[@"state"];
124新增: require([@[@"creating",@"ready",@"retiring",@"retired"] containsObject:phase], "Unknown guest setup state.");
125新增: if (prepare) {
126新增: 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.");
134新增: if (!record) {
135新增: require([phase isEqual:@"creating"] && !getpwuid([receipt[@"uid"] intValue]), "Setup account disappeared or its UID is in use.");
136新增: record = [node createRecordWithRecordType:kODRecordTypeUsers name:setup attributes:@{
137新增: kODAttributeTypeGUID:@[receipt[@"guid"]], kODAttributeTypeUniqueID:@[uid],
138新增: kODAttributeTypePrimaryGroupID:@[@"20"], kODAttributeTypeFullName:@[@"Cage Setup"],
139新增: kODAttributeTypeNFSHomeDirectory:@[@"/var/empty"], kODAttributeTypeUserShell:@[@"/bin/sh"],
140新增: @"dsAttrTypeNative:IsHidden":@[@"1"]
141新增: } error:NULL];
142新增: require(record != nil, "Cannot create the dedicated temporary guest account.");
143新增: }
144新增: if ([phase isEqual:@"creating"])
145新增: require([record changePassword:nil toPassword:pw error:NULL], "Cannot initialize the temporary password.");
146新增: require([record verifyPassword:pw error:NULL], "The stored credential does not match this guest.");
147新增: // macOS PAM checks /etc/shells even for System Settings authorization.
148新增: // A hidden admin with /usr/bin/false passes OD password checks but
149新增: // authorizationhost rejects it during account management.
150新增: if ([[record valuesForAttribute:kODAttributeTypeUserShell error:NULL].firstObject isEqual:@"/usr/bin/false"])
151新增: require([record setValue:@"/bin/sh" forAttribute:kODAttributeTypeUserShell error:NULL], "Cannot repair the temporary account's login shell.");
152新增: if (!member(admin, record)) require([admin addMemberRecord:record error:NULL], "Cannot grant temporary setup privileges.");
153新增: require(member(admin, record), "Guest setup privileges were not applied.");
154新增: receipt[@"state"] = @"ready";
155新增: } else {
156新增: require(![phase isEqual:@"creating"], "The temporary account has not completed setup.");
157新增: if (![phase isEqual:@"retired"]) {
158新增: receipt[@"state"] = @"retiring"; save(receipt,file);
159新增: }
160新增: // Keep the disabled directory record. Its home is the shared system
161新增: // directory /var/empty and must never be processed as a deletable home.
162新增: if (record) retire(node, admin, record);
163新增: require(!member(admin,ordinary), "The regular Cage user is a guest administrator.");
164新增: receipt[@"state"] = @"retired";
165新增: }
166新增: save(receipt,file);
167新增: close(lock);
168新增: return 0;
169新增: }
170新增:}
新增scripts/guest-os/macos-setup-bridge.h+5 −0看文件
@@ -0,0 +1,5 @@
1新增:#include <stdbool.h>
2新增:
3新增:// Signature of Code-Hex/vz v3.7.1's startVirtualMachineWindow cgo entry.
4新增:void CageRunSetupBridge(void *machine, void *queue, double width, double height,
5新增: const char *title, bool controller);
新增scripts/guest-os/macos-setup-bridge.m+47 −0看文件
@@ -0,0 +1,47 @@
1新增:#import "macos-setup-bridge.h"
2新增:#import "macos-setup-view.h"
3新增:
4新增:// Build-only QA overlay. Demonstrate handing the actual VM to the main thread
5新增:// and closing a session. It never publishes a framebuffer or accepts input.
6新增:void CageRunSetupBridge(void *machine, void *queue, double width, double height,
7新增: const char *title, bool controller) {
8新增: (void)width; (void)height; (void)title; (void)controller;
9新增: @autoreleasepool {
10新增: if (!NSThread.isMainThread) {
11新增: fprintf(stderr, "Cage setup probe requires the AppKit main thread\n");
12新增: return;
13新增: }
14新增: NSApplication *app = [NSApplication sharedApplication];
15新增: [app setActivationPolicy:NSApplicationActivationPolicyProhibited];
16新增: VZVirtualMachine *vm = (__bridge VZVirtualMachine *)machine;
17新增: __block BOOL allowed = YES;
18新增: CageGuestSetupView *setup = [[CageGuestSetupView alloc] initWithMachine:vm
19新增: size:NSMakeSize(1024, 640) setupAuthorized:^BOOL { return allowed; }];
20新增: allowed = NO;
21新增: BOOL revoked = setup && ![setup snapshotPNG] && ![setup clickAtX:1 y:1] && ![setup scrollAtX:1 y:1 deltaX:0 deltaY:10];
22新增: fprintf(stderr, "Cage setup probe: main-thread binding and revocation %s\n", revoked ? "passed" : "failed");
23新增: [setup close];
24新增:
25新增: // Preserve Lima's normal shutdown path while AppKit owns its main loop.
26新增: dispatch_queue_t vmQueue = (__bridge dispatch_queue_t)queue;
27新增: __block BOOL seenRunning = NO;
28新增: NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.25 repeats:YES block:^(NSTimer *tick) {
29新增: (void)tick;
30新增: dispatch_async(vmQueue, ^{
31新增: VZVirtualMachineState state = vm.state;
32新增: if (state == VZVirtualMachineStateRunning) seenRunning = YES;
33新增: if (seenRunning && (state == VZVirtualMachineStateStopped || state == VZVirtualMachineStateError)) {
34新增: dispatch_async(dispatch_get_main_queue(), ^{
35新增: [app stop:nil];
36新增: NSEvent *wake = [NSEvent otherEventWithType:NSEventTypeApplicationDefined
37新增: location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0
38新增: context:nil subtype:0 data1:0 data2:0];
39新增: [app postEvent:wake atStart:YES];
40新增: });
41新增: }
42新增: });
43新增: }];
44新增: [app run];
45新增: [timer invalidate];
46新增: }
47新增:}
新增scripts/guest-os/macos-setup-view.h+22 −0看文件
@@ -0,0 +1,22 @@
1新增:#import <AppKit/AppKit.h>
2新增:#import <Virtualization/Virtualization.h>
3新增:
4新增:NS_ASSUME_NONNULL_BEGIN
5新增:
6新增:// QA-only adapter for a VM the caller already owns. All calls, including the
7新增:// authorization check, run on the AppKit main thread. A revoked session closes.
8新增:@interface CageGuestSetupView : NSObject
9新增:- (nullable instancetype)initWithMachine:(VZVirtualMachine *)machine
10新增: size:(NSSize)size
11新增: setupAuthorized:(BOOL (^)(void))setupAuthorized;
12新增:- (instancetype)init NS_UNAVAILABLE;
13新增:- (nullable NSData *)snapshotPNG;
14新增:- (nullable NSData *)snapshotJPEG;
15新增:- (BOOL)sendKey:(NSEvent *)event;
16新增:// Click in the view's logical coordinates, with the origin at its top left.
17新增:- (BOOL)clickAtX:(CGFloat)x y:(CGFloat)y;
18新增:- (BOOL)scrollAtX:(CGFloat)x y:(CGFloat)y deltaX:(CGFloat)deltaX deltaY:(CGFloat)deltaY;
19新增:- (void)close;
20新增:@end
21新增:
22新增:NS_ASSUME_NONNULL_END
新增scripts/guest-os/macos-setup-view.m+117 −0看文件
@@ -0,0 +1,117 @@
1新增:#import "macos-setup-view.h"
2新增:#include <math.h>
3新增:
4新增:@implementation CageGuestSetupView {
5新增: NSWindow *_window;
6新增: VZVirtualMachineView *_view;
7新增: BOOL (^_authorized)(void);
8新增:}
9新增:
10新增:- (instancetype)initWithMachine:(VZVirtualMachine *)machine
11新增: size:(NSSize)size
12新增: setupAuthorized:(BOOL (^)(void))setupAuthorized {
13新增: if (!NSThread.isMainThread || !machine || !setupAuthorized || !setupAuthorized() ||
14新增: !isfinite(size.width) || !isfinite(size.height) || size.width <= 0 || size.height <= 0) return nil;
15新增: self = [super init];
16新增: if (self) {
17新增: _authorized = [setupAuthorized copy];
18新增: NSRect rect = NSMakeRect(0, 0, size.width, size.height);
19新增: _window = [[NSWindow alloc] initWithContentRect:rect styleMask:NSWindowStyleMaskBorderless
20新增: backing:NSBackingStoreBuffered defer:NO];
21新增: _window.excludedFromWindowsMenu = YES;
22新增: _view = [[VZVirtualMachineView alloc] initWithFrame:rect];
23新增: _view.virtualMachine = machine;
24新增: _window.contentView = _view;
25新增: [_window makeFirstResponder:_view];
26新增: }
27新增: return self;
28新增:}
29新增:
30新增:- (BOOL)canUseView {
31新增: if (!NSThread.isMainThread) return NO;
32新增: if (!_view || !_authorized || !_authorized()) {
33新增: [self close];
34新增: return NO;
35新增: }
36新增: return YES;
37新增:}
38新增:
39新增:- (NSData *)snapshotType:(NSBitmapImageFileType)type properties:(NSDictionary *)properties {
40新增: if (![self canUseView]) return nil;
41新增: NSBitmapImageRep *rep = [_view bitmapImageRepForCachingDisplayInRect:_view.bounds];
42新增: if (!rep) return nil;
43新增: [_view cacheDisplayInRect:_view.bounds toBitmapImageRep:rep];
44新增: NSData *data = [rep representationUsingType:type properties:properties];
45新增: return [self canUseView] ? data : nil;
46新增:}
47新增:
48新增:- (NSData *)snapshotPNG { return [self snapshotType:NSBitmapImageFileTypePNG properties:@{}]; }
49新增:- (NSData *)snapshotJPEG {
50新增: return [self snapshotType:NSBitmapImageFileTypeJPEG properties:@{NSImageCompressionFactor: @0.92}];
51新增:}
52新增:
53新增:- (BOOL)sendKey:(NSEvent *)event {
54新增: if (![self canUseView]) return NO;
55新增: NSEventType kind = event.type;
56新增: if (kind != NSEventTypeKeyDown && kind != NSEventTypeKeyUp && kind != NSEventTypeFlagsChanged) return NO;
57新增: BOOL flagsOnly = kind == NSEventTypeFlagsChanged;
58新增: NSEvent *target = [NSEvent keyEventWithType:kind location:NSZeroPoint modifierFlags:event.modifierFlags
59新增: timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:_window.windowNumber
60新增: context:nil characters:flagsOnly ? @"" : event.characters ?: @""
61新增: charactersIgnoringModifiers:flagsOnly ? @"" : event.charactersIgnoringModifiers ?: @""
62新增: isARepeat:!flagsOnly && event.isARepeat keyCode:event.keyCode];
63新增: if (kind == NSEventTypeKeyDown) [_view keyDown:target];
64新增: else if (kind == NSEventTypeKeyUp) [_view keyUp:target];
65新增: else [_view flagsChanged:target];
66新增: return YES;
67新增:}
68新增:
69新增:- (BOOL)clickAtX:(CGFloat)x y:(CGFloat)y {
70新增: if (![self canUseView]) return NO;
71新增: NSRect rect = _view.bounds;
72新增: if (!isfinite(x) || !isfinite(y) || x < 0 || y < 0 || x >= NSWidth(rect) || y >= NSHeight(rect)) return NO;
73新增: NSPoint point = [_view convertPoint:NSMakePoint(x, NSHeight(rect) - y) toView:nil];
74新增: for (NSNumber *type in @[@(NSEventTypeLeftMouseDown), @(NSEventTypeLeftMouseUp)]) {
75新增: if (![self canUseView]) return NO;
76新增: NSEvent *event = [NSEvent mouseEventWithType:type.unsignedIntegerValue location:point modifierFlags:0
77新增: timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:_window.windowNumber
78新增: context:nil eventNumber:1 clickCount:1 pressure:1];
79新增: if (event.type == NSEventTypeLeftMouseDown) [_view mouseDown:event];
80新增: else [_view mouseUp:event];
81新增: }
82新增: return YES;
83新增:}
84新增:
85新增:- (BOOL)scrollAtX:(CGFloat)x y:(CGFloat)y deltaX:(CGFloat)deltaX deltaY:(CGFloat)deltaY {
86新增: if (![self canUseView]) return NO;
87新增: NSRect rect = _view.bounds;
88新增: if (!isfinite(x) || !isfinite(y) || !isfinite(deltaX) || !isfinite(deltaY) ||
89新增: x < 0 || y < 0 || x >= NSWidth(rect) || y >= NSHeight(rect) ||
90新增: fabs(deltaX) > 4096 || fabs(deltaY) > 4096) return NO;
91新增: NSPoint point = [_view convertPoint:NSMakePoint(x, NSHeight(rect) - y) toView:nil];
92新增: NSEvent *move = [NSEvent mouseEventWithType:NSEventTypeMouseMoved location:point modifierFlags:0
93新增: timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:_window.windowNumber
94新增: context:nil eventNumber:0 clickCount:0 pressure:0];
95新增: [_view mouseMoved:move];
96新增: CGEventRef wheel = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 2, (int32_t)deltaY, (int32_t)deltaX);
97新增: if (!wheel) return NO;
98新增: // A new CG event inherits the host pointer location. Retarget the hidden
99新增: // window at the screen origin before the VZ view maps it into the guest.
100新增: NSPoint screen = [_window convertPointToScreen:point];
101新增: CGEventSetLocation(wheel, CGPointMake(screen.x, NSMaxY(NSScreen.screens.firstObject.frame) - screen.y));
102新增: NSEvent *event = [NSEvent eventWithCGEvent:wheel];
103新增: CFRelease(wheel);
104新增: if (!event || ![self canUseView]) return NO;
105新增: [_view scrollWheel:event];
106新增: return YES;
107新增:}
108新增:
109新增:- (void)close {
110新增: NSAssert(NSThread.isMainThread, @"Close the setup view on the AppKit main thread.");
111新增: _authorized = nil;
112新增: _view.virtualMachine = nil;
113新增: _window.contentView = nil;
114新增: _view = nil;
115新增: _window = nil;
116新增:}
117新增:@end
新增scripts/guest-os/macos-window-input.swift+262 −0看文件
@@ -0,0 +1,262 @@
1新增:import AppKit
2新增:import ApplicationServices
3新增:import ScreenCaptureKit
4新增:
5新增:struct MacInputWindow {
6新增: let app: AXUIElement
7新增: let focused: AXUIElement
8新增: let pid: pid_t
9新增: let origin: CGPoint
10新增: let extent: CGSize
11新增:}
12新增:
13新增:@MainActor
14新增:func checkedMacInputWindow(_ input: Request, window: SCWindow) throws -> MacInputWindow {
15新增: guard AXIsProcessTrusted() else { throw Failure(9, "accessibility_permission") }
16新增: guard let pid = window.owningApplication?.processID, input.pid == pid, input.window == window.windowID,
17新增: NSWorkspace.shared.frontmostApplication?.processIdentifier == pid else { throw Failure(7, "window_changed") }
18新增: let app = AXUIElementCreateApplication(pid)
19新增: AXUIElementSetMessagingTimeout(app, 1)
20新增: var value: CFTypeRef?
21新增: guard AXUIElementCopyAttributeValue(app, kAXFocusedWindowAttribute as CFString, &value) == .success,
22新增: let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { throw Failure(7, "window_changed") }
23新增: let focused = value as! AXUIElement
24新增: var position: CFTypeRef?, size: CFTypeRef?
25新增: var origin = CGPoint.zero, extent = CGSize.zero
26新增: guard AXUIElementCopyAttributeValue(focused, kAXPositionAttribute as CFString, &position) == .success,
27新增: AXUIElementCopyAttributeValue(focused, kAXSizeAttribute as CFString, &size) == .success,
28新增: let position, let size, CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(size) == AXValueGetTypeID(),
29新增: AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(size as! AXValue, .cgSize, &extent) else {
30新增: throw Failure(7, "window_changed")
31新增: }
32新增: let tolerance: CGFloat = input.action == "project-click" ? 24 : 1
33新增: guard abs(origin.x - window.frame.minX) < tolerance, abs(origin.y - window.frame.minY) < tolerance,
34新增: abs(extent.width - window.frame.width) < tolerance, abs(extent.height - window.frame.height) < tolerance else {
35新增: throw Failure(7, "window_changed")
36新增: }
37新增: return MacInputWindow(app: app, focused: focused, pid: pid, origin: origin, extent: extent)
38新增:}
39新增:
40新增:@MainActor
41新增:func macPressTarget(_ target: MacInputWindow, point: CGPoint) -> AXUIElement? {
42新增: var hit: AXUIElement?
43新增: guard AXUIElementCopyElementAtPosition(target.app, Float(point.x), Float(point.y), &hit) == .success else { return nil }
44新增: var node = hit
45新增: for _ in 0..<8 {
46新增: guard let current = node, !CFEqual(current, target.focused) else { break }
47新增: func attribute(_ name: String) -> CFTypeRef? {
48新增: var value: CFTypeRef?
49新增: return AXUIElementCopyAttributeValue(current, name as CFString, &value) == .success ? value : nil
50新增: }
51新增: var pid: pid_t = 0
52新增: guard AXUIElementGetPid(current, &pid) == .success, pid == target.pid,
53新增: let owner = attribute(kAXWindowAttribute), CFEqual(owner, target.focused) else { break }
54新增: if let role = attribute(kAXRoleAttribute) as? String, [kAXButtonRole, "AXLink"].contains(role) {
55新增: var actions: CFArray?
56新增: if AXUIElementCopyActionNames(current, &actions) == .success,
57新增: (actions as? [String])?.contains(kAXPressAction) == true { return current }
58新增: }
59新增: guard let parent = attribute(kAXParentAttribute), CFGetTypeID(parent) == AXUIElementGetTypeID() else { break }
60新增: node = (parent as! AXUIElement)
61新增: }
62新增: return nil
63新增:}
64新增:
65新增:// Each socket owns its held input and composition. Disconnect releases only that socket.
66新增:@MainActor
67新增:final class MacWindowInputSession {
68新增: private static var pointerOwner: UUID?
69新增: private static var keyOwners: [UInt16: UUID] = [:]
70新增: private let id = UUID()
71新增: private let source = CGEventSource(stateID: .privateState)
72新增: private var keys: [UInt16: (pid_t, CGWindowID)] = [:]
73新增: private var pressedCodes: [String: UInt16] = [:]
74新增: private var buttons: [Int: (pid_t, CGWindowID, CGPoint, Int)] = [:]
75新增: private var press: (element: AXUIElement, down: CGEvent, point: CGPoint, pid: pid_t, window: CGWindowID)?
76新增: private var focusedElement: AXUIElement?
77新增: private var focusedTarget = ""
78新增: private var focusContext = ""
79新增: private var composition: (id: String, context: String, sequence: Int, updated: Date)?
80新增:
81新增: static func requirePointerOwner(_ session: MacWindowInputSession?) throws {
82新增: if let owner = pointerOwner, owner != session?.id { throw Failure(8, "input_owned_by_another_view") }
83新增: }
84新增:
85新增: private func flags(_ input: Request) -> CGEventFlags {
86新增: var value: CGEventFlags = []
87新增: if input.shift == true { value.insert(.maskShift) }
88新增: if input.control == true { value.insert(.maskControl) }
89新增: if input.alt == true { value.insert(.maskAlternate) }
90新增: if input.command == true { value.insert(.maskCommand) }
91新增: return value
92新增: }
93新增:
94新增: func key(_ input: Request, target: MacInputWindow, window: SCWindow) throws {
95新增: try Self.requirePointerOwner(self)
96新增: if let pending = press {
97新增: guard pending.pid == target.pid, pending.window == window.windowID else { throw Failure(7, "window_changed") }
98新增: pending.down.postToPid(target.pid)
99新增: press = nil
100新增: }
101新增: guard let down = input.down, let name = input.code, let key = input.key else { throw Failure(8, "invalid_input") }
102新增: let mapped = MacKeyboard.virtualKey(code: name, key: key, shortcut: input.command == true || input.control == true || input.alt == true)
103新增: guard let code = pressedCodes[name] ?? (down ? mapped : nil) else {
104新增: if down { throw Failure(8, "invalid_input") }
105新增: return
106新增: }
107新增: guard let event = CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: down) else { throw Failure(8, "input_failed") }
108新增: if let owner = Self.keyOwners[code], owner != id { throw Failure(8, "input_owned_by_another_view") }
109新增: if !down && keys[code] == nil { return }
110新增: event.flags = flags(input)
111新增: event.setIntegerValueField(.keyboardEventAutorepeat, value: down && keys[code] != nil ? 1 : 0)
112新增: if down && input.command != true && input.control != true && key.count == 1 {
113新增: let text = Array(key.utf16)
114新增: text.withUnsafeBufferPointer { event.keyboardSetUnicodeString(stringLength: text.count, unicodeString: $0.baseAddress) }
115新增: }
116新增: if down { keys[code] = (target.pid, window.windowID); pressedCodes[name] = code; Self.keyOwners[code] = id }
117新增: else { keys.removeValue(forKey: code); pressedCodes.removeValue(forKey: name); Self.keyOwners.removeValue(forKey: code) }
118新增: event.postToPid(target.pid)
119新增: }
120新增:
121新增: func pointer(_ input: Request, target: MacInputWindow, window: SCWindow, canvas: ClaudeCanvas?) throws {
122新增: try Self.requirePointerOwner(self)
123新增: guard let phase = input.phase, ["down", "move", "up"].contains(phase),
124新增: let x = input.x, let y = input.y, x.isFinite, y.isFinite, (0..<1).contains(x), (0..<1).contains(y) else { throw Failure(8, "invalid_input") }
125新增: let crop = canvas?.cropTop ?? 0
126新增: let point = CGPoint(x: target.origin.x + target.extent.width * x, y: target.origin.y + crop + (target.extent.height - crop) * y)
127新增: let button = phase == "move" ? buttons.keys.sorted().first : input.button
128新增: let types: [NSEvent.EventType]
129新增: if phase == "move" { types = [.leftMouseDragged, .otherMouseDragged, .rightMouseDragged] }
130新增: else if phase == "down" { types = [.leftMouseDown, .otherMouseDown, .rightMouseDown] }
131新增: else { types = [.leftMouseUp, .otherMouseUp, .rightMouseUp] }
132新增: if phase != "move" && (button == nil || !(0...2).contains(button!) || !(1...3).contains(input.clicks ?? 0)) { throw Failure(8, "invalid_input") }
133新增: if phase == "up", let button, buttons[button] == nil { return }
134新增: if let pending = press {
135新增: guard pending.pid == target.pid, pending.window == window.windowID else { throw Failure(7, "window_changed") }
136新增: if phase == "move" && abs(point.x - pending.point.x) < 4 && abs(point.y - pending.point.y) < 4 { return }
137新增: press = nil
138新增: if phase == "up", button == 0, flags(input).isEmpty,
139新增: let hit = macPressTarget(target, point: point), CFEqual(hit, pending.element) {
140新增: buttons.removeValue(forKey: 0)
141新增: if buttons.isEmpty { Self.pointerOwner = nil }
142新增: guard AXUIElementPerformAction(hit, kAXPressAction as CFString) == .success else { throw Failure(8, "input_failed") }
143新增: return
144新增: }
145新增: pending.down.postToPid(target.pid)
146新增: }
147新增: let type = button.map { types[$0] } ?? .mouseMoved
148新增: let count = input.clicks ?? button.flatMap { buttons[$0]?.3 } ?? 0
149新增: let local = CGPoint(x: point.x - target.origin.x, y: target.extent.height - (point.y - target.origin.y))
150新增: guard let event = NSEvent.mouseEvent(with: type, location: local, modifierFlags: NSEvent.ModifierFlags(rawValue: UInt(flags(input).rawValue)),
151新增: timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: Int(window.windowID), context: nil,
152新增: eventNumber: 0, clickCount: count, pressure: phase == "up" ? 0 : 1)?.cgEvent else { throw Failure(8, "input_failed") }
153新增: event.location = point
154新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(window.windowID))
155新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(window.windowID))
156新增: if phase == "down", let button { buttons[button] = (target.pid, window.windowID, point, count); Self.pointerOwner = id }
157新增: if phase == "up", let button { buttons.removeValue(forKey: button); if buttons.isEmpty { Self.pointerOwner = nil } }
158新增: if phase == "move" { for button in Array(buttons.keys) { buttons[button] = (target.pid, window.windowID, point, count) } }
159新增: // Preserve the existing AX activation for Electron buttons. A real
160新增: // drag flushes the deferred down before its first dragged event.
161新增: if phase == "down", button == 0, count == 1, buttons.count == 1, flags(input).isEmpty,
162新增: let element = macPressTarget(target, point: point) {
163新增: press = (element, event, point, target.pid, window.windowID)
164新增: return
165新增: }
166新增: event.postToPid(target.pid)
167新增: }
168新增:
169新增: private func stillOwnsWindow(_ pid: pid_t, _ window: CGWindowID) -> Bool {
170新增: guard (try? consoleUser()) != nil else { return false }
171新增: let values = CGWindowListCopyWindowInfo(.optionIncludingWindow, window) as? [[String: Any]]
172新增: return values?.first?[kCGWindowOwnerPID as String] as? Int32 == pid
173新增: }
174新增:
175新增: func reset() {
176新增: for (code, target) in keys {
177新增: if stillOwnsWindow(target.0, target.1) { CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: false)?.postToPid(target.0) }
178新增: if Self.keyOwners[code] == id { Self.keyOwners.removeValue(forKey: code) }
179新增: }
180新增: for (button, target) in buttons where !(button == 0 && press != nil) && stillOwnsWindow(target.0, target.1) {
181新增: let type: CGEventType = button == 0 ? .leftMouseUp : button == 2 ? .rightMouseUp : .otherMouseUp
182新增: let mouse: CGMouseButton = button == 0 ? .left : button == 2 ? .right : .center
183新增: if let event = CGEvent(mouseEventSource: source, mouseType: type, mouseCursorPosition: target.2, mouseButton: mouse) {
184新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(target.1))
185新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(target.1))
186新增: event.postToPid(target.0)
187新增: }
188新增: }
189新增: keys.removeAll(); pressedCodes.removeAll(); buttons.removeAll(); press = nil; composition = nil
190新增: if Self.pointerOwner == id { Self.pointerOwner = nil }
191新增: }
192新增:
193新增: func ime(_ input: Request, window: SCWindow, canvas: ClaudeCanvas?, commit: (String) throws -> Void) throws -> [String: Any] {
194新增: let mode = input.mode ?? ""
195新增: guard ["status", "begin", "update", "commit", "cancel"].contains(mode) else { throw Failure(8, "input_mode_invalid") }
196新增: let token = input.session ?? "", sequence = input.sequence ?? 0
197新增: if mode != "status" && (token.count != 32 || token.range(of: "^[a-f0-9]{32}$", options: .regularExpression) == nil || sequence < 0) { throw Failure(8, "input_session_invalid") }
198新增: if mode == "cancel" {
199新增: if composition?.id == token && sequence > composition!.sequence { composition = nil }
200新增: return ["available": false]
201新增: }
202新增: let target = try checkedMacInputWindow(input, window: window)
203新增: func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? {
204新增: var value: CFTypeRef?
205新增: return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil
206新增: }
207新增: guard let raw = attribute(target.app, kAXFocusedUIElementAttribute), CFGetTypeID(raw) == AXUIElementGetTypeID() else {
208新增: composition = nil; focusedElement = nil; return ["available": false]
209新增: }
210新增: let element = raw as! AXUIElement
211新增: var pid: pid_t = 0
212新增: var valueWritable = DarwinBoolean(false), selectionWritable = DarwinBoolean(false)
213新增: _ = AXUIElementIsAttributeSettable(element, kAXValueAttribute as CFString, &valueWritable)
214新增: _ = AXUIElementIsAttributeSettable(element, kAXSelectedTextAttribute as CFString, &selectionWritable)
215新增: guard AXUIElementGetPid(element, &pid) == .success, pid == target.pid,
216新增: [kAXTextFieldRole, kAXTextAreaRole, kAXComboBoxRole].contains(attribute(element, kAXRoleAttribute) as? String ?? ""),
217新增: valueWritable.boolValue || selectionWritable.boolValue,
218新增: let owner = attribute(element, kAXWindowAttribute), CFEqual(owner, target.focused),
219新增: (attribute(element, kAXEnabledAttribute) as? Bool) != false else { composition = nil; return ["available": false] }
220新增: let identity = "\(window.windowID):\(target.pid):\(input.geometry ?? "")"
221新增: if focusedElement == nil || !CFEqual(focusedElement!, element) || focusedTarget != identity {
222新增: focusedElement = element; focusedTarget = identity; focusContext = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased(); composition = nil
223新增: }
224新增: var rect = CGRect.zero
225新增: var exact = false
226新增: if let range = attribute(element, kAXSelectedTextRangeAttribute), CFGetTypeID(range) == AXValueGetTypeID() {
227新增: var selected = CFRange()
228新增: if AXValueGetValue(range as! AXValue, .cfRange, &selected) {
229新增: selected.location += selected.length; selected.length = 0
230新增: var bounds: CFTypeRef?
231新增: if let parameter = AXValueCreate(.cfRange, &selected),
232新增: AXUIElementCopyParameterizedAttributeValue(element, kAXBoundsForRangeParameterizedAttribute as CFString, parameter, &bounds) == .success,
233新增: let bounds, CFGetTypeID(bounds) == AXValueGetTypeID() { exact = AXValueGetValue(bounds as! AXValue, .cgRect, &rect) }
234新增: }
235新增: }
236新增: if !exact || rect.height <= 0 {
237新增: var point = CGPoint.zero, size = CGSize.zero
238新增: guard let position = attribute(element, kAXPositionAttribute), let extent = attribute(element, kAXSizeAttribute),
239新增: CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(extent) == AXValueGetTypeID(),
240新增: AXValueGetValue(position as! AXValue, .cgPoint, &point), AXValueGetValue(extent as! AXValue, .cgSize, &size) else { return ["available": false] }
241新增: rect = CGRect(origin: point, size: CGSize(width: 1, height: min(24, size.height)))
242新增: }
243新增: if let current = composition, current.context != focusContext || Date().timeIntervalSince(current.updated) > 30 { composition = nil }
244新增: let result: [String: Any] = ["available": true, "context": focusContext, "preedit_supported": false,
245新增: "password": attribute(element, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole,
246新增: "rect": [rect.minX - target.origin.x, rect.minY - target.origin.y - (canvas?.cropTop ?? 0), max(1, rect.width), max(1, rect.height)],
247新增: "width": target.extent.width, "height": target.extent.height - (canvas?.cropTop ?? 0), "caret_exact": exact]
248新增: if mode == "status" {
249新增: if composition?.id == token { composition?.updated = Date() }
250新增: return result
251新增: }
252新增: if mode == "begin" {
253新增: guard input.context == focusContext else { return ["available": false] }
254新增: composition = (token, focusContext, sequence, Date()); return result
255新增: }
256新增: guard let current = composition, current.id == token, sequence > current.sequence else { return ["available": false] }
257新增: guard (input.text ?? "").utf8.count <= 8192 else { throw Failure(8, "input_text_limit") }
258新增: if mode == "commit" { try commit(input.text ?? ""); composition = nil }
259新增: else { composition = (token, focusContext, sequence, Date()) }
260新增: return result
261新增: }
262新增:}
新增scripts/guest-os/macos-window-stream.swift+131 −0看文件
@@ -0,0 +1,131 @@
1新增:import AppKit
2新增:import CoreImage
3新增:import ScreenCaptureKit
4新增:
5新增:@MainActor
6新增:final class MacWindowStream: NSObject, SCStreamOutput, SCStreamDelegate {
7新增: static let shared = MacWindowStream()
8新增: private var stream: SCStream?
9新增: private var key = ""
10新增: private var generation = UUID().uuidString
11新增: private var number: UInt64 = 0
12新增: private var sequence: String { generation + "-" + String(number) }
13新增: private var buffer: CVPixelBuffer?
14新增: private var expiry: Task<Void, Never>?
15新增: private var waiters: [UUID: CheckedContinuation<Void, Never>] = [:]
16新增: private let images = CIContext()
17新增:
18新增: nonisolated func stream(_ stream: SCStream, didOutputSampleBuffer sample: CMSampleBuffer, of type: SCStreamOutputType) {
19新增: guard type == .screen,
20新增: let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: false) as? [[SCStreamFrameInfo: Any]],
21新增: let status = attachments.first?[.status] as? Int else { return }
22新增: let pixels = sample.isValid ? sample.imageBuffer : nil
23新增: let changed = (attachments.first?[.dirtyRects] as? [Any])?.isEmpty != true
24新增: Task { @MainActor [weak self] in
25新增: guard let self, self.stream === stream else { return }
26新增: if status == SCFrameStatus.complete.rawValue, let pixels {
27新增: if self.buffer != nil && !changed { return }
28新增: self.buffer = pixels
29新增: self.number += 1
30新增: } else if status != SCFrameStatus.idle.rawValue {
31新增: self.buffer = nil
32新增: self.number += 1
33新增: }
34新增: self.wake()
35新增: }
36新增: }
37新增:
38新增: nonisolated func stream(_ stream: SCStream, didStopWithError error: Error) {
39新增: Task { @MainActor [weak self] in
40新增: guard let self, self.stream === stream else { return }
41新增: self.stream = nil
42新增: self.buffer = nil
43新增: self.wake()
44新增: }
45新增: }
46新增:
47新增: private func stop() async {
48新增: let previous = stream
49新增: stream = nil
50新增: buffer = nil
51新增: key = ""
52新增: wake()
53新增: try? await previous?.stopCapture()
54新增: }
55新增:
56新增: private func wake() {
57新增: let pending = waiters.values
58新增: waiters.removeAll()
59新增: for continuation in pending { continuation.resume() }
60新增: }
61新增:
62新增: private func waitForFrame(after expected: String, seconds: Double) async throws {
63新增: let id = UUID()
64新增: let timeout = Task { @MainActor [weak self] in
65新增: do { try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000)) }
66新增: catch { return }
67新增: self?.waiters.removeValue(forKey: id)?.resume()
68新增: }
69新增: defer { timeout.cancel() }
70新增: await withTaskCancellationHandler {
71新增: await withCheckedContinuation { continuation in
72新增: if Task.isCancelled || stream == nil || expected != sequence { continuation.resume() }
73新增: else { waiters[id] = continuation }
74新增: }
75新增: } onCancel: {
76新增: Task { @MainActor [weak self] in self?.waiters.removeValue(forKey: id)?.resume() }
77新增: }
78新增: try Task.checkCancellation()
79新增: }
80新增:
81新增: private func renew() {
82新增: expiry?.cancel()
83新增: expiry = Task { [weak self] in
84新增: do { try await Task.sleep(nanoseconds: 1_500_000_000) }
85新增: catch { return }
86新增: await self?.stop()
87新增: }
88新增: }
89新增:
90新增: func unchanged(after: String?) -> Bool {
91新增: guard stream != nil, buffer != nil, after == sequence else { return false }
92新增: renew()
93新增: return true
94新增: }
95新增:
96新增: func frame(filter: SCContentFilter, configuration: SCStreamConfiguration, identity: String, after: String?, wait: Bool = false) async throws -> (CGImage?, String) {
97新增: expiry?.cancel()
98新增: defer { renew() }
99新增: if stream == nil || key != identity {
100新增: await stop()
101新增: generation = UUID().uuidString
102新增: number = 0
103新增: key = identity
104新增: configuration.minimumFrameInterval = CMTime(value: 1, timescale: 30)
105新增: configuration.queueDepth = 3
106新增: configuration.pixelFormat = kCVPixelFormatType_32BGRA
107新增: let next = SCStream(filter: filter, configuration: configuration, delegate: self)
108新增: try next.addStreamOutput(self, type: .screen, sampleHandlerQueue: DispatchQueue(label: "cage.window.frames"))
109新增: stream = next
110新增: do { try await next.startCapture() }
111新增: catch { await stop(); throw error }
112新增: }
113新增: // Only the first frame of a newly configured stream needs to wait.
114新增: let deadline = Date().addingTimeInterval(5)
115新增: while buffer == nil && stream != nil && Date() < deadline {
116新增: try await waitForFrame(after: sequence, seconds: max(0, deadline.timeIntervalSinceNow))
117新增: }
118新增: if wait, buffer != nil, after == sequence {
119新增: // Revalidate window ownership and the console session at least every
120新增: // two seconds even when ScreenCaptureKit reports no changed pixels.
121新增: try await waitForFrame(after: sequence, seconds: 2)
122新增: }
123新增: guard key == identity else { throw Failure(7, "window_changed") }
124新增: guard let buffer else { await stop(); throw Failure(8, "capture_no_frame") }
125新增: let sequence = self.sequence
126新增: if sequence == after { return (nil, sequence) }
127新增: let image = CIImage(cvPixelBuffer: buffer)
128新增: guard let output = images.createCGImage(image, from: image.extent) else { throw Failure(8, "capture_conversion_failed") }
129新增: return (output, sequence)
130新增: }
131新增:}
新增scripts/guest-os/maintain-macos-workbench.sh+186 −0看文件
@@ -0,0 +1,186 @@
1新增:#!/bin/bash
2新增:# Runs through the verified provisioning identity of an already bound Mac.
3新增:# The ordinary account and its home directory are never initialized here.
4新增:set -euo pipefail
5新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin
6新增:[[ $# == 3 && $1 == /* && $2 =~ ^[a-z][a-z0-9_]{0,30}$ && ( $3 == components || $3 == tools ) ]]
7新增:[[ $EUID == 0 && $(uname -sm) == 'Darwin arm64' && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]]
8新增:[[ -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 ]]
9新增:lock=/var/run/cage-component-update.lock
10新增:[[ ! -L $lock && ( ! -e $lock || ( -f $lock && $(stat -f %u "$lock") == 0 ) ) ]]
11新增:exec 9>"$lock"
12新增:/usr/bin/lockf -s -t 0 9 || { echo '另一项组件更新仍在运行,请稍后重试。' >&2; exit 1; }
13新增:umask 022
14新增:kit=$(cd -P "$1" && pwd)
15新增:# Helpers run as the ordinary guest user and need a traversable working directory.
16新增:cd /
17新增:user=$2
18新增:mode=$3
19新增:uid=$(id -u "$user")
20新增:[[ $uid -ge 500 && " $(id -Gn "$user") " != *' admin '* ]]
21新增:[[ $(stat -f %u "$kit") == 0 && -z $(find "$kit" \( -type l -o ! -user root -o -perm -0020 -o -perm -0002 \) -print -quit) ]]
22新增:manifest="$kit/native-components.json"
23新增:/usr/bin/perl "$kit/native-component-manifest.pl" source "$manifest" "$kit"
24新增:backup=$(mktemp -d /private/var/tmp/cage-components-backup.XXXXXXXX)
25新增:chmod 700 "$backup"
26新增:changed=()
27新增:existed=()
28新增:loaded=()
29新增:previous_loaded=()
30新增:apps=()
31新增:app_existed=()
32新增:app_applied=0
33新增:cli_previous=''
34新增:if [[ -L /usr/local/libexec/cage-cli ]]; then cli_previous=$(readlink /usr/local/libexec/cage-cli); fi
35新增:
36新增:finish() {
37新增: local status=$? index target label
38新增: trap - EXIT
39新增: if (( status != 0 )); then
40新增: for ((index=0; index<${#loaded[@]}; index++)); do
41新增: label=${loaded[$index]}
42新增: sudo -Hu "$user" /bin/launchctl bootout "gui/$uid/$label" >/dev/null 2>&1 || true
43新增: done
44新增: for ((index=${#changed[@]}-1; index>=0; index--)); do
45新增: target=${changed[$index]}
46新增: if [[ ${existed[$index]} == yes ]]; then
47新增: mv -f "$backup/$index" "$target" || status=1
48新增: elif [[ -f $target && ! -L $target ]]; then
49新增: rm "$target" || status=1
50新增: fi
51新增: done
52新增: for ((index=app_applied-1; index>=0; index--)); do
53新增: target=${apps[$index]}
54新增: if [[ -d $target && ! -L $target ]]; then rm -rf "$target"; fi
55新增: if [[ ${app_existed[$index]} == yes ]]; then mv "$backup/old-app-$index" "$target" || status=1; fi
56新增: done
57新增: if [[ -n $cli_previous ]]; then
58新增: ln -s "$cli_previous" "$backup/cli-previous"
59新增: mv -fh "$backup/cli-previous" /usr/local/libexec/cage-cli || status=1
60新增: fi
61新增: for ((index=0; index<${#previous_loaded[@]}; index++)); do
62新增: label=${previous_loaded[$index]}
63新增: if ! sudo -Hu "$user" /bin/launchctl bootstrap "gui/$uid" "/Users/$user/Library/LaunchAgents/$label.plist" >/dev/null 2>&1; then status=1; fi
64新增: done
65新增: fi
66新增: if (( status == 0 )); then
67新增: rm -rf "$backup"
68新增: else
69新增: printf '组件更新未完成。已恢复可恢复的原文件,备份位于 %s。可以在 Cage 重试。\n' "$backup" >&2
70新增: fi
71新增: exit "$status"
72新增:}
73新增:trap finish EXIT
74新增:trap 'exit 1' HUP INT TERM
75新增:
76新增:# Verify app ownership before stopping the corresponding GUI helpers.
77新增:for app in "$kit"/*.app "$kit"/project/*.app; do
78新增: [[ -d $app ]] || continue
79新增: identifier=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Contents/Info.plist")
80新增: [[ $identifier == dev.cage.* ]]
81新增: codesign --verify --deep --strict -R "=identifier \"$identifier\"" "$app"
82新增: target="/Applications/$(basename "$app")"
83新增: if [[ -e $target ]]; then
84新增: [[ -d $target && ! -L $target ]]
85新增: # Missing or damaged installed files are repairable. The incoming app
86新增: # is fully verified, and an existing signing team remains a constraint.
87新增: previous_team=$(codesign -dv "$target" 2>&1 | sed -n 's/^TeamIdentifier=//p' || true)
88新增: next_team=$(codesign -dv "$app" 2>&1 | sed -n 's/^TeamIdentifier=//p')
89新增: [[ -z $previous_team || $previous_team == not\ set || $previous_team == "$next_team" ]]
90新增: fi
91新增: index=${#apps[@]}
92新增: ditto "$app" "$backup/new-app-$index"
93新增: chmod -R a+rX,go-w "$backup/new-app-$index"
94新增: codesign --verify --deep --strict "$backup/new-app-$index"
95新增: apps+=("$target")
96新增: if [[ -d $target ]]; then app_existed+=(yes); else app_existed+=(no); fi
97新增:done
98新增:for label in dev.cage.GuestClaudeWindow dev.cage.GuestClipboard dev.cage.GuestBrowser; do
99新增: if sudo -Hu "$user" /bin/launchctl print "gui/$uid/$label" >/dev/null 2>&1; then
100新增: loaded+=("$label")
101新增: previous_loaded+=("$label")
102新增: sudo -Hu "$user" /bin/launchctl bootout "gui/$uid/$label"
103新增: fi
104新增:done
105新增:# Project shares and workbench terminals have already been closed by the host.
106新增:while read -r pid owner executable; do
107新增: if [[ $owner == "$uid" && $executable == /Applications/CageProjectAccess.app/Contents/MacOS/CageProjectAccess ]]; then kill -TERM "$pid" 2>/dev/null || true; fi
108新增:done < <(ps -axo pid=,uid=,comm=)
109新增:
110新增:for ((index=0; index<${#apps[@]}; index++)); do
111新增: target=${apps[$index]}
112新增: if [[ ${app_existed[$index]} == yes ]]; then mv "$target" "$backup/old-app-$index"; fi
113新增: app_applied=$((index+1))
114新增: mv "$backup/new-app-$index" "$target"
115新增:done
116新增:
117新增:while IFS= read -r -d '' source && IFS= read -r -d '' target; do
118新增: # The CLI installer publishes a new immutable helper directory and moves
119新增: # its owned symlink. It also generates the verified Python entry shebang.
120新增: [[ $target != /usr/local/libexec/cage-cli/* && $target != /Applications/* ]] || continue
121新增: parent=$(dirname "$target")
122新增: check=$parent
123新增: while [[ $check != / ]]; do
124新增: [[ ! -L $check ]]
125新增: check=$(dirname "$check")
126新增: done
127新增: mkdir -p "$parent"
128新增: [[ ! -L $target && ( ! -e $target || -f $target ) ]]
129新增: if [[ -f $target ]] && cmp -s "$kit/$source" "$target"; then continue; fi
130新增: index=${#changed[@]}
131新增: if [[ -f $target ]]; then
132新增: cp -p "$target" "$backup/$index"
133新增: existed+=(yes)
134新增: else
135新增: existed+=(no)
136新增: fi
137新增: changed+=("$target")
138新增: stage=$(mktemp "$parent/.cage-component.XXXXXXXX")
139新增: cp -p "$kit/$source" "$stage"
140新增: case "$target" in
141新增: */controller/cage-tailnet|/usr/local/libexec/cage-register-*|/usr/local/libexec/cage-macos-editor|/usr/local/libexec/cage-sshfs|/usr/local/libexec/cage-macos-terminal|/usr/local/libexec/cage-finish-initial-setup|/usr/local/libexec/cage-macos-ipv6-check) chmod 755 "$stage" ;;
142新增: *) chmod a+r,go-w "$stage" ;;
143新增: esac
144新增: mv -f "$stage" "$target"
145新增:done < <(/usr/bin/perl "$kit/native-component-manifest.pl" targets "$manifest" "$kit")
146新增:
147新增:if [[ $mode == tools ]]; then
148新增: bash "$kit/install-macos-node.sh" "$kit/node.tgz"
149新增: bash "$kit/install-macos-browser.sh" "$kit" --update-tools
150新增: bash "$kit/cli/install-macos-cli.sh" "$kit/cli"
151新增:else
152新增: bash "$kit/install-macos-cli.sh" "$kit" --components
153新增:fi
154新增:for app in "$kit"/*.app "$kit"/project/*.app; do
155新增: [[ -d $app ]] || continue
156新增: codesign --verify --deep --strict "/Applications/$(basename "$app")"
157新增:done
158新增:# Registration can migrate an existing agent's lifecycle settings. Restore
159新增:# those files with the matching binaries if activation or publication fails.
160新增:for label in dev.cage.GuestClaudeWindow dev.cage.GuestClipboard dev.cage.GuestBrowser; do
161新增: target="/Users/$user/Library/LaunchAgents/$label.plist"
162新增: [[ ! -L $target && ( ! -e $target || ( -f $target && $(stat -f %u "$target") == "$uid" ) ) ]]
163新增: index=${#changed[@]}
164新增: if [[ -f $target ]]; then
165新增: cp -p "$target" "$backup/$index"
166新增: existed+=(yes)
167新增: else
168新增: existed+=(no)
169新增: fi
170新增: changed+=("$target")
171新增:done
172新增:sudo -Hu "$user" /usr/local/libexec/cage-register-claude-window --prepare
173新增:sudo -Hu "$user" /usr/local/libexec/cage-register-clipboard --prepare
174新增:sudo -Hu "$user" /usr/local/libexec/cage-register-browser --prepare
175新增:# New helpers are activated for an already logged-in GUI user as well.
176新增:if [[ $(stat -f %u /dev/console) == "$uid" ]]; then
177新增: for label in dev.cage.GuestClaudeWindow dev.cage.GuestClipboard dev.cage.GuestBrowser; do
178新增: if [[ " ${loaded[*]-} " != *" $label "* ]]; then loaded+=("$label"); fi
179新增: done
180新增:fi
181新增:for ((index=0; index<${#loaded[@]}; index++)); do
182新增: label=${loaded[$index]}
183新增: sudo -Hu "$user" /bin/launchctl bootstrap "gui/$uid" "/Users/$user/Library/LaunchAgents/$label.plist"
184新增:done
185新增:/usr/bin/perl "$kit/native-component-manifest.pl" publish "$manifest" "$kit"
186新增:printf '%s\n' '原生客机组件已更新并通过文件核验。'
新增scripts/guest-os/maintain-windows-workbench.ps1+152 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/new-windows-test-vm.ps1+172 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/new-windows-test-vm.tests.ps1+33 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/package-macos-browser.sh+14 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/package-macos-guest.sh+35 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/prepare-macos-cli-kit.sh+40 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/prepare-macos-media.sh+59 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/provision-claude-offline-windows.ps1+212 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/provision-claude-offline-windows.tests.ps1+62 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/provision-macos-workbench.sh+79 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/publish-windows-component-manifest.ps1+53 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/register-macos-browser.sh+35 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/register-macos-claude-window.sh+53 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/register-macos-clipboard.sh+36 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/setup-windows-guest.ps1+128 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/start-windows-evaluation-setup.ps1+182 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tailnet-client.mjs+2 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/test-macos-claude-trial.py+109 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/test-native-debugger.mjs+74 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/test-windows-guest-powershell.cmd+23 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/editor-preferences/EditorPreferences.csproj+12 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/editor-preferences/Program.cs+25 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/macos-browser-service.test.mjs+82 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/macos-cli-login.py+111 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/macos-diagnostics-test.swift+33 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/macos-phone-browser.test.mjs+129 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/native-display-fixture.mjs+76 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/native-download-host-fixture.mjs+50 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/native-input-leases/NativeInputLeases.csproj+12 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/native-input-leases/Program.cs+58 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/native-maintenance.py+269 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/windows-browser-deny-proxy.mjs+34 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/windows-browser-extensions.test.mjs+63 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/windows-browser-fixtures.mjs+12 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/windows-browser.test.mjs+535 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/windows-maintenance.ps1+112 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/tests/windows-native-browser-fixture.mjs+50 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/update-windows-workbench-components.ps1+139 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-browser-extensions.mjs+92 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-browser.mjs+1118 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-evaluation-autounattend.xml+44 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-evaluation.tests.ps1+195 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-file-dialog-qa/WindowsFileDialogProbe.cs+184 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-file-dialog-qa/WindowsFileDialogQA.csproj+18 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-guest-media.ps1+156 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-host-enrollment-smoke.ps1+62 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-host-enrollment.ps1+117 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-host-image.ps1+162 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-host-image.tests.ps1+73 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-phone-browser.mjs+90 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-powershell-media.smoke.ps1+44 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-workbench-packages.json+11 −0看文件

改动太大,不在线显示。

新增scripts/guest-os/windows-workbench-packages.ps1+25 −0看文件

改动太大,不在线显示。