发布 v0.1.1-alpha:支持图片文件传输与声音输出
同步当前安装版的本地账户、Claude Desktop、主题及三平台实现,保留显式发布入口。修复依赖维护通道、恢复标签页启动和原生文件操作。
同步当前安装版的本地账户、Claude Desktop、主题及三平台实现,保留显式发布入口。修复依赖维护通道、恢复标签页启动和原生文件操作。
| @@ -0,0 +1,52 @@ | ||
| 1 | 新增:name: Three-platform checks and test packages | |
| 2 | 新增:on: | |
| 3 | 新增: push: | |
| 4 | 新增: branches: ['**', '!codex/release/**'] | |
| 5 | 新增: pull_request: | |
| 6 | 新增: workflow_dispatch: | |
| 7 | 新增:permissions: | |
| 8 | 新增: contents: read | |
| 9 | 新增:concurrency: | |
| 10 | 新增: group: cage-ci-${{ github.event.pull_request.number || github.ref }} | |
| 11 | 新增: cancel-in-progress: true | |
| 12 | 新增:jobs: | |
| 13 | 新增: workflow-checks: | |
| 14 | 新增: runs-on: ubuntu-24.04 | |
| 15 | 新增: timeout-minutes: 15 | |
| 16 | 新增: steps: | |
| 17 | 新增: - uses: actions/checkout@v4 | |
| 18 | 新增: with: | |
| 19 | 新增: persist-credentials: false | |
| 20 | 新增: - uses: actions/setup-node@v4 | |
| 21 | 新增: with: | |
| 22 | 新增: node-version: 24 | |
| 23 | 新增: - uses: actions/setup-go@v5 | |
| 24 | 新增: with: | |
| 25 | 新增: go-version-file: go.mod | |
| 26 | 新增: - name: Version consistency and release safety tests | |
| 27 | 新增: run: | | |
| 28 | 新增: node scripts/check-version.mjs | |
| 29 | 新增: node --test scripts/release-version.test.mjs scripts/release-control.test.mjs scripts/prepare-release-assets.test.mjs | |
| 30 | 新增: - name: Validate workflow syntax | |
| 31 | 新增: run: go run github.com/rhysd/actionlint/cmd/[email protected] -color | |
| 32 | 新增: macos: | |
| 33 | 新增: needs: workflow-checks | |
| 34 | 新增: uses: ./.github/workflows/macos-build.yml | |
| 35 | 新增: with: | |
| 36 | 新增: ref: ${{ github.sha }} | |
| 37 | 新增: release: false | |
| 38 | 新增: artifact_name: cage-macos-arm64-test | |
| 39 | 新增: windows: | |
| 40 | 新增: needs: workflow-checks | |
| 41 | 新增: uses: ./.github/workflows/windows-build.yml | |
| 42 | 新增: with: | |
| 43 | 新增: ref: ${{ github.sha }} | |
| 44 | 新增: release: false | |
| 45 | 新增: artifact_name: cage-windows-amd64-test | |
| 46 | 新增: linux: | |
| 47 | 新增: needs: workflow-checks | |
| 48 | 新增: uses: ./.github/workflows/linux-build.yml | |
| 49 | 新增: with: | |
| 50 | 新增: ref: ${{ github.sha }} | |
| 51 | 新增: release: false | |
| 52 | 新增: artifact_name: cage-linux-amd64-test | |
| @@ -1,60 +0,0 @@ | ||
| 1 | 删除:name: Cage checks | |
| 2 | 删除:on: | |
| 3 | 删除: push: | |
| 4 | 删除: pull_request: | |
| 5 | 删除: workflow_dispatch: | |
| 6 | 删除:permissions: | |
| 7 | 删除: contents: read | |
| 8 | 删除:concurrency: | |
| 9 | 删除: group: cage-checks-${{ github.ref }} | |
| 10 | 删除: cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} | |
| 11 | 删除:jobs: | |
| 12 | 删除: macos: | |
| 13 | 删除: runs-on: macos-15 | |
| 14 | 删除: timeout-minutes: 40 | |
| 15 | 删除: steps: | |
| 16 | 删除: - uses: actions/checkout@v4 | |
| 17 | 删除: with: | |
| 18 | 删除: persist-credentials: false | |
| 19 | 删除: - uses: actions/setup-go@v5 | |
| 20 | 删除: with: | |
| 21 | 删除: go-version-file: go.mod | |
| 22 | 删除: - uses: actions/setup-node@v4 | |
| 23 | 删除: with: | |
| 24 | 删除: node-version: 24 | |
| 25 | 删除: cache: npm | |
| 26 | 删除: cache-dependency-path: ui/package-lock.json | |
| 27 | 删除: - uses: astral-sh/[email protected] | |
| 28 | 删除: - name: Application version consistency | |
| 29 | 删除: run: node scripts/check-version.mjs | |
| 30 | 删除: - name: Build the actual macOS application | |
| 31 | 删除: run: bash scripts/build-app.sh | |
| 32 | 删除: - name: Workbench checks | |
| 33 | 删除: run: | | |
| 34 | 删除: npm run --prefix ui lint | |
| 35 | 删除: npm test --prefix ui | |
| 36 | 删除: node --test internal/cage/clipboard.test.cjs internal/cage/browser-audit.test.mjs internal/cage/browser-downloads.test.mjs | |
| 37 | 删除: uv run internal/cage/save-download.test.py | |
| 38 | 删除: uv run internal/cage/editor-migrate.test.py | |
| 39 | 删除: - name: Go tests and vet | |
| 40 | 删除: run: | | |
| 41 | 删除: make test-go | |
| 42 | 删除: go test -race ./internal/cage ./internal/managedproxy ./internal/workbench | |
| 43 | 删除: go vet ./cmd/cage ./internal/cage ./internal/managedproxy ./internal/workbench | |
| 44 | 删除: - name: Native application updater | |
| 45 | 删除: run: bash scripts/test-app-updates.sh | |
| 46 | 删除: - name: Patched networking and shared files | |
| 47 | 删除: run: | | |
| 48 | 删除: go test github.com/containers/gvisor-tap-vsock/pkg/services/dns github.com/lima-vm/lima/v2/pkg/hostagent/dns github.com/lima-vm/lima/v2/pkg/networks/usernet github.com/lima-vm/sshocker/pkg/reversesshfs | |
| 49 | 删除: - name: Dependency licenses | |
| 50 | 删除: run: bash scripts/licenses --check | |
| 51 | 删除: - name: Verify bundle | |
| 52 | 删除: run: | | |
| 53 | 删除: codesign --verify --deep --strict _output/Cage.app | |
| 54 | 删除: _output/Cage.app/Contents/Resources/cage --help | |
| 55 | 删除: _output/Cage.app/Contents/Resources/mihomo -v | |
| 56 | 删除: - uses: actions/upload-artifact@v4 | |
| 57 | 删除: with: | |
| 58 | 删除: name: cage-development-build | |
| 59 | 删除: path: _output/Cage.app | |
| 60 | 删除: retention-days: 7 | |
| @@ -0,0 +1,106 @@ | ||
| 1 | 新增:name: Reusable Linux desktop and Debian package | |
| 2 | 新增:on: | |
| 3 | 新增: workflow_call: | |
| 4 | 新增: inputs: | |
| 5 | 新增: ref: | |
| 6 | 新增: description: Exact 40-character commit SHA to build | |
| 7 | 新增: required: true | |
| 8 | 新增: type: string | |
| 9 | 新增: release: | |
| 10 | 新增: description: Produce a release candidate without test reports | |
| 11 | 新增: type: boolean | |
| 12 | 新增: default: false | |
| 13 | 新增: artifact_name: | |
| 14 | 新增: description: Name of the package artifact | |
| 15 | 新增: required: true | |
| 16 | 新增: type: string | |
| 17 | 新增:permissions: | |
| 18 | 新增: contents: read | |
| 19 | 新增:jobs: | |
| 20 | 新增: debian: | |
| 21 | 新增: runs-on: ubuntu-24.04 | |
| 22 | 新增: timeout-minutes: 60 | |
| 23 | 新增: defaults: | |
| 24 | 新增: run: | |
| 25 | 新增: shell: bash | |
| 26 | 新增: container: | |
| 27 | 新增: image: debian:12 | |
| 28 | 新增: # Permit WebKit's own sandbox inside this disposable test container. | |
| 29 | 新增: options: --security-opt seccomp=unconfined --security-opt systempaths=unconfined | |
| 30 | 新增: steps: | |
| 31 | 新增: - name: Install build and test dependencies | |
| 32 | 新增: run: | | |
| 33 | 新增: apt-get update | |
| 34 | 新增: DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential pkg-config libgtk-3-dev libwebkit2gtk-4.1-dev libjson-glib-dev dpkg-dev curl ca-certificates git qemu-system-x86 qemu-utils ovmf openssh-client iproute2 dbus-x11 xvfb xauth fonts-noto-cjk zsh | |
| 35 | 新增: useradd -m -s /bin/bash cage | |
| 36 | 新增: - uses: actions/checkout@v4 | |
| 37 | 新增: with: | |
| 38 | 新增: ref: ${{ inputs.ref }} | |
| 39 | 新增: persist-credentials: false | |
| 40 | 新增: - name: Verify the immutable build revision | |
| 41 | 新增: env: | |
| 42 | 新增: CAGE_BUILD_REF: ${{ inputs.ref }} | |
| 43 | 新增: CAGE_RELEASE: ${{ inputs.release }} | |
| 44 | 新增: run: | | |
| 45 | 新增: [[ "$CAGE_BUILD_REF" =~ ^[0-9a-fA-F]{40}$ ]] || { echo 'Build ref must be a complete commit SHA.' >&2; exit 1; } | |
| 46 | 新增: [[ "$(git rev-parse HEAD)" == "${CAGE_BUILD_REF,,}" ]] || { echo 'Checkout differs from the requested commit.' >&2; exit 1; } | |
| 47 | 新增: if [[ "$CAGE_RELEASE" == true && "$GITHUB_EVENT_NAME" != workflow_dispatch ]]; then | |
| 48 | 新增: echo 'Release candidates require an explicitly dispatched release workflow.' >&2 | |
| 49 | 新增: exit 1 | |
| 50 | 新增: fi | |
| 51 | 新增: - uses: actions/setup-go@v5 | |
| 52 | 新增: with: | |
| 53 | 新增: go-version-file: go.mod | |
| 54 | 新增: - uses: actions/setup-node@v4 | |
| 55 | 新增: with: | |
| 56 | 新增: node-version: 24 | |
| 57 | 新增: cache: npm | |
| 58 | 新增: cache-dependency-path: ui/package-lock.json | |
| 59 | 新增: - name: Build Linux application and package | |
| 60 | 新增: run: | | |
| 61 | 新增: node scripts/check-version.mjs | |
| 62 | 新增: bash scripts/build-linux.sh | |
| 63 | 新增: bash scripts/package-linux.sh --skip-build | |
| 64 | 新增: npm test --prefix ui | |
| 65 | 新增: npm run --prefix ui lint | |
| 66 | 新增: - name: Linux executable tests as an ordinary user | |
| 67 | 新增: run: | | |
| 68 | 新增: chown -R cage:cage "$GITHUB_WORKSPACE" | |
| 69 | 新增: runuser -u cage -- go test ./internal/... ./cmd/... | |
| 70 | 新增: runuser -u cage -- go vet ./internal/managedproxy ./internal/workbench ./cmd/cage | |
| 71 | 新增: - name: Install, render native workbench, reinstall and remove | |
| 72 | 新增: run: | | |
| 73 | 新增: version=$(cat VERSION) | |
| 74 | 新增: bash scripts/test-linux-install.sh "_output/releases/$version/linux/Cage-$version-linux-amd64.deb" | |
| 75 | 新增: - name: Record release candidate identity | |
| 76 | 新增: if: ${{ inputs.release }} | |
| 77 | 新增: run: | | |
| 78 | 新增: version=$(cat VERSION) | |
| 79 | 新增: node scripts/release-version.mjs metadata linux "_output/releases/$version/linux/build-metadata.json" | |
| 80 | 新增: - name: Upload verified package and corresponding source | |
| 81 | 新增: uses: actions/upload-artifact@v4 | |
| 82 | 新增: with: | |
| 83 | 新增: name: ${{ inputs.artifact_name }} | |
| 84 | 新增: path: | | |
| 85 | 新增: _output/releases/*/linux/Cage-*-linux-amd64.deb | |
| 86 | 新增: _output/releases/*/linux/SHA256SUMS | |
| 87 | 新增: _output/releases/*/linux/mihomo-*-source.tar.gz | |
| 88 | 新增: _output/releases/*/linux/build-metadata.json | |
| 89 | 新增: if-no-files-found: error | |
| 90 | 新增: overwrite: true | |
| 91 | 新增: retention-days: 14 | |
| 92 | 新增: - name: Preserve public development test reports | |
| 93 | 新增: if: ${{ always() && !inputs.release }} | |
| 94 | 新增: uses: actions/upload-artifact@v4 | |
| 95 | 新增: with: | |
| 96 | 新增: name: ${{ inputs.artifact_name }}-reports | |
| 97 | 新增: path: | | |
| 98 | 新增: /home/cage-package-test/reports/install.json | |
| 99 | 新增: /home/cage-package-test/reports/first-install.json | |
| 100 | 新增: /home/cage-package-test/reports/first-install.json.png | |
| 101 | 新增: /home/cage-package-test/reports/after-reinstall.json | |
| 102 | 新增: /home/cage-package-test/reports/after-reinstall.json.png | |
| 103 | 新增: if-no-files-found: ignore | |
| 104 | 新增: overwrite: true | |
| 105 | 新增: retention-days: 14 | |
| 106 | 新增: # KVM and physical desktop acceptance remain separate real-machine checks. | |
| @@ -0,0 +1,168 @@ | ||
| 1 | 新增:name: Build Cage for Apple Silicon | |
| 2 | 新增:on: | |
| 3 | 新增: workflow_call: | |
| 4 | 新增: inputs: | |
| 5 | 新增: ref: | |
| 6 | 新增: description: Exact source commit SHA to build | |
| 7 | 新增: required: true | |
| 8 | 新增: type: string | |
| 9 | 新增: release: | |
| 10 | 新增: description: Build signed and notarized release files after checks | |
| 11 | 新增: required: false | |
| 12 | 新增: type: boolean | |
| 13 | 新增: default: false | |
| 14 | 新增: artifact_name: | |
| 15 | 新增: description: Name of the resulting workflow artifact | |
| 16 | 新增: required: true | |
| 17 | 新增: type: string | |
| 18 | 新增:permissions: | |
| 19 | 新增: contents: read | |
| 20 | 新增: | |
| 21 | 新增:jobs: | |
| 22 | 新增: checks: | |
| 23 | 新增: # GitHub's macos-15 image is arm64. Nested VMs are not available here. | |
| 24 | 新增: runs-on: macos-15 | |
| 25 | 新增: timeout-minutes: 45 | |
| 26 | 新增: defaults: | |
| 27 | 新增: run: | |
| 28 | 新增: shell: bash | |
| 29 | 新增: steps: | |
| 30 | 新增: - uses: actions/checkout@v4 | |
| 31 | 新增: with: | |
| 32 | 新增: ref: ${{ inputs.ref }} | |
| 33 | 新增: persist-credentials: false | |
| 34 | 新增: - name: Verify the exact source and Apple Silicon runner | |
| 35 | 新增: env: | |
| 36 | 新增: BUILD_REF: ${{ inputs.ref }} | |
| 37 | 新增: RELEASE_BUILD: ${{ inputs.release }} | |
| 38 | 新增: run: | | |
| 39 | 新增: [[ "$BUILD_REF" =~ ^[0-9a-f]{40}$ ]] || { echo 'Pass an exact commit SHA.' >&2; exit 1; } | |
| 40 | 新增: [[ "$(git rev-parse HEAD)" == "$BUILD_REF" ]] | |
| 41 | 新增: [[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] | |
| 42 | 新增: if [[ "$RELEASE_BUILD" == true && "$GITHUB_EVENT_NAME" != workflow_dispatch ]]; then | |
| 43 | 新增: echo 'Release candidates require an explicit release dispatch.' >&2 | |
| 44 | 新增: exit 1 | |
| 45 | 新增: fi | |
| 46 | 新增: - uses: actions/setup-go@v5 | |
| 47 | 新增: with: | |
| 48 | 新增: go-version-file: go.mod | |
| 49 | 新增: - uses: actions/setup-node@v4 | |
| 50 | 新增: with: | |
| 51 | 新增: node-version: 24 | |
| 52 | 新增: cache: npm | |
| 53 | 新增: cache-dependency-path: ui/package-lock.json | |
| 54 | 新增: - uses: astral-sh/[email protected] | |
| 55 | 新增: - name: Application version consistency | |
| 56 | 新增: run: node scripts/check-version.mjs | |
| 57 | 新增: - name: Build the macOS application without release credentials | |
| 58 | 新增: env: | |
| 59 | 新增: CAGE_SIGNING_IDENTITY: '-' | |
| 60 | 新增: run: bash scripts/build-app.sh | |
| 61 | 新增: - name: Workbench checks | |
| 62 | 新增: run: | | |
| 63 | 新增: npm run --prefix ui lint | |
| 64 | 新增: npm test --prefix ui | |
| 65 | 新增: node --test internal/cage/clipboard.test.cjs internal/cage/browser-audit.test.mjs internal/cage/browser-downloads.test.mjs internal/cage/browser-uploads.test.mjs | |
| 66 | 新增: uv run internal/cage/save-download.test.py | |
| 67 | 新增: uv run internal/cage/editor-migrate.test.py | |
| 68 | 新增: - name: Go tests and vet | |
| 69 | 新增: run: | | |
| 70 | 新增: make test-go | |
| 71 | 新增: go test -race ./internal/cage ./internal/managedproxy ./internal/workbench | |
| 72 | 新增: go vet ./cmd/cage ./internal/cage ./internal/managedproxy ./internal/workbench | |
| 73 | 新增: - name: Native application updater | |
| 74 | 新增: run: bash scripts/test-app-updates.sh | |
| 75 | 新增: - name: Patched networking and shared files | |
| 76 | 新增: run: go test github.com/containers/gvisor-tap-vsock/pkg/services/dns github.com/lima-vm/lima/v2/pkg/hostagent/dns github.com/lima-vm/lima/v2/pkg/networks/usernet github.com/lima-vm/sshocker/pkg/reversesshfs | |
| 77 | 新增: - name: Dependency licenses | |
| 78 | 新增: run: bash scripts/licenses --check | |
| 79 | 新增: - name: Verify the application bundle | |
| 80 | 新增: run: | | |
| 81 | 新增: codesign --verify --deep --strict _output/Cage.app | |
| 82 | 新增: _output/Cage.app/Contents/Resources/cage --help | |
| 83 | 新增: _output/Cage.app/Contents/Resources/mihomo -v | |
| 84 | 新增: [[ "$(lipo -archs _output/Cage.app/Contents/MacOS/Cage)" == arm64 ]] | |
| 85 | 新增: - name: Archive a complete development App with executable permissions | |
| 86 | 新增: if: ${{ !inputs.release }} | |
| 87 | 新增: run: | | |
| 88 | 新增: version=$(tr -d '\r\n' < VERSION) | |
| 89 | 新增: mkdir -p _output/ci-macos-test | |
| 90 | 新增: archive="$PWD/_output/ci-macos-test/Cage-$version-macos-arm64-test.tar.gz" | |
| 91 | 新增: tar -czf "$archive" -C _output Cage.app | |
| 92 | 新增: check=$(mktemp -d "$RUNNER_TEMP/cage-app-archive.XXXXXX") | |
| 93 | 新增: trap 'rm -rf "$check"' EXIT | |
| 94 | 新增: tar -xzf "$archive" -C "$check" | |
| 95 | 新增: codesign --verify --deep --strict "$check/Cage.app" | |
| 96 | 新增: for executable in Contents/MacOS/Cage Contents/Resources/cage Contents/Resources/mihomo Contents/Resources/CageUpdateInstaller; do | |
| 97 | 新增: test -x "$check/Cage.app/$executable" | |
| 98 | 新增: done | |
| 99 | 新增: (cd _output/ci-macos-test && shasum -a 256 "${archive##*/}" > SHA256SUMS) | |
| 100 | 新增: - uses: actions/upload-artifact@v4 | |
| 101 | 新增: if: ${{ !inputs.release }} | |
| 102 | 新增: with: | |
| 103 | 新增: name: ${{ inputs.artifact_name }} | |
| 104 | 新增: path: _output/ci-macos-test/ | |
| 105 | 新增: if-no-files-found: error | |
| 106 | 新增: overwrite: true | |
| 107 | 新增: compression-level: 0 | |
| 108 | 新增: retention-days: 14 | |
| 109 | 新增: | |
| 110 | 新增: release: | |
| 111 | 新增: if: ${{ inputs.release && github.event_name == 'workflow_dispatch' }} | |
| 112 | 新增: needs: checks | |
| 113 | 新增: runs-on: macos-15 | |
| 114 | 新增: environment: cage-release | |
| 115 | 新增: timeout-minutes: 75 | |
| 116 | 新增: defaults: | |
| 117 | 新增: run: | |
| 118 | 新增: shell: bash | |
| 119 | 新增: steps: | |
| 120 | 新增: - uses: actions/checkout@v4 | |
| 121 | 新增: with: | |
| 122 | 新增: ref: ${{ inputs.ref }} | |
| 123 | 新增: persist-credentials: false | |
| 124 | 新增: - name: Verify the exact source and Apple Silicon runner | |
| 125 | 新增: env: | |
| 126 | 新增: BUILD_REF: ${{ inputs.ref }} | |
| 127 | 新增: run: | | |
| 128 | 新增: [[ "$BUILD_REF" =~ ^[0-9a-f]{40}$ ]] | |
| 129 | 新增: [[ "$(git rev-parse HEAD)" == "$BUILD_REF" ]] | |
| 130 | 新增: [[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] | |
| 131 | 新增: - uses: actions/setup-go@v5 | |
| 132 | 新增: with: | |
| 133 | 新增: go-version-file: go.mod | |
| 134 | 新增: - uses: actions/setup-node@v4 | |
| 135 | 新增: with: | |
| 136 | 新增: node-version: 24 | |
| 137 | 新增: cache: npm | |
| 138 | 新增: cache-dependency-path: ui/package-lock.json | |
| 139 | 新增: - name: Build, sign, notarize and verify using a temporary keychain | |
| 140 | 新增: env: | |
| 141 | 新增: CAGE_MACOS_P12_BASE64: ${{ secrets.CAGE_MACOS_P12_BASE64 }} | |
| 142 | 新增: CAGE_MACOS_P12_PASSWORD: ${{ secrets.CAGE_MACOS_P12_PASSWORD }} | |
| 143 | 新增: CAGE_MACOS_SIGNING_IDENTITY: ${{ secrets.CAGE_MACOS_SIGNING_IDENTITY }} | |
| 144 | 新增: CAGE_MACOS_NOTARY_KEY_BASE64: ${{ secrets.CAGE_MACOS_NOTARY_KEY_BASE64 }} | |
| 145 | 新增: CAGE_MACOS_NOTARY_KEY_ID: ${{ secrets.CAGE_MACOS_NOTARY_KEY_ID }} | |
| 146 | 新增: CAGE_MACOS_NOTARY_ISSUER_ID: ${{ secrets.CAGE_MACOS_NOTARY_ISSUER_ID }} | |
| 147 | 新增: CAGE_MACOS_PROVISIONING_PROFILE_BASE64: ${{ secrets.CAGE_MACOS_PROVISIONING_PROFILE_BASE64 }} | |
| 148 | 新增: run: bash scripts/ci-macos-signing.sh run | |
| 149 | 新增: - name: Remove temporary signing credentials | |
| 150 | 新增: if: ${{ always() }} | |
| 151 | 新增: run: bash scripts/ci-macos-signing.sh cleanup | |
| 152 | 新增: - name: Stage only public release files | |
| 153 | 新增: run: | | |
| 154 | 新增: version=$(tr -d '\r\n' < VERSION) | |
| 155 | 新增: source_version=$(sed -n 's/^version=//p' scripts/fetch-proxy-core.sh) | |
| 156 | 新增: release="$PWD/_output/releases/$version" | |
| 157 | 新增: node scripts/release-version.mjs metadata macos "$release/build-metadata.json" | |
| 158 | 新增: mkdir -p _output/ci-macos-release | |
| 159 | 新增: cp "$release/Cage-$version-macos-arm64.dmg" "$release/mihomo-$source_version-source.tar.gz" "$release/SHA256SUMS" "$release/build-metadata.json" _output/ci-macos-release/ | |
| 160 | 新增: (cd _output/ci-macos-release && shasum -a 256 --check SHA256SUMS) | |
| 161 | 新增: - uses: actions/upload-artifact@v4 | |
| 162 | 新增: with: | |
| 163 | 新增: name: ${{ inputs.artifact_name }} | |
| 164 | 新增: path: _output/ci-macos-release/ | |
| 165 | 新增: if-no-files-found: error | |
| 166 | 新增: overwrite: true | |
| 167 | 新增: compression-level: 0 | |
| 168 | 新增: retention-days: 14 | |
| @@ -0,0 +1,137 @@ | ||
| 1 | 新增:name: Publish Cage after an explicit release request | |
| 2 | 新增:on: | |
| 3 | 新增: workflow_dispatch: | |
| 4 | 新增: inputs: | |
| 5 | 新增: bump: | |
| 6 | 新增: description: Version increment (prerelease continues the alpha/beta sequence) | |
| 7 | 新增: required: true | |
| 8 | 新增: default: prerelease | |
| 9 | 新增: type: choice | |
| 10 | 新增: options: [prerelease, patch, minor, major] | |
| 11 | 新增:permissions: | |
| 12 | 新增: contents: read | |
| 13 | 新增:concurrency: | |
| 14 | 新增: group: cage-explicit-release | |
| 15 | 新增: cancel-in-progress: false | |
| 16 | 新增:jobs: | |
| 17 | 新增: readiness: | |
| 18 | 新增: if: github.repository == 'Lee-xeo/Claude-Cage' && github.ref == 'refs/heads/main' | |
| 19 | 新增: runs-on: ubuntu-24.04 | |
| 20 | 新增: timeout-minutes: 10 | |
| 21 | 新增: environment: cage-release | |
| 22 | 新增: steps: | |
| 23 | 新增: - uses: actions/checkout@v4 | |
| 24 | 新增: with: | |
| 25 | 新增: ref: ${{ github.sha }} | |
| 26 | 新增: persist-credentials: false | |
| 27 | 新增: - uses: actions/setup-node@v4 | |
| 28 | 新增: with: | |
| 29 | 新增: node-version: 24 | |
| 30 | 新增: - name: Check release configuration before creating a candidate | |
| 31 | 新增: env: | |
| 32 | 新增: CAGE_MACOS_P12_BASE64: ${{ secrets.CAGE_MACOS_P12_BASE64 }} | |
| 33 | 新增: CAGE_MACOS_P12_PASSWORD: ${{ secrets.CAGE_MACOS_P12_PASSWORD }} | |
| 34 | 新增: CAGE_MACOS_SIGNING_IDENTITY: ${{ secrets.CAGE_MACOS_SIGNING_IDENTITY }} | |
| 35 | 新增: CAGE_MACOS_NOTARY_KEY_BASE64: ${{ secrets.CAGE_MACOS_NOTARY_KEY_BASE64 }} | |
| 36 | 新增: CAGE_MACOS_NOTARY_KEY_ID: ${{ secrets.CAGE_MACOS_NOTARY_KEY_ID }} | |
| 37 | 新增: CAGE_MACOS_NOTARY_ISSUER_ID: ${{ secrets.CAGE_MACOS_NOTARY_ISSUER_ID }} | |
| 38 | 新增: CAGE_WINDOWS_PFX_BASE64: ${{ secrets.CAGE_WINDOWS_PFX_BASE64 }} | |
| 39 | 新增: CAGE_WINDOWS_PFX_PASSWORD: ${{ secrets.CAGE_WINDOWS_PFX_PASSWORD }} | |
| 40 | 新增: CAGE_WINDOWS_QEMU_SOURCE_URL: ${{ vars.CAGE_WINDOWS_QEMU_SOURCE_URL }} | |
| 41 | 新增: CAGE_WINDOWS_QEMU_SOURCE_SHA256: ${{ vars.CAGE_WINDOWS_QEMU_SOURCE_SHA256 }} | |
| 42 | 新增: run: node scripts/check-release-readiness.mjs | |
| 43 | 新增: - name: Validate versions and release behavior | |
| 44 | 新增: run: | | |
| 45 | 新增: node scripts/check-version.mjs | |
| 46 | 新增: node --test scripts/release-version.test.mjs scripts/release-control.test.mjs scripts/prepare-release-assets.test.mjs | |
| 47 | 新增: prepare: | |
| 48 | 新增: needs: readiness | |
| 49 | 新增: runs-on: ubuntu-24.04 | |
| 50 | 新增: timeout-minutes: 10 | |
| 51 | 新增: permissions: | |
| 52 | 新增: contents: write | |
| 53 | 新增: outputs: | |
| 54 | 新增: version: ${{ steps.candidate.outputs.version }} | |
| 55 | 新增: commit_sha: ${{ steps.candidate.outputs.commit_sha }} | |
| 56 | 新增: source_sha: ${{ steps.candidate.outputs.source_sha }} | |
| 57 | 新增: steps: | |
| 58 | 新增: - uses: actions/checkout@v4 | |
| 59 | 新增: with: | |
| 60 | 新增: ref: ${{ github.sha }} | |
| 61 | 新增: persist-credentials: false | |
| 62 | 新增: - uses: actions/setup-node@v4 | |
| 63 | 新增: with: | |
| 64 | 新增: node-version: 24 | |
| 65 | 新增: - name: Prepare or reuse this run's version-only candidate | |
| 66 | 新增: id: candidate | |
| 67 | 新增: env: | |
| 68 | 新增: GH_TOKEN: ${{ github.token }} | |
| 69 | 新增: run: node scripts/release-control.mjs prepare | |
| 70 | 新增: macos: | |
| 71 | 新增: needs: prepare | |
| 72 | 新增: uses: ./.github/workflows/macos-build.yml | |
| 73 | 新增: with: | |
| 74 | 新增: ref: ${{ needs.prepare.outputs.commit_sha }} | |
| 75 | 新增: release: true | |
| 76 | 新增: artifact_name: release-macos | |
| 77 | 新增: windows: | |
| 78 | 新增: needs: prepare | |
| 79 | 新增: uses: ./.github/workflows/windows-build.yml | |
| 80 | 新增: with: | |
| 81 | 新增: ref: ${{ needs.prepare.outputs.commit_sha }} | |
| 82 | 新增: release: true | |
| 83 | 新增: artifact_name: release-windows | |
| 84 | 新增: linux: | |
| 85 | 新增: needs: prepare | |
| 86 | 新增: uses: ./.github/workflows/linux-build.yml | |
| 87 | 新增: with: | |
| 88 | 新增: ref: ${{ needs.prepare.outputs.commit_sha }} | |
| 89 | 新增: release: true | |
| 90 | 新增: artifact_name: release-linux | |
| 91 | 新增: publish: | |
| 92 | 新增: needs: [prepare, macos, windows, linux] | |
| 93 | 新增: runs-on: ubuntu-24.04 | |
| 94 | 新增: timeout-minutes: 45 | |
| 95 | 新增: permissions: | |
| 96 | 新增: contents: write | |
| 97 | 新增: outputs: | |
| 98 | 新增: tag: ${{ steps.release.outputs.tag }} | |
| 99 | 新增: url: ${{ steps.release.outputs.url }} | |
| 100 | 新增: steps: | |
| 101 | 新增: - uses: actions/checkout@v4 | |
| 102 | 新增: with: | |
| 103 | 新增: ref: ${{ needs.prepare.outputs.commit_sha }} | |
| 104 | 新增: fetch-depth: 0 | |
| 105 | 新增: persist-credentials: false | |
| 106 | 新增: - uses: actions/setup-node@v4 | |
| 107 | 新增: with: | |
| 108 | 新增: node-version: 24 | |
| 109 | 新增: - uses: actions/download-artifact@v4 | |
| 110 | 新增: with: | |
| 111 | 新增: name: release-macos | |
| 112 | 新增: path: _output/release-artifacts/macos | |
| 113 | 新增: - uses: actions/download-artifact@v4 | |
| 114 | 新增: with: | |
| 115 | 新增: name: release-windows | |
| 116 | 新增: path: _output/release-artifacts/windows | |
| 117 | 新增: - uses: actions/download-artifact@v4 | |
| 118 | 新增: with: | |
| 119 | 新增: name: release-linux | |
| 120 | 新增: path: _output/release-artifacts/linux | |
| 121 | 新增: - name: Verify all platforms, promote atomically, then publish complete assets | |
| 122 | 新增: id: release | |
| 123 | 新增: env: | |
| 124 | 新增: GH_TOKEN: ${{ github.token }} | |
| 125 | 新增: RELEASE_SOURCE_SHA: ${{ needs.prepare.outputs.source_sha }} | |
| 126 | 新增: RELEASE_COMMIT_SHA: ${{ needs.prepare.outputs.commit_sha }} | |
| 127 | 新增: RELEASE_VERSION: ${{ needs.prepare.outputs.version }} | |
| 128 | 新增: run: node scripts/release-control.mjs publish | |
| 129 | 新增: website: | |
| 130 | 新增: needs: publish | |
| 131 | 新增: permissions: | |
| 132 | 新增: contents: read | |
| 133 | 新增: pages: write | |
| 134 | 新增: id-token: write | |
| 135 | 新增: uses: ./.github/workflows/www.yml | |
| 136 | 新增: with: | |
| 137 | 新增: release_tag: ${{ needs.publish.outputs.tag }} | |
| @@ -0,0 +1,122 @@ | ||
| 1 | 新增:name: Reusable Windows build and installer | |
| 2 | 新增:on: | |
| 3 | 新增: workflow_call: | |
| 4 | 新增: inputs: | |
| 5 | 新增: ref: | |
| 6 | 新增: description: Exact 40-character commit SHA to build | |
| 7 | 新增: required: true | |
| 8 | 新增: type: string | |
| 9 | 新增: release: | |
| 10 | 新增: description: Require trusted signing and reviewed corresponding sources | |
| 11 | 新增: type: boolean | |
| 12 | 新增: default: false | |
| 13 | 新增: artifact_name: | |
| 14 | 新增: description: Release artifact name, or development artifact prefix | |
| 15 | 新增: required: true | |
| 16 | 新增: type: string | |
| 17 | 新增:permissions: | |
| 18 | 新增: contents: read | |
| 19 | 新增:jobs: | |
| 20 | 新增: development: | |
| 21 | 新增: if: ${{ !inputs.release }} | |
| 22 | 新增: strategy: | |
| 23 | 新增: fail-fast: false | |
| 24 | 新增: matrix: | |
| 25 | 新增: os: [windows-2022, windows-2025] | |
| 26 | 新增: runs-on: ${{ matrix.os }} | |
| 27 | 新增: timeout-minutes: 60 | |
| 28 | 新增: defaults: | |
| 29 | 新增: run: | |
| 30 | 新增: shell: pwsh | |
| 31 | 新增: steps: | |
| 32 | 新增: - uses: actions/checkout@v4 | |
| 33 | 新增: with: | |
| 34 | 新增: ref: ${{ inputs.ref }} | |
| 35 | 新增: persist-credentials: false | |
| 36 | 新增: - uses: actions/setup-go@v5 | |
| 37 | 新增: with: | |
| 38 | 新增: go-version-file: go.mod | |
| 39 | 新增: - uses: actions/setup-node@v4 | |
| 40 | 新增: with: | |
| 41 | 新增: node-version: 24 | |
| 42 | 新增: cache: npm | |
| 43 | 新增: cache-dependency-path: ui/package-lock.json | |
| 44 | 新增: - uses: actions/setup-dotnet@v4 | |
| 45 | 新增: with: | |
| 46 | 新增: dotnet-version: 10.0.403 | |
| 47 | 新增: - uses: astral-sh/[email protected] | |
| 48 | 新增: - uses: actions/cache@v4 | |
| 49 | 新增: with: | |
| 50 | 新增: path: _output/windows-deps | |
| 51 | 新增: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json') }} | |
| 52 | 新增: - name: Build, test and install the unsigned development package | |
| 53 | 新增: env: | |
| 54 | 新增: CAGE_BUILD_REF: ${{ inputs.ref }} | |
| 55 | 新增: run: ./scripts/ci-windows-build.ps1 | |
| 56 | 新增: - uses: actions/upload-artifact@v4 | |
| 57 | 新增: with: | |
| 58 | 新增: name: ${{ inputs.artifact_name }}-${{ matrix.os }} | |
| 59 | 新增: path: _output/releases/*/windows/* | |
| 60 | 新增: if-no-files-found: error | |
| 61 | 新增: overwrite: true | |
| 62 | 新增: retention-days: 14 | |
| 63 | 新增: - name: Preserve public test reports | |
| 64 | 新增: if: always() | |
| 65 | 新增: uses: actions/upload-artifact@v4 | |
| 66 | 新增: with: | |
| 67 | 新增: name: ${{ inputs.artifact_name }}-${{ matrix.os }}-reports | |
| 68 | 新增: path: ${{ runner.temp }}/cage-smoke-*.json | |
| 69 | 新增: if-no-files-found: ignore | |
| 70 | 新增: overwrite: true | |
| 71 | 新增: retention-days: 14 | |
| 72 | 新增: release: | |
| 73 | 新增: if: ${{ inputs.release }} | |
| 74 | 新增: runs-on: windows-2025 | |
| 75 | 新增: environment: cage-release | |
| 76 | 新增: timeout-minutes: 60 | |
| 77 | 新增: defaults: | |
| 78 | 新增: run: | |
| 79 | 新增: shell: pwsh | |
| 80 | 新增: steps: | |
| 81 | 新增: - uses: actions/checkout@v4 | |
| 82 | 新增: with: | |
| 83 | 新增: ref: ${{ inputs.ref }} | |
| 84 | 新增: persist-credentials: false | |
| 85 | 新增: - uses: actions/setup-go@v5 | |
| 86 | 新增: with: | |
| 87 | 新增: go-version-file: go.mod | |
| 88 | 新增: - uses: actions/setup-node@v4 | |
| 89 | 新增: with: | |
| 90 | 新增: node-version: 24 | |
| 91 | 新增: cache: npm | |
| 92 | 新增: cache-dependency-path: ui/package-lock.json | |
| 93 | 新增: - uses: actions/setup-dotnet@v4 | |
| 94 | 新增: with: | |
| 95 | 新增: dotnet-version: 10.0.403 | |
| 96 | 新增: - uses: astral-sh/[email protected] | |
| 97 | 新增: - uses: actions/cache@v4 | |
| 98 | 新增: with: | |
| 99 | 新增: path: _output/windows-deps | |
| 100 | 新增: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json') }} | |
| 101 | 新增: - name: Build, sign, test and install the release candidate | |
| 102 | 新增: env: | |
| 103 | 新增: CAGE_BUILD_REF: ${{ inputs.ref }} | |
| 104 | 新增: CAGE_WINDOWS_PFX_BASE64: ${{ secrets.CAGE_WINDOWS_PFX_BASE64 }} | |
| 105 | 新增: CAGE_WINDOWS_PFX_PASSWORD: ${{ secrets.CAGE_WINDOWS_PFX_PASSWORD }} | |
| 106 | 新增: CAGE_WINDOWS_QEMU_SOURCE_URL: ${{ vars.CAGE_WINDOWS_QEMU_SOURCE_URL }} | |
| 107 | 新增: CAGE_WINDOWS_QEMU_SOURCE_SHA256: ${{ vars.CAGE_WINDOWS_QEMU_SOURCE_SHA256 }} | |
| 108 | 新增: run: ./scripts/ci-windows-build.ps1 -Release | |
| 109 | 新增: - uses: actions/upload-artifact@v4 | |
| 110 | 新增: with: | |
| 111 | 新增: name: ${{ inputs.artifact_name }} | |
| 112 | 新增: path: | | |
| 113 | 新增: _output/releases/*/windows/Cage-*-windows-amd64-setup.exe | |
| 114 | 新增: _output/releases/*/windows/SHA256SUMS | |
| 115 | 新增: _output/releases/*/windows/mihomo-*-source.tar.gz | |
| 116 | 新增: _output/releases/*/windows/qemu-*-source.tar.gz | |
| 117 | 新增: _output/releases/*/windows/qemu-*-windows-full-source.* | |
| 118 | 新增: _output/releases/*/windows/build-metadata.json | |
| 119 | 新增: if-no-files-found: error | |
| 120 | 新增: overwrite: true | |
| 121 | 新增: retention-days: 14 | |
| 122 | 新增: # The caller owns publication. This workflow has no repository write access. | |
| @@ -6,17 +6,23 @@ on: | ||
| 6 | 6 | pull_request: |
| 7 | 7 | paths: ['www/**', 'assets/**', 'README*.md', 'scripts/verify-macos-release.sh', '.github/workflows/www.yml'] |
| 8 | 8 | release: |
| 9 | 删除: types: [published, edited] | |
| 9 | 新增: types: [published] | |
| 10 | 10 | workflow_dispatch: |
| 11 | 11 | inputs: |
| 12 | 12 | release_tag: |
| 13 | 13 | description: 'Optional public release tag to download and verify before deployment' |
| 14 | 14 | required: false |
| 15 | 15 | type: string |
| 16 | 新增: workflow_call: | |
| 17 | 新增: inputs: | |
| 18 | 新增: release_tag: | |
| 19 | 新增: description: Exact published Cage release to verify and deploy | |
| 20 | 新增: required: true | |
| 21 | 新增: type: string | |
| 16 | 22 | permissions: |
| 17 | 23 | contents: read |
| 18 | 24 | concurrency: |
| 19 | 删除: group: website-${{ github.ref }} | |
| 25 | 新增: group: website-${{ github.event_name }}-${{ inputs.release_tag || github.event.release.tag_name || github.ref }} | |
| 20 | 26 | cancel-in-progress: false |
| 21 | 27 | jobs: |
| 22 | 28 | verify-release: |
| @@ -56,7 +62,14 @@ jobs: | ||
| 56 | 62 | - run: npm ci --prefix www |
| 57 | 63 | - run: node --test www/scripts/sync-release.test.mjs |
| 58 | 64 | - name: Resolve the public download version |
| 59 | 删除: run: node www/scripts/sync-release.mjs | |
| 65 | 新增: env: | |
| 66 | 新增: RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag }} | |
| 67 | 新增: run: | | |
| 68 | 新增: if [[ -n "$RELEASE_TAG" ]]; then | |
| 69 | 新增: node www/scripts/sync-release.mjs --tag "$RELEASE_TAG" | |
| 70 | 新增: else | |
| 71 | 新增: node www/scripts/sync-release.mjs | |
| 72 | 新增: fi | |
| 60 | 73 | - run: npm run --prefix www check |
| 61 | 74 | - run: npm run --prefix www build |
| 62 | 75 | - run: node www/scripts/check-site.mjs |
| @@ -65,7 +78,7 @@ jobs: | ||
| 65 | 78 | path: www/dist |
| 66 | 79 | deploy: |
| 67 | 80 | needs: build |
| 68 | 删除: if: always() && needs.build.result == 'success' && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.event_name == 'release') | |
| 81 | 新增: if: always() && needs.build.result == 'success' && (github.event_name == 'workflow_dispatch' || github.event_name == 'release') && (github.ref == 'refs/heads/main' || github.event_name == 'release') | |
| 69 | 82 | runs-on: ubuntu-latest |
| 70 | 83 | timeout-minutes: 10 |
| 71 | 84 | concurrency: |
| @@ -0,0 +1,14 @@ | ||
| 1 | 新增:# Cage 项目协作约定 | |
| 2 | 新增: | |
| 3 | 新增:## 跨平台同步 | |
| 4 | 新增: | |
| 5 | 新增:- 每次修改都要同步处理 macOS、Windows 和 Linux,保持共用功能、接口、数据格式和用户操作的一致性。 | |
| 6 | 新增:- 修改原生桥、启动与退出、权限、快捷键、更新或打包流程时,核对三个平台的对应实现。平台专属代码按实际需要修改,共用代码应继续兼容三个平台。 | |
| 7 | 新增:- 同步维护受影响的说明与构建配置,按改动影响执行相应平台验证。无法实测的项目明确记录;不能把单平台通过写成三平台通过,也不能默默遗漏其他平台。 | |
| 8 | 新增: | |
| 9 | 新增:## 版本与发布 | |
| 10 | 新增: | |
| 11 | 新增:- 默认只完成用户要求的修改、验证和交付。完成开发、构建测试包、提交或推送代码,都不自动授权升级版本号或发版。 | |
| 12 | 新增:- 只有用户明确要求发版时,才升级版本号、创建发布标签并执行发布;预发行版本同样遵守此规则。 | |
| 13 | 新增:- 关于自动发布、CI/CD 或发布方案的讨论不构成发版授权。自动化流程必须保留用户明确发版的触发点,普通代码推送不能隐式变成应用发版。 | |
| 14 | 新增:- 用户要求发版后,可以自动执行已授权的构建、签名、公证、打包、校验与发布步骤,无需逐步重复征询。跨平台能力和验证范围仍需如实说明。 | |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # 参与开发 |
| 2 | 2 | |
| 3 | 删除:Cage 的主要开发环境是 Apple Silicon macOS 14+。用户安装预构建 App 即可使用;本页面向需要修改工作台、控制服务或虚拟机底座的贡献者。 | |
| 3 | 新增:Cage 的桌面开发目标为 Apple Silicon macOS 14+、Windows 10 22H2/11 x64 和 Debian/Ubuntu Linux x86_64。平台构建工具、安装器和验收范围见 [Windows 指南](docs/windows.md#维护者构建与验收)与 [Linux 指南](docs/linux.md#维护者构建与验收)。用户安装预构建 App 即可使用;本页面向需要修改工作台、控制服务或虚拟机底座的贡献者。 | |
| 4 | 4 | |
| 5 | 5 | ## 从源码构建 |
| 6 | 6 | |
| @@ -30,7 +30,7 @@ bash scripts/build-app.sh --install | ||
| 30 | 30 | |
| 31 | 31 | | 目录 | 职责 | |
| 32 | 32 | |---|---| |
| 33 | 删除:| `desktop/` | Swift 原生 Mac 窗口、菜单和系统集成 | | |
| 33 | 新增:| `desktop/` | Swift macOS 窗口;`desktop/windows/` 为 WinForms/WebView2 窗口;`desktop/linux/` 为 GTK/WebKitGTK 窗口 | | |
| 34 | 34 | | `ui/` | React 工作台、代理管理、设置和网络状态 | |
| 35 | 35 | | `internal/workbench/` | 工作台控制接口、任务、终端和设置 | |
| 36 | 36 | | `internal/cage/` | 强制代理、网络门槛和客机服务 | |
| @@ -40,6 +40,10 @@ bash scripts/build-app.sh --install | ||
| 40 | 40 | |
| 41 | 41 | 修改前阅读对应的[工作台设计](docs/design/workbench.md)、[网络检查设计](docs/design/network-checks.md)或[内置代理设计](docs/design/managed-proxy.md)。调整接口、数据归属或安全边界时,同时更新设计与用户说明。 |
| 42 | 42 | |
| 43 | 新增:## 自动检查与发布 | |
| 44 | 新增: | |
| 45 | 新增:日常推送会运行三平台检查并生成测试包,版本号保持不变。只有用户明确要求发版时,才运行独立的发布入口;配置和失败恢复见 [CI/CD 指南](docs/ci-cd.md)。 | |
| 46 | 新增: | |
| 43 | 47 | ## 验证改动 |
| 44 | 48 | |
| 45 | 49 | 选择覆盖本次行为的检查。工作台的基础检查: |
| @@ -63,6 +67,8 @@ go test github.com/containers/gvisor-tap-vsock/pkg/services/dns \ | ||
| 63 | 67 | github.com/lima-vm/lima/v2/pkg/networks/usernet |
| 64 | 68 | ``` |
| 65 | 69 | |
| 70 | 新增:修改外观或主题管理时,执行 `node ui/scripts/appearance-smoke.mjs`、`node ui/scripts/theme-smoke.mjs` 和 `node ui/scripts/builtin-theme-smoke.mjs`,并运行 `go test -race ./internal/workbench -run 'Test(CodexAppearance|Appearance)'`。浏览器脚本需要可用的 Playwright 和前端开发服务,可通过 `CAGE_PLAYWRIGHT_MODULE`、`CAGE_UI_URL` 指定;使用隔离控制接口,不接入日常 VM。原生文件窗口还须在实际 App 中验证导入、导出与取消。 | |
| 71 | 新增: | |
| 66 | 72 | 修改浏览器启动或控制逻辑时,在 Linux 客机的独立 X 显示中运行 `DISPLAY=:183 node scripts/browser-controls-smoke.mjs`。该检查使用临时配置和真实控制器,验证人工浏览标记、标签与导航、重启后的页面及 Cookie 恢复,并检查未认证请求和跨来源请求仍被拒绝。 |
| 67 | 73 | |
| 68 | 74 | 修改更新或恢复界面时,运行 `node ui/scripts/recovery-ui-smoke.mjs`;修改画面可见性时,运行 `node ui/scripts/remote-visibility-smoke.mjs`。两者需要可用的 Playwright 和已启动的前端开发服务,可通过 `CAGE_UI_URL` 指定地址;测试使用隔离接口,后者还使用真实 RFB 握手与帧验证停止和恢复,不连接日常 VM。修改原生更新流程时运行 `bash scripts/test-app-updates.sh`,正式签名、公证及真实安装仍须单独验收。组件清单、固定工具安装器和网络续租回归已包含在上述 Go 包测试中,无需重复执行一套独立命令。 |
| @@ -88,7 +94,7 @@ make cage | ||
| 88 | 94 | |
| 89 | 95 | `cage access`、独立 VNC 和编辑器端口仅供诊断,输出可能包含访问凭据,不要直接上传。普通用户通过 App 或 `cage desktop` 自动建立会话,无需输入内部访问密码。 |
| 90 | 96 | |
| 91 | 删除:代理节点统一通过 Cage 内的订阅、本地 YAML 或手动节点入口配置。运行时只使用 App 随附核心。来源、运行配置和日志位于私有配置的 `proxy/` 子目录,通过独立用户 launchd 任务运行;来源与凭据文件权限为 `0600`。`config.json` 中的代理端点和版本由节点管理器生成,通用设置及恢复操作不能覆盖。 | |
| 97 | 新增:代理节点统一通过 Cage 内的订阅、本地 YAML 或手动节点入口配置。运行时只使用 App 随附核心。来源、运行配置和日志位于私有配置的 `proxy/` 子目录;macOS 通过独立用户 launchd 任务运行,Linux 通过普通用户后台进程运行。来源与凭据文件权限为 `0600`。`config.json` 中的代理端点和版本由节点管理器生成,通用设置及恢复操作不能覆盖。 | |
| 92 | 98 | |
| 93 | 99 | ## 提交改进 |
| 94 | 100 | |
| @@ -51,7 +51,7 @@ all: agent-vm | ||
| 51 | 51 | |
| 52 | 52 | # Claude Cage ships a separate entry point with a mandatory proxy profile. |
| 53 | 53 | cage: cage-ui assets |
| 54 | 删除: $(GO_BUILD) -o _output/bin/cage ./cmd/cage | |
| 54 | 新增: $(GO_BUILD) -o _output/bin/cage$(EXE) ./cmd/cage | |
| 55 | 55 | ifeq ($(GOOS),darwin) |
| 56 | 56 | codesign -f --entitlements third_party/lima/vz.entitlements -s - _output/bin/cage |
| 57 | 57 | endif |
| @@ -60,6 +60,22 @@ cage-ui: | ||
| 60 | 60 | npm --prefix ui ci --no-audit --no-fund |
| 61 | 61 | npm run --prefix ui build |
| 62 | 62 | |
| 63 | 新增:.PHONY: cage cage-ui cage-windows package-windows cage-linux package-linux check-linux | |
| 64 | 新增:cage-linux: | |
| 65 | 新增: bash scripts/build-linux.sh | |
| 66 | 新增: | |
| 67 | 新增:package-linux: | |
| 68 | 新增: bash scripts/package-linux.sh | |
| 69 | 新增: | |
| 70 | 新增:check-linux: | |
| 71 | 新增: GOOS=linux GOARCH=amd64 CGO_ENABLED=0 $(GO) vet -tags $(TAGS) . ./cmd/... ./internal/... | |
| 72 | 新增: | |
| 73 | 新增:cage-windows: | |
| 74 | 新增: pwsh -NoProfile -File scripts/build-windows.ps1 | |
| 75 | 新增: | |
| 76 | 新增:package-windows: | |
| 77 | 新增: pwsh -NoProfile -File scripts/package-windows.ps1 | |
| 78 | 新增: | |
| 63 | 79 | agent-vm: assets |
| 64 | 80 | $(GO_BUILD) -o _output/bin/agent-vm$(EXE) ./cmd/agent-vm |
| 65 | 81 | ifeq ($(GOOS),darwin) |
| @@ -54,7 +54,7 @@ Claude Cage የሊኑክስ ተርሚናልን፣ አሳሽ እና ፋይል አ | ||
| 54 | 54 | |
| 55 | 55 | ጫኚው የስራ ቤንች እና የኔትወርክ ፕሮክሲ ኮርን ያካትታል። ዕለታዊ አጠቃቀም Go፣ Node.js፣ Docker ወይም Clash መጫን አያስፈልገውም። መጀመሪያ ማስጀመር የሊኑክስን ምስል እና የግንባታ መሳሪያዎችን ለማውረድ አሁንም የበይነመረብ ግንኙነት ይፈልጋል። Cage የኔትወርክ ተኪ አገልግሎትም ሆነ የClaude መለያ አይሰጥም። |
| 56 | 56 | |
| 57 | 删除:የአሁኑ ስሪት፡ `0.1.0-alpha.1`. የምንጭ ኮድ፣ ድር ጣቢያ እና የተለቀቁት ይፋዊ ናቸው። ለጫኚ ፊርማ፣ አፕል ኖተራይዜሽን እና የማረጋገጫ ወሰን የእያንዳንዱን ልቀት ማስታወሻ ይመልከቱ። ንጹህ ማሽን መጫን፣ macOS 14 ን በሚያሄዱ አካላዊ Macs ላይ ተኳሃኝነት፣ የእውነተኛ Claude መለያ ፈቃድ እና የሞዴል ጥያቄዎች አሁንም ሙሉ ማረጋገጫ ያስፈልጋቸዋል። | |
| 57 | 新增:የአሁኑ ስሪት፡ `0.1.1-alpha`. የምንጭ ኮድ፣ ድር ጣቢያ እና የተለቀቁት ይፋዊ ናቸው። ለጫኚ ፊርማ፣ አፕል ኖተራይዜሽን እና የማረጋገጫ ወሰን የእያንዳንዱን ልቀት ማስታወሻ ይመልከቱ። ንጹህ ማሽን መጫን፣ macOS 14 ን በሚያሄዱ አካላዊ Macs ላይ ተኳሃኝነት፣ የእውነተኛ Claude መለያ ፈቃድ እና የሞዴል ጥያቄዎች አሁንም ሙሉ ማረጋገጫ ያስፈልጋቸዋል። | |
| 58 | 58 | |
| 59 | 59 | የውስጠ-መተግበሪያ ማሻሻያ ድጋፍ ያላቸው ስሪቶች ከታች በስተግራ ጥግ ላይ ያለውን የዝማኔ ቁጥጥር ያሳያሉ። ዝማኔ ሲገኝ፣ የታች ቀስት መሣሪያ ጫፉ 'አውርድ ዝመናን' ያነባል። እሱን ጠቅ ማድረግ ያውርዳል፣ ያረጋግጣል፣ ይጭናል እና መተግበሪያውን እንደገና ያስጀምራል። አስቀምጥ እና መጀመሪያ ስራዎችን ማስኬድ አቁም. በተመረጠው የአውታረ መረብ ተኪ በኩል ማውረድን ያዘምናል፣ ወደ ቀጥታ ግንኙነት ምንም መመለስ የለም። በራስ ሰር መጫን ከተመሳሳይ አታሚ ፊርማ እና የአፕል ማረጋገጫ ያስፈልገዋል። ተከታይ ስሪቶች የውስጠ-መተግበሪያ ዝማኔዎችን መጠቀም ይችላሉ። ለዝርዝር መረጃ ይመልከቱ [ያሻሽሉ እና ያራግፉ](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ Claude Cage عبارة عن جهاز Linux افتراضي خفيف الوزن ي | ||
| 54 | 54 | |
| 55 | 55 | يشتمل برنامج التثبيت على منضدة العمل ونواة وكيل الشبكة. لا يتطلب الاستخدام اليومي تثبيت Go أو Node.js أو Docker أو Clash. لا يزال الإطلاق الأول يتطلب اتصالاً بالإنترنت لتنزيل صورة Linux وأدوات التطوير. لا يوفر Cage خدمة وكيل الشبكة ولا حساب Claude. |
| 56 | 56 | |
| 57 | 删除:الإصدار الحالي: `0.1.0-alpha.1`. كود المصدر والموقع الإلكتروني والإصدارات عامة. راجع ملاحظات كل إصدار لتوقيع المثبت وتوثيق Apple ونطاق التحقق من الصحة. لا يزال التثبيت النظيف للجهاز، والتوافق على أجهزة Mac الفعلية التي تعمل بنظام macOS 14، والترخيص الحقيقي لحساب Claude، وطلبات النماذج تتطلب التحقق الكامل من الصحة. | |
| 57 | 新增:الإصدار الحالي: `0.1.1-alpha`. كود المصدر والموقع الإلكتروني والإصدارات عامة. راجع ملاحظات كل إصدار لتوقيع المثبت وتوثيق Apple ونطاق التحقق من الصحة. لا يزال التثبيت النظيف للجهاز، والتوافق على أجهزة Mac الفعلية التي تعمل بنظام macOS 14، والترخيص الحقيقي لحساب Claude، وطلبات النماذج تتطلب التحقق الكامل من الصحة. | |
| 58 | 58 | |
| 59 | 59 | تُظهر الإصدارات التي تدعم التحديث داخل التطبيق عنصر تحكم في التحديث في الزاوية السفلية اليسرى. عندما يتوفر تحديث، يقرأ تلميح الأداة المتجه للأسفل "تنزيل التحديث". يؤدي النقر فوقه إلى تنزيل التطبيق والتحقق منه وتثبيته وإعادة تشغيله. حفظ وإيقاف تشغيل المهام أولاً. يتم تنزيل التحديثات من خلال وكيل الشبكة المحدد، دون الرجوع إلى الاتصال المباشر. يتطلب التثبيت التلقائي توقيعًا من نفس الناشر وتحققًا من Apple. يمكن للإصدارات اللاحقة استخدام التحديثات داخل التطبيق. لمزيد من التفاصيل، انظر [ترقية وإلغاء التثبيت](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ Claude Cage - гэта лёгкая віртуальная машына Linux, | ||
| 54 | 54 | |
| 55 | 55 | Праграма ўстаноўкі ўключае варштат і ядро сеткавага проксі. Штодзённае выкарыстанне не патрабуе ўстаноўкі Go, Node.js, Docker або Clash. Для першага запуску па-ранейшаму патрабуецца падключэнне да Інтэрнэту для загрузкі вобраза Linux і інструментаў распрацоўкі. Cage не забяспечвае ні паслугу сеткавага проксі, ні ўліковы запіс Claude. |
| 56 | 56 | |
| 57 | 删除:Актуальная версія: `0.1.0-alpha.1`. Зыходны код, вэб-сайт і выпускі з'яўляюцца агульнадаступнымі. Звярніцеся да заўваг да кожнага выпуску для подпісу ўсталёўшчыка, натарыяльнага засведчання Apple і аб'ёму праверкі. Усталяванне на чыстай машыне, сумяшчальнасць на фізічных Mac пад кіраваннем macOS 14, аўтарызацыя рэальнага ўліковага запісу Claude і запыты мадэляў па-ранейшаму патрабуюць поўнай праверкі. | |
| 57 | 新增:Актуальная версія: `0.1.1-alpha`. Зыходны код, вэб-сайт і выпускі з'яўляюцца агульнадаступнымі. Звярніцеся да заўваг да кожнага выпуску для подпісу ўсталёўшчыка, натарыяльнага засведчання Apple і аб'ёму праверкі. Усталяванне на чыстай машыне, сумяшчальнасць на фізічных Mac пад кіраваннем macOS 14, аўтарызацыя рэальнага ўліковага запісу Claude і запыты мадэляў па-ранейшаму патрабуюць поўнай праверкі. | |
| 58 | 58 | |
| 59 | 59 | Версіі з падтрымкай абнаўленняў у праграме паказваюць элемент кіравання абнаўленнямі ў левым ніжнім куце. Калі абнаўленне даступна, падказка са стрэлкай уніз абвяшчае «Спампаваць абнаўленне». Пстрыкнуўшы па ім, праграма спампоўваецца, правяраецца, усталёўваецца і перазапускаецца. Спачатку захавайце і спыніце запушчаныя задачы. Абнаўленні спампоўваюцца праз абраны сеткавы проксі без вяртання да прамога злучэння. Аўтаматычная ўстаноўка патрабуе подпісу таго ж выдаўца і праверкі Apple. Наступныя версіі могуць выкарыстоўваць абнаўленні ў дадатку. Падрабязней гл [Абнавіць і выдаліць](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ La versión inicial admite **Apple Silicon Macs (chips de la serie M), con macOS | ||
| 54 | 54 | |
| 55 | 55 | El instalador incluye el banco de trabajo y el núcleo del proxy de red. El uso diario no requiere instalar Go, Node.js, Docker o Clash. El primer lanzamiento aún requiere una conexión a Internet para descargar la imagen de Linux y las herramientas de desarrollo. Cage no proporciona un servicio de proxy de red ni una cuenta Claude. |
| 56 | 56 | |
| 57 | 删除:Versión actual: `0.1.0-alpha.1`. El código fuente, el sitio web y los lanzamientos son públicos. Consulte las notas de cada versión para conocer la firma del instalador, la certificación notarial de Apple y el alcance de la validación. La instalación en máquina limpia, la compatibilidad con Mac físicos que ejecutan macOS 14, la autorización de cuentas reales de Claude y las solicitudes de modelos aún requieren una validación completa. | |
| 57 | 新增:Versión actual: `0.1.1-alpha`. El código fuente, el sitio web y los lanzamientos son públicos. Consulte las notas de cada versión para conocer la firma del instalador, la certificación notarial de Apple y el alcance de la validación. La instalación en máquina limpia, la compatibilidad con Mac físicos que ejecutan macOS 14, la autorización de cuentas reales de Claude y las solicitudes de modelos aún requieren una validación completa. | |
| 58 | 58 | |
| 59 | 59 | Las versiones con soporte de actualización en la aplicación muestran un control de actualización en la esquina inferior izquierda. Cuando hay una actualización disponible, la información sobre herramientas de la flecha hacia abajo dice "Descargar actualización". Al hacer clic en él, se descarga, verifica, instala y reinicia la aplicación. Guarde y detenga la ejecución de tareas primero. Las actualizaciones se descargan a través del proxy de red seleccionado, sin recurrir a una conexión directa. La instalación automática requiere una firma del mismo editor y verificación de Apple. Las versiones posteriores pueden utilizar actualizaciones dentro de la aplicación. Para más detalles, consulte [Actualizar y desinstalar](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ Claude Cage یک ماشین مجازی لینوکس سبک وزن است که ت | ||
| 54 | 54 | |
| 55 | 55 | نصب کننده شامل میز کار و هسته پروکسی شبکه است. استفاده روزانه نیازی به نصب Go، Node.js، Docker یا Clash ندارد. اولین راهاندازی همچنان به اتصال اینترنت برای دانلود تصویر لینوکس و ابزارهای توسعه نیاز دارد. Cage نه سرویس پروکسی شبکه و نه حساب Claude ارائه می دهد. |
| 56 | 56 | |
| 57 | 删除:نسخه فعلی: `0.1.0-alpha.1`. کد منبع، وبسایت و نسخهها عمومی هستند. به یادداشتهای هر نسخه برای امضای نصبکننده، تأیید اسناد رسمی اپل و دامنه اعتبارسنجی مراجعه کنید. نصب ماشین تمیز، سازگاری در مک های فیزیکی دارای سیستم عامل macOS 14، مجوز واقعی حساب Claude، و درخواست های مدل هنوز به تأیید کامل نیاز دارند. | |
| 57 | 新增:نسخه فعلی: `0.1.1-alpha`. کد منبع، وبسایت و نسخهها عمومی هستند. به یادداشتهای هر نسخه برای امضای نصبکننده، تأیید اسناد رسمی اپل و دامنه اعتبارسنجی مراجعه کنید. نصب ماشین تمیز، سازگاری در مک های فیزیکی دارای سیستم عامل macOS 14، مجوز واقعی حساب Claude، و درخواست های مدل هنوز به تأیید کامل نیاز دارند. | |
| 58 | 58 | |
| 59 | 59 | نسخههایی که از بهروزرسانی درونبرنامه پشتیبانی میکنند، کنترل بهروزرسانی را در گوشه پایین سمت چپ نشان میدهند. وقتی یک بهروزرسانی در دسترس است، راهنمای ابزار فلش رو به پایین «دانلود بهروزرسانی» را میخواند. با کلیک بر روی آن برنامه دانلود، تأیید، نصب و راه اندازی مجدد می شود. ابتدا وظایف در حال اجرا را ذخیره و متوقف کنید. بهروزرسانیها از طریق پراکسی شبکه انتخاب شده، بدون بازگشت به اتصال مستقیم، دانلود میشوند. نصب خودکار به امضای همان ناشر و تأیید اپل نیاز دارد. نسخه های بعدی می توانند از به روز رسانی های درون برنامه ای استفاده کنند. برای جزئیات، نگاه کنید [ارتقا و حذف نصب کنید](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ La version initiale prend en charge **Mac Apple Silicon (puces de la série M), | ||
| 54 | 54 | |
| 55 | 55 | Le programme d'installation comprend le workbench et le noyau du proxy réseau. Une utilisation quotidienne ne nécessite pas l'installation de Go, Node.js, Docker ou Clash. Le premier lancement nécessite toujours une connexion Internet pour télécharger l’image Linux et les outils de développement. Cage ne fournit ni service proxy réseau ni compte Claude. |
| 56 | 56 | |
| 57 | 删除:Version actuelle : `0.1.0-alpha.1`. Le code source, le site Web et les versions sont publics. Reportez-vous aux notes de chaque version pour la signature du programme d'installation, la notarisation Apple et la portée de la validation. L'installation sur une machine propre, la compatibilité sur les Mac physiques exécutant macOS 14, l'autorisation réelle du compte Claude et les demandes de modèle nécessitent toujours une validation complète. | |
| 57 | 新增:Version actuelle : `0.1.1-alpha`. Le code source, le site Web et les versions sont publics. Reportez-vous aux notes de chaque version pour la signature du programme d'installation, la notarisation Apple et la portée de la validation. L'installation sur une machine propre, la compatibilité sur les Mac physiques exécutant macOS 14, l'autorisation réelle du compte Claude et les demandes de modèle nécessitent toujours une validation complète. | |
| 58 | 58 | |
| 59 | 59 | Les versions avec prise en charge des mises à jour intégrées à l'application affichent un contrôle de mise à jour dans le coin inférieur gauche. Lorsqu'une mise à jour est disponible, l'info-bulle de la flèche vers le bas indique « Télécharger la mise à jour ». En cliquant dessus, vous téléchargez, vérifiez, installez et redémarrez l'application. Enregistrez et arrêtez d'abord les tâches en cours d'exécution. Les mises à jour sont téléchargées via le proxy réseau sélectionné, sans recours à une connexion directe. L'installation automatique nécessite une signature du même éditeur et une vérification Apple. Les versions ultérieures peuvent utiliser des mises à jour intégrées à l'application. Pour plus de détails, voir [Mettre à niveau et désinstaller](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ Claude Cage는 Linux 터미널, 브라우저 및 파일 편집기를 단일 데 | ||
| 54 | 54 | |
| 55 | 55 | 설치 프로그램에는 워크벤치와 네트워크 프록시 코어가 포함되어 있습니다. 일상적인 사용에는 Go, Node.js, Docker 또는 Clash를 설치할 필요가 없습니다. 처음 실행 시에는 Linux 이미지와 개발 도구를 다운로드하기 위해 인터넷 연결이 필요합니다. Cage는 네트워크 프록시 서비스나 Claude 계정을 제공하지 않습니다. |
| 56 | 56 | |
| 57 | 删除:현재 버전: `0.1.0-alpha.1`. 소스 코드, 웹사이트, 릴리스는 공개되어 있습니다. 설치 프로그램 서명, Apple 공증 및 검증 범위에 대해서는 각 릴리스의 노트를 참조하세요. 클린 머신 설치, macOS 14를 실행하는 실제 Mac에서의 호환성, 실제 Claude 계정 인증 및 모델 요청에는 여전히 완전한 검증이 필요합니다. | |
| 57 | 新增:현재 버전: `0.1.1-alpha`. 소스 코드, 웹사이트, 릴리스는 공개되어 있습니다. 설치 프로그램 서명, Apple 공증 및 검증 범위에 대해서는 각 릴리스의 노트를 참조하세요. 클린 머신 설치, macOS 14를 실행하는 실제 Mac에서의 호환성, 실제 Claude 계정 인증 및 모델 요청에는 여전히 완전한 검증이 필요합니다. | |
| 58 | 58 | |
| 59 | 59 | 인앱 업데이트를 지원하는 버전은 왼쪽 하단에 업데이트 컨트롤이 표시됩니다. 업데이트를 사용할 수 있으면 아래쪽 화살표 도구 설명에 '업데이트 다운로드'가 표시됩니다. 이를 클릭하면 애플리케이션이 다운로드, 확인, 설치 및 다시 시작됩니다. 먼저 실행 중인 작업을 저장하고 중지하세요. 업데이트는 직접 연결을 사용하지 않고 선택한 네트워크 프록시를 통해 다운로드됩니다. 자동 설치에는 동일한 게시자의 서명과 Apple 확인이 필요합니다. 후속 버전에서는 인앱 업데이트를 사용할 수 있습니다. 자세한 내용은 다음을 참조하세요. [업그레이드 및 제거](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -46,7 +46,7 @@ Claude Cage 是一个轻量 Linux 虚拟机,把 Linux 终端、浏览器和文 | ||
| 46 | 46 | |
| 47 | 47 | ## 下载与安装 |
| 48 | 48 | |
| 49 | 删除:首版面向 **Apple Silicon Mac(M 系列芯片),macOS 14 或更新版本**。Intel Mac、Windows 和 Linux 尚不作为 Cage 桌面版的受支持平台。 | |
| 49 | 新增:首版面向 **Apple Silicon Mac(M 系列芯片),macOS 14 或更新版本**。Windows 10 22H2 / Windows 11 x64 的桌面实现与安装器已加入源码,当前处于开发验收阶段,见 [Windows 安装与更新](docs/windows.md)。Linux x86_64 的原生工作台与 Debian/Ubuntu 安装包已加入源码,处于开发验收阶段,见 [Linux 安装与使用](docs/linux.md)。Intel Mac 与 Windows ARM64 尚不作为 Cage 桌面版的受支持平台。 | |
| 50 | 50 | |
| 51 | 51 | 1. 打开 [GitHub Releases](https://github.com/Lee-xeo/Claude-Cage/releases),选择发布条目中的 Apple Silicon `.dmg` 安装包。 |
| 52 | 52 | 2. 打开安装包,将 **Cage** 拖入 **Applications(应用程序)**,再从“应用程序”启动。 |
| @@ -54,7 +54,7 @@ Claude Cage 是一个轻量 Linux 虚拟机,把 Linux 终端、浏览器和文 | ||
| 54 | 54 | |
| 55 | 55 | 安装包随附工作台和代理核心,日常使用无需安装 Go、Node.js、Docker 或 Clash。首次启动仍需联网下载 Linux 镜像与开发工具;Cage 不提供代理服务或 Claude 账户。 |
| 56 | 56 | |
| 57 | 删除:当前版本为 `0.1.0-alpha.1`。源码、主页与发行物公开;安装包的签名、公证和验收范围以对应 Release 说明为准。干净机器安装、macOS 14 实机兼容性、真实 Claude 授权与模型请求仍需完整验收。 | |
| 57 | 新增:当前版本为 `0.1.1-alpha`。源码、主页与发行物公开;安装包的签名、公证和验收范围以对应 Release 说明为准。干净机器安装、macOS 14 实机兼容性、真实 Claude 授权与模型请求仍需完整验收。 | |
| 58 | 58 | |
| 59 | 59 | 支持应用内更新的版本会在左下角显示更新入口:有新版时,向下箭头的悬浮提示为“下载更新”,点击后下载、校验、安装并重启;有运行任务时先确认保存并停止。更新经所选代理下载,无直连回退。自动安装要求同一发布者签名且通过 Apple 验证;后续版本可通过应用内更新。具体条件见[升级与卸载](docs/getting-started.md#升级与卸载)。 |
| 60 | 60 | |
| @@ -70,11 +70,11 @@ Claude Cage 是一个轻量 Linux 虚拟机,把 Linux 终端、浏览器和文 | ||
| 70 | 70 | |
| 71 | 71 | ### 3. 打开项目,运行 Claude |
| 72 | 72 | |
| 73 | 删除:点击“打开项目”选择 Mac 上的文件夹,再新建终端,输入 `claude`,在 Cage 浏览器中完成自己的账户授权。也可以先使用默认工作区,无需提前准备项目。完整步骤见[开始使用](docs/getting-started.md)。 | |
| 73 | 新增:点击“打开项目”选择本机上的文件夹,再新建终端,输入 `claude`,在 Cage 浏览器中完成自己的账户授权。也可以先使用默认工作区,无需提前准备项目。完整步骤见[开始使用](docs/getting-started.md)。 | |
| 74 | 74 | |
| 75 | 75 | ## 使用前了解这些边界 |
| 76 | 76 | |
| 77 | 删除:- 共享项目中的修改和删除会直接影响 Mac 上的文件。请使用版本控制或备份;`.git` 等元数据默认只读,Git 提交在 Mac 上完成。 | |
| 77 | 新增:- 共享项目中的修改和删除会直接影响本机上的文件。请使用版本控制或备份;`.git` 等元数据默认只读,Git 提交在主机上完成。 | |
| 78 | 78 | - 所有项目共用一个 Cage 环境,也共用其中的工具、账户与 Linux 文件系统。项目之间没有独立隔离。 |
| 79 | 79 | - 当前允许客机通过代理访问公网 IPv4 TCP,DNS 通过同一代理发送;公网 UDP、IPv6、ICMP,以及客机主动访问主机和局域网的连接受到阻断。依赖这些能力的工具可能无法使用。 |
| 80 | 80 | - 网络检查展示当前配置和采样证据,无法保证账户不会受到平台限制,也不能代替完整的虚拟化安全审计。 |
| @@ -54,7 +54,7 @@ Claude Cage သည် desktop အပလီကေးရှင်းတစ်ခ | ||
| 54 | 54 | |
| 55 | 55 | ထည့်သွင်းသူတွင် workbench နှင့် network proxy core ပါဝင်သည်။ နေ့စဉ်အသုံးပြုမှုသည် Go၊ Node.js၊ Docker သို့မဟုတ် Clash ကို ထည့်သွင်းရန် မလိုအပ်ပါ။ Linux ရုပ်ပုံနှင့် ဖွံ့ဖြိုးတိုးတက်ရေးကိရိယာများကို ဒေါင်းလုဒ်လုပ်ရန် ပထမဦးစွာ လွှင့်တင်ရန် အင်တာနက်ချိတ်ဆက်မှု လိုအပ်နေသေးသည်။ Cage သည် ကွန်ရက် ပရောက်စီ ဝန်ဆောင်မှု သို့မဟုတ် Claude အကောင့်ကို မပေးပေ။ |
| 56 | 56 | |
| 57 | 删除:လက်ရှိဗားရှင်း- `0.1.0-alpha.1`. အရင်းအမြစ်ကုဒ်၊ ဝဘ်ဆိုက်နှင့် ထုတ်ဝေမှုများကို အများသူငှာဖြစ်သည်။ တပ်ဆင်သူလက်မှတ်ထိုးခြင်းအတွက် ထုတ်ဝေမှုတစ်ခုစီ၏ မှတ်စုများ၊ Apple notarization နှင့် တရားဝင်မှုအတိုင်းအတာကို ကိုးကားပါ။ စက်သန့်ရှင်းမှု တပ်ဆင်မှု၊ macOS 14 အသုံးပြုသည့် ရုပ်ပိုင်းဆိုင်ရာ Mac များတွင် လိုက်ဖက်ညီမှု၊ အစစ်အမှန် Claude အကောင့်ခွင့်ပြုချက်နှင့် မော်ဒယ်တောင်းဆိုမှုများသည် အပြည့်အဝ တရားဝင်မှု လိုအပ်နေသေးသည်။ | |
| 57 | 新增:လက်ရှိဗားရှင်း- `0.1.1-alpha`. အရင်းအမြစ်ကုဒ်၊ ဝဘ်ဆိုက်နှင့် ထုတ်ဝေမှုများကို အများသူငှာဖြစ်သည်။ တပ်ဆင်သူလက်မှတ်ထိုးခြင်းအတွက် ထုတ်ဝေမှုတစ်ခုစီ၏ မှတ်စုများ၊ Apple notarization နှင့် တရားဝင်မှုအတိုင်းအတာကို ကိုးကားပါ။ စက်သန့်ရှင်းမှု တပ်ဆင်မှု၊ macOS 14 အသုံးပြုသည့် ရုပ်ပိုင်းဆိုင်ရာ Mac များတွင် လိုက်ဖက်ညီမှု၊ အစစ်အမှန် Claude အကောင့်ခွင့်ပြုချက်နှင့် မော်ဒယ်တောင်းဆိုမှုများသည် အပြည့်အဝ တရားဝင်မှု လိုအပ်နေသေးသည်။ | |
| 58 | 58 | |
| 59 | 59 | အက်ပ်အတွင်း အပ်ဒိတ်ပံ့ပိုးမှုပါရှိသော ဗားရှင်းများသည် ဘယ်ဘက်အောက်ခြေထောင့်တွင် အပ်ဒိတ်ထိန်းချုပ်မှုကို ပြသသည်။ အပ်ဒိတ်တစ်ခုရလာသောအခါ၊ အောက်မြှားကိရိယာအကြံပြုချက်သည် 'ဒေါင်းလုဒ်အပ်ဒိတ်' ကိုဖတ်သည်။ ၎င်းကိုနှိပ်ခြင်းဖြင့် ဒေါင်းလုဒ်လုပ်ခြင်း၊ အတည်ပြုခြင်း၊ ထည့်သွင်းခြင်းနှင့် အက်ပ်လီကေးရှင်းကို ပြန်လည်စတင်ပါ။ အလုပ်များကို ဦးစွာသိမ်းပြီး ရပ်လိုက်ပါ။ တိုက်ရိုက်ချိတ်ဆက်မှုသို့ နောက်ပြန်မဆုတ်ဘဲ ရွေးချယ်ထားသော ကွန်ရက်ပရောက်စီမှတစ်ဆင့် ဒေါင်းလုဒ်လုပ်ခြင်းကို အပ်ဒိတ်လုပ်ပါ။ အလိုအလျောက်ထည့်သွင်းခြင်းတွင် တူညီသောထုတ်ဝေသူနှင့် Apple အတည်ပြုခြင်းမှ လက်မှတ်လိုအပ်သည်။ နောက်ဆက်တွဲဗားရှင်းများသည် အက်ပ်အတွင်း အပ်ဒိတ်များကို သုံးနိုင်သည်။ အသေးစိတ်ကို ကြည့်ပါ။ [အဆင့်မြှင့်ပြီး ဖြုတ်လိုက်ပါ။](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ Claude Cage یک ماشین مجازی لینوکس سبک وزن است که ت | ||
| 54 | 54 | |
| 55 | 55 | نصب کننده شامل میز کار و هسته پروکسی شبکه است. استفاده روزانه نیازی به نصب Go، Node.js، Docker یا Clash ندارد. اولین راهاندازی همچنان به اتصال اینترنت برای دانلود تصویر لینوکس و ابزارهای توسعه نیاز دارد. Cage نه سرویس پروکسی شبکه و نه حساب Claude ارائه می دهد. |
| 56 | 56 | |
| 57 | 删除:نسخه فعلی: `0.1.0-alpha.1`. کد منبع، وبسایت و نسخهها عمومی هستند. به یادداشتهای هر نسخه برای امضای نصبکننده، تأیید اسناد رسمی اپل و دامنه اعتبارسنجی مراجعه کنید. نصب ماشین تمیز، سازگاری در مک های فیزیکی دارای سیستم عامل macOS 14، مجوز واقعی حساب Claude، و درخواست های مدل هنوز به تأیید کامل نیاز دارند. | |
| 57 | 新增:نسخه فعلی: `0.1.1-alpha`. کد منبع، وبسایت و نسخهها عمومی هستند. به یادداشتهای هر نسخه برای امضای نصبکننده، تأیید اسناد رسمی اپل و دامنه اعتبارسنجی مراجعه کنید. نصب ماشین تمیز، سازگاری در مک های فیزیکی دارای سیستم عامل macOS 14، مجوز واقعی حساب Claude، و درخواست های مدل هنوز به تأیید کامل نیاز دارند. | |
| 58 | 58 | |
| 59 | 59 | نسخههایی که از بهروزرسانی درونبرنامه پشتیبانی میکنند، کنترل بهروزرسانی را در گوشه پایین سمت چپ نشان میدهند. وقتی یک بهروزرسانی در دسترس است، راهنمای ابزار فلش رو به پایین «دانلود بهروزرسانی» را میخواند. با کلیک بر روی آن برنامه دانلود، تأیید، نصب و راه اندازی مجدد می شود. ابتدا وظایف در حال اجرا را ذخیره و متوقف کنید. بهروزرسانیها از طریق پراکسی شبکه انتخاب شده، بدون بازگشت به اتصال مستقیم، دانلود میشوند. نصب خودکار به امضای همان ناشر و تأیید اپل نیاز دارد. نسخه های بعدی می توانند از به روز رسانی های درون برنامه ای استفاده کنند. برای جزئیات، نگاه کنید [ارتقا و حذف نصب کنید](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ | ||
| 54 | 54 | |
| 55 | 55 | انسټالر کې ورک بینچ او د شبکې پراکسي کور شامل دي. ورځنی استعمال د Go، Node.js، Docker، یا Clash نصبولو ته اړتیا نلري. لومړی لانچ لاهم د لینکس عکس او پراختیا وسیلو ډاونلوډ کولو لپاره انټرنیټ پیوستون ته اړتیا لري. Cage نه د شبکې پراکسي خدمت وړاندې کوي او نه د کلاډ حساب. |
| 56 | 56 | |
| 57 | 删除:اوسنۍ نسخه: `0.1.0-alpha.1`. د سرچینې کوډ، ویب پاڼه، او خپرونه عامه دي. د انسټالر لاسلیک کولو، د ایپل نوټاریزیشن، او د اعتبار ساحه لپاره د هرې خوشې کولو یادښتونو ته مراجعه وکړئ. د کلین ماشین نصب کول، د macOS 14 چلولو فزیکي ماکونو کې مطابقت، د ریښتیني کلاډ حساب واک، او د ماډل غوښتنې لاهم بشپړ تایید ته اړتیا لري. | |
| 57 | 新增:اوسنۍ نسخه: `0.1.1-alpha`. د سرچینې کوډ، ویب پاڼه، او خپرونه عامه دي. د انسټالر لاسلیک کولو، د ایپل نوټاریزیشن، او د اعتبار ساحه لپاره د هرې خوشې کولو یادښتونو ته مراجعه وکړئ. د کلین ماشین نصب کول، د macOS 14 چلولو فزیکي ماکونو کې مطابقت، د ریښتیني کلاډ حساب واک، او د ماډل غوښتنې لاهم بشپړ تایید ته اړتیا لري. | |
| 58 | 58 | |
| 59 | 59 | د ایپ اپډیټ ملاتړ سره نسخې په لاندې کیڼ کونج کې د تازه کنټرول ښیې. کله چې یو تازه معلومات شتون ولري، د ښکته تیر ټوپ ټایپ 'د ډاونلوډ تازه کول' لوستل کیږي. په دې کلیک کولو سره اپلیکیشن ډاونلوډ، تایید، نصب او بیا پیل کوي. لومړی د چلولو دندې خوندي کړئ او ودروئ. تازه معلومات د ټاکل شوي شبکې پراکسي له لارې ډاونلوډ کیږي ، پرته له مستقیم اړیکې سره. اتوماتیک نصب د ورته خپرونکي لاسلیک او د ایپل تصدیق ته اړتیا لري. ورپسې نسخې کولی شي په اپلیکیشن کې تازه معلومات وکاروي. د جزیاتو لپاره، وګورئ [اپ گریڈ او غیر نصب کړئ](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ Claude Cage — это легкая виртуальная машина Linux, | ||
| 54 | 54 | |
| 55 | 55 | Установщик включает в себя рабочую среду и ядро сетевого прокси. Ежедневное использование не требует установки Go, Node.js, Docker или Clash. При первом запуске по-прежнему требуется подключение к Интернету для загрузки образа Linux и инструментов разработки. Cage не предоставляет ни услуги сетевого прокси, ни учетную запись Claude. |
| 56 | 56 | |
| 57 | 删除:Текущая версия: `0.1.0-alpha.1`. Исходный код, веб-сайт и релизы являются общедоступными. Подробную информацию о подписании установщика, нотариальном заверении Apple и объеме проверки см. в примечаниях к каждому выпуску. Установка на чистом компьютере, совместимость с физическими компьютерами Mac под управлением macOS 14, авторизация реальной учетной записи Claude и запросы моделей по-прежнему требуют полной проверки. | |
| 57 | 新增:Текущая версия: `0.1.1-alpha`. Исходный код, веб-сайт и релизы являются общедоступными. Подробную информацию о подписании установщика, нотариальном заверении Apple и объеме проверки см. в примечаниях к каждому выпуску. Установка на чистом компьютере, совместимость с физическими компьютерами Mac под управлением macOS 14, авторизация реальной учетной записи Claude и запросы моделей по-прежнему требуют полной проверки. | |
| 58 | 58 | |
| 59 | 59 | В версиях с поддержкой обновления внутри приложения в левом нижнем углу отображается элемент управления обновлением. Когда обновление доступно, всплывающая подсказка со стрелкой вниз гласит: «Загрузить обновление». Нажатие на нее загружает, проверяет, устанавливает и перезапускает приложение. Сначала сохраните и остановите выполнение задач. Обновления загружаются через выбранный сетевой прокси-сервер без возврата к прямому соединению. Для автоматической установки требуется подпись того же издателя и проверка Apple. Последующие версии могут использовать обновления внутри приложения. Подробности см. [Обновить и удалить](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ Siideynta hore waa ay taageertaa **Apple Silicon Macs (M-series chips), oo ku sh | ||
| 54 | 54 | |
| 55 | 55 | Rakibahu waxa ka mid ah bench-ka shaqada iyo xudunta wakiilka network. Isticmaalka maalinlaha ah uma baahna rakibida Go, Node.js, Docker, ama Clash. Daahfurka ugu horreeya wuxuu weli u baahan yahay isku xirka internetka si loo soo dejiyo sawirka Linux iyo aaladaha horumarinta. Cage ma bixiso adeeg wakiil shabakad ama akoon Claude. |
| 56 | 56 | |
| 57 | 删除:Nooca hadda: `0.1.0-alpha.1`. Koodhka isha, mareegaha, iyo sii daynta waa dadwayne. Tixraac qoraalada sii daynta kasta ee saxeexa rakibaha, notarization Apple, iyo baaxadda ansixinta. Ku rakibida mashiinka nadiifka ah, waafaqid ku saabsan Macs-ka jireed ee ku shaqeeya macOS 14, oggolaanshaha koontada Claude dhabta ah, iyo codsiyada moodeelka ayaa wali u baahan ansaxinta buuxda. | |
| 57 | 新增:Nooca hadda: `0.1.1-alpha`. Koodhka isha, mareegaha, iyo sii daynta waa dadwayne. Tixraac qoraalada sii daynta kasta ee saxeexa rakibaha, notarization Apple, iyo baaxadda ansixinta. Ku rakibida mashiinka nadiifka ah, waafaqid ku saabsan Macs-ka jireed ee ku shaqeeya macOS 14, oggolaanshaha koontada Claude dhabta ah, iyo codsiyada moodeelka ayaa wali u baahan ansaxinta buuxda. | |
| 58 | 58 | |
| 59 | 59 | Noocyada leh taageerada cusboonaysiinta app-ku waxay muujinayaan xakamaynta cusboonaysiinta ee geeska bidix ee hoose. Marka cusboonaysiinta la heli karo, aaladda fallaadha hoose waxay akhridaa 'Download update'. Markaad gujiso waxay soo dejisaa, xaqiijisaa, rakibtaa, oo dib u bilawdaa arjiga. Keydi oo jooji socodsiinta hawlaha marka hore. Cusboonaysiinta soo dejinta iyada oo loo marayo wakiilka shabakadda ee la xushay, iyada oo aan dib loogu laaban xiriir toos ah. Rakibaadda tooska ah waxay u baahan tahay saxeex isla daabacaha iyo xaqiijinta Apple. Noocyada soo socda waxay isticmaali karaan cusbooneysiinta app-ka. Faahfaahinta, eeg [Kor u qaad oo ka saar](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ | ||
| 54 | 54 | |
| 55 | 55 | እቲ መተካእታ ንወርክቤንችን ኔትወርክ ፕሮክሲ ኮርን የጠቓልል። መዓልታዊ ኣጠቓቕማ Go, Node.js, Docker, ወይ Clash ምትካል ኣየድልዮን እዩ። መጀመርታ ምጅማር ሕጂ ውን ናይ ሊኑክስ ምስልን መሳርሒታት ምዕባለን ንምውራድ ናይ ኢንተርነት ምትእስሳር የድሊ። Cage ናይ መርበብ ፕሮክሲ ኣገልግሎት ይኹን ናይ Claude ኣካውንት ኣይህብን እዩ። |
| 56 | 56 | |
| 57 | 删除:ናይ ሕጂ ስሪት፤ `0.1.0-alpha.1`. እቲ ምንጪ ኮድ፡ መርበብ ሓበሬታን ምውጻእን ንህዝቢ ዝቐርብ እዩ። ንመተካእታ ምፍራም፣ ኣፕል ኖታራይዜሽንን ስፍሓት ምጽዳቕን ዝምልከት ናይ ነፍሲ ወከፍ ምውጻእ መዘኻኸሪታት ተወከስ። ጽሩይ-ማሽን ምትካል፡ ኣብ macOS 14 ዝሰርሓ ፊዚካዊ ማክስ ምትእስሳር፡ ሓቀኛ ክላውድ ኣካውንት ፍቓድ፡ ከምኡ’ውን ናይ ሞዴል ሕቶታት ሕጂ’ውን ምሉእ ምጽዳቕ የድልዮም። | |
| 57 | 新增:ናይ ሕጂ ስሪት፤ `0.1.1-alpha`. እቲ ምንጪ ኮድ፡ መርበብ ሓበሬታን ምውጻእን ንህዝቢ ዝቐርብ እዩ። ንመተካእታ ምፍራም፣ ኣፕል ኖታራይዜሽንን ስፍሓት ምጽዳቕን ዝምልከት ናይ ነፍሲ ወከፍ ምውጻእ መዘኻኸሪታት ተወከስ። ጽሩይ-ማሽን ምትካል፡ ኣብ macOS 14 ዝሰርሓ ፊዚካዊ ማክስ ምትእስሳር፡ ሓቀኛ ክላውድ ኣካውንት ፍቓድ፡ ከምኡ’ውን ናይ ሞዴል ሕቶታት ሕጂ’ውን ምሉእ ምጽዳቕ የድልዮም። | |
| 58 | 58 | |
| 59 | 59 | ኣብ ውሽጢ መተግበሪ ናይ ምዕባለ ደገፍ ዘለዎም ስሪት ኣብ ታሕተዋይ ጸጋማይ ኩርናዕ ናይ ምዕባለ ምቁጽጻር የርእዩ። ሓደ ምዕባለ ምስ ዝህሉ፡ እቲ ኣብ ታሕቲ ዘሎ ፍላጻ ዝሕብር መሳርሒ ‘Download update’ ዝብል ይንበብ። ንዕኡ ጠዊቕካ ነቲ መተግበሪ የውርድ፣ የረጋግጽ፣ ይተክልን ዳግማይ ይጅምሮን። መጀመርታ ስራሕካ ዓቅብ፣ ድሕሪኡ ዝሰርሑ ዕማማት ኣቋርጽ። እዋናዊ ሓበሬታታት ብመንገዲ እቲ ዝተመርጸ መርበብ ፕሮክሲ ይወርድ፣ ናብ ቀጥታዊ ምትእስሳር ዝኾነ ምምላስ የብሉን። ኣውቶማቲክ ምትካል ካብ ተመሳሳሊ ኣሕታሚ ፌርማን ምርግጋጽ ኣፕልን የድሊ። ስዒቦም ዝመጹ ስሪታት ኣብ ውሽጢ ኣፕ ዝግበር ምዕባለታት ክጥቀሙ ይኽእሉ። ንዝርዝር ሓበሬታ ርአ [ምዕባይን ምእላይን።](docs/getting-started.md#升级与卸载). |
| 60 | 60 | |
| @@ -54,7 +54,7 @@ Claude Cage 是一個輕量 Linux 虛擬機器,把 Linux 終端、瀏覽器和 | ||
| 54 | 54 | |
| 55 | 55 | 安裝包隨附工作臺和代理核心,日常使用無需安裝 Go、Node.js、Docker 或 Clash。首次啟動仍需聯網下載 Linux 映象與開發工具;Cage 不提供代理服務或 Claude 賬戶。 |
| 56 | 56 | |
| 57 | 删除:當前版本為 `0.1.0-alpha.1`。原始碼、主頁與發行物公開;安裝包的簽名、公證和驗收範圍以對應 Release 說明為準。乾淨機器安裝、macOS 14 實機相容性、真實 Claude 授權與模型請求仍需完整驗收。 | |
| 57 | 新增:當前版本為 `0.1.1-alpha`。原始碼、主頁與發行物公開;安裝包的簽名、公證和驗收範圍以對應 Release 說明為準。乾淨機器安裝、macOS 14 實機相容性、真實 Claude 授權與模型請求仍需完整驗收。 | |
| 58 | 58 | |
| 59 | 59 | 支援應用內更新的版本會在左下角顯示更新入口:有新版時,向下箭頭的懸浮提示為“下載更新”,點選後下載、校驗、安裝並重啟;有執行任務時先確認儲存並停止。更新經所選代理下載,無直連回退。自動安裝要求同一發布者簽名且透過 Apple 驗證;後續版本可透過應用內更新。具體條件見[升級與解除安裝](docs/getting-started.md#升级与卸载)。 |
| 60 | 60 | |
| @@ -4924,27 +4924,6 @@ github.com/lima-vm/sshocker ./third_party/sshocker: LICENSE | ||
| 4924 | 4924 | See the License for the specific language governing permissions and |
| 4925 | 4925 | limitations under the License. |
| 4926 | 4926 | |
| 4927 | 删除:================================================================================ | |
| 4928 | 删除:github.com/linuxkit/virtsock v0.0.0-20220523201153-1a23e78aa7a2: LICENSE | |
| 4929 | 删除:================================================================================ | |
| 4930 | 删除: | |
| 4931 | 删除:Unless explicitly stated at the top of the file, this code is covered | |
| 4932 | 删除:by the following license: | |
| 4933 | 删除: | |
| 4934 | 删除:Copyright 2016-2017 The authors | |
| 4935 | 删除: | |
| 4936 | 删除:Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4937 | 删除:you may not use this file except in compliance with the License. | |
| 4938 | 删除:You may obtain a copy of the License at | |
| 4939 | 删除: | |
| 4940 | 删除: http://www.apache.org/licenses/LICENSE-2.0 | |
| 4941 | 删除: | |
| 4942 | 删除:Unless required by applicable law or agreed to in writing, software | |
| 4943 | 删除:distributed under the License is distributed on an "AS IS" BASIS, | |
| 4944 | 删除:WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 4945 | 删除:See the License for the specific language governing permissions and | |
| 4946 | 删除:limitations under the License. | |
| 4947 | 删除: | |
| 4948 | 4927 | ================================================================================ |
| 4949 | 4928 | github.com/mattn/go-colorable v0.1.15: LICENSE |
| 4950 | 4929 | ================================================================================ |
| @@ -1 +1 @@ | ||
| 1 | 删除:0.1.0-alpha.1 | |
| 1 | 新增:0.1.1-alpha | |
| @@ -15,6 +15,7 @@ import ( | ||
| 15 | 15 | "github.com/sylvinus/agent-vm/internal/appupdate" |
| 16 | 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | 17 | "github.com/sylvinus/agent-vm/internal/cli" |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 18 | 19 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| 19 | 20 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 20 | 21 | "github.com/sylvinus/agent-vm/internal/workbench" |
| @@ -26,7 +27,7 @@ cage desktop Open the unified Cage workbench (desktop launcher) | ||
| 26 | 27 | cage serve Run its private localhost control service |
| 27 | 28 | cage init Create a private profile; add and select nodes in Cage settings |
| 28 | 29 | cage check Verify proxy transport (no VM required) |
| 29 | 删除:cage proxy-start Start Cage's bundled proxy core with the applied node (macOS) | |
| 30 | 新增:cage proxy-start Start Cage's bundled proxy core with the applied node | |
| 30 | 31 | cage proxy-stop Stop Cage's core and close external networking |
| 31 | 32 | cage setup Build the isolated base VM through the specified proxy |
| 32 | 33 | cage up Start the shared Cage environment, editor and browser |
| @@ -61,6 +62,9 @@ func run() int { | ||
| 61 | 62 | fmt.Print(help) |
| 62 | 63 | return 0 |
| 63 | 64 | } |
| 65 | 新增: if err := host.ConfigureWindowsRuntime(); err != nil { | |
| 66 | 新增: return fail(err) | |
| 67 | 新增: } | |
| 64 | 68 | path := os.Getenv(cage.ConfigEnv) |
| 65 | 69 | if path == "" { |
| 66 | 70 | home, _ := os.UserHomeDir() |
| @@ -73,6 +77,22 @@ func run() int { | ||
| 73 | 77 | if args[0] == "app-update" { |
| 74 | 78 | return appupdate.Run(path, args[1:], os.Stdout) |
| 75 | 79 | } |
| 80 | 新增: if args[0] == "browser-file" { | |
| 81 | 新增: if len(args) < 4 || len(args) > 5 || args[1] != "--json" { | |
| 82 | 新增: return fail(fmt.Errorf("browser-file --json save|open|reveal ID [destination]")) | |
| 83 | 新增: } | |
| 84 | 新增: destination := "" | |
| 85 | 新增: if len(args) == 5 { | |
| 86 | 新增: destination = args[4] | |
| 87 | 新增: } | |
| 88 | 新增: result, err := workbench.BrowserFile(path, args[2], args[3], destination) | |
| 89 | 新增: if err != nil { | |
| 90 | 新增: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) | |
| 91 | 新增: return 1 | |
| 92 | 新增: } | |
| 93 | 新增: _ = json.NewEncoder(os.Stdout).Encode(result) | |
| 94 | 新增: return 0 | |
| 95 | 新增: } | |
| 76 | 96 | if args[0] == "serve" { |
| 77 | 97 | if err := workbench.Serve(path); err != nil { |
| 78 | 98 | return fail(err) |
| @@ -144,7 +164,7 @@ func run() int { | ||
| 144 | 164 | return 0 |
| 145 | 165 | } |
| 146 | 166 | if args[0] == "init" { |
| 147 | 删除: if err = os.MkdirAll(filepath.Dir(path), 0700); err != nil { | |
| 167 | 新增: if err = host.EnsurePrivateDir(filepath.Dir(path)); err != nil { | |
| 148 | 168 | return fail(err) |
| 149 | 169 | } |
| 150 | 170 | f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) |
| @@ -246,16 +266,28 @@ func run() int { | ||
| 246 | 266 | args = append([]string{"setup", "--memory", "4", "--cpus", "2", "--disk", "24", "--preinstall=node,python,chromium,claude,code-server"}, args[1:]...) |
| 247 | 267 | } |
| 248 | 268 | if args[0] == "up" || args[0] == "login" { |
| 249 | 删除: result := cli.Main([]string{"run", "bash", "-c", cfg.StartScript()}, cli.Stdio()) | |
| 269 | 新增: result := cli.Main([]string{"run", "true"}, cli.Stdio()) | |
| 250 | 270 | if result != 0 { |
| 251 | 271 | return result |
| 252 | 272 | } |
| 253 | 删除: fmt.Println("Cage local services are ready. Open Cage.app or run cage desktop to complete the required network checks. External networking stays closed until the workbench approves this VM; no local access password is required.") | |
| 273 | 新增: if err := workbench.RunMaintenanceScript(context.Background(), path, cfg.StartScript(), os.Stdout, os.Stderr); err != nil { | |
| 274 | 新增: return fail(err) | |
| 275 | 新增: } | |
| 276 | 新增: fmt.Println("Cage local services are ready. Open Cage or run cage desktop to complete the required network checks. External networking stays closed until the workbench approves this VM; no local access password is required.") | |
| 254 | 277 | if args[0] == "login" { |
| 255 | 278 | return cli.Main([]string{"run", "--tty", "bash", "-lc", "source /etc/profile.d/claude-cage.sh; exec claude auth login"}, cli.Stdio()) |
| 256 | 279 | } |
| 257 | 280 | return 0 |
| 258 | 281 | } |
| 282 | 新增: if args[0] == "update-tools" { | |
| 283 | 新增: if result := cli.Main([]string{"run", "true"}, cli.Stdio()); result != 0 { | |
| 284 | 新增: return result | |
| 285 | 新增: } | |
| 286 | 新增: if err := workbench.RunMaintenanceScript(context.Background(), path, cage.ToolsUpdateScript(), os.Stdout, os.Stderr); err != nil { | |
| 287 | 新增: return fail(err) | |
| 288 | 新增: } | |
| 289 | 新增: return 0 | |
| 290 | 新增: } | |
| 259 | 291 | if args[0] == "access" { |
| 260 | 292 | args = []string{"run", "bash", "-c", `printf 'Editor password: '; sed -n 's/^password: //p' "$HOME/.config/claude-cage/code-server.yaml"; printf 'Browser password: '; cat "$HOME/.config/claude-cage/browser-password"; printf '\n'`} |
| 261 | 293 | } |
| @@ -265,9 +297,20 @@ func run() int { | ||
| 265 | 297 | } |
| 266 | 298 | return cli.Main(args, cli.Stdio()) |
| 267 | 299 | } |
| 300 | 新增: | |
| 301 | 新增:// Service assets exceed Windows' command-line limit. Give only this internal | |
| 302 | 新增:// invocation a script stream; interactive login and ordinary run keep stdin. | |
| 303 | 新增:func runGuestServiceStart(script string, stdio cli.IO, invoke func([]string, cli.IO) int) int { | |
| 304 | 新增: stdio.Stdin = strings.NewReader(script) | |
| 305 | 新增: return invoke([]string{"run", "bash", "-s"}, stdio) | |
| 306 | 新增:} | |
| 307 | 新增: | |
| 268 | 308 | func fail(err error) int { fmt.Fprintln(os.Stderr, strings.TrimSpace(err.Error())); return 1 } |
| 269 | 309 | |
| 270 | 310 | func openWorkbench(address string) error { |
| 311 | 新增: if runtime.GOOS == "windows" { | |
| 312 | 新增: return exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", address).Start() | |
| 313 | 新增: } | |
| 271 | 314 | command := "xdg-open" |
| 272 | 315 | if runtime.GOOS == "darwin" { |
| 273 | 316 | command = "open" |
| @@ -1,8 +1,20 @@ | ||
| 1 | 1 | package main |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 新增: "bytes" | |
| 5 | 新增: "crypto/sha256" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "io" | |
| 4 | 9 | "os" |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "slices" | |
| 12 | 新增: "strings" | |
| 5 | 13 | "testing" |
| 14 | 新增: "unicode/utf16" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/cli" | |
| 6 | 18 | ) |
| 7 | 19 | |
| 8 | 20 | func TestEntryDropsInheritedUnsafeSwitchesBeforeDispatch(t *testing.T) { |
| @@ -32,3 +44,52 @@ func TestEntryDropsInheritedUnsafeSwitchesBeforeDispatch(t *testing.T) { | ||
| 32 | 44 | t.Errorf("profile selection changed: %q", got) |
| 33 | 45 | } |
| 34 | 46 | } |
| 47 | 新增: | |
| 48 | 新增:func TestGuestServiceStartStreamsScriptAndPreservesInteractiveInput(t *testing.T) { | |
| 49 | 新增: script := cage.DefaultConfig().StartScript() | |
| 50 | 新增: t.Logf("service payload: %d bytes, %d UTF-16 code units", len(script), len(utf16.Encode([]rune(script)))) | |
| 51 | 新增: if len(utf16.Encode([]rune(script))) <= 32767 { | |
| 52 | 新增: t.Fatal("fixture no longer exercises the Windows command-line limit") | |
| 53 | 新增: } | |
| 54 | 新增: input := strings.NewReader("interactive input must remain available") | |
| 55 | 新增: var output, stderr bytes.Buffer | |
| 56 | 新增: stdio := cli.IO{Stdin: input, Stdout: &output, Stderr: &stderr} | |
| 57 | 新增: code := runGuestServiceStart(script, stdio, func(args []string, streams cli.IO) int { | |
| 58 | 新增: if !slices.Equal(args, []string{"run", "bash", "-s"}) { | |
| 59 | 新增: t.Fatalf("unexpected service command: %q", args) | |
| 60 | 新增: } | |
| 61 | 新增: // Use a real child process to verify transport on Windows without | |
| 62 | 新增: // executing guest provisioning against the host filesystem. | |
| 63 | 新增: cmd := exec.Command(os.Args[0], append([]string{"-test.run=^TestGuestServiceScriptCaptureProcess$", "--"}, args...)...) | |
| 64 | 新增: cmd.Env = append(os.Environ(), "CAGE_TEST_SCRIPT_CAPTURE=1") | |
| 65 | 新增: cmd.Stdin, cmd.Stdout, cmd.Stderr = streams.Stdin, streams.Stdout, streams.Stderr | |
| 66 | 新增: err := cmd.Run() | |
| 67 | 新增: var exit *exec.ExitError | |
| 68 | 新增: if errors.As(err, &exit) { | |
| 69 | 新增: return exit.ExitCode() | |
| 70 | 新增: } | |
| 71 | 新增: if err != nil { | |
| 72 | 新增: t.Fatal(err) | |
| 73 | 新增: } | |
| 74 | 新增: return 0 | |
| 75 | 新增: }) | |
| 76 | 新增: if code != 17 || output.String() != fmt.Sprintf("%x", sha256.Sum256([]byte(script))) { | |
| 77 | 新增: t.Fatalf("script transport or exit status changed: code=%d stdout=%q stderr=%q", code, output.String(), stderr.String()) | |
| 78 | 新增: } | |
| 79 | 新增: remaining, err := io.ReadAll(stdio.Stdin) | |
| 80 | 新增: if err != nil || string(remaining) != "interactive input must remain available" { | |
| 81 | 新增: t.Fatalf("internal service startup consumed interactive stdin: %q, %v", remaining, err) | |
| 82 | 新增: } | |
| 83 | 新增:} | |
| 84 | 新增: | |
| 85 | 新增:func TestGuestServiceScriptCaptureProcess(t *testing.T) { | |
| 86 | 新增: if os.Getenv("CAGE_TEST_SCRIPT_CAPTURE") != "1" { | |
| 87 | 新增: t.Skip("helper process for script transport") | |
| 88 | 新增: } | |
| 89 | 新增: data, err := io.ReadAll(os.Stdin) | |
| 90 | 新增: if err != nil { | |
| 91 | 新增: os.Exit(18) | |
| 92 | 新增: } | |
| 93 | 新增: fmt.Printf("%x", sha256.Sum256(data)) | |
| 94 | 新增: os.Exit(17) | |
| 95 | 新增:} | |
| @@ -0,0 +1,30 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "testing" | |
| 7 | 新增: | |
| 8 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestWindowsEntryDropsOpenSSHAncestorDescriptors(t *testing.T) { | |
| 12 | 新增: names := []string{"OPENSSH_STDIO_MODE", "c28fc6f98a2c44abbbd89d6a3037d0d9_POSIX_FD_STATE"} | |
| 13 | 新增: for _, name := range names { | |
| 14 | 新增: t.Setenv(name, "ancestor-state") | |
| 15 | 新增: } | |
| 16 | 新增: // A missing isolated config reaches runtime initialization, then returns | |
| 17 | 新增: // before any proxy connection, VM work or access to the user's profile. | |
| 18 | 新增: t.Setenv(cage.ConfigEnv, filepath.Join(t.TempDir(), "missing.json")) | |
| 19 | 新增: previous := os.Args | |
| 20 | 新增: os.Args = []string{"cage", "check"} | |
| 21 | 新增: t.Cleanup(func() { os.Args = previous }) | |
| 22 | 新增: if code := run(); code != 1 { | |
| 23 | 新增: t.Fatalf("missing configuration returned %d", code) | |
| 24 | 新增: } | |
| 25 | 新增: for _, name := range names { | |
| 26 | 新增: if _, exists := os.LookupEnv(name); exists { | |
| 27 | 新增: t.Errorf("%s survived Windows runtime initialization", name) | |
| 28 | 新增: } | |
| 29 | 新增: } | |
| 30 | 新增:} | |
| @@ -0,0 +1,126 @@ | ||
| 1 | 新增:import Foundation | |
| 2 | 新增:import Security | |
| 3 | 新增:import LocalAuthentication | |
| 4 | 新增: | |
| 5 | 新增:struct CageAccountError: LocalizedError { | |
| 6 | 新增: let message: String | |
| 7 | 新增: var errorDescription: String? { message } | |
| 8 | 新增: init(_ message: String) { self.message = message } | |
| 9 | 新增:} | |
| 10 | 新增: | |
| 11 | 新增:// Secrets stay between the native launcher, macOS Keychain and the loopback | |
| 12 | 新增:// controller. The web view receives status only, never the device credential. | |
| 13 | 新增:final class CageAccountDevice: NSObject, URLSessionTaskDelegate, @unchecked Sendable { | |
| 14 | 新增: private lazy var session: URLSession = { | |
| 15 | 新增: let config = URLSessionConfiguration.ephemeral | |
| 16 | 新增: config.connectionProxyDictionary = [:] | |
| 17 | 新增: config.timeoutIntervalForRequest = 15 | |
| 18 | 新增: return URLSession(configuration: config, delegate: self, delegateQueue: nil) | |
| 19 | 新增: }() | |
| 20 | 新增: private let base: URL | |
| 21 | 新增: private let ticket: String | |
| 22 | 新增: private static let service = "io.github.lee-xeo.claude-cage.account" | |
| 23 | 新增: | |
| 24 | 新增: init(entry: URL) throws { | |
| 25 | 新增: guard entry.scheme == "http", entry.host == "localhost", let ticket = entry.fragment, !ticket.isEmpty else { throw CageAccountError("本地账户连接无效") } | |
| 26 | 新增: var parts = URLComponents(url: entry, resolvingAgainstBaseURL: false)! | |
| 27 | 新增: parts.fragment = nil; parts.path = ""; parts.query = nil | |
| 28 | 新增: base = parts.url!; self.ticket = ticket | |
| 29 | 新增: super.init() | |
| 30 | 新增: } | |
| 31 | 新增: deinit { session.invalidateAndCancel() } | |
| 32 | 新增: func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } | |
| 33 | 新增: private func call(_ path: String, _ body: [String: Any]? = nil) async throws -> [String: Any] { | |
| 34 | 新增: var request = URLRequest(url: base.appendingPathComponent("api/account" + path)) | |
| 35 | 新增: if path == "@session" { request.url = base.appendingPathComponent("api/session") } | |
| 36 | 新增: request.httpMethod = body == nil ? "GET" : "POST" | |
| 37 | 新增: request.setValue(base.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")), forHTTPHeaderField: "Origin") | |
| 38 | 新增: if let body { request.setValue("application/json", forHTTPHeaderField: "Content-Type"); request.httpBody = try JSONSerialization.data(withJSONObject: body) } | |
| 39 | 新增: let (data, response) = try await session.data(for: request) | |
| 40 | 新增: guard let response = response as? HTTPURLResponse, response.statusCode == 200 else { | |
| 41 | 新增: throw CageAccountError(String(data: data.prefix(512), encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "账户操作未完成") | |
| 42 | 新增: } | |
| 43 | 新增: guard let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw CageAccountError("本地账户响应无效") } | |
| 44 | 新增: return value | |
| 45 | 新增: } | |
| 46 | 新增: private static func query(binding: String, kind: String) -> [String: Any] { | |
| 47 | 新增: var result: [String: Any] = [kSecClass as String: kSecClassGenericPassword, | |
| 48 | 新增: kSecAttrService as String: service, | |
| 49 | 新增: kSecAttrAccount as String: binding + "." + kind] | |
| 50 | 新增: if kind == "biometric" { | |
| 51 | 新增: result[kSecUseDataProtectionKeychain as String] = true | |
| 52 | 新增: result[kSecAttrSynchronizable as String] = false | |
| 53 | 新增: } | |
| 54 | 新增: return result | |
| 55 | 新增: } | |
| 56 | 新增: private static func remove(binding: String, kind: String) throws { | |
| 57 | 新增: let status = SecItemDelete(query(binding: binding, kind: kind) as CFDictionary) | |
| 58 | 新增: guard status == errSecSuccess || status == errSecItemNotFound else { throw CageAccountError("无法移除本机钥匙串记录,请重试") } | |
| 59 | 新增: } | |
| 60 | 新增: private static func store(_ credential: [String: Any], binding: String, kind: String) throws { | |
| 61 | 新增: var item = query(binding: binding, kind: kind) | |
| 62 | 新增: item[kSecValueData as String] = try JSONSerialization.data(withJSONObject: credential) | |
| 63 | 新增: item[kSecAttrLabel as String] = kind == "biometric" ? "Cage 指纹解锁" : "Cage 记住登录" | |
| 64 | 新增: if kind == "biometric" { | |
| 65 | 新增: var error: Unmanaged<CFError>? | |
| 66 | 新增: guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .biometryCurrentSet, &error) else { throw CageAccountError("这台 Mac 无法创建指纹保护的凭据") } | |
| 67 | 新增: item[kSecAttrAccessControl as String] = access | |
| 68 | 新增: } | |
| 69 | 新增: try remove(binding: binding, kind: kind) | |
| 70 | 新增: let status = SecItemAdd(item as CFDictionary, nil) | |
| 71 | 新增: guard status == errSecSuccess else { throw CageAccountError("macOS 未能保存快捷登录凭据(\(status)),密码登录仍然可用") } | |
| 72 | 新增: } | |
| 73 | 新增: private static func read(binding: String, kind: String) throws -> [String: Any] { | |
| 74 | 新增: var item = query(binding: binding, kind: kind) | |
| 75 | 新增: item[kSecReturnData as String] = true; item[kSecMatchLimit as String] = kSecMatchLimitOne | |
| 76 | 新增: let context = LAContext() | |
| 77 | 新增: context.localizedReason = "解锁你的 Cage 工作空间" | |
| 78 | 新增: context.localizedFallbackTitle = "" | |
| 79 | 新增: if kind == "automatic" { | |
| 80 | 新增: // The login Keychain is local to this Mac and its ACL trusts the | |
| 81 | 新增: // signed app. Automatic reopen must never trigger an OS prompt. | |
| 82 | 新增: context.interactionNotAllowed = true | |
| 83 | 新增: } | |
| 84 | 新增: item[kSecUseAuthenticationContext as String] = context | |
| 85 | 新增: var result: CFTypeRef? | |
| 86 | 新增: let status = SecItemCopyMatching(item as CFDictionary, &result) | |
| 87 | 新增: if status == errSecUserCanceled { throw CageAccountError("已取消指纹验证,可继续使用密码") } | |
| 88 | 新增: guard status == errSecSuccess, let data = result as? Data, | |
| 89 | 新增: let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw CageAccountError("快捷登录不可用,请使用密码解锁后重新开启") } | |
| 90 | 新增: return value | |
| 91 | 新增: } | |
| 92 | 新增: func handle(operation: String, kind: String?) async throws -> [String: Any] { | |
| 93 | 新增: defer { session.invalidateAndCancel() } | |
| 94 | 新增: _ = try await call("@session", ["token": ticket]) | |
| 95 | 新增: let account = try await call("") | |
| 96 | 新增: guard let binding = account["device_binding"] as? String, binding.count == 64 else { throw CageAccountError("当前后台不支持快捷登录,请先完成更新") } | |
| 97 | 新增: let context = LAContext() | |
| 98 | 新增: let biometricAvailable = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) | |
| 99 | 新增: if operation == "status" { | |
| 100 | 新增: return ["supported": true, "biometric_available": biometricAvailable] | |
| 101 | 新增: } | |
| 102 | 新增: guard let kind, ["automatic", "biometric"].contains(kind) else { throw CageAccountError("快捷登录类型无效") } | |
| 103 | 新增: switch operation { | |
| 104 | 新增: case "enable": | |
| 105 | 新增: if kind == "biometric" && !biometricAvailable { throw CageAccountError("请先在 macOS 系统设置中设置 Touch ID") } | |
| 106 | 新增: let credential = try await call("/device-enroll", ["kind": kind]) | |
| 107 | 新增: do { try Self.store(credential, binding: binding, kind: kind) } | |
| 108 | 新增: catch { | |
| 109 | 新增: _ = try? await call("/device-revoke", ["kind": kind]) | |
| 110 | 新增: throw error | |
| 111 | 新增: } | |
| 112 | 新增: case "disable": | |
| 113 | 新增: _ = try await call("/device-revoke", ["kind": kind]) | |
| 114 | 新增: try Self.remove(binding: binding, kind: kind) | |
| 115 | 新增: case "unlock": | |
| 116 | 新增: // Check persisted manual-lock state before touching the Keychain. | |
| 117 | 新增: if kind == "automatic" && account["require_authentication"] as? Bool == true { throw CageAccountError("Cage 已手动锁定,请使用指纹或密码") } | |
| 118 | 新增: guard let devices = account["devices"] as? [String: String], let expectedID = devices[kind] else { throw CageAccountError("请先使用密码登录,再开启快捷登录") } | |
| 119 | 新增: let credential = try Self.read(binding: binding, kind: kind) | |
| 120 | 新增: guard credential["id"] as? String == expectedID else { throw CageAccountError("快捷登录授权已失效,请使用密码") } | |
| 121 | 新增: _ = try await call("/device-unlock", ["kind": kind, "credential": credential]) | |
| 122 | 新增: default: throw CageAccountError("快捷登录操作无效") | |
| 123 | 新增: } | |
| 124 | 新增: return ["ok": true] | |
| 125 | 新增: } | |
| 126 | 新增:} | |
| @@ -1,12 +1,15 @@ | ||
| 1 | 1 | import Cocoa |
| 2 | 2 | import WebKit |
| 3 | 新增:import UniformTypeIdentifiers | |
| 3 | 4 | |
| 4 | 5 | @main |
| 5 | 6 | final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandlerWithReply { |
| 6 | 7 | private var window: NSWindow! |
| 7 | 8 | private var webView: WKWebView! |
| 9 | 新增: private var accountDeviceBusy = false | |
| 8 | 10 | private var expectedPort = 0 |
| 9 | 11 | private var allowQuit = false |
| 12 | 新增: private var nativeFilePanelOpen = false | |
| 10 | 13 | private var loading: NSTextField! |
| 11 | 14 | private var retry: NSButton! |
| 12 | 15 | private var backdrop: NSVisualEffectView! |
| @@ -155,6 +158,10 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 155 | 158 | @objc private func editPaste(){edit("paste",fallback:"paste:")} |
| 156 | 159 | @objc private func editSelectAll(){edit("selectAll",fallback:"selectAll:")} |
| 157 | 160 | private func edit(_ command:String,fallback:String){ |
| 161 | 新增: if nativeFilePanelOpen || window.attachedSheet != nil { | |
| 162 | 新增: NSApp.sendAction(Selector(fallback), to: nil, from: self) | |
| 163 | 新增: return | |
| 164 | 新增: } | |
| 158 | 165 | webView.evaluateJavaScript("window.cageEditAction?.('\(command)') ?? false") {result,error in |
| 159 | 166 | if (result as? Bool) != true {NSApp.sendAction(Selector(fallback),to:nil,from:self)} |
| 160 | 167 | } |
| @@ -224,6 +231,20 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 224 | 231 | } |
| 225 | 232 | } |
| 226 | 233 | } |
| 234 | 新增: private func browserFile(_ operation: String, id: String, path: String? = nil, reply: @escaping (Any?, String?) -> Void) { | |
| 235 | 新增: guard UUID(uuidString: id) != nil, let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else { reply(nil,"下载标识无效"); return } | |
| 236 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 237 | 新增: let process = Process(); process.executableURL = executable | |
| 238 | 新增: process.arguments = ["browser-file", "--json", operation, id] + (path.map { [$0] } ?? []) | |
| 239 | 新增: let output = Pipe(); process.standardOutput = output; process.standardError = FileHandle.nullDevice | |
| 240 | 新增: do { | |
| 241 | 新增: try process.run() | |
| 242 | 新增: let data = output.fileHandleForReading.readDataToEndOfFile(); process.waitUntilExit() | |
| 243 | 新增: guard data.count <= 65536, let result = try JSONSerialization.jsonObject(with: data) as? [String:Any] else { throw CageUpdateError("下载操作未返回有效结果") } | |
| 244 | 新增: DispatchQueue.main.async { reply(process.terminationStatus == 0 ? result : nil, process.terminationStatus == 0 ? nil : result["message"] as? String ?? "下载操作失败") } | |
| 245 | 新增: } catch { DispatchQueue.main.async { reply(nil,error.localizedDescription) } } | |
| 246 | 新增: } | |
| 247 | 新增: } | |
| 227 | 248 | private func showError(_ text: String) { loading.stringValue = text; loading.isHidden = false; retry.isHidden = false; webView.isHidden = true } |
| 228 | 249 | private func applyAppearance(_ value: [String:Any]) { |
| 229 | 250 | let mode = value["mode"] as? String ?? "system" |
| @@ -247,6 +268,25 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 247 | 268 | let origin = message.frameInfo.securityOrigin |
| 248 | 269 | guard message.frameInfo.isMainFrame, origin.protocol == "http", origin.host == "localhost", origin.port == expectedPort, let body = message.body as? [String:Any], let action = body["action"] as? String else { replyHandler(nil,"请求来源无效"); return } |
| 249 | 270 | switch action { |
| 271 | 新增: case "accountDevice": | |
| 272 | 新增: guard !controllerNeedsUpdate, !accountDeviceBusy, | |
| 273 | 新增: let operation = body["operation"] as? String, ["status", "enable", "disable", "unlock"].contains(operation) else { replyHandler(nil,"账户操作正在进行或后台需要更新,请稍后重试"); return } | |
| 274 | 新增: accountDeviceBusy = true | |
| 275 | 新增: let kind = body["kind"] as? String | |
| 276 | 新增: requestEntry { result in | |
| 277 | 新增: guard case .success(let entry) = result, let url = entry.url else { | |
| 278 | 新增: self.accountDeviceBusy = false; replyHandler(nil,"无法连接本地账户,请重新打开 Cage"); return | |
| 279 | 新增: } | |
| 280 | 新增: Task.detached { | |
| 281 | 新增: do { | |
| 282 | 新增: let client = try CageAccountDevice(entry: url) | |
| 283 | 新增: let value = try await client.handle(operation: operation, kind: kind) | |
| 284 | 新增: await MainActor.run { self.accountDeviceBusy = false; replyHandler(value,nil) } | |
| 285 | 新增: } catch { | |
| 286 | 新增: await MainActor.run { self.accountDeviceBusy = false; replyHandler(nil,error.localizedDescription) } | |
| 287 | 新增: } | |
| 288 | 新增: } | |
| 289 | 新增: } | |
| 250 | 290 | case "workbenchReady": |
| 251 | 291 | guard !controllerNeedsUpdate else { replyHandler(nil,"后台版本尚未同步,更新未完成"); return } |
| 252 | 292 | appUpdater?.markLaunchReady() |
| @@ -261,12 +301,66 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 261 | 301 | applyAppearance(value) |
| 262 | 302 | replyHandler(true,nil) |
| 263 | 303 | case "clipboardRead": replyHandler(NSPasteboard.general.string(forType:.string) ?? "",nil) |
| 304 | 新增: case "clipboardReadContent": | |
| 305 | 新增: let board = NSPasteboard.general | |
| 306 | 新增: if let image = NSImage(pasteboard: board), let tiff = image.tiffRepresentation, | |
| 307 | 新增: let bitmap = NSBitmapImageRep(data: tiff) { | |
| 308 | 新增: guard bitmap.pixelsWide > 0, bitmap.pixelsHigh > 0, | |
| 309 | 新增: bitmap.pixelsWide <= 40_000_000 / bitmap.pixelsHigh, | |
| 310 | 新增: let png = bitmap.representation(using: .png, properties: [:]), png.count <= 20 * 1024 * 1024 else { | |
| 311 | 新增: replyHandler(nil,"图片不能超过 20 MB 或 4000 万像素"); return | |
| 312 | 新增: } | |
| 313 | 新增: replyHandler(["png":png.base64EncodedString()],nil) | |
| 314 | 新增: } else { replyHandler(["text":board.string(forType:.string) ?? ""],nil) } | |
| 264 | 315 | case "clipboardWrite": |
| 265 | 316 | guard let text = body["text"] as? String else { replyHandler(nil,"缺少文本"); return } |
| 266 | 317 | NSPasteboard.general.clearContents(); NSPasteboard.general.setString(text, forType:.string); replyHandler(true,nil) |
| 318 | 新增: case "saveBrowserDownload": | |
| 319 | 新增: guard !nativeFilePanelOpen, let id = body["id"] as? String, UUID(uuidString:id) != nil else { replyHandler(nil,"请先完成当前文件窗口"); return } | |
| 320 | 新增: let panel = NSSavePanel(); panel.canCreateDirectories = true | |
| 321 | 新增: panel.nameFieldStringValue = ((body["name"] as? String ?? "download") as NSString).lastPathComponent | |
| 322 | 新增: panel.prompt = "保存"; panel.title = "将下载另存为到本机" | |
| 323 | 新增: nativeFilePanelOpen = true | |
| 324 | 新增: panel.beginSheetModal(for: window) { response in | |
| 325 | 新增: self.nativeFilePanelOpen = false | |
| 326 | 新增: guard response == .OK, let url = panel.url else { replyHandler(["canceled":true],nil); return } | |
| 327 | 新增: self.browserFile("save",id:id,path:url.path,reply:replyHandler) | |
| 328 | 新增: } | |
| 329 | 新增: case "browserDownloadAction": | |
| 330 | 新增: guard let id = body["id"] as? String, let operation = body["operation"] as? String, ["open","reveal"].contains(operation) else { replyHandler(nil,"下载操作无效"); return } | |
| 331 | 新增: browserFile(operation,id:id,reply:replyHandler) | |
| 332 | 新增: case "importTheme": | |
| 333 | 新增: let panel = NSOpenPanel() | |
| 334 | 新增: panel.allowedContentTypes = [.json]; panel.allowsMultipleSelection = false | |
| 335 | 新增: panel.canChooseDirectories = false; panel.canChooseFiles = true; panel.prompt = "导入主题" | |
| 336 | 新增: nativeFilePanelOpen = true | |
| 337 | 新增: panel.beginSheetModal(for: window) { response in | |
| 338 | 新增: self.nativeFilePanelOpen = false | |
| 339 | 新增: guard response == .OK, let url = panel.url else { replyHandler("", nil); return } | |
| 340 | 新增: do { | |
| 341 | 新增: let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } | |
| 342 | 新增: let data = try handle.read(upToCount: 256 * 1024 + 1) ?? Data() | |
| 343 | 新增: guard data.count <= 256 * 1024, let text = String(data: data, encoding: .utf8) else { replyHandler(nil, "请选择不超过 256 KB 的 UTF-8 JSON 主题文件"); return } | |
| 344 | 新增: replyHandler(text, nil) | |
| 345 | 新增: } catch { replyHandler(nil, "无法读取主题文件,请检查文件权限") } | |
| 346 | 新增: } | |
| 347 | 新增: case "exportTheme": | |
| 348 | 新增: guard let text = body["text"] as? String, let data = text.data(using: .utf8), data.count <= 256 * 1024, | |
| 349 | 新增: let document = try? JSONSerialization.jsonObject(with: data) as? [String: Any], document["format"] as? String == "cage-theme", document["version"] as? Int == 1 else { replyHandler(nil, "主题文件格式无效"); return } | |
| 350 | 新增: let panel = NSSavePanel(); panel.allowedContentTypes = [.json]; panel.canCreateDirectories = true | |
| 351 | 新增: let filename = (body["filename"] as? String ?? "Cage.cage-theme.json") as NSString | |
| 352 | 新增: panel.nameFieldStringValue = filename.lastPathComponent; panel.prompt = "导出主题" | |
| 353 | 新增: nativeFilePanelOpen = true | |
| 354 | 新增: panel.beginSheetModal(for: window) { response in | |
| 355 | 新增: self.nativeFilePanelOpen = false | |
| 356 | 新增: guard response == .OK, let url = panel.url else { replyHandler(false, nil); return } | |
| 357 | 新增: do { try data.write(to: url, options: .atomic); replyHandler(true, nil) } | |
| 358 | 新增: catch { replyHandler(nil, "主题未能导出,请检查保存位置的权限") } | |
| 359 | 新增: } | |
| 267 | 360 | case "chooseFolder": |
| 268 | 361 | let panel = NSOpenPanel(); panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true; panel.allowsMultipleSelection = false; panel.prompt = "共享此项目"; panel.message = "仅此文件夹会与 Cage 共享。请选择具体项目。" |
| 269 | 删除: panel.beginSheetModal(for:window) { response in replyHandler(response == .OK ? panel.url?.path : "",nil) } | |
| 362 | 新增: nativeFilePanelOpen = true | |
| 363 | 新增: panel.beginSheetModal(for:window) { response in self.nativeFilePanelOpen = false; replyHandler(response == .OK ? panel.url?.path : "",nil) } | |
| 270 | 364 | case "refreshSession": |
| 271 | 365 | requestEntry(options: controllerNeedsUpdate ? ["--existing"] : []) { result in |
| 272 | 366 | switch result { |
| @@ -282,6 +376,17 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 282 | 376 | } |
| 283 | 377 | } |
| 284 | 378 | func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alert = NSAlert(); alert.messageText = message; alert.beginSheetModal(for:window){_ in completionHandler()} } |
| 379 | 新增: func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping ([URL]?) -> Void) { | |
| 380 | 新增: let origin = frame.securityOrigin | |
| 381 | 新增: guard frame.isMainFrame, origin.protocol == "http", origin.host == "localhost", origin.port == expectedPort, !nativeFilePanelOpen else { completionHandler(nil); return } | |
| 382 | 新增: let panel = NSOpenPanel(); panel.canChooseFiles = true; panel.canChooseDirectories = false | |
| 383 | 新增: panel.allowsMultipleSelection = parameters.allowsMultipleSelection | |
| 384 | 新增: panel.title = "选择本机文件"; nativeFilePanelOpen = true | |
| 385 | 新增: panel.beginSheetModal(for: window) { response in | |
| 386 | 新增: self.nativeFilePanelOpen = false | |
| 387 | 新增: completionHandler(response == .OK ? panel.urls : nil) | |
| 388 | 新增: } | |
| 389 | 新增: } | |
| 285 | 390 | func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alert = NSAlert(); alert.messageText = message; alert.addButton(withTitle:"确定"); alert.addButton(withTitle:"取消"); alert.beginSheetModal(for:window){completionHandler($0 == .alertFirstButtonReturn)} } |
| 286 | 391 | private func publishWindowVisibility(forceHidden: Bool = false) { |
| 287 | 392 | guard window != nil, webView != nil else { return } |
| @@ -0,0 +1,864 @@ | ||
| 1 | 新增:/* Native Linux host for the shared Cage workbench. */ | |
| 2 | 新增:#include <gtk/gtk.h> | |
| 3 | 新增:#include <webkit2/webkit2.h> | |
| 4 | 新增:#include <json-glib/json-glib.h> | |
| 5 | 新增:#include <glib/gstdio.h> | |
| 6 | 新增:#include <unistd.h> | |
| 7 | 新增:#include <string.h> | |
| 8 | 新增:#include <stdlib.h> | |
| 9 | 新增: | |
| 10 | 新增:#ifndef CAGE_VERSION | |
| 11 | 新增:#define CAGE_VERSION "development" | |
| 12 | 新增:#endif | |
| 13 | 新增:#define MAX_THEME (256 * 1024) | |
| 14 | 新增:#define MAX_MESSAGE (2 * 1024 * 1024) | |
| 15 | 新增: | |
| 16 | 新增:typedef struct { | |
| 17 | 新增: GtkApplication *application; | |
| 18 | 新增: GtkWidget *window, *stack, *status, *retry, *existing, *complete; | |
| 19 | 新增: WebKitWebView *web; | |
| 20 | 新增: WebKitUserContentManager *content; | |
| 21 | 新增: char *backend, *profile, *token, *smoke_output, *web_data, *web_cache; | |
| 22 | 新增: const char *storage_phase, *storage_marker; | |
| 23 | 新增: int port, result; | |
| 24 | 新增: gboolean bootstrapping, needs_update, ready, picker_open, smoke_started, navigation_failed; | |
| 25 | 新增: gboolean initial_dark; | |
| 26 | 新增:} Cage; | |
| 27 | 新增:static Cage app; | |
| 28 | 新增:static void bootstrap(const char *option); | |
| 29 | 新增:static void show_error(const char *message); | |
| 30 | 新增: | |
| 31 | 新增:typedef void (*BackendCallback)(JsonObject *, const GError *, gpointer); | |
| 32 | 新增:typedef struct { | |
| 33 | 新增: GSubprocess *process; | |
| 34 | 新增: GCancellable *cancel; | |
| 35 | 新增: guint deadline; | |
| 36 | 新增: BackendCallback callback; | |
| 37 | 新增: gpointer data; | |
| 38 | 新增:} Command; | |
| 39 | 新增: | |
| 40 | 新增:static const char *text_member(JsonObject *object, const char *name) { | |
| 41 | 新增: JsonNode *node = object ? json_object_get_member(object, name) : NULL; | |
| 42 | 新增: return node && JSON_NODE_HOLDS_VALUE(node) && json_node_get_value_type(node) == G_TYPE_STRING | |
| 43 | 新增: ? json_node_get_string(node) : ""; | |
| 44 | 新增:} | |
| 45 | 新增:static char *json_text(JsonNode *node) { | |
| 46 | 新增: JsonGenerator *generator = json_generator_new(); | |
| 47 | 新增: json_generator_set_root(generator, node); | |
| 48 | 新增: char *text = json_generator_to_data(generator, NULL); | |
| 49 | 新增: g_object_unref(generator); | |
| 50 | 新增: return text; | |
| 51 | 新增:} | |
| 52 | 新增:static char *quote(const char *value) { | |
| 53 | 新增: JsonNode *node = json_node_new(JSON_NODE_VALUE); | |
| 54 | 新增: json_node_set_string(node, value); | |
| 55 | 新增: char *result = json_text(node); | |
| 56 | 新增: json_node_free(node); | |
| 57 | 新增: return result; | |
| 58 | 新增:} | |
| 59 | 新增:static gboolean valid_workbench(const char *raw, int expected_port, gboolean entry) { | |
| 60 | 新增: if (!raw) return FALSE; | |
| 61 | 新增: GUri *uri = g_uri_parse(raw, G_URI_FLAGS_NONE, NULL); | |
| 62 | 新增: if (!uri) return FALSE; | |
| 63 | 新增: int port = g_uri_get_port(uri); | |
| 64 | 新增: const char *fragment = g_uri_get_fragment(uri); | |
| 65 | 新增: gboolean valid = g_strcmp0(g_uri_get_scheme(uri), "http") == 0 && | |
| 66 | 新增: g_strcmp0(g_uri_get_host(uri), "localhost") == 0 && | |
| 67 | 新增: !g_uri_get_userinfo(uri) && port >= 1024 && port <= 65535 && | |
| 68 | 新增: (!expected_port || expected_port == port) && | |
| 69 | 新增: (!entry || (fragment && strlen(fragment) >= 2)); | |
| 70 | 新增: g_uri_unref(uri); | |
| 71 | 新增: return valid; | |
| 72 | 新增:} | |
| 73 | 新增:static gboolean private_directory(const char *path) { | |
| 74 | 新增: if (g_mkdir_with_parents(path, 0700) != 0) return FALSE; | |
| 75 | 新增: GFile *file = g_file_new_for_path(path); | |
| 76 | 新增: GFileInfo *info = g_file_query_info(file, G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_UNIX_UID, | |
| 77 | 新增: G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL, NULL); | |
| 78 | 新增: gboolean valid = info && g_file_info_get_file_type(info) == G_FILE_TYPE_DIRECTORY && | |
| 79 | 新增: g_file_info_get_attribute_uint32(info, G_FILE_ATTRIBUTE_UNIX_UID) == geteuid() && g_chmod(path, 0700) == 0; | |
| 80 | 新增: g_clear_object(&info); g_object_unref(file); | |
| 81 | 新增: return valid; | |
| 82 | 新增:} | |
| 83 | 新增:static gboolean prepare_web_storage(void) { | |
| 84 | 新增: char *profile_directory = g_path_get_dirname(app.profile); | |
| 85 | 新增: char *root = g_build_filename(profile_directory, "webkit", NULL); | |
| 86 | 新增: app.web_data = g_build_filename(root, "data", NULL); | |
| 87 | 新增: app.web_cache = g_build_filename(root, "cache", NULL); | |
| 88 | 新增: gboolean valid = private_directory(profile_directory) && private_directory(root) && | |
| 89 | 新增: private_directory(app.web_data) && private_directory(app.web_cache); | |
| 90 | 新增: g_free(root); g_free(profile_directory); | |
| 91 | 新增: return valid; | |
| 92 | 新增:} | |
| 93 | 新增:static gboolean command_timeout(gpointer data) { | |
| 94 | 新增: Command *command = data; | |
| 95 | 新增: command->deadline = 0; | |
| 96 | 新增: g_cancellable_cancel(command->cancel); | |
| 97 | 新增: g_subprocess_force_exit(command->process); | |
| 98 | 新增: return G_SOURCE_REMOVE; | |
| 99 | 新增:} | |
| 100 | 新增:static void command_finished(GObject *source, GAsyncResult *result, gpointer data) { | |
| 101 | 新增: Command *command = data; | |
| 102 | 新增: GError *error = NULL; | |
| 103 | 新增: char *output = NULL; | |
| 104 | 新增: JsonParser *parser = json_parser_new(); | |
| 105 | 新增: JsonObject *object = NULL; | |
| 106 | 新增: if (command->deadline) g_source_remove(command->deadline); | |
| 107 | 新增: if (g_subprocess_communicate_utf8_finish(G_SUBPROCESS(source), result, &output, NULL, &error)) { | |
| 108 | 新增: if (!output || strlen(output) > 65536 || !json_parser_load_from_data(parser, output, -1, NULL) || | |
| 109 | 新增: !JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser))) { | |
| 110 | 新增: g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA, "Cage 后台未返回有效状态,请查看私有配置中的 control.log。"); | |
| 111 | 新增: } else { | |
| 112 | 新增: object = json_node_get_object(json_parser_get_root(parser)); | |
| 113 | 新增: if (!g_subprocess_get_successful(command->process)) { | |
| 114 | 新增: const char *message = text_member(object, "message"); | |
| 115 | 新增: g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_FAILED, | |
| 116 | 新增: *message ? message : "Cage 后台操作失败,请查看 control.log。"); | |
| 117 | 新增: } | |
| 118 | 新增: } | |
| 119 | 新增: } | |
| 120 | 新增: command->callback(object, error, command->data); | |
| 121 | 新增: g_clear_error(&error); | |
| 122 | 新增: g_free(output); | |
| 123 | 新增: g_object_unref(parser); | |
| 124 | 新增: g_object_unref(command->process); | |
| 125 | 新增: g_object_unref(command->cancel); | |
| 126 | 新增: g_free(command); | |
| 127 | 新增:} | |
| 128 | 新增:static void backend_arguments(const char *const *args, guint seconds, BackendCallback callback, gpointer data) { | |
| 129 | 新增: GError *error = NULL; | |
| 130 | 新增: GSubprocessLauncher *launcher = g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_SILENCE); | |
| 131 | 新增: g_subprocess_launcher_setenv(launcher, "CLAUDE_CAGE_CONFIG", app.profile, TRUE); | |
| 132 | 新增: GSubprocess *process = g_subprocess_launcher_spawnv(launcher, args, &error); | |
| 133 | 新增: g_object_unref(launcher); | |
| 134 | 新增: if (!process) { | |
| 135 | 新增: callback(NULL, error, data); | |
| 136 | 新增: g_clear_error(&error); | |
| 137 | 新增: return; | |
| 138 | 新增: } | |
| 139 | 新增: Command *command = g_new0(Command, 1); | |
| 140 | 新增: command->process = process; | |
| 141 | 新增: command->cancel = g_cancellable_new(); | |
| 142 | 新增: command->callback = callback; | |
| 143 | 新增: command->data = data; | |
| 144 | 新增: command->deadline = g_timeout_add_seconds(seconds, command_timeout, command); | |
| 145 | 新增: g_subprocess_communicate_utf8_async(process, NULL, command->cancel, command_finished, command); | |
| 146 | 新增:} | |
| 147 | 新增:static void backend(const char *action, const char *option, BackendCallback callback, gpointer data) { | |
| 148 | 新增: const char *args[] = {app.backend, action, "--json", option, NULL}; | |
| 149 | 新增: backend_arguments(args, 180, callback, data); | |
| 150 | 新增:} | |
| 151 | 新增:static void script(const char *code) { | |
| 152 | 新增: if (app.web && app.port && valid_workbench(webkit_web_view_get_uri(app.web), app.port, FALSE)) | |
| 153 | 新增: webkit_web_view_evaluate_javascript(app.web, code, -1, NULL, NULL, NULL, NULL, NULL); | |
| 154 | 新增:} | |
| 155 | 新增:static void action(const char *name) { | |
| 156 | 新增: char *quoted = quote(name); | |
| 157 | 新增: char *code = g_strdup_printf("window.cageNativeAction?.(%s)", quoted); | |
| 158 | 新增: script(code); | |
| 159 | 新增: g_free(code); | |
| 160 | 新增: g_free(quoted); | |
| 161 | 新增:} | |
| 162 | 新增:static void publish_visibility(void) { | |
| 163 | 新增: GdkWindow *window = gtk_widget_get_window(app.window); | |
| 164 | 新增: gboolean visible = gtk_widget_get_visible(app.window) && window && | |
| 165 | 新增: !(gdk_window_get_state(window) & GDK_WINDOW_STATE_ICONIFIED); | |
| 166 | 新增: script(visible ? | |
| 167 | 新增: "window.cageWindowVisible=true;window.dispatchEvent(new Event('cage-window-visibility'));" : | |
| 168 | 新增: "window.cageWindowVisible=false;window.dispatchEvent(new Event('cage-window-visibility'));" ); | |
| 169 | 新增:} | |
| 170 | 新增:static gboolean visibility_changed(GtkWidget *widget, GdkEvent *event, gpointer data) { | |
| 171 | 新增: (void)widget; (void)event; (void)data; | |
| 172 | 新增: publish_visibility(); | |
| 173 | 新增: return FALSE; | |
| 174 | 新增:} | |
| 175 | 新增:static gboolean close_window(GtkWidget *widget, GdkEvent *event, gpointer data) { | |
| 176 | 新增: (void)event; (void)data; | |
| 177 | 新增: gtk_widget_hide(widget); | |
| 178 | 新增: publish_visibility(); | |
| 179 | 新增: return TRUE; | |
| 180 | 新增:} | |
| 181 | 新增:static gboolean quit_idle(gpointer data) { | |
| 182 | 新增: (void)data; | |
| 183 | 新增: g_application_quit(G_APPLICATION(app.application)); | |
| 184 | 新增: return G_SOURCE_REMOVE; | |
| 185 | 新增:} | |
| 186 | 新增:static void show_error(const char *message) { | |
| 187 | 新增: gtk_label_set_text(GTK_LABEL(app.status), message); | |
| 188 | 新增: gtk_stack_set_visible_child_name(GTK_STACK(app.stack), "status"); | |
| 189 | 新增: gtk_widget_show(app.retry); | |
| 190 | 新增:} | |
| 191 | 新增:static void reply_json(WebKitScriptMessageReply *reply, JSCContext *context, const char *json) { | |
| 192 | 新增: JSCValue *value = jsc_value_new_from_json(context, json); | |
| 193 | 新增: webkit_script_message_reply_return_value(reply, value); | |
| 194 | 新增: g_object_unref(value); | |
| 195 | 新增:} | |
| 196 | 新增:static void reply_string(WebKitScriptMessageReply *reply, JSCContext *context, const char *text) { | |
| 197 | 新增: JSCValue *value = jsc_value_new_string(context, text); | |
| 198 | 新增: webkit_script_message_reply_return_value(reply, value); | |
| 199 | 新增: g_object_unref(value); | |
| 200 | 新增:} | |
| 201 | 新增:static void reply_error(WebKitScriptMessageReply *reply, const char *message) { | |
| 202 | 新增: webkit_script_message_reply_return_error_message(reply, message); | |
| 203 | 新增:} | |
| 204 | 新增:static char *choose_file(GtkFileChooserAction kind, const char *title, const char *filename) { | |
| 205 | 新增: if (app.picker_open) return NULL; | |
| 206 | 新增: app.picker_open = TRUE; | |
| 207 | 新增: GtkWidget *dialog = gtk_file_chooser_dialog_new(title, GTK_WINDOW(app.window), kind, | |
| 208 | 新增: "取消", GTK_RESPONSE_CANCEL, kind == GTK_FILE_CHOOSER_ACTION_SAVE ? "保存" : "选择", GTK_RESPONSE_ACCEPT, NULL); | |
| 209 | 新增: gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(dialog), TRUE); | |
| 210 | 新增: if (kind == GTK_FILE_CHOOSER_ACTION_SAVE) { | |
| 211 | 新增: char *base = g_path_get_basename(filename && *filename ? filename : "Cage.cage-theme.json"); | |
| 212 | 新增: gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), base); | |
| 213 | 新增: gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); | |
| 214 | 新增: g_free(base); | |
| 215 | 新增: } | |
| 216 | 新增: if (kind != GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER) { | |
| 217 | 新增: GtkFileFilter *filter = gtk_file_filter_new(); | |
| 218 | 新增: gtk_file_filter_set_name(filter, "Cage 主题 (*.json)"); | |
| 219 | 新增: gtk_file_filter_add_pattern(filter, "*.json"); | |
| 220 | 新增: gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); | |
| 221 | 新增: } | |
| 222 | 新增: char *path = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT | |
| 223 | 新增: ? gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)) : NULL; | |
| 224 | 新增: gtk_widget_destroy(dialog); | |
| 225 | 新增: app.picker_open = FALSE; | |
| 226 | 新增: return path; | |
| 227 | 新增:} | |
| 228 | 新增:typedef struct { WebKitScriptMessageReply *reply; JSCContext *context; } PendingReply; | |
| 229 | 新增:static PendingReply *pending_reply(WebKitScriptMessageReply *reply, JSCContext *context) { | |
| 230 | 新增: PendingReply *pending = g_new0(PendingReply, 1); | |
| 231 | 新增: pending->reply = webkit_script_message_reply_ref(reply); | |
| 232 | 新增: pending->context = g_object_ref(context); | |
| 233 | 新增: return pending; | |
| 234 | 新增:} | |
| 235 | 新增:static void pending_free(PendingReply *pending) { | |
| 236 | 新增: webkit_script_message_reply_unref(pending->reply); | |
| 237 | 新增: g_object_unref(pending->context); | |
| 238 | 新增: g_free(pending); | |
| 239 | 新增:} | |
| 240 | 新增:static void browser_file_finished(JsonObject *object, const GError *error, gpointer data) { | |
| 241 | 新增: PendingReply *pending = data; | |
| 242 | 新增: if (error) reply_error(pending->reply, error->message); | |
| 243 | 新增: else { | |
| 244 | 新增: JsonNode *node = json_node_new(JSON_NODE_OBJECT); | |
| 245 | 新增: json_node_set_object(node, object); | |
| 246 | 新增: char *json = json_to_string(node, FALSE); | |
| 247 | 新增: reply_json(pending->reply, pending->context, json); | |
| 248 | 新增: g_free(json); json_node_free(node); | |
| 249 | 新增: } | |
| 250 | 新增: pending_free(pending); | |
| 251 | 新增:} | |
| 252 | 新增:static void clipboard_received(GtkClipboard *clipboard, const gchar *text, gpointer data) { | |
| 253 | 新增: (void)clipboard; | |
| 254 | 新增: PendingReply *pending = data; | |
| 255 | 新增: if (text && strlen(text) > MAX_MESSAGE) reply_error(pending->reply, "剪贴板内容超过 2 MB。"); | |
| 256 | 新增: else reply_string(pending->reply, pending->context, text ? text : ""); | |
| 257 | 新增: pending_free(pending); | |
| 258 | 新增:} | |
| 259 | 新增:static void clipboard_content_text(GtkClipboard *clipboard, const gchar *text, gpointer data) { | |
| 260 | 新增: (void)clipboard; | |
| 261 | 新增: PendingReply *pending = data; | |
| 262 | 新增: if (text && strlen(text) > MAX_MESSAGE) reply_error(pending->reply, "剪贴板内容超过 2 MB。"); | |
| 263 | 新增: else { | |
| 264 | 新增: char *quoted = quote(text ? text : ""); | |
| 265 | 新增: char *json = g_strdup_printf("{\"text\":%s}", quoted); | |
| 266 | 新增: reply_json(pending->reply, pending->context, json); | |
| 267 | 新增: g_free(json); g_free(quoted); | |
| 268 | 新增: } | |
| 269 | 新增: pending_free(pending); | |
| 270 | 新增:} | |
| 271 | 新增:static void clipboard_content_image(GtkClipboard *clipboard, GdkPixbuf *image, gpointer data) { | |
| 272 | 新增: PendingReply *pending = data; | |
| 273 | 新增: if (!image) { | |
| 274 | 新增: gtk_clipboard_request_text(clipboard, clipboard_content_text, pending); | |
| 275 | 新增: return; | |
| 276 | 新增: } | |
| 277 | 新增: gchar *buffer = NULL; | |
| 278 | 新增: gsize length = 0; | |
| 279 | 新增: if ((gint64)gdk_pixbuf_get_width(image) * gdk_pixbuf_get_height(image) > 40000000 || | |
| 280 | 新增: !gdk_pixbuf_save_to_buffer(image, &buffer, &length, "png", NULL, NULL) || length > 20 * 1024 * 1024) { | |
| 281 | 新增: reply_error(pending->reply, "图片不能超过 20 MB 或 4000 万像素。"); | |
| 282 | 新增: } else { | |
| 283 | 新增: char *encoded = g_base64_encode((const guchar *)buffer, length); | |
| 284 | 新增: char *json = g_strdup_printf("{\"png\":\"%s\"}", encoded); | |
| 285 | 新增: reply_json(pending->reply, pending->context, json); | |
| 286 | 新增: g_free(json); g_free(encoded); | |
| 287 | 新增: } | |
| 288 | 新增: g_free(buffer); | |
| 289 | 新增: pending_free(pending); | |
| 290 | 新增:} | |
| 291 | 新增:static void session_refreshed(JsonObject *object, const GError *error, gpointer data) { | |
| 292 | 新增: PendingReply *pending = data; | |
| 293 | 新增: const char *url = text_member(object, "url"); | |
| 294 | 新增: if (error || !valid_workbench(url, 0, TRUE)) | |
| 295 | 新增: reply_error(pending->reply, error ? error->message : "工作台会话恢复失败,请重新连接。"); | |
| 296 | 新增: else { | |
| 297 | 新增: char *quoted = quote(url); | |
| 298 | 新增: char *json = g_strdup_printf("{\"url\":%s}", quoted); | |
| 299 | 新增: reply_json(pending->reply, pending->context, json); | |
| 300 | 新增: g_free(json); g_free(quoted); | |
| 301 | 新增: } | |
| 302 | 新增: pending_free(pending); | |
| 303 | 新增:} | |
| 304 | 新增:static void smoke_report(char *evidence) { | |
| 305 | 新增: GError *error = NULL; | |
| 306 | 新增: if (g_file_set_contents(app.smoke_output, evidence, -1, &error)) app.result = 0; | |
| 307 | 新增: else { | |
| 308 | 新增: g_printerr("Linux smoke: cannot save report: %s\n", error->message); | |
| 309 | 新增: g_clear_error(&error); | |
| 310 | 新增: } | |
| 311 | 新增: g_free(evidence); | |
| 312 | 新增: g_application_quit(G_APPLICATION(app.application)); | |
| 313 | 新增:} | |
| 314 | 新增:static void smoke_stopped(JsonObject *object, const GError *error, gpointer data) { | |
| 315 | 新增: if (error || g_strcmp0(text_member(object, "status"), "prepared") != 0) { | |
| 316 | 新增: g_printerr("Linux smoke: controller cleanup failed.\n"); | |
| 317 | 新增: g_free(data); | |
| 318 | 新增: g_application_quit(G_APPLICATION(app.application)); | |
| 319 | 新增: } else smoke_report(data); | |
| 320 | 新增:} | |
| 321 | 新增:static void smoke_snapshot(GObject *source, GAsyncResult *result, gpointer data) { | |
| 322 | 新增: char *report = data; | |
| 323 | 新增: GError *error = NULL; | |
| 324 | 新增: cairo_surface_t *surface = webkit_web_view_get_snapshot_finish(WEBKIT_WEB_VIEW(source), result, &error); | |
| 325 | 新增: char *path = g_strconcat(app.smoke_output, ".png", NULL); | |
| 326 | 新增: gboolean saved = surface && cairo_surface_write_to_png(surface, path) == CAIRO_STATUS_SUCCESS; | |
| 327 | 新增: if (surface) cairo_surface_destroy(surface); | |
| 328 | 新增: g_free(path); g_clear_error(&error); | |
| 329 | 新增: if (saved && g_strcmp0(app.storage_phase, "seed") == 0) smoke_report(report); | |
| 330 | 新增: else if (saved) backend("prepare-update", NULL, smoke_stopped, report); | |
| 331 | 新增: else { | |
| 332 | 新增: g_printerr("Linux smoke: could not capture rendered workbench.\n"); | |
| 333 | 新增: g_free(report); | |
| 334 | 新增: g_application_quit(G_APPLICATION(app.application)); | |
| 335 | 新增: } | |
| 336 | 新增:} | |
| 337 | 新增:static void smoke_evaluated(GObject *source, GAsyncResult *result, gpointer data) { | |
| 338 | 新增: (void)data; | |
| 339 | 新增: GError *error = NULL; | |
| 340 | 新增: JSCValue *value = webkit_web_view_call_async_javascript_function_finish(WEBKIT_WEB_VIEW(source), result, &error); | |
| 341 | 新增: if (!value || error || !jsc_value_is_object(value)) { | |
| 342 | 新增: g_printerr("Linux smoke: authenticated workbench verification failed.\n"); | |
| 343 | 新增: g_clear_error(&error); g_clear_object(&value); | |
| 344 | 新增: g_application_quit(G_APPLICATION(app.application)); | |
| 345 | 新增: return; | |
| 346 | 新增: } | |
| 347 | 新增: char *json = jsc_value_to_json(value, 0); | |
| 348 | 新增: JsonParser *parser = json_parser_new(); | |
| 349 | 新增: gboolean ok = json && json_parser_load_from_data(parser, json, -1, NULL) && | |
| 350 | 新增: JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser)); | |
| 351 | 新增: JsonObject *object = ok ? json_node_get_object(json_parser_get_root(parser)) : NULL; | |
| 352 | 新增: ok = object && json_object_has_member(object, "success") && json_object_get_boolean_member(object, "success"); | |
| 353 | 新增: if (ok) { | |
| 354 | 新增: json_object_set_string_member(object, "version", CAGE_VERSION); | |
| 355 | 新增: json_object_set_int_member(object, "webkitMajor", webkit_get_major_version()); | |
| 356 | 新增: json_object_set_int_member(object, "webkitMinor", webkit_get_minor_version()); | |
| 357 | 新增: json_object_set_int_member(object, "webkitMicro", webkit_get_micro_version()); | |
| 358 | 新增: char *report = json_text(json_parser_get_root(parser)); | |
| 359 | 新增: webkit_web_view_get_snapshot(app.web, WEBKIT_SNAPSHOT_REGION_VISIBLE, WEBKIT_SNAPSHOT_OPTIONS_NONE, | |
| 360 | 新增: NULL, smoke_snapshot, report); | |
| 361 | 新增: } else { | |
| 362 | 新增: g_printerr("Linux smoke: workbench evidence was incomplete.\n"); | |
| 363 | 新增: g_application_quit(G_APPLICATION(app.application)); | |
| 364 | 新增: } | |
| 365 | 新增: g_free(json); g_object_unref(parser); g_object_unref(value); | |
| 366 | 新增:} | |
| 367 | 新增:static gboolean start_smoke(gpointer data) { | |
| 368 | 新增: (void)data; | |
| 369 | 新增: char *phase = quote(app.storage_phase ? app.storage_phase : ""); | |
| 370 | 新增: char *marker = quote(app.storage_marker ? app.storage_marker : ""); | |
| 371 | 新增: char *body = g_strdup_printf( | |
| 372 | 新增: "const phase=%s,marker=%s;const storageKey='cage-linux-smoke-persistence';" | |
| 373 | 新增: "if(phase==='seed')localStorage.setItem(storageKey,marker);" | |
| 374 | 新增: "const storageMarkerMatched=!phase||localStorage.getItem(storageKey)===marker;" | |
| 375 | 新增: "if(phase==='verify'&&storageMarkerMatched)localStorage.removeItem(storageKey);" | |
| 376 | 新增: "const bridge=window.webkit.messageHandlers.cage;" | |
| 377 | 新增: "let unauthenticatedBridgeDenied=false;try{await window.webkit.messageHandlers.cageTransport.postMessage({token:'invalid',request:{action:'clipboardRead'}});}catch{unauthenticatedBridgeDenied=true;}" | |
| 378 | 新增: "const native=await bridge.postMessage({action:'accountDevice',operation:'status'});" | |
| 379 | 新增: "const update=await bridge.postMessage({action:'appUpdate',operation:'status'});" | |
| 380 | 新增: "const accountResponse=await fetch('/api/account');const account=await accountResponse.json();" | |
| 381 | 新增: "const stateResponse=await fetch('/api/status');const state=await stateResponse.json();" | |
| 382 | 新增: "const settingsResponse=await fetch('/api/settings');await settingsResponse.json();" | |
| 383 | 新增: "const root=document.getElementById('root');" | |
| 384 | 新增: "const rendered=!!root&&root.innerText.trim().length>40&&root.querySelectorAll('button').length>3;" | |
| 385 | 新增: "const success=rendered&&accountResponse.ok&&account.unlocked===true&&stateResponse.ok&&settingsResponse.ok&&native.supported===false&&update.phase==='manual'&&unauthenticatedBridgeDenied&&storageMarkerMatched;" | |
| 386 | 新增: "return {success,nativeBridgeReady:true,authenticated:accountResponse.ok,accountUnlocked:account.unlocked===true," | |
| 387 | 新增: "workbenchRendered:rendered,workbenchReadyAcknowledged:true,statusReceived:stateResponse.ok,settingsReceived:settingsResponse.ok,unauthenticatedBridgeDenied," | |
| 388 | 新增: "storageMarkerMatched,localStoragePersisted:phase==='verify'&&storageMarkerMatched};", phase, marker); | |
| 389 | 新增: webkit_web_view_call_async_javascript_function(app.web, body, -1, NULL, NULL, NULL, NULL, smoke_evaluated, NULL); | |
| 390 | 新增: g_free(body); g_free(phase); g_free(marker); | |
| 391 | 新增: return G_SOURCE_REMOVE; | |
| 392 | 新增:} | |
| 393 | 新增:static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *value, WebKitScriptMessageReply *reply, gpointer data) { | |
| 394 | 新增: (void)manager; (void)data; | |
| 395 | 新增: char *json = jsc_value_to_json(value, 0); | |
| 396 | 新增: JsonParser *parser = json_parser_new(); | |
| 397 | 新增: if (!json || strlen(json) > MAX_MESSAGE || !json_parser_load_from_data(parser, json, -1, NULL) || | |
| 398 | 新增: !JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser))) { | |
| 399 | 新增: reply_error(reply, "原生请求格式无效。"); | |
| 400 | 新增: goto done; | |
| 401 | 新增: } | |
| 402 | 新增: JsonObject *envelope = json_node_get_object(json_parser_get_root(parser)); | |
| 403 | 新增: if (!app.token || g_strcmp0(text_member(envelope, "token"), app.token) != 0 || | |
| 404 | 新增: !valid_workbench(webkit_web_view_get_uri(app.web), app.port, FALSE)) { | |
| 405 | 新增: reply_error(reply, "请求来源无效。"); | |
| 406 | 新增: goto done; | |
| 407 | 新增: } | |
| 408 | 新增: JsonNode *request_node = json_object_get_member(envelope, "request"); | |
| 409 | 新增: if (!request_node || !JSON_NODE_HOLDS_OBJECT(request_node)) { | |
| 410 | 新增: reply_error(reply, "原生请求格式无效。"); | |
| 411 | 新增: goto done; | |
| 412 | 新增: } | |
| 413 | 新增: JsonObject *request = json_node_get_object(request_node); | |
| 414 | 新增: const char *name = text_member(request, "action"); | |
| 415 | 新增: JSCContext *context = jsc_value_get_context(value); | |
| 416 | 新增: if (!strcmp(name, "workbenchReady")) { | |
| 417 | 新增: if (app.needs_update) reply_error(reply, "后台版本尚未同步,更新未完成。"); | |
| 418 | 新增: else { | |
| 419 | 新增: app.ready = TRUE; | |
| 420 | 新增: reply_json(reply, context, "true"); | |
| 421 | 新增: if (app.smoke_output && !app.smoke_started) { | |
| 422 | 新增: app.smoke_started = TRUE; | |
| 423 | 新增: g_idle_add(start_smoke, NULL); | |
| 424 | 新增: } | |
| 425 | 新增: } | |
| 426 | 新增: } else if (!strcmp(name, "accountDevice")) { | |
| 427 | 新增: if (!strcmp(text_member(request, "operation"), "status")) reply_json(reply, context, "{\"supported\":false}"); | |
| 428 | 新增: else reply_error(reply, "Linux 版本使用 Cage 账户密码解锁。"); | |
| 429 | 新增: } else if (!strcmp(name, "appUpdate")) { | |
| 430 | 新增: const char *operation = text_member(request, "operation"); | |
| 431 | 新增: if (strcmp(operation, "status") && strcmp(operation, "check") && strcmp(operation, "install") && strcmp(operation, "cancel")) | |
| 432 | 新增: reply_error(reply, "更新操作无效。"); | |
| 433 | 新增: else { | |
| 434 | 新增: char *version = quote(CAGE_VERSION); | |
| 435 | 新增: char *state = g_strdup_printf("{\"phase\":\"manual\",\"currentVersion\":%s,\"message\":\"Linux 版本使用系统安装包更新。请保存工作、停止环境并退出 Cage,再安装新版 .deb;用户数据会保留。\"}", version); | |
| 436 | 新增: reply_json(reply, context, state); | |
| 437 | 新增: g_free(state); g_free(version); | |
| 438 | 新增: } | |
| 439 | 新增: } else if (!strcmp(name, "saveBrowserDownload") || !strcmp(name, "browserDownloadAction")) { | |
| 440 | 新增: const char *id = text_member(request, "id"); | |
| 441 | 新增: const char *operation = !strcmp(name, "saveBrowserDownload") ? "save" : text_member(request, "operation"); | |
| 442 | 新增: if (!g_uuid_string_is_valid(id) || (strcmp(operation,"save") && strcmp(operation,"open") && strcmp(operation,"reveal"))) { | |
| 443 | 新增: reply_error(reply, "下载操作无效。"); | |
| 444 | 新增: } else if (app.picker_open) { | |
| 445 | 新增: reply_error(reply, "请先完成当前文件窗口。"); | |
| 446 | 新增: } else { | |
| 447 | 新增: char *path = NULL; | |
| 448 | 新增: if (!strcmp(operation,"save")) { | |
| 449 | 新增: app.picker_open = TRUE; | |
| 450 | 新增: GtkWidget *dialog = gtk_file_chooser_dialog_new("将下载另存为到本机", GTK_WINDOW(app.window), GTK_FILE_CHOOSER_ACTION_SAVE, | |
| 451 | 新增: "取消", GTK_RESPONSE_CANCEL, "保存", GTK_RESPONSE_ACCEPT, NULL); | |
| 452 | 新增: char *base = g_path_get_basename(text_member(request,"name")); | |
| 453 | 新增: gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), *base ? base : "download"); | |
| 454 | 新增: gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); | |
| 455 | 新增: if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); | |
| 456 | 新增: gtk_widget_destroy(dialog); g_free(base); app.picker_open = FALSE; | |
| 457 | 新增: } | |
| 458 | 新增: if (!strcmp(operation,"save") && !path) reply_json(reply,context,"{\"canceled\":true}"); | |
| 459 | 新增: else { | |
| 460 | 新增: const char *args[] = {app.backend,"browser-file","--json",operation,id,path,NULL}; | |
| 461 | 新增: backend_arguments(args,1800,browser_file_finished,pending_reply(reply,context)); | |
| 462 | 新增: } | |
| 463 | 新增: g_free(path); | |
| 464 | 新增: } | |
| 465 | 新增: } else if (!strcmp(name, "chooseFolder")) { | |
| 466 | 新增: if (app.picker_open) reply_error(reply, "请先完成当前文件选择。"); | |
| 467 | 新增: else { | |
| 468 | 新增: char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, "仅此文件夹会与 Cage 共享。请选择具体项目。", NULL); | |
| 469 | 新增: reply_string(reply, context, path ? path : ""); | |
| 470 | 新增: g_free(path); | |
| 471 | 新增: } | |
| 472 | 新增: } else if (!strcmp(name, "clipboardRead")) { | |
| 473 | 新增: gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), clipboard_received, pending_reply(reply, context)); | |
| 474 | 新增: } else if (!strcmp(name, "clipboardReadContent")) { | |
| 475 | 新增: gtk_clipboard_request_image(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), clipboard_content_image, pending_reply(reply, context)); | |
| 476 | 新增: } else if (!strcmp(name, "clipboardWrite")) { | |
| 477 | 新增: const char *text = text_member(request, "text"); | |
| 478 | 新增: GtkClipboard *clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); | |
| 479 | 新增: gtk_clipboard_set_text(clipboard, text, -1); | |
| 480 | 新增: gtk_clipboard_store(clipboard); | |
| 481 | 新增: reply_json(reply, context, "true"); | |
| 482 | 新增: } else if (!strcmp(name, "appearance")) { | |
| 483 | 新增: const char *mode = text_member(request, "mode"); | |
| 484 | 新增: const char *background = text_member(request, "background"); | |
| 485 | 新增: GdkRGBA color; | |
| 486 | 新增: gboolean valid = (!strcmp(mode, "light") || !strcmp(mode, "dark") || !strcmp(mode, "system")) && | |
| 487 | 新增: strlen(background) == 7 && background[0] == '#' && strspn(background + 1, "0123456789abcdefABCDEF") == 6 && | |
| 488 | 新增: gdk_rgba_parse(&color, background); | |
| 489 | 新增: if (!valid) reply_error(reply, "外观参数无效。"); | |
| 490 | 新增: else { | |
| 491 | 新增: g_object_set(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", | |
| 492 | 新增: !strcmp(mode, "system") ? app.initial_dark : !strcmp(mode, "dark"), NULL); | |
| 493 | 新增: webkit_web_view_set_background_color(app.web, &color); | |
| 494 | 新增: reply_json(reply, context, "true"); | |
| 495 | 新增: } | |
| 496 | 新增: } else if (!strcmp(name, "importTheme")) { | |
| 497 | 新增: if (app.picker_open) reply_error(reply, "请先完成当前文件选择。"); | |
| 498 | 新增: else { | |
| 499 | 新增: char *path = choose_file(GTK_FILE_CHOOSER_ACTION_OPEN, "导入主题", NULL); | |
| 500 | 新增: if (!path) reply_string(reply, context, ""); | |
| 501 | 新增: else { | |
| 502 | 新增: /* Only read a regular local file, with a hard allocation bound. */ | |
| 503 | 新增: GFile *file = g_file_new_for_path(path); | |
| 504 | 新增: GFileInfo *info = g_file_query_info(file, G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE, | |
| 505 | 新增: G_FILE_QUERY_INFO_NONE, NULL, NULL); | |
| 506 | 新增: gboolean regular = info && g_file_info_get_file_type(info) == G_FILE_TYPE_REGULAR && g_file_info_get_size(info) <= MAX_THEME; | |
| 507 | 新增: GFileInputStream *stream = regular ? g_file_read(file, NULL, NULL) : NULL; | |
| 508 | 新增: char *contents = g_malloc(MAX_THEME + 2); | |
| 509 | 新增: gsize length = 0; | |
| 510 | 新增: gboolean ok = stream && g_input_stream_read_all(G_INPUT_STREAM(stream), contents, MAX_THEME + 1, &length, NULL, NULL); | |
| 511 | 新增: if (ok && length <= MAX_THEME && g_utf8_validate(contents, length, NULL) && !memchr(contents, 0, length)) { | |
| 512 | 新增: contents[length] = 0; | |
| 513 | 新增: reply_string(reply, context, contents); | |
| 514 | 新增: } else reply_error(reply, "请选择不超过 256 KB 的 UTF-8 JSON 主题文件。"); | |
| 515 | 新增: g_clear_object(&stream); g_clear_object(&info); g_object_unref(file); g_free(contents); | |
| 516 | 新增: } | |
| 517 | 新增: g_free(path); | |
| 518 | 新增: } | |
| 519 | 新增: } else if (!strcmp(name, "exportTheme")) { | |
| 520 | 新增: const char *contents = text_member(request, "text"); | |
| 521 | 新增: JsonParser *theme_parser = json_parser_new(); | |
| 522 | 新增: gboolean valid = strlen(contents) <= MAX_THEME && json_parser_load_from_data(theme_parser, contents, -1, NULL) && | |
| 523 | 新增: JSON_NODE_HOLDS_OBJECT(json_parser_get_root(theme_parser)); | |
| 524 | 新增: JsonObject *theme = valid ? json_node_get_object(json_parser_get_root(theme_parser)) : NULL; | |
| 525 | 新增: JsonNode *version = theme ? json_object_get_member(theme, "version") : NULL; | |
| 526 | 新增: valid = theme && !strcmp(text_member(theme, "format"), "cage-theme") && version && | |
| 527 | 新增: JSON_NODE_HOLDS_VALUE(version) && json_node_get_value_type(version) == G_TYPE_INT64 && json_node_get_int(version) == 1; | |
| 528 | 新增: if (!valid) reply_error(reply, "主题文件格式无效。"); | |
| 529 | 新增: else if (app.picker_open) reply_error(reply, "请先完成当前文件选择。"); | |
| 530 | 新增: else { | |
| 531 | 新增: char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SAVE, "导出主题", text_member(request, "filename")); | |
| 532 | 新增: if (!path) reply_json(reply, context, "false"); | |
| 533 | 新增: else if (g_file_set_contents(path, contents, -1, NULL)) reply_json(reply, context, "true"); | |
| 534 | 新增: else reply_error(reply, "主题未能导出,请检查保存位置的权限。"); | |
| 535 | 新增: g_free(path); | |
| 536 | 新增: } | |
| 537 | 新增: g_object_unref(theme_parser); | |
| 538 | 新增: } else if (!strcmp(name, "refreshSession")) { | |
| 539 | 新增: backend("desktop", app.needs_update ? "--existing" : NULL, session_refreshed, pending_reply(reply, context)); | |
| 540 | 新增: } else if (!strcmp(name, "reconnect")) { | |
| 541 | 新增: reply_json(reply, context, "true"); bootstrap(NULL); | |
| 542 | 新增: } else if (!strcmp(name, "quitNow")) { | |
| 543 | 新增: reply_json(reply, context, "true"); g_idle_add(quit_idle, NULL); | |
| 544 | 新增: } else reply_error(reply, "未知原生操作。"); | |
| 545 | 新增:done: | |
| 546 | 新增: g_free(json); g_object_unref(parser); | |
| 547 | 新增: return TRUE; | |
| 548 | 新增:} | |
| 549 | 新增:static void install_bridge(void) { | |
| 550 | 新增: /* WebKitGTK does not expose the sender frame on its reply signal. Only the | |
| 551 | 新增: * exact workbench's top document receives this nonce; the host validates it | |
| 552 | 新增: * again, and the workbench CSP prohibits frames. The raw transport alone | |
| 553 | 新增: * confers no native capabilities. */ | |
| 554 | 新增: g_free(app.token); | |
| 555 | 新增: app.token = g_uuid_string_random(); | |
| 556 | 新增: char *token = quote(app.token); | |
| 557 | 新增: char *code = g_strdup_printf( | |
| 558 | 新增: "(()=>{'use strict';window.cageLinuxBridgeInit='injected';if(window!==window.top||location.protocol!=='http:'||location.hostname!=='localhost'||location.port!=='%d')return;" | |
| 559 | 新增: "window.cageLinuxBridgeInit='origin-valid';try{" | |
| 560 | 新增: "const transport=window.webkit.messageHandlers.cageTransport;const token=%s;" | |
| 561 | 新增: "const cage=Object.freeze({postMessage(request){return transport.postMessage({token,request});}});" | |
| 562 | 新增: "Object.defineProperty(window.webkit.messageHandlers,'cage',{value:cage,writable:false,configurable:false});" | |
| 563 | 新增: "window.cageLinuxBridgeInit='ready';}catch(error){window.cageLinuxBridgeInit=error.name;}" | |
| 564 | 新增: "})();", app.port, token); | |
| 565 | 新增: /* The host allowlist narrows injection; the script and native receiver | |
| 566 | 新增: * both enforce the exact controller port. */ | |
| 567 | 新增: char *origin = g_strdup("http://localhost/*"); | |
| 568 | 新增: const char *allowed[] = {origin, NULL}; | |
| 569 | 新增: WebKitUserScript *user_script = webkit_user_script_new(code, WEBKIT_USER_CONTENT_INJECT_TOP_FRAME, | |
| 570 | 新增: WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, allowed, NULL); | |
| 571 | 新增: webkit_user_content_manager_remove_all_scripts(app.content); | |
| 572 | 新增: webkit_user_content_manager_add_script(app.content, user_script); | |
| 573 | 新增: webkit_user_script_unref(user_script); | |
| 574 | 新增: g_free(code); g_free(origin); g_free(token); | |
| 575 | 新增:} | |
| 576 | 新增:static void bootstrapped(JsonObject *object, const GError *error, gpointer data) { | |
| 577 | 新增: (void)data; | |
| 578 | 新增: app.bootstrapping = FALSE; | |
| 579 | 新增: gtk_widget_set_sensitive(app.retry, TRUE); | |
| 580 | 新增: if (error) { show_error(error->message); return; } | |
| 581 | 新增: const char *status = text_member(object, "status"); | |
| 582 | 新增: app.needs_update = strcmp(status, "ready") != 0; | |
| 583 | 新增: if (!strcmp(status, "upgrade_pending")) { | |
| 584 | 新增: gtk_label_set_text(GTK_LABEL(app.status), text_member(object, "message")); | |
| 585 | 新增: gtk_widget_show(app.existing); gtk_widget_show(app.complete); | |
| 586 | 新增: return; | |
| 587 | 新增: } | |
| 588 | 新增: const char *url = text_member(object, "url"); | |
| 589 | 新增: if ((strcmp(status, "ready") && strcmp(status, "existing")) || !valid_workbench(url, 0, TRUE)) { | |
| 590 | 新增: show_error("后台返回了无效的工作台入口。"); return; | |
| 591 | 新增: } | |
| 592 | 新增: GUri *uri = g_uri_parse(url, G_URI_FLAGS_NONE, NULL); | |
| 593 | 新增: app.port = g_uri_get_port(uri); | |
| 594 | 新增: g_uri_unref(uri); | |
| 595 | 新增: app.ready = FALSE; | |
| 596 | 新增: install_bridge(); | |
| 597 | 新增: gtk_window_set_title(GTK_WINDOW(app.window), app.needs_update ? "Cage(更新待完成)" : "Cage"); | |
| 598 | 新增: webkit_web_view_load_uri(app.web, url); | |
| 599 | 新增:} | |
| 600 | 新增:static void bootstrap(const char *option) { | |
| 601 | 新增: if (app.bootstrapping) return; | |
| 602 | 新增: app.bootstrapping = TRUE; | |
| 603 | 新增: gtk_label_set_text(GTK_LABEL(app.status), "正在连接 Cage 工作台…"); | |
| 604 | 新增: gtk_stack_set_visible_child_name(GTK_STACK(app.stack), "status"); | |
| 605 | 新增: gtk_widget_hide(app.retry); gtk_widget_hide(app.existing); gtk_widget_hide(app.complete); | |
| 606 | 新增: backend("desktop", option, bootstrapped, NULL); | |
| 607 | 新增:} | |
| 608 | 新增:static void retry_clicked(GtkButton *button, gpointer data) { (void)button; (void)data; bootstrap(NULL); } | |
| 609 | 新增:static void existing_clicked(GtkButton *button, gpointer data) { (void)button; (void)data; bootstrap("--existing"); } | |
| 610 | 新增:static void complete_clicked(GtkButton *button, gpointer data) { | |
| 611 | 新增: (void)button; (void)data; | |
| 612 | 新增: GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(app.window), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_OK_CANCEL, | |
| 613 | 新增: "请先保存文件。继续后将停止 Cage 环境并完成后台更新,终端任务会结束,项目和登录状态会保留。"); | |
| 614 | 新增: gboolean accepted = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK; | |
| 615 | 新增: gtk_widget_destroy(dialog); | |
| 616 | 新增: if (accepted) bootstrap("--complete-update"); | |
| 617 | 新增:} | |
| 618 | 新增:static gboolean decide_policy(WebKitWebView *web, WebKitPolicyDecision *decision, WebKitPolicyDecisionType type, gpointer data) { | |
| 619 | 新增: (void)web; (void)data; | |
| 620 | 新增: if (type == WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) { webkit_policy_decision_ignore(decision); return TRUE; } | |
| 621 | 新增: if (type == WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION) { | |
| 622 | 新增: WebKitNavigationAction *navigation = webkit_navigation_policy_decision_get_navigation_action(WEBKIT_NAVIGATION_POLICY_DECISION(decision)); | |
| 623 | 新增: const char *uri = webkit_uri_request_get_uri(webkit_navigation_action_get_request(navigation)); | |
| 624 | 新增: if (!valid_workbench(uri, app.port, FALSE)) { webkit_policy_decision_ignore(decision); return TRUE; } | |
| 625 | 新增: } | |
| 626 | 新增: return FALSE; | |
| 627 | 新增:} | |
| 628 | 新增:static gboolean deny_permission(WebKitWebView *web, WebKitPermissionRequest *request, gpointer data) { | |
| 629 | 新增: (void)web; (void)data; webkit_permission_request_deny(request); return TRUE; | |
| 630 | 新增:} | |
| 631 | 新增:static gboolean workbench_file_chooser(WebKitWebView *web, WebKitFileChooserRequest *request, gpointer data) { | |
| 632 | 新增: (void)data; | |
| 633 | 新增: /* Browser uploads, avatars and imports use the host's native HTML chooser. */ | |
| 634 | 新增: if (valid_workbench(webkit_web_view_get_uri(web), app.port, FALSE)) return FALSE; | |
| 635 | 新增: webkit_file_chooser_request_cancel(request); | |
| 636 | 新增: return TRUE; | |
| 637 | 新增:} | |
| 638 | 新增:static void deny_download(WebKitWebContext *context, WebKitDownload *download, gpointer data) { | |
| 639 | 新增: (void)context; (void)data; webkit_download_cancel(download); | |
| 640 | 新增:} | |
| 641 | 新增:static gboolean deny_context_menu(WebKitWebView *web, WebKitContextMenu *menu, GdkEvent *event, WebKitHitTestResult *hit, gpointer data) { | |
| 642 | 新增: (void)web; (void)menu; (void)event; (void)hit; (void)data; return TRUE; | |
| 643 | 新增:} | |
| 644 | 新增:static void load_changed(WebKitWebView *web, WebKitLoadEvent event, gpointer data) { | |
| 645 | 新增: (void)data; | |
| 646 | 新增: if (event == WEBKIT_LOAD_STARTED) app.navigation_failed = FALSE; | |
| 647 | 新增: if (event == WEBKIT_LOAD_FINISHED && !app.navigation_failed && valid_workbench(webkit_web_view_get_uri(web), app.port, FALSE)) { | |
| 648 | 新增: gtk_stack_set_visible_child_name(GTK_STACK(app.stack), "web"); | |
| 649 | 新增: gtk_widget_grab_focus(GTK_WIDGET(web)); | |
| 650 | 新增: publish_visibility(); | |
| 651 | 新增: } | |
| 652 | 新增:} | |
| 653 | 新增:static gboolean load_failed(WebKitWebView *web, WebKitLoadEvent event, const char *uri, GError *error, gpointer data) { | |
| 654 | 新增: (void)web; (void)event; (void)uri; (void)error; (void)data; | |
| 655 | 新增: app.navigation_failed = TRUE; | |
| 656 | 新增: show_error("无法连接 Cage 工作台。后台任务保留,可重试连接。"); | |
| 657 | 新增: return TRUE; | |
| 658 | 新增:} | |
| 659 | 新增:static void process_terminated(WebKitWebView *web, WebKitWebProcessTerminationReason reason, gpointer data) { | |
| 660 | 新增: (void)web; (void)reason; (void)data; | |
| 661 | 新增: show_error("工作台显示进程已退出。后台任务保留,可重试连接。"); | |
| 662 | 新增:} | |
| 663 | 新增:static void menu_action(GSimpleAction *simple, GVariant *parameter, gpointer data) { | |
| 664 | 新增: (void)parameter; (void)data; | |
| 665 | 新增: const char *name = g_action_get_name(G_ACTION(simple)); | |
| 666 | 新增: if (!strcmp(name, "closeWindow")) { gtk_widget_hide(app.window); publish_visibility(); } | |
| 667 | 新增: else if (!strcmp(name, "quit")) { | |
| 668 | 新增: if (gtk_stack_get_visible_child(GTK_STACK(app.stack)) == GTK_WIDGET(app.web)) action("quit"); | |
| 669 | 新增: else g_application_quit(G_APPLICATION(app.application)); | |
| 670 | 新增: } else if (!strcmp(name, "updates")) { | |
| 671 | 新增: GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(app.window), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, | |
| 672 | 新增: "Linux 版本通过安装包更新。请保存文件、停止环境并退出 Cage,再安装已核对摘要的官方新版本。"); | |
| 673 | 新增: gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); | |
| 674 | 新增: } else if (!strcmp(name, "about")) { | |
| 675 | 新增: gtk_show_about_dialog(GTK_WINDOW(app.window), "program-name", "Cage", "version", CAGE_VERSION, | |
| 676 | 新增: "comments", "本机隔离编码工作区", "license-type", GTK_LICENSE_MIT_X11, NULL); | |
| 677 | 新增: } else action(name); | |
| 678 | 新增:} | |
| 679 | 新增:static void add_menu_action(GMenu *menu, const char *name, const char *label, const char *accelerator) { | |
| 680 | 新增: GSimpleAction *simple = g_simple_action_new(name, NULL); | |
| 681 | 新增: g_signal_connect(simple, "activate", G_CALLBACK(menu_action), NULL); | |
| 682 | 新增: g_action_map_add_action(G_ACTION_MAP(app.application), G_ACTION(simple)); | |
| 683 | 新增: g_object_unref(simple); | |
| 684 | 新增: char *full = g_strconcat("app.", name, NULL); | |
| 685 | 新增: g_menu_append(menu, label, full); | |
| 686 | 新增: if (accelerator) { | |
| 687 | 新增: const char *accelerators[] = {accelerator, NULL}; | |
| 688 | 新增: gtk_application_set_accels_for_action(app.application, full, accelerators); | |
| 689 | 新增: } | |
| 690 | 新增: g_free(full); | |
| 691 | 新增:} | |
| 692 | 新增:static void create_window(void) { | |
| 693 | 新增: app.window = gtk_application_window_new(app.application); | |
| 694 | 新增: gtk_window_set_title(GTK_WINDOW(app.window), "Cage"); | |
| 695 | 新增: gtk_window_set_default_size(GTK_WINDOW(app.window), 1280, 850); | |
| 696 | 新增: gtk_widget_set_size_request(app.window, 820, 580); | |
| 697 | 新增: gtk_window_set_icon_name(GTK_WINDOW(app.window), "io.github.lee_xeo.Cage"); | |
| 698 | 新增: g_signal_connect(app.window, "delete-event", G_CALLBACK(close_window), NULL); | |
| 699 | 新增: g_signal_connect(app.window, "window-state-event", G_CALLBACK(visibility_changed), NULL); | |
| 700 | 新增: g_signal_connect(app.window, "map-event", G_CALLBACK(visibility_changed), NULL); | |
| 701 | 新增: g_signal_connect(app.window, "unmap-event", G_CALLBACK(visibility_changed), NULL); | |
| 702 | 新增: g_object_get(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", &app.initial_dark, NULL); | |
| 703 | 新增: GtkWidget *layout = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); | |
| 704 | 新增: gtk_container_add(GTK_CONTAINER(app.window), layout); | |
| 705 | 新增: GMenu *menu = g_menu_new(), *file = g_menu_new(), *settings = g_menu_new(), *help = g_menu_new(); | |
| 706 | 新增: /* Workbench shortcuts stay in JavaScript so terminal/browser focus rules apply. */ | |
| 707 | 新增: add_menu_action(file, "openProject", "打开项目…", NULL); | |
| 708 | 新增: add_menu_action(file, "newTab", "新建网页", NULL); | |
| 709 | 新增: add_menu_action(file, "newTerminal", "新建终端", NULL); | |
| 710 | 新增: add_menu_action(file, "closeTab", "关闭当前标签", NULL); | |
| 711 | 新增: add_menu_action(file, "closeWindow", "关闭窗口(保留环境)", NULL); | |
| 712 | 新增: add_menu_action(file, "quit", "退出 Cage…", "<Primary>q"); | |
| 713 | 新增: add_menu_action(settings, "settings", "打开设置", NULL); | |
| 714 | 新增: add_menu_action(settings, "updates", "应用更新…", NULL); | |
| 715 | 新增: add_menu_action(help, "about", "关于 Cage", NULL); | |
| 716 | 新增: g_menu_append_submenu(menu, "文件", G_MENU_MODEL(file)); | |
| 717 | 新增: g_menu_append_submenu(menu, "设置", G_MENU_MODEL(settings)); | |
| 718 | 新增: g_menu_append_submenu(menu, "帮助", G_MENU_MODEL(help)); | |
| 719 | 新增: gtk_box_pack_start(GTK_BOX(layout), gtk_menu_bar_new_from_model(G_MENU_MODEL(menu)), FALSE, FALSE, 0); | |
| 720 | 新增: g_object_unref(menu); g_object_unref(file); g_object_unref(settings); g_object_unref(help); | |
| 721 | 新增: app.stack = gtk_stack_new(); | |
| 722 | 新增: gtk_box_pack_start(GTK_BOX(layout), app.stack, TRUE, TRUE, 0); | |
| 723 | 新增: GtkWidget *status_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 16); | |
| 724 | 新增: gtk_widget_set_margin_start(status_box, 48); gtk_widget_set_margin_end(status_box, 48); | |
| 725 | 新增: gtk_widget_set_margin_top(status_box, 48); gtk_widget_set_valign(status_box, GTK_ALIGN_START); | |
| 726 | 新增: app.status = gtk_label_new("正在启动 Cage 工作台…"); | |
| 727 | 新增: gtk_label_set_line_wrap(GTK_LABEL(app.status), TRUE); | |
| 728 | 新增: gtk_label_set_xalign(GTK_LABEL(app.status), 0); | |
| 729 | 新增: gtk_box_pack_start(GTK_BOX(status_box), app.status, FALSE, FALSE, 0); | |
| 730 | 新增: app.retry = gtk_button_new_with_label("重试连接"); | |
| 731 | 新增: app.existing = gtk_button_new_with_label("打开现有环境保存文件"); | |
| 732 | 新增: app.complete = gtk_button_new_with_label("保存后停止环境并完成更新"); | |
| 733 | 新增: GtkWidget *buttons[] = {app.retry, app.existing, app.complete}; | |
| 734 | 新增: for (guint i = 0; i < G_N_ELEMENTS(buttons); i++) { | |
| 735 | 新增: gtk_widget_set_halign(buttons[i], GTK_ALIGN_START); | |
| 736 | 新增: gtk_box_pack_start(GTK_BOX(status_box), buttons[i], FALSE, FALSE, 0); | |
| 737 | 新增: } | |
| 738 | 新增: g_signal_connect(app.retry, "clicked", G_CALLBACK(retry_clicked), NULL); | |
| 739 | 新增: g_signal_connect(app.existing, "clicked", G_CALLBACK(existing_clicked), NULL); | |
| 740 | 新增: g_signal_connect(app.complete, "clicked", G_CALLBACK(complete_clicked), NULL); | |
| 741 | 新增: gtk_stack_add_named(GTK_STACK(app.stack), status_box, "status"); | |
| 742 | 新增: /* Workbench layout persists within this private Cage profile. No system | |
| 743 | 新增: * browser profile or guest browser data is shared with this WebView. */ | |
| 744 | 新增: WebKitWebsiteDataManager *storage = webkit_website_data_manager_new( | |
| 745 | 新增: "base-data-directory", app.web_data, "base-cache-directory", app.web_cache, NULL); | |
| 746 | 新增: WebKitWebContext *context = webkit_web_context_new_with_website_data_manager(storage); | |
| 747 | 新增: g_object_unref(storage); | |
| 748 | 新增: webkit_web_context_set_sandbox_enabled(context, TRUE); | |
| 749 | 新增: webkit_website_data_manager_set_network_proxy_settings(webkit_web_context_get_website_data_manager(context), WEBKIT_NETWORK_PROXY_MODE_NO_PROXY, NULL); | |
| 750 | 新增: g_signal_connect(context, "download-started", G_CALLBACK(deny_download), NULL); | |
| 751 | 新增: app.content = webkit_user_content_manager_new(); | |
| 752 | 新增: g_signal_connect(app.content, "script-message-with-reply-received::cageTransport", G_CALLBACK(bridge_received), NULL); | |
| 753 | 新增: webkit_user_content_manager_register_script_message_handler_with_reply(app.content, "cageTransport", NULL); | |
| 754 | 新增: app.web = WEBKIT_WEB_VIEW(g_object_new(WEBKIT_TYPE_WEB_VIEW, "web-context", context, "user-content-manager", app.content, NULL)); | |
| 755 | 新增: g_object_unref(context); | |
| 756 | 新增: WebKitSettings *web_settings = webkit_web_view_get_settings(app.web); | |
| 757 | 新增: webkit_settings_set_enable_developer_extras(web_settings, FALSE); | |
| 758 | 新增: webkit_settings_set_javascript_can_open_windows_automatically(web_settings, FALSE); | |
| 759 | 新增: webkit_settings_set_enable_write_console_messages_to_stdout(web_settings, FALSE); | |
| 760 | 新增: g_signal_connect(app.web, "decide-policy", G_CALLBACK(decide_policy), NULL); | |
| 761 | 新增: g_signal_connect(app.web, "permission-request", G_CALLBACK(deny_permission), NULL); | |
| 762 | 新增: g_signal_connect(app.web, "run-file-chooser", G_CALLBACK(workbench_file_chooser), NULL); | |
| 763 | 新增: g_signal_connect(app.web, "context-menu", G_CALLBACK(deny_context_menu), NULL); | |
| 764 | 新增: g_signal_connect(app.web, "load-changed", G_CALLBACK(load_changed), NULL); | |
| 765 | 新增: g_signal_connect(app.web, "load-failed", G_CALLBACK(load_failed), NULL); | |
| 766 | 新增: g_signal_connect(app.web, "web-process-terminated", G_CALLBACK(process_terminated), NULL); | |
| 767 | 新增: gtk_stack_add_named(GTK_STACK(app.stack), GTK_WIDGET(app.web), "web"); | |
| 768 | 新增: gtk_widget_show_all(app.window); | |
| 769 | 新增: bootstrap(NULL); | |
| 770 | 新增:} | |
| 771 | 新增:static void activate(GtkApplication *application, gpointer data) { | |
| 772 | 新增: (void)application; (void)data; | |
| 773 | 新增: if (!app.window) create_window(); | |
| 774 | 新增: else { gtk_widget_show(app.window); gtk_window_deiconify(GTK_WINDOW(app.window)); gtk_window_present(GTK_WINDOW(app.window)); publish_visibility(); } | |
| 775 | 新增:} | |
| 776 | 新增:static gboolean smoke_deadline(gpointer data) { | |
| 777 | 新增: (void)data; | |
| 778 | 新增: g_printerr("Linux smoke: timed out before a ready, authenticated workbench.\n"); | |
| 779 | 新增: g_application_quit(G_APPLICATION(app.application)); | |
| 780 | 新增: return G_SOURCE_REMOVE; | |
| 781 | 新增:} | |
| 782 | 新增:static void smoke_diagnostics_ready(GObject *source, GAsyncResult *result, gpointer data) { | |
| 783 | 新增: (void)data; | |
| 784 | 新增: GError *error = NULL; | |
| 785 | 新增: JSCValue *value = webkit_web_view_call_async_javascript_function_finish(WEBKIT_WEB_VIEW(source), result, &error); | |
| 786 | 新增: if (value) { | |
| 787 | 新增: char *json = jsc_value_to_json(value, 0); | |
| 788 | 新增: g_printerr("Linux smoke startup diagnostics: %s\n", json ? json : "unavailable"); | |
| 789 | 新增: g_free(json); g_object_unref(value); | |
| 790 | 新增: } else g_printerr("Linux smoke: JavaScript diagnostics unavailable.\n"); | |
| 791 | 新增: g_clear_error(&error); | |
| 792 | 新增:} | |
| 793 | 新增:static gboolean smoke_diagnostics(gpointer data) { | |
| 794 | 新增: (void)data; | |
| 795 | 新增: if (app.ready || !app.web) return G_SOURCE_REMOVE; | |
| 796 | 新增: const char *body = | |
| 797 | 新增: "const account=await fetch('/api/account');const state=await fetch('/api/status');const settings=await fetch('/api/settings');" | |
| 798 | 新增: "let unlocked=false;try{unlocked=(await account.json()).unlocked===true;}catch{}" | |
| 799 | 新增: "const descriptor=Object.getOwnPropertyDescriptor(window,'webkit');" | |
| 800 | 新增: "return {bridgeAvailable:!!window.webkit?.messageHandlers?.cage,bridgeInit:window.cageLinuxBridgeInit||'not-injected',webkitConfigurable:descriptor?.configurable,transportPresent:!!window.webkit?.messageHandlers?.cageTransport,readyState:document.readyState," | |
| 801 | 新增: "renderedButtons:document.querySelectorAll('button').length,accountStatus:account.status,accountUnlocked:unlocked,statusStatus:state.status,settingsStatus:settings.status};"; | |
| 802 | 新增: webkit_web_view_call_async_javascript_function(app.web, body, -1, NULL, NULL, "cage-smoke-diagnostics", NULL, smoke_diagnostics_ready, NULL); | |
| 803 | 新增: return G_SOURCE_REMOVE; | |
| 804 | 新增:} | |
| 805 | 新增:static int self_test(void) { | |
| 806 | 新增: g_assert_true(valid_workbench("http://localhost:23456/#secret", 23456, TRUE)); | |
| 807 | 新增: g_assert_true(valid_workbench("http://localhost:23456/", 23456, FALSE)); | |
| 808 | 新增: g_assert_false(valid_workbench("http://localhost:23456/", 23456, TRUE)); | |
| 809 | 新增: g_assert_false(valid_workbench("http://localhost:23457/#secret", 23456, TRUE)); | |
| 810 | 新增: g_assert_false(valid_workbench("http://127.0.0.1:23456/#secret", 23456, TRUE)); | |
| 811 | 新增: g_assert_false(valid_workbench("http://localhost.evil.test:23456/#secret", 23456, TRUE)); | |
| 812 | 新增: g_assert_false(valid_workbench("http://user@localhost:23456/#secret", 23456, TRUE)); | |
| 813 | 新增: g_assert_false(valid_workbench("https://localhost:23456/#secret", 23456, TRUE)); | |
| 814 | 新增: g_assert_false(valid_workbench("file:///tmp/workbench.html", 0, FALSE)); | |
| 815 | 新增: g_assert_false(valid_workbench("javascript:alert(1)", 0, FALSE)); | |
| 816 | 新增: g_assert_false(valid_workbench("http://localhost:80/#secret", 0, TRUE)); | |
| 817 | 新增: g_print("Linux desktop origin policy: 11 checks passed.\n"); | |
| 818 | 新增: return 0; | |
| 819 | 新增:} | |
| 820 | 新增:int main(int argc, char **argv) { | |
| 821 | 新增: if (argc == 2 && !strcmp(argv[1], "--self-test")) return self_test(); | |
| 822 | 新增: if (argc == 2 && !strcmp(argv[1], "--version")) { g_print("Cage %s\n", CAGE_VERSION); return 0; } | |
| 823 | 新增: if (argc == 3 && !strcmp(argv[1], "--smoke-test") && g_path_is_absolute(argv[2]) && g_getenv("CLAUDE_CAGE_CONFIG")) { | |
| 824 | 新增: app.smoke_output = g_strdup(argv[2]); app.result = 1; | |
| 825 | 新增: app.storage_phase = g_getenv("CAGE_SMOKE_STORAGE_PHASE"); | |
| 826 | 新增: app.storage_marker = g_getenv("CAGE_SMOKE_STORAGE_MARKER"); | |
| 827 | 新增: if (app.storage_phase && (g_strcmp0(app.storage_phase, "seed") && g_strcmp0(app.storage_phase, "verify"))) return 2; | |
| 828 | 新增: if (app.storage_phase && (!app.storage_marker || !*app.storage_marker || strlen(app.storage_marker) > 128)) return 2; | |
| 829 | 新增: } else if (argc != 1) { | |
| 830 | 新增: g_printerr("Usage: cage-desktop [--version | --self-test | --smoke-test /absolute/report.json]\nSmoke tests require an isolated CLAUDE_CAGE_CONFIG with an unlocked test account.\n"); | |
| 831 | 新增: return 2; | |
| 832 | 新增: } | |
| 833 | 新增: if (geteuid() == 0) { g_printerr("Cage 桌面需要以普通用户运行,请勿使用 sudo 启动。\n"); return 1; } | |
| 834 | 新增: char *executable = g_file_read_link("/proc/self/exe", NULL); | |
| 835 | 新增: if (!executable) { g_printerr("无法定位 Cage 安装目录。\n"); return 1; } | |
| 836 | 新增: char *directory = g_path_get_dirname(executable); | |
| 837 | 新增: app.backend = g_build_filename(directory, "cage", NULL); | |
| 838 | 新增: g_free(directory); g_free(executable); | |
| 839 | 新增: if (!g_file_test(app.backend, G_FILE_TEST_IS_EXECUTABLE)) { g_printerr("安装目录缺少 Cage 后台,请重新安装。\n"); return 1; } | |
| 840 | 新增: const char *configured = g_getenv("CLAUDE_CAGE_CONFIG"); | |
| 841 | 新增: app.profile = configured && *configured ? g_canonicalize_filename(configured, NULL) | |
| 842 | 新增: : g_build_filename(g_get_home_dir(), ".claude-cage", "config.json", NULL); | |
| 843 | 新增: g_setenv("CLAUDE_CAGE_CONFIG", app.profile, TRUE); | |
| 844 | 新增: if (!prepare_web_storage()) { | |
| 845 | 新增: g_printerr("无法创建 Cage 私有界面数据目录,请检查配置目录的所有者、权限或符号链接。\n"); | |
| 846 | 新增: return 1; | |
| 847 | 新增: } | |
| 848 | 新增: char *hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, app.profile, -1); | |
| 849 | 新增: char *id = g_strdup_printf("app.cage.desktop.p%.24s", hash); | |
| 850 | 新增: app.application = gtk_application_new(id, G_APPLICATION_DEFAULT_FLAGS); | |
| 851 | 新增: g_free(hash); g_free(id); | |
| 852 | 新增: g_signal_connect(app.application, "activate", G_CALLBACK(activate), NULL); | |
| 853 | 新增: if (app.smoke_output) { | |
| 854 | 新增: g_timeout_add_seconds(120, smoke_deadline, NULL); | |
| 855 | 新增: g_timeout_add_seconds(15, smoke_diagnostics, NULL); | |
| 856 | 新增: } | |
| 857 | 新增: int status = g_application_run(G_APPLICATION(app.application), 1, argv); | |
| 858 | 新增: if (app.window) gtk_widget_destroy(app.window); | |
| 859 | 新增: g_object_unref(app.application); | |
| 860 | 新增: g_free(app.backend); g_free(app.profile); g_free(app.token); g_free(app.smoke_output); | |
| 861 | 新增: g_free(app.web_data); g_free(app.web_cache); | |
| 862 | 新增: g_clear_object(&app.content); | |
| 863 | 新增: return status ? status : app.result; | |
| 864 | 新增:} | |
| @@ -0,0 +1,117 @@ | ||
| 1 | 新增:#!/usr/bin/env node | |
| 2 | 新增:// Run under a real Linux display or xvfb-run + dbus-run-session. | |
| 3 | 新增:import { mkdtemp, mkdir, readFile, rm, stat } from 'node:fs/promises'; | |
| 4 | 新增:import { tmpdir } from 'node:os'; | |
| 5 | 新增:import { dirname, isAbsolute, join, resolve } from 'node:path'; | |
| 6 | 新增:import { randomBytes } from 'node:crypto'; | |
| 7 | 新增:import { spawn } from 'node:child_process'; | |
| 8 | 新增: | |
| 9 | 新增:const [nativeArgument, outputArgument] = process.argv.slice(2); | |
| 10 | 新增:if (!nativeArgument || !outputArgument || process.argv.length !== 4) { | |
| 11 | 新增: console.error('Usage: test-smoke.mjs /path/to/cage-desktop /absolute/report.json'); | |
| 12 | 新增: process.exit(2); | |
| 13 | 新增:} | |
| 14 | 新增:const native = resolve(nativeArgument); | |
| 15 | 新增:const backend = join(dirname(native), 'cage'); | |
| 16 | 新增:const output = resolve(outputArgument); | |
| 17 | 新增:const root = await mkdtemp(join(tmpdir(), 'cage-linux-smoke-')); | |
| 18 | 新增:// Cage places the default workspace beside the profile; both stay in this | |
| 19 | 新增:// fixture directory so cleanup also removes the temporary workspace. | |
| 20 | 新增:const env = { ...process.env, CLAUDE_CAGE_CONFIG: join(root, 'profile', 'config.json') }; | |
| 21 | 新增:let clean = false; | |
| 22 | 新增:let result = 1; | |
| 23 | 新增: | |
| 24 | 新增:function execute(executable, args, timeout = 190000) { | |
| 25 | 新增: return new Promise((resolvePromise, reject) => { | |
| 26 | 新增: const child = spawn(executable, args, { env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] }); | |
| 27 | 新增: let stdout = '', stderr = '', overflow = false; | |
| 28 | 新增: const stopGroup = () => { | |
| 29 | 新增: try { process.kill(-child.pid, 'SIGKILL'); } catch { /* Already exited. */ } | |
| 30 | 新增: }; | |
| 31 | 新增: const timer = setTimeout(stopGroup, timeout); | |
| 32 | 新增: child.stdout.on('data', data => { | |
| 33 | 新增: stdout += data; | |
| 34 | 新增: if (stdout.length > 65536) { overflow = true; stopGroup(); } | |
| 35 | 新增: }); | |
| 36 | 新增: child.stderr.on('data', data => { | |
| 37 | 新增: stderr = (stderr + data).slice(-8192); | |
| 38 | 新增: if (executable === native && args[0] === '--smoke-test') process.stderr.write(data); | |
| 39 | 新增: }); | |
| 40 | 新增: child.on('error', error => { clearTimeout(timer); reject(error); }); | |
| 41 | 新增: // A failed native process can leave WebKit children holding its pipes open. | |
| 42 | 新增: // The controller deliberately detaches into its own group and is cleaned | |
| 43 | 新增: // through prepare-update below, never by this process-group signal. | |
| 44 | 新增: child.on('exit', (code, signal) => { if (code !== 0 || signal) stopGroup(); }); | |
| 45 | 新增: child.on('close', (code, signal) => { | |
| 46 | 新增: clearTimeout(timer); | |
| 47 | 新增: if (overflow) reject(new Error('Backend response exceeded the output limit.')); | |
| 48 | 新增: else resolvePromise({ code, signal, stdout, stderr }); | |
| 49 | 新增: }); | |
| 50 | 新增: }); | |
| 51 | 新增:} | |
| 52 | 新增:function parseBackend(run) { | |
| 53 | 新增: // Do not include stdout in errors: desktop's URL carries a session token. | |
| 54 | 新增: let data; | |
| 55 | 新增: try { data = JSON.parse(run.stdout); } catch { throw new Error('Backend returned invalid JSON.'); } | |
| 56 | 新增: if (run.code !== 0) throw new Error('Backend operation failed; inspect the isolated control.log.'); | |
| 57 | 新增: return data; | |
| 58 | 新增:} | |
| 59 | 新增: | |
| 60 | 新增:try { | |
| 61 | 新增: if (!isAbsolute(output)) throw new Error('Report path must be absolute.'); | |
| 62 | 新增: await mkdir(join(root, 'profile'), { mode: 0o700 }); | |
| 63 | 新增: await mkdir(dirname(output), { recursive: true }); | |
| 64 | 新增: await rm(output, { force: true }); | |
| 65 | 新增: await rm(output + '.png', { force: true }); | |
| 66 | 新增: const policy = await execute(native, ['--self-test'], 30000); | |
| 67 | 新增: if (policy.code !== 0) throw new Error('Native origin policy tests failed.'); | |
| 68 | 新增: const entry = parseBackend(await execute(backend, ['desktop', '--json'])); | |
| 69 | 新增: if (entry.status !== 'ready') throw new Error('Isolated backend was not ready.'); | |
| 70 | 新增: const url = new URL(entry.url); | |
| 71 | 新增: if (url.protocol !== 'http:' || url.hostname !== 'localhost' || !url.hash || url.username || url.password) | |
| 72 | 新增: throw new Error('Backend returned an invalid loopback entry.'); | |
| 73 | 新增: const authenticate = await fetch(url.origin + '/api/session', { | |
| 74 | 新增: method: 'POST', redirect: 'error', | |
| 75 | 新增: headers: { 'Origin': url.origin, 'Content-Type': 'application/json' }, | |
| 76 | 新增: body: JSON.stringify({ token: url.hash.slice(1) }), | |
| 77 | 新增: }); | |
| 78 | 新增: if (!authenticate.ok) throw new Error('Session authentication failed.'); | |
| 79 | 新增: const cookie = authenticate.headers.get('set-cookie')?.split(';')[0]; | |
| 80 | 新增: if (!cookie) throw new Error('Authenticated response did not create a session cookie.'); | |
| 81 | 新增: const password = randomBytes(24).toString('base64url'); | |
| 82 | 新增: const account = await fetch(url.origin + '/api/account/create', { | |
| 83 | 新增: method: 'POST', redirect: 'error', | |
| 84 | 新增: headers: { 'Origin': url.origin, 'Content-Type': 'application/json', 'Cookie': cookie }, | |
| 85 | 新增: body: JSON.stringify({ username: 'Linux Smoke', password, confirm_password: password }), | |
| 86 | 新增: }); | |
| 87 | 新增: if (!account.ok || !(await account.json()).unlocked) throw new Error('Could not prepare the isolated unlocked test account.'); | |
| 88 | 新增: env.CAGE_SMOKE_STORAGE_MARKER = randomBytes(24).toString('hex'); | |
| 89 | 新增: for (const phase of ['seed', 'verify']) { | |
| 90 | 新增: env.CAGE_SMOKE_STORAGE_PHASE = phase; | |
| 91 | 新增: await rm(output, { force: true }); | |
| 92 | 新增: const nativeRun = await execute(native, ['--smoke-test', output], 150000); | |
| 93 | 新增: if (nativeRun.code !== 0) throw new Error(`Native WebKit workbench ${phase} test failed.`); | |
| 94 | 新增: const pass = JSON.parse(await readFile(output, 'utf8')); | |
| 95 | 新增: if (pass.success !== true || pass.storageMarkerMatched !== true) throw new Error(`Native storage ${phase} evidence is incomplete.`); | |
| 96 | 新增: } | |
| 97 | 新增: const evidence = JSON.parse(await readFile(output, 'utf8')); | |
| 98 | 新增: for (const key of ['success', 'nativeBridgeReady', 'authenticated', 'accountUnlocked', 'workbenchRendered', 'workbenchReadyAcknowledged', 'statusReceived', 'settingsReceived', 'unauthenticatedBridgeDenied', 'localStoragePersisted']) { | |
| 99 | 新增: if (evidence[key] !== true) throw new Error(`Native smoke report lacks ${key}.`); | |
| 100 | 新增: } | |
| 101 | 新增: if ((await stat(output + '.png')).size < 1024) throw new Error('Native screenshot is missing or empty.'); | |
| 102 | 新增: for (const directory of ['webkit', 'webkit/data', 'webkit/cache']) { | |
| 103 | 新增: if ((await stat(join(root, 'profile', directory))).mode & 0o077) throw new Error('WebKit profile storage is not private.'); | |
| 104 | 新增: } | |
| 105 | 新增: result = 0; | |
| 106 | 新增: console.log(JSON.stringify({ success: true, report: output, screenshot: output + '.png', version: evidence.version })); | |
| 107 | 新增:} catch (error) { | |
| 108 | 新增: console.error(error.message); | |
| 109 | 新增:} finally { | |
| 110 | 新增: try { | |
| 111 | 新增: const stopped = parseBackend(await execute(backend, ['prepare-update', '--json'])); | |
| 112 | 新增: clean = stopped.status === 'prepared'; | |
| 113 | 新增: } catch { /* Preserve the fixture until a remaining controller can be stopped. */ } | |
| 114 | 新增: if (clean) await rm(root, { recursive: true, force: true }); | |
| 115 | 新增: else { console.error(`Cleanup incomplete; isolated profile retained at ${root}`); result = 1; } | |
| 116 | 新增:} | |
| 117 | 新增:process.exitCode = result; | |
| @@ -0,0 +1,2 @@ | ||
| 1 | 新增:bin/ | |
| 2 | 新增:obj/ | |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增:<Project Sdk="Microsoft.NET.Sdk"> | |
| 2 | 新增: <PropertyGroup> | |
| 3 | 新增: <OutputType>Exe</OutputType> | |
| 4 | 新增: <TargetFramework>net10.0</TargetFramework> | |
| 5 | 新增: <Nullable>enable</Nullable> | |
| 6 | 新增: <ImplicitUsings>enable</ImplicitUsings> | |
| 7 | 新增: </PropertyGroup> | |
| 8 | 新增: <ItemGroup> | |
| 9 | 新增: <Compile Include="../windows/UpdatePolicy.cs" Link="UpdatePolicy.cs" /> | |
| 10 | 新增: <Compile Include="../windows/Backend.cs" Link="Backend.cs" /> | |
| 11 | 新增: <Compile Include="../windows/UpdateRecovery.cs" Link="UpdateRecovery.cs" /> | |
| 12 | 新增: </ItemGroup> | |
| 13 | 新增:</Project> | |
| @@ -0,0 +1,92 @@ | ||
| 1 | 新增:using Cage.Windows; | |
| 2 | 新增: | |
| 3 | 新增:// The recovery integration tests launch a copy of this executable through the | |
| 4 | 新增:// same subprocess/JSON boundary used by the shipped updater. | |
| 5 | 新增:if (args is ["prepare-update", "--json", "--stop"]) | |
| 6 | 新增:{ | |
| 7 | 新增: File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "controller-invoked"), Environment.ProcessId.ToString()); | |
| 8 | 新增: if (File.Exists(Path.Combine(AppContext.BaseDirectory, "broken-backend"))) | |
| 9 | 新增: { | |
| 10 | 新增: Console.WriteLine("{\"status\":\"failed\"}"); Environment.Exit(7); | |
| 11 | 新增: } | |
| 12 | 新增: Console.WriteLine(File.Exists(Path.Combine(AppContext.BaseDirectory, "running-environment")) | |
| 13 | 新增: ? "{\"status\":\"stop_required\"}" : "{\"status\":\"prepared\"}"); | |
| 14 | 新增: return; | |
| 15 | 新增:} | |
| 16 | 新增: | |
| 17 | 新增:var assertions = 0; | |
| 18 | 新增:void Check(bool condition, string message) { assertions++; if (!condition) throw new Exception(message); } | |
| 19 | 新增:void Reject(Action action, string message) | |
| 20 | 新增:{ | |
| 21 | 新增: assertions++; | |
| 22 | 新增: try { action(); } catch (InvalidDataException) { return; } | |
| 23 | 新增: throw new Exception(message); | |
| 24 | 新增:} | |
| 25 | 新增:Check(UpdatePolicy.IsWorkbench("http://localhost:4321/", 4321), "expected local origin rejected"); | |
| 26 | 新增:foreach (var origin in new[] { "https://localhost:4321/", "http://localhost:4322/", "http://localhost.evil:4321/", "http://user@localhost:4321/", "http://127.0.0.1:4321/", "file:///C:/workbench.html" }) | |
| 27 | 新增: Check(!UpdatePolicy.IsWorkbench(origin, 4321), "foreign native bridge origin accepted: " + origin); | |
| 28 | 新增:Check(UpdatePolicy.Entry("http://localhost:4321/#token").Port == 4321, "entry URL rejected"); | |
| 29 | 新增:Reject(() => UpdatePolicy.Entry("http://localhost:4321/"), "entry without token accepted"); | |
| 30 | 新增:Check(UpdatePolicy.IsNewer("0.1.0-alpha.10", "0.1.0-alpha.9"), "numeric prerelease ordering"); | |
| 31 | 新增:Check(UpdatePolicy.IsNewer("0.1.0", "0.1.0-alpha.10"), "stable release ordering"); | |
| 32 | 新增:Check(UpdatePolicy.IsNewer("1.0.0-alpha.beta", "1.0.0-alpha.10"), "text prerelease ordering"); | |
| 33 | 新增:Check(!UpdatePolicy.IsNewer("0.1.0-alpha.01", "0.1.0-alpha.0"), "leading zero accepted"); | |
| 34 | 新增:Check(!UpdatePolicy.IsNewer("0.1.0-alpha.1", "0.1.0-alpha.1"), "same version accepted"); | |
| 35 | 新增:Check(!UpdatePolicy.IsNewer("0.1.0-alpha.1", "0.1.0"), "downgrade accepted"); | |
| 36 | 新增:Check(!UpdatePolicy.IsNewer("v0.2.0", "0.1.0"), "noncanonical version accepted"); | |
| 37 | 新增:Check(!UpdatePolicy.IsNewer("0.2.0+metadata", "0.1.0"), "unmatched backend version accepted"); | |
| 38 | 新增:var root = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "cage-update-policy-tests")); | |
| 39 | 新增:var good = Path.Combine(root, "download-abc", "Cage-setup.exe"); | |
| 40 | 新增:Check(UpdatePolicy.DownloadPath(good, root) == good, "private download rejected"); | |
| 41 | 新增:foreach (var path in new[] { Path.Combine(root + "-other", "download-abc", "Cage-setup.exe"), Path.Combine(root, "verified-abc", "Cage-setup.exe"), Path.Combine(root, "download-abc", "nested", "Cage-setup.exe"), Path.Combine(root, "download-abc", "Cage.exe") }) | |
| 42 | 新增: Reject(() => UpdatePolicy.DownloadPath(path, root), "untrusted download path accepted: " + path); | |
| 43 | 新增:Console.WriteLine($"Windows update/bridge policy: {assertions} assertions passed."); | |
| 44 | 新增: | |
| 45 | 新增:var integration = Path.Combine(Path.GetTempPath(), "cage-recovery-" + Guid.NewGuid()); | |
| 46 | 新增:Directory.CreateDirectory(integration); | |
| 47 | 新增:try | |
| 48 | 新增:{ | |
| 49 | 新增: var backup = Path.Combine(integration, "old application"); | |
| 50 | 新增: var candidate = Path.Combine(integration, "new application"); | |
| 51 | 新增: void InstallFixture(string app, bool broken) | |
| 52 | 新增: { | |
| 53 | 新增: var resources = Path.Combine(app, "resources"); Directory.CreateDirectory(resources); | |
| 54 | 新增: foreach (var file in Directory.EnumerateFiles(AppContext.BaseDirectory)) | |
| 55 | 新增: File.Copy(file, Path.Combine(resources, Path.GetFileName(file))); | |
| 56 | 新增: var controller = Path.Combine(resources, "cage.exe"); | |
| 57 | 新增: File.Copy(Environment.ProcessPath!, controller, true); | |
| 58 | 新增: if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(controller, File.GetUnixFileMode(Environment.ProcessPath!)); | |
| 59 | 新增: if (broken) File.WriteAllText(Path.Combine(resources, "broken-backend"), "cannot start"); | |
| 60 | 新增: } | |
| 61 | 新增: InstallFixture(backup, false); InstallFixture(candidate, true); | |
| 62 | 新增: await UpdateRecovery.PrepareRollback(backup); | |
| 63 | 新增: Check(File.Exists(Path.Combine(backup, "resources", "controller-invoked")), "recovery did not execute the old backend"); | |
| 64 | 新增: Check(!File.Exists(Path.Combine(candidate, "resources", "controller-invoked")), "recovery executed the broken candidate backend"); | |
| 65 | 新增: File.WriteAllText(Path.Combine(backup, "resources", "running-environment"), "still running"); | |
| 66 | 新增: var rejected = false; | |
| 67 | 新增: try { await UpdateRecovery.PrepareRollback(backup); } catch (IOException) { rejected = true; } | |
| 68 | 新增: Check(rejected, "recovery continued without a prepared response from the old backend"); | |
| 69 | 新增: | |
| 70 | 新增: var garbage = Path.Combine(integration, "locked backup"); Directory.CreateDirectory(garbage); | |
| 71 | 新增: var lockedFile = Path.Combine(garbage, "old.dll"); File.WriteAllText(lockedFile, "old version"); | |
| 72 | 新增: var download = Path.Combine(integration, "download"); Directory.CreateDirectory(download); | |
| 73 | 新增: var marker = Path.Combine(integration, "ack.json"); File.WriteAllText(marker, "confirmed"); | |
| 74 | 新增: var liveApp = Path.Combine(candidate, "Cage.exe"); File.WriteAllText(liveApp, "healthy new application"); | |
| 75 | 新增: FileStream? locked = null; | |
| 76 | 新增: if (OperatingSystem.IsWindows()) locked = new FileStream(lockedFile, FileMode.Open, FileAccess.Read, FileShare.Read); | |
| 77 | 新增: else File.SetUnixFileMode(garbage, UnixFileMode.UserRead | UnixFileMode.UserExecute); | |
| 78 | 新增: try | |
| 79 | 新增: { | |
| 80 | 新增: UpdateRecovery.CleanupAfterSuccess(garbage, download, marker); | |
| 81 | 新增: Check(File.ReadAllText(liveApp) == "healthy new application", "cleanup changed the confirmed new application"); | |
| 82 | 新增: Check(File.Exists(lockedFile), "fixture did not cause the intended cleanup failure"); | |
| 83 | 新增: Check(!Directory.Exists(download) && !File.Exists(marker), "one cleanup failure prevented independent cleanup"); | |
| 84 | 新增: } | |
| 85 | 新增: finally | |
| 86 | 新增: { | |
| 87 | 新增: locked?.Dispose(); | |
| 88 | 新增: if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(garbage, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); | |
| 89 | 新增: } | |
| 90 | 新增: Console.WriteLine($"Windows recovery integration: {assertions - 22} assertions passed; actual child process and filesystem failures exercised."); | |
| 91 | 新增:} | |
| 92 | 新增:finally { Directory.Delete(integration, true); } | |
| @@ -0,0 +1,2 @@ | ||
| 1 | 新增:bin/ | |
| 2 | 新增:obj/ | |
| @@ -0,0 +1,171 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Reflection; | |
| 3 | 新增:using System.Security.Cryptography; | |
| 4 | 新增:using System.Text.Json; | |
| 5 | 新增: | |
| 6 | 新增:namespace Cage.Windows; | |
| 7 | 新增: | |
| 8 | 新增:internal sealed class AppUpdater : IDisposable | |
| 9 | 新增:{ | |
| 10 | 新增: public static string Version => typeof(AppUpdater).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "development"; | |
| 11 | 新增: public static string Root => Path.Combine(Backend.Root, "updates"); | |
| 12 | 新增: private readonly Action<Dictionary<string, object?>> changed; | |
| 13 | 新增: private readonly Func<bool> confirmStop; | |
| 14 | 新增: private readonly Action quit, reconnect; | |
| 15 | 新增: private readonly Dictionary<string, object?> state = new() { ["phase"] = "idle", ["currentVersion"] = Version, ["message"] = "" }; | |
| 16 | 新增: private CancellationTokenSource? cancellation; | |
| 17 | 新增: private InstallPlan? prepared; | |
| 18 | 新增: private bool committed; | |
| 19 | 新增: | |
| 20 | 新增: public AppUpdater(Action<Dictionary<string, object?>> changed, Func<bool> confirmStop, Action quit, Action reconnect) | |
| 21 | 新增: { | |
| 22 | 新增: this.changed = changed; this.confirmStop = confirmStop; this.quit = quit; this.reconnect = reconnect; | |
| 23 | 新增: try | |
| 24 | 新增: { | |
| 25 | 新增: var result = Path.Combine(Root, "last-result.json"); | |
| 26 | 新增: if (File.Exists(result) && new FileInfo(result).Length <= 16384) | |
| 27 | 新增: { | |
| 28 | 新增: var value = JsonDocument.Parse(File.ReadAllText(result)).RootElement; | |
| 29 | 新增: state["message"] = value.Text("message"); | |
| 30 | 新增: if (value.TryGetProperty("success", out var success) && !success.GetBoolean()) { state["phase"] = "failed"; state["retryable"] = true; } | |
| 31 | 新增: } | |
| 32 | 新增: } | |
| 33 | 新增: catch (Exception e) when (e is IOException or JsonException or UnauthorizedAccessException) { } | |
| 34 | 新增: } | |
| 35 | 新增: | |
| 36 | 新增: public Dictionary<string, object?> Handle(string operation) | |
| 37 | 新增: { | |
| 38 | 新增: switch (operation) | |
| 39 | 新增: { | |
| 40 | 新增: case "status": break; | |
| 41 | 新增: case "check": if (cancellation == null && prepared == null) _ = Run(true); break; | |
| 42 | 新增: case "install": if (cancellation == null) _ = prepared != null ? Install() : Run(false); break; | |
| 43 | 新增: case "cancel": if (!committed && state["phase"] as string != "installing") cancellation?.Cancel(); break; | |
| 44 | 新增: default: throw new InvalidDataException("更新操作无效"); | |
| 45 | 新增: } | |
| 46 | 新增: return new(state); | |
| 47 | 新增: } | |
| 48 | 新增: | |
| 49 | 新增: private void Change(string phase, string message, bool retryable = false) | |
| 50 | 新增: { | |
| 51 | 新增: state["phase"] = phase; state["message"] = message; state["retryable"] = retryable; changed(new(state)); | |
| 52 | 新增: } | |
| 53 | 新增: | |
| 54 | 新增: public void MarkReady() | |
| 55 | 新增: { | |
| 56 | 新增: if (!Guid.TryParse(Environment.GetEnvironmentVariable("CAGE_UPDATE_CONFIRMATION"), out var token)) return; | |
| 57 | 新增: Directory.CreateDirectory(Root); UpdatePolicy.PlainPath(Root); | |
| 58 | 新增: File.WriteAllText(Path.Combine(Root, "launch-" + token + ".json"), JsonSerializer.Serialize(new { version = Version })); | |
| 59 | 新增: Change("current", "Cage 已更新至 " + Version); | |
| 60 | 新增: Environment.SetEnvironmentVariable("CAGE_UPDATE_CONFIRMATION", null); | |
| 61 | 新增: } | |
| 62 | 新增: | |
| 63 | 新增: private async Task Run(bool checkOnly) | |
| 64 | 新增: { | |
| 65 | 新增: cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(25)); | |
| 66 | 新增: var token = cancellation.Token; | |
| 67 | 新增: Change("checking", "正在通过所选代理检查更新"); | |
| 68 | 新增: string? archive = null; | |
| 69 | 新增: using var process = new Process { StartInfo = Backend.StartInfo(Backend.Executable, "app-update", checkOnly ? "check" : "download") }; | |
| 70 | 新增: var started = false; | |
| 71 | 新增: try | |
| 72 | 新增: { | |
| 73 | 新增: if (!process.Start()) throw new IOException("无法启动更新检查"); | |
| 74 | 新增: started = true; | |
| 75 | 新增: using var abort = token.Register(() => { try { if (!process.HasExited) process.Kill(); } catch (InvalidOperationException) { } }); | |
| 76 | 新增: var errors = Backend.Drain(process.StandardError, token); | |
| 77 | 新增: JsonElement last = default; | |
| 78 | 新增: while (await process.StandardOutput.ReadLineAsync(token) is { } line) | |
| 79 | 新增: { | |
| 80 | 新增: if (line.Length > 65536) throw new IOException("更新响应超过允许大小"); | |
| 81 | 新增: last = JsonDocument.Parse(line).RootElement.Clone(); | |
| 82 | 新增: foreach (var property in last.EnumerateObject()) | |
| 83 | 新增: if (property.Name is not ("archivePath" or "sha256")) state[property.Name] = property.Value.ValueKind switch { | |
| 84 | 新增: JsonValueKind.String => property.Value.GetString(), | |
| 85 | 新增: JsonValueKind.True => true, JsonValueKind.False => false, | |
| 86 | 新增: JsonValueKind.Number => property.Value.GetInt64(), | |
| 87 | 新增: _ => property.Value.Clone(), | |
| 88 | 新增: }; | |
| 89 | 新增: changed(new(state)); | |
| 90 | 新增: } | |
| 91 | 新增: await process.WaitForExitAsync(token); await errors; | |
| 92 | 新增: if (process.ExitCode != 0) throw new IOException(last.ValueKind == JsonValueKind.Object && last.Text("message") is { Length: > 0 } error ? error : "更新请求未完成"); | |
| 93 | 新增: if (checkOnly || last.Text("phase") != "downloaded") return; | |
| 94 | 新增: archive = UpdatePolicy.DownloadPath(last.Text("archivePath"), Root); | |
| 95 | 新增: var version = last.Text("latestVersion"); var digest = last.Text("sha256"); | |
| 96 | 新增: if (!UpdatePolicy.IsNewer(version, Version)) throw new IOException("安装包版本无效或不高于当前版本"); | |
| 97 | 新增: Change("verifying", "正在验证 Windows 签名和安装包内容"); | |
| 98 | 新增: var publisher = await Task.Run(() => Authenticode.Publisher(Environment.ProcessPath!), token); | |
| 99 | 新增: await Task.Run(() => UpdateInstaller.VerifyArchive(archive, digest, version, publisher), token); | |
| 100 | 新增: token.ThrowIfCancellationRequested(); | |
| 101 | 新增: prepared = new InstallPlan(archive, digest, version, publisher, | |
| 102 | 新增: AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar), Environment.ProcessId, | |
| 103 | 新增: Process.GetCurrentProcess().StartTime.ToUniversalTime().Ticks, Guid.NewGuid().ToString()); | |
| 104 | 新增: archive = null; | |
| 105 | 新增: Change("ready", "更新已下载并验证,可安装重启", true); | |
| 106 | 新增: } | |
| 107 | 新增: catch (OperationCanceledException) { Change("failed", "更新已暂停,可稍后重试", true); } | |
| 108 | 新增: catch (Exception error) { Change("failed", error.Message, true); } | |
| 109 | 新增: finally | |
| 110 | 新增: { | |
| 111 | 新增: if (started && !process.HasExited) process.Kill(); | |
| 112 | 新增: if (archive != null) { try { Directory.Delete(Path.GetDirectoryName(archive)!, true); } catch (IOException) { } } | |
| 113 | 新增: cancellation.Dispose(); cancellation = null; | |
| 114 | 新增: } | |
| 115 | 新增: if (prepared != null) await Install(); | |
| 116 | 新增: } | |
| 117 | 新增: | |
| 118 | 新增: private async Task Install() | |
| 119 | 新增: { | |
| 120 | 新增: if (prepared == null) return; | |
| 121 | 新增: cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(5)); | |
| 122 | 新增: var token = cancellation.Token; | |
| 123 | 新增: Process? helper = null; | |
| 124 | 新增: var helperPath = Path.Combine(Root, "helper-" + Guid.NewGuid() + ".exe"); | |
| 125 | 新增: Change("installing", "正在准备安装更新"); | |
| 126 | 新增: try | |
| 127 | 新增: { | |
| 128 | 新增: // Validate the destination before stopping a running environment. | |
| 129 | 新增: UpdatePolicy.PlainPath(prepared.Target); | |
| 130 | 新增: Directory.CreateDirectory(Root); UpdatePolicy.PlainPath(Root); | |
| 131 | 新增: File.Copy(Environment.ProcessPath!, helperPath); | |
| 132 | 新增: await Task.Run(() => Authenticode.SamePublisher(helperPath, prepared.Publisher), token); | |
| 133 | 新增: var start = Backend.StartInfo(helperPath, "--install-update"); start.RedirectStandardInput = true; | |
| 134 | 新增: helper = new Process { StartInfo = start }; | |
| 135 | 新增: if (!helper.Start()) throw new IOException("无法启动安全安装程序"); | |
| 136 | 新增: await helper.StandardInput.WriteLineAsync(JsonSerializer.Serialize(prepared)); | |
| 137 | 新增: await helper.StandardInput.FlushAsync(token); | |
| 138 | 新增: var ready = await helper.StandardOutput.ReadLineAsync(token); | |
| 139 | 新增: if (ready != "READY") throw new IOException("安装程序准备失败,原应用已保留"); | |
| 140 | 新增: var (exit, data) = await Backend.Json(["prepare-update", "--json"], token); | |
| 141 | 新增: if (data.Text("status") == "stop_required") | |
| 142 | 新增: { | |
| 143 | 新增: if (!confirmStop()) { Change("ready", "更新已下载,保存工作后可继续安装", true); return; } | |
| 144 | 新增: (exit, data) = await Backend.Json(["prepare-update", "--json", "--stop"], token); | |
| 145 | 新增: } | |
| 146 | 新增: if (exit != 0 || data.Text("status") != "prepared") throw new IOException(data.Text("message") is { Length: > 0 } detail ? detail : "环境未能安全停止"); | |
| 147 | 新增: if (helper.HasExited) throw new IOException("安装程序已退出,原应用已保留"); | |
| 148 | 新增: await helper.StandardInput.WriteLineAsync("COMMIT"); await helper.StandardInput.FlushAsync(token); | |
| 149 | 新增: helper.StandardInput.Close(); committed = true; | |
| 150 | 新增: Change("installing", "正在安装并重启 Cage"); quit(); | |
| 151 | 新增: } | |
| 152 | 新增: catch (Exception error) { Change("failed", error is OperationCanceledException ? "安装准备超时,原应用已保留" : error.Message, true); reconnect(); } | |
| 153 | 新增: finally | |
| 154 | 新增: { | |
| 155 | 新增: if (!committed && helper != null) | |
| 156 | 新增: { | |
| 157 | 新增: helper.StandardInput.Close(); | |
| 158 | 新增: try { await helper.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5)); } | |
| 159 | 新增: catch (TimeoutException) { if (!helper.HasExited) helper.Kill(); } | |
| 160 | 新增: } | |
| 161 | 新增: helper?.Dispose(); | |
| 162 | 新增: if (!committed) { try { File.Delete(helperPath); } catch (IOException) { } } | |
| 163 | 新增: cancellation?.Dispose(); cancellation = null; | |
| 164 | 新增: } | |
| 165 | 新增: } | |
| 166 | 新增: | |
| 167 | 新增: public void Dispose() { if (!committed) cancellation?.Cancel(); } | |
| 168 | 新增:} | |
| 169 | 新增: | |
| 170 | 新增:internal sealed record InstallPlan(string Archive, string Digest, string Version, string Publisher, | |
| 171 | 新增: string Target, int ParentPid, long ParentStartTicks, string Confirmation); | |
| @@ -0,0 +1,54 @@ | ||
| 1 | 新增:using System.Runtime.InteropServices; | |
| 2 | 新增:using System.Security.Cryptography; | |
| 3 | 新增:using System.Security.Cryptography.X509Certificates; | |
| 4 | 新增: | |
| 5 | 新增:namespace Cage.Windows; | |
| 6 | 新增: | |
| 7 | 新增:internal static class Authenticode | |
| 8 | 新增:{ | |
| 9 | 新增: public static string Publisher(string path) | |
| 10 | 新增: { | |
| 11 | 新增: UpdatePolicy.PlainPath(path); | |
| 12 | 新增: var file = new TrustFile { Size = (uint)Marshal.SizeOf<TrustFile>(), Path = path }; | |
| 13 | 新增: var memory = Marshal.AllocHGlobal(Marshal.SizeOf<TrustFile>()); | |
| 14 | 新增: try | |
| 15 | 新增: { | |
| 16 | 新增: Marshal.StructureToPtr(file, memory, false); | |
| 17 | 新增: var data = new TrustData { | |
| 18 | 新增: Size = (uint)Marshal.SizeOf<TrustData>(), UiChoice = 2, UnionChoice = 1, | |
| 19 | 新增: File = memory, StateAction = 1, | |
| 20 | 新增: // Verification must not make a direct network request around the | |
| 21 | 新增: // selected Cage proxy. Windows uses its existing trust cache. | |
| 22 | 新增: ProviderFlags = 0x1000, | |
| 23 | 新增: }; | |
| 24 | 新增: var action = new Guid("00AAC56B-CD44-11D0-8CC2-00C04FC295EE"); | |
| 25 | 新增: var result = WinVerifyTrust(new IntPtr(-1), ref action, ref data); | |
| 26 | 新增: data.StateAction = 2; _ = WinVerifyTrust(new IntPtr(-1), ref action, ref data); | |
| 27 | 新增: if (result != 0) throw new IOException("Windows 无法验证安装包签名;原应用已保留。请确认系统证书信任状态。"); | |
| 28 | 新增:#pragma warning disable SYSLIB0057 | |
| 29 | 新增: using var signed = X509Certificate.CreateFromSignedFile(path); | |
| 30 | 新增: using var certificate = new X509Certificate2(signed); | |
| 31 | 新增:#pragma warning restore SYSLIB0057 | |
| 32 | 新增: return Convert.ToHexString(SHA256.HashData(certificate.PublicKey.ExportSubjectPublicKeyInfo())); | |
| 33 | 新增: } | |
| 34 | 新增: finally { Marshal.DestroyStructure<TrustFile>(memory); Marshal.FreeHGlobal(memory); } | |
| 35 | 新增: } | |
| 36 | 新增: | |
| 37 | 新增: public static void SamePublisher(string path, string expected) | |
| 38 | 新增: { | |
| 39 | 新增: if (!string.Equals(Publisher(path), expected, StringComparison.Ordinal)) | |
| 40 | 新增: throw new IOException("更新包的发布者签名与当前 Cage 不一致"); | |
| 41 | 新增: } | |
| 42 | 新增: | |
| 43 | 新增: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] | |
| 44 | 新增: private struct TrustFile { public uint Size; [MarshalAs(UnmanagedType.LPWStr)] public string Path; public IntPtr Handle; public IntPtr KnownSubject; } | |
| 45 | 新增: [StructLayout(LayoutKind.Sequential)] | |
| 46 | 新增: private struct TrustData { | |
| 47 | 新增: public uint Size; public IntPtr PolicyCallback, SipClient; | |
| 48 | 新增: public uint UiChoice, RevocationChecks, UnionChoice; public IntPtr File; | |
| 49 | 新增: public uint StateAction; public IntPtr StateData, UrlReference; | |
| 50 | 新增: public uint ProviderFlags, UiContext; public IntPtr SignatureSettings; | |
| 51 | 新增: } | |
| 52 | 新增: [DllImport("wintrust.dll", ExactSpelling = true, PreserveSig = true)] | |
| 53 | 新增: private static extern int WinVerifyTrust(IntPtr window, ref Guid action, ref TrustData data); | |
| 54 | 新增:} | |
| @@ -0,0 +1,68 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Text; | |
| 3 | 新增:using System.Text.Json; | |
| 4 | 新增: | |
| 5 | 新增:namespace Cage.Windows; | |
| 6 | 新增: | |
| 7 | 新增:internal static class Backend | |
| 8 | 新增:{ | |
| 9 | 新增: private static string ConfigPath => Path.GetFullPath( | |
| 10 | 新增: Environment.GetEnvironmentVariable("CLAUDE_CAGE_CONFIG") is { Length: > 0 } configured | |
| 11 | 新增: ? configured : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude-cage", "config.json")); | |
| 12 | 新增: public static string Root => Path.GetDirectoryName(ConfigPath)!; | |
| 13 | 新增: public static string Executable => Path.Combine(AppContext.BaseDirectory, "resources", "cage.exe"); | |
| 14 | 新增: | |
| 15 | 新增: public static ProcessStartInfo StartInfo(string executable, params string[] arguments) | |
| 16 | 新增: { | |
| 17 | 新增: var start = new ProcessStartInfo(executable) { | |
| 18 | 新增: UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, | |
| 19 | 新增: RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8, | |
| 20 | 新增: WorkingDirectory = AppContext.BaseDirectory, | |
| 21 | 新增: }; | |
| 22 | 新增: // Helpers execute outside the installed directory. Keep an explicitly | |
| 23 | 新增: // selected relative profile bound to the same absolute file. | |
| 24 | 新增: start.Environment["CLAUDE_CAGE_CONFIG"] = ConfigPath; | |
| 25 | 新增: foreach (var arg in arguments) start.ArgumentList.Add(arg); | |
| 26 | 新增: return start; | |
| 27 | 新增: } | |
| 28 | 新增: | |
| 29 | 新增: public static Task<(int Exit, JsonElement Data)> Json(string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null) => | |
| 30 | 新增: JsonAt(Executable, arguments, cancellation, deadline); | |
| 31 | 新增: | |
| 32 | 新增: public static async Task<(int Exit, JsonElement Data)> JsonAt(string executable, string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null) | |
| 33 | 新增: { | |
| 34 | 新增: using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation); | |
| 35 | 新增: timeout.CancelAfter(deadline ?? TimeSpan.FromMinutes(3)); | |
| 36 | 新增: using var process = new Process { StartInfo = StartInfo(executable, arguments) }; | |
| 37 | 新增: if (!process.Start()) throw new IOException("无法启动 Cage 后台"); | |
| 38 | 新增: using var abort = timeout.Token.Register(() => { try { if (!process.HasExited) process.Kill(); } catch (InvalidOperationException) { } }); | |
| 39 | 新增: try | |
| 40 | 新增: { | |
| 41 | 新增: var errors = Drain(process.StandardError, timeout.Token); | |
| 42 | 新增: var text = await ReadLimited(process.StandardOutput, 65536, timeout.Token); | |
| 43 | 新增: await process.WaitForExitAsync(timeout.Token); await errors; | |
| 44 | 新增: try { return (process.ExitCode, JsonDocument.Parse(text).RootElement.Clone()); } | |
| 45 | 新增: catch (JsonException) { throw new IOException("Cage 后台未返回有效状态,请查看工作台日志"); } | |
| 46 | 新增: } | |
| 47 | 新增: finally { if (!process.HasExited) process.Kill(); } | |
| 48 | 新增: } | |
| 49 | 新增: | |
| 50 | 新增: public static async Task<string> ReadLimited(StreamReader reader, int limit, CancellationToken token) | |
| 51 | 新增: { | |
| 52 | 新增: var text = new StringBuilder(); var buffer = new char[4096]; int count; | |
| 53 | 新增: while ((count = await reader.ReadAsync(buffer.AsMemory(), token)) > 0) | |
| 54 | 新增: { | |
| 55 | 新增: text.Append(buffer, 0, count); | |
| 56 | 新增: if (text.Length > limit) throw new IOException("后台响应超过允许大小"); | |
| 57 | 新增: } | |
| 58 | 新增: return text.ToString(); | |
| 59 | 新增: } | |
| 60 | 新增: | |
| 61 | 新增: public static async Task Drain(StreamReader reader, CancellationToken token) | |
| 62 | 新增: { | |
| 63 | 新增: var buffer = new char[4096]; | |
| 64 | 新增: while (await reader.ReadAsync(buffer.AsMemory(), token) > 0) { } | |
| 65 | 新增: } | |
| 66 | 新增: public static string Text(this JsonElement data, string name) => | |
| 67 | 新增: data.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString()! : ""; | |
| 68 | 新增:} | |
| @@ -0,0 +1,28 @@ | ||
| 1 | 新增:<Project Sdk="Microsoft.NET.Sdk"> | |
| 2 | 新增: <PropertyGroup> | |
| 3 | 新增: <OutputType>WinExe</OutputType> | |
| 4 | 新增: <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> | |
| 5 | 新增: <UseWindowsForms>true</UseWindowsForms> | |
| 6 | 新增: <EnableWindowsTargeting>true</EnableWindowsTargeting> | |
| 7 | 新增: <RuntimeIdentifier>win-x64</RuntimeIdentifier> | |
| 8 | 新增: <SelfContained>true</SelfContained> | |
| 9 | 新增: <PublishSingleFile>true</PublishSingleFile> | |
| 10 | 新增: <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract> | |
| 11 | 新增: <EnableCompressionInSingleFile>true</EnableCompressionInSingleFile> | |
| 12 | 新增: <AssemblyName>Cage</AssemblyName> | |
| 13 | 新增: <RootNamespace>Cage.Windows</RootNamespace> | |
| 14 | 新增: <Nullable>enable</Nullable> | |
| 15 | 新增: <ImplicitUsings>enable</ImplicitUsings> | |
| 16 | 新增: <Version>0.1.0-alpha.1</Version> | |
| 17 | 新增: <ApplicationManifest>app.manifest</ApplicationManifest> | |
| 18 | 新增: <ApplicationIcon>../../packaging/windows/Cage.ico</ApplicationIcon> | |
| 19 | 新增: <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> | |
| 20 | 新增: <IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion> | |
| 21 | 新增: </PropertyGroup> | |
| 22 | 新增: <ItemGroup> | |
| 23 | 新增: <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4314.35" /> | |
| 24 | 新增: </ItemGroup> | |
| 25 | 新增: <Target Name="RemoveUnusedWebView2WpfReference" BeforeTargets="ResolveAssemblyReferences"> | |
| 26 | 新增: <ItemGroup><Reference Remove="@(Reference)" Condition="'%(Reference.Filename)' == 'Microsoft.Web.WebView2.Wpf'" /></ItemGroup> | |
| 27 | 新增: </Target> | |
| 28 | 新增:</Project> | |
| @@ -0,0 +1,302 @@ | ||
| 1 | 新增:using System.Text.Json; | |
| 2 | 新增:using Microsoft.Web.WebView2.Core; | |
| 3 | 新增:using Microsoft.Web.WebView2.WinForms; | |
| 4 | 新增: | |
| 5 | 新增:namespace Cage.Windows; | |
| 6 | 新增: | |
| 7 | 新增:internal sealed class MainWindow : Form | |
| 8 | 新增:{ | |
| 9 | 新增: private WebView2 web = new() { Dock = DockStyle.Fill, Visible = false }; | |
| 10 | 新增: private readonly Label message = new() { AutoSize = true, MaximumSize = new Size(720, 0), Text = "正在启动 Cage 工作台…", Margin = new Padding(12) }; | |
| 11 | 新增: private readonly FlowLayoutPanel status = new() { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, Padding = new Padding(48), WrapContents = false }; | |
| 12 | 新增: private readonly Button retry = new() { Text = "重试连接", AutoSize = true, Visible = false }; | |
| 13 | 新增: private readonly Button existing = new() { Text = "打开现有环境保存文件", AutoSize = true, Visible = false }; | |
| 14 | 新增: private readonly Button complete = new() { Text = "保存后停止环境并完成更新", AutoSize = true, Visible = false }; | |
| 15 | 新增: private readonly NotifyIcon tray; | |
| 16 | 新增: private readonly AppUpdater updater; | |
| 17 | 新增: private int expectedPort; | |
| 18 | 新增: private bool controllerNeedsUpdate, allowQuit, bootstrapping, webFailed; | |
| 19 | 新增: private readonly CancellationTokenSource lifetime = new(); | |
| 20 | 新增: | |
| 21 | 新增: public MainWindow() | |
| 22 | 新增: { | |
| 23 | 新增: Text = "Cage"; Width = 1280; Height = 850; MinimumSize = new Size(820, 580); | |
| 24 | 新增: StartPosition = FormStartPosition.CenterScreen; BackColor = Color.FromArgb(247, 247, 247); | |
| 25 | 新增: Icon = Icon.ExtractAssociatedIcon(Environment.ProcessPath!) ?? SystemIcons.Application; | |
| 26 | 新增: var menus = new MenuStrip(); | |
| 27 | 新增: var file = new ToolStripMenuItem("文件"); | |
| 28 | 新增: AddAction(file, "打开项目…", "openProject", Keys.Control | Keys.O); | |
| 29 | 新增: AddAction(file, "新建网页", "newTab", Keys.Control | Keys.T); | |
| 30 | 新增: AddAction(file, "新建终端", "newTerminal", Keys.Control | Keys.Shift | Keys.Enter); | |
| 31 | 新增: AddAction(file, "关闭当前标签", "closeTab", Keys.Control | Keys.W); | |
| 32 | 新增: file.DropDownItems.Add("关闭窗口(保留环境)", null, (_, _) => Hide()); | |
| 33 | 新增: file.DropDownItems.Add("退出 Cage…", null, (_, _) => RequestQuit()); | |
| 34 | 新增: var settings = new ToolStripMenuItem("设置"); | |
| 35 | 新增: AddAction(settings, "打开设置", "settings", Keys.Control | Keys.Oemcomma); | |
| 36 | 新增: settings.DropDownItems.Add("检查应用更新…", null, (_, _) => updater!.Handle("check")); | |
| 37 | 新增: var help = new ToolStripMenuItem("帮助"); | |
| 38 | 新增: help.DropDownItems.Add("关于 Cage", null, (_, _) => MessageBox.Show(this, $"Cage {AppUpdater.Version}\n本机隔离编码工作区", "关于 Cage")); | |
| 39 | 新增: menus.Items.AddRange([file, settings, help]); MainMenuStrip = menus; | |
| 40 | 新增: status.Controls.AddRange([message, retry, existing, complete]); | |
| 41 | 新增: Controls.Add(web); Controls.Add(status); Controls.Add(menus); | |
| 42 | 新增: retry.Click += async (_, _) => { | |
| 43 | 新增: if (webFailed || web.CoreWebView2 == null) await Initialize(true); else await Bootstrap(); | |
| 44 | 新增: }; | |
| 45 | 新增: existing.Click += async (_, _) => await Bootstrap("--existing"); | |
| 46 | 新增: complete.Click += async (_, _) => { | |
| 47 | 新增: if (ConfirmStop()) await Bootstrap("--complete-update"); | |
| 48 | 新增: }; | |
| 49 | 新增: var trayMenu = new ContextMenuStrip(); | |
| 50 | 新增: trayMenu.Items.Add("打开 Cage", null, (_, _) => RestoreWindow()); | |
| 51 | 新增: trayMenu.Items.Add("退出 Cage…", null, (_, _) => RequestQuit()); | |
| 52 | 新增: tray = new NotifyIcon { Icon = Icon, Text = "Cage", Visible = true, ContextMenuStrip = trayMenu }; | |
| 53 | 新增: tray.DoubleClick += (_, _) => RestoreWindow(); | |
| 54 | 新增: updater = new AppUpdater(PublishUpdate, ConfirmStop, () => { allowQuit = true; Close(); }, () => _ = Bootstrap()); | |
| 55 | 新增: Shown += async (_, _) => { | |
| 56 | 新增: if (Program.SmokeOutput != null) _ = SmokeDeadline(); | |
| 57 | 新增: await Initialize(); | |
| 58 | 新增: }; | |
| 59 | 新增: Resize += (_, _) => PublishVisibility(); VisibleChanged += (_, _) => PublishVisibility(); | |
| 60 | 新增: FormClosing += (_, e) => { | |
| 61 | 新增: if (!allowQuit && e.CloseReason is not (CloseReason.WindowsShutDown or CloseReason.TaskManagerClosing)) { e.Cancel = true; Hide(); } | |
| 62 | 新增: }; | |
| 63 | 新增: FormClosed += (_, _) => { lifetime.Cancel(); updater.Dispose(); tray.Dispose(); web.Dispose(); }; | |
| 64 | 新增: } | |
| 65 | 新增: | |
| 66 | 新增: private void AddAction(ToolStripMenuItem menu, string label, string action, Keys shortcut) => | |
| 67 | 新增: menu.DropDownItems.Add(new ToolStripMenuItem(label, null, (_, _) => Action(action)) { ShortcutKeys = shortcut }); | |
| 68 | 新增: private bool ConfirmStop() => MessageBox.Show(this, | |
| 69 | 新增: "请先保存编辑器中的文件并结束正在运行的工作。继续后 Cage 会停止环境、安装已验证的更新并重新启动。", | |
| 70 | 新增: "保存并停止环境后安装重启", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK; | |
| 71 | 新增: | |
| 72 | 新增: public void RestoreWindow() { Show(); WindowState = FormWindowState.Normal; Activate(); PublishVisibility(); } | |
| 73 | 新增: private void RequestQuit() | |
| 74 | 新增: { | |
| 75 | 新增: RestoreWindow(); | |
| 76 | 新增: if (web.Visible) Action("quit"); | |
| 77 | 新增: else { allowQuit = true; Close(); } | |
| 78 | 新增: } | |
| 79 | 新增: private void Action(string name) => Script("window.cageNativeAction?.(" + JsonSerializer.Serialize(name) + ")"); | |
| 80 | 新增: private void PublishVisibility() => Script($"window.cageWindowVisible = {(Visible && WindowState != FormWindowState.Minimized ? "true" : "false")}; window.dispatchEvent(new Event('cage-window-visibility'));"); | |
| 81 | 新增: private void PublishUpdate(Dictionary<string, object?> state) => Script("window.dispatchEvent(new CustomEvent('cage-app-update',{detail:" + JsonSerializer.Serialize(state) + "}));"); | |
| 82 | 新增: private async void Script(string script) | |
| 83 | 新增: { | |
| 84 | 新增: if (web.CoreWebView2 == null || IsDisposed) return; | |
| 85 | 新增: try { await web.ExecuteScriptAsync(script); } | |
| 86 | 新增: catch (InvalidOperationException) { } | |
| 87 | 新增: catch (System.Runtime.InteropServices.COMException) { } | |
| 88 | 新增: } | |
| 89 | 新增: private void Error(string text) | |
| 90 | 新增: { | |
| 91 | 新增: message.Text = text; status.Show(); status.BringToFront(); retry.Show(); web.Hide(); | |
| 92 | 新增: } | |
| 93 | 新增: | |
| 94 | 新增: private async Task Initialize(bool recreate = false) | |
| 95 | 新增: { | |
| 96 | 新增: retry.Enabled = false; | |
| 97 | 新增: try | |
| 98 | 新增: { | |
| 99 | 新增: if (recreate) | |
| 100 | 新增: { | |
| 101 | 新增: Controls.Remove(web); web.Dispose(); | |
| 102 | 新增: web = new WebView2 { Dock = DockStyle.Fill, Visible = false }; | |
| 103 | 新增: Controls.Add(web); status.BringToFront(); | |
| 104 | 新增: } | |
| 105 | 新增: var environment = await CoreWebView2Environment.CreateAsync(null, Path.Combine(Backend.Root, "webview2")); | |
| 106 | 新增: await web.EnsureCoreWebView2Async(environment); | |
| 107 | 新增: var core = web.CoreWebView2; | |
| 108 | 新增: core.Settings.AreDevToolsEnabled = false; core.Settings.AreDefaultContextMenusEnabled = false; | |
| 109 | 新增: core.Settings.IsStatusBarEnabled = false; core.Settings.IsZoomControlEnabled = false; | |
| 110 | 新增: core.Settings.AreBrowserAcceleratorKeysEnabled = false; | |
| 111 | 新增: core.Settings.IsPasswordAutosaveEnabled = false; core.Settings.IsGeneralAutofillEnabled = false; | |
| 112 | 新增: core.NavigationStarting += (_, e) => { if (!UpdatePolicy.IsWorkbench(e.Uri, expectedPort)) e.Cancel = true; }; | |
| 113 | 新增: core.NewWindowRequested += (_, e) => e.Handled = true; | |
| 114 | 新增: core.DownloadStarting += (_, e) => e.Cancel = true; | |
| 115 | 新增: core.PermissionRequested += (_, e) => e.State = CoreWebView2PermissionState.Deny; | |
| 116 | 新增: core.WebMessageReceived += Receive; | |
| 117 | 新增: core.ProcessFailed += (_, _) => { webFailed = true; Error("工作台显示进程已退出。后台任务保留,可重试连接。"); }; | |
| 118 | 新增: core.NavigationCompleted += (_, e) => { | |
| 119 | 新增: if (!e.IsSuccess) { Error("无法连接 Cage 工作台。后台任务保留,可重试连接。"); return; } | |
| 120 | 新增: status.Hide(); web.Show(); web.Focus(); PublishVisibility(); | |
| 121 | 新增: }; | |
| 122 | 新增: await core.AddScriptToExecuteOnDocumentCreatedAsync(BridgeScript); | |
| 123 | 新增: webFailed = false; | |
| 124 | 新增: await Bootstrap(); | |
| 125 | 新增: } | |
| 126 | 新增: catch (WebView2RuntimeNotFoundException) | |
| 127 | 新增: { | |
| 128 | 新增: Error("缺少 Microsoft Edge WebView2 Runtime。请运行 Cage 安装程序安装随附运行时后重试。"); | |
| 129 | 新增: webFailed = true; | |
| 130 | 新增: } | |
| 131 | 新增: catch (Exception error) { webFailed = true; Error("无法初始化工作台:" + error.Message); } | |
| 132 | 新增: finally { retry.Enabled = true; } | |
| 133 | 新增: } | |
| 134 | 新增: | |
| 135 | 新增: private async Task SmokeDeadline() | |
| 136 | 新增: { | |
| 137 | 新增: try { await Task.Delay(TimeSpan.FromSeconds(120), lifetime.Token); allowQuit = true; Close(); } | |
| 138 | 新增: catch (OperationCanceledException) { } | |
| 139 | 新增: } | |
| 140 | 新增: | |
| 141 | 新增: private async Task CompleteSmoke() | |
| 142 | 新增: { | |
| 143 | 新增: if (Program.SmokeOutput == null) return; | |
| 144 | 新增: try | |
| 145 | 新增: { | |
| 146 | 新增: var (exit, data) = await Backend.Json(["prepare-update", "--json"], lifetime.Token); | |
| 147 | 新增: if (exit != 0 || data.Text("status") != "prepared") throw new IOException("自检结束时无法确认后台已停止"); | |
| 148 | 新增: File.WriteAllText(Program.SmokeOutput, JsonSerializer.Serialize(new { | |
| 149 | 新增: success = true, nativeBridgeReady = true, version = AppUpdater.Version, | |
| 150 | 新增: webviewVersion = web.CoreWebView2.Environment.BrowserVersionString, | |
| 151 | 新增: })); | |
| 152 | 新增: } | |
| 153 | 新增: catch (Exception error) { Error(error.Message); } | |
| 154 | 新增: finally { allowQuit = true; BeginInvoke(Close); } | |
| 155 | 新增: } | |
| 156 | 新增: | |
| 157 | 新增: private async Task Bootstrap(params string[] options) | |
| 158 | 新增: { | |
| 159 | 新增: if (bootstrapping || web.CoreWebView2 == null) return; | |
| 160 | 新增: bootstrapping = true; | |
| 161 | 新增: message.Text = "正在连接 Cage 工作台…"; status.Show(); status.BringToFront(); | |
| 162 | 新增: retry.Hide(); existing.Hide(); complete.Hide(); | |
| 163 | 新增: try | |
| 164 | 新增: { | |
| 165 | 新增: var (exit, data) = await Backend.Json(["desktop", "--json", ..options], lifetime.Token); | |
| 166 | 新增: if (exit != 0) throw new IOException(data.Text("message") is { Length: > 0 } detail ? detail : "工作台未能启动"); | |
| 167 | 新增: controllerNeedsUpdate = data.Text("status") != "ready"; | |
| 168 | 新增: if (data.Text("status") == "upgrade_pending") | |
| 169 | 新增: { | |
| 170 | 新增: message.Text = data.Text("message"); existing.Show(); complete.Show(); return; | |
| 171 | 新增: } | |
| 172 | 新增: var entry = UpdatePolicy.Entry(data.Text("url")); expectedPort = entry.Port; | |
| 173 | 新增: Text = controllerNeedsUpdate ? "Cage(更新待完成)" : "Cage"; | |
| 174 | 新增: web.CoreWebView2.Navigate(entry.AbsoluteUri); | |
| 175 | 新增: } | |
| 176 | 新增: catch (OperationCanceledException) { if (!lifetime.IsCancellationRequested) Error("连接后台超时,请重试。"); } | |
| 177 | 新增: catch (Exception error) { Error(error.Message); } | |
| 178 | 新增: finally { bootstrapping = false; } | |
| 179 | 新增: } | |
| 180 | 新增: | |
| 181 | 新增: private async void Receive(object? sender, CoreWebView2WebMessageReceivedEventArgs e) | |
| 182 | 新增: { | |
| 183 | 新增: // CoreWebView2.WebMessageReceived is top-document only. Frame messages | |
| 184 | 新增: // have a separate CoreWebView2Frame event, which this host never handles. | |
| 185 | 新增: if (!UpdatePolicy.IsWorkbench(e.Source, expectedPort)) return; | |
| 186 | 新增: string id = ""; | |
| 187 | 新增: try | |
| 188 | 新增: { | |
| 189 | 新增: if (e.WebMessageAsJson.Length > 2 * 1024 * 1024) throw new InvalidDataException("请求过大"); | |
| 190 | 新增: var body = JsonDocument.Parse(e.WebMessageAsJson).RootElement; | |
| 191 | 新增: id = body.Text("id"); | |
| 192 | 新增: if (!Guid.TryParse(id, out _)) return; | |
| 193 | 新增: var request = body.GetProperty("request"); | |
| 194 | 新增: object? result; | |
| 195 | 新增: switch (request.Text("action")) | |
| 196 | 新增: { | |
| 197 | 新增: case "workbenchReady": | |
| 198 | 新增: if (controllerNeedsUpdate) throw new IOException("后台版本尚未同步,更新未完成"); | |
| 199 | 新增: updater.MarkReady(); result = true; _ = CompleteSmoke(); break; | |
| 200 | 新增: case "appUpdate": result = updater.Handle(request.Text("operation")); break; | |
| 201 | 新增: case "importTheme": | |
| 202 | 新增: using (var picker = new OpenFileDialog { Filter = "Cage 主题 (*.json)|*.json", Title = "导入主题", Multiselect = false }) | |
| 203 | 新增: { | |
| 204 | 新增: if (picker.ShowDialog(this) != DialogResult.OK) { result = ""; break; } | |
| 205 | 新增: using var stream = File.OpenRead(picker.FileName); | |
| 206 | 新增: if (stream.Length > 256 * 1024) throw new InvalidDataException("主题文件不能超过 256 KB"); | |
| 207 | 新增: using var reader = new StreamReader(stream, new System.Text.UTF8Encoding(false, true)); | |
| 208 | 新增: result = reader.ReadToEnd(); | |
| 209 | 新增: } | |
| 210 | 新增: break; | |
| 211 | 新增: case "exportTheme": | |
| 212 | 新增: var themeText = request.Text("text"); | |
| 213 | 新增: if (System.Text.Encoding.UTF8.GetByteCount(themeText) > 256 * 1024) throw new InvalidDataException("主题文件不能超过 256 KB"); | |
| 214 | 新增: var themeDocument = JsonDocument.Parse(themeText).RootElement; | |
| 215 | 新增: if (themeDocument.Text("format") != "cage-theme" || themeDocument.GetProperty("version").GetInt32() != 1) throw new InvalidDataException("主题文件格式无效"); | |
| 216 | 新增: using (var picker = new SaveFileDialog { Filter = "Cage 主题 (*.json)|*.json", Title = "导出主题", FileName = Path.GetFileName(request.Text("filename")), DefaultExt = "json", AddExtension = true }) | |
| 217 | 新增: { | |
| 218 | 新增: if (picker.ShowDialog(this) != DialogResult.OK) { result = false; break; } | |
| 219 | 新增: File.WriteAllText(picker.FileName, themeText, new System.Text.UTF8Encoding(false)); result = true; | |
| 220 | 新增: } | |
| 221 | 新增: break; | |
| 222 | 新增: case "chooseFolder": | |
| 223 | 新增: using (var picker = new FolderBrowserDialog { Description = "仅此文件夹会与 Cage 共享。请选择具体项目。", UseDescriptionForTitle = true, ShowNewFolderButton = true }) | |
| 224 | 新增: result = picker.ShowDialog(this) == DialogResult.OK ? picker.SelectedPath : ""; | |
| 225 | 新增: break; | |
| 226 | 新增: case "clipboardRead": result = Clipboard.ContainsText() ? Clipboard.GetText() : ""; break; | |
| 227 | 新增: case "saveBrowserDownload": | |
| 228 | 新增: case "browserDownloadAction": | |
| 229 | 新增: { | |
| 230 | 新增: var downloadID = request.Text("id"); | |
| 231 | 新增: if (!Guid.TryParse(downloadID, out _)) throw new InvalidDataException("下载标识无效"); | |
| 232 | 新增: var operation = request.Text("action") == "saveBrowserDownload" ? "save" : request.Text("operation"); | |
| 233 | 新增: if (operation is not ("save" or "open" or "reveal")) throw new InvalidDataException("下载操作无效"); | |
| 234 | 新增: var arguments = new List<string> { "browser-file", "--json", operation, downloadID }; | |
| 235 | 新增: if (operation == "save") | |
| 236 | 新增: { | |
| 237 | 新增: var fileName = Path.GetFileName(request.Text("name")); | |
| 238 | 新增: foreach (var character in Path.GetInvalidFileNameChars()) fileName = fileName.Replace(character, '_'); | |
| 239 | 新增: using var picker = new SaveFileDialog { Title = "将下载另存为到本机", FileName = fileName, OverwritePrompt = true, AddExtension = false }; | |
| 240 | 新增: if (picker.ShowDialog(this) != DialogResult.OK) { result = new { canceled = true }; break; } | |
| 241 | 新增: arguments.Add(picker.FileName); | |
| 242 | 新增: } | |
| 243 | 新增: var response = await Backend.Json(arguments.ToArray(), lifetime.Token, TimeSpan.FromMinutes(30)); | |
| 244 | 新增: if (response.Exit != 0) throw new IOException(response.Data.Text("message")); | |
| 245 | 新增: result = response.Data; break; | |
| 246 | 新增: } | |
| 247 | 新增: case "clipboardReadContent": | |
| 248 | 新增: if (Clipboard.ContainsImage()) | |
| 249 | 新增: { | |
| 250 | 新增: using var clipboardImage = Clipboard.GetImage() ?? throw new InvalidDataException("无法读取剪贴板图片"); | |
| 251 | 新增: if ((long)clipboardImage.Width * clipboardImage.Height > 40_000_000) throw new InvalidDataException("图片不能超过 4000 万像素"); | |
| 252 | 新增: using var imageStream = new MemoryStream(); | |
| 253 | 新增: clipboardImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Png); | |
| 254 | 新增: if (imageStream.Length > 20 * 1024 * 1024) throw new InvalidDataException("图片不能超过 20 MB"); | |
| 255 | 新增: result = new { png = Convert.ToBase64String(imageStream.ToArray()) }; | |
| 256 | 新增: } | |
| 257 | 新增: else result = new { text = Clipboard.ContainsText() ? Clipboard.GetText() : "" }; | |
| 258 | 新增: break; | |
| 259 | 新增: case "clipboardWrite": | |
| 260 | 新增: if (request.Text("text") is { Length: > 0 } text) Clipboard.SetText(text); else Clipboard.Clear(); | |
| 261 | 新增: result = true; break; | |
| 262 | 新增: case "appearance": | |
| 263 | 新增: var mode = request.Text("mode"); var background = request.Text("background"); | |
| 264 | 新增: if (mode is not ("system" or "light" or "dark") || !System.Text.RegularExpressions.Regex.IsMatch(background, "^#[0-9a-fA-F]{6}$")) | |
| 265 | 新增: throw new InvalidDataException("外观参数无效"); | |
| 266 | 新增: BackColor = ColorTranslator.FromHtml(background); web.DefaultBackgroundColor = BackColor; | |
| 267 | 新增: web.CoreWebView2.Profile.PreferredColorScheme = mode == "dark" ? CoreWebView2PreferredColorScheme.Dark : mode == "light" ? CoreWebView2PreferredColorScheme.Light : CoreWebView2PreferredColorScheme.Auto; | |
| 268 | 新增: result = true; break; | |
| 269 | 新增: case "refreshSession": | |
| 270 | 新增: var (exit, data) = await Backend.Json(controllerNeedsUpdate ? ["desktop", "--json", "--existing"] : ["desktop", "--json"], lifetime.Token); | |
| 271 | 新增: if (exit != 0) throw new IOException("工作台会话恢复失败"); | |
| 272 | 新增: result = new { url = UpdatePolicy.Entry(data.Text("url")).AbsoluteUri }; break; | |
| 273 | 新增: case "reconnect": result = true; _ = Bootstrap(); break; | |
| 274 | 新增: case "quitNow": result = true; allowQuit = true; BeginInvoke(Close); break; | |
| 275 | 新增: default: throw new InvalidDataException("未知原生操作"); | |
| 276 | 新增: } | |
| 277 | 新增: web.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, result })); | |
| 278 | 新增: } | |
| 279 | 新增: catch (Exception error) | |
| 280 | 新增: { | |
| 281 | 新增: if (id.Length != 0 && !IsDisposed) web.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, error = error.Message })); | |
| 282 | 新增: } | |
| 283 | 新增: } | |
| 284 | 新增: | |
| 285 | 新增: private const string BridgeScript = """ | |
| 286 | 新增: (() => { | |
| 287 | 新增: if (window !== window.top || location.protocol !== 'http:' || location.hostname !== 'localhost') return; | |
| 288 | 新增: const pending = new Map(); | |
| 289 | 新增: chrome.webview.addEventListener('message', ({data}) => { | |
| 290 | 新增: const item = pending.get(data.id); if (!item) return; | |
| 291 | 新增: pending.delete(data.id); clearTimeout(item.timer); | |
| 292 | 新增: data.error ? item.reject(new Error(data.error)) : item.resolve(data.result); | |
| 293 | 新增: }); | |
| 294 | 新增: const cage = {postMessage(request) { return new Promise((resolve, reject) => { | |
| 295 | 新增: const id = crypto.randomUUID(); | |
| 296 | 新增: const timer = setTimeout(() => { pending.delete(id); reject(new Error('原生操作超时,请重试')); }, 240000); | |
| 297 | 新增: pending.set(id, {resolve, reject, timer}); chrome.webview.postMessage({id, request}); | |
| 298 | 新增: }); }}; | |
| 299 | 新增: Object.defineProperty(window, 'webkit', {value: {messageHandlers: {cage}}, writable: false}); | |
| 300 | 新增: })(); | |
| 301 | 新增: """; | |
| 302 | 新增:} | |
| @@ -0,0 +1,65 @@ | ||
| 1 | 新增:using System.IO.Pipes; | |
| 2 | 新增:using System.Security.Cryptography; | |
| 3 | 新增:using System.Security.Principal; | |
| 4 | 新增:using System.Text; | |
| 5 | 新增:using System.Runtime.InteropServices; | |
| 6 | 新增: | |
| 7 | 新增:namespace Cage.Windows; | |
| 8 | 新增: | |
| 9 | 新增:internal static class Program | |
| 10 | 新增:{ | |
| 11 | 新增: public static string? SmokeOutput { get; private set; } | |
| 12 | 新增: [STAThread] | |
| 13 | 新增: private static int Main(string[] args) | |
| 14 | 新增: { | |
| 15 | 新增: if (args is ["--install-update"]) return UpdateInstaller.Run().GetAwaiter().GetResult(); | |
| 16 | 新增: if (args is ["--smoke-test", var output] && Path.IsPathFullyQualified(output)) | |
| 17 | 新增: { | |
| 18 | 新增: SmokeOutput = output; | |
| 19 | 新增: if (File.Exists(output)) File.Delete(output); | |
| 20 | 新增: } | |
| 21 | 新增: else if (args.Length != 0) return 2; | |
| 22 | 新增: ApplicationConfiguration.Initialize(); | |
| 23 | 新增: if (RuntimeInformation.OSArchitecture != Architecture.X64 || Environment.OSVersion.Version.Build < 19045) | |
| 24 | 新增: { | |
| 25 | 新增: MessageBox.Show("Cage 需要 Windows 10 22H2(19045)或 Windows 11,x64(Intel/AMD)系统。", "Cage"); | |
| 26 | 新增: return 1; | |
| 27 | 新增: } | |
| 28 | 新增: var sid = WindowsIdentity.GetCurrent().User?.Value ?? Environment.UserName; | |
| 29 | 新增: var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sid)))[..24]; | |
| 30 | 新增: using var mutex = new Mutex(true, @"Local\Cage-" + key, out var owner); | |
| 31 | 新增: if (!owner) | |
| 32 | 新增: { | |
| 33 | 新增: if (SmokeOutput != null) return 3; | |
| 34 | 新增: try | |
| 35 | 新增: { | |
| 36 | 新增: using var client = new NamedPipeClientStream(".", "Cage-" + key, PipeDirection.Out, PipeOptions.CurrentUserOnly); | |
| 37 | 新增: client.Connect(3000); client.WriteByte(1); | |
| 38 | 新增: } | |
| 39 | 新增: catch (IOException) { MessageBox.Show("Cage 已在运行,但窗口暂时无法唤起。请从任务栏打开 Cage。", "Cage"); } | |
| 40 | 新增: catch (TimeoutException) { MessageBox.Show("Cage 正在启动,请稍候。", "Cage"); } | |
| 41 | 新增: return 0; | |
| 42 | 新增: } | |
| 43 | 新增: using var form = new MainWindow(); | |
| 44 | 新增: using var cancellation = new CancellationTokenSource(); | |
| 45 | 新增: _ = Task.Run(async () => | |
| 46 | 新增: { | |
| 47 | 新增: while (!cancellation.IsCancellationRequested) | |
| 48 | 新增: { | |
| 49 | 新增: try | |
| 50 | 新增: { | |
| 51 | 新增: await using var pipe = new NamedPipeServerStream("Cage-" + key, PipeDirection.In, 1, | |
| 52 | 新增: PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); | |
| 53 | 新增: await pipe.WaitForConnectionAsync(cancellation.Token); | |
| 54 | 新增: var data = new byte[1]; | |
| 55 | 新增: if (await pipe.ReadAsync(data, cancellation.Token) == 1 && data[0] == 1 && form.IsHandleCreated) | |
| 56 | 新增: form.BeginInvoke(form.RestoreWindow); | |
| 57 | 新增: } | |
| 58 | 新增: catch (OperationCanceledException) { break; } | |
| 59 | 新增: catch (IOException) { } | |
| 60 | 新增: } | |
| 61 | 新增: }); | |
| 62 | 新增: Application.Run(form); cancellation.Cancel(); | |
| 63 | 新增: return SmokeOutput == null || File.Exists(SmokeOutput) ? 0 : 1; | |
| 64 | 新增: } | |
| 65 | 新增:} | |
| @@ -0,0 +1,194 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Security.Cryptography; | |
| 3 | 新增:using System.Text.Json; | |
| 4 | 新增: | |
| 5 | 新增:namespace Cage.Windows; | |
| 6 | 新增: | |
| 7 | 新增:internal static class UpdateInstaller | |
| 8 | 新增:{ | |
| 9 | 新增: public static void VerifyArchive(string path, string hash, string version, string publisher) | |
| 10 | 新增: { | |
| 11 | 新增: UpdatePolicy.DownloadPath(path, AppUpdater.Root); UpdatePolicy.PlainPath(path); | |
| 12 | 新增: if (new FileInfo(path).Length is <= 0 or > (512L << 20)) throw new IOException("安装包大小无效"); | |
| 13 | 新增: using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); | |
| 14 | 新增: var actual = Convert.ToHexString(SHA256.HashData(stream)); | |
| 15 | 新增: if (hash.Length != 64 || !string.Equals(actual, hash, StringComparison.OrdinalIgnoreCase)) | |
| 16 | 新增: throw new IOException("安装包下载后发生变化,请重新下载"); | |
| 17 | 新增: Authenticode.SamePublisher(path, publisher); | |
| 18 | 新增: var metadata = FileVersionInfo.GetVersionInfo(path); | |
| 19 | 新增: if (metadata.ProductName != "Cage" || metadata.ProductVersion != version) | |
| 20 | 新增: throw new IOException("安装包产品身份或版本不匹配"); | |
| 21 | 新增: } | |
| 22 | 新增: | |
| 23 | 新增: public static async Task<int> Run() | |
| 24 | 新增: { | |
| 25 | 新增: InstallPlan? plan = null; | |
| 26 | 新增: string? backup = null; | |
| 27 | 新增: var replaced = false; | |
| 28 | 新增: var committed = false; | |
| 29 | 新增: var succeeded = false; | |
| 30 | 新增: Process? launched = null; | |
| 31 | 新增: try | |
| 32 | 新增: { | |
| 33 | 新增: using var inputTimeout = new CancellationTokenSource(TimeSpan.FromMinutes(5)); | |
| 34 | 新增: var line = await Console.In.ReadLineAsync(inputTimeout.Token); | |
| 35 | 新增: if (line == null || line.Length > 16384) return 1; | |
| 36 | 新增: plan = JsonSerializer.Deserialize<InstallPlan>(line) ?? throw new IOException("安装计划无效"); | |
| 37 | 新增: if (!Guid.TryParse(plan.Confirmation, out _) || !Path.IsPathFullyQualified(plan.Target) || plan.Target.Contains('"') || | |
| 38 | 新增: plan.Target.TrimEnd(Path.DirectorySeparatorChar) != plan.Target || | |
| 39 | 新增: string.Equals(Path.GetPathRoot(plan.Target), plan.Target, StringComparison.OrdinalIgnoreCase)) | |
| 40 | 新增: throw new IOException("安装目标无效"); | |
| 41 | 新增: UpdatePolicy.PlainPath(plan.Target); UpdatePolicy.PlainPath(AppUpdater.Root); | |
| 42 | 新增: if (File.ReadAllText(Path.Combine(plan.Target, "Cage.install-id")).Trim() != "io.github.lee-xeo.claude-cage") | |
| 43 | 新增: throw new IOException("请先使用 Cage 安装程序安装应用,再自动更新"); | |
| 44 | 新增: var original = Path.Combine(plan.Target, "Cage.exe"); | |
| 45 | 新增: var ownPublisher = Authenticode.Publisher(Environment.ProcessPath!); | |
| 46 | 新增: if (plan.Publisher != ownPublisher) throw new IOException("安装计划发布者不匹配"); | |
| 47 | 新增: Authenticode.SamePublisher(original, ownPublisher); | |
| 48 | 新增: if (!UpdatePolicy.IsNewer(plan.Version, FileVersionInfo.GetVersionInfo(original).ProductVersion ?? "")) | |
| 49 | 新增: throw new IOException("更新版本必须高于当前安装版本"); | |
| 50 | 新增: VerifyArchive(plan.Archive, plan.Digest, plan.Version, ownPublisher); | |
| 51 | 新增: // Hold the verified file open without write/delete sharing until the | |
| 52 | 新增: // installer exits. Another process cannot swap it after verification. | |
| 53 | 新增: await using var archiveLock = new FileStream(plan.Archive, FileMode.Open, FileAccess.Read, FileShare.Read); | |
| 54 | 新增: VerifyArchive(plan.Archive, plan.Digest, plan.Version, ownPublisher); | |
| 55 | 新增: using var parent = Process.GetProcessById(plan.ParentPid); | |
| 56 | 新增: if (parent.StartTime.ToUniversalTime().Ticks != plan.ParentStartTicks || | |
| 57 | 新增: !string.Equals(parent.MainModule?.FileName, original, StringComparison.OrdinalIgnoreCase)) | |
| 58 | 新增: throw new IOException("更新请求进程身份不匹配"); | |
| 59 | 新增: backup = Path.Combine(AppUpdater.Root, "previous-" + plan.Confirmation); | |
| 60 | 新增: if (Directory.Exists(backup)) throw new IOException("更新备份目录已存在"); | |
| 61 | 新增: // Preparation is reversible and completes before the controller stops. | |
| 62 | 新增: CopyTree(plan.Target, backup); | |
| 63 | 新增: Console.WriteLine("READY"); await Console.Out.FlushAsync(); | |
| 64 | 新增: if (await Console.In.ReadLineAsync(inputTimeout.Token) != "COMMIT") return 1; | |
| 65 | 新增: committed = true; | |
| 66 | 新增: await parent.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(45)); | |
| 67 | 新增: VerifyArchive(plan.Archive, plan.Digest, plan.Version, ownPublisher); | |
| 68 | 新增: // NSIS requires /D= to be the final, unquoted argument; the executable | |
| 69 | 新增: // path is passed separately and no command shell is involved. | |
| 70 | 新增: using (var installer = Process.Start(new ProcessStartInfo(plan.Archive) { | |
| 71 | 新增: UseShellExecute = false, CreateNoWindow = true, | |
| 72 | 新增: Arguments = "/S /UPDATE /D=" + plan.Target, | |
| 73 | 新增: WorkingDirectory = Path.GetDirectoryName(plan.Archive), | |
| 74 | 新增: }) ?? throw new IOException("无法启动 Windows 安装器")) | |
| 75 | 新增: { | |
| 76 | 新增: replaced = true; | |
| 77 | 新增: try { await installer.WaitForExitAsync().WaitAsync(TimeSpan.FromMinutes(10)); } | |
| 78 | 新增: catch (TimeoutException) { if (!installer.HasExited) installer.Kill(true); await installer.WaitForExitAsync(); throw; } | |
| 79 | 新增: if (installer.ExitCode != 0) throw new IOException("Windows 安装程序未完成安装"); | |
| 80 | 新增: } | |
| 81 | 新增: Authenticode.SamePublisher(original, ownPublisher); | |
| 82 | 新增: if (FileVersionInfo.GetVersionInfo(original).ProductVersion != plan.Version) | |
| 83 | 新增: throw new IOException("安装后版本不匹配"); | |
| 84 | 新增: var marker = Path.Combine(AppUpdater.Root, "launch-" + plan.Confirmation + ".json"); | |
| 85 | 新增: if (File.Exists(marker)) File.Delete(marker); | |
| 86 | 新增: var launch = new ProcessStartInfo(original) { UseShellExecute = false, WorkingDirectory = plan.Target }; | |
| 87 | 新增: launch.Environment["CAGE_UPDATE_CONFIRMATION"] = plan.Confirmation; | |
| 88 | 新增: launched = Process.Start(launch) ?? throw new IOException("新版 Cage 无法启动"); | |
| 89 | 新增: var deadline = DateTime.UtcNow.AddSeconds(120); | |
| 90 | 新增: var ready = false; | |
| 91 | 新增: while (DateTime.UtcNow < deadline && !launched.HasExited) | |
| 92 | 新增: { | |
| 93 | 新增: if (File.Exists(marker) && new FileInfo(marker).Length < 16384) | |
| 94 | 新增: { | |
| 95 | 新增: try | |
| 96 | 新增: { | |
| 97 | 新增: var confirmation = JsonDocument.Parse(await File.ReadAllTextAsync(marker)).RootElement; | |
| 98 | 新增: ready = confirmation.Text("version") == plan.Version; | |
| 99 | 新增: } | |
| 100 | 新增: catch (IOException) { } | |
| 101 | 新增: catch (JsonException) { } | |
| 102 | 新增: if (ready) break; | |
| 103 | 新增: } | |
| 104 | 新增: await Task.Delay(500); | |
| 105 | 新增: } | |
| 106 | 新增: if (!ready) throw new IOException("新版工作台未能完成启动确认"); | |
| 107 | 新增: succeeded = true; | |
| 108 | 新增: Result(true, "Cage 已更新至 " + plan.Version); | |
| 109 | 新增: // The currently executing helper cannot delete itself on Windows. | |
| 110 | 新增: // Keep this small signed file; the next successful update may remove it. | |
| 111 | 新增: return 0; | |
| 112 | 新增: } | |
| 113 | 新增: catch (Exception error) | |
| 114 | 新增: { | |
| 115 | 新增: if (succeeded) return 0; | |
| 116 | 新增: var detail = error.Message; | |
| 117 | 新增: if (replaced && plan != null && backup != null) | |
| 118 | 新增: { | |
| 119 | 新增: try | |
| 120 | 新增: { | |
| 121 | 新增: // Stop the exact new controller through its lifecycle API before | |
| 122 | 新增: // restoring files. Never kill other Cage instances by name. | |
| 123 | 新增: Authenticode.SamePublisher(UpdateRecovery.BackendPath(backup), plan.Publisher); | |
| 124 | 新增: await UpdateRecovery.PrepareRollback(backup); | |
| 125 | 新增: if (launched is { HasExited: false }) { launched.Kill(); await launched.WaitForExitAsync(); } | |
| 126 | 新增: var restored = plan.Target + ".restore-" + plan.Confirmation; | |
| 127 | 新增: var failed = plan.Target + ".failed-" + plan.Confirmation; | |
| 128 | 新增: CopyTree(backup, restored); | |
| 129 | 新增: var hadCandidate = Directory.Exists(plan.Target); | |
| 130 | 新增: if (hadCandidate) Directory.Move(plan.Target, failed); | |
| 131 | 新增: try { Directory.Move(restored, plan.Target); } | |
| 132 | 新增: catch { if (hadCandidate) Directory.Move(failed, plan.Target); throw; } | |
| 133 | 新增: UpdateRecovery.CleanupDirectory(backup); backup = null; | |
| 134 | 新增: Result(false, "更新未完成,已恢复原应用:" + detail); | |
| 135 | 新增: Process.Start(new ProcessStartInfo(Path.Combine(plan.Target, "Cage.exe")) { UseShellExecute = false, WorkingDirectory = plan.Target }); | |
| 136 | 新增: return 1; | |
| 137 | 新增: } | |
| 138 | 新增: catch (Exception recovery) { detail += ";自动恢复未完成,原应用备份已保留:" + recovery.Message; } | |
| 139 | 新增: } | |
| 140 | 新增: Result(false, "更新未完成:" + detail); | |
| 141 | 新增: if (committed && !replaced && plan != null) | |
| 142 | 新增: { | |
| 143 | 新增: try | |
| 144 | 新增: { | |
| 145 | 新增: var original = Path.Combine(plan.Target, "Cage.exe"); | |
| 146 | 新增: Authenticode.SamePublisher(original, plan.Publisher); | |
| 147 | 新增: Process.Start(new ProcessStartInfo(original) { UseShellExecute = false, WorkingDirectory = plan.Target }); | |
| 148 | 新增: } | |
| 149 | 新增: catch (Exception restart) when (restart is IOException or System.ComponentModel.Win32Exception) { } | |
| 150 | 新增: } | |
| 151 | 新增: return 1; | |
| 152 | 新增: } | |
| 153 | 新增: finally | |
| 154 | 新增: { | |
| 155 | 新增: launched?.Dispose(); | |
| 156 | 新增: if (succeeded && plan != null && backup != null) | |
| 157 | 新增: UpdateRecovery.CleanupAfterSuccess(backup, Path.GetDirectoryName(plan.Archive)!, Path.Combine(AppUpdater.Root, "launch-" + plan.Confirmation + ".json")); | |
| 158 | 新增: else if (!replaced) UpdateRecovery.CleanupDirectory(backup); | |
| 159 | 新增: } | |
| 160 | 新增: } | |
| 161 | 新增: | |
| 162 | 新增: private static void Result(bool success, string message) | |
| 163 | 新增: { | |
| 164 | 新增: try | |
| 165 | 新增: { | |
| 166 | 新增: Directory.CreateDirectory(AppUpdater.Root); UpdatePolicy.PlainPath(AppUpdater.Root); | |
| 167 | 新增: File.WriteAllText(Path.Combine(AppUpdater.Root, "last-result.json"), JsonSerializer.Serialize(new { success, message })); | |
| 168 | 新增: } | |
| 169 | 新增: catch (IOException) { } | |
| 170 | 新增: catch (UnauthorizedAccessException) { } | |
| 171 | 新增: } | |
| 172 | 新增: | |
| 173 | 新增: private static void CopyTree(string source, string target) | |
| 174 | 新增: { | |
| 175 | 新增: UpdatePolicy.PlainPath(source); Directory.CreateDirectory(target); | |
| 176 | 新增: long size = 0; var count = 0; | |
| 177 | 新增: var pending = new Queue<string>(); pending.Enqueue(source); | |
| 178 | 新增: while (pending.TryDequeue(out var directory)) | |
| 179 | 新增: foreach (var entry in Directory.EnumerateFileSystemEntries(directory)) | |
| 180 | 新增: { | |
| 181 | 新增: var attributes = File.GetAttributes(entry); | |
| 182 | 新增: if (++count > 100000 || (attributes & FileAttributes.ReparsePoint) != 0) | |
| 183 | 新增: throw new IOException("安装目录包含联接或过多文件,无法安全备份"); | |
| 184 | 新增: var destination = Path.Combine(target, Path.GetRelativePath(source, entry)); | |
| 185 | 新增: if ((attributes & FileAttributes.Directory) != 0) { Directory.CreateDirectory(destination); pending.Enqueue(entry); } | |
| 186 | 新增: else | |
| 187 | 新增: { | |
| 188 | 新增: size += new FileInfo(entry).Length; | |
| 189 | 新增: if (size > (4L << 30)) throw new IOException("安装目录超过允许的备份大小"); | |
| 190 | 新增: File.Copy(entry, destination, false); | |
| 191 | 新增: } | |
| 192 | 新增: } | |
| 193 | 新增: } | |
| 194 | 新增:} | |
| @@ -0,0 +1,75 @@ | ||
| 1 | 新增:using System.Globalization; | |
| 2 | 新增:using System.Text.RegularExpressions; | |
| 3 | 新增: | |
| 4 | 新增:namespace Cage.Windows; | |
| 5 | 新增: | |
| 6 | 新增:internal static partial class UpdatePolicy | |
| 7 | 新增:{ | |
| 8 | 新增: public static bool IsWorkbench(string? raw, int port) => | |
| 9 | 新增: Uri.TryCreate(raw, UriKind.Absolute, out var url) && port > 0 && | |
| 10 | 新增: url.Scheme == "http" && url.Host == "localhost" && url.Port == port && | |
| 11 | 新增: url.UserInfo.Length == 0; | |
| 12 | 新增: | |
| 13 | 新增: public static Uri Entry(string raw) | |
| 14 | 新增: { | |
| 15 | 新增: if (!Uri.TryCreate(raw, UriKind.Absolute, out var url) || | |
| 16 | 新增: !IsWorkbench(raw, url.Port) || url.Port <= 0 || url.Fragment.Length < 2) | |
| 17 | 新增: throw new InvalidDataException("后台返回了无效的工作台地址"); | |
| 18 | 新增: return url; | |
| 19 | 新增: } | |
| 20 | 新增: | |
| 21 | 新增: [GeneratedRegex(@"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$")] | |
| 22 | 新增: private static partial Regex VersionPattern(); | |
| 23 | 新增: | |
| 24 | 新增: private static string[]? VersionParts(string value) | |
| 25 | 新增: { | |
| 26 | 新增: var match = VersionPattern().Match(value); | |
| 27 | 新增: if (!match.Success) return null; | |
| 28 | 新增: var pre = match.Groups[4].Value; | |
| 29 | 新增: if (pre.Split('.').Any(x => x.Length > 1 && x[0] == '0' && x.All(char.IsAsciiDigit))) return null; | |
| 30 | 新增: return [match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value, pre]; | |
| 31 | 新增: } | |
| 32 | 新增: | |
| 33 | 新增: private static int Number(string a, string b) => a.Length != b.Length | |
| 34 | 新增: ? a.Length.CompareTo(b.Length) : string.CompareOrdinal(a, b); | |
| 35 | 新增: | |
| 36 | 新增: public static bool IsNewer(string candidate, string current) | |
| 37 | 新增: { | |
| 38 | 新增: var a = VersionParts(candidate); var b = VersionParts(current); | |
| 39 | 新增: if (a == null || b == null) return false; | |
| 40 | 新增: for (var i = 0; i < 3; i++) | |
| 41 | 新增: if (a[i] != b[i]) return Number(a[i], b[i]) > 0; | |
| 42 | 新增: if (a[3].Length == 0 || b[3].Length == 0) return a[3].Length == 0 && b[3].Length != 0; | |
| 43 | 新增: var x = a[3].Split('.'); var y = b[3].Split('.'); | |
| 44 | 新增: for (var i = 0; i < Math.Min(x.Length, y.Length); i++) | |
| 45 | 新增: { | |
| 46 | 新增: if (x[i] == y[i]) continue; | |
| 47 | 新增: var xn = x[i].All(char.IsAsciiDigit); var yn = y[i].All(char.IsAsciiDigit); | |
| 48 | 新增: if (xn != yn) return !xn; | |
| 49 | 新增: return (xn ? Number(x[i], y[i]) : string.CompareOrdinal(x[i], y[i])) > 0; | |
| 50 | 新增: } | |
| 51 | 新增: return x.Length > y.Length; | |
| 52 | 新增: } | |
| 53 | 新增: | |
| 54 | 新增: public static string DownloadPath(string raw, string updateRoot) | |
| 55 | 新增: { | |
| 56 | 新增: var path = Path.GetFullPath(raw); | |
| 57 | 新增: var directory = Path.GetDirectoryName(path) ?? ""; | |
| 58 | 新增: if (!string.Equals(Path.GetDirectoryName(directory), Path.GetFullPath(updateRoot).TrimEnd(Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase) || | |
| 59 | 新增: !Path.GetFileName(directory).StartsWith("download-", StringComparison.Ordinal) || | |
| 60 | 新增: !string.Equals(Path.GetFileName(path), "Cage-setup.exe", StringComparison.Ordinal)) | |
| 61 | 新增: throw new InvalidDataException("更新安装包不属于 Cage 的私有下载目录"); | |
| 62 | 新增: return path; | |
| 63 | 新增: } | |
| 64 | 新增: | |
| 65 | 新增: public static void PlainPath(string path) | |
| 66 | 新增: { | |
| 67 | 新增: var entry = Path.GetFullPath(path); | |
| 68 | 新增: while (!string.IsNullOrEmpty(entry)) | |
| 69 | 新增: { | |
| 70 | 新增: if ((File.Exists(entry) || Directory.Exists(entry)) && (File.GetAttributes(entry) & FileAttributes.ReparsePoint) != 0) | |
| 71 | 新增: throw new InvalidDataException("更新路径包含符号链接或目录联接"); | |
| 72 | 新增: entry = Path.GetDirectoryName(entry); | |
| 73 | 新增: } | |
| 74 | 新增: } | |
| 75 | 新增:} | |
| @@ -0,0 +1,34 @@ | ||
| 1 | 新增:namespace Cage.Windows; | |
| 2 | 新增: | |
| 3 | 新增:internal static class UpdateRecovery | |
| 4 | 新增:{ | |
| 5 | 新增: public static string BackendPath(string backup) => Path.Combine(backup, "resources", "cage.exe"); | |
| 6 | 新增: | |
| 7 | 新增: // The installed candidate may be unable to start. Use the existing backup's | |
| 8 | 新增: // verified controller to check the shared profile and stop any new process. | |
| 9 | 新增: public static async Task PrepareRollback(string backup, CancellationToken cancellation = default) | |
| 10 | 新增: { | |
| 11 | 新增: var (exit, result) = await Backend.JsonAt(BackendPath(backup), ["prepare-update", "--json", "--stop"], cancellation); | |
| 12 | 新增: if (exit != 0 || result.Text("status") != "prepared") | |
| 13 | 新增: throw new IOException("旧版后台无法确认环境已停止,原应用备份已保留"); | |
| 14 | 新增: } | |
| 15 | 新增: | |
| 16 | 新增: public static void CleanupDirectory(string? path) | |
| 17 | 新增: { | |
| 18 | 新增: if (path == null) return; | |
| 19 | 新增: try { Directory.Delete(path, true); } | |
| 20 | 新增: catch (IOException) { } | |
| 21 | 新增: catch (UnauthorizedAccessException) { } | |
| 22 | 新增: } | |
| 23 | 新增: | |
| 24 | 新增: // This only runs after workbench acknowledgement. Cleanup failures leave | |
| 25 | 新增: // files for later removal and cannot change the installation result. | |
| 26 | 新增: public static void CleanupAfterSuccess(string backup, string download, string marker) | |
| 27 | 新增: { | |
| 28 | 新增: CleanupDirectory(backup); | |
| 29 | 新增: CleanupDirectory(download); | |
| 30 | 新增: try { File.Delete(marker); } | |
| 31 | 新增: catch (IOException) { } | |
| 32 | 新增: catch (UnauthorizedAccessException) { } | |
| 33 | 新增: } | |
| 34 | 新增:} | |
| @@ -0,0 +1,14 @@ | ||
| 1 | 新增:<?xml version="1.0" encoding="utf-8"?> | |
| 2 | 新增:<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> | |
| 3 | 新增: <assemblyIdentity version="1.0.0.0" name="Cage.Windows" /> | |
| 4 | 新增: <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"><security><requestedPrivileges> | |
| 5 | 新增: <requestedExecutionLevel level="asInvoker" uiAccess="false" /> | |
| 6 | 新增: </requestedPrivileges></security></trustInfo> | |
| 7 | 新增: <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"><application> | |
| 8 | 新增: <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" /> | |
| 9 | 新增: </application></compatibility> | |
| 10 | 新增: <application xmlns="urn:schemas-microsoft-com:asm.v3"><windowsSettings> | |
| 11 | 新增: <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware> | |
| 12 | 新增: <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness> | |
| 13 | 新增: </windowsSettings></application> | |
| 14 | 新增:</assembly> | |
| @@ -0,0 +1,27 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "version": 1, | |
| 3 | 新增: "dependencies": { | |
| 4 | 新增: "net10.0-windows10.0.19041": { | |
| 5 | 新增: "Microsoft.NET.ILLink.Tasks": { | |
| 6 | 新增: "type": "Direct", | |
| 7 | 新增: "requested": "[10.0.14, )", | |
| 8 | 新增: "resolved": "10.0.14", | |
| 9 | 新增: "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" | |
| 10 | 新增: }, | |
| 11 | 新增: "Microsoft.Web.WebView2": { | |
| 12 | 新增: "type": "Direct", | |
| 13 | 新增: "requested": "[1.0.4314.35, )", | |
| 14 | 新增: "resolved": "1.0.4314.35", | |
| 15 | 新增: "contentHash": "x5MFf2W03xueU1mMNvivXfHSsQ+ODo7vJ36qw/dLtU5Gs+8d7+7N7zzmNNDoT3ffosmcvZNBtUnlzyiDUuBkSQ==" | |
| 16 | 新增: } | |
| 17 | 新增: }, | |
| 18 | 新增: "net10.0-windows10.0.19041/win-x64": { | |
| 19 | 新增: "Microsoft.Web.WebView2": { | |
| 20 | 新增: "type": "Direct", | |
| 21 | 新增: "requested": "[1.0.4314.35, )", | |
| 22 | 新增: "resolved": "1.0.4314.35", | |
| 23 | 新增: "contentHash": "x5MFf2W03xueU1mMNvivXfHSsQ+ODo7vJ36qw/dLtU5Gs+8d7+7N7zzmNNDoT3ffosmcvZNBtUnlzyiDUuBkSQ==" | |
| 24 | 新增: } | |
| 25 | 新增: } | |
| 26 | 新增: } | |
| 27 | 新增:} | |
| 文件末尾没有换行 | ||
| @@ -8,6 +8,8 @@ | ||
| 8 | 8 | |---|---| |
| 9 | 9 | | 安装、配置代理、打开第一个项目 | [开始使用](getting-started.md) | |
| 10 | 10 | | 查看快捷键、文件保存、关闭与退出行为 | [日常使用](getting-started.md#日常使用) | |
| 11 | 新增:| 在 Windows 上安装、使用和更新 | [Windows 支持](windows.md) | | |
| 12 | 新增:| 在 Linux 上安装、使用和更新 | [Linux 支持](linux.md) | | |
| 11 | 13 | | 升级应用、更新环境工具或卸载 | [升级与卸载](getting-started.md#升级与卸载) | |
| 12 | 14 | | 查看首个内测版本的能力与验收范围 | [0.1.0-alpha.1 发行说明](releases/0.1.0-alpha.1.md) | |
| 13 | 15 | | 排查下载、启动、联网与授权问题 | [常见问题与恢复](troubleshooting.md) | |
| @@ -22,6 +24,8 @@ | ||
| 22 | 24 | | 理解网络检查、暂停与恢复 | [网络检查设计](design/network-checks.md) | |
| 23 | 25 | | 理解节点配置、代理核心与凭据归属 | [内置代理设计](design/managed-proxy.md) | |
| 24 | 26 | | 构建签名、公证的 macOS 安装包 | [发布 macOS 安装包](releasing.md) | |
| 27 | 新增:| 构建 Windows 安装包与执行平台验收 | [Windows 构建与验收](windows.md#维护者构建与验收) | | |
| 28 | 新增:| 运行三平台 CI、配置签名和自动发布 | [CI/CD 指南](ci-cd.md) | | |
| 25 | 29 | | 发布 Release、验证公开附件与部署主页 | [公开发行与主页部署](public-releases.md) | |
| 26 | 30 | |
| 27 | 31 | ## 上游与许可 |
| @@ -0,0 +1,94 @@ | ||
| 1 | 新增:# 三平台检查与发布 | |
| 2 | 新增: | |
| 3 | 新增:Cage 的日常推送会检查 macOS、Windows 和 Linux,并保存测试安装包。公开发布需要用户明确要求后单独触发;日常推送、测试重跑和测试包下载都不会升级版本号或创建 Release。 | |
| 4 | 新增: | |
| 5 | 新增:工作流需要与对应的三平台应用源码一并合入远端后才生效。本地保存配置不会改变 GitHub 上既有工作流的行为;首次接入应先完成源码整理与三平台检查,再启用显式发布入口。 | |
| 6 | 新增: | |
| 7 | 新增:## 日常开发 | |
| 8 | 新增: | |
| 9 | 新增:向工作分支或 main 推送代码、提交 Pull Request 后,`Three-platform checks and test packages` 会运行以下流程: | |
| 10 | 新增: | |
| 11 | 新增:1. 检查版本一致性、发布逻辑测试和工作流语法。 | |
| 12 | 新增:2. 从同一个提交分别构建 Apple Silicon macOS、Windows x64 和 Linux x64。 | |
| 13 | 新增:3. 执行对应测试与安装检查,保存可下载的测试包和验收报告。 | |
| 14 | 新增: | |
| 15 | 新增:在仓库的 [Actions 页面](https://github.com/Lee-xeo/Claude-Cage/actions) 打开本次运行,可在 Artifacts 中下载测试包。测试包沿用 `VERSION` 中的版本号,每次运行以提交 SHA 区分;macOS 包保留完整 App 权限,Windows 包明确标为未签名,Linux 输出 `.deb`。测试包不会进入应用更新源。 | |
| 16 | 新增: | |
| 17 | 新增:官网文件的普通推送只做检查和构建。官网部署随显式发布流程完成,也可以由维护者明确运行网站部署工作流。 | |
| 18 | 新增: | |
| 19 | 新增:## 明确发版后的自动流程 | |
| 20 | 新增: | |
| 21 | 新增:用户要求发版后,维护者在 main 上运行 `Publish Cage after an explicit release request`。也可以在收到用户的发版指令后执行: | |
| 22 | 新增: | |
| 23 | 新增:```sh | |
| 24 | 新增:gh workflow run release.yml --repo Lee-xeo/Claude-Cage --ref main -f bump=prerelease | |
| 25 | 新增:``` | |
| 26 | 新增: | |
| 27 | 新增:`prerelease` 用于继续当前 Alpha/Beta 序列;`patch` 发布修订版本(已有预发行时转为对应正式版);`minor` 和 `major` 分别提升次版本、主版本。流程从源码版本、已存在的规范版本标签和 Release 中取最高版本作为起点,避免复用已占用的版本,包括草稿。 | |
| 28 | 新增: | |
| 29 | 新增:例如最高已用版本为 `0.2.0-alpha.1`,选择 `prerelease` 会生成 `0.2.0-alpha.2`,选择 `patch` 会生成 `0.2.0`。普通推送不会执行这些计算和修改。 | |
| 30 | 新增: | |
| 31 | 新增:发布流程依次执行: | |
| 32 | 新增: | |
| 33 | 新增:1. 检查签名、公证与对应源码材料是否配置齐全。缺少任何必需材料就停止,尚不创建版本提交。 | |
| 34 | 新增:2. 在 `codex/release/<运行编号>` 候选分支同步 `VERSION` 与 UI、官网的 package/lock 版本,只修改五个版本文件。 | |
| 35 | 新增:3. 三个平台构建同一个候选提交,完成各自的检查。macOS 执行 Developer ID 签名与 Apple 公证,Windows 执行可信 Authenticode 签名,Linux 生成系统安装包。 | |
| 36 | 新增:4. 核对三端产物版本和源码 SHA,一起校验安装包、随附组件对应源码及统一 `SHA256SUMS`。 | |
| 37 | 新增:5. 确认 main 没有被其他提交推进,原子快进 main 并创建版本标签。创建草稿 Release,上传并核对全部附件,最后公开发布。 | |
| 38 | 新增:6. 重新验证本次公开版本,并部署指向该版本的官网。 | |
| 39 | 新增: | |
| 40 | 新增:任一平台失败时不会公开 Release。构建过程中 main 出现新提交,也会停止发布;流程不强推、不覆盖别人的提交。候选分支保留本次版本与提交,便于失败后继续。 | |
| 41 | 新增: | |
| 42 | 新增:发布使用普通版本与预发行通道的既有规则。硬件虚拟化、真实桌面操作和 Claude 账户使用仍属于实机验收,不能由托管 CI 编译成功替代;发行说明需要如实说明范围。 | |
| 43 | 新增: | |
| 44 | 新增:## 首次配置发布材料 | |
| 45 | 新增: | |
| 46 | 新增:在仓库 Settings → Environments 中使用 `cage-release` 环境,仅允许 main 部署。日常构建不进入这个环境,也不接触签名材料。配置操作不会自行触发发版。 | |
| 47 | 新增: | |
| 48 | 新增:以下内容放入该环境的 Secrets,不能提交到源码或粘贴到公开日志: | |
| 49 | 新增: | |
| 50 | 新增:| Secret | 用途 | | |
| 51 | 新增:|---|---| | |
| 52 | 新增:| `CAGE_MACOS_P12_BASE64` | 含 Developer ID Application 私钥的 P12 文件,以 Base64 保存 | | |
| 53 | 新增:| `CAGE_MACOS_P12_PASSWORD` | P12 导出密码 | | |
| 54 | 新增:| `CAGE_MACOS_SIGNING_IDENTITY` | 完整的 Developer ID Application 身份名称 | | |
| 55 | 新增:| `CAGE_MACOS_NOTARY_KEY_BASE64` | App Store Connect 团队 API 私钥,以 Base64 保存 | | |
| 56 | 新增:| `CAGE_MACOS_NOTARY_KEY_ID` | API Key ID | | |
| 57 | 新增:| `CAGE_MACOS_NOTARY_ISSUER_ID` | API Issuer ID | | |
| 58 | 新增:| `CAGE_MACOS_PROVISIONING_PROFILE_BASE64` | 可选;原生能力需要时提供对应 Provisioning Profile | | |
| 59 | 新增:| `CAGE_WINDOWS_PFX_BASE64` | 含可信代码签名私钥的 PFX 文件,以 Base64 保存 | | |
| 60 | 新增:| `CAGE_WINDOWS_PFX_PASSWORD` | PFX 密码 | | |
| 61 | 新增: | |
| 62 | 新增:Windows 对应源码地址放入同一环境的 Variables: | |
| 63 | 新增: | |
| 64 | 新增:| Variable | 用途 | | |
| 65 | 新增:|---|---| | |
| 66 | 新增:| `CAGE_WINDOWS_QEMU_SOURCE_URL` | 经核对的完整 QEMU 对应源码归档公开 HTTPS 地址,不含认证信息或临时签名参数,包含随附库与固件源码 | | |
| 67 | 新增:| `CAGE_WINDOWS_QEMU_SOURCE_SHA256` | 该归档的 SHA-256 | | |
| 68 | 新增: | |
| 69 | 新增:Windows 的普通开发包不需要证书。正式发布缺少可信证书时停止,不能用自签名证书或未签名包代替。当前签名接入使用 PFX;若以后采用硬件密钥或云签名服务,应调整签名接入并重新验收。 | |
| 70 | 新增: | |
| 71 | 新增:macOS 使用临时钥匙串,Windows 使用临时证书导入;成功、失败及中断路径均清理签名材料。发布产物只包含安装包、对应源码和摘要;中间公证凭据、私钥与配置文件不进入附件。 | |
| 72 | 新增: | |
| 73 | 新增:签名文件通常体积较小,按 GitHub Secret 的限制保存;首次使用前应在相应平台确认凭据可用。材料存在不代表签名、公证或安装一定成功,正式构建仍会验证。 | |
| 74 | 新增: | |
| 75 | 新增:## 失败后继续 | |
| 76 | 新增: | |
| 77 | 新增:从原来的 Actions 运行选择重跑失败任务。相同运行编号复用同一个候选版本,不再次升级版本号。已经上传到本次私有草稿且摘要匹配的文件会复用;不匹配的本次草稿附件可重新上传。公开 Release 的附件不会被自动替换。 | |
| 78 | 新增: | |
| 79 | 新增:如果发布已经完成而官网部署失败,可以重跑网站任务;发布步骤重跑会确认公开附件仍与验证结果一致。不要新建另一轮发布来重试同一个版本,也不要手工编辑仍在执行中的候选分支或草稿附件。 | |
| 80 | 新增: | |
| 81 | 新增:若 main 已经有新提交,需要重新发起一次明确的发布请求,让新提交参与同一轮验证。Actions 测试产物默认保留 14 天;产物过期后需要重新构建对应候选提交。 | |
| 82 | 新增: | |
| 83 | 新增:## 工作流与验证边界 | |
| 84 | 新增: | |
| 85 | 新增:- `.github/workflows/ci.yml`:日常只读检查与测试包入口。 | |
| 86 | 新增:- `.github/workflows/release.yml`:显式发布入口及三端汇总。 | |
| 87 | 新增:- `macos-build.yml`、`windows-build.yml`、`linux-build.yml`:日常与发布共用的构建、检查契约。 | |
| 88 | 新增:- `.github/workflows/www.yml`:官网检查与显式部署,发布时使用明确的版本标签。 | |
| 89 | 新增:- `scripts/release-version.mjs`:版本选择、五文件同步内容与产物来源记录。 | |
| 90 | 新增:- `scripts/release-control.mjs`:候选提交、完整附件校验和发布重试。 | |
| 91 | 新增: | |
| 92 | 新增:GitHub 允许通过 `workflow_call` 复用构建任务;环境凭据在实际执行的任务上加载。[GitHub 文档](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows) 使用 `GITHUB_TOKEN` 创建的 push/Release 事件通常不会再触发其他工作流,因此发布入口直接调用网站工作流,不依赖隐式事件串联。[触发规则](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow) | |
| 93 | 新增: | |
| 94 | 新增:根目录 `release.sh` 保留的是上游 agent-vm 的发行流程,不用于 Cage 三平台自动发布。 | |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # Cage 内置代理 |
| 2 | 2 | |
| 3 | 删除:本文说明 macOS Cage 内置代理的产品范围和工程边界。应用随附独立核心,管理订阅、节点和代理生命周期;客机公网 UDP、IPv6、ICMP 持续阻断。联网授权规则见[网络检测设计](network-checks.md),界面入口见[工作台设计](workbench.md)。发行版本的验证范围以 GitHub Release 说明为准;本地验收截图和原始运行数据不随源码发布。 | |
| 3 | 新增:本文说明 Cage 内置代理的产品范围和工程边界。应用随附独立核心,管理订阅、节点和代理生命周期;客机公网 UDP、IPv6、ICMP 持续阻断。联网授权规则见[网络检测设计](network-checks.md),界面入口见[工作台设计](workbench.md)。发行版本的验证范围以 GitHub Release 说明为准;本地验收截图和原始运行数据不随源码发布。 | |
| 4 | 4 | |
| 5 | 5 | ## 用户怎样使用 |
| 6 | 6 | |
| @@ -46,10 +46,18 @@ Cage 代理管理界面 → 已认证的 Cage 控制服务 → 私有控制 sock | ||
| 46 | 46 | |
| 47 | 47 | Mihomo 以随 App 分发的独立进程运行,由 Cage 控制服务负责启动、就绪检查、停止和配置切换;故障后用户可以重新应用节点或重启核心。运行不引用 `/Applications/Clash Verge.app`,不搜索 PATH。构建固定 `v1.19.33`,校验官方发布压缩包的 SHA-256,并将来源与 GPL-3.0 许可资料放入制品。工作台或 App 窗口关闭而环境保留运行时,独立 launchd 任务继续提供代理;明确停止环境会停止该核心。 |
| 48 | 48 | |
| 49 | 新增:Linux 将核心作为普通用户的独立后台进程运行,窗口关闭后继续提供代理。私有进程记录包含可执行文件、启动时间与系统启动标识;停止前用 pidfd 固定并核验进程身份,避免误停复用同一 PID 的其他程序。Linux 根据 IPv4 默认路由与物理设备归属选择 PCI、USB 或 virtio 网卡,排除隧道、桥接和容器 veth;找不到符合条件的出口时保持离线。实现需要 Linux 5.3 或更新内核。 | |
| 50 | 新增: | |
| 49 | 51 | 前端继续使用 Cage 现有认证接口,不直接持有核心控制权限。核心控制 socket 放在主机私有目录,guest 无法访问;订阅 URL、节点凭据和完整配置同样不进入共享项目、普通日志或状态接口。socket 的目录和文件权限必须落实,不能依赖核心 HTTP secret 保护 Unix socket。 |
| 50 | 52 | |
| 51 | 53 | 导入内容只提供节点、必要的代理链和来源信息;Cage 自己生成运行配置。外部配置不能覆盖监听端口、控制接口、TUN、DNS 边界、文件路径或全局出站规则。Cage 业务流量统一走选定节点,不引入订阅中的 DIRECT 回退规则。 |
| 52 | 54 | |
| 55 | 新增:## 依赖安装与更新 | |
| 56 | 新增: | |
| 57 | 新增:Cage 的环境组件同步、固定工具升级和 Claude Desktop 安装需要在业务网络尚未放行时下载依赖。这些操作使用短时维护通道:固定安装脚本经 SSH 连接主机上的认证代理,再通过当前所选节点访问软件源。维护操作不授予业务联网权限,不解除人工暂停,也不向普通终端注入代理凭据。 | |
| 58 | 新增: | |
| 59 | 新增:维护代理只接受 Debian、NodeSource、GitHub 发布文件、npm 和 Anthropic 下载服务的指定域名,限定 HTTP 80 与 HTTPS 443;HTTP 请求限于 GET/HEAD,HTTPS 按目标域名限制隧道。它不校验 HTTPS 隧道内的具体请求路径,安装器继续负责软件包签名或摘要校验。临时凭据经 SSH 标准输入传递;任务结束、失败或取消时关闭代理及连接并清理凭据。所选代理不可用时失败,不回退主机直连。此路径由三平台共用的后端和客机安装脚本实现。 | |
| 60 | 新增: | |
| 53 | 61 | ## 与本机 Clash 共存 |
| 54 | 62 | |
| 55 | 63 | 使用独立配置、缓存、日志、进程和监听地址,仅绑定 loopback。默认沿用 Cage 专用端口 `17896`,占用时给出冲突提示并允许配置其他端口;不终止占用者,也不连接来源未知的现有监听器。代理入口采用 Cage 私有认证。 |
| @@ -66,7 +74,9 @@ Cage 不设置主机系统代理,不开启主机 TUN,不修改本机 Clash | ||
| 66 | 74 | |
| 67 | 75 | Cage 业务 DNS 继续通过选定节点发送,不回退主机解析器。订阅下载、首次节点服务器域名解析属于代理自身的启动通信,需要与业务流量分开说明。 |
| 68 | 76 | |
| 69 | 删除:订阅默认经当前配置的代理下载;没有节点时可导入本地文件,或明确选择通过主机网络下载。手动更新提供相同的主机下载选项;自动更新始终使用已配置代理,失败后至少间隔 15 分钟重试。下载只接受 HTTPS,限制大小和重定向次数,不静默切换路径,不调用本机 Clash 接口。主机下载的域名和核心节点服务器域名使用 IP 定位的 `https://1.1.1.1/dns-query` 启动解析;这部分通信独立于业务 DNS,界面予以说明。 | |
| 77 | 新增:订阅默认经当前配置的代理下载;没有节点时可导入本地文件,或明确选择通过主机网络下载。手动更新提供相同的主机下载选项;自动更新始终使用已配置代理,失败后至少间隔 15 分钟重试。下载只接受 HTTPS,限制大小和重定向次数,不静默切换路径,不调用本机 Clash 接口。 | |
| 78 | 新增: | |
| 79 | 新增:主机下载的域名和核心节点服务器域名使用两个 IP 定位的加密 DNS:Cloudflare `https://1.1.1.1/dns-query` 和[阿里公共 DNS](https://static-aliyun-doc.oss-cn-hangzhou.aliyuncs.com/download%2Fpdf%2F171662%2FAPI_Reference_intl_en-US.pdf) `https://223.5.5.5/dns-query`。二者并行查询,单个服务不可达不会阻塞另一个;主机下载的启动解析最多等待 8 秒,收到有效公网 IPv4 后取消其余请求。节点域名解析由 Mihomo 的多服务器解析器执行。这部分通信通过主机网络,域名可能发送给两个 DNS 服务,独立于业务 DNS;状态和诊断页面列出这两个服务。两者失败时不回退系统 DNS、明文 DNS 或未经验证的 TLS 连接。客机业务 DNS 仍经选定节点发送。 | |
| 70 | 80 | |
| 71 | 81 | ## 节点切换与检查 |
| 72 | 82 | |
| @@ -8,6 +8,7 @@ Cage 先启动可离线使用的环境,再检查网络与配置。关键项通 | ||
| 8 | 8 | - 动态 IP:允许换地址,可限定同一城市、同一国家/地区,或不限制地区。城市同时比较国家、州/省和城市名称。 |
| 9 | 9 | - 已保存的地址和地区不会被重检、重启或后台定位结果自动替换。首次未配置时可以采用检测结果;改动已有基准需要在设置中明确保存。 |
| 10 | 10 | - 时区和语言可以在启动或应用设置时采用出口地区建议。运行中的环境不会因后台监测静默重启。语言采用内置地区默认值;多语言地区允许手动覆盖,未提供建议的地区保留已选语言。 |
| 11 | 新增:- 位置查询失败后可点击“手动设置时区和语言”,关闭两个自动开关并编辑系统时区、系统语言与网页首选语言。使用静态 IP 或不限制地区时,手动模式在保存和启动时仅测量出口 IP,跳过位置查询;国家或城市限制仍需实际位置证据。切换手动模式不会修改出口规则。 | |
| 11 | 12 | |
| 12 | 13 | 地区约束依据 IP 数据库,属于近似定位。运行中约每 30 秒采样一次,发现越界或无法确认受限地区时暂停外网。通用 HTTP/SOCKS5 协议不能约束代理运营方每条连接使用哪个出口,因此 Cage 的规则是**检查采样并在发现异常后阻断**;上游的静态出口、会话粘性和地区路由仍需由代理本身保证。 |
| 13 | 14 | |
| @@ -59,6 +60,8 @@ VM 外出站控制由 hostagent 持有。新实例默认关闭外网,guest 内 | ||
| 59 | 60 | |
| 60 | 61 | ## 外部服务与隐私 |
| 61 | 62 | |
| 62 | 删除:固定出口查询使用 [ipify 的公开接口](https://www.ipify.org/)。地区信息查询使用 [ipwho.is 的指定 IP 查询接口](https://ipwhois.io/documentation),查询地址与实际测到的出口绑定。同一 IP 的位置缓存一小时,最多保存 64 条,以减少查询和配额占用;该服务公开的免费额度为每出口每天 1,000 次,超限或不可用时不能把缺失定位判为处于允许范围。 | |
| 63 | 新增:固定出口查询使用 [ipify 的公开接口](https://www.ipify.org/)。地区信息优先查询 [ipwho.is](https://ipwhois.io/documentation),连接失败、超时、限流或位置无效时改查 [IP.SB](https://ip.sb/api/)。每个服务的请求最多等待 8 秒,取消检查会停止后续查询。两项位置查询都通过选定代理,携带已经测得的出口 IP;返回 IP 必须与之相同,国家代码和 IANA 时区必须有效。备用服务不会改变出口规则、时区或语言的保存基准。 | |
| 64 | 新增: | |
| 65 | 新增:同一 IP 的位置缓存一小时,最多保存 64 条,以减少查询和配额占用。各服务的免费额度和可用性由服务商决定;所有服务均失败时,报告会区分已取得出口 IP 与位置查询失败,受国家或城市约束的网络继续保持关闭。用户可关闭自动时区和自动语言并手动选择;手动时区、语言不能替代出口地区的检测证据。 | |
| 63 | 66 | |
| 64 | 67 | 社区检测网站仅在用户点击时从 Cage 浏览器打开,不自动抓取内部接口或上传完整报告。来源、许可及可采用的方法见[社区工具核查](../research/community-safety-tools.md)。分享报告会去掉配置指纹、运行标识、代理凭据、IP 地址和本机路径,不能用于放行环境。 |
| @@ -1,6 +1,20 @@ | ||
| 1 | 1 | # Cage 工作台 |
| 2 | 2 | |
| 3 | 删除:Cage 面向在本机项目中编码的用户。主界面管理本地项目、网页、终端和文件编辑器;设置页集中管理环境配置。界面采用 Codex 桌面端的侧栏与内容区结构,保留 Cage 的名称和图标,不提供账户或云端协作入口。 | |
| 3 | 新增:Cage 面向在本机项目中编码的用户。主界面管理本地项目、网页、终端和文件编辑器;设置页集中管理环境配置。界面采用 Codex 桌面端的侧栏与内容区结构,保留 Cage 的名称和图标,提供单个本地账户,不连接云端账户服务。 | |
| 4 | 新增: | |
| 5 | 新增:## 本地账户与锁定 | |
| 6 | 新增: | |
| 7 | 新增:每份 Cage 配置只有一个本地账户,与同一个持久环境关联。首次使用设置用户名和密码,随后通过密码解锁;左下角显示头像和用户名,菜单提供账户设置、应用设置、锁定与退出账户。头像接受不超过 2 MB 的 PNG/JPEG,在本机居中裁切为 128×128 PNG,资料和密码分别保存。 | |
| 8 | 新增: | |
| 9 | 新增:“锁定 Cage”关闭工作台的终端与画面连接,保留后台进程;重新解锁恢复连接。“退出账户”先停止环境,成功后清除驻留解锁材料。停止失败时保留登录状态并报告错误。退出应用清除内存中的解锁材料,后台任务继续运行;启用记住登录后,再次打开可自动进入。锁定不会撤销运行中应用已持有的令牌。 | |
| 10 | 新增: | |
| 11 | 新增:私有 `account.json` 保存账户资料和加密后的随机内部密钥。密码通过 Argon2id(64 MiB、3 轮、2 路)派生 AES-GCM 包装密钥,修改密码只重新包装同一内部密钥。内部密钥经 SSH stdin 和客机私有 FIFO 交给密钥环,用户密码不传入客机;秘密不写入 URL、命令参数、日志或前端持久存储。启动失败不覆盖已有未知密码的密钥环。 | |
| 12 | 新增: | |
| 13 | 新增:控制接口沿用来源和主机会话校验,并增加账户解锁要求;锁定时取消现有显示连接,异步环境任务不受影响。账户元数据、登录及外观读取可在锁定时访问。账户文件损坏时拒绝启动,避免误建新账户覆盖旧密钥。此功能不加密项目或整个虚拟磁盘,不提供不同操作系统用户之间的额外隔离,也没有在线密码找回。 | |
| 14 | 新增: | |
| 15 | 新增:macOS 的“登录与解锁”提供记住登录与 Touch ID 两项开关。首次创建账户时默认勾选记住登录,用户可取消;手动关闭后不会在后续启动时重新开启。记住登录允许重新打开应用直接进入;手动锁定会持久保存必须验证的状态,即使后台重启也拒绝自动登录。密码或 Touch ID 成功解锁后解除该限制。退出账户撤销所有本机快捷登录凭据,之后需要密码重新开启。 | |
| 16 | 新增: | |
| 17 | 新增:每种快捷登录使用独立随机凭据包装同一个内部密钥。原生启动器通过受认证的本机接口交换凭据,网页只获得状态;后端不接受指纹成功的布尔值作为解锁依据。自动登录凭据保存在本机登录钥匙串,访问受应用代码签名控制;指纹凭据存入 Data Protection Keychain 并使用 `biometryCurrentSet`,必须通过系统指纹验证才能读取。指纹变化、取消、钥匙串不可用时保留密码入口。带指纹功能的构建需要匹配应用标识的 Developer ID 描述文件,构建可通过 `CAGE_PROVISIONING_PROFILE` 指定;缺少系统授权时不会改为不受保护的指纹凭据。 | |
| 4 | 18 | |
| 5 | 19 | ## 主界面 |
| 6 | 20 | |
| @@ -29,7 +43,7 @@ Cage 只使用一个持久环境,VM、账户登录态、开发工具和家目 | ||
| 29 | 43 | |
| 30 | 44 | 未启动时,主界面提供“启动 Cage 环境”,无需选择项目。每份配置只创建和使用一个持久 VM;默认工作区通常为 `~/.claude-cage-workspace`。环境就绪后可直接使用浏览器和终端,再按需打开本地文件夹。重新打开应用继续连接同一环境。 |
| 31 | 45 | |
| 32 | 删除:打开项目时,主机通过已有受目录约束的 SFTP 实现,把用户选定的文件夹动态挂载到当前 VM 的同名路径。项目 A 切换到 B 后,A 的共享目录、终端进程、浏览器和编辑器页保持运行。目录旁的加号始终在对应目录新建终端;终端工具栏在该终端所属目录创建新会话,项目文件入口使用当前选择的目录。明确打开的目录继续保留,并在环境重启时恢复共享。所有项目处于同一环境,可以访问其中已共享的目录、工具和账号。 | |
| 46 | 新增:打开项目时,主机通过已有受目录约束的 SFTP 实现,把用户选定的文件夹动态挂载到当前 VM:macOS 使用同名路径,Windows 的 `C:\Users\name\project` 映射为 `/c/Users/name/project`。项目 A 切换到 B 后,A 的共享目录、终端进程、浏览器和编辑器页保持运行。目录旁的加号始终在对应目录新建终端;终端工具栏在该终端所属目录创建新会话,项目文件入口使用当前选择的目录。明确打开的目录继续保留,并在环境重启时恢复共享。所有项目处于同一环境,可以访问其中已共享的目录、工具和账号。 | |
| 33 | 47 | |
| 34 | 48 | VM 身份固定保存在主机私有的 `environment.json`;最后打开的项目保存在 `workbench.json`,明确打开的目录保存于 `projects.json`。控制服务通过 `/api/status` 的 `projects` 返回完整目录列表,不设最近使用条数限制。终端与编辑器创建请求可携带 `workspace`,只接受默认目录、当前目录及已保存的项目目录;省略时沿用最后打开的项目。前端的目录选择不修改共享授权,也不影响浏览器。首次升级优先保留原有环境的虚拟磁盘;历史其他 VM 不自动删除。项目切换不改变环境身份,也不触发代理探测、网络重检或环境重启。网络与系统配置的修改继续按既有流程验证并重启。 |
| 35 | 49 | |
| @@ -39,11 +53,33 @@ VM 身份固定保存在主机私有的 `environment.json`;最后打开的项 | ||
| 39 | 53 | |
| 40 | 54 | 地址栏右侧星标与 ⌘D 打开当前网页的收藏编辑框,收藏夹按钮与 ⌘⇧O 打开收藏面板。收藏支持名称、HTTP(S) 地址、单层收藏夹分组、搜索、移动和删除;删除收藏夹将其中的收藏移至未分类。打开收藏通过现有浏览器新建页接口进入 VM,不在主机执行收藏网址。文件编辑器与内部浏览器页面不提供收藏。 |
| 41 | 55 | |
| 42 | 删除:收藏由主机控制服务保存在当前配置目录的私有 `favorites.json`,权限为 `0600`;所有项目共用,应用和控制服务重启后保留,不与 Chromium 或外部浏览器同步。`GET /api/favorites` 返回 `items` 与 `folders`;`POST /api/favorites` 通过 `save`、`delete`、`save_folder`、`delete_folder` 操作单条记录,沿用工作台认证与来源校验。修改在专用互斥锁下读取最新文件并原子写入,避免并发新增覆盖其他窗口的收藏。保存失败保留编辑输入,读取失败不覆盖原文件。收藏操作不更改 VM、网络或共享目录状态。 | |
| 56 | 新增:收藏由主机控制服务保存在当前配置目录的私有 `favorites.json`,Unix 权限为 `0600`,Windows 使用仅当前用户与 SYSTEM 可访问的显式 DACL;所有项目共用,应用和控制服务重启后保留,不与 Chromium 或外部浏览器同步。`GET /api/favorites` 返回 `items` 与 `folders`;`POST /api/favorites` 通过 `save`、`delete`、`save_folder`、`delete_folder` 操作单条记录,沿用工作台认证与来源校验。修改在专用互斥锁下读取最新文件并原子写入,避免并发新增覆盖其他窗口的收藏。保存失败保留编辑输入,读取失败不覆盖原文件。收藏操作不更改 VM、网络或共享目录状态。 | |
| 57 | 新增: | |
| 58 | 新增:## Claude 入口与终端 | |
| 59 | 新增: | |
| 60 | 新增:浏览器下方提供 `claude.ai` 和 `Claude Desktop` 两个入口。前者在 Cage 浏览器中新建官网页面;后者管理同一份官方 Linux 桌面应用,Chat 与 Code 在应用内切换。Desktop 的安装、登录资料和工作进程均位于当前持久环境中,文件访问沿用已共享的项目范围。Cage 管理安装、启动、状态与关闭,不读取应用会话,也不自动操作其中的任务。 | |
| 61 | 新增: | |
| 62 | 新增:首次进入 Desktop 页面只读取状态,点击“下载并安装”才下载安装包。安装使用 Anthropic 官方 apt 源,校验固定的签名密钥指纹并由 apt 验证软件包;不安装推荐依赖中的 QEMU/KVM,不承诺需要嵌套虚拟机的 Cowork 功能。下载通过[依赖维护通道](managed-proxy.md#依赖安装与更新)使用所选代理,无需业务网络已放行,失败可重试;没有直接联网回退。已安装的应用在进入页面时启动,切换到浏览器或终端保持应用运行;“关闭应用”在提醒保存后停止进程及图形会话,保留登录数据。更新或修复需要先关闭应用。 | |
| 63 | 新增: | |
| 64 | 新增:Desktop 使用编码用户 `cage`、独立的 X11 显示 `:78` 与按需启动的 systemd 服务。虚拟屏幕、窗口管理器、会话总线和应用属于同一服务,停止服务时一起回收。现有浏览器保持使用 `cage-browser` 和 `:77`。Desktop 的 VNC 只监听客机私有 Unix socket,经当前环境的 SSH 标准输入输出通道连接工作台,不创建可被自动转发的 TCP 监听端口。工作台沿用认证与来源校验,网页脚本无法调用应用控制接口。浏览器的 `claude://` 回调仅交给正在运行的官方应用;其他外部协议不由该入口执行。系统密钥环保存应用登录状态,由 Cage 使用账户内部密钥自动创建和解锁。Claude 自身的账号登录仍由用户完成。 | |
| 65 | 新增: | |
| 66 | 新增:项目旁的加号、终端工具栏与新建终端快捷键均打开类型选择框。普通终端提供 shell;Claude 终端在所选项目中新建交互 shell,并运行设置中的启动命令,默认 `claude`。命令支持参数及单行 shell 表达式,仅在客机执行;退出 Claude 后返回 shell。命令保存在私有 `workbench.json` 的 `claude_terminal_command` 字段,留空恢复默认,拒绝换行、NUL 和超过 4096 字节的输入。保存不重启环境,也不修改现有终端;刷新或重连不会重复执行启动命令。 | |
| 67 | 新增: | |
| 68 | 新增:应用状态与操作由 `/api/claude-desktop`、`/api/claude-desktop/{install,start,stop}` 提供;安装和启动沿用工作台异步任务。`POST /api/terminals` 的 `kind` 可为 `shell` 或 `claude`,省略时保持普通终端行为。原始启动命令不从新建终端请求接收,只读取已保存偏好。 | |
| 69 | 新增: | |
| 70 | 新增:Desktop 画面使用显示区域宽高的 2 倍像素,应用以 `--force-device-scale-factor=2` 启动,使文字和控件保持正常显示大小,并保留高分屏清晰度。窗口尺寸与侧栏变化沿用画面尺寸同步。macOS、Windows 与 Linux 共用此显示链路;缩放参数在下次启动应用时生效。 | |
| 71 | 新增: | |
| 72 | 新增:## 声音输出 | |
| 73 | 新增: | |
| 74 | 新增:浏览器、Claude Desktop 和环境内其他程序的声音通过工作台在本机播放,输出设备由本机系统选择。底部提供静音和音量控制,偏好保存在当前工作台的本地存储中。首次播放如果受到 WebView 自动播放限制,点击页面或“启用声音”即可继续。切换标签、项目或设置页保持声音;静音、停止环境、锁定账户及退出应用关闭播放连接,重新连接从当前声音开始。 | |
| 75 | 新增: | |
| 76 | 新增:客机的 `cage-audio.service` 仅加载虚拟输出 `cage_output` 及其 monitor,通过限定用户组的 Unix socket 接受应用音频,不加载麦克风或物理设备。浏览器与主用户通过统一的 PulseAudio 配置连接该设备。工作台 `GET /api/audio` 返回固定格式或建立 WebSocket,沿用主机来源、会话和账户认证;每条播放连接经现有 SSH 通道运行固定的 monitor 采集命令。账户访问上下文取消会结束音频请求,客户端断开会结束对应采集进程。每个控制服务最多接受四条音频连接,不增加客机网络监听端口。 | |
| 77 | 新增: | |
| 78 | 新增:传输格式为 48 kHz 双声道 16 位小端 PCM,每条消息通常包含 20 ms 音频。AudioWorklet 适配本机采样率,起播缓冲为 60 ms,缓存上限为 250 ms;积压或中断后清理旧音频。声音输出独立于业务外网放行,依赖安装使用维护通道。macOS、Windows 和 Linux 共用后端及 Web Audio 播放器,不申请本机麦克风权限。 | |
| 43 | 79 | |
| 44 | 80 | ## 设置页 |
| 45 | 81 | |
| 46 | 删除:设置占据完整窗口,左侧分类为通用、外观、网络与代理、IP 变化规则、时区与语言、环境与恢复;右侧显示表单,底部固定保存区。离开未保存的表单需要确认,保存失败保留输入。返回工作台保留选中的标签与终端,并恢复可见浏览器画面的连接。 | |
| 82 | 新增:设置占据完整窗口,左侧分类为账户、通用、外观、网络与代理、IP 变化规则、时区与语言、环境与恢复;右侧显示表单,底部固定保存区。离开未保存的表单需要确认,保存失败保留输入。返回工作台保留选中的标签与终端,并恢复可见浏览器画面的连接。 | |
| 47 | 83 | |
| 48 | 84 | 通用页提供浏览器默认网站,缺省为 `https://www.bing.com/`。该偏好保存在 `workbench.json` 的 `browser_home_url`,只接受不含认证信息的 HTTP(S) 网址;保存同步至客机浏览器,无需重启 VM 或终端。工作台新建网页、浏览器最后一页关闭后的补充页使用这个地址;连接时将恢复的空白页和 Chromium 内置新标签页转到该地址,已有普通网页继续保留。 |
| 49 | 85 | |
| @@ -53,10 +89,20 @@ VM 身份固定保存在主机私有的 `environment.json`;最后打开的项 | ||
| 53 | 89 | |
| 54 | 90 | ## 视觉与交互 |
| 55 | 91 | |
| 56 | 删除:外观以可独立配置的浅色、深色主题组织,支持跟随系统切换。主题包含强调色、背景、文字、对比度、界面及代码字体和侧栏透明度;字号在界面层统一缩放。标准侧栏宽 248px,较窄窗口使用 224px;设置正文最大宽度 720px。原生窗口与终端跟随当前主题,VM 内的编辑器及网页保留自身外观。 | |
| 92 | 新增:外观以可独立配置的浅色、深色主题组织,支持跟随系统切换。主题包含强调色、背景、文字、对比度、界面及代码字体和侧栏透明度。可选的元素颜色覆盖用于侧栏、工具栏、文字层级、输入、边框、按钮、交互与状态;终端另有背景、前景、光标、选区及完整 ANSI 颜色覆盖。未覆盖的颜色继续由基础色和对比度推导,恢复自动颜色即删除对应覆盖。字号在界面层统一缩放。标准侧栏宽 248px,较窄窗口使用 224px;设置正文最大宽度 720px。原生窗口与终端跟随当前主题,VM 内的编辑器及网页保留自身外观。 | |
| 93 | 新增: | |
| 94 | 新增:内置主题目录统一维护主题系列、分组、用途说明及浅深变体。Codex、Solarized、Ayu 的既有标识与默认配色保持兼容;新增编辑器、阅读及无障碍搭配只在用户选择后应用。预设切换整体复制配色及终端色板,删除上一个预设或自定义留下的颜色覆盖,保留用户字体。高对比与蓝橙配色明确启用不透明窗口;切换回其他主题后可通过“半透明侧栏”自行调整。 | |
| 95 | 新增: | |
| 96 | 新增:无障碍预设以可计算的颜色对比作为验收依据:蓝橙配色的主要文字、辅助文字、链接、状态文字和终端 ANSI 文字对其使用背景达到 4.5:1,高对比配色达到 7:1;焦点和边框对相邻背景达到 3:1。对比度检查覆盖未编辑的内置配置,用户改色后不再保证这些阈值。该检查不代表整款应用的 WCAG 合规认证。成功、警告和错误继续通过不同图标及文字表达;蓝橙配色用于减少红绿依赖,不承诺适用于所有色觉差异。 | |
| 57 | 97 | |
| 58 | 98 | 外观由控制服务独立保存至 appearance.json,前端自动提交,修改失败保留输入并允许重试。读取、保存和本机 Codex 导入分别通过 GET /api/appearance、POST /api/appearance、GET /api/appearance/codex 完成,沿用工作台认证。外观操作不走环境配置应用流程,不重启 VM 或终端;本机导入只复制当前偏好,不创建持续文件监听。 |
| 59 | 99 | |
| 100 | 新增:自定义主题库与当前外观一同保存于 appearance.json,最多 50 项。每项具有独立标识、名称及浅深两套主题快照;应用主题只替换两套主题,保留模式、字号和交互偏好。修改当前配色不会自动改写已命名主题,用户需明确选择更新或另存。删除主题仅移除快照。Codex 同步保留此主题库。 | |
| 101 | 新增: | |
| 102 | 新增:主题文件契约为 `{format: "cage-theme", version: 1, name, lightTheme, darkTheme}`。每套主题包含 `preset/accent/surface/ink/contrast/opaqueWindows/fonts`,以及可选的 `colors` 和 `terminal` 颜色表。前端在导入前严格校验版本、字段、字体、六位 HEX 颜色与 256 KB 文件上限;后端对当前主题及全部快照再次校验,未知颜色键、无效颜色、重复标识或超限主题库均不得替换已保存文件。外观保存请求上限为 512 KB。 | |
| 103 | 新增: | |
| 104 | 新增:macOS 的 `importTheme/exportTheme` 原生操作仅接受受信任工作台主框架调用,通过系统文件窗口读写 UTF-8 JSON。Windows 桥接执行相同操作;浏览器使用文件输入与 Blob 下载。取消文件窗口不改动外观,导入同名主题分配新标识,导出内容只含主题配置。原生标题栏跟随当前侧栏颜色,已有终端直接更新 xterm 主题而不重连。 | |
| 105 | 新增: | |
| 60 | 106 | 按钮按下即时反馈,项目列表在 180ms 内展开,设置页在 160ms 内进入;减少动态效果模式下直接显示最终状态。工作台终端保持连接。浏览器画面不可见时关闭显示连接,重新可见时重连;浏览器进程、页面、下载和登录状态继续保留。原生窗口隐藏、最小化或关闭也会暂停显示连接,单纯失去键盘焦点不触发暂停。 |
| 61 | 107 | |
| 62 | 108 | 主要验证视口为 1280×850 与原生最小窗口的内容区 820×558。更窄页面可收起侧栏;设置表单独立滚动,保存操作持续可见。环境连接正常且外网放行仍有效时,品牌区、工作台和状态栏显示绿色带对钩盾牌,并提供状态文字。连接中断、检查中、网络关闭或放行过期时撤销绿色标记;VM 运行但浏览器连接未就绪时显示恢复入口。 |
| @@ -67,9 +113,11 @@ VM 身份固定保存在主机私有的 `environment.json`;最后打开的项 | ||
| 67 | 113 | |
| 68 | 114 | ## 模块职责 |
| 69 | 115 | |
| 116 | 新增:Linux 原生窗口使用 GTK 3 与 WebKitGTK,Windows 使用 WinForms 与 WebView2,macOS 使用 Swift 与 WKWebView;三个平台消费同一 `cage desktop --json` 入口和原生桥协议。Windows 使用 QEMU/WHPX 与 Windows ConPTY,Mac 使用 Apple 虚拟化与 POSIX PTY,客机软件及代理出口约束共用。Linux 使用 QEMU/KVM 与 POSIX PTY,更新通过系统安装包手动完成。平台构建与边界见 [Windows 指南](../windows.md)和 [Linux 指南](../linux.md)。 | |
| 117 | 新增: | |
| 70 | 118 | 主机控制服务管理配置、VM 生命周期、会话与只通向该配置唯一 VM 的连接。前端只调用这个服务。终端在 VM 的 SSH 会话中执行;浏览器控制器和 Chromium 在 VM 内运行。编辑器页面也通过 VM 浏览器呈现,避免将来自 guest 的任意网页脚本作为主机控制页面加载。 |
| 71 | 119 | |
| 72 | 删除:应用窗口是本机工作台的容器,不是执行外部网站的主机浏览器。外部地址统一交给 VM 浏览器;所有网页与编码进程的网络仍由现有 VM 外代理出口接管。 | |
| 120 | 新增:应用窗口仅加载本机工作台。外部地址统一交给 VM 浏览器;所有网页与编码进程的网络仍由现有 VM 外代理出口接管。 | |
| 73 | 121 | |
| 74 | 122 | Chromium 通过继承的私有调试管道接受标签与导航命令,不开放 CDP 端口。网页由用户手工操作,启动时关闭 Blink 的 `AutomationControlled` 标记,避免仅因工作台控制管道而向网页报告自动化模式。浏览器服务停止时,先由控制器通知 Chromium 保存标签和配置后退出,再清理剩余子进程。此设置保留浏览器控制与登录态,不保证第三方网站的人机验证一定通过。 |
| 75 | 123 | |
| @@ -86,7 +134,17 @@ Chromium 通过继承的私有调试管道接受标签与导航命令,不开 | ||
| 86 | 134 | |
| 87 | 135 | 日常入口免密。App 持有主机私有启动密钥,通过 localhost 换取有效期 60 秒的一次性入口,再建立 HttpOnly 会话;浏览器和编辑器的内部凭据由工作台管理。链接消费后从地址栏移除,不能重复使用。直接打开一个未认证的控制地址会要求从 App 或启动器进入,不提供人工密码表单。 |
| 88 | 136 | |
| 89 | 删除:虚拟显示由 Xtigervnc 提供,直接监听仅限 guest 私有 Unix socket;X0tigervnc 负责已验证的剪贴板与显示传输。轻量窗口管理器让 kiosk Chromium 随显示区域调整,不提供桌面壳。工作台通过浏览器控制器调整显示模式,以 2 倍像素呈现;画面连接断开时按有上限的间隔重试,不因此重启 VM 或终端。 | |
| 137 | 新增:虚拟显示由 Xtigervnc 提供,直接监听仅限 guest 私有 Unix socket;X0tigervnc 负责文本剪贴板与显示传输。轻量窗口管理器让 kiosk Chromium 随显示区域调整,不提供桌面壳。工作台通过浏览器控制器调整显示模式,以 2 倍像素呈现;画面连接断开时按有上限的间隔重试,不因此重启 VM 或终端。 | |
| 138 | 新增: | |
| 139 | 新增:### 图片输入 | |
| 140 | 新增: | |
| 141 | 新增:工作内容区接受本机图片粘贴和图片文件拖入,地址栏及设置表单保留本地输入行为。拖入网页或 Desktop 的图片交给当前已聚焦的输入框,目标应用须支持图片粘贴;终端接收客机文件路径,不自动提交命令。macOS、Windows、Linux 的 `clipboardReadContent` 原生操作在明确粘贴时返回 `{png: base64}` 或 `{text: string}`,原有 `clipboardRead` 文本契约保留。浏览器事件中的 PNG、JPEG、WebP、GIF 统一转为静态 PNG。 | |
| 142 | 新增: | |
| 143 | 新增:`POST /api/input/image` 接收 `png`、`target` 和 `id`,沿用会话、来源及账户解锁校验。目标为 `browser`、`desktop` 或 `terminal`;浏览器必须提供活动标签标识,终端必须提供存活会话标识。每张 PNG 最大 20 MB、4000 万像素,控制服务解码校验后才交给客机。浏览器通过已有受认证控制通道执行,标签检查和图片输入与标签激活共用操作队列;Desktop 和终端通过 SSH stdin 传入图片,不把图片或主机文件路径放入命令参数。 | |
| 144 | 新增: | |
| 145 | 新增:客机图片助手以目标应用用户运行。网页使用 `cage-browser` 的 `:77` 显示,Desktop 使用 `cage` 的 `:78` 显示及其 Xauthority。GTK 提供 `image/png` 剪贴板并处理大图片的分段传输,xdotool 发送粘贴按键;收到目标的数据请求后返回。剪贴板所有者最多保留 120 秒,被替换后留出 10 秒完成已有传输。终端附件使用随机文件名写入 `~/.local/share/cage/attachments/`,权限为 `0600`,目录为 `0700`,不自动清理仍可能被任务引用的图片。Cage 的图片传递不借助外部存储服务,也不扩大主机目录共享范围;目标网页或应用可按自身行为上传附件。 | |
| 146 | 新增: | |
| 147 | 新增:前端在异步读取、转换图片前保留输入队列位置;图片失败会取消已排在其后的回车等输入,避免提交缺少附件的内容。切换标签或断开连接时,尚未发送的输入取消。接口成功表示图片已传入应用剪贴板或保存为客机文件;目标应用是否将它接受为附件仍由应用自身决定。反向图片复制、任意文件拖入和旧版独立 noVNC 页面不属于此接口。 | |
| 90 | 148 | |
| 91 | 149 | 自动时区查询通过已选代理完成。应用配置前验证,随后停止环境、保存前一份配置并重启;探测失败保留原配置。运行中不会因定期位置探测自动重启。用户选择恢复配置时,同样明确提示终端中断,并启动恢复后的环境。按键偏好单独保存,不重启环境。 |
| 92 | 150 | |
| @@ -94,13 +152,19 @@ Chromium 通过继承的私有调试管道接受标签与导航命令,不开 | ||
| 94 | 152 | |
| 95 | 153 | 下载列表区分下载中、保存中、已保存、失败和已取消。只有完整文件在共享目录中发布后才显示已保存;写入失败保留客机源文件,可在修复空间或共享连接后重试。状态原子保存在浏览器私有目录,控制器恢复后只对已完整下载且源文件仍在的项目提供保存重试;下载被中断时需要从原网页重新下载。列表保留最近 50 条结束记录,最多同时处理 50 个未结束下载,保存过程串行执行。成功保存后清理对应客机源文件;清理失败显示提示,已保存文件保持可用。 |
| 96 | 154 | |
| 155 | 新增:侧栏“下载”与浏览器工具栏提供同一下载列表。工作台观察到下载完成后,通过三平台系统保存窗口提供另存为;上传选择尚未结束时延后弹出。取消另存为保留默认位置的文件,历史记录不会在应用重开时反复弹窗。用户可以打开文件、在文件管理器中显示位置,或再次另存为;操作系统使用对应文件的默认应用。文件不会在下载后自动打开。 | |
| 156 | 新增: | |
| 157 | 新增:本机保存由原生桥调用 `browser-file --json save|open|reveal` 完成。浏览器页面只提供下载标识与建议文件名,目标路径来自系统保存窗口;HTTP 接口不接受任意本机读写路径。控制接口按下载标识检查已完成记录,读取默认工作区中的文件,或在共享保存失败时从客机按标识流式读取完整源文件。另存为先写目标目录中的临时文件,核对传递长度并同步到磁盘后原子发布;失败保留原目标文件。默认下载位置和另存为位置分别按记录保存于主机私有 `browser-downloads/`,用户选择的位置优先,停止 VM 后仍可查看,界面最多返回最近 100 个本机位置。来源、账户及会话校验继续生效,账户锁定会取消进行中的文件传递。 | |
| 158 | 新增: | |
| 159 | 新增:网页的标准文件输入使用 CDP 拦截选择请求。每个请求绑定标签、会话和原输入节点,工作台的 HTML 文件输入调用本机系统选择器。文件通过受认证的 `POST /api/browser/files/uploads/{id}` 流式传递,保留原始字节和文件名,单个上限 2 GB,多选最多 100 个。全部文件到达后才设置原网页的文件输入;取消或导航使旧请求失效,失败批次不提交部分文件。客机临时文件权限为 `0600`,目录为 `0700`;已提交文件保留到原文档导航、标签关闭或浏览器控制器重启,以支持网页延后读取 File 对象。网页自身的上传、格式校验与账户权限由网页处理,Cage 不代替网站提交消息或请求。 | |
| 160 | 新增: | |
| 97 | 161 | 编辑器由独立系统服务监督,进程异常退出时自动重新启动。工作台的编辑器恢复操作只重启该服务并重新加载项目页面,保留 VM、浏览器和工作台终端。迁移旧版编辑器时,先核对用户、安装目录、Cage 私有配置和监听参数;无法确认身份的进程不自动停止。 |
| 98 | 162 | |
| 99 | 163 | ## 更新与后台接管 |
| 100 | 164 | |
| 101 | 删除:左下角更新入口在发现新版时显示向下箭头,悬浮提示“下载更新”。点击后通过所选受管代理下载 Release 安装包并核验摘要、应用身份、同一 Developer ID Team 签名和 Apple 验证结果,随后安装并重启;代理失败无直连回退。有运行环境时,原生确认框要求用户先保存并停止。安装或新工作台启动失败时尝试恢复旧 App,无法恢复时保留备份和失败信息。ad-hoc 构建不进入自动安装流程。 | |
| 165 | 新增:左下角更新入口在发现新版时显示向下箭头,悬浮提示“下载更新”。点击后通过所选受管代理下载 Release 安装包并核验摘要、应用身份及平台签名:macOS 检查同一 Developer ID Team 与 Apple 验证结果;Windows 检查 Authenticode 信任链、相同发布者公钥和安装器版本,随后安装并重启;代理失败无直连回退。有运行环境时,原生确认框要求用户先保存并停止。安装或新工作台启动失败时尝试恢复旧 App,无法恢复时保留备份和失败信息。ad-hoc 或未签名开发构建不进入自动安装流程。 | |
| 102 | 166 | |
| 103 | 删除:更新源为公开 GitHub Releases 接口,不需要 GitHub 凭据,也不读取浏览器登录会话。访问失败时显示原因;草稿、附件缺失或非公开发行物不能作为可用更新。首次安装使用公开 DMG,后续版本由应用内更新器检查和下载。 | |
| 167 | 新增:更新源为公开 GitHub Releases 接口,不需要 GitHub 凭据,也不读取浏览器登录会话。访问失败时显示原因;草稿、附件缺失或非公开发行物不能作为可用更新。首次安装使用对应平台的 DMG 或 Windows EXE 安装器,后续版本由应用内更新器检查和下载。 | |
| 104 | 168 | |
| 105 | 169 | 应用启动通过私有启动密钥核对正在运行的控制服务。身份包含完整版本、当前可执行文件的 SHA-256 和控制协议号;文件摘要在进程启动时固定,同版本号的不同构建也能区分。相同构建复用后台;不同构建只有在没有运行环境、作业和存活终端时才自动接管。接管期间拒绝新任务,停止独立代理并优雅退出控制服务,然后由新程序取得同一配置的控制锁。 |
| 106 | 170 | |
| @@ -116,6 +180,6 @@ Chromium 通过继承的私有调试管道接受标签与导航命令,不开 | ||
| 116 | 180 | |
| 117 | 181 | “更新环境组件”在现有 VM 中重新应用幂等脚本,重启浏览器与编辑器相关服务,保留磁盘、项目、账户和工作台独立终端。操作前需要保存浏览器和编辑器中的修改;编辑器内的集成终端可能结束。脚本失败时清单保持无效,用户可查看任务结果并重试。已有运行依赖完整时,组件更新可在暂停外网时执行;用户的暂停状态继续保留。 |
| 118 | 182 | |
| 119 | 删除:“更新环境工具”是单独的显式操作,需要组件已经同步且外网处于有效放行状态。Chromium 使用 Debian 软件源的更新,code-server、mise 和 Claude 使用随 App 固定的最低版本;当前版本更高时保留现有版本。初次安装与后续升级共用固定安装器,下载包核验摘要后才安装。工具更新不重建磁盘,完成后重新启动相关服务并核对组件状态。更新期间继续运行原有网络检查与短期续租;人工暂停、停止或配置变化仍会阻止联网。 | |
| 183 | 新增:“更新环境工具”是单独的显式操作,需要环境正在运行且组件已经同步。Chromium 使用 Debian 软件源的更新,code-server、mise 和 Claude 使用随 App 固定的最低版本;当前版本更高时保留现有版本。初次安装与后续升级共用固定安装器,下载包核验摘要后才安装。工具更新不重建磁盘,完成后重新启动相关服务并核对组件状态。依赖维护通道不以业务网络放行为前提;更新期间继续维护已有的业务联网检查与短期续租,用户手动暂停外网的状态保持不变,停止环境会取消安装。 | |
| 120 | 184 | |
| 121 | 185 | `GET /api/environment/versions` 只在用户查看环境设置时读取工具版本,不加入周期状态查询。返回控制服务实际构建、组件的 `current` / `required`、后端判定的 `update_required`、工具实际与最低版本,以及 `tools_update_allowed`。组件与工具更新分别通过 `POST /api/environment/update`、`POST /api/environment/tools` 提交到现有作业队列。应用原生版本来自 App 的版本信息,不能用旧控制服务的版本代替。 |
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | # 开始使用 Cage |
| 2 | 2 | |
| 3 | 删除:这份指南从安装应用开始,带你完成代理配置、启动环境和第一次项目操作。Cage 在 Mac 上运行一个持久 Linux 环境,终端、浏览器和编辑器都使用这个环境;日常使用只需打开 Cage 应用。 | |
| 3 | 新增:这份指南从安装应用开始,带你完成代理配置、启动环境和第一次项目操作。Cage 在主机上运行一个持久 Linux 环境,终端、浏览器和编辑器都使用这个环境;日常使用只需打开 Cage 应用。 | |
| 4 | 4 | |
| 5 | 5 | ## 准备好三样东西 |
| 6 | 6 | |
| 7 | 7 | | 需要准备 | 说明 | |
| 8 | 8 | |---|---| |
| 9 | 删除:| Apple Silicon Mac,macOS 14+ | 在苹果菜单“关于本机”查看芯片和系统版本。其他平台尚未完成桌面版验收。 | | |
| 9 | 新增:| 支持的平台与虚拟化 | Apple Silicon Mac 需要 macOS 14+。Windows 10/11 x64 和 Debian/Ubuntu x86_64 的开发安装、虚拟化要求与验收状态见 [Windows 指南](windows.md)和 [Linux 指南](linux.md)。 | | |
| 10 | 10 | | 可用的代理 | Clash/Mihomo YAML 订阅、本地 YAML,或自己的 HTTP/SOCKS5 节点。Cage 随附代理核心,不提供代理服务。 | |
| 11 | 11 | | 自己的 Claude 使用资格 | 需要使用 Claude Code 时,在 Cage 内完成自己的授权。主机已有登录不会自动导入。 | |
| 12 | 12 | |
| @@ -18,9 +18,13 @@ | ||
| 18 | 18 | |
| 19 | 19 | 打开 `.dmg`,将 Cage 拖入 Applications(应用程序),然后从“应用程序”打开 Cage。无需先安装开发工具或 Clash。签名、公证和平台验证情况以该安装包的 Release 说明为准。如果系统拒绝打开,先按[安装问题](troubleshooting.md#下载或安装受阻)核对版本与来源。 |
| 20 | 20 | |
| 21 | 新增:Windows 安装器、系统虚拟化要求、快捷键和卸载方式见 [Windows 指南](windows.md);Linux 的 `.deb` 安装包与 KVM 要求见 [Linux 指南](linux.md)。下述代理、环境和项目操作共用。 | |
| 22 | 新增: | |
| 23 | 新增:首次打开时创建一个本地账户:设置用户名和至少 8 个字符的密码。Mac 首次创建时默认勾选“记住登录”,可取消勾选;之后也可在账户设置关闭,关闭后的选择会保留。账户只用于本机 Cage;左下角头像菜单的“账户设置”可更换头像、用户名和密码。请妥善保存密码,首版没有在线找回。它不替代 Claude 账号,也不会加密项目文件或整个虚拟磁盘。 | |
| 24 | 新增: | |
| 21 | 25 | ## 2. 导入并选择代理 |
| 22 | 26 | |
| 23 | 删除:首次打开时点击“配置网络与代理”。之后也可以从左下角“设置 → 网络与代理”进入。没有节点时点击“添加来源”,选择一种导入方式: | |
| 27 | 新增:进入工作台后点击“配置网络与代理”。之后也可以从左下角“设置 → 网络与代理”进入。没有节点时点击“添加来源”,选择一种导入方式: | |
| 24 | 28 | |
| 25 | 29 | - **订阅链接**:填写来源名称和 HTTPS 订阅地址。首次没有可用节点时,勾选“通过主机网络下载这份订阅”;不勾选则经当前配置的代理下载,失败不会自动切换路径。 |
| 26 | 30 | - **本地 YAML**:选择文件,或粘贴配置内容。适合已经导出节点配置的情况。 |
| @@ -30,7 +34,7 @@ | ||
| 30 | 34 | |
| 31 | 35 | 订阅应包含 `proxies` 或 `payload` 节点内容。Base64 列表、单个分享链接以及仅含远程 provider 的配置暂不支持;请向服务提供方获取 Clash/Mihomo YAML 节点订阅,或导出本地 YAML。导入只采用节点与明确的代理链,配置中的系统代理、TUN、端口及直连规则不会应用到 Cage。 |
| 32 | 36 | |
| 33 | 删除:Cage 使用独立端口和配置,不设置 Mac 系统代理,不开启主机 TUN,也不改变本机 Clash 的节点选择。订阅的主机下载与节点域名启动解析属于代理的准备通信;Cage 环境内的业务 DNS 仍经过选定节点。 | |
| 37 | 新增:Cage 使用独立端口和配置,不设置 系统代理,不开启主机 TUN,也不改变本机 Clash 的节点选择。订阅的主机下载与节点域名启动解析属于代理的准备通信;Cage 环境内的业务 DNS 仍经过选定节点。 | |
| 34 | 38 | |
| 35 | 39 | HTTP/SOCKS5 服务可通过“订阅 → 添加来源 → 手动节点”录入服务器、端口和认证。所有节点均由 Cage 自带核心承接,网络页的加密 DNS 经当前节点转发。没有应用有效节点时,Cage 不会联网。 |
| 36 | 40 | |
| @@ -38,7 +42,7 @@ HTTP/SOCKS5 服务可通过“订阅 → 添加来源 → 手动节点”录入 | ||
| 38 | 42 | |
| 39 | 43 | 返回工作台,点击“启动 Cage 环境”。无需先选择项目。应用先只读检查本机 Git;已启用保护,或确认未安装 Git 时,会直接继续。 |
| 40 | 44 | |
| 41 | 删除:如果出现“启动前,保护本机 Git”,请阅读说明,再点击“启用保护并继续”。这会将当前 Mac 用户的一项全局 Git 设置改为 `safe.bareRepository=explicit`,防止 Git 自动识别共享目录中的裸仓库并使用其中的配置。普通 `.git` 项目的提交、拉取、历史和远程地址不受影响;使用裸仓库时需要通过 `--git-dir` 明确指定。设置也会影响本机其他 Git 工具,Cage 仅在你明确确认后修改,重新检查通过后才启动环境。也可以选择“暂不启动”。 | |
| 45 | 新增:如果出现“启动前,保护本机 Git”,请阅读说明,再点击“启用保护并继续”。这会将当前主机用户的一项全局 Git 设置改为 `safe.bareRepository=explicit`,防止 Git 自动识别共享目录中的裸仓库并使用其中的配置。普通 `.git` 项目的提交、拉取、历史和远程地址不受影响;使用裸仓库时需要通过 `--git-dir` 明确指定。设置也会影响本机其他 Git 工具,Cage 仅在你明确确认后修改,重新检查通过后才启动环境。也可以选择“暂不启动”。 | |
| 42 | 46 | |
| 43 | 47 | 第一次启动会依次准备镜像、安装工具、连接浏览器并执行检查;界面显示当前阶段,“操作详情”提供进一步信息。Git 检查未通过时,按[启动前 Git 检查](troubleshooting.md#启动前的-git-检查未通过)处理,无需重新配置代理。 |
| 44 | 48 | |
| @@ -50,24 +54,30 @@ HTTP/SOCKS5 服务可通过“订阅 → 添加来源 → 手动节点”录入 | ||
| 50 | 54 | |
| 51 | 55 | ## 4. 打开项目并开始工作 |
| 52 | 56 | |
| 53 | 删除:点击“打开项目”,选择 Mac 上的项目文件夹。新终端和文件编辑器将从这个目录开始工作;首次试用也可保留默认工作区。 | |
| 54 | 删除: | |
| 55 | 删除:在项目旁点击“+”创建终端,输入: | |
| 57 | 新增:点击“打开项目”,选择 主机上的项目文件夹。新终端和文件编辑器将从这个目录开始工作;首次试用也可保留默认工作区。 | |
| 56 | 58 | |
| 57 | 删除:```sh | |
| 58 | 删除:claude | |
| 59 | 删除:``` | |
| 59 | 新增:在项目旁点击“+”,选择“新建 Claude 终端”,Cage 会在该项目中自动运行 `claude`。也可选择普通终端,手动输入命令。“设置 → 通用 → Claude 终端启动命令”可添加参数,例如 `claude --continue`;保存后只影响新建的 Claude 终端,退出 Claude 后仍可继续使用 shell。 | |
| 60 | 60 | |
| 61 | 61 | 按 Claude Code 的提示,在 Cage 浏览器中完成自己的账户授权。主机已有的 Claude 登录、浏览器用户目录和 SSH 密钥不会自动导入。如果授权链接没有自动打开,可复制完整链接到 Cage 浏览器地址栏;链接可能包含一次性授权信息,不要发到 Issue 中。 |
| 62 | 62 | |
| 63 | 删除:可以先让 Claude 读取项目并解释一个文件,确认模型请求正常,再让它在测试文件中完成一个小修改。通过“浏览文件”查看内容,并在 Mac 上确认同一文件的变化。首次使用前请备份重要项目。 | |
| 63 | 新增:可以先让 Claude 读取项目并解释一个文件,确认模型请求正常,再让它在测试文件中完成一个小修改。通过“浏览文件”查看内容,并在主机上确认同一文件的变化。首次使用前请备份重要项目。 | |
| 64 | 64 | |
| 65 | 删除:文件修改会直接作用于共享目录。`.git` 等元数据默认只读,因此可以让 Claude 修改代码,再回到 Mac 的 Git 工具中审查和提交。 | |
| 65 | 新增:文件修改会直接作用于共享目录。`.git` 等元数据默认只读,因此可以让 Claude 修改代码,再回到 主机的 Git 工具中审查和提交。 | |
| 66 | 66 | |
| 67 | 67 | 点击左侧“浏览器”可返回正在使用的浏览页面;通过顶部加号新建网页。地址栏中的 `localhost` 指向 Cage 的 Linux 环境,可用于预览在 Cage 终端中启动的开发服务。 |
| 68 | 68 | |
| 69 | 69 | ## 日常使用 |
| 70 | 70 | |
| 71 | 新增:### Claude 官网与桌面应用 | |
| 72 | 新增: | |
| 73 | 新增:浏览器下方的 `claude.ai` 入口直接在 Cage 浏览器中打开官网。`Claude Desktop` 入口提供官方桌面应用:首次点击“下载并安装”,Cage 从 Anthropic 官方源完成安装,随后打开应用;Chat 和 Code 在同一个应用内切换。安装前先启动环境并确保所选代理可用,无需等待业务网络放行;应用内联网仍需通过网络检查。安装失败时可查看进度并重试。 | |
| 74 | 新增: | |
| 75 | 新增:应用只在使用时下载和启动。切换到浏览器或终端时保持运行;点击应用上方的“关闭应用”释放其运行资源,登录数据仍保留在 Cage 中。应用关闭后可“更新 / 修复安装”。Claude 账号的首次登录在 Cage 内完成,不导入主机账号。系统密钥环由 Cage 在内部创建和解锁,无需再设置一份密钥环密码;修改 Cage 密码会保留应用登录数据。需要额外虚拟机的 Cowork 功能暂未适配。 | |
| 76 | 新增: | |
| 77 | 新增:### 锁定与退出账户 | |
| 78 | 新增: | |
| 79 | 新增:左下角头像菜单中的“锁定 Cage”隐藏工作台并要求重新输入密码,正在运行的 Claude、终端和环境任务继续运行。“退出账户”会先提醒保存文件,再停止环境并锁定凭据。仅退出应用时后台任务继续运行。“账户设置 → 登录与解锁”可开启“记住登录”,下次打开直接进入;手动锁定后仍需密码或 Touch ID,重新打开也不会跳过验证。Mac 已设置 Touch ID 时,可开启指纹解锁。退出账户会撤销本机快捷登录授权。 | |
| 80 | 新增: | |
| 71 | 81 | ### 项目、标签与文件 |
| 72 | 82 | |
| 73 | 83 | 左侧“项目”列出默认工作区和明确打开的文件夹,列表由 Cage 保存,重新打开应用后仍可看到。点击目录旁的加号,在该目录中新建终端;已有终端始终留在创建它的目录下。所有项目共用一个持久环境,工具、账户和 Linux 文件系统也相互共享。已打开的目录在环境启动时恢复连接。 |
| @@ -78,7 +88,13 @@ claude | ||
| 78 | 88 | |
| 79 | 89 | 点击地址栏右侧的星标或按 ⌘D 收藏当前网页,可修改名称并选择或新建收藏夹。点击旁边的收藏夹按钮或按 ⌘⇧O,可搜索、打开和编辑收藏;编辑时可移动到其他收藏夹。删除收藏夹会把其中的网页移至“未分类”。收藏保存在本机当前 Cage 配置中,所有项目共用,重启后保留。 |
| 80 | 90 | |
| 81 | 删除:浏览器下载统一写入 Cage 默认工作区的 `Downloads`,同名文件自动换名。新配置的默认工作区通常为 `~/.claude-cage-workspace/`;迁移配置可能保留已有位置。可以在默认工作区的文件编辑器中查看,不需要到代理私有目录查找下载文件。 | |
| 91 | 新增:### 浏览器上传与下载 | |
| 92 | 新增: | |
| 93 | 新增:在网页中点击上传后,工作台显示“上传本机文件”。点击“选择本机文件”,即可用系统文件窗口选择图片、视频或文档,传递进度会显示在面板中。只传递所选文件,不增加文件夹共享。网页允许多选时最多选择 100 个文件,每个文件不超过 2 GB;目标网站自身的格式与大小限制仍然有效。可以取消上传,刷新或关闭原网页后需要重新选择。 | |
| 94 | 新增: | |
| 95 | 新增:网页下载仍在 Cage 内完成。本机先收到默认工作区 `Downloads` 中的完整文件,同名文件自动换名。工作台连接期间观察到下载完成后,会弹出系统“另存为”窗口;取消时保留默认位置的文件。共享目录暂时不可写而客机文件已完整下载时,也可以从下载列表直接另存为。 | |
| 96 | 新增: | |
| 97 | 新增:左侧“下载”入口和地址栏旁的下载按钮都可查看进度、文件名和保存位置,并提供“打开文件”“在文件夹中显示”“另存为”。已记录的本机文件在停止环境后仍能查看;再次打开 Cage 也保留保存位置。新配置的默认工作区通常为 `~/.claude-cage-workspace/`,迁移配置可能保留已有位置。使用普通浏览器打开工作台时,导出由该浏览器的下载功能处理。 | |
| 82 | 98 | |
| 83 | 99 | ### 关闭、退出与再次打开 |
| 84 | 100 | |
| @@ -98,11 +114,29 @@ claude | ||
| 98 | 114 | |
| 99 | 115 | “设置 → 通用”可以选择按键习惯。Mac 模式将网页和编辑器的 `⌘F`、`⌘Z`、`⌘⇧Z` 等映射为 Linux 对应的 Ctrl 组合;本机地址栏与设置输入框保留 Mac 操作。终端的 `Ctrl+C` 中断命令,`⌘C` 复制选中文本。 |
| 100 | 116 | |
| 101 | 删除:复制粘贴支持纯文本、中文、多行和 emoji。先点击目标输入框,再使用快捷键或工具栏按钮;普通浏览器限制剪贴板权限时,可用“文本传递”面板。Cage 仅在主动复制或粘贴时访问本机剪贴板,不持续轮询。图片和文件通过共享项目传递。 | |
| 117 | 新增:Windows 和 Linux 默认采用 Ctrl 按键习惯,工作台快捷键中的 `⌘` 对应 `Ctrl`;终端复制粘贴使用 `Ctrl+Shift+C/V`,保留 `Ctrl+C` 中断命令。 | |
| 118 | 新增: | |
| 119 | 新增:复制粘贴支持纯文本、中文、多行和 emoji。先点击目标输入框,再使用快捷键或工具栏按钮;普通浏览器限制剪贴板权限时,可用“文本传递”面板。Cage 仅在主动复制或粘贴时访问本机剪贴板,不持续轮询。 | |
| 120 | 新增: | |
| 121 | 新增:本机截图和图片可以粘贴到 Cage,也可以把 PNG、JPEG、WebP 或 GIF 文件拖入工作内容区。网页和 Claude Desktop 会把图片粘贴到当前已选中的输入框,因此拖入前应先点击支持图片的输入位置;不支持图片粘贴的网页可通过上传按钮选择本机文件。终端会把图片保存到客机的 `~/.local/share/cage/attachments/`,并插入带引号的完整路径,供 Claude Code 等工具读取,不自动执行命令。 | |
| 122 | 新增: | |
| 123 | 新增:粘贴或拖入的图片及转换后的 PNG 均不能超过 20 MB,分辨率不能超过 4000 万像素;GIF 按静态画面传递。Cage 通过本机与客机的控制通道传递图片,不借助外部存储服务;目标网页或应用可以按自身行为上传附件。终端附件保留到用户自行删除。切换目标或断开连接后,尚未发送的输入会取消。图片剪贴板支持从本机传入 Cage;其他文件可使用网页上传按钮或下载入口。使用旧环境时,先按应用提示更新环境组件。 | |
| 102 | 124 | |
| 103 | 125 | ### 外观与浏览器首页 |
| 104 | 126 | |
| 105 | 删除:“设置 → 外观”支持跟随系统或固定明暗主题,并调整配色、对比度、字体、字号、指针和动态效果,修改自动保存。可从本机 Codex 导入外观偏好,导入后独立保存。虚拟机内的网页和编辑器保留各自外观设置。 | |
| 127 | 新增:“设置 → 外观”支持跟随系统或固定使用浅色、深色主题。基础配色可调整强调色、背景和文字,展开每套主题的“自定义”后,还可分别调整侧栏、工具栏、标题、辅助文字、边框、输入框、按钮、链接、焦点、悬停、选中及状态提示颜色。终端的背景、文字、光标、选区与 ANSI 色板也可单独设置;虚拟机内的网页和编辑器保留各自外观设置。 | |
| 128 | 新增: | |
| 129 | 新增:每套主题的预设下拉框按“经典、编辑器、阅读、无障碍”分组,共有 14 个系列、22 套明暗搭配。可选 Codex、Solarized、Ayu、VS Code Modern / Classic、GitHub、Nord、Dracula、Monokai,以及参考 Typora 的纸白、暖纸和夜间风格。部分主题只提供浅色或深色版本,下拉框只显示当前模式可用的版本。选择预设会同时应用界面与终端配色,替换之前的元素颜色覆盖,保留已设置的字体;已保存的自定义主题不会被改写。 | |
| 130 | 新增: | |
| 131 | 新增:“无障碍 → 色觉友好 · 蓝橙”用蓝色与橙色区分成功和错误,减少红绿依赖;“高对比”提供白底黑字和黑底白字两种搭配,并加强边框与焦点。两类预设都关闭半透明侧栏,使对比保持稳定。卡片中带图标和文字的成功、警告、错误预览,可帮助比较状态色。不同色觉差异的适用配色会有差别,可继续自定义并另存主题;这些配色影响 Cage 界面和内置终端,虚拟机中的网页与编辑器保持各自外观。 | |
| 132 | 新增: | |
| 133 | 新增:颜色支持取色器和六位 HEX 输入。HEX 输入按 Enter 或离开输入框后生效;单独设置的颜色旁可恢复自动配色。字体、字号、对比度、指针和动态效果也在此调整。修改即时生效并自动保存,失败时保留当前输入,可点击“重试保存”。 | |
| 134 | 新增: | |
| 135 | 新增:在“我的主题”中输入名称,点击“另存为主题”,即可将浅色、深色两套配色、字体和侧栏透明度保存为一个主题。下拉框用于切换主题;修改后可“更新此主题”,也可另存,或点击“恢复已保存配色”放弃此次配色调整。删除主题会保留当前配色。最多保存 50 个自定义主题。 | |
| 136 | 新增: | |
| 137 | 新增:“导出主题”将当前两套配置保存为 `.cage-theme.json` 文件;“导入主题”校验文件后添加并应用,同名文件会另存,不覆盖已有主题。桌面版通过系统文件窗口读写,浏览器版使用文件选择与下载。主题文件不包含账户、代理、项目或本机路径;明暗切换模式、字号及交互偏好不随主题文件迁移。文件须为不超过 256 KB 的 Cage JSON 主题,格式版本不支持或内容无效时保留当前设置。 | |
| 138 | 新增: | |
| 139 | 新增:“从本机 Codex 同步”可复制 Codex 当前的外观偏好,导入后独立保存,并保留 Cage 中已保存的自定义主题。 | |
| 106 | 140 | |
| 107 | 141 | “设置 → 通用 → 浏览器默认网站”控制新网页的默认入口,初始为 Bing;保存后下次打开网页生效,无需重启环境。 |
| 108 | 142 | |
| @@ -124,18 +158,26 @@ claude | ||
| 124 | 158 | |
| 125 | 159 | ## 网络与数据边界 |
| 126 | 160 | |
| 127 | 删除:Cage 使用轻量 Linux 虚拟机,没有完整桌面。浏览器与编辑器页面在虚拟机内执行,Mac 工作台呈现画面和终端;Chromium 以普通用户运行并保留自身沙箱。 | |
| 161 | 新增:Cage 使用轻量 Linux 虚拟机,没有完整桌面。浏览器与编辑器页面在虚拟机内执行,本机工作台呈现画面和终端;Chromium 以普通用户运行并保留自身沙箱。 | |
| 128 | 162 | |
| 129 | 163 | - 对外 TCP 在主机侧虚拟网卡出口统一交给指定代理,没有直连回退。DNS 经同一代理转为 DoH,代理失败时不回退主机 DNS。 |
| 130 | 164 | - 客机公网 IPv6、普通 UDP、ICMP,以及主动访问主机和局域网的连接受到阻断;当前公网出站支持 IPv4 TCP。SSH 管理、共享文件和本地显示使用明确的内部通道。 |
| 131 | 165 | - 代理凭据保存在主机私有配置,不传入客机。终端 SSH 禁用本机转义、本机命令、代理转发与交互密码,且不继承主机环境变量。 |
| 132 | 166 | - 工作台只监听本机 loopback,App 自动换取会话;接口校验 Host、Origin 与会话,外部网页不能直接调用管理操作。 |
| 133 | 删除:- 默认工作区及明确打开的项目目录会共享到同一环境,彼此可以访问。修改、删除共享文件会影响 Mac,请保留备份。不要把 Cage 私有配置目录或正在运行的控制程序作为共享项目。 | |
| 167 | 新增:- 默认工作区及明确打开的项目目录会共享到同一环境,彼此可以访问。修改、删除共享文件会影响主机,请保留备份。不要把 Cage 私有配置目录或正在运行的控制程序作为共享项目。 | |
| 134 | 168 | |
| 135 | 169 | 网络约束在虚拟机外,客机中的 sudo 不能直接关闭。虚拟机或浏览器漏洞、主机管理员修改配置,以及用户在主机执行共享项目中的脚本,超出这层边界能阻止的范围。Cage 不提供账号封禁预测或避免限制的承诺。镜像化分享和系统时钟伪造尚未提供。 |
| 136 | 170 | |
| 171 | 新增:### 播放环境声音 | |
| 172 | 新增: | |
| 173 | 新增:在 Cage 浏览器播放视频或音频时,声音会从本机当前的扬声器或耳机输出。底部的扬声器按钮可以静音,旁边的滑块调整整个 Cage 环境的音量;Claude Desktop 和终端程序共用此控制。若出现“启用声音”,点击一次后继续播放。 | |
| 174 | 新增: | |
| 175 | 新增:切换标签或项目不会停止声音。静音、停止环境、锁定 Cage 账户或退出应用会断开播放;取消静音后播放当前内容,不补播中断期间的声音。旧环境首次使用时需要更新组件。此功能提供声音输出,不提供本机麦克风输入。 | |
| 176 | 新增: | |
| 137 | 177 | ## 升级与卸载 |
| 138 | 178 | |
| 179 | 新增:本节的安装包替换与卸载步骤适用于 macOS。Windows 用户参阅 [Windows 更新与卸载](windows.md#更新与卸载),Linux 用户参阅 [Linux 更新与卸载](linux.md#更新与卸载);Linux 使用系统安装包手动更新。环境组件与工具仍在各平台共用的工作台设置中更新。 | |
| 180 | 新增: | |
| 139 | 181 | 首次安装请下载公开 Release 的 DMG。应用内更新用于后续版本升级。 |
| 140 | 182 | |
| 141 | 183 | 应用内更新入口在左下角。有新版时,向下箭头悬浮显示“下载更新”;点击后自动下载、校验、安装并重启。有环境或任务运行时,下载校验完成后会弹出原生确认框,请保存文件再确认停止;暂不安装可保留下载结果,稍后继续。应用更新会结束工作台终端,保留项目、配置、虚拟磁盘和登录状态。安装或启动失败时会尝试恢复旧应用,并显示失败原因。 |
| @@ -144,7 +186,7 @@ Cage 使用轻量 Linux 虚拟机,没有完整桌面。浏览器与编辑器 | ||
| 144 | 186 | |
| 145 | 187 | 手动替换 App 前,保存文件并选择“停止环境并退出”。新 App 会核对后台版本;若出现“更新待完成”,可先打开现有环境保存文件,再选择“保存后停止环境并完成更新”。Alpha 版本间的兼容性和特殊迁移要求以对应 Release 说明为准。 |
| 146 | 188 | |
| 147 | 删除:“设置 → 环境与恢复”分别提供环境组件与工具更新,并显示实际版本。组件更新会重启浏览器和编辑器,保留 VM、磁盘和工作台独立终端;编辑器内的集成终端可能结束,操作前需要保存内容。工具更新还要求外网已通过检查并获准联网,采用当前 App 指定的最低版本;人工暂停外网不会被更新操作解除。替换 App 不等于已经升级全部 Linux 工具。 | |
| 189 | 新增:“设置 → 环境与恢复”分别提供环境组件与工具更新,并显示实际版本。组件更新会重启浏览器和编辑器,保留 VM、磁盘和工作台独立终端;编辑器内的集成终端可能结束,操作前需要保存内容。依赖安装和工具更新使用所选代理,无需业务网络已经放行;工具更新采用当前 App 指定的最低版本,人工暂停外网不会被更新操作解除。替换 App 不等于已经升级全部 Linux 工具。 | |
| 148 | 190 | |
| 149 | 191 | 卸载应用前也应先停止环境并退出,再将 Cage.app 移到废纸篓。删除 App 不会自动删除共享项目、默认工作区、代理配置或虚拟磁盘。需要清理这些数据时,先备份:私有状态默认在 `~/.claude-cage/`,默认工作区通常在 `~/.claude-cage-workspace/`,自行打开的项目仍在原目录。删除虚拟磁盘会丢失只存在于 Linux 环境中的文件和登录状态。 |
| 150 | 192 | |
| @@ -0,0 +1,80 @@ | ||
| 1 | 新增:# Linux 安装、使用与验收 | |
| 2 | 新增: | |
| 3 | 新增:Cage 的 Linux 桌面版面向 Debian 12、Ubuntu 24.04 的 x86_64 电脑,使用 GTK 3 与 WebKitGTK 显示工作台。项目、终端、浏览器、编辑器和内置代理沿用其他平台的操作方式;所有项目共用一个持久 Linux 虚拟机。 | |
| 4 | 新增: | |
| 5 | 新增:Linux 支持处于开发验收阶段。安装包及真实测试范围以对应发行说明为准;云服务器中的窗口测试不能代表所有桌面环境、显卡和输入法均已通过验收。ARM64、RPM 发行版及 Wayland 的完整交互尚未验收。 | |
| 6 | 新增: | |
| 7 | 新增:开发包已在 Debian 12 云端隔离环境验证原生工作台、窗口重开后的界面状态、代理生命周期、系统包安装与卸载保留数据。QEMU 软件模拟验证了客体启动、共享文件保护和迁移重启。KVM 硬件加速、Ubuntu 24.04 实机以及真实 Claude 业务网络仍需验收。 | |
| 8 | 新增: | |
| 9 | 新增:## 安装前准备 | |
| 10 | 新增: | |
| 11 | 新增:电脑需要图形桌面、可用的 KVM 硬件虚拟化、足够的磁盘空间和自己的代理节点。默认虚拟磁盘上限为 24 GiB。云主机需要服务商开放嵌套虚拟化;没有 `/dev/kvm` 的服务器不能按普通桌面流程启动 Cage 环境。 | |
| 12 | 新增: | |
| 13 | 新增:检查当前用户可读写 `/dev/kvm`: | |
| 14 | 新增: | |
| 15 | 新增:```sh | |
| 16 | 新增:test -r /dev/kvm && test -w /dev/kvm | |
| 17 | 新增:``` | |
| 18 | 新增: | |
| 19 | 新增:设备不存在时,检查 BIOS/UEFI 虚拟化和内核 KVM 模块。设备存在但权限不足时,可由管理员将用户加入 `kvm` 组,再退出桌面并重新登录: | |
| 20 | 新增: | |
| 21 | 新增:```sh | |
| 22 | 新增:sudo usermod -aG kvm "$USER" | |
| 23 | 新增:``` | |
| 24 | 新增: | |
| 25 | 新增:Cage 日常以普通用户运行。不要用 `sudo cage-desktop` 启动工作台。 | |
| 26 | 新增: | |
| 27 | 新增:## 安装并开始工作 | |
| 28 | 新增: | |
| 29 | 新增:从对应 Release 下载 `Cage-<版本>-linux-amd64.deb` 与 `SHA256SUMS`,核对该文件的 SHA-256 后安装: | |
| 30 | 新增: | |
| 31 | 新增:```sh | |
| 32 | 新增:sudo apt install ./Cage-<版本>-linux-amd64.deb | |
| 33 | 新增:``` | |
| 34 | 新增: | |
| 35 | 新增:安装器随附 Cage 后台、工作台和 Mihomo 代理核心。APT 从系统软件源安装 WebKitGTK、QEMU、OVMF 虚拟机固件及 OpenSSH 等依赖;无需安装 Go、Node.js、Docker 或其他代理客户端。首次启动环境仍需联网下载 Linux 镜像与客机工具。 | |
| 36 | 新增: | |
| 37 | 新增:从应用菜单打开 **Cage**,也可运行 `cage-desktop`。系统包名和后台命令为 `claude-cage`,避免与发行版自带的同名 Wayland 程序冲突。导入自己的代理、选择节点,再按[开始使用](getting-started.md#2-导入并选择代理)打开项目。项目路径例如 `/home/alice/Projects/demo`,只共享默认工作区与明确选择的目录;项目中的修改和删除会同步到主机。Git 元数据保护沿用现有约束,提交在主机 Git 中完成。 | |
| 38 | 新增: | |
| 39 | 新增:Linux 使用 Ctrl 快捷键:`Ctrl+O` 打开项目,`Ctrl+T` 新建网页,`Ctrl+L` 定位地址栏,`Ctrl+W` 关闭标签,`Ctrl+Shift+Enter` 新建终端。终端用 `Ctrl+Shift+C/V` 复制粘贴,`Ctrl+C` 中断命令。 | |
| 40 | 新增: | |
| 41 | 新增:关闭窗口保留后台环境与任务,再次打开 Cage 可重新连接。在应用内停止环境后退出,才能结束后台任务。Linux 本地账户使用密码解锁;设备快速解锁暂不提供。 | |
| 42 | 新增: | |
| 43 | 新增:浏览器上传使用本机文件选择窗口,下载可通过 GTK“另存为”选择保存位置。侧栏“下载”提供打开文件、打开所在文件夹和再次另存为;文件按当前桌面关联的应用打开。操作与限制见[浏览器上传与下载](getting-started.md#浏览器上传与下载)。 | |
| 44 | 新增: | |
| 45 | 新增:## 更新与卸载 | |
| 46 | 新增: | |
| 47 | 新增:Linux 版本通过系统安装包手动更新。应用内更新入口显示更新方式,不自动替换系统文件。先保存文件、停止环境并退出 Cage,再安装新版 `.deb`。安装器发现已安装的 Cage、控制服务或代理进程仍运行时,会拒绝覆盖并提示退出。 | |
| 48 | 新增: | |
| 49 | 新增:更新和卸载保留 `~/.claude-cage` 中的配置、代理与虚拟磁盘,默认工作区 `~/.claude-cage-workspace` 及自行打开的项目目录也保留。卸载命令为: | |
| 50 | 新增: | |
| 51 | 新增:```sh | |
| 52 | 新增:sudo apt remove claude-cage | |
| 53 | 新增:``` | |
| 54 | 新增: | |
| 55 | 新增:需要删除用户数据时应先自行备份。只保存在虚拟磁盘中的文件和登录状态会随虚拟磁盘删除而丢失。 | |
| 56 | 新增: | |
| 57 | 新增:## 常见问题 | |
| 58 | 新增: | |
| 59 | 新增:- 工作台无法显示:确认在普通用户的图形桌面会话中启动,且系统 WebKitGTK 安装完整。不要关闭 WebKit 沙箱来绕过桌面配置问题。 | |
| 60 | 新增:- 提示 KVM 不可用:按安装前准备检查设备和权限。普通阿里云实例未必提供嵌套虚拟化。 | |
| 61 | 新增:- 提示找不到物理网卡:内置代理需要可识别的主机网络接口。Docker 容器的 veth、VPN 隧道和桥接接口不作为物理出口;桌面主机与容器测试的网络条件不同。 | |
| 62 | 新增:- 能打开工作台但无法联网:在 Cage 内确认已选择代理节点并查看网络检查。主机浏览器能联网不能证明 Cage 代理已可用。 | |
| 63 | 新增: | |
| 64 | 新增:反馈时提供发行版、CPU 架构、Cage 版本、桌面环境以及失败步骤和错误原文。避免附带代理密码、订阅链接、账户文件和带会话信息的地址。 | |
| 65 | 新增: | |
| 66 | 新增:## 维护者构建与验收 | |
| 67 | 新增: | |
| 68 | 新增:正式构建基线为 Debian 12 x86_64;从更新发行版构建的原生程序可能需要更高版本 glibc,不能标为兼容 Debian 12。GTK/WebKitGTK 依赖来自发行版软件源([Debian 依赖](https://packages.debian.org/bookworm/libwebkit2gtk-4.1-0)、[Ubuntu 依赖](https://packages.ubuntu.com/noble/libwebkit2gtk-4.1-0)),动态库最低版本由打包脚本自动提取。 | |
| 69 | 新增: | |
| 70 | 新增:构建需要遵循 `go.mod` 的 Go、Node.js 24、C 编译器和以下系统包: | |
| 71 | 新增: | |
| 72 | 新增:```sh | |
| 73 | 新增:sudo apt install build-essential pkg-config libgtk-3-dev libwebkit2gtk-4.1-dev libjson-glib-dev dpkg-dev curl ca-certificates | |
| 74 | 新增:make cage-linux | |
| 75 | 新增:bash scripts/package-linux.sh --skip-build | |
| 76 | 新增:``` | |
| 77 | 新增: | |
| 78 | 新增:应用目录为 `_output/linux-amd64/app`;安装包、校验清单和 Mihomo 对应源码位于 `_output/releases/<版本>/linux`。`packaging/linux/dependencies.json` 固定代理核心及源码的下载地址与哈希。Cage 不随包复制发行版 QEMU 或 WebKit 库,系统包管理器负责这些组件的维护。 | |
| 79 | 新增: | |
| 80 | 新增:`make check-linux` 可在其他主机检查 Linux Go 编译与静态诊断。原生桌面、Go 测试及安装检查须在 Linux 执行;CI 使用非 root 用户、独立配置和虚拟显示。真实发行还需验证 KVM 启动、代理出口及失败阻断、中文空格路径共享、终端输入与缩放、网页和编辑器、关闭恢复、升级和卸载后的数据保留,以及常见 X11/Wayland 桌面和输入法。 | |
| @@ -1,20 +1,38 @@ | ||
| 1 | 1 | # 公开发行与主页部署 |
| 2 | 2 | |
| 3 | 删除:本页供维护者发布 Cage 安装包并维护项目主页。公开下载源为 [GitHub Releases](https://github.com/Lee-xeo/Claude-Cage/releases),项目主页为 <https://lee-xeo.github.io/Claude-Cage/>。构建、签名与公证步骤见[发布 macOS 安装包](releasing.md)。 | |
| 3 | 新增:本页供维护者发布 Cage 安装包并维护项目主页。公开下载源为 [GitHub Releases](https://github.com/Lee-xeo/Claude-Cage/releases),项目主页为 <https://lee-xeo.github.io/Claude-Cage/>。macOS 构建、签名与公证步骤见[发布 macOS 安装包](releasing.md),Windows 安装器、签名及验收要求见 [Windows 指南](windows.md#维护者构建与验收),Linux 系统包构建与验收见 [Linux 指南](linux.md#维护者构建与验收)。 | |
| 4 | 新增: | |
| 5 | 新增:## 自动发布入口 | |
| 6 | 新增: | |
| 7 | 新增:日常推送只检查并保存测试包,不升级版本号或公开发布。收到用户明确发版指令后,使用 [三平台 CI/CD](ci-cd.md) 的显式发布入口;它统一准备版本、验证三平台、上传完整草稿并公开发布。以下手工步骤用于维护和故障恢复,同样需要用户的发版授权。 | |
| 4 | 8 | |
| 5 | 9 | ## 发布安装包 |
| 6 | 10 | |
| 7 | 删除:`VERSION` 表示正在构建的应用版本;主页下载入口只指向附件完整的公开 Release。发布新版本时,先完成相关测试、提交源码并推送对应的 `v<版本>` 标签,再按发行文档生成已签名且通过公证的 DMG。 | |
| 11 | 新增:`VERSION` 表示正在构建的应用版本;主页下载入口只指向附件完整的公开 Release。发布新版本时,先完成相关测试、提交源码并推送对应的 `v<版本>` 标签,再按平台发行文档生成已签名且通过公证的 macOS DMG,以及完成签名和实机验收的 Windows 安装器。 | |
| 8 | 12 | |
| 9 | 删除:每个 Release 必须同时包含: | |
| 13 | 新增:以 macOS 为主的公开 Release 包含: | |
| 10 | 14 | |
| 11 | 15 | - `Cage-<版本>-macos-arm64.dmg`。 |
| 12 | 16 | - 与安装包中代理核心版本一致的 `mihomo-v<版本>-source.tar.gz`。 |
| 13 | 删除:- 覆盖这两个文件的 `SHA256SUMS`,摘要在最终公证票据附加后生成。 | |
| 17 | 新增:- `SHA256SUMS`,摘要在最终签名和公证票据附加后生成。 | |
| 18 | 新增: | |
| 19 | 新增:同批发布 Windows 时,增加 `Cage-<版本>-windows-amd64-setup.exe`、该构建的 QEMU 主程序源码和包含随附库/固件的完整对应源码归档。两个平台共用一份 `SHA256SUMS`;不要用一个平台的清单覆盖另一个平台的清单。未签名开发包不得作为正式平台附件。 | |
| 20 | 新增: | |
| 21 | 新增:Linux 附件为 `Cage-<版本>-linux-amd64.deb`,同批附带固定版本的 Mihomo 对应源码。Linux 用户通过系统包管理器手动安装,应用不自动替换系统文件。发布说明必须区分云端容器测试与真实 Linux/KVM 桌面验收;未完成的项目不得列为通过。合并工具也接受 `_output/releases/<版本>/linux` 目录,并去除相同内容的重复源码附件。 | |
| 22 | 新增: | |
| 23 | 新增:使用本地合并工具核对平台目录中的摘要并生成统一发布目录: | |
| 24 | 新增: | |
| 25 | 新增:```sh | |
| 26 | 新增:node scripts/prepare-release-assets.mjs \ | |
| 27 | 新增: --output _output/publish-vVERSION \ | |
| 28 | 新增: _output/releases/VERSION _output/releases/VERSION/windows | |
| 29 | 新增:``` | |
| 30 | 新增: | |
| 31 | 新增:把 `VERSION` 替换为实际版本。输出目录必须不存在;工具拒绝摘要错误、不同内容的同名文件和开发安装器,相同源码附件只保留一份。该工具只准备文件,签名、公证与实机检查仍由对应平台流程完成。 | |
| 14 | 32 | |
| 15 | 33 | 先创建草稿并上传全部附件,再发布草稿。Alpha 版本标为预发行;所有 `gh` 命令显式指定 `--repo Lee-xeo/Claude-Cage`,避免 fork 的默认仓库指向上游。已发布的安装包不原地覆盖,修正二进制时使用新版本号。 |
| 16 | 34 | |
| 17 | 删除:发布或编辑 Release 会运行 `Website and public releases`:匿名下载附件,核对 SHA-256、应用版本、Developer ID 签名、公证票据与 Gatekeeper;通过后重建并部署主页。草稿不会进入公开下载列表。验收失败时,该轮主页部署停止,维护者应检查 Actions 日志并修正发行物。 | |
| 35 | 新增:人工公开发布 Release 会运行 `Website and public releases`:匿名下载附件,核对 SHA-256、应用版本、Developer ID 签名、公证票据与 Gatekeeper;通过后重建并部署主页。自动发布入口直接调用同一网站流程。草稿不会进入公开下载列表;编辑历史 Release 不自动重新部署网站。验收失败时,该轮主页部署停止,维护者应检查 Actions 日志并修正发行物。 | |
| 18 | 36 | |
| 19 | 37 | 版本标签对应的源码须包含发布工作流。需要复验时,使用下文带 `release_tag` 的手动命令。 |
| 20 | 38 | |
| @@ -22,9 +40,9 @@ GitHub Release 一旦公开,应用内更新即可读到它,早于这项事 | ||
| 22 | 40 | |
| 23 | 41 | ## 应用内更新 |
| 24 | 42 | |
| 25 | 删除:支持应用内更新的客户端直接读取公开 Release,经所选受管代理下载,没有主机直连回退。正式客户端忽略预发行;预发行客户端可接收更新的预发行或正式版本。客户端仍独立核对摘要、应用身份、同一 Developer ID Team 和 Apple 验证结果。 | |
| 43 | 新增:支持应用内更新的客户端直接读取公开 Release,经所选受管代理下载,没有主机直连回退。正式客户端忽略预发行;预发行客户端可接收更新的预发行或正式版本。客户端仍独立核对摘要、应用身份、平台签名:macOS 检查同一 Developer ID Team 和 Apple 验证结果,Windows 检查 Authenticode 信任链及相同发布者公钥。 | |
| 26 | 44 | |
| 27 | 删除:首个内测版本为 `0.1.0-alpha.1`,首次安装使用 DMG,后续版本可通过应用内入口升级。公开源校验与单元测试不能证明真实用户环境下的替换、重启和回滚已经验收;每次发布均须在 Release 中说明实际验证范围。 | |
| 45 | 新增:首个内测版本为 `0.1.0-alpha.1`,macOS 首次安装使用 DMG,Windows 使用对应 EXE;后续版本可通过应用内入口升级。公开源校验与单元测试不能证明真实用户环境下的替换、重启和回滚已经验收;每次发布均须在 Release 中说明实际验证范围。 | |
| 28 | 46 | |
| 29 | 47 | 可在不安装、不启动 App 的情况下验证公开附件: |
| 30 | 48 | |
| @@ -37,7 +55,7 @@ bash scripts/verify-macos-release.sh /tmp/cage-release-check/assets | ||
| 37 | 55 | |
| 38 | 56 | ## 主页与措辞同步 |
| 39 | 57 | |
| 40 | 删除:GitHub Pages 的发布源设为 GitHub Actions。`main` 的网站文件变更会自动部署;手动重新部署使用: | |
| 58 | 新增:GitHub Pages 的发布源设为 GitHub Actions。普通推送只做网站检查和构建;显式发版后由发布流程验证对应版本并部署。维护者明确需要重新部署时使用: | |
| 41 | 59 | |
| 42 | 60 | ```sh |
| 43 | 61 | gh workflow run www.yml --repo Lee-xeo/Claude-Cage --ref main |
| @@ -45,6 +63,8 @@ gh workflow run www.yml --repo Lee-xeo/Claude-Cage --ref main | ||
| 45 | 63 | |
| 46 | 64 | 需要同时重验某个公开安装包时,在命令后增加 `-f release_tag=v0.1.0-alpha.1`,替换为实际版本。 |
| 47 | 65 | |
| 66 | 新增:主页默认选择具有完整 macOS 资产的公开 Release。同一 Release 的 Windows 正式安装器及有效摘要存在时,下载区同时提供 Windows 10/11 x64 入口;未签名或缺失附件不显示。Windows-only Release 仍可被 Windows 应用更新器选择,但不会成为主页的默认发布版本。 | |
| 67 | 新增: | |
| 48 | 68 | 主页构建从公开 Release 刷新下载链接,避免源码版本领先安装包时出现失效下载。图片、样式、404 返回链接与兼容重定向均使用 `/Claude-Cage/` 子路径。 |
| 49 | 69 | |
| 50 | 70 | 产品正文由维护者确认的 README 驱动人工同步。README 修改完成后,再更新网页措辞及多语言版本,并分别核对功能范围、安装条件与验收限制。网站部署本身不会自动翻译 README。 |
| @@ -52,7 +52,8 @@ Cage 需要先选择自己的代理。首次首页点击“配置网络与代理 | ||
| 52 | 52 | | 出口 IP 或地区不符合规则 | 选择符合原规则的节点;确实要更换出口时,在“IP 变化规则”中明确修改基准。重检不会自动接受新 IP。 | |
| 53 | 53 | | 代理不可用、核心未就绪 | 在代理页重新应用节点,或到“诊断”查看核心状态并重启 Cage 核心。 | |
| 54 | 54 | | 端口已占用 | 在代理“诊断”中为 Cage 选择未占用的独立端口。无需终止本机其他代理。修改端口需要重启环境。 | |
| 55 | 删除:| 时区、语言或位置查询失败 | 检查代理连通性与“时区与语言”设置,修复后重新应用。不要用主机位置替代失败的检测。 | | |
| 55 | 新增:| 已测得出口 IP,但位置查询失败 | Cage 会依次尝试 ipwho.is 和 IP.SB;可重试、更换节点,或点击“手动设置时区和语言”。使用静态 IP 或不限制地区时,手动模式不依赖位置服务;国家或城市规则仍须取得有效位置才能放行。 | | |
| 56 | 新增:| 代理基础设施 DNS 不可用 | 确认主机能访问 Cloudflare 或阿里 DoH;Cage 会并行尝试二者。业务 DNS 设置不改变节点域名的启动解析。 | | |
| 56 | 57 | | 已暂停或检查报告过期 | 确认配置后重新检查。关键项通过才会恢复外网。 | |
| 57 | 58 | | 主机网络切换后暂时离线 | 等待 Cage 重新绑定当前物理网卡并完成检查;若曾手动暂停,仍需主动重检。 | |
| 58 | 59 | |
| @@ -0,0 +1,72 @@ | ||
| 1 | 新增:# Windows 安装、更新与发布 | |
| 2 | 新增: | |
| 3 | 新增:Cage 的 Windows 版本面向 Windows 10 22H2(内部版本 19045)和 Windows 11 的 x64 电脑。安装后从开始菜单打开 Cage,导入自己的代理,再启动 Linux 环境。工作台、项目、终端和浏览器沿用 macOS 版的操作方式。 | |
| 4 | 新增: | |
| 5 | 新增:Windows 实现和安装器处于开发验收阶段。源码构建成功不代表所有电脑均已通过验收;下载时应查看对应发行说明。未签名开发包用于测试,不能通过应用内更新自动安装。正式发行还需要可信代码签名、完整的随附软件源码材料和 Win10/11 实机验收。 | |
| 6 | 新增: | |
| 7 | 新增:当前开发包已在 Windows 11 Pro 24H2(26100)的 Intel x64 实体机验证安装、覆盖安装、原生工作台、QEMU/WHPX 启动、十一项关键安全检查、中文空格路径共享、终端输入与缩放,以及浏览器和编辑器操作。暂停外网后客机 HTTPS 请求被阻断,重新检测后恢复;配置和项目文件在覆盖安装后保留。卸载保留数据及拒绝未签名更新也已实测。Windows 10 的实机兼容性和可信签名版本之间的完整升级仍待验证。 | |
| 8 | 新增: | |
| 9 | 新增:## 安装前准备 | |
| 10 | 新增: | |
| 11 | 新增:| 项目 | 要求 | | |
| 12 | 新增:|---|---| | |
| 13 | 新增:| 系统 | x64 Windows 10 22H2 或 Windows 11;不包含 Windows ARM64 与 32 位系统 | | |
| 14 | 新增:| 虚拟化 | BIOS/UEFI 已启用处理器虚拟化,Windows 已启用“Windows 虚拟机监控程序平台” | | |
| 15 | 新增:| 存储 | 使用本地磁盘,保留安装包、Linux 镜像、虚拟磁盘和更新备份所需空间;初始虚拟磁盘上限为 24 GiB | | |
| 16 | 新增:| 代理 | 自己的 Clash/Mihomo YAML 来源或 HTTP/SOCKS5 节点;Cage 不提供代理服务 | | |
| 17 | 新增: | |
| 18 | 新增:在“启用或关闭 Windows 功能”中启用“Windows 虚拟机监控程序平台”,按系统要求重启。也可在管理员终端执行: | |
| 19 | 新增: | |
| 20 | 新增:```powershell | |
| 21 | 新增:DISM /Online /Enable-Feature /FeatureName:HypervisorPlatform /All | |
| 22 | 新增:``` | |
| 23 | 新增: | |
| 24 | 新增:这个系统功能需要一次管理员授权;Cage 日常运行和应用安装使用普通用户权限。企业电脑若禁止虚拟化,应由设备管理员启用。Cage 使用独立的 QEMU 虚拟机,不依赖 WSL 或 Docker。 | |
| 25 | 新增: | |
| 26 | 新增:## 安装并开始工作 | |
| 27 | 新增: | |
| 28 | 新增:1. 下载对应版本的 `Cage-<版本>-windows-amd64-setup.exe`,核对同批的 `SHA256SUMS`。开发包名为 `Cage-<版本>-windows-amd64-setup-unsigned.exe`,明确标识未签名状态。 | |
| 29 | 新增:2. 运行安装程序,选择安装位置。安装器随附 .NET 桌面运行组件、WebView2 安装程序、QEMU、OpenSSH 客户端和代理核心,无需另装 Go、Node.js 或 Clash。 | |
| 30 | 新增:3. 从开始菜单启动 Cage,按[开始使用](getting-started.md#2-导入并选择代理)导入并选择代理。首次启动下载 Linux 镜像及开发工具,通过网络检查后即可使用。 | |
| 31 | 新增: | |
| 32 | 新增:安装器不设置系统代理,不安装 SSH 服务,不把随附工具加入系统 PATH。WebView2 是 Microsoft 提供的系统浏览器运行时,其安装与维护由 Microsoft 安装程序负责。 | |
| 33 | 新增: | |
| 34 | 新增:“打开项目”接受 Windows 文件夹。例如 `C:\Users\姓名\Projects\demo` 在 Linux 内对应 `/c/Users/姓名/Projects/demo`。项目文件仍保存在原来的 Windows 文件夹中,编辑和删除会同步;`.git` 等元数据保持只读,提交在主机 Git 中完成。只共享默认工作区与明确打开的目录。 | |
| 35 | 新增: | |
| 36 | 新增:Windows 快捷键以 `Ctrl` 为主:`Ctrl+O` 打开项目、`Ctrl+T` 新建网页、`Ctrl+L` 定位地址栏、`Ctrl+W` 关闭标签,`Ctrl+Shift+Enter` 新建终端。终端使用 `Ctrl+Shift+C/V` 复制粘贴,`Ctrl+C` 中断命令。网页和编辑器采用 Linux 的 Ctrl 组合键。 | |
| 37 | 新增: | |
| 38 | 新增:关闭窗口会保留环境与后台任务,可从托盘图标重新打开;停止环境或选择停止后退出会结束终端。重新打开应用可连接仍运行的会话。 | |
| 39 | 新增: | |
| 40 | 新增:浏览器上传通过本机文件选择窗口选取文件;下载完成可用 Windows“另存为”选择位置。侧栏“下载”提供打开文件、在资源管理器中显示与再次另存为,取消保存窗口时保留默认 Downloads 中的文件。操作与限制见[浏览器上传与下载](getting-started.md#浏览器上传与下载)。 | |
| 41 | 新增: | |
| 42 | 新增:## 更新与卸载 | |
| 43 | 新增: | |
| 44 | 新增:应用内更新从固定的公开 GitHub Releases 来源选择 Windows x64 安装器,并沿用预发行与正式版通道规则。检查与下载经过已经应用并运行的 Cage 代理,不回退主机直连。下载安装器后校验 SHA-256、版本、产品名称和 Authenticode 签名;当前应用与新安装器必须具有相同的发布者公钥,未签名开发包不能自动安装更新。 | |
| 45 | 新增: | |
| 46 | 新增:有运行任务时,安装前会要求保存并确认停止。更新器先备份应用,再通过工作台统一入口停止环境、代理和控制服务,等待当前窗口退出后执行静默安装。新应用完成工作台启动确认后才认定成功;安装或启动失败时尝试恢复旧程序,保留失败原因和必要备份。磁盘空间不足、文件被其他软件占用等情况可能阻止自动恢复,应按错误信息处理。 | |
| 47 | 新增: | |
| 48 | 新增:手动更新前也应保存文件、停止环境并退出 Cage,再运行新版安装器。旧后台仍运行时安装器会拒绝覆盖。更新应用不等于更新 Linux 内所有工具;工具升级在“设置 → 环境与恢复”中单独执行。 | |
| 49 | 新增: | |
| 50 | 新增:卸载前停止环境并退出,在 Windows“设置 → 应用”中卸载 Cage。卸载保留用户数据:默认配置、代理和虚拟磁盘位于 `%USERPROFILE%\.claude-cage`,默认工作区通常位于 `%USERPROFILE%\.claude-cage-workspace`,自行打开的项目仍在原目录。WebView2 可能由其他程序共用,不随 Cage 自动卸载。需要另行删除数据时先备份,删除虚拟磁盘会丢失只保存在 Linux 环境中的文件与登录状态。 | |
| 51 | 新增: | |
| 52 | 新增:## 常见启动问题 | |
| 53 | 新增: | |
| 54 | 新增:- 提示虚拟化不可用:检查 BIOS/UEFI 的虚拟化开关及 Windows 虚拟机监控程序平台,重启后再试。远程或嵌套虚拟机还需要外层宿主允许嵌套虚拟化。 | |
| 55 | 新增:- 提示缺少 WebView2:重新运行完整安装程序。不要从第三方站点下载同名 DLL。 | |
| 56 | 新增:- 工作台能打开,环境不能联网:检查 Cage 内是否已选择节点及网络检查结果。Windows 浏览器能联网不表示 Cage 节点已配置。 | |
| 57 | 新增:- 提示权限或路径不可用:使用当前用户有权限访问的本地目录,不把 Cage 安装目录、私有配置或磁盘根目录作为共享项目。更新器拒绝含符号链接或目录联接的安装路径。 | |
| 58 | 新增: | |
| 59 | 新增:反馈问题时提供 Cage 版本、Windows 版本与内部版本号、CPU 架构、失败步骤和错误原文。不要附带代理密码、订阅链接、会话地址或未脱敏的配置文件。 | |
| 60 | 新增: | |
| 61 | 新增:## 维护者构建与验收 | |
| 62 | 新增: | |
| 63 | 新增:构建使用 PowerShell 7、Go(遵循 `go.mod`)、Node.js、.NET 10 SDK、7-Zip 和 NSIS。依赖版本、下载地址及哈希固定在 `packaging/windows/dependencies.json`;构建时逐个校验。源码默认版本来自根目录 `VERSION`。 | |
| 64 | 新增: | |
| 65 | 新增:```powershell | |
| 66 | 新增:pwsh -File scripts/build-windows.ps1 | |
| 67 | 新增:pwsh -File scripts/package-windows.ps1 -SkipBuild | |
| 68 | 新增:``` | |
| 69 | 新增: | |
| 70 | 新增:应用目录输出到 `_output/windows-amd64/app`,安装器与校验文件输出到 `_output/releases/<版本>/windows`。正式签名构建使用构建脚本的 `-Release` 模式,并配置当前用户证书存储中的代码签名证书;发布脚本还要求与 QEMU 构建相对应的源码归档。参数以脚本帮助为准。签名完成后再生成发行物摘要,不能对签名后的文件重新修改。两个平台同批发布时,使用[公开发行流程](public-releases.md#发布安装包)生成共用校验清单;官网仅在公开 Release 的 Windows 附件和摘要有效时显示下载按钮。 | |
| 71 | 新增: | |
| 72 | 新增:CI 负责源码、原生窗口、安装器和 Windows 可执行测试;干净 Windows 10/11 上的虚拟化仍需要设备验收。每次正式发行至少记录:首次安装、WebView2 首次启动、无虚拟化时的提示、代理导入、VM 首次下载与启动、网络隔离检查、中文和空格路径共享、终端输入与缩放、退出恢复、从旧签名版升级、失败恢复、卸载后数据保留。只有真实执行的项目才能标记通过。 | |
| @@ -0,0 +1,26 @@ | ||
| 1 | 新增:package appupdate | |
| 2 | 新增: | |
| 3 | 新增:import "testing" | |
| 4 | 新增: | |
| 5 | 新增:func TestPlatformReleaseNeverInstallsAnotherPlatform(t *testing.T) { | |
| 6 | 新增: r := fixtureRelease("0.2.0", false) | |
| 7 | 新增: windowsAsset := r.Assets[0] | |
| 8 | 新增: windowsAsset.Name = "Cage-0.2.0-windows-amd64-setup.exe" | |
| 9 | 新增: windowsAsset.URL = "https://github.com/" + repository + "/releases/download/v0.2.0/" + windowsAsset.Name | |
| 10 | 新增: r.Assets = append(r.Assets, windowsAsset) | |
| 11 | 新增: for _, tc := range []struct{ os, arch, name string }{ | |
| 12 | 新增: {"windows", "amd64", windowsAsset.Name}, | |
| 13 | 新增: {"darwin", "arm64", r.Assets[0].Name}, | |
| 14 | 新增: } { | |
| 15 | 新增: c, err := selectPlatformRelease([]release{r}, "0.1.0", tc.os, tc.arch) | |
| 16 | 新增: if err != nil || c == nil || c.Archive.Name != tc.name { | |
| 17 | 新增: t.Fatalf("%s/%s: %#v %v", tc.os, tc.arch, c, err) | |
| 18 | 新增: } | |
| 19 | 新增: } | |
| 20 | 新增: if c, err := selectPlatformRelease([]release{fixtureRelease("0.2.0", false)}, "0.1.0", "windows", "amd64"); err != nil || c != nil { | |
| 21 | 新增: t.Fatalf("macOS package selected on Windows: %#v %v", c, err) | |
| 22 | 新增: } | |
| 23 | 新增: if _, err := selectPlatformRelease([]release{r}, "0.1.0", "windows", "arm64"); err == nil { | |
| 24 | 新增: t.Fatal("unsupported architecture appeared up to date") | |
| 25 | 新增: } | |
| 26 | 新增:} | |
| @@ -15,11 +15,13 @@ import ( | ||
| 15 | 15 | "os" |
| 16 | 16 | "os/signal" |
| 17 | 17 | "path/filepath" |
| 18 | 新增: "runtime" | |
| 18 | 19 | "strings" |
| 19 | 20 | "syscall" |
| 20 | 21 | "time" |
| 21 | 22 | |
| 22 | 23 | "github.com/sylvinus/agent-vm/internal/cage" |
| 24 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 23 | 25 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 24 | 26 | "github.com/sylvinus/agent-vm/internal/version" |
| 25 | 27 | "golang.org/x/mod/semver" |
| @@ -106,15 +108,13 @@ func Run(configPath string, args []string, output io.Writer) int { | ||
| 106 | 108 | return fail(err) |
| 107 | 109 | } |
| 108 | 110 | directory := filepath.Join(filepath.Dir(configPath), "updates") |
| 109 | 删除: if err = os.MkdirAll(directory, 0700); err != nil { | |
| 111 | 新增: if err = host.EnsurePrivateDir(directory); err != nil { | |
| 110 | 112 | return fail(errors.New("无法创建私有更新目录")) |
| 111 | 113 | } |
| 112 | 114 | if st, e := os.Lstat(directory); e != nil || !st.IsDir() || st.Mode()&os.ModeSymlink != 0 { |
| 113 | 115 | return fail(errors.New("更新目录必须是私有普通目录")) |
| 114 | 116 | } |
| 115 | 删除: if err = os.Chmod(directory, 0700); err != nil { | |
| 116 | 删除: return fail(errors.New("无法保护更新目录")) | |
| 117 | 删除: } | |
| 117 | 新增: | |
| 118 | 118 | job, err := os.MkdirTemp(directory, "download-") |
| 119 | 119 | if err != nil { |
| 120 | 120 | return fail(errors.New("无法创建更新下载任务")) |
| @@ -125,7 +125,14 @@ func Run(configPath string, args []string, output io.Writer) int { | ||
| 125 | 125 | _ = os.RemoveAll(job) |
| 126 | 126 | } |
| 127 | 127 | }() |
| 128 | 删除: archive := filepath.Join(job, "Cage.dmg") | |
| 128 | 新增: if err = host.EnsurePrivateDir(job); err != nil { | |
| 129 | 新增: return fail(err) | |
| 130 | 新增: } | |
| 131 | 新增: localName := "Cage.dmg" | |
| 132 | 新增: if runtime.GOOS == "windows" { | |
| 133 | 新增: localName = "Cage-setup.exe" | |
| 134 | 新增: } | |
| 135 | 新增: archive := filepath.Join(job, localName) | |
| 129 | 136 | state.Phase, state.Message, state.TotalBytes = "downloading", "正在下载更新", c.Archive.Size |
| 130 | 137 | emit() |
| 131 | 138 | err = download(ctx, client, c.Archive, digest, archive, func(n int64) { |
| @@ -249,6 +256,24 @@ func findRelease(ctx context.Context, client *http.Client, current string) (*can | ||
| 249 | 256 | } |
| 250 | 257 | |
| 251 | 258 | func selectRelease(releases []release, current string) (*candidate, error) { |
| 259 | 新增: return selectPlatformRelease(releases, current, runtime.GOOS, runtime.GOARCH) | |
| 260 | 新增:} | |
| 261 | 新增: | |
| 262 | 新增:func archiveName(version, goos, goarch string) (string, error) { | |
| 263 | 新增: switch { | |
| 264 | 新增: case goos == "darwin" && goarch == "arm64": | |
| 265 | 新增: return "Cage-" + version + "-macos-arm64.dmg", nil | |
| 266 | 新增: case goos == "windows" && goarch == "amd64": | |
| 267 | 新增: return "Cage-" + version + "-windows-amd64-setup.exe", nil | |
| 268 | 新增: default: | |
| 269 | 新增: return "", errors.New("此平台尚无 Cage 应用内更新发行包") | |
| 270 | 新增: } | |
| 271 | 新增:} | |
| 272 | 新增: | |
| 273 | 新增:func selectPlatformRelease(releases []release, current, goos, goarch string) (*candidate, error) { | |
| 274 | 新增: if _, err := archiveName(current, goos, goarch); err != nil { | |
| 275 | 新增: return nil, err | |
| 276 | 新增: } | |
| 252 | 277 | currentTag := "v" + current |
| 253 | 278 | if !semver.IsValid(currentTag) || semver.Canonical(currentTag) != currentTag { |
| 254 | 279 | return nil, errors.New("当前应用版本无效,无法安全比较更新") |
| @@ -267,11 +292,12 @@ func selectRelease(releases []release, current string) (*candidate, error) { | ||
| 267 | 292 | continue |
| 268 | 293 | } |
| 269 | 294 | c := candidate{Version: v} |
| 295 | 新增: name, _ := archiveName(v, goos, goarch) | |
| 270 | 296 | for _, a := range r.Assets { |
| 271 | 297 | if a.State != "uploaded" { |
| 272 | 298 | continue |
| 273 | 299 | } |
| 274 | 删除: if a.Name == "Cage-"+v+"-macos-arm64.dmg" && a.Size > 0 && a.Size <= maxArchive { | |
| 300 | 新增: if a.Name == name && a.Size > 0 && a.Size <= maxArchive { | |
| 275 | 301 | c.Archive = a |
| 276 | 302 | } |
| 277 | 303 | if a.Name == "SHA256SUMS" && a.Size > 0 && a.Size <= 64<<10 { |
| @@ -373,6 +399,9 @@ func download(ctx context.Context, client *http.Client, a asset, digest, path st | ||
| 373 | 399 | os.Remove(path) |
| 374 | 400 | } |
| 375 | 401 | }() |
| 402 | 新增: if err := host.ProtectFile(path); err != nil { | |
| 403 | 新增: return errors.New("无法保护更新文件") | |
| 404 | 新增: } | |
| 376 | 405 | hash := sha256.New() |
| 377 | 406 | w := &progressWriter{writer: io.MultiWriter(f, hash), notify: progress} |
| 378 | 407 | n, err := io.Copy(w, io.LimitReader(resp.Body, a.Size+1)) |
| @@ -5,6 +5,7 @@ import ( | ||
| 5 | 5 | "context" |
| 6 | 6 | "crypto/sha256" |
| 7 | 7 | "fmt" |
| 8 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 8 | 9 | "io" |
| 9 | 10 | "net/http" |
| 10 | 11 | "net/url" |
| @@ -19,16 +20,16 @@ func fixtureRelease(v string, pre bool) release { | ||
| 19 | 20 | } |
| 20 | 21 | func TestReleaseSelectionPreservesChannelsAndNumericPrereleases(t *testing.T) { |
| 21 | 22 | rs := []release{fixtureRelease("0.2.0-alpha.9", true), fixtureRelease("0.2.0-alpha.10", true), fixtureRelease("0.1.0", false)} |
| 22 | 删除: c, err := selectRelease(rs, "0.2.0-alpha.1") | |
| 23 | 新增: c, err := selectPlatformRelease(rs, "0.2.0-alpha.1", "darwin", "arm64") | |
| 23 | 24 | if err != nil || c == nil || c.Version != "0.2.0-alpha.10" { |
| 24 | 25 | t.Fatalf("selected %#v: %v", c, err) |
| 25 | 26 | } |
| 26 | 27 | rs = append(rs, fixtureRelease("0.2.0", false), fixtureRelease("0.3.0-alpha.1", true)) |
| 27 | 删除: c, err = selectRelease(rs, "0.1.0") | |
| 28 | 新增: c, err = selectPlatformRelease(rs, "0.1.0", "darwin", "arm64") | |
| 28 | 29 | if err != nil || c == nil || c.Version != "0.2.0" { |
| 29 | 30 | t.Fatalf("stable channel %#v: %v", c, err) |
| 30 | 31 | } |
| 31 | 删除: if c, err = selectRelease(rs, "0.3.0"); err != nil || c != nil { | |
| 32 | 新增: if c, err = selectPlatformRelease(rs, "0.3.0", "darwin", "arm64"); err != nil || c != nil { | |
| 32 | 33 | t.Fatalf("downgrade: %#v %v", c, err) |
| 33 | 34 | } |
| 34 | 35 | } |
| @@ -43,7 +44,7 @@ func TestRejectReleaseAssetOutsideRepositoryOrOversize(t *testing.T) { | ||
| 43 | 44 | } { |
| 44 | 45 | r := fixtureRelease("0.2.0", false) |
| 45 | 46 | mutate(&r) |
| 46 | 删除: if c, err := selectRelease([]release{r}, "0.1.0"); err != nil || c != nil { | |
| 47 | 新增: if c, err := selectPlatformRelease([]release{r}, "0.1.0", "darwin", "arm64"); err != nil || c != nil { | |
| 47 | 48 | t.Fatalf("accepted %#v: %v", c, err) |
| 48 | 49 | } |
| 49 | 50 | } |
| @@ -87,8 +88,7 @@ func TestDownloadVerifiesSizeDigestAndPrivateFile(t *testing.T) { | ||
| 87 | 88 | if err != nil || e != nil || string(b) != content || received != a.Size { |
| 88 | 89 | t.Fatalf("download %q %v %v %d", b, err, e, received) |
| 89 | 90 | } |
| 90 | 删除: st, _ := os.Stat(path) | |
| 91 | 删除: if st.Mode().Perm() != 0600 { | |
| 91 | 新增: if host.CheckPrivateFile(path) != nil { | |
| 92 | 92 | t.Fatal("public file") |
| 93 | 93 | } |
| 94 | 94 | } else { |
| @@ -2,10 +2,12 @@ | ||
| 2 | 2 | import { spawn, execFile } from "node:child_process"; |
| 3 | 3 | import { promisify } from "node:util"; |
| 4 | 4 | const runFile = promisify(execFile); |
| 5 | 删除:import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs"; | |
| 5 | 新增:import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, constants } from "node:fs"; | |
| 6 | 新增:import { open } from "node:fs/promises"; | |
| 6 | 7 | import http from "node:http"; |
| 7 | 8 | import { auditBrowser } from "./browser-audit.mjs"; |
| 8 | 9 | import { DownloadManager } from "./browser-downloads.mjs"; |
| 10 | 新增:import { UploadManager, uploadLimit } from "./browser-uploads.mjs"; | |
| 9 | 11 | import { timingSafeEqual } from "node:crypto"; |
| 10 | 12 | |
| 11 | 13 | const config = JSON.parse( |
| @@ -77,12 +79,16 @@ const downloads = new DownloadManager({ | ||
| 77 | 79 | return JSON.parse(output); |
| 78 | 80 | }, |
| 79 | 81 | }); |
| 82 | 新增:const uploadDirectory = "/home/cage-browser/.cage-uploads"; | |
| 83 | 新增:rmSync(uploadDirectory, { recursive: true, force: true }); | |
| 84 | 新增:const uploadSessions = new Map(); | |
| 85 | 新增:const uploads = new UploadManager({ directory: uploadDirectory, cdp, changed: () => broadcastState() }); | |
| 80 | 86 | function cdp(method, params = {}, sessionId, timeout = 4500) { |
| 81 | 87 | return new Promise((resolve, reject) => { |
| 82 | 88 | const id = ++sequence; |
| 83 | 89 | const timer = setTimeout(() => { |
| 84 | 90 | pending.delete(id); |
| 85 | 删除: reject(new Error("Browser command timed out")); | |
| 91 | 新增: reject(new Error(`Browser command timed out: ${method}`)); | |
| 86 | 92 | }, timeout); |
| 87 | 93 | pending.set(id, { resolve, reject, timer }); |
| 88 | 94 | chrome.stdio[3].write( |
| @@ -126,6 +132,7 @@ chrome.stdio[4].on("data", (chunk) => { | ||
| 126 | 132 | if (t.type === "page" && !auditContexts.has(t.browserContextId)) { |
| 127 | 133 | const fresh = !targets.has(t.targetId); |
| 128 | 134 | targets.set(t.targetId, t); |
| 135 | 新增: if (fresh) void session(t.targetId).catch(() => {}); | |
| 129 | 136 | if (t.targetId === activeId) rememberSelection(); |
| 130 | 137 | broadcastState(); |
| 131 | 138 | if (!activeId) activeId = t.targetId; |
| @@ -136,6 +143,8 @@ chrome.stdio[4].on("data", (chunk) => { | ||
| 136 | 143 | if (event.method === "Target.targetDestroyed") { |
| 137 | 144 | if (!targets.has(p.targetId)) continue; |
| 138 | 145 | targets.delete(p.targetId); |
| 146 | 新增: uploads.cancelTab(p.targetId); | |
| 147 | 新增: for (const [sid, tab] of uploadSessions) if (tab === p.targetId) uploadSessions.delete(sid); | |
| 139 | 148 | sessions.delete(p.targetId); |
| 140 | 149 | broadcastState(); |
| 141 | 150 | if (activeId === p.targetId) { |
| @@ -146,6 +155,11 @@ chrome.stdio[4].on("data", (chunk) => { | ||
| 146 | 155 | if (event.method === "Browser.downloadWillBegin") |
| 147 | 156 | downloads.begin(p.guid, p.suggestedFilename); |
| 148 | 157 | if (event.method === "Browser.downloadProgress") downloads.progress(p); |
| 158 | 新增: const uploadTab = uploadSessions.get(event.sessionId); | |
| 159 | 新增: if (uploadTab && event.method === "Page.fileChooserOpened") | |
| 160 | 新增: void uploads.opened(uploadTab, event.sessionId, p).catch(() => {}); | |
| 161 | 新增: if (uploadTab && event.method === "Page.frameNavigated" && !p.frame?.parentId) | |
| 162 | 新增: uploads.cancelTab(uploadTab); | |
| 149 | 163 | } |
| 150 | 164 | }); |
| 151 | 165 | chrome.on("exit", () => { |
| @@ -166,15 +180,21 @@ async function session(id) { | ||
| 166 | 180 | if (!sessions.has(id)) |
| 167 | 181 | sessions.set( |
| 168 | 182 | id, |
| 169 | 删除: cdp("Target.attachToTarget", { targetId: id, flatten: true }).then( | |
| 170 | 删除: (r) => r.sessionId, | |
| 171 | 删除: ), | |
| 183 | 新增: cdp("Target.attachToTarget", { targetId: id, flatten: true }).then(async (r) => { | |
| 184 | 新增: uploadSessions.set(r.sessionId, id); | |
| 185 | 新增: await cdp("Page.enable", {}, r.sessionId); | |
| 186 | 新增: await cdp("Page.setInterceptFileChooserDialog", { enabled: true }, r.sessionId); | |
| 187 | 新增: return r.sessionId; | |
| 188 | 新增: }).catch(error => { sessions.delete(id); throw error; }), | |
| 172 | 189 | ); |
| 173 | 190 | return sessions.get(id); |
| 174 | 191 | } |
| 175 | 192 | async function activate(id, focus = false) { |
| 176 | 193 | if (!targets.has(id)) throw new Error("Tab no longer exists"); |
| 194 | 新增: // Restored background tabs may have no live renderer until activated. | |
| 195 | 新增: // Page.enable must not block the command that wakes that renderer. | |
| 177 | 196 | await cdp("Target.activateTarget", { targetId: id }); |
| 197 | 新增: await session(id); | |
| 178 | 198 | activeId = id; |
| 179 | 199 | rememberSelection(); |
| 180 | 200 | broadcastState(focus); |
| @@ -293,6 +313,7 @@ function publicState() { | ||
| 293 | 313 | return { |
| 294 | 314 | active: activeId, |
| 295 | 315 | downloads: downloads.snapshot(), |
| 316 | 新增: uploads: uploads.snapshot(), | |
| 296 | 317 | tabs: [...targets.values()].map((t) => ({ |
| 297 | 318 | id: t.targetId, |
| 298 | 319 | title: displayTitle(t), |
| @@ -361,6 +382,21 @@ function mutate(fn) { | ||
| 361 | 382 | return result; |
| 362 | 383 | } |
| 363 | 384 | |
| 385 | 新增:function pasteImage(png) { | |
| 386 | 新增: if (typeof png !== "string" || png.length > 27962028) throw new Error("Image too large"); | |
| 387 | 新增: const data = Buffer.from(png, "base64"); | |
| 388 | 新增: if (!data.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) throw new Error("Invalid PNG"); | |
| 389 | 新增: return new Promise((resolve, reject) => { | |
| 390 | 新增: const child = spawn("/usr/local/bin/cage-image-input", ["paste"], { | |
| 391 | 新增: stdio: ["pipe", "ignore", "ignore"], timeout: 15000, | |
| 392 | 新增: }); | |
| 393 | 新增: child.on("error", reject); | |
| 394 | 新增: child.stdin.on("error", reject); | |
| 395 | 新增: child.on("close", (code) => code === 0 ? resolve() : reject(new Error("Image paste failed"))); | |
| 396 | 新增: child.stdin.end(data); | |
| 397 | 新增: }); | |
| 398 | 新增:} | |
| 399 | 新增: | |
| 364 | 400 | const server = http.createServer(async (req, res) => { |
| 365 | 401 | res.setHeader("Cache-Control", "no-store"); |
| 366 | 402 | res.setHeader("Content-Type", "application/json"); |
| @@ -378,6 +414,25 @@ const server = http.createServer(async (req, res) => { | ||
| 378 | 414 | } |
| 379 | 415 | try { |
| 380 | 416 | if (!ready) throw new Error("Browser is starting"); |
| 417 | 新增: const route = new URL(req.url, "http://localhost"); | |
| 418 | 新增: if (req.method === "POST" && route.pathname === "/upload-file") { | |
| 419 | 新增: if (Number(req.headers["content-length"]) > uploadLimit) throw new Error("每个文件不能超过 2 GB"); | |
| 420 | 新增: res.end(JSON.stringify(await uploads.receive(route.searchParams.get("id"), route.searchParams.get("name"), req))); | |
| 421 | 新增: return; | |
| 422 | 新增: } | |
| 423 | 新增: if (req.method === "GET" && route.pathname === "/download-file") { | |
| 424 | 新增: const source = downloads.sourceFile(route.searchParams.get("id")); | |
| 425 | 新增: const file = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW); | |
| 426 | 新增: const stat = await file.stat(); | |
| 427 | 新增: if (!stat.isFile()) { await file.close(); throw new Error("下载文件不可用"); } | |
| 428 | 新增: res.setHeader("Content-Type", "application/octet-stream"); | |
| 429 | 新增: res.setHeader("Content-Length", stat.size); | |
| 430 | 新增: const stream = file.createReadStream(); | |
| 431 | 新增: res.on("close", () => stream.destroy()); | |
| 432 | 新增: stream.on("error", () => res.destroy()); | |
| 433 | 新增: stream.pipe(res); | |
| 434 | 新增: return; | |
| 435 | 新增: } | |
| 381 | 436 | if (req.method === "GET" && req.url === "/health") { |
| 382 | 437 | res.end('{"ready":true}'); |
| 383 | 438 | return; |
| @@ -403,9 +458,11 @@ const server = http.createServer(async (req, res) => { | ||
| 403 | 458 | let text = ""; |
| 404 | 459 | for await (const chunk of req) { |
| 405 | 460 | text += chunk; |
| 406 | 删除: if (text.length > 65536) throw new Error("Request too large"); | |
| 461 | 新增: if (text.length > (req.url === "/paste-image" ? 28 * 1024 * 1024 : 65536)) throw new Error("Request too large"); | |
| 407 | 462 | } |
| 408 | 463 | const input = JSON.parse(text || "{}"); |
| 464 | 新增: if (req.url === "/upload-finish") { res.end(JSON.stringify(await uploads.finish(input.id))); return; } | |
| 465 | 新增: if (req.url === "/upload-cancel") { uploads.cancel(input.id); res.end('{"ok":true}'); return; } | |
| 409 | 466 | if (req.url === "/download-retry") { |
| 410 | 467 | res.end(JSON.stringify(downloads.retry(input.id))); |
| 411 | 468 | return; |
| @@ -437,6 +494,10 @@ const server = http.createServer(async (req, res) => { | ||
| 437 | 494 | const id = input.id || activeId; |
| 438 | 495 | if (!targets.has(id)) throw new Error("Tab no longer exists"); |
| 439 | 496 | switch (req.url) { |
| 497 | 新增: case "/paste-image": | |
| 498 | 新增: if (input.id !== activeId) throw new Error("Image target changed"); | |
| 499 | 新增: await pasteImage(input.png); | |
| 500 | 新增: break; | |
| 440 | 501 | case "/insert-text": |
| 441 | 502 | if (input.id !== activeId || typeof input.text !== "string" || |
| 442 | 503 | !input.text || Buffer.byteLength(input.text, "utf8") > 8192) |
| @@ -503,7 +564,10 @@ server.listen(18500, "127.0.0.1"); | ||
| 503 | 564 | [...targets.keys()][0], |
| 504 | 565 | ); |
| 505 | 566 | ready = true; |
| 506 | 删除:})().catch(() => process.exit(1)); | |
| 567 | 新增:})().catch(error => { | |
| 568 | 新增: console.error("Browser startup failed:", error.message); | |
| 569 | 新增: process.exit(1); | |
| 570 | 新增:}); | |
| 507 | 571 | process.on("SIGTERM", () => { |
| 508 | 572 | shuttingDown = true; |
| 509 | 573 | server.close(); |
| @@ -185,4 +185,11 @@ export class DownloadManager { | ||
| 185 | 185 | snapshot() { |
| 186 | 186 | return [...this.records.values()].reverse().map(({ sourceReady, ...record }) => record); |
| 187 | 187 | } |
| 188 | 新增: | |
| 189 | 新增: sourceFile(id) { | |
| 190 | 新增: const record = this.records.get(id); | |
| 191 | 新增: if (!record?.sourceReady || record.state === "downloading" || record.state === "saving" || !this.sourceExists(id)) | |
| 192 | 新增: throw new Error("下载源文件不可用或尚未完成"); | |
| 193 | 新增: return join(this.directory, "Downloads", id); | |
| 194 | 新增: } | |
| 188 | 195 | } |
| @@ -0,0 +1,132 @@ | ||
| 1 | 新增:import { randomUUID } from "node:crypto"; | |
| 2 | 新增:import { mkdir, open, rm } from "node:fs/promises"; | |
| 3 | 新增:import { basename, join } from "node:path"; | |
| 4 | 新增: | |
| 5 | 新增:export const uploadLimit = 2 * 1024 * 1024 * 1024; | |
| 6 | 新增:export const validFileName = (name) => | |
| 7 | 新增: typeof name === "string" && | |
| 8 | 新增: name.length > 0 && | |
| 9 | 新增: Buffer.byteLength(name) <= 255 && | |
| 10 | 新增: basename(name) === name && | |
| 11 | 新增: !/[\\\x00-\x1f]/.test(name) && | |
| 12 | 新增: ![".", ".."].includes(name); | |
| 13 | 新增: | |
| 14 | 新增:export class UploadManager { | |
| 15 | 新增: constructor({ directory, cdp, changed = () => {} }) { | |
| 16 | 新增: this.directory = directory; | |
| 17 | 新增: this.cdp = cdp; | |
| 18 | 新增: this.changed = changed; | |
| 19 | 新增: this.requests = new Map(); | |
| 20 | 新增: this.retained = new Map(); | |
| 21 | 新增: } | |
| 22 | 新增: | |
| 23 | 新增: async opened(tabId, sessionId, event) { | |
| 24 | 新增: if (!event.backendNodeId) return; | |
| 25 | 新增: this.cancelTab(tabId, false); | |
| 26 | 新增: const id = randomUUID(); | |
| 27 | 新增: this.requests.set(id, { | |
| 28 | 新增: id, | |
| 29 | 新增: tabId, | |
| 30 | 新增: sessionId, | |
| 31 | 新增: node: event.backendNodeId, | |
| 32 | 新增: multiple: event.mode === "selectMultiple", | |
| 33 | 新增: files: [], | |
| 34 | 新增: busy: false, | |
| 35 | 新增: }); | |
| 36 | 新增: this.changed(); | |
| 37 | 新增: } | |
| 38 | 新增: | |
| 39 | 新增: snapshot() { | |
| 40 | 新增: return [...this.requests.values()].map(({ id, tabId, multiple }) => ({ | |
| 41 | 新增: id, | |
| 42 | 新增: tabId, | |
| 43 | 新增: multiple, | |
| 44 | 新增: })); | |
| 45 | 新增: } | |
| 46 | 新增: | |
| 47 | 新增: request(id) { | |
| 48 | 新增: const request = this.requests.get(id); | |
| 49 | 新增: if (!request) | |
| 50 | 新增: throw new Error("上传窗口已关闭或网页已刷新,请重新点击网页的上传按钮"); | |
| 51 | 新增: return request; | |
| 52 | 新增: } | |
| 53 | 新增: | |
| 54 | 新增: async receive(id, name, stream) { | |
| 55 | 新增: const request = this.request(id); | |
| 56 | 新增: if (!validFileName(name)) throw new Error("文件名无效"); | |
| 57 | 新增: if (request.busy || request.files.length >= (request.multiple ? 100 : 1)) | |
| 58 | 新增: throw new Error("请选择允许数量的文件"); | |
| 59 | 新增: request.busy = true; | |
| 60 | 新增: const directory = join(this.directory, id, randomUUID()); | |
| 61 | 新增: const path = join(directory, name); | |
| 62 | 新增: let file, | |
| 63 | 新增: size = 0, | |
| 64 | 新增: accepted = false; | |
| 65 | 新增: try { | |
| 66 | 新增: await mkdir(directory, { recursive: true, mode: 0o700 }); | |
| 67 | 新增: file = await open(path, "wx", 0o600); | |
| 68 | 新增: for await (const chunk of stream) { | |
| 69 | 新增: size += chunk.length; | |
| 70 | 新增: if (size > uploadLimit) throw new Error("每个文件不能超过 2 GB"); | |
| 71 | 新增: if (this.requests.get(id) !== request) throw new Error("上传已取消"); | |
| 72 | 新增: await file.writeFile(chunk); | |
| 73 | 新增: } | |
| 74 | 新增: await file.close(); | |
| 75 | 新增: file = null; | |
| 76 | 新增: if (this.requests.get(id) !== request) throw new Error("上传已取消"); | |
| 77 | 新增: request.files.push(path); | |
| 78 | 新增: accepted = true; | |
| 79 | 新增: return { ok: true, name, size }; | |
| 80 | 新增: } finally { | |
| 81 | 新增: await file?.close(); | |
| 82 | 新增: if (!accepted) await rm(directory, { recursive: true, force: true }); | |
| 83 | 新增: request.busy = false; | |
| 84 | 新增: } | |
| 85 | 新增: } | |
| 86 | 新增: | |
| 87 | 新增: async finish(id) { | |
| 88 | 新增: const request = this.request(id); | |
| 89 | 新增: if (request.busy || !request.files.length) | |
| 90 | 新增: throw new Error("请先选择并传递文件"); | |
| 91 | 新增: request.busy = true; | |
| 92 | 新增: try { | |
| 93 | 新增: await this.cdp( | |
| 94 | 新增: "DOM.setFileInputFiles", | |
| 95 | 新增: { backendNodeId: request.node, files: request.files }, | |
| 96 | 新增: request.sessionId, | |
| 97 | 新增: ); | |
| 98 | 新增: this.requests.delete(id); | |
| 99 | 新增: // Chromium File objects can read lazily. Retain bytes until the document | |
| 100 | 新增: // is replaced or the tab closes, rather than deleting during submission. | |
| 101 | 新增: const retained = this.retained.get(request.tabId) || []; | |
| 102 | 新增: retained.push(id); | |
| 103 | 新增: this.retained.set(request.tabId, retained); | |
| 104 | 新增: this.changed(); | |
| 105 | 新增: return { ok: true }; | |
| 106 | 新增: } catch (error) { | |
| 107 | 新增: this.cancel(id); | |
| 108 | 新增: throw error; | |
| 109 | 新增: } | |
| 110 | 新增: } | |
| 111 | 新增: | |
| 112 | 新增: cancel(id) { | |
| 113 | 新增: if (!this.requests.delete(id)) return; | |
| 114 | 新增: void rm(join(this.directory, id), { recursive: true, force: true }).catch( | |
| 115 | 新增: () => {}, | |
| 116 | 新增: ); | |
| 117 | 新增: this.changed(); | |
| 118 | 新增: } | |
| 119 | 新增: | |
| 120 | 新增: cancelTab(tabId, removeRetained = true) { | |
| 121 | 新增: for (const request of this.requests.values()) | |
| 122 | 新增: if (request.tabId === tabId) this.cancel(request.id); | |
| 123 | 新增: if (removeRetained) { | |
| 124 | 新增: for (const id of this.retained.get(tabId) || []) | |
| 125 | 新增: void rm(join(this.directory, id), { | |
| 126 | 新增: recursive: true, | |
| 127 | 新增: force: true, | |
| 128 | 新增: }).catch(() => {}); | |
| 129 | 新增: this.retained.delete(tabId); | |
| 130 | 新增: } | |
| 131 | 新增: } | |
| 132 | 新增:} | |
| @@ -0,0 +1,83 @@ | ||
| 1 | 新增:import { test } from "node:test"; | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增:import { mkdtemp, readFile, rm, stat } from "node:fs/promises"; | |
| 4 | 新增:import { tmpdir } from "node:os"; | |
| 5 | 新增:import { join } from "node:path"; | |
| 6 | 新增:import { Readable } from "node:stream"; | |
| 7 | 新增:import { UploadManager } from "./browser-uploads.mjs"; | |
| 8 | 新增: | |
| 9 | 新增:async function fixture(t, multiple = true) { | |
| 10 | 新增: const directory = await mkdtemp(join(tmpdir(), "cage-uploads-")); | |
| 11 | 新增: t.after(() => rm(directory, { recursive: true, force: true })); | |
| 12 | 新增: const calls = []; | |
| 13 | 新增: const manager = new UploadManager({ | |
| 14 | 新增: directory, | |
| 15 | 新增: cdp: async (...args) => calls.push(args), | |
| 16 | 新增: }); | |
| 17 | 新增: await manager.opened("tab-1", "session-1", { | |
| 18 | 新增: backendNodeId: 42, | |
| 19 | 新增: mode: multiple ? "selectMultiple" : "selectSingle", | |
| 20 | 新增: }); | |
| 21 | 新增: return { manager, directory, calls, id: manager.snapshot()[0].id }; | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:test("binary files retain their names and bytes, and only the original input receives them", async (t) => { | |
| 25 | 新增: const f = await fixture(t); | |
| 26 | 新增: const bytes = Buffer.from([0, 255, 27, 99, 0]); | |
| 27 | 新增: await f.manager.receive( | |
| 28 | 新增: f.id, | |
| 29 | 新增: "参考视频.mp4", | |
| 30 | 新增: Readable.from([bytes.subarray(0, 2), bytes.subarray(2)]), | |
| 31 | 新增: ); | |
| 32 | 新增: await f.manager.receive(f.id, "empty.txt", Readable.from([])); | |
| 33 | 新增: await f.manager.finish(f.id); | |
| 34 | 新增: assert.equal(f.calls[0][0], "DOM.setFileInputFiles"); | |
| 35 | 新增: assert.equal(f.calls[0][1].backendNodeId, 42); | |
| 36 | 新增: assert.equal(f.calls[0][2], "session-1"); | |
| 37 | 新增: const [file, empty] = f.calls[0][1].files; | |
| 38 | 新增: assert.deepEqual(await readFile(file), bytes); | |
| 39 | 新增: assert.equal((await stat(file)).mode & 0o777, 0o600); | |
| 40 | 新增: assert.equal((await readFile(empty)).length, 0); | |
| 41 | 新增: assert.deepEqual(f.manager.snapshot(), []); | |
| 42 | 新增: assert.equal(f.manager.retained.get("tab-1").length, 1); | |
| 43 | 新增:}); | |
| 44 | 新增: | |
| 45 | 新增:test("cancel during a stream refuses the rest and never assigns partial files", async (t) => { | |
| 46 | 新增: const f = await fixture(t); | |
| 47 | 新增: async function* chunks() { | |
| 48 | 新增: yield Buffer.from("partial"); | |
| 49 | 新增: f.manager.cancel(f.id); | |
| 50 | 新增: yield Buffer.from("discarded"); | |
| 51 | 新增: } | |
| 52 | 新增: await assert.rejects(f.manager.receive(f.id, "video.mp4", chunks()), /取消/); | |
| 53 | 新增: await assert.rejects(f.manager.finish(f.id), /关闭/); | |
| 54 | 新增: assert.deepEqual(f.calls, []); | |
| 55 | 新增:}); | |
| 56 | 新增: | |
| 57 | 新增:test("a stale chooser and traversal names cannot select arbitrary files", async (t) => { | |
| 58 | 新增: const f = await fixture(t, false); | |
| 59 | 新增: for (const name of ["../secret", "a/b", "a\\b", "..", "a\u0000b"]) { | |
| 60 | 新增: await assert.rejects( | |
| 61 | 新增: f.manager.receive(f.id, name, Readable.from([Buffer.from("data")])), | |
| 62 | 新增: /文件名/, | |
| 63 | 新增: ); | |
| 64 | 新增: } | |
| 65 | 新增: await f.manager.receive(f.id, "one.txt", Readable.from([Buffer.from("one")])); | |
| 66 | 新增: await assert.rejects( | |
| 67 | 新增: f.manager.receive(f.id, "two.txt", Readable.from([])), | |
| 68 | 新增: /数量/, | |
| 69 | 新增: ); | |
| 70 | 新增: f.manager.cancelTab("tab-1"); | |
| 71 | 新增: await assert.rejects(f.manager.finish(f.id), /关闭/); | |
| 72 | 新增: assert.deepEqual(f.calls, []); | |
| 73 | 新增:}); | |
| 74 | 新增: | |
| 75 | 新增:test("a removed DOM input produces a recoverable cancellation", async (t) => { | |
| 76 | 新增: const f = await fixture(t); | |
| 77 | 新增: await f.manager.receive(f.id, "one.txt", Readable.from([Buffer.from("one")])); | |
| 78 | 新增: f.manager.cdp = async () => { | |
| 79 | 新增: throw new Error("Node no longer exists"); | |
| 80 | 新增: }; | |
| 81 | 新增: await assert.rejects(f.manager.finish(f.id), /Node/); | |
| 82 | 新增: assert.deepEqual(f.manager.snapshot(), []); | |
| 83 | 新增:}); | |
| @@ -0,0 +1,30 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:mkdir -p "$HOME/.config/claude-cage" | |
| 4 | 新增:exec 9>"$HOME/.config/claude-cage/desktop-install.lock" | |
| 5 | 新增:flock -n 9 || { echo 'Claude Desktop installation is already running.' >&2; exit 1; } | |
| 6 | 新增:if systemctl is-active --quiet cage-claude-desktop.service; then | |
| 7 | 新增: echo '请先保存工作并关闭 Claude Desktop,再更新或修复安装。' >&2 | |
| 8 | 新增: exit 1 | |
| 9 | 新增:fi | |
| 10 | 新增:case "$(dpkg --print-architecture)" in arm64|amd64) ;; *) echo 'Unsupported desktop architecture.' >&2; exit 1;; esac | |
| 11 | 新增:printf '正在准备安装依赖…\n' | |
| 12 | 新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 update </dev/null | |
| 13 | 新增:# Satisfy the vendor's kde-cli-tools | ... | libglib2.0-bin dependency before | |
| 14 | 新增:# resolving Claude, so apt does not pull in a KDE/Qt desktop toolchain. | |
| 15 | 新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 install -y --no-install-recommends ca-certificates curl gnupg dbus-x11 xauth x11-utils x11-xserver-utils tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox gnome-keyring gcr bubblewrap socat openssh-client libglib2.0-bin </dev/null | |
| 16 | 新增:temporary=$(mktemp -d) | |
| 17 | 新增:trap 'rm -rf "$temporary"' EXIT | |
| 18 | 新增:printf '正在验证 Anthropic 安装源…\n' | |
| 19 | 新增:curl --proto '=https' --proto-redir '=https' -fSL --connect-timeout 15 --max-time 90 https://downloads.claude.ai/claude-desktop/key.asc -o "$temporary/key.asc" | |
| 20 | 新增:fingerprint=$(gpg --batch --show-keys --with-colons "$temporary/key.asc" | awk -F: '$1 == "fpr" {print $10; exit}') | |
| 21 | 新增:test "$fingerprint" = 31DDDE24DDFAB679F42D7BD2BAA929FF1A7ECACE || { echo 'Anthropic signing key did not match; installation stopped.' >&2; exit 1; } | |
| 22 | 新增:sudo install -m 0644 "$temporary/key.asc" /usr/share/keyrings/claude-desktop-archive-keyring.asc | |
| 23 | 新增:printf '%s\n' 'deb [arch=amd64,arm64 signed-by=/usr/share/keyrings/claude-desktop-archive-keyring.asc] https://downloads.claude.ai/claude-desktop/apt/stable stable main' | sudo tee /etc/apt/sources.list.d/claude-desktop.list >/dev/null | |
| 24 | 新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 update </dev/null | |
| 25 | 新增:printf '正在下载并安装 Claude Desktop…\n' | |
| 26 | 新增:# Cowork's nested VM packages are intentionally optional; Chat and Code share | |
| 27 | 新增:# the official, unmodified desktop binary. Apt verifies repository signatures. | |
| 28 | 新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 install -y --no-install-recommends claude-desktop </dev/null | |
| 29 | 新增:test "$(dpkg-query -W -f='${Status}' claude-desktop)" = 'install ok installed' | |
| 30 | 新增:printf 'Claude Desktop 已安装。\n' | |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:test "$#" -eq 1 | |
| 4 | 新增:test "${#1}" -le 8192 | |
| 5 | 新增:case "$1" in claude://*) ;; *) exit 2;; esac | |
| 6 | 新增:systemctl is-active --quiet cage-claude-desktop.service || exit 1 | |
| 7 | 新增:export DISPLAY=:78 XAUTHORITY=/run/cage-desktop/Xauthority XDG_RUNTIME_DIR=/run/cage-desktop | |
| 8 | 新增:export DBUS_SESSION_BUS_ADDRESS="$(cat /run/cage-desktop/bus-address)" | |
| 9 | 新增:exec /usr/bin/claude-desktop "$1" | |
| @@ -0,0 +1,61 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:# Keep dbus-daemon and other children from announcing readiness for the app. | |
| 4 | 新增:if [ "${CAGE_DESKTOP_SESSION:-}" != 1 ]; then | |
| 5 | 新增: export CAGE_DESKTOP_SESSION=1 CAGE_NOTIFY_SOCKET="$NOTIFY_SOCKET" | |
| 6 | 新增: unset NOTIFY_SOCKET | |
| 7 | 新增: exec dbus-run-session -- "$0" | |
| 8 | 新增:fi | |
| 9 | 新增:export DISPLAY=:78 XAUTHORITY=/run/cage-desktop/Xauthority | |
| 10 | 新增:export XDG_RUNTIME_DIR=/run/cage-desktop XDG_CURRENT_DESKTOP=Openbox | |
| 11 | 新增:export PATH="$HOME/.local/bin:$PATH" BROWSER=/usr/local/bin/cage-open | |
| 12 | 新增:dbus-update-activation-environment DISPLAY XAUTHORITY XDG_RUNTIME_DIR XDG_CURRENT_DESKTOP | |
| 13 | 新增:umask 077 | |
| 14 | 新增:touch "$XAUTHORITY" | |
| 15 | 新增:xauth -f "$XAUTHORITY" add "$DISPLAY" . "$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')" | |
| 16 | 新增:printf '%s' "$DBUS_SESSION_BUS_ADDRESS" > "$XDG_RUNTIME_DIR/bus-address" | |
| 17 | 新增:password="$HOME/.config/claude-cage/desktop-password" | |
| 18 | 新增:if [ ! -s "$password" ]; then | |
| 19 | 新增: mkdir -p "$(dirname "$password")" | |
| 20 | 新增: od -An -N4 -tx1 /dev/urandom | tr -d ' \n' > "$password" | |
| 21 | 新增:fi | |
| 22 | 新增:tigervncpasswd -f < "$password" > "$XDG_RUNTIME_DIR/vnc-password" | |
| 23 | 新增:Xtigervnc "$DISPLAY" -geometry 1600x1000 -depth 24 -rfbport -1 -rfbunixpath "$XDG_RUNTIME_DIR/display.sock" -rfbunixmode 0600 -nolisten tcp -auth "$XAUTHORITY" -SecurityTypes VncAuth -PasswordFile "$XDG_RUNTIME_DIR/vnc-password" & | |
| 24 | 新增:display_pid=$! | |
| 25 | 新增:trap 'kill "$display_pid" 2>/dev/null || true' EXIT | |
| 26 | 新增:for i in $(seq 1 100); do | |
| 27 | 新增: if xdpyinfo -display "$DISPLAY" >/dev/null 2>&1; then break; fi | |
| 28 | 新增: kill -0 "$display_pid" | |
| 29 | 新增: sleep .1 | |
| 30 | 新增:done | |
| 31 | 新增:xdpyinfo -display "$DISPLAY" >/dev/null | |
| 32 | 新增:openbox --config-file /etc/claude-cage/desktop-openbox.xml & | |
| 33 | 新增:X0tigervnc -display "$DISPLAY" -rfbport -1 -rfbunixpath "$XDG_RUNTIME_DIR/vnc.sock" -rfbunixmode 0600 -SecurityTypes VncAuth -PasswordFile "$XDG_RUNTIME_DIR/vnc-password" -AlwaysShared & | |
| 34 | 新增:mkfifo -m 0600 "$XDG_RUNTIME_DIR/unlock" | |
| 35 | 新增:gnome-keyring-daemon --unlock --components=secrets < "$XDG_RUNTIME_DIR/unlock" >/dev/null | |
| 36 | 新增:rm "$XDG_RUNTIME_DIR/unlock" | |
| 37 | 新增:# Do not replace or erase an existing keyring when the supplied key is wrong. | |
| 38 | 新增:keyring_unlocked() { | |
| 39 | 新增: gdbus call --session --dest org.freedesktop.secrets --object-path /org/freedesktop/secrets/aliases/login --method org.freedesktop.DBus.Properties.Get org.freedesktop.Secret.Collection Locked 2>/dev/null | grep -q false && | |
| 40 | 新增: gdbus call --session --dest org.freedesktop.secrets --object-path /org/freedesktop/secrets/aliases/default --method org.freedesktop.DBus.Properties.Get org.freedesktop.Secret.Collection Locked 2>/dev/null | grep -q false | |
| 41 | 新增:} | |
| 42 | 新增:for i in $(seq 1 50); do | |
| 43 | 新增: if keyring_unlocked; then break; fi | |
| 44 | 新增: sleep .1 | |
| 45 | 新增:done | |
| 46 | 新增:keyring_unlocked || { echo '无法解锁已有密钥环,登录数据未修改。' >&2; exit 1; } | |
| 47 | 新增:touch "$XDG_RUNTIME_DIR/keyring-ready" | |
| 48 | 新增:# RemoteView displays two framebuffer pixels per CSS pixel, as for Chromium. | |
| 49 | 新增:# Scale the application's layout too so controls retain their intended size. | |
| 50 | 新增:claude-desktop --force-device-scale-factor=2 & | |
| 51 | 新增:app_pid=$! | |
| 52 | 新增:# The service becomes ready only after the application has opened a window. | |
| 53 | 新增:for i in $(seq 1 200); do | |
| 54 | 新增: kill -0 "$app_pid" | |
| 55 | 新增: if xprop -root _NET_CLIENT_LIST 2>/dev/null | grep -q '0x[1-9a-f]'; then | |
| 56 | 新增: NOTIFY_SOCKET="$CAGE_NOTIFY_SOCKET" systemd-notify --ready | |
| 57 | 新增: break | |
| 58 | 新增: fi | |
| 59 | 新增: sleep .1 | |
| 60 | 新增:done | |
| 61 | 新增:wait "$app_pid" | |
| @@ -0,0 +1,29 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:if systemctl is-active --quiet cage-claude-desktop.service; then | |
| 4 | 新增: test -f /run/cage-desktop/keyring-ready || { echo '请先保存并关闭现有 Claude Desktop,再使用 Cage 账户重新打开。' >&2; exit 1; } | |
| 5 | 新增: exit 0 | |
| 6 | 新增:fi | |
| 7 | 新增:if systemctl is-failed --quiet cage-claude-desktop.service; then | |
| 8 | 新增: sudo systemctl reset-failed cage-claude-desktop.service | |
| 9 | 新增:fi | |
| 10 | 新增:sudo systemctl start --no-block cage-claude-desktop.service | |
| 11 | 新增:for i in $(seq 1 150); do | |
| 12 | 新增: if [ -p /run/cage-desktop/unlock ]; then break; fi | |
| 13 | 新增: if systemctl is-failed --quiet cage-claude-desktop.service; then | |
| 14 | 新增: echo '图形会话未能启动。' >&2; exit 1 | |
| 15 | 新增: fi | |
| 16 | 新增: sleep .1 | |
| 17 | 新增:done | |
| 18 | 新增:test -p /run/cage-desktop/unlock || { echo '等待凭据解锁通道超时。' >&2; exit 1; } | |
| 19 | 新增:# The internal random key comes exclusively from SSH stdin, never argv or disk. | |
| 20 | 新增:timeout 10 sh -c 'cat > /run/cage-desktop/unlock' | |
| 21 | 新增:for i in $(seq 1 300); do | |
| 22 | 新增: if systemctl is-active --quiet cage-claude-desktop.service; then exit 0; fi | |
| 23 | 新增: if systemctl is-failed --quiet cage-claude-desktop.service; then | |
| 24 | 新增: echo 'Claude Desktop 未能启动或密钥环未能解锁;已有登录数据保持不变。' >&2; exit 1 | |
| 25 | 新增: fi | |
| 26 | 新增: sleep .1 | |
| 27 | 新增:done | |
| 28 | 新增:echo 'Claude Desktop 启动超时。' >&2 | |
| 29 | 新增:exit 1 | |
| @@ -0,0 +1,66 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import _ "embed" | |
| 4 | 新增: | |
| 5 | 新增://go:embed claude-desktop-install.sh | |
| 6 | 新增:var claudeDesktopInstall string | |
| 7 | 新增: | |
| 8 | 新增://go:embed claude-desktop-session.sh | |
| 9 | 新增:var claudeDesktopSession string | |
| 10 | 新增: | |
| 11 | 新增://go:embed claude-desktop-open.sh | |
| 12 | 新增:var claudeDesktopOpen string | |
| 13 | 新增: | |
| 14 | 新增://go:embed claude-desktop-start.sh | |
| 15 | 新增:var claudeDesktopStart string | |
| 16 | 新增: | |
| 17 | 新增://go:embed guest-open.sh | |
| 18 | 新增:var guestOpen string | |
| 19 | 新增: | |
| 20 | 新增:func guestOpenScript() string { | |
| 21 | 新增: return "sudo tee /usr/local/bin/cage-open >/dev/null <<'CAGE_OPEN_URL'\n" + guestOpen + "\nCAGE_OPEN_URL\nsudo chmod 0755 /usr/local/bin/cage-open\nsudo ln -sf /usr/local/bin/cage-open /usr/local/bin/xdg-open\n" | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:func ClaudeDesktopInstallScript() string { | |
| 25 | 新增: return claudeDesktopInstall + "\n" + ClaudeDesktopProvisionScript() | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:// Provisioning is independent of the browser and never restarts it. Desktop | |
| 29 | 新增:// services are deliberately not enabled at boot: the user opens the app. | |
| 30 | 新增:func ClaudeDesktopProvisionScript() string { | |
| 31 | 新增: return "set -euo pipefail\n" + | |
| 32 | 新增: "sudo install -d -m 0755 /etc/claude-cage\n" + | |
| 33 | 新增: "sudo tee /usr/local/bin/cage-claude-session >/dev/null <<'CAGE_CLAUDE_SESSION'\n" + claudeDesktopSession + "\nCAGE_CLAUDE_SESSION\n" + | |
| 34 | 新增: "sudo tee /usr/local/bin/cage-claude-open >/dev/null <<'CAGE_CLAUDE_OPEN'\n" + claudeDesktopOpen + "\nCAGE_CLAUDE_OPEN\n" + | |
| 35 | 新增: "sudo tee /usr/local/bin/cage-claude-start >/dev/null <<'CAGE_CLAUDE_START'\n" + claudeDesktopStart + "\nCAGE_CLAUDE_START\n" + | |
| 36 | 新增: "sudo chmod 0755 /usr/local/bin/cage-claude-session /usr/local/bin/cage-claude-open /usr/local/bin/cage-claude-start\n" + guestOpenScript() + ` | |
| 37 | 新增:printf 'cage-browser ALL=(cage) NOPASSWD: /usr/local/bin/cage-claude-open *\n' | sudo tee /etc/sudoers.d/cage-claude-desktop >/dev/null | |
| 38 | 新增:sudo chmod 0440 /etc/sudoers.d/cage-claude-desktop | |
| 39 | 新增:sudo tee /etc/claude-cage/desktop-openbox.xml >/dev/null <<'CAGE_CLAUDE_WINDOWS' | |
| 40 | 新增:<?xml version="1.0" encoding="UTF-8"?> | |
| 41 | 新增:<openbox_config xmlns="http://openbox.org/3.4/rc"> | |
| 42 | 新增:<focus><focusNew>yes</focusNew><followMouse>no</followMouse></focus> | |
| 43 | 新增:<desktops><number>1</number></desktops> | |
| 44 | 新增:<applications><application type="normal"><decor>no</decor><maximized>yes</maximized></application></applications> | |
| 45 | 新增:</openbox_config> | |
| 46 | 新增:CAGE_CLAUDE_WINDOWS | |
| 47 | 新增:sudo tee /etc/systemd/system/cage-claude-desktop.service >/dev/null <<'CAGE_CLAUDE_UNIT' | |
| 48 | 新增:[Unit] | |
| 49 | 新增:Description=Claude Desktop in Cage | |
| 50 | 新增:[Service] | |
| 51 | 新增:Type=notify | |
| 52 | 新增:NotifyAccess=all | |
| 53 | 新增:User=cage | |
| 54 | 新增:WorkingDirectory=/home/cage | |
| 55 | 新增:Environment=HOME=/home/cage | |
| 56 | 新增:EnvironmentFile=/etc/claude-cage/environment | |
| 57 | 新增:RuntimeDirectory=cage-desktop | |
| 58 | 新增:RuntimeDirectoryMode=0700 | |
| 59 | 新增:ExecStart=/usr/local/bin/cage-claude-session | |
| 60 | 新增:KillMode=control-group | |
| 61 | 新增:TimeoutStartSec=45 | |
| 62 | 新增:TimeoutStopSec=20 | |
| 63 | 新增:CAGE_CLAUDE_UNIT | |
| 64 | 新增:sudo systemctl daemon-reload | |
| 65 | 新增:` | |
| 66 | 新增:} | |
| @@ -0,0 +1,49 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "os/exec" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestClaudeDesktopInstallerRejectsUntrustedKey(t *testing.T) { | |
| 12 | 新增: dir := t.TempDir() | |
| 13 | 新增: commands := map[string]string{ | |
| 14 | 新增: "sudo": "#!/bin/sh\nif [ \"$1\" = env ]; then exec \"$@\"; fi\necho blocked-privileged-operation >&2; exit 97\n", | |
| 15 | 新增: "apt-get": "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$HOME/apt-requests\"\n", | |
| 16 | 新增: "systemctl": "#!/bin/sh\nexit 3\n", | |
| 17 | 新增: "flock": "#!/bin/sh\nexit 0\n", | |
| 18 | 新增: "dpkg": "#!/bin/sh\necho arm64\n", | |
| 19 | 新增: "curl": "#!/bin/sh\nexit 0\n", | |
| 20 | 新增: "gpg": "#!/bin/sh\necho 'fpr:::::::::UNTRUSTEDKEY:'\n", | |
| 21 | 新增: } | |
| 22 | 新增: for name, body := range commands { | |
| 23 | 新增: if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0755); err != nil { | |
| 24 | 新增: t.Fatal(err) | |
| 25 | 新增: } | |
| 26 | 新增: } | |
| 27 | 新增: cmd := exec.Command("bash", "-c", claudeDesktopInstall) | |
| 28 | 新增: cmd.Env = append(os.Environ(), "HOME="+dir, "PATH="+dir+":"+os.Getenv("PATH")) | |
| 29 | 新增: out, err := cmd.CombinedOutput() | |
| 30 | 新增: if err == nil || !strings.Contains(string(out), "signing key did not match") { | |
| 31 | 新增: t.Fatalf("untrusted key was not rejected: %v %s", err, out) | |
| 32 | 新增: } | |
| 33 | 新增: requests, _ := os.ReadFile(filepath.Join(dir, "apt-requests")) | |
| 34 | 新增: if strings.Contains(string(requests), "claude-desktop") { | |
| 35 | 新增: t.Fatal("desktop package requested before source authentication") | |
| 36 | 新增: } | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:func TestClaudeDesktopScriptsParse(t *testing.T) { | |
| 40 | 新增: for name, script := range map[string]string{"install": ClaudeDesktopInstallScript(), "provision": ClaudeDesktopProvisionScript(), "session": claudeDesktopSession, "start": claudeDesktopStart, "open": claudeDesktopOpen, "browser-open": guestOpen} { | |
| 41 | 新增: t.Run(name, func(t *testing.T) { | |
| 42 | 新增: cmd := exec.Command("bash", "-n") | |
| 43 | 新增: cmd.Stdin = strings.NewReader(script) | |
| 44 | 新增: if out, err := cmd.CombinedOutput(); err != nil { | |
| 45 | 新增: t.Fatalf("%v: %s", err, out) | |
| 46 | 新增: } | |
| 47 | 新增: }) | |
| 48 | 新增: } | |
| 49 | 新增:} | |
| @@ -15,6 +15,8 @@ import ( | ||
| 15 | 15 | "path/filepath" |
| 16 | 16 | "sync" |
| 17 | 17 | "time" |
| 18 | 新增: | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 18 | 20 | ) |
| 19 | 21 | |
| 20 | 22 | const gateRecordName = "cage-gate.json" |
| @@ -36,17 +38,21 @@ type gateCommand struct { | ||
| 36 | 38 | // StartGateControl publishes an authenticated Unix endpoint in host-private |
| 37 | 39 | // storage. It creates no TCP listener or guest-visible control credential. |
| 38 | 40 | func StartGateControl(configPath, instanceDir string, gate *EgressGate) (func(), error) { |
| 39 | 删除: dir, err := os.MkdirTemp("/tmp", "cage-gate-") | |
| 41 | 新增: dir, err := os.MkdirTemp(gateTempDir(), "cage-gate-") | |
| 40 | 42 | if err != nil { |
| 41 | 43 | return nil, err |
| 42 | 44 | } |
| 45 | 新增: if err = host.EnsurePrivateDir(dir); err != nil { | |
| 46 | 新增: os.RemoveAll(dir) | |
| 47 | 新增: return nil, err | |
| 48 | 新增: } | |
| 43 | 49 | socket := filepath.Join(dir, "control.sock") |
| 44 | 50 | listener, err := net.Listen("unix", socket) |
| 45 | 51 | if err != nil { |
| 46 | 52 | os.RemoveAll(dir) |
| 47 | 53 | return nil, err |
| 48 | 54 | } |
| 49 | 删除: if err = os.Chmod(socket, 0600); err != nil { | |
| 55 | 新增: if err = host.ProtectFile(socket); err != nil { | |
| 50 | 56 | listener.Close() |
| 51 | 57 | os.RemoveAll(dir) |
| 52 | 58 | return nil, err |
| @@ -66,6 +72,12 @@ func StartGateControl(configPath, instanceDir string, gate *EgressGate) (func(), | ||
| 66 | 72 | return nil, err |
| 67 | 73 | } |
| 68 | 74 | defer os.Remove(temporary.Name()) |
| 75 | 新增: if err = host.ProtectFile(temporary.Name()); err != nil { | |
| 76 | 新增: temporary.Close() | |
| 77 | 新增: listener.Close() | |
| 78 | 新增: os.RemoveAll(dir) | |
| 79 | 新增: return nil, err | |
| 80 | 新增: } | |
| 69 | 81 | _, err = temporary.Write(data) |
| 70 | 82 | if closeErr := temporary.Close(); err == nil { |
| 71 | 83 | err = closeErr |
| @@ -178,8 +190,7 @@ type GateClient struct{ record gateRecord } | ||
| 178 | 190 | |
| 179 | 191 | func OpenGateClient(instanceDir string) (*GateClient, error) { |
| 180 | 192 | path := filepath.Join(instanceDir, gateRecordName) |
| 181 | 删除: info, err := os.Lstat(path) | |
| 182 | 删除: if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 { | |
| 193 | 新增: if err := host.CheckPrivateFile(path); err != nil { | |
| 183 | 194 | return nil, errors.New("网络门槛控制记录不可用,请停止并重启环境") |
| 184 | 195 | } |
| 185 | 196 | data, err := os.ReadFile(path) |
| @@ -0,0 +1,6 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package cage | |
| 4 | 新增: | |
| 5 | 新增:// macOS's user temp directory often exceeds AF_UNIX's path limit. | |
| 6 | 新增:func gateTempDir() string { return "/tmp" } | |
| @@ -0,0 +1,4 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:// Windows AF_UNIX sockets use the user's temp directory, never a drive root. | |
| 4 | 新增:func gateTempDir() string { return "" } | |
| @@ -0,0 +1,46 @@ | ||
| 1 | 新增:# A virtual output shared by Cage applications. No hardware or microphone | |
| 2 | 新增:# modules are loaded, and the PulseAudio protocol is Unix-socket only. | |
| 3 | 新增:if ! command -v pulseaudio >/dev/null || ! command -v parec >/dev/null; then | |
| 4 | 新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 update </dev/null | |
| 5 | 新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 install -y --no-install-recommends pulseaudio pulseaudio-utils </dev/null | |
| 6 | 新增:fi | |
| 7 | 新增:getent group cage-audio >/dev/null || sudo groupadd --system cage-audio | |
| 8 | 新增:sudo usermod -a -G cage-audio cage | |
| 9 | 新增:sudo usermod -a -G cage-audio cage-browser | |
| 10 | 新增:sudo install -d -m 0755 /etc/claude-cage /etc/pulse/client.conf.d | |
| 11 | 新增:sudo tee /etc/pulse/client.conf.d/99-cage.conf >/dev/null <<'CLIENT' | |
| 12 | 新增:default-server = unix:/run/cage-audio/native | |
| 13 | 新增:autospawn = no | |
| 14 | 新增:CLIENT | |
| 15 | 新增:sudo tee /etc/claude-cage/audio.pa >/dev/null <<'PULSE' | |
| 16 | 新增:load-module module-null-sink sink_name=cage_output rate=48000 channels=2 format=s16le sink_properties=device.description=Cage | |
| 17 | 新增:load-module module-native-protocol-unix socket=/run/cage-audio/native auth-anonymous=0 auth-cookie-enabled=0 auth-group-enable=1 auth-group=cage-audio | |
| 18 | 新增:set-default-sink cage_output | |
| 19 | 新增:set-default-source cage_output.monitor | |
| 20 | 新增:PULSE | |
| 21 | 新增:sudo tee /etc/systemd/system/cage-audio.service >/dev/null <<'UNIT' | |
| 22 | 新增:[Unit] | |
| 23 | 新增:Description=Cage virtual audio output | |
| 24 | 新增:[Service] | |
| 25 | 新增:User=cage | |
| 26 | 新增:Group=cage-audio | |
| 27 | 新增:Environment=HOME=/home/cage | |
| 28 | 新增:Environment=PULSE_RUNTIME_PATH=/run/cage-audio/runtime | |
| 29 | 新增:Environment=PULSE_STATE_PATH=/run/cage-audio/state | |
| 30 | 新增:RuntimeDirectory=cage-audio | |
| 31 | 新增:RuntimeDirectoryMode=0750 | |
| 32 | 新增:ExecStart=/usr/bin/pulseaudio -n --daemonize=no --exit-idle-time=-1 --disallow-exit --disallow-module-loading --disable-shm=true --realtime=no --high-priority=no --use-pid-file=no --file=/etc/claude-cage/audio.pa | |
| 33 | 新增:Restart=on-failure | |
| 34 | 新增:RestartSec=1 | |
| 35 | 新增:TimeoutStopSec=5 | |
| 36 | 新增:NoNewPrivileges=true | |
| 37 | 新增:UNIT | |
| 38 | 新增:sudo chmod 0644 /etc/claude-cage/audio.pa /etc/pulse/client.conf.d/99-cage.conf /etc/systemd/system/cage-audio.service | |
| 39 | 新增:sudo systemctl daemon-reload | |
| 40 | 新增:sudo systemctl reset-failed cage-audio 2>/dev/null || true | |
| 41 | 新增:sudo systemctl restart cage-audio | |
| 42 | 新增:for i in $(seq 1 50); do | |
| 43 | 新增: if pactl --server=unix:/run/cage-audio/native info >/dev/null 2>&1; then break; fi | |
| 44 | 新增: sleep .1 | |
| 45 | 新增:done | |
| 46 | 新增:pactl --server=unix:/run/cage-audio/native info >/dev/null | |
| @@ -6,9 +6,14 @@ if ! locale -a | tr '[:upper:]' '[:lower:]' | grep -qx "${CAGE_LOCALE,,}" && ! l | ||
| 6 | 6 | printf '%s UTF-8\n' "$CAGE_LOCALE" | sudo tee -a /etc/locale.gen >/dev/null |
| 7 | 7 | sudo locale-gen >/dev/null |
| 8 | 8 | fi |
| 9 | 删除:printf 'TZ=%s\nLANG=%s\nLC_ALL=%s\nCAGE_LANGUAGE=%s\nBROWSER=/usr/local/bin/cage-open\n' "$CAGE_TZ" "$CAGE_LOCALE" "$CAGE_LOCALE" "$CAGE_LANGUAGE" | sudo tee /etc/claude-cage/environment >/dev/null | |
| 9 | 新增:printf 'TZ=%s\nLANG=%s\nLC_ALL=%s\nCAGE_LANGUAGE=%s\nBROWSER=/usr/local/bin/cage-open\nPULSE_SERVER=unix:/run/cage-audio/native\n' "$CAGE_TZ" "$CAGE_LOCALE" "$CAGE_LOCALE" "$CAGE_LANGUAGE" | sudo tee /etc/claude-cage/environment >/dev/null | |
| 10 | 10 | sudo update-locale "LANG=$CAGE_LOCALE" "LC_ALL=$CAGE_LOCALE" |
| 11 | 11 | set -a |
| 12 | 12 | . /etc/claude-cage/environment |
| 13 | 13 | set +a |
| 14 | 14 | unset HTTP_PROXY HTTPS_PROXY ALL_PROXY FTP_PROXY NO_PROXY http_proxy https_proxy all_proxy ftp_proxy no_proxy |
| 15 | 新增: | |
| 16 | 新增:# Only the scoped installer receives this variable; services load their fixed environment. | |
| 17 | 新增:if [ -n "${CAGE_INSTALL_PROXY:-}" ]; then | |
| 18 | 新增: export http_proxy="$CAGE_INSTALL_PROXY" https_proxy="$CAGE_INSTALL_PROXY" HTTP_PROXY="$CAGE_INSTALL_PROXY" HTTPS_PROXY="$CAGE_INSTALL_PROXY" | |
| 19 | 新增:fi | |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增:#!/bin/sh | |
| 2 | 新增:set -eu | |
| 3 | 新增:case "${1:-}" in | |
| 4 | 新增: claude://*) exec sudo -u cage /usr/local/bin/cage-claude-open "$1" ;; | |
| 5 | 新增: http://*|https://*|about:blank) ;; | |
| 6 | 新增: *) echo 'Only HTTP(S) browser URLs and Claude desktop callbacks are accepted.' >&2; exit 2;; | |
| 7 | 新增:esac | |
| 8 | 新增:exec sudo -u cage-browser /usr/bin/node --input-type=module - "$1" <<'NODE' | |
| 9 | 新增:import {readFileSync} from 'node:fs'; | |
| 10 | 新增:const {token}=JSON.parse(readFileSync('/etc/claude-cage/browser-control.json','utf8')); | |
| 11 | 新增:const response=await fetch('http://127.0.0.1:18500/new',{method:'POST',headers:{Authorization:'Bearer '+token,'Content-Type':'application/json'},body:JSON.stringify({url:process.argv[2]})}); | |
| 12 | 新增:if(!response.ok)process.exit(1); | |
| 13 | 新增:NODE | |
| @@ -3,23 +3,10 @@ | ||
| 3 | 3 | if systemctl is-active --quiet cage-webvnc; then |
| 4 | 4 | sudo systemctl stop cage-webvnc |
| 5 | 5 | fi |
| 6 | 删除:if ! command -v X0tigervnc >/dev/null || ! command -v Xtigervnc >/dev/null || ! command -v openbox >/dev/null || ! command -v xrandr >/dev/null; then | |
| 7 | 删除: sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox x11-xserver-utils | |
| 6 | 新增:if ! command -v X0tigervnc >/dev/null || ! command -v Xtigervnc >/dev/null || ! command -v openbox >/dev/null || ! command -v xrandr >/dev/null || ! command -v xdotool >/dev/null; then | |
| 7 | 新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox x11-xserver-utils xdotool libgtk-3-0 | |
| 8 | 8 | fi |
| 9 | 9 | sudo install -d -m 0755 /etc/claude-cage /usr/local/lib |
| 10 | 删除:sudo tee /usr/local/bin/cage-open >/dev/null <<'SCRIPT' | |
| 11 | 删除:#!/bin/sh | |
| 12 | 删除:set -eu | |
| 13 | 删除:case "${1:-}" in http://*|https://*|about:blank) ;; *) echo 'Only HTTP(S) browser URLs are accepted.' >&2; exit 2;; esac | |
| 14 | 删除:exec sudo -u cage-browser /usr/bin/node --input-type=module - "$1" <<'NODE' | |
| 15 | 删除:import {readFileSync} from 'node:fs'; | |
| 16 | 删除:const {token}=JSON.parse(readFileSync('/etc/claude-cage/browser-control.json','utf8')); | |
| 17 | 删除:const response=await fetch('http://127.0.0.1:18500/new',{method:'POST',headers:{Authorization:'Bearer '+token,'Content-Type':'application/json'},body:JSON.stringify({url:process.argv[2]})}); | |
| 18 | 删除:if(!response.ok)process.exit(1); | |
| 19 | 删除:NODE | |
| 20 | 删除:SCRIPT | |
| 21 | 删除:sudo chmod 0755 /usr/local/bin/cage-open | |
| 22 | 删除:sudo ln -sf /usr/local/bin/cage-open /usr/local/bin/xdg-open | |
| 23 | 10 | sudo tee /usr/local/bin/cage-editor-start >/dev/null <<'SCRIPT' |
| 24 | 11 | #!/bin/sh |
| 25 | 12 | set -eu |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | #!/usr/bin/env bash |
| 2 | 2 | set -euo pipefail |
| 3 | 删除:sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends locales tzdata tigervnc-standalone-server openbox x11-xserver-utils tigervnc-scraping-server tigervnc-tools novnc websockify fonts-noto-cjk fonts-noto-color-emoji | |
| 3 | 新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends locales tzdata tigervnc-standalone-server openbox x11-xserver-utils tigervnc-scraping-server tigervnc-tools novnc websockify fonts-noto-cjk fonts-noto-color-emoji | |
| 4 | 4 | if ! id cage-browser >/dev/null 2>&1; then |
| 5 | 5 | sudo useradd --create-home --shell /bin/bash cage-browser |
| 6 | 6 | fi |
| @@ -39,7 +39,7 @@ cage_install_tool() ( | ||
| 39 | 39 | curl --proto '=https' --tlsv1.2 --fail --location --retry 3 --connect-timeout 15 --max-time 600 "$url" -o "$stage/$artifact" |
| 40 | 40 | printf '%s %s\n' "$checksum" "$stage/$artifact" | sha256sum --check --status || { echo 'Tool checksum mismatch; installation refused.' >&2; exit 1; } |
| 41 | 41 | if [ "$tool" = code-server ]; then |
| 42 | 删除: sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$stage/$artifact" </dev/null | |
| 42 | 新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends "$stage/$artifact" </dev/null | |
| 43 | 43 | else |
| 44 | 44 | tar -xzf "$stage/$artifact" -C "$stage" |
| 45 | 45 | mkdir -p "$HOME/.local/bin" |
| @@ -18,6 +18,9 @@ var guestDependencies string | ||
| 18 | 18 | //go:embed guest-services.sh |
| 19 | 19 | var guestServices string |
| 20 | 20 | |
| 21 | 新增://go:embed guest-audio.sh | |
| 22 | 新增:var guestAudio string | |
| 23 | 新增: | |
| 21 | 24 | //go:embed novnc-patch.py |
| 22 | 25 | var novncPatch string |
| 23 | 26 | |
| @@ -33,14 +36,24 @@ var browserAudit string | ||
| 33 | 36 | //go:embed browser-downloads.mjs |
| 34 | 37 | var browserDownloads string |
| 35 | 38 | |
| 39 | 新增://go:embed browser-uploads.mjs | |
| 40 | 新增:var browserUploads string | |
| 41 | 新增: | |
| 36 | 42 | //go:embed editor-migrate.py |
| 37 | 43 | var editorMigrate string |
| 38 | 44 | |
| 39 | 45 | //go:embed save-download.py |
| 40 | 46 | var saveDownload string |
| 41 | 47 | |
| 48 | 新增://go:embed image-input.py | |
| 49 | 新增:var imageInput string | |
| 50 | 新增: | |
| 51 | 新增:func imageInputScript() string { | |
| 52 | 新增: return "\nsudo tee /usr/local/bin/cage-image-input >/dev/null <<'CAGE_IMAGE_INPUT'\n" + imageInput + "\nCAGE_IMAGE_INPUT\nsudo chmod 0755 /usr/local/bin/cage-image-input\n" | |
| 53 | 新增:} | |
| 54 | 新增: | |
| 42 | 55 | func browserServices() string { |
| 43 | 删除: return guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee /usr/share/novnc/cage-clipboard.js >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE' | |
| 56 | 新增: return guestAudio + "\n" + guestOpenScript() + imageInputScript() + "\nsudo tee /usr/local/lib/browser-uploads.mjs >/dev/null <<'CAGE_BROWSER_UPLOADS'\n" + browserUploads + "\nCAGE_BROWSER_UPLOADS\n" + guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee /usr/share/novnc/cage-clipboard.js >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE' | |
| 44 | 57 | from pathlib import Path |
| 45 | 58 | import re |
| 46 | 59 | p = Path("/usr/share/novnc/vnc.html") |
| @@ -97,8 +110,8 @@ func RequiredToolVersions() map[string]string { | ||
| 97 | 110 | func ToolsUpdateScript() string { |
| 98 | 111 | return "set -euo pipefail\nexport PATH=\"$HOME/.local/bin:$PATH\"\n" + ToolInstallPrelude() + ` |
| 99 | 112 | sudo env DEBIAN_FRONTEND=noninteractive dpkg --configure -a </dev/null |
| 100 | 删除:sudo env DEBIAN_FRONTEND=noninteractive apt-get update </dev/null | |
| 101 | 删除:sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --only-upgrade chromium </dev/null | |
| 113 | 新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get update </dev/null | |
| 114 | 新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --only-upgrade chromium </dev/null | |
| 102 | 115 | cage_install_tool mise |
| 103 | 116 | cage_install_tool code-server |
| 104 | 117 | cage_install_tool claude |
| @@ -0,0 +1,129 @@ | ||
| 1 | 新增:#!/usr/bin/python3 | |
| 2 | 新增:"""Receive a validated PNG on stdin; never read host paths or use the network.""" | |
| 3 | 新增:import ctypes as C | |
| 4 | 新增:import fcntl | |
| 5 | 新增:import json | |
| 6 | 新增:import os | |
| 7 | 新增:from pathlib import Path | |
| 8 | 新增:import select | |
| 9 | 新增:import signal | |
| 10 | 新增:import subprocess | |
| 11 | 新增:import sys | |
| 12 | 新增:import tempfile | |
| 13 | 新增: | |
| 14 | 新增: | |
| 15 | 新增:def save_image(data): | |
| 16 | 新增: directory = Path.home() / '.local/share/cage/attachments' | |
| 17 | 新增: directory.mkdir(parents=True, exist_ok=True, mode=0o700) | |
| 18 | 新增: fd, path = tempfile.mkstemp(prefix='image-', suffix='.png', dir=directory) | |
| 19 | 新增: try: | |
| 20 | 新增: with os.fdopen(fd, 'wb') as stream: | |
| 21 | 新增: stream.write(data) | |
| 22 | 新增: except BaseException: | |
| 23 | 新增: os.unlink(path) | |
| 24 | 新增: raise | |
| 25 | 新增: return {'path': path} | |
| 26 | 新增: | |
| 27 | 新增: | |
| 28 | 新增:def clipboard_owner(data, ack): | |
| 29 | 新增: # GTK handles X11 TARGETS and incremental transfers, including large PNGs. | |
| 30 | 新增: # Keep the owner alive after the caller returns until replaced or expired. | |
| 31 | 新增: gtk = C.CDLL('libgtk-3.so.0') | |
| 32 | 新增: gdk = C.CDLL('libgdk-3.so.0') | |
| 33 | 新增: glib = C.CDLL('libglib-2.0.so.0') | |
| 34 | 新增: pointer = C.c_void_p | |
| 35 | 新增: def bind(lib, name, result, *args): | |
| 36 | 新增: fn = getattr(lib, name) | |
| 37 | 新增: fn.restype, fn.argtypes = result, list(args) | |
| 38 | 新增: return fn | |
| 39 | 新增: init = bind(gtk, 'gtk_init_check', C.c_int, pointer, pointer) | |
| 40 | 新增: atom = bind(gdk, 'gdk_atom_intern_static_string', pointer, C.c_char_p) | |
| 41 | 新增: get = bind(gtk, 'gtk_clipboard_get', pointer, pointer) | |
| 42 | 新增: set_data = bind(gtk, 'gtk_selection_data_set', None, pointer, pointer, C.c_int, pointer, C.c_int) | |
| 43 | 新增: flush = bind(gdk, 'gdk_flush', None) | |
| 44 | 新增: main = bind(gtk, 'gtk_main', None) | |
| 45 | 新增: quit_main = bind(gtk, 'gtk_main_quit', None) | |
| 46 | 新增: callback = C.CFUNCTYPE(C.c_int, pointer) | |
| 47 | 新增: timeout = bind(glib, 'g_timeout_add', C.c_uint, C.c_uint, callback, pointer) | |
| 48 | 新增: class Target(C.Structure): | |
| 49 | 新增: _fields_ = [('target', C.c_char_p), ('flags', C.c_uint), ('info', C.c_uint)] | |
| 50 | 新增: provide_type = C.CFUNCTYPE(None, pointer, pointer, C.c_uint, pointer) | |
| 51 | 新增: clear_type = C.CFUNCTYPE(None, pointer, pointer) | |
| 52 | 新增: own = bind(gtk, 'gtk_clipboard_set_with_data', C.c_int, pointer, C.POINTER(Target), C.c_uint, provide_type, clear_type, pointer) | |
| 53 | 新增: if not init(None, None): | |
| 54 | 新增: raise RuntimeError('display unavailable') | |
| 55 | 新增: png = atom(b'image/png') | |
| 56 | 新增: buffer = C.create_string_buffer(data) | |
| 57 | 新增: acknowledged = False | |
| 58 | 新增: @callback | |
| 59 | 新增: def stop(_): | |
| 60 | 新增: quit_main() | |
| 61 | 新增: return 0 | |
| 62 | 新增: @provide_type | |
| 63 | 新增: def provide(_clipboard, selection, _info, _user): | |
| 64 | 新增: nonlocal acknowledged | |
| 65 | 新增: set_data(selection, png, 8, buffer, len(data)) | |
| 66 | 新增: flush() | |
| 67 | 新增: if not acknowledged: | |
| 68 | 新增: os.write(ack, b'ok') | |
| 69 | 新增: os.close(ack) | |
| 70 | 新增: acknowledged = True | |
| 71 | 新增: @clear_type | |
| 72 | 新增: def clear(_clipboard, _user): | |
| 73 | 新增: # An INCR transfer can outlive selection ownership. | |
| 74 | 新增: timeout(10000, stop, None) | |
| 75 | 新增: targets = (Target * 1)(Target(b'image/png', 0, 0)) | |
| 76 | 新增: if not own(get(atom(b'CLIPBOARD')), targets, 1, provide, clear, None): | |
| 77 | 新增: raise RuntimeError('clipboard unavailable') | |
| 78 | 新增: flush() | |
| 79 | 新增: subprocess.run(['xdotool', 'key', '--clearmodifiers', 'ctrl+v'], check=True, | |
| 80 | 新增: stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=3) | |
| 81 | 新增: timeout(120000, stop, None) | |
| 82 | 新增: main() | |
| 83 | 新增: | |
| 84 | 新增: | |
| 85 | 新增:def paste_image(data): | |
| 86 | 新增: lock_dir = Path.home() / '.cache/cage' | |
| 87 | 新增: lock_dir.mkdir(parents=True, exist_ok=True, mode=0o700) | |
| 88 | 新增: with open(lock_dir / 'image-input.lock', 'a') as lock: | |
| 89 | 新增: fcntl.flock(lock, fcntl.LOCK_EX) | |
| 90 | 新增: read_fd, write_fd = os.pipe() | |
| 91 | 新增: pid = os.fork() | |
| 92 | 新增: if pid == 0: | |
| 93 | 新增: os.close(read_fd) | |
| 94 | 新增: lock.close() | |
| 95 | 新增: os.setsid() | |
| 96 | 新增: with open(os.devnull, 'r+b') as null: | |
| 97 | 新增: for fd in (0, 1, 2): | |
| 98 | 新增: os.dup2(null.fileno(), fd) | |
| 99 | 新增: try: | |
| 100 | 新增: clipboard_owner(data, write_fd) | |
| 101 | 新增: finally: | |
| 102 | 新增: os._exit(0) | |
| 103 | 新增: os.close(write_fd) | |
| 104 | 新增: try: | |
| 105 | 新增: ready, _, _ = select.select([read_fd], [], [], 10) | |
| 106 | 新增: if not ready or os.read(read_fd, 2) != b'ok': | |
| 107 | 新增: os.kill(pid, signal.SIGTERM) | |
| 108 | 新增: os.waitpid(pid, 0) | |
| 109 | 新增: raise RuntimeError('目标没有接收图片,请点击支持图片的输入框后重试;若环境组件过旧,请先更新环境') | |
| 110 | 新增: finally: | |
| 111 | 新增: os.close(read_fd) | |
| 112 | 新增: return {'ok': True} | |
| 113 | 新增: | |
| 114 | 新增: | |
| 115 | 新增:if __name__ == '__main__': | |
| 116 | 新增: try: | |
| 117 | 新增: data = sys.stdin.buffer.read(20 * 1024 * 1024 + 1) | |
| 118 | 新增: if not data.startswith(b'\x89PNG\r\n\x1a\n') or len(data) > 20 * 1024 * 1024: | |
| 119 | 新增: raise ValueError('PNG input invalid') | |
| 120 | 新增: if sys.argv[1:] == ['save']: | |
| 121 | 新增: result = save_image(data) | |
| 122 | 新增: elif sys.argv[1:] == ['paste']: | |
| 123 | 新增: result = paste_image(data) | |
| 124 | 新增: else: | |
| 125 | 新增: raise ValueError('unknown action') | |
| 126 | 新增: print(json.dumps(result)) | |
| 127 | 新增: except Exception as error: | |
| 128 | 新增: print(str(error), file=sys.stderr) | |
| 129 | 新增: sys.exit(1) | |
| @@ -68,26 +68,45 @@ replace_once(' clipboardPasteFrom(text) {', ''' // Cage: serialize the cli | ||
| 68 | 68 | } |
| 69 | 69 | |
| 70 | 70 | cageRunInput(action) { |
| 71 | 新增: return this._cageQueueInput(() => this._cageRunInput(action)); | |
| 72 | 新增: } | |
| 73 | 新增: | |
| 74 | 新增: async _cageRunInput(action) { | |
| 75 | 新增: if (this._rfbConnectionState !== 'connected' || this._viewOnly || !this._supportsFence) | |
| 76 | 新增: throw new Error('Input transport is not ready'); | |
| 77 | 新增: // Flush preceding VNC clicks/keys before a browser text insertion. | |
| 78 | 新增: await new Promise((resolve, reject) => { | |
| 79 | 新增: const id = 'cage-input-' + (this._cageInputSequence = (this._cageInputSequence || 0) + 1); | |
| 80 | 新增: const timer = setTimeout(() => { | |
| 81 | 新增: this._cageInputFence = null; | |
| 82 | 新增: reject(new Error('Input fence timed out')); | |
| 83 | 新增: }, 4000); | |
| 84 | 新增: this._cageInputFence = { id, timer, resolve }; | |
| 85 | 新增: RFB.messages.clientFence(this._sock, (1 << 31) | 1, id); | |
| 86 | 新增: }); | |
| 87 | 新增: if (this._rfbConnectionState !== 'connected') throw new Error('Input disconnected'); | |
| 88 | 新增: return action(); | |
| 89 | 新增: } | |
| 90 | 新增: | |
| 91 | 新增: cagePasteContent(content, pasteImage, valid) { | |
| 92 | 新增: // Reserve the queue before asynchronous host clipboard/image decoding. | |
| 93 | 新增: // Keep a rejection handler attached even if an earlier input fails. | |
| 94 | 新增: const pending = Promise.resolve(content).then(value => ({value}), error => ({error})); | |
| 71 | 95 | return this._cageQueueInput(async () => { |
| 72 | 删除: if (this._rfbConnectionState !== 'connected' || this._viewOnly || !this._supportsFence) | |
| 73 | 删除: throw new Error('Input transport is not ready'); | |
| 74 | 删除: // Flush preceding VNC clicks/keys before a browser text insertion. | |
| 75 | 删除: await new Promise((resolve, reject) => { | |
| 76 | 删除: const id = 'cage-input-' + (this._cageInputSequence = (this._cageInputSequence || 0) + 1); | |
| 77 | 删除: const timer = setTimeout(() => { | |
| 78 | 删除: this._cageInputFence = null; | |
| 79 | 删除: reject(new Error('Input fence timed out')); | |
| 80 | 删除: }, 4000); | |
| 81 | 删除: this._cageInputFence = { id, timer, resolve }; | |
| 82 | 删除: RFB.messages.clientFence(this._sock, (1 << 31) | 1, id); | |
| 83 | 删除: }); | |
| 84 | 删除: if (this._rfbConnectionState !== 'connected') throw new Error('Input disconnected'); | |
| 85 | 删除: return action(); | |
| 96 | 新增: const {value, error} = await pending; | |
| 97 | 新增: if (error) throw error; | |
| 98 | 新增: if (!valid()) throw new Error('Input target changed'); | |
| 99 | 新增: if (value.png) return this._cageRunInput(() => pasteImage(value)); | |
| 100 | 新增: return this._cagePasteText(value.text || ''); | |
| 86 | 101 | }); |
| 87 | 102 | } |
| 88 | 103 | |
| 89 | 104 | cagePasteText(text) { |
| 90 | 删除: return this._cageQueueInput(() => new Promise((resolve, reject) => { | |
| 105 | 新增: return this._cageQueueInput(() => this._cagePasteText(text)); | |
| 106 | 新增: } | |
| 107 | 新增: | |
| 108 | 新增: _cagePasteText(text) { | |
| 109 | 新增: return new Promise((resolve, reject) => { | |
| 91 | 110 | if (this._rfbConnectionState !== 'connected' || this._viewOnly || |
| 92 | 111 | !this._supportsFence || |
| 93 | 112 | !this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify] || |
| @@ -102,7 +121,7 @@ replace_once(' clipboardPasteFrom(text) {', ''' // Cage: serialize the cli | ||
| 102 | 121 | }, 4000); |
| 103 | 122 | this._cagePasteJob = {id, timer, resolve, phase: 'data'}; |
| 104 | 123 | this.clipboardPasteFrom(text); |
| 105 | 删除: })); | |
| 124 | 新增: }); | |
| 106 | 125 | } |
| 107 | 126 | |
| 108 | 127 | clipboardPasteFrom(text) {''') |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package cage | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "errors" | |
| 7 | 新增: "syscall" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func profileProcessAlive(pid int) bool { | |
| 11 | 新增: err := syscall.Kill(pid, 0) | |
| 12 | 新增: return err == nil || errors.Is(err, syscall.EPERM) | |
| 13 | 新增:} | |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import "golang.org/x/sys/windows" | |
| 4 | 新增: | |
| 5 | 新增:func profileProcessAlive(pid int) bool { | |
| 6 | 新增: h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid)) | |
| 7 | 新增: if err != nil { | |
| 8 | 新增: return err == windows.ERROR_ACCESS_DENIED | |
| 9 | 新增: } | |
| 10 | 新增: defer windows.CloseHandle(h) | |
| 11 | 新增: var code uint32 | |
| 12 | 新增: return windows.GetExitCodeProcess(h, &code) == nil && code == 259 | |
| 13 | 新增:} | |
| @@ -8,7 +8,6 @@ import ( | ||
| 8 | 8 | "fmt" |
| 9 | 9 | "os" |
| 10 | 10 | "path/filepath" |
| 11 | 删除: "syscall" | |
| 12 | 11 | ) |
| 13 | 12 | |
| 14 | 13 | type runningProfile struct { |
| @@ -64,12 +63,7 @@ func (c Config) CheckRunning(state string) error { | ||
| 64 | 63 | if r.PID < 1 { |
| 65 | 64 | continue |
| 66 | 65 | } |
| 67 | 删除: p, err := os.FindProcess(r.PID) | |
| 68 | 删除: if err != nil { | |
| 69 | 删除: continue | |
| 70 | 删除: } | |
| 71 | 删除: alive := p.Signal(syscall.Signal(0)) == nil | |
| 72 | 删除: p.Release() | |
| 66 | 新增: alive := profileProcessAlive(r.PID) | |
| 73 | 67 | if alive && r.Fingerprint != c.Fingerprint() { |
| 74 | 68 | return fmt.Errorf("cage configuration changed while a VM is running; run cage stop before restarting") |
| 75 | 69 | } |
| @@ -61,7 +61,7 @@ def copy_to_workspace(source, size, workspace, name): | ||
| 61 | 61 | except OSError: |
| 62 | 62 | if published is None: |
| 63 | 63 | raise |
| 64 | 删除: published['warning'] = '文件已保存到 Mac;共享目录中的临时文件暂时无法清理。' | |
| 64 | 新增: published['warning'] = '文件已保存到本机;共享目录中的临时文件暂时无法清理。' | |
| 65 | 65 | finally: |
| 66 | 66 | os.close(destination) |
| 67 | 67 | os.close(parent) |
| @@ -85,14 +85,14 @@ def error_message(error): | ||
| 85 | 85 | return str(error) |
| 86 | 86 | if isinstance(error, OSError): |
| 87 | 87 | if error.errno == errno.ENOSPC: |
| 88 | 删除: return '空间不足,文件尚未保存到 Mac。清理空间后可重试。' | |
| 88 | 新增: return '空间不足,文件尚未保存到本机。清理空间后可重试。' | |
| 89 | 89 | if error.errno in (errno.EACCES, errno.EPERM, errno.EROFS): |
| 90 | 90 | return '无法写入共享下载目录。检查目录权限和共享连接后可重试。' |
| 91 | 91 | if error.errno in (errno.ELOOP, errno.ENOTDIR): |
| 92 | 92 | return '下载目录包含符号链接或已不再是目录,请修复后重试。' |
| 93 | 93 | if error.errno == errno.ENOENT: |
| 94 | 94 | return '下载源文件或共享目录不可用,请检查后重试。' |
| 95 | 删除: return '文件尚未保存到 Mac。检查共享连接和可用空间后可重试。' | |
| 95 | 新增: return '文件尚未保存到本机。检查共享连接和可用空间后可重试。' | |
| 96 | 96 | |
| 97 | 97 | |
| 98 | 98 | def main(): |
| @@ -141,7 +141,7 @@ def main(): | ||
| 141 | 141 | except OSError: |
| 142 | 142 | cleaned = False |
| 143 | 143 | if not cleaned: |
| 144 | 删除: result['warning'] = '文件已保存到 Mac;客机中的下载源文件发生变化或暂时无法清理。' | |
| 144 | 新增: result['warning'] = '文件已保存到本机;客机中的下载源文件发生变化或暂时无法清理。' | |
| 145 | 145 | print(json.dumps(result, ensure_ascii=False)) |
| 146 | 146 | return 0 |
| 147 | 147 | finally: |
| @@ -624,6 +624,11 @@ func (s *start) boot() error { | ||
| 624 | 624 | if err := s.beforeBoot(); err != nil { |
| 625 | 625 | return err |
| 626 | 626 | } |
| 627 | 新增: // Existing environments also require KVM. Otherwise Lima silently falls | |
| 628 | 新增: // back to software emulation after a host loses virtualization support. | |
| 629 | 新增: if !skipPrereqs && !host.LinuxPrereqs(s.io.Stderr) { | |
| 630 | 新增: return errStop | |
| 631 | 新增: } | |
| 627 | 632 | // Windows: QEMU's folder on PATH (winget does not put it there), for the |
| 628 | 633 | // hostagent this starts. |
| 629 | 634 | if !host.WindowsPrereqs(s.io.Stdout, s.io.Stderr) { |
| @@ -0,0 +1,59 @@ | ||
| 1 | 新增:package cli | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "runtime" | |
| 9 | 新增: "strings" | |
| 10 | 新增: "testing" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/vm" | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/vm/vmtest" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:func TestLinuxExistingVMChecksPrerequisitesBeforeBoot(t *testing.T) { | |
| 17 | 新增: saved := skipPrereqs | |
| 18 | 新增: t.Cleanup(func() { skipPrereqs = saved }) | |
| 19 | 新增: for _, missing := range []string{"QEMU", "KVM"} { | |
| 20 | 新增: t.Run(missing, func(t *testing.T) { | |
| 21 | 新增: if missing == "KVM" { | |
| 22 | 新增: if _, err := os.Stat("/dev/kvm"); !os.IsNotExist(err) { | |
| 23 | 新增: t.Skip("requires a Linux host without /dev/kvm") | |
| 24 | 新增: } | |
| 25 | 新增: } | |
| 26 | 新增: bin := t.TempDir() | |
| 27 | 新增: if missing == "KVM" { | |
| 28 | 新增: qemu := "qemu-system-x86_64" | |
| 29 | 新增: if runtime.GOARCH == "arm64" { | |
| 30 | 新增: qemu = "qemu-system-aarch64" | |
| 31 | 新增: } | |
| 32 | 新增: for _, name := range []string{qemu, "qemu-img"} { | |
| 33 | 新增: if err := os.WriteFile(filepath.Join(bin, name), []byte("#!/bin/sh\nexit 0\n"), 0755); err != nil { | |
| 34 | 新增: t.Fatal(err) | |
| 35 | 新增: } | |
| 36 | 新增: } | |
| 37 | 新增: } | |
| 38 | 新增: t.Setenv("PATH", bin) | |
| 39 | 新增: fake := vmtest.New(&vm.Instance{Name: "existing", Status: vm.Stopped}) | |
| 40 | 新增: te := newTestEnv(t, fake) | |
| 41 | 新增: s := &start{app: te.app, ctx: context.Background(), name: "existing"} | |
| 42 | 新增: skipPrereqs = false | |
| 43 | 新增: if err := s.boot(); !errors.Is(err, errStop) { | |
| 44 | 新增: t.Fatalf("missing %s did not stop existing VM boot: %v", missing, err) | |
| 45 | 新增: } | |
| 46 | 新增: if strings.Contains(fake.CallLog(), "start ") || fake.VMs["existing"].Status != vm.Stopped { | |
| 47 | 新增: t.Fatalf("driver started before prerequisite failure: %s", fake.CallLog()) | |
| 48 | 新增: } | |
| 49 | 新增: if missing == "KVM" && !strings.Contains(te.stderr.String(), "/dev/kvm") { | |
| 50 | 新增: t.Fatalf("missing KVM diagnostic: %s", te.stderr.String()) | |
| 51 | 新增: } | |
| 52 | 新增: // The test-only bypass still permits intentional TCG/fake-driver tests. | |
| 53 | 新增: skipPrereqs = true | |
| 54 | 新增: if err := s.boot(); err != nil || fake.VMs["existing"].Status != vm.Running { | |
| 55 | 新增: t.Fatalf("controlled prerequisite bypass failed: %v", err) | |
| 56 | 新增: } | |
| 57 | 新增: }) | |
| 58 | 新增: } | |
| 59 | 新增:} | |
| @@ -53,6 +53,10 @@ type startEnv struct { | ||
| 53 | 53 | |
| 54 | 54 | func newStartEnv(t *testing.T, answers ...string) *startEnv { |
| 55 | 55 | t.Helper() |
| 56 | 新增: // These tests use a fake VM; the host running them need not have KVM. | |
| 57 | 新增: savedPrereqs := skipPrereqs | |
| 58 | 新增: skipPrereqs = true | |
| 59 | 新增: t.Cleanup(func() { skipPrereqs = savedPrereqs }) | |
| 56 | 60 | if _, err := exec.LookPath("git"); err != nil { |
| 57 | 61 | t.Skip("no git") |
| 58 | 62 | } |
| @@ -2,6 +2,8 @@ package gitguard | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "context" |
| 5 | 新增: "os" | |
| 6 | 新增: "path/filepath" | |
| 5 | 7 | "strings" |
| 6 | 8 | "time" |
| 7 | 9 | |
| @@ -52,7 +54,12 @@ func BareState(ctx context.Context) string { | ||
| 52 | 54 | // gitx.Untrusted sets the value on the command line: that scope is not |
| 53 | 55 | // the user's, the last of the others is. |
| 54 | 56 | cmd := gitx.Untrusted(ctx, "config", "--show-scope", "--get-all", "safe.bareRepository") |
| 55 | 删除: cmd.Dir = "/" | |
| 57 | 新增: // Windows needs a volume-qualified directory. The system/user drive root | |
| 58 | 新增: // also keeps this global-config query outside the shared project. | |
| 59 | 新增: cmd.Dir = string(filepath.Separator) | |
| 60 | 新增: if home, err := os.UserHomeDir(); err == nil { | |
| 61 | 新增: cmd.Dir = filepath.VolumeName(home) + string(filepath.Separator) | |
| 62 | 新增: } | |
| 56 | 63 | cmd.WaitDelay = 2 * time.Second |
| 57 | 64 | out, _ = cmd.Output() |
| 58 | 65 | value := "" |
| @@ -1,5 +1,20 @@ | ||
| 1 | 1 | package gitguard |
| 2 | 2 | |
| 3 | 删除:// linked reports whether the regular file p has other hard links. Not | |
| 4 | 删除:// checked on Windows. | |
| 5 | 删除:func linked(p string) bool { return false } | |
| 3 | 新增:import "golang.org/x/sys/windows" | |
| 4 | 新增: | |
| 5 | 新增:// linked detects writable aliases of metadata on NTFS as well as Unix. | |
| 6 | 新增:func linked(p string) bool { | |
| 7 | 新增: name, err := windows.UTF16PtrFromString(p) | |
| 8 | 新增: if err != nil { | |
| 9 | 新增: return false | |
| 10 | 新增: } | |
| 11 | 新增: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, | |
| 12 | 新增: windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, | |
| 13 | 新增: nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) | |
| 14 | 新增: if err != nil { | |
| 15 | 新增: return false | |
| 16 | 新增: } | |
| 17 | 新增: defer windows.CloseHandle(handle) | |
| 18 | 新增: var info windows.ByHandleFileInformation | |
| 19 | 新增: return windows.GetFileInformationByHandle(handle, &info) == nil && info.NumberOfLinks > 1 | |
| 20 | 新增:} | |
| @@ -0,0 +1,24 @@ | ||
| 1 | 新增:package gitguard | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "testing" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestWindowsMetadataHardLinkIsDetected(t *testing.T) { | |
| 10 | 新增: dir := t.TempDir() | |
| 11 | 新增: config := filepath.Join(dir, "config") | |
| 12 | 新增: if err := os.WriteFile(config, []byte("metadata"), 0600); err != nil { | |
| 13 | 新增: t.Fatal(err) | |
| 14 | 新增: } | |
| 15 | 新增: if linked(config) { | |
| 16 | 新增: t.Fatal("single link reported as shared metadata") | |
| 17 | 新增: } | |
| 18 | 新增: if err := os.Link(config, filepath.Join(dir, "editable-alias")); err != nil { | |
| 19 | 新增: t.Fatal(err) | |
| 20 | 新增: } | |
| 21 | 新增: if !linked(config) { | |
| 22 | 新增: t.Fatal("writable NTFS alias of metadata was not detected") | |
| 23 | 新增: } | |
| 24 | 新增:} | |
| @@ -121,17 +121,25 @@ func inGroup(name string) bool { | ||
| 121 | 121 | return err == nil && slices.Contains(ids, g.Gid) |
| 122 | 122 | } |
| 123 | 123 | |
| 124 | 删除:// WindowsPrereqs checks for QEMU, which Lima runs on Windows. Whether the | |
| 125 | 删除:// "Windows Hypervisor Platform" feature is on cannot be read without | |
| 126 | 删除:// administrator rights: a host without it fails at the first start, where | |
| 127 | 删除:// WindowsStartHint explains it. winget's QEMU does not add itself to PATH: | |
| 124 | 新增:// WindowsPrereqs checks for QEMU and queries the Windows Hypervisor Platform | |
| 125 | 新增:// capability without elevation. | |
| 126 | 新增:// winget's QEMU does not add itself to PATH: | |
| 128 | 127 | // its default folder goes on PATH for this process. True elsewhere. |
| 129 | 128 | func WindowsPrereqs(out, w io.Writer) bool { |
| 130 | 129 | if runtime.GOOS != "windows" { |
| 131 | 130 | return true |
| 132 | 131 | } |
| 132 | 新增: if err := ConfigureWindowsRuntime(); err != nil { | |
| 133 | 新增: fmt.Fprintln(w, err) | |
| 134 | 新增: return false | |
| 135 | 新增: } | |
| 136 | 新增: if err := windowsHypervisorReady(); err != nil { | |
| 137 | 新增: fmt.Fprintln(w, err) | |
| 138 | 新增: return false | |
| 139 | 新增: } | |
| 133 | 140 | bin, _ := qemuBinary() |
| 134 | 删除: if _, err := exec.LookPath(bin); err == nil { | |
| 141 | 新增: _, imageErr := exec.LookPath("qemu-img") | |
| 142 | 新增: if _, err := exec.LookPath(bin); err == nil && imageErr == nil { | |
| 135 | 143 | return true |
| 136 | 144 | } |
| 137 | 145 | dir := os.Getenv("AGENT_VM_QEMU_DIR") |
| @@ -139,8 +147,10 @@ func WindowsPrereqs(out, w io.Writer) bool { | ||
| 139 | 147 | dir = `C:\Program Files\qemu` |
| 140 | 148 | } |
| 141 | 149 | if _, err := os.Stat(filepath.Join(dir, bin+".exe")); err == nil { |
| 142 | 删除: os.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) | |
| 143 | 删除: return true | |
| 150 | 新增: if _, err := os.Stat(filepath.Join(dir, "qemu-img.exe")); err == nil { | |
| 151 | 新增: os.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) | |
| 152 | 新增: return true | |
| 153 | 新增: } | |
| 144 | 154 | } |
| 145 | 155 | fmt.Fprintf(w, "Error: Lima needs '%s' on PATH (not found).\n Install QEMU with: winget install -e --id SoftwareFreedomConservancy.QEMU\n QEMU also needs the 'Windows Hypervisor Platform' Windows feature (see 'agent-vm doctor').\n", bin) |
| 146 | 156 | return false |
| @@ -0,0 +1,37 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "os" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:// EnsurePrivateDir creates host-only storage and removes inherited access. | |
| 9 | 新增:// Windows uses an explicit DACL; POSIX mode bits do not protect Windows files. | |
| 10 | 新增:func EnsurePrivateDir(path string) error { | |
| 11 | 新增: if err := os.MkdirAll(path, 0700); err != nil { | |
| 12 | 新增: return err | |
| 13 | 新增: } | |
| 14 | 新增: info, err := os.Lstat(path) | |
| 15 | 新增: if err != nil { | |
| 16 | 新增: return err | |
| 17 | 新增: } | |
| 18 | 新增: if !info.IsDir() || info.Mode()&(os.ModeSymlink|os.ModeIrregular) != 0 { | |
| 19 | 新增: return errors.New("private storage must be a real directory") | |
| 20 | 新增: } | |
| 21 | 新增: return protectPrivate(path, true) | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:// ProtectFile restricts an existing file or local socket to the current user. | |
| 25 | 新增:func ProtectFile(path string) error { return protectPrivate(path, false) } | |
| 26 | 新增: | |
| 27 | 新增:// CheckPrivateFile rejects non-regular files and access by other local users. | |
| 28 | 新增:func CheckPrivateFile(path string) error { | |
| 29 | 新增: info, err := os.Lstat(path) | |
| 30 | 新增: if err != nil { | |
| 31 | 新增: return err | |
| 32 | 新增: } | |
| 33 | 新增: if !info.Mode().IsRegular() { | |
| 34 | 新增: return errors.New("private record must be a regular file") | |
| 35 | 新增: } | |
| 36 | 新增: return checkPrivate(path, info) | |
| 37 | 新增:} | |
| @@ -0,0 +1,41 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "testing" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestPrivateStorageProtectsNewAndReplacedRecords(t *testing.T) { | |
| 10 | 新增: dir := filepath.Join(t.TempDir(), "profile") | |
| 11 | 新增: if err := EnsurePrivateDir(dir); err != nil { | |
| 12 | 新增: t.Fatal(err) | |
| 13 | 新增: } | |
| 14 | 新增: path := filepath.Join(dir, "credential") | |
| 15 | 新增: if err := os.WriteFile(path, []byte("private"), 0600); err != nil { | |
| 16 | 新增: t.Fatal(err) | |
| 17 | 新增: } | |
| 18 | 新增: if err := ProtectFile(path); err != nil { | |
| 19 | 新增: t.Fatal(err) | |
| 20 | 新增: } | |
| 21 | 新增: if err := CheckPrivateFile(path); err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: replacement, err := os.CreateTemp(dir, ".replacement-") | |
| 25 | 新增: if err != nil { | |
| 26 | 新增: t.Fatal(err) | |
| 27 | 新增: } | |
| 28 | 新增: if err := ProtectFile(replacement.Name()); err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: replacement.Close() | |
| 32 | 新增: if err := os.Rename(replacement.Name(), path); err != nil { | |
| 33 | 新增: t.Fatal(err) | |
| 34 | 新增: } | |
| 35 | 新增: if err := CheckPrivateFile(path); err != nil { | |
| 36 | 新增: t.Fatalf("atomic replacement lost private permissions: %v", err) | |
| 37 | 新增: } | |
| 38 | 新增: if err := CheckPrivateFile(dir); err == nil { | |
| 39 | 新增: t.Fatal("directory accepted as credential record") | |
| 40 | 新增: } | |
| 41 | 新增:} | |
| @@ -0,0 +1,23 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package host | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "errors" | |
| 7 | 新增: "os" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func protectPrivate(path string, dir bool) error { | |
| 11 | 新增: mode := os.FileMode(0600) | |
| 12 | 新增: if dir { | |
| 13 | 新增: mode = 0700 | |
| 14 | 新增: } | |
| 15 | 新增: return os.Chmod(path, mode) | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:func checkPrivate(_ string, info os.FileInfo) error { | |
| 19 | 新增: if info.Mode().Perm()&0077 != 0 { | |
| 20 | 新增: return errors.New("private record is accessible to other users") | |
| 21 | 新增: } | |
| 22 | 新增: return nil | |
| 23 | 新增:} | |
| @@ -0,0 +1,76 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "os" | |
| 6 | 新增: "unsafe" | |
| 7 | 新增: | |
| 8 | 新增: "golang.org/x/sys/windows" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func privateSID() (*windows.SID, error) { | |
| 12 | 新增: u, err := windows.GetCurrentProcessToken().GetTokenUser() | |
| 13 | 新增: if err != nil { | |
| 14 | 新增: return nil, err | |
| 15 | 新增: } | |
| 16 | 新增: return u.User.Sid, nil | |
| 17 | 新增:} | |
| 18 | 新增: | |
| 19 | 新增:func protectPrivate(path string, dir bool) error { | |
| 20 | 新增: sid, err := privateSID() | |
| 21 | 新增: if err != nil { | |
| 22 | 新增: return err | |
| 23 | 新增: } | |
| 24 | 新增: flags := "" | |
| 25 | 新增: if dir { | |
| 26 | 新增: flags = "OICI" | |
| 27 | 新增: } | |
| 28 | 新增: sd, err := windows.SecurityDescriptorFromString("D:P(A;" + flags + ";FA;;;" + sid.String() + ")(A;" + flags + ";FA;;;SY)") | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: return err | |
| 31 | 新增: } | |
| 32 | 新增: acl, _, err := sd.DACL() | |
| 33 | 新增: if err != nil { | |
| 34 | 新增: return err | |
| 35 | 新增: } | |
| 36 | 新增: // Elevated Windows processes may create files owned by Administrators. | |
| 37 | 新增: // Preserve the same per-user contract for elevated and normal launches by | |
| 38 | 新增: // explicitly assigning the current user's SID as well as the private ACL. | |
| 39 | 新增: return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, | |
| 40 | 新增: windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, sid, nil, acl, nil) | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:func checkPrivate(path string, _ os.FileInfo) error { | |
| 44 | 新增: sid, err := privateSID() | |
| 45 | 新增: if err != nil { | |
| 46 | 新增: return err | |
| 47 | 新增: } | |
| 48 | 新增: sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) | |
| 49 | 新增: if err != nil { | |
| 50 | 新增: return err | |
| 51 | 新增: } | |
| 52 | 新增: owner, _, err := sd.Owner() | |
| 53 | 新增: if err != nil || owner == nil || !windows.EqualSid(owner, sid) { | |
| 54 | 新增: return errors.New("private record is not owned by the current user") | |
| 55 | 新增: } | |
| 56 | 新增: acl, _, err := sd.DACL() | |
| 57 | 新增: if err != nil || acl == nil || acl.AceCount == 0 { | |
| 58 | 新增: return errors.New("private record has no usable access restriction") | |
| 59 | 新增: } | |
| 60 | 新增: for i := uint32(0); i < uint32(acl.AceCount); i++ { | |
| 61 | 新增: var ace *windows.ACCESS_ALLOWED_ACE | |
| 62 | 新增: if err := windows.GetAce(acl, i, &ace); err != nil { | |
| 63 | 新增: return err | |
| 64 | 新增: } | |
| 65 | 新增: // Only simple allow ACEs from our protected DACL are accepted. Unknown | |
| 66 | 新增: // ACE formats must not accidentally grant access that this check misses. | |
| 67 | 新增: if ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE { | |
| 68 | 新增: return errors.New("private record has an unsupported access rule") | |
| 69 | 新增: } | |
| 70 | 新增: principal := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) | |
| 71 | 新增: if !windows.EqualSid(principal, sid) && !principal.IsWellKnown(windows.WinLocalSystemSid) { | |
| 72 | 新增: return errors.New("private record is accessible to other users") | |
| 73 | 新增: } | |
| 74 | 新增: } | |
| 75 | 新增: return nil | |
| 76 | 新增:} | |
| @@ -0,0 +1,40 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "testing" | |
| 7 | 新增: | |
| 8 | 新增: "golang.org/x/sys/windows" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestPrivateFileRejectsEveryoneReadACL(t *testing.T) { | |
| 12 | 新增: path := filepath.Join(t.TempDir(), "credential") | |
| 13 | 新增: if err := os.WriteFile(path, []byte("secret"), 0600); err != nil { | |
| 14 | 新增: t.Fatal(err) | |
| 15 | 新增: } | |
| 16 | 新增: sid, err := privateSID() | |
| 17 | 新增: if err != nil { | |
| 18 | 新增: t.Fatal(err) | |
| 19 | 新增: } | |
| 20 | 新增: sd, err := windows.SecurityDescriptorFromString("D:P(A;;FA;;;" + sid.String() + ")(A;;FR;;;WD)") | |
| 21 | 新增: if err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: acl, _, err := sd.DACL() | |
| 25 | 新增: if err != nil { | |
| 26 | 新增: t.Fatal(err) | |
| 27 | 新增: } | |
| 28 | 新增: if err := windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, acl, nil); err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: if err := CheckPrivateFile(path); err == nil { | |
| 32 | 新增: t.Fatal("publicly readable credential accepted") | |
| 33 | 新增: } | |
| 34 | 新增: if err := ProtectFile(path); err != nil { | |
| 35 | 新增: t.Fatal(err) | |
| 36 | 新增: } | |
| 37 | 新增: if err := CheckPrivateFile(path); err != nil { | |
| 38 | 新增: t.Fatalf("restricted DACL rejected: %v", err) | |
| 39 | 新增: } | |
| 40 | 新增:} | |
| @@ -0,0 +1,6 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package host | |
| 4 | 新增: | |
| 5 | 新增:func ConfigureWindowsRuntime() error { return nil } | |
| 6 | 新增:func windowsHypervisorReady() error { return nil } | |
| @@ -0,0 +1,69 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "fmt" | |
| 5 | 新增: "os" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "runtime" | |
| 8 | 新增: "strings" | |
| 9 | 新增: "unsafe" | |
| 10 | 新增: | |
| 11 | 新增: "golang.org/x/sys/windows" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:// ConfigureWindowsRuntime uses only the runtime shipped next to cage.exe. | |
| 15 | 新增:// The install does not modify the user's system PATH or SSH configuration. | |
| 16 | 新增:func ConfigureWindowsRuntime() error { | |
| 17 | 新增: // These describe an OpenSSH ancestor's private descriptors. Forwarding | |
| 18 | 新增: // them through a non-OpenSSH process corrupts a new SSH client's pipes. | |
| 19 | 新增: for _, name := range []string{"OPENSSH_STDIO_MODE", "c28fc6f98a2c44abbbd89d6a3037d0d9_POSIX_FD_STATE"} { | |
| 20 | 新增: os.Unsetenv(name) | |
| 21 | 新增: } | |
| 22 | 新增: version := windows.RtlGetVersion() | |
| 23 | 新增: if runtime.GOARCH != "amd64" || version.MajorVersion < 10 || version.BuildNumber < 19045 { | |
| 24 | 新增: return fmt.Errorf("Cage 需要 64 位 Windows 10 22H2(19045)或 Windows 11") | |
| 25 | 新增: } | |
| 26 | 新增: var processMachine, nativeMachine uint16 | |
| 27 | 新增: if err := windows.IsWow64Process2(windows.CurrentProcess(), &processMachine, &nativeMachine); err != nil || nativeMachine != 0x8664 { | |
| 28 | 新增: return fmt.Errorf("Cage Windows 版本需要 Intel 或 AMD 的 x64 处理器,暂不支持 Windows on ARM") | |
| 29 | 新增: } | |
| 30 | 新增: exe, err := os.Executable() | |
| 31 | 新增: if err != nil { | |
| 32 | 新增: return err | |
| 33 | 新增: } | |
| 34 | 新增: base := filepath.Join(filepath.Dir(exe), "runtime") | |
| 35 | 新增: paths := []string{} | |
| 36 | 新增: for _, item := range []struct{ dir, exe string }{{"qemu", "qemu-system-x86_64.exe"}, {"openssh", "ssh.exe"}} { | |
| 37 | 新增: dir := filepath.Join(base, item.dir) | |
| 38 | 新增: if st, err := os.Stat(filepath.Join(dir, item.exe)); err == nil && st.Mode().IsRegular() { | |
| 39 | 新增: paths = append(paths, dir) | |
| 40 | 新增: if item.dir == "qemu" { | |
| 41 | 新增: os.Setenv("AGENT_VM_QEMU_DIR", dir) | |
| 42 | 新增: } else { | |
| 43 | 新增: // Shellwords parses this override; forward slashes preserve paths | |
| 44 | 新增: // with spaces without interpreting Windows backslashes as escapes. | |
| 45 | 新增: os.Setenv("SSH", "'"+strings.ReplaceAll(filepath.ToSlash(filepath.Join(dir, "ssh.exe")), "'", "'\\''")+"'") | |
| 46 | 新增: } | |
| 47 | 新增: } | |
| 48 | 新增: } | |
| 49 | 新增: if len(paths) > 0 { | |
| 50 | 新增: paths = append(paths, os.Getenv("PATH")) | |
| 51 | 新增: return os.Setenv("PATH", strings.Join(paths, string(os.PathListSeparator))) | |
| 52 | 新增: } | |
| 53 | 新增: return nil | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:// This capability query does not require elevation and performs no changes. | |
| 57 | 新增:// The desktop installer can offer the Windows Features screen separately. | |
| 58 | 新增:func windowsHypervisorReady() error { | |
| 59 | 新增: proc := windows.NewLazySystemDLL("WinHvPlatform.dll").NewProc("WHvGetCapability") | |
| 60 | 新增: if err := proc.Find(); err != nil { | |
| 61 | 新增: return fmt.Errorf("请启用 Windows Hypervisor Platform(Windows 虚拟机监控程序平台)并重启后再启动环境") | |
| 62 | 新增: } | |
| 63 | 新增: var present, written uint32 | |
| 64 | 新增: result, _, _ := proc.Call(0, uintptr(unsafe.Pointer(&present)), unsafe.Sizeof(present), uintptr(unsafe.Pointer(&written))) | |
| 65 | 新增: if result != 0 || written != 4 || present == 0 { | |
| 66 | 新增: return fmt.Errorf("Windows 虚拟化尚未就绪:请在固件中启用 CPU 虚拟化,启用 Windows Hypervisor Platform 并重启") | |
| 67 | 新增: } | |
| 68 | 新增: return nil | |
| 69 | 新增:} | |
| @@ -0,0 +1,6 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package host | |
| 4 | 新增: | |
| 5 | 新增:func ListenInstanceStop(string, func()) (func(), error) { return func() {}, nil } | |
| 6 | 新增:func RequestInstanceStop(string) (bool, error) { return false, nil } | |
| @@ -0,0 +1,88 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/sha256" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "fmt" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "strings" | |
| 9 | 新增: "sync" | |
| 10 | 新增: "unsafe" | |
| 11 | 新增: | |
| 12 | 新增: "golang.org/x/sys/windows" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:func stopEventName(instanceDir string) (*uint16, error) { | |
| 16 | 新增: sid, err := privateSID() | |
| 17 | 新增: if err != nil { | |
| 18 | 新增: return nil, err | |
| 19 | 新增: } | |
| 20 | 新增: hash := sha256.Sum256([]byte(sid.String() + "\x00" + strings.ToLower(filepath.Clean(instanceDir)))) | |
| 21 | 新增: return windows.UTF16PtrFromString(fmt.Sprintf(`Local\CageHostagentStop-%x`, hash[:16])) | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:// ListenInstanceStop receives graceful-stop requests without a console. | |
| 25 | 新增:// The event's DACL restricts notification to the current user and SYSTEM. | |
| 26 | 新增:func ListenInstanceStop(instanceDir string, onStop func()) (func(), error) { | |
| 27 | 新增: name, err := stopEventName(instanceDir) | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: return nil, err | |
| 30 | 新增: } | |
| 31 | 新增: sid, err := privateSID() | |
| 32 | 新增: if err != nil { | |
| 33 | 新增: return nil, err | |
| 34 | 新增: } | |
| 35 | 新增: sd, err := windows.SecurityDescriptorFromString("D:P(A;;GA;;;" + sid.String() + ")(A;;GA;;;SY)") | |
| 36 | 新增: if err != nil { | |
| 37 | 新增: return nil, err | |
| 38 | 新增: } | |
| 39 | 新增: attrs := &windows.SecurityAttributes{SecurityDescriptor: sd} | |
| 40 | 新增: attrs.Length = uint32(unsafe.Sizeof(*attrs)) | |
| 41 | 新增: event, err := windows.CreateEvent(attrs, 1, 0, name) | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: return nil, err | |
| 44 | 新增: } | |
| 45 | 新增: done := make(chan struct{}) | |
| 46 | 新增: finished := make(chan struct{}) | |
| 47 | 新增: var once sync.Once | |
| 48 | 新增: stop := func() { once.Do(func() { close(done) }); <-finished } | |
| 49 | 新增: go func() { | |
| 50 | 新增: defer close(finished) | |
| 51 | 新增: defer windows.CloseHandle(event) | |
| 52 | 新增: for { | |
| 53 | 新增: select { | |
| 54 | 新增: case <-done: | |
| 55 | 新增: return | |
| 56 | 新增: default: | |
| 57 | 新增: } | |
| 58 | 新增: result, err := windows.WaitForSingleObject(event, 250) | |
| 59 | 新增: if err != nil { | |
| 60 | 新增: onStop() | |
| 61 | 新增: return | |
| 62 | 新增: } | |
| 63 | 新增: if result == windows.WAIT_OBJECT_0 { | |
| 64 | 新增: onStop() | |
| 65 | 新增: <-done | |
| 66 | 新增: return | |
| 67 | 新增: } | |
| 68 | 新增: } | |
| 69 | 新增: }() | |
| 70 | 新增: return stop, nil | |
| 71 | 新增:} | |
| 72 | 新增: | |
| 73 | 新增:// RequestInstanceStop returns false when no Cage hostagent owns the event. | |
| 74 | 新增:func RequestInstanceStop(instanceDir string) (bool, error) { | |
| 75 | 新增: name, err := stopEventName(instanceDir) | |
| 76 | 新增: if err != nil { | |
| 77 | 新增: return false, err | |
| 78 | 新增: } | |
| 79 | 新增: event, err := windows.OpenEvent(windows.EVENT_MODIFY_STATE, false, name) | |
| 80 | 新增: if errors.Is(err, windows.ERROR_FILE_NOT_FOUND) { | |
| 81 | 新增: return false, nil | |
| 82 | 新增: } | |
| 83 | 新增: if err != nil { | |
| 84 | 新增: return false, err | |
| 85 | 新增: } | |
| 86 | 新增: defer windows.CloseHandle(event) | |
| 87 | 新增: return true, windows.SetEvent(event) | |
| 88 | 新增:} | |
| @@ -0,0 +1,32 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "path/filepath" | |
| 5 | 新增: "testing" | |
| 6 | 新增: "time" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestInstanceStopEventWorksWithoutConsoleAndStaysScoped(t *testing.T) { | |
| 10 | 新增: dir := t.TempDir() | |
| 11 | 新增: notified := make(chan struct{}, 1) | |
| 12 | 新增: stop, err := ListenInstanceStop(dir, func() { notified <- struct{}{} }) | |
| 13 | 新增: if err != nil { | |
| 14 | 新增: t.Fatal(err) | |
| 15 | 新增: } | |
| 16 | 新增: t.Cleanup(stop) | |
| 17 | 新增: if requested, err := RequestInstanceStop(filepath.Join(dir, "other")); err != nil || requested { | |
| 18 | 新增: t.Fatalf("another instance received stop: %v %v", requested, err) | |
| 19 | 新增: } | |
| 20 | 新增: if requested, err := RequestInstanceStop(dir); err != nil || !requested { | |
| 21 | 新增: t.Fatalf("stop was not delivered: %v %v", requested, err) | |
| 22 | 新增: } | |
| 23 | 新增: select { | |
| 24 | 新增: case <-notified: | |
| 25 | 新增: case <-time.After(2 * time.Second): | |
| 26 | 新增: t.Fatal("stop event was not received") | |
| 27 | 新增: } | |
| 28 | 新增: stop() | |
| 29 | 新增: if requested, err := RequestInstanceStop(dir); err != nil || requested { | |
| 30 | 新增: t.Fatalf("closed event retained a listener: %v %v", requested, err) | |
| 31 | 新增: } | |
| 32 | 新增:} | |
| @@ -3,7 +3,8 @@ | ||
| 3 | 3 | |
| 4 | 4 | // Copied from third_party/lima/cmd/limactl/hostagent.go, which is in package |
| 5 | 5 | // main and cannot be imported. Changed by agent-vm: the package name, and |
| 6 | 删除:// WrapArgsError (in limactl's main.go) is cobra's own error here. | |
| 6 | 新增:// WrapArgsError (in limactl's main.go) is cobra's own error here. Cage also | |
| 7 | 新增:// receives stop requests through its buffered channel and Windows event. | |
| 7 | 8 | // TestHostagentCopy fails when the two drift apart. |
| 8 | 9 | |
| 9 | 10 | package limaembed |
| @@ -83,8 +84,13 @@ func hostagentAction(cmd *cobra.Command, args []string) error { | ||
| 83 | 84 | defer runtime.UnlockOSThread() |
| 84 | 85 | } |
| 85 | 86 | |
| 86 | 删除: signalCh := make(chan os.Signal, 1) | |
| 87 | 新增: signalCh := hostagentSignals | |
| 87 | 88 | signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM) |
| 89 | 新增: stopNotification, err := watchHostagentStop(socket) | |
| 90 | 新增: if err != nil { | |
| 91 | 新增: return err | |
| 92 | 新增: } | |
| 93 | 新增: defer stopNotification() | |
| 88 | 94 | |
| 89 | 95 | stdout := &syncWriter{w: cmd.OutOrStdout()} |
| 90 | 96 | stderr := &syncWriter{w: cmd.ErrOrStderr()} |
| @@ -19,6 +19,8 @@ func TestHostagentCopy(t *testing.T) { | ||
| 19 | 19 | } |
| 20 | 20 | want := strings.Replace(string(upstream), "package main", "package limaembed", 1) |
| 21 | 21 | want = strings.Replace(want, "WrapArgsError(cobra.ExactArgs(1))", "cobra.ExactArgs(1)", 1) |
| 22 | 新增: want = strings.Replace(want, "signalCh := make(chan os.Signal, 1)", "signalCh := hostagentSignals", 1) | |
| 23 | 新增: want = strings.Replace(want, "signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM)", "signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM)\n\tstopNotification, err := watchHostagentStop(socket)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stopNotification()", 1) | |
| 22 | 24 | // Our header: the comment block after the license lines. |
| 23 | 25 | got := string(ours) |
| 24 | 26 | start := strings.Index(got, "// Copied from") |
| @@ -65,7 +65,7 @@ func Run(args []string) bool { | ||
| 65 | 65 | dns.Names, dns.Answered = policy.Name, policy.Answered |
| 66 | 66 | } |
| 67 | 67 | if path := os.Getenv(cage.ConfigEnv); path != "" { |
| 68 | 删除: stopJobWatch, err = cage.WatchJobStop(filepath.Dir(path), os.Getenv(cage.JobEnv), func() { _ = osutil.SysKill(os.Getpid(), osutil.SigInt) }) | |
| 68 | 新增: stopJobWatch, err = cage.WatchJobStop(filepath.Dir(path), os.Getenv(cage.JobEnv), notifyHostagentStop) | |
| 69 | 69 | if err != nil { |
| 70 | 70 | logrus.Fatal(err) |
| 71 | 71 | } |
| @@ -50,6 +50,15 @@ func (e *eventWatch) Write(p []byte) (int, error) { | ||
| 50 | 50 | return e.w.Write(p) |
| 51 | 51 | } |
| 52 | 52 | |
| 53 | 新增:// Preserve file flushing through the notification wrapper. Windows file | |
| 54 | 新增:// watchers need it to observe newly appended hostagent status events. | |
| 55 | 新增:func (e *eventWatch) Sync() error { | |
| 56 | 新增: if s, ok := e.w.(syncer); ok { | |
| 57 | 新增: return s.Sync() | |
| 58 | 新增: } | |
| 59 | 新增: return nil | |
| 60 | 新增:} | |
| 61 | 新增: | |
| 53 | 62 | func (e *eventWatch) event(line []byte) { |
| 54 | 63 | var ev events.Event |
| 55 | 64 | if json.Unmarshal(line, &ev) != nil || ev.Status.PortForward == nil { |
| @@ -0,0 +1,99 @@ | ||
| 1 | 新增:package limaembed | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "fmt" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "sync/atomic" | |
| 9 | 新增: "testing" | |
| 10 | 新增: "time" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/lima-vm/lima/v2/pkg/hostagent/events" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:type countedSyncFile struct { | |
| 16 | 新增: *os.File | |
| 17 | 新增: syncs atomic.Int32 | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:func (w *countedSyncFile) Sync() error { | |
| 21 | 新增: w.syncs.Add(1) | |
| 22 | 新增: return w.File.Sync() | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:// This uses Windows file notifications and the real Lima event watcher. It | |
| 26 | 新增:// starts no VM and writes only synthetic events in the test's temp directory. | |
| 27 | 新增:func TestWindowsEventWatchFlush(t *testing.T) { | |
| 28 | 新增: dir := t.TempDir() | |
| 29 | 新增: stdoutPath, stderrPath := filepath.Join(dir, "ha.stdout.log"), filepath.Join(dir, "ha.stderr.log") | |
| 30 | 新增: file, err := os.Create(stdoutPath) | |
| 31 | 新增: if err != nil { | |
| 32 | 新增: t.Fatal(err) | |
| 33 | 新增: } | |
| 34 | 新增: defer file.Close() | |
| 35 | 新增: if err := os.WriteFile(stderrPath, nil, 0600); err != nil { | |
| 36 | 新增: t.Fatal(err) | |
| 37 | 新增: } | |
| 38 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 39 | 新增: defer cancel() | |
| 40 | 新增: initial, running, done := make(chan struct{}, 1), make(chan struct{}, 1), make(chan error, 1) | |
| 41 | 新增: go func() { | |
| 42 | 新增: done <- events.Watch(ctx, stdoutPath, stderrPath, time.Time{}, false, func(ev events.Event) bool { | |
| 43 | 新增: if ev.Status.Running { | |
| 44 | 新增: running <- struct{}{} | |
| 45 | 新增: return true | |
| 46 | 新增: } | |
| 47 | 新增: select { | |
| 48 | 新增: case initial <- struct{}{}: | |
| 49 | 新增: default: | |
| 50 | 新增: } | |
| 51 | 新增: return false | |
| 52 | 新增: }) | |
| 53 | 新增: }() | |
| 54 | 新增: _, err = fmt.Fprintf(file, "{\"time\":%q,\"status\":{}}\n", time.Now().Format(time.RFC3339Nano)) | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: if err := file.Sync(); err != nil { | |
| 59 | 新增: t.Fatal(err) | |
| 60 | 新增: } | |
| 61 | 新增: select { | |
| 62 | 新增: case <-initial: | |
| 63 | 新增: case <-time.After(3 * time.Second): | |
| 64 | 新增: t.Fatal("watcher did not observe initial event") | |
| 65 | 新增: } | |
| 66 | 新增: // Let the real tailer return to waiting at EOF before the measured write. | |
| 67 | 新增: time.Sleep(200 * time.Millisecond) | |
| 68 | 新增: counted := &countedSyncFile{File: file} | |
| 69 | 新增: writer := &syncWriter{w: newEventWatch(counted, "synthetic-test")} | |
| 70 | 新增: start := time.Now() | |
| 71 | 新增: _, err = fmt.Fprintf(writer, "{\"time\":%q,\"status\":{\"running\":true}}\n", time.Now().Format(time.RFC3339Nano)) | |
| 72 | 新增: if err != nil { | |
| 73 | 新增: t.Fatal(err) | |
| 74 | 新增: } | |
| 75 | 新增: received := false | |
| 76 | 新增: select { | |
| 77 | 新增: case <-running: | |
| 78 | 新增: received = true | |
| 79 | 新增: case <-time.After(2 * time.Second): | |
| 80 | 新增: } | |
| 81 | 新增: t.Logf("runningReceived=%t latency=%s forwardedSyncCalls=%d", received, time.Since(start), counted.syncs.Load()) | |
| 82 | 新增: writer.flush() | |
| 83 | 新增: cancel() | |
| 84 | 新增: file.Close() | |
| 85 | 新增: select { | |
| 86 | 新增: case err := <-done: | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: t.Fatal(err) | |
| 89 | 新增: } | |
| 90 | 新增: case <-time.After(3 * time.Second): | |
| 91 | 新增: t.Fatal("watcher cleanup timed out") | |
| 92 | 新增: } | |
| 93 | 新增: if !received { | |
| 94 | 新增: t.Fatal("hostagent running event did not reach the file watcher") | |
| 95 | 新增: } | |
| 96 | 新增: if counted.syncs.Load() == 0 { | |
| 97 | 新增: t.Fatal("notification wrapper did not forward Sync to the log file") | |
| 98 | 新增: } | |
| 99 | 新增:} | |
| @@ -0,0 +1,23 @@ | ||
| 1 | 新增:package limaembed | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: | |
| 7 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:// One hostagent runs in this process. Buffering preserves cancellation that | |
| 11 | 新增:// arrives while the driver and hostagent are still initializing. | |
| 12 | 新增:var hostagentSignals = make(chan os.Signal, 1) | |
| 13 | 新增: | |
| 14 | 新增:func notifyHostagentStop() { | |
| 15 | 新增: select { | |
| 16 | 新增: case hostagentSignals <- os.Interrupt: | |
| 17 | 新增: default: | |
| 18 | 新增: } | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 21 | 新增:func watchHostagentStop(socket string) (func(), error) { | |
| 22 | 新增: return host.ListenInstanceStop(filepath.Dir(socket), notifyHostagentStop) | |
| 23 | 新增:} | |
| @@ -17,6 +17,8 @@ import ( | ||
| 17 | 17 | "runtime" |
| 18 | 18 | "strconv" |
| 19 | 19 | "time" |
| 20 | 新增: | |
| 21 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 20 | 22 | ) |
| 21 | 23 | |
| 22 | 24 | // CorePath deliberately never searches PATH or another application's bundle. |
| @@ -25,8 +27,12 @@ func CorePath() (string, error) { | ||
| 25 | 27 | if err != nil { |
| 26 | 28 | return "", err |
| 27 | 29 | } |
| 28 | 删除: for _, p := range []string{filepath.Join(filepath.Dir(exe), "mihomo"), filepath.Join(filepath.Dir(exe), "..", "proxy-core", "mihomo")} { | |
| 29 | 删除: if st, e := os.Stat(p); e == nil && st.Mode().IsRegular() && st.Mode()&0111 != 0 { | |
| 30 | 新增: name := "mihomo" | |
| 31 | 新增: if runtime.GOOS == "windows" { | |
| 32 | 新增: name += ".exe" | |
| 33 | 新增: } | |
| 34 | 新增: for _, p := range []string{filepath.Join(filepath.Dir(exe), name), filepath.Join(filepath.Dir(exe), "..", "proxy-core", name)} { | |
| 35 | 新增: if st, e := os.Stat(p); e == nil && st.Mode().IsRegular() && (runtime.GOOS == "windows" || st.Mode()&0111 != 0) { | |
| 30 | 36 | return filepath.Clean(p), nil |
| 31 | 37 | } |
| 32 | 38 | } |
| @@ -42,7 +48,7 @@ func Validate(ctx context.Context, profile string, s Store) error { | ||
| 42 | 48 | return err |
| 43 | 49 | } |
| 44 | 50 | dir := Dir(profile) |
| 45 | 删除: if err = os.MkdirAll(dir, 0700); err != nil { | |
| 51 | 新增: if err = host.EnsurePrivateDir(dir); err != nil { | |
| 46 | 52 | return err |
| 47 | 53 | } |
| 48 | 54 | f, err := os.CreateTemp(dir, "validate-*.yaml") |
| @@ -50,6 +56,10 @@ func Validate(ctx context.Context, profile string, s Store) error { | ||
| 50 | 56 | return err |
| 51 | 57 | } |
| 52 | 58 | defer os.Remove(f.Name()) |
| 59 | 新增: if err = host.ProtectFile(f.Name()); err != nil { | |
| 60 | 新增: f.Close() | |
| 61 | 新增: return err | |
| 62 | 新增: } | |
| 53 | 63 | if _, err = f.Write(b); err != nil { |
| 54 | 64 | f.Close() |
| 55 | 65 | return err |
| @@ -58,7 +68,7 @@ func Validate(ctx context.Context, profile string, s Store) error { | ||
| 58 | 68 | ctx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| 59 | 69 | defer cancel() |
| 60 | 70 | cmd := exec.CommandContext(ctx, core, "-t", "-d", dir, "-f", f.Name()) |
| 61 | 删除: cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=" + dir} | |
| 71 | 新增: cmd.Env = coreEnvironment(dir) | |
| 62 | 72 | if output, e := cmd.CombinedOutput(); e != nil { |
| 63 | 73 | _ = Write(filepath.Join(dir, "validation.log"), output) |
| 64 | 74 | return errors.New("代理核心拒绝该配置,请检查节点协议和参数;原配置已保留") |
| @@ -116,6 +126,12 @@ func label(profile string) string { | ||
| 116 | 126 | } |
| 117 | 127 | func servicePath(profile string) string { return filepath.Join(Dir(profile), "managed-service.plist") } |
| 118 | 128 | func Stop(profile string) error { |
| 129 | 新增: if runtime.GOOS == "windows" { | |
| 130 | 新增: return stopWindowsCore(profile) | |
| 131 | 新增: } | |
| 132 | 新增: if runtime.GOOS == "linux" { | |
| 133 | 新增: return stopLinuxCore(profile) | |
| 134 | 新增: } | |
| 119 | 135 | if _, err := os.Stat(servicePath(profile)); os.IsNotExist(err) { |
| 120 | 136 | return nil |
| 121 | 137 | } |
| @@ -132,6 +148,12 @@ func Stop(profile string) error { | ||
| 132 | 148 | return nil |
| 133 | 149 | } |
| 134 | 150 | func Start(ctx context.Context, profile string, s Store) error { |
| 151 | 新增: if runtime.GOOS == "windows" { | |
| 152 | 新增: return startWindowsCore(ctx, profile, s) | |
| 153 | 新增: } | |
| 154 | 新增: if runtime.GOOS == "linux" { | |
| 155 | 新增: return startLinuxCore(ctx, profile, s) | |
| 156 | 新增: } | |
| 135 | 157 | if runtime.GOOS != "darwin" { |
| 136 | 158 | return errors.New("内置代理当前支持 macOS") |
| 137 | 159 | } |
| @@ -17,7 +17,7 @@ import ( | ||
| 17 | 17 | ) |
| 18 | 18 | |
| 19 | 19 | // BootstrapClient is for explicit infrastructure downloads only. It ignores |
| 20 | 删除:// environment proxies and resolves public hosts over an IP-addressed DoH URL. | |
| 20 | 新增:// environment proxies and resolves public hosts over IP-addressed DoH URLs. | |
| 21 | 21 | func BootstrapClient() *http.Client { |
| 22 | 22 | tr := &http.Transport{Proxy: nil, DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 23 | 23 | host, port, err := net.SplitHostPort(addr) |
| @@ -62,24 +62,72 @@ func usageSummary(raw string) string { | ||
| 62 | 62 | func publicIP(ip netip.Addr) bool { |
| 63 | 63 | return ip.Is4() && ip.IsGlobalUnicast() && !ip.IsPrivate() && !ip.IsLoopback() && !ip.IsLinkLocalUnicast() && !netip.MustParsePrefix("100.64.0.0/10").Contains(ip) && !netip.MustParsePrefix("198.18.0.0/15").Contains(ip) |
| 64 | 64 | } |
| 65 | 新增: | |
| 66 | 新增:// BootstrapDNSURLs is shared by host downloads and the core's node resolver. | |
| 67 | 新增:// Numeric HTTPS endpoints need neither the host resolver nor a working proxy. | |
| 68 | 新增:func BootstrapDNSURLs() []string { | |
| 69 | 新增: return []string{"https://1.1.1.1/dns-query", "https://223.5.5.5/dns-query"} | |
| 70 | 新增:} | |
| 71 | 新增: | |
| 65 | 72 | func resolveInfrastructure(ctx context.Context, host string) (netip.Addr, error) { |
| 66 | 删除: q := new(dns.Msg) | |
| 67 | 删除: q.SetQuestion(dns.Fqdn(host), dns.TypeA) | |
| 68 | 删除: b, _ := q.Pack() | |
| 69 | 73 | tr := &http.Transport{Proxy: nil} |
| 70 | 74 | defer tr.CloseIdleConnections() |
| 71 | 删除: c := &http.Client{Transport: tr, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("DNS redirect refused") }} | |
| 72 | 删除: req, _ := http.NewRequestWithContext(ctx, "POST", "https://1.1.1.1/dns-query", bytes.NewReader(b)) | |
| 75 | 新增: c := &http.Client{Transport: tr, Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("DNS redirect refused") }} | |
| 76 | 新增: return resolveInfrastructureWith(ctx, host, c, BootstrapDNSURLs()) | |
| 77 | 新增:} | |
| 78 | 新增: | |
| 79 | 新增:func resolveInfrastructureWith(ctx context.Context, host string, client *http.Client, servers []string) (netip.Addr, error) { | |
| 80 | 新增: ctx, cancel := context.WithTimeout(ctx, 8*time.Second) | |
| 81 | 新增: defer cancel() | |
| 82 | 新增: q := new(dns.Msg) | |
| 83 | 新增: q.SetQuestion(dns.Fqdn(host), dns.TypeA) | |
| 84 | 新增: wire, err := q.Pack() | |
| 85 | 新增: if err != nil { | |
| 86 | 新增: return netip.Addr{}, errors.New("代理基础设施域名无效") | |
| 87 | 新增: } | |
| 88 | 新增: type result struct { | |
| 89 | 新增: ip netip.Addr | |
| 90 | 新增: err error | |
| 91 | 新增: } | |
| 92 | 新增: results := make(chan result, len(servers)) | |
| 93 | 新增: // A blocked resolver must not delay a reachable one. Cancel the remaining | |
| 94 | 新增: // HTTPS requests once a usable public answer is available. | |
| 95 | 新增: for _, server := range servers { | |
| 96 | 新增: go func() { | |
| 97 | 新增: ip, err := queryInfrastructureDNS(ctx, client, server, q, wire) | |
| 98 | 新增: results <- result{ip, err} | |
| 99 | 新增: }() | |
| 100 | 新增: } | |
| 101 | 新增: for range servers { | |
| 102 | 新增: select { | |
| 103 | 新增: case <-ctx.Done(): | |
| 104 | 新增: return netip.Addr{}, ctx.Err() | |
| 105 | 新增: case result := <-results: | |
| 106 | 新增: if result.err == nil { | |
| 107 | 新增: return result.ip, nil | |
| 108 | 新增: } | |
| 109 | 新增: } | |
| 110 | 新增: } | |
| 111 | 新增: return netip.Addr{}, errors.New("代理基础设施 DNS 均不可用或未返回公网 IPv4;请检查主机网络后重试,未使用系统 DNS 回退") | |
| 112 | 新增:} | |
| 113 | 新增: | |
| 114 | 新增:func queryInfrastructureDNS(ctx context.Context, client *http.Client, server string, q *dns.Msg, wire []byte) (netip.Addr, error) { | |
| 115 | 新增: req, err := http.NewRequestWithContext(ctx, "POST", server, bytes.NewReader(wire)) | |
| 116 | 新增: if err != nil { | |
| 117 | 新增: return netip.Addr{}, err | |
| 118 | 新增: } | |
| 73 | 119 | req.Header.Set("Content-Type", "application/dns-message") |
| 74 | 120 | req.Header.Set("Accept", "application/dns-message") |
| 75 | 删除: resp, err := c.Do(req) | |
| 121 | 新增: resp, err := client.Do(req) | |
| 76 | 122 | if err != nil { |
| 77 | 123 | return netip.Addr{}, errors.New("代理基础设施域名解析失败") |
| 78 | 124 | } |
| 79 | 125 | defer resp.Body.Close() |
| 80 | 删除: wire, err := io.ReadAll(io.LimitReader(resp.Body, 65536)) | |
| 126 | 新增: wire, err = io.ReadAll(io.LimitReader(resp.Body, 65536)) | |
| 81 | 127 | var answer dns.Msg |
| 82 | 删除: if err != nil || resp.StatusCode != 200 || answer.Unpack(wire) != nil || answer.Id != q.Id { | |
| 128 | 新增: if err != nil || resp.StatusCode != 200 || answer.Unpack(wire) != nil || answer.Id != q.Id || | |
| 129 | 新增: !answer.Response || answer.Truncated || answer.Rcode != dns.RcodeSuccess || len(answer.Question) != 1 || | |
| 130 | 新增: !strings.EqualFold(answer.Question[0].Name, q.Question[0].Name) || answer.Question[0].Qtype != dns.TypeA || answer.Question[0].Qclass != dns.ClassINET { | |
| 83 | 131 | return netip.Addr{}, errors.New("代理基础设施 DNS 响应无效") |
| 84 | 132 | } |
| 85 | 133 | for _, rr := range answer.Answer { |
| @@ -0,0 +1,185 @@ | ||
| 1 | 新增:package managedproxy | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "io" | |
| 7 | 新增: "net" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "net/http/httptest" | |
| 10 | 新增: "os" | |
| 11 | 新增: "reflect" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "testing" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/miekg/dns" | |
| 17 | 新增: "go.yaml.in/yaml/v3" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:func writeDNSAnswer(t *testing.T, w http.ResponseWriter, r *http.Request, mutate func(*dns.Msg)) { | |
| 21 | 新增: t.Helper() | |
| 22 | 新增: if r.Method != "POST" || r.Header.Get("Content-Type") != "application/dns-message" || r.Header.Get("Accept") != "application/dns-message" { | |
| 23 | 新增: t.Error("bootstrap changed its encrypted DNS request contract") | |
| 24 | 新增: } | |
| 25 | 新增: wire, _ := io.ReadAll(r.Body) | |
| 26 | 新增: var q dns.Msg | |
| 27 | 新增: if err := q.Unpack(wire); err != nil || len(q.Question) != 1 || q.Question[0].Qtype != dns.TypeA { | |
| 28 | 新增: t.Error("invalid bootstrap question", err) | |
| 29 | 新增: w.WriteHeader(400) | |
| 30 | 新增: return | |
| 31 | 新增: } | |
| 32 | 新增: answer := new(dns.Msg) | |
| 33 | 新增: answer.SetReply(&q) | |
| 34 | 新增: answer.Answer = []dns.RR{&dns.A{Hdr: dns.RR_Header{Name: q.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60}, A: net.ParseIP("8.8.8.8").To4()}} | |
| 35 | 新增: if mutate != nil { | |
| 36 | 新增: mutate(answer) | |
| 37 | 新增: } | |
| 38 | 新增: wire, err := answer.Pack() | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: t.Error(err) | |
| 41 | 新增: } | |
| 42 | 新增: w.Header().Set("Content-Type", "application/dns-message") | |
| 43 | 新增: _, _ = w.Write(wire) | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:func TestInfrastructureDNSDoesNotWaitForBlockedResolver(t *testing.T) { | |
| 47 | 新增: started, canceled := make(chan struct{}), make(chan struct{}) | |
| 48 | 新增: release := make(chan struct{}) | |
| 49 | 新增: server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 50 | 新增: if r.URL.Path == "/blocked" { | |
| 51 | 新增: _, _ = io.Copy(io.Discard, r.Body) | |
| 52 | 新增: close(started) | |
| 53 | 新增: select { | |
| 54 | 新增: case <-r.Context().Done(): | |
| 55 | 新增: close(canceled) | |
| 56 | 新增: case <-release: | |
| 57 | 新增: } | |
| 58 | 新增: return | |
| 59 | 新增: } | |
| 60 | 新增: select { | |
| 61 | 新增: case <-started: | |
| 62 | 新增: case <-r.Context().Done(): | |
| 63 | 新增: return | |
| 64 | 新增: } | |
| 65 | 新增: writeDNSAnswer(t, w, r, nil) | |
| 66 | 新增: })) | |
| 67 | 新增: defer server.Close() | |
| 68 | 新增: defer close(release) | |
| 69 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) | |
| 70 | 新增: defer cancel() | |
| 71 | 新增: ip, err := resolveInfrastructureWith(ctx, "example.com", server.Client(), []string{server.URL + "/blocked", server.URL + "/working"}) | |
| 72 | 新增: if err != nil || ip.String() != "8.8.8.8" { | |
| 73 | 新增: t.Fatal("reachable resolver could not bypass blocked one", ip, err) | |
| 74 | 新增: } | |
| 75 | 新增: select { | |
| 76 | 新增: case <-canceled: | |
| 77 | 新增: case <-ctx.Done(): | |
| 78 | 新增: t.Fatal("unused DNS query was not canceled") | |
| 79 | 新增: } | |
| 80 | 新增:} | |
| 81 | 新增: | |
| 82 | 新增:func TestInfrastructureDNSRejectsInvalidAnswersAndTriesOtherResolver(t *testing.T) { | |
| 83 | 新增: for _, tc := range []struct { | |
| 84 | 新增: name string | |
| 85 | 新增: mutate func(*dns.Msg) | |
| 86 | 新增: }{ | |
| 87 | 新增: {"wrong ID", func(m *dns.Msg) { m.Id++ }}, | |
| 88 | 新增: {"not a reply", func(m *dns.Msg) { m.Response = false }}, | |
| 89 | 新增: {"NXDOMAIN", func(m *dns.Msg) { m.Rcode = dns.RcodeNameError }}, | |
| 90 | 新增: {"truncated", func(m *dns.Msg) { m.Truncated = true }}, | |
| 91 | 新增: {"wrong question", func(m *dns.Msg) { m.Question[0].Name = "other.example." }}, | |
| 92 | 新增: {"private IP", func(m *dns.Msg) { m.Answer[0].(*dns.A).A = net.ParseIP("127.0.0.1").To4() }}, | |
| 93 | 新增: {"no answer", func(m *dns.Msg) { m.Answer = nil }}, | |
| 94 | 新增: } { | |
| 95 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 96 | 新增: server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 97 | 新增: mutate := tc.mutate | |
| 98 | 新增: if r.URL.Path == "/working" { | |
| 99 | 新增: mutate = nil | |
| 100 | 新增: } | |
| 101 | 新增: writeDNSAnswer(t, w, r, mutate) | |
| 102 | 新增: })) | |
| 103 | 新增: defer server.Close() | |
| 104 | 新增: ctx := context.Background() | |
| 105 | 新增: if _, err := resolveInfrastructureWith(ctx, "example.com", server.Client(), []string{server.URL + "/invalid"}); err == nil { | |
| 106 | 新增: t.Fatal("invalid DNS response was accepted") | |
| 107 | 新增: } | |
| 108 | 新增: ip, err := resolveInfrastructureWith(ctx, "example.com", server.Client(), []string{server.URL + "/invalid", server.URL + "/working"}) | |
| 109 | 新增: if err != nil || ip.String() != "8.8.8.8" { | |
| 110 | 新增: t.Fatal("valid DNS alternative failed", ip, err) | |
| 111 | 新增: } | |
| 112 | 新增: }) | |
| 113 | 新增: } | |
| 114 | 新增:} | |
| 115 | 新增: | |
| 116 | 新增:func TestInfrastructureDNSAllUnavailableAndCancellation(t *testing.T) { | |
| 117 | 新增: server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 118 | 新增: w.WriteHeader(503) | |
| 119 | 新增: })) | |
| 120 | 新增: defer server.Close() | |
| 121 | 新增: servers := []string{server.URL + "/one", server.URL + "/two"} | |
| 122 | 新增: if ip, err := resolveInfrastructureWith(context.Background(), "example.com", server.Client(), servers); err == nil || ip.IsValid() || !strings.Contains(err.Error(), "未使用系统 DNS 回退") { | |
| 123 | 新增: t.Fatal("all failed resolvers must fail closed", ip, err) | |
| 124 | 新增: } | |
| 125 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 126 | 新增: cancel() | |
| 127 | 新增: if _, err := resolveInfrastructureWith(ctx, "example.com", server.Client(), servers); !errors.Is(err, context.Canceled) { | |
| 128 | 新增: t.Fatal("cancellation was not preserved", err) | |
| 129 | 新增: } | |
| 130 | 新增:} | |
| 131 | 新增: | |
| 132 | 新增:func TestRuntimeUsesRedundantBootstrapWithoutChangingBusinessDNS(t *testing.T) { | |
| 133 | 新增: s, _ := Load(t.TempDir()) | |
| 134 | 新增: if err := s.Import("test", "", []byte(testNodes), "source", 0, ""); err != nil { | |
| 135 | 新增: t.Fatal(err) | |
| 136 | 新增: } | |
| 137 | 新增: s.Selected = s.Sources[0].Nodes[0].ID | |
| 138 | 新增: wire, err := s.Runtime(t.TempDir()) | |
| 139 | 新增: if err != nil { | |
| 140 | 新增: t.Fatal(err) | |
| 141 | 新增: } | |
| 142 | 新增: var config struct { | |
| 143 | 新增: DNS struct { | |
| 144 | 新增: Default []string `yaml:"default-nameserver"` | |
| 145 | 新增: Proxy []string `yaml:"proxy-server-nameserver"` | |
| 146 | 新增: Names []string `yaml:"nameserver"` | |
| 147 | 新增: } `yaml:"dns"` | |
| 148 | 新增: Rules []string `yaml:"rules"` | |
| 149 | 新增: } | |
| 150 | 新增: if err := yaml.Unmarshal(wire, &config); err != nil { | |
| 151 | 新增: t.Fatal(err) | |
| 152 | 新增: } | |
| 153 | 新增: want := BootstrapDNSURLs() | |
| 154 | 新增: if len(want) < 2 || !reflect.DeepEqual(config.DNS.Default, want) || !reflect.DeepEqual(config.DNS.Proxy, want) { | |
| 155 | 新增: t.Fatal("node bootstrap did not receive both DNS services", config.DNS) | |
| 156 | 新增: } | |
| 157 | 新增: if !reflect.DeepEqual(config.DNS.Names, []string{"https://1.1.1.1/dns-query#" + Group}) || !reflect.DeepEqual(config.Rules, []string{"MATCH," + Group}) { | |
| 158 | 新增: t.Fatal("bootstrap fallback changed business routing", config) | |
| 159 | 新增: } | |
| 160 | 新增:} | |
| 161 | 新增: | |
| 162 | 新增:func TestInfrastructureDNSLiveIntegration(t *testing.T) { | |
| 163 | 新增: if os.Getenv("CAGE_TEST_BOOTSTRAP") != "1" { | |
| 164 | 新增: t.Skip("explicit host-network DNS test required") | |
| 165 | 新增: } | |
| 166 | 新增: ip, err := resolveInfrastructure(context.Background(), "example.com") | |
| 167 | 新增: if err != nil || !publicIP(ip) { | |
| 168 | 新增: t.Fatal("redundant encrypted DNS lookup failed", err) | |
| 169 | 新增: } | |
| 170 | 新增: // Inspect each service separately as a diagnostic. One may be unreachable | |
| 171 | 新增: // on this network; successful combined resolution is the required result. | |
| 172 | 新增: for _, endpoint := range BootstrapDNSURLs() { | |
| 173 | 新增: t.Run(endpoint, func(t *testing.T) { | |
| 174 | 新增: tr := &http.Transport{Proxy: nil} | |
| 175 | 新增: defer tr.CloseIdleConnections() | |
| 176 | 新增: client := &http.Client{Transport: tr, Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }} | |
| 177 | 新增: ip, err := resolveInfrastructureWith(context.Background(), "example.com", client, []string{endpoint}) | |
| 178 | 新增: if err != nil || !publicIP(ip) { | |
| 179 | 新增: t.Log("DNS endpoint unavailable on this network", err) | |
| 180 | 新增: return | |
| 181 | 新增: } | |
| 182 | 新增: t.Log("DNS endpoint returned a usable public IPv4") | |
| 183 | 新增: }) | |
| 184 | 新增: } | |
| 185 | 新增:} | |
| @@ -16,6 +16,12 @@ import ( | ||
| 16 | 16 | // PhysicalInterface uses the system's preferred reachable IPv4 hardware port. |
| 17 | 17 | // A route through utun is not a physical uplink, even when it is the default. |
| 18 | 18 | func PhysicalInterface(ctx context.Context) (string, error) { |
| 19 | 新增: if runtime.GOOS == "windows" { | |
| 20 | 新增: return windowsPhysicalInterface(ctx) | |
| 21 | 新增: } | |
| 22 | 新增: if runtime.GOOS == "linux" { | |
| 23 | 新增: return linuxPhysicalInterface(ctx) | |
| 24 | 新增: } | |
| 19 | 25 | if runtime.GOOS != "darwin" { |
| 20 | 26 | return "", errors.New("物理网卡识别当前支持 macOS") |
| 21 | 27 | } |
| @@ -0,0 +1,68 @@ | ||
| 1 | 新增:package managedproxy | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "net" | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "strconv" | |
| 10 | 新增: "strings" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func linuxPhysicalInterface(ctx context.Context) (string, error) { | |
| 14 | 新增: if err := ctx.Err(); err != nil { | |
| 15 | 新增: return "", err | |
| 16 | 新增: } | |
| 17 | 新增: routes, err := os.ReadFile("/proc/net/route") | |
| 18 | 新增: if err != nil { | |
| 19 | 新增: return "", errors.New("无法读取 Linux IPv4 路由,请检查主机网络后重试") | |
| 20 | 新增: } | |
| 21 | 新增: interfaces, err := net.Interfaces() | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: return "", err | |
| 24 | 新增: } | |
| 25 | 新增: usable := map[string]bool{} | |
| 26 | 新增: for _, iface := range interfaces { | |
| 27 | 新增: if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { | |
| 28 | 新增: continue | |
| 29 | 新增: } | |
| 30 | 新增: // PCI, USB and virtio NICs have a device parent. TUN, WireGuard, | |
| 31 | 新增: // bridges and container veth pairs do not. Virtio cloud NICs qualify. | |
| 32 | 新增: if _, err := os.Stat(filepath.Join("/sys/class/net", iface.Name, "device")); err != nil { | |
| 33 | 新增: continue | |
| 34 | 新增: } | |
| 35 | 新增: addresses, _ := iface.Addrs() | |
| 36 | 新增: for _, address := range addresses { | |
| 37 | 新增: ip, _, err := net.ParseCIDR(address.String()) | |
| 38 | 新增: if err == nil && ip.To4() != nil && !ip.IsLinkLocalUnicast() && !ip.IsUnspecified() { | |
| 39 | 新增: usable[iface.Name] = true | |
| 40 | 新增: } | |
| 41 | 新增: } | |
| 42 | 新增: } | |
| 43 | 新增: return selectLinuxPhysicalInterface(string(routes), usable) | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:func selectLinuxPhysicalInterface(routes string, usable map[string]bool) (string, error) { | |
| 47 | 新增: selected := "" | |
| 48 | 新增: var best uint64 | |
| 49 | 新增: for _, line := range strings.Split(routes, "\n") { | |
| 50 | 新增: fields := strings.Fields(line) | |
| 51 | 新增: if len(fields) < 8 || !usable[fields[0]] || fields[1] != "00000000" || fields[7] != "00000000" { | |
| 52 | 新增: continue | |
| 53 | 新增: } | |
| 54 | 新增: flags, flagErr := strconv.ParseUint(fields[3], 16, 32) | |
| 55 | 新增: metric, metricErr := strconv.ParseUint(fields[6], 10, 64) | |
| 56 | 新增: // Require an active default route; reject unreachable routes. | |
| 57 | 新增: if flagErr != nil || metricErr != nil || flags&1 == 0 || flags&0x200 != 0 { | |
| 58 | 新增: continue | |
| 59 | 新增: } | |
| 60 | 新增: if selected == "" || metric < best || metric == best && fields[0] < selected { | |
| 61 | 新增: selected, best = fields[0], metric | |
| 62 | 新增: } | |
| 63 | 新增: } | |
| 64 | 新增: if selected == "" { | |
| 65 | 新增: return "", errors.New("未找到带 IPv4 默认路由的物理或云主机网卡;Cage 外网保持关闭,请连接网络后重试") | |
| 66 | 新增: } | |
| 67 | 新增: return selected, nil | |
| 68 | 新增:} | |
| @@ -0,0 +1,31 @@ | ||
| 1 | 新增:package managedproxy | |
| 2 | 新增: | |
| 3 | 新增:import "testing" | |
| 4 | 新增: | |
| 5 | 新增:func TestLinuxPhysicalRouteSkipsTUNAndUsesLowestMetric(t *testing.T) { | |
| 6 | 新增: const routes = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT | |
| 7 | 新增:tun0 00000000 00000000 0001 0 0 0 00000000 0 0 0 | |
| 8 | 新增:ens5 00000000 0100000A 0003 0 0 100 00000000 0 0 0 | |
| 9 | 新增:eth1 00000000 0100000A 0003 0 0 20 00000000 0 0 0 | |
| 10 | 新增:eth2 00000000 0100000A 0203 0 0 1 00000000 0 0 0 | |
| 11 | 新增:eth3 00000000 0100000A 0002 0 0 1 00000000 0 0 0 | |
| 12 | 新增:eth4 00000000 0100000A 0003 0 0 1 0000FFFF 0 0 0 | |
| 13 | 新增:` | |
| 14 | 新增: for _, tc := range []struct { | |
| 15 | 新增: name string | |
| 16 | 新增: usable map[string]bool | |
| 17 | 新增: want string | |
| 18 | 新增: }{ | |
| 19 | 新增: {"physical metric", map[string]bool{"ens5": true, "eth1": true, "eth2": true, "eth3": true, "eth4": true}, "eth1"}, | |
| 20 | 新增: {"cloud virtio", map[string]bool{"ens5": true}, "ens5"}, | |
| 21 | 新增: {"disconnected physical interfaces", map[string]bool{}, ""}, | |
| 22 | 新增: {"reject and inactive routes", map[string]bool{"eth2": true, "eth3": true, "eth4": true}, ""}, | |
| 23 | 新增: } { | |
| 24 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 25 | 新增: got, err := selectLinuxPhysicalInterface(routes, tc.usable) | |
| 26 | 新增: if got != tc.want || (err != nil) != (tc.want == "") { | |
| 27 | 新增: t.Fatalf("got %q, %v; want %q", got, err, tc.want) | |
| 28 | 新增: } | |
| 29 | 新增: }) | |
| 30 | 新增: } | |
| 31 | 新增:} | |
| @@ -0,0 +1,255 @@ | ||
| 1 | 新增:package managedproxy | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "net" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "strconv" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "syscall" | |
| 15 | 新增: "time" | |
| 16 | 新增: | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 18 | 新增: "golang.org/x/sys/unix" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:type linuxCoreRecord struct { | |
| 22 | 新增: PID int `json:"pid"` | |
| 23 | 新增: Executable string `json:"executable"` | |
| 24 | 新增: Started uint64 `json:"started"` | |
| 25 | 新增: BootID string `json:"boot_id"` | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:func linuxCoreRecordPath(profile string) string { | |
| 29 | 新增: return filepath.Join(Dir(profile), "managed-process.json") | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:func identifyLinuxCore(pid int) (linuxCoreRecord, error) { | |
| 33 | 新增: var record linuxCoreRecord | |
| 34 | 新增: root := filepath.Join("/proc", strconv.Itoa(pid)) | |
| 35 | 新增: executable, err := os.Readlink(filepath.Join(root, "exe")) | |
| 36 | 新增: if err != nil { | |
| 37 | 新增: return record, err | |
| 38 | 新增: } | |
| 39 | 新增: started, err := linuxProcessStart(pid) | |
| 40 | 新增: if err != nil { | |
| 41 | 新增: return record, err | |
| 42 | 新增: } | |
| 43 | 新增: bootID, err := os.ReadFile("/proc/sys/kernel/random/boot_id") | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: return record, err | |
| 46 | 新增: } | |
| 47 | 新增: return linuxCoreRecord{PID: pid, Executable: executable, Started: started, BootID: strings.TrimSpace(string(bootID))}, nil | |
| 48 | 新增:} | |
| 49 | 新增: | |
| 50 | 新增:func linuxProcessStart(pid int) (uint64, error) { | |
| 51 | 新增: stat, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat")) | |
| 52 | 新增: if err != nil { | |
| 53 | 新增: return 0, err | |
| 54 | 新增: } | |
| 55 | 新增: // comm is parenthesized and may itself contain spaces and parentheses. | |
| 56 | 新增: end := strings.LastIndexByte(string(stat), ')') | |
| 57 | 新增: if end < 0 { | |
| 58 | 新增: return 0, errors.New("无法读取代理进程启动时间") | |
| 59 | 新增: } | |
| 60 | 新增: fields := strings.Fields(string(stat)[end+1:]) | |
| 61 | 新增: if len(fields) < 20 { | |
| 62 | 新增: return 0, errors.New("无法读取代理进程启动时间") | |
| 63 | 新增: } | |
| 64 | 新增: return strconv.ParseUint(fields[19], 10, 64) // field 22: starttime | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:// A pidfd pins the process while its recorded executable and start time are | |
| 68 | 新增:// checked. A PID recycled between verification and signaling remains harmless. | |
| 69 | 新增:func stopLinuxProcess(record linuxCoreRecord, core string) error { | |
| 70 | 新增: bootID, err := os.ReadFile("/proc/sys/kernel/random/boot_id") | |
| 71 | 新增: if err != nil { | |
| 72 | 新增: return err | |
| 73 | 新增: } | |
| 74 | 新增: if strings.TrimSpace(string(bootID)) != record.BootID { | |
| 75 | 新增: return nil // A process from a previous boot cannot still own the proxy. | |
| 76 | 新增: } | |
| 77 | 新增: resolved, err := filepath.EvalSymlinks(core) | |
| 78 | 新增: if err != nil { | |
| 79 | 新增: return err | |
| 80 | 新增: } | |
| 81 | 新增: if resolved != record.Executable { | |
| 82 | 新增: return errors.New("Cage 代理进程不属于当前安装目录") | |
| 83 | 新增: } | |
| 84 | 新增: fd, err := unix.PidfdOpen(record.PID, 0) | |
| 85 | 新增: if errors.Is(err, unix.ESRCH) { | |
| 86 | 新增: return nil | |
| 87 | 新增: } | |
| 88 | 新增: if err != nil { | |
| 89 | 新增: return fmt.Errorf("无法安全打开 Cage 代理进程(需要 Linux 5.3 或更新内核): %w", err) | |
| 90 | 新增: } | |
| 91 | 新增: defer unix.Close(fd) | |
| 92 | 新增: // Check start time before exe: a reused PID may belong to another user, | |
| 93 | 新增: // whose /proc/PID/exe we cannot read even though starttime is available. | |
| 94 | 新增: started, err := linuxProcessStart(record.PID) | |
| 95 | 新增: if os.IsNotExist(err) || err == nil && started != record.Started { | |
| 96 | 新增: return nil | |
| 97 | 新增: } | |
| 98 | 新增: if err != nil { | |
| 99 | 新增: return err | |
| 100 | 新增: } | |
| 101 | 新增: current, err := identifyLinuxCore(record.PID) | |
| 102 | 新增: if os.IsNotExist(err) { | |
| 103 | 新增: return nil | |
| 104 | 新增: } | |
| 105 | 新增: if err != nil { | |
| 106 | 新增: return err | |
| 107 | 新增: } | |
| 108 | 新增: if current != record { | |
| 109 | 新增: // The recorded process has exited and this PID now belongs to someone | |
| 110 | 新增: // else. Discard the stale record without signaling the new owner. | |
| 111 | 新增: return nil | |
| 112 | 新增: } | |
| 113 | 新增: for _, signal := range []unix.Signal{unix.SIGTERM, unix.SIGKILL} { | |
| 114 | 新增: if err := unix.PidfdSendSignal(fd, signal, nil, 0); errors.Is(err, unix.ESRCH) { | |
| 115 | 新增: return nil | |
| 116 | 新增: } else if err != nil { | |
| 117 | 新增: return err | |
| 118 | 新增: } | |
| 119 | 新增: deadline := time.Now().Add(5 * time.Second) | |
| 120 | 新增: for time.Now().Before(deadline) { | |
| 121 | 新增: poll := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} | |
| 122 | 新增: n, err := unix.Poll(poll, 100) | |
| 123 | 新增: if err != nil && !errors.Is(err, unix.EINTR) { | |
| 124 | 新增: return err | |
| 125 | 新增: } | |
| 126 | 新增: if n > 0 && poll[0].Revents&unix.POLLIN != 0 { | |
| 127 | 新增: return nil | |
| 128 | 新增: } | |
| 129 | 新增: } | |
| 130 | 新增: } | |
| 131 | 新增: return errors.New("Cage 代理进程未能及时停止") | |
| 132 | 新增:} | |
| 133 | 新增: | |
| 134 | 新增:func stopLinuxCore(profile string) error { | |
| 135 | 新增: path := linuxCoreRecordPath(profile) | |
| 136 | 新增: if err := host.CheckPrivateFile(path); os.IsNotExist(err) { | |
| 137 | 新增: return nil | |
| 138 | 新增: } else if err != nil { | |
| 139 | 新增: return err | |
| 140 | 新增: } | |
| 141 | 新增: b, err := os.ReadFile(path) | |
| 142 | 新增: if err != nil { | |
| 143 | 新增: return err | |
| 144 | 新增: } | |
| 145 | 新增: var record linuxCoreRecord | |
| 146 | 新增: if len(b) > 4096 || json.Unmarshal(b, &record) != nil || record.PID <= 1 || record.Started == 0 || record.BootID == "" { | |
| 147 | 新增: return errors.New("Cage 代理进程记录无效") | |
| 148 | 新增: } | |
| 149 | 新增: core, err := CorePath() | |
| 150 | 新增: if err != nil { | |
| 151 | 新增: return err | |
| 152 | 新增: } | |
| 153 | 新增: if err := stopLinuxProcess(record, core); err != nil { | |
| 154 | 新增: return err | |
| 155 | 新增: } | |
| 156 | 新增: _ = os.Remove(Socket(profile)) | |
| 157 | 新增: return os.Remove(path) | |
| 158 | 新增:} | |
| 159 | 新增: | |
| 160 | 新增:func startLinuxCore(ctx context.Context, profile string, s Store) error { | |
| 161 | 新增: name, err := PhysicalInterface(ctx) | |
| 162 | 新增: if err != nil { | |
| 163 | 新增: return err | |
| 164 | 新增: } | |
| 165 | 新增: path := filepath.Join(Dir(profile), "config.yaml") | |
| 166 | 新增: bound, _ := BoundInterface(path) | |
| 167 | 新增: if bound == name && Running(ctx, profile, s) { | |
| 168 | 新增: return nil | |
| 169 | 新增: } | |
| 170 | 新增: if err := Validate(ctx, profile, s); err != nil { | |
| 171 | 新增: return err | |
| 172 | 新增: } | |
| 173 | 新增: if err := stopLinuxCore(profile); err != nil { | |
| 174 | 新增: return err | |
| 175 | 新增: } | |
| 176 | 新增: l, err := net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", s.Port)) | |
| 177 | 新增: if err != nil { | |
| 178 | 新增: return errors.New("Cage 代理端口已被占用,请更换独立端口") | |
| 179 | 新增: } | |
| 180 | 新增: l.Close() | |
| 181 | 新增: core, err := CorePath() | |
| 182 | 新增: if err != nil { | |
| 183 | 新增: return err | |
| 184 | 新增: } | |
| 185 | 新增: if err := host.EnsurePrivateDir(filepath.Dir(Socket(profile))); err != nil { | |
| 186 | 新增: return err | |
| 187 | 新增: } | |
| 188 | 新增: b, err := s.Runtime(profile) | |
| 189 | 新增: if err != nil { | |
| 190 | 新增: return err | |
| 191 | 新增: } | |
| 192 | 新增: b, err = BindInterface(b, name) | |
| 193 | 新增: if err != nil { | |
| 194 | 新增: return err | |
| 195 | 新增: } | |
| 196 | 新增: if err := Write(path, b); err != nil { | |
| 197 | 新增: return err | |
| 198 | 新增: } | |
| 199 | 新增: _ = os.Remove(Socket(profile)) | |
| 200 | 新增: logPath := filepath.Join(Dir(profile), "runtime.log") | |
| 201 | 新增: if err := Write(logPath, nil); err != nil { | |
| 202 | 新增: return err | |
| 203 | 新增: } | |
| 204 | 新增: log, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND, 0600) | |
| 205 | 新增: if err != nil { | |
| 206 | 新增: return err | |
| 207 | 新增: } | |
| 208 | 新增: defer log.Close() | |
| 209 | 新增: cmd := exec.Command(core, "-d", Dir(profile), "-f", path) | |
| 210 | 新增: cmd.Env, cmd.Stdout, cmd.Stderr = coreEnvironment(Dir(profile)), log, log | |
| 211 | 新增: cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} | |
| 212 | 新增: if err := cmd.Start(); err != nil { | |
| 213 | 新增: return err | |
| 214 | 新增: } | |
| 215 | 新增: record, err := identifyLinuxCore(cmd.Process.Pid) | |
| 216 | 新增: if err == nil { | |
| 217 | 新增: var data []byte | |
| 218 | 新增: data, err = json.Marshal(record) | |
| 219 | 新增: if err == nil { | |
| 220 | 新增: err = Write(linuxCoreRecordPath(profile), data) | |
| 221 | 新增: } | |
| 222 | 新增: } | |
| 223 | 新增: if err != nil { | |
| 224 | 新增: _ = cmd.Process.Kill() | |
| 225 | 新增: _ = cmd.Wait() | |
| 226 | 新增: return err | |
| 227 | 新增: } | |
| 228 | 新增: exited := make(chan struct{}) | |
| 229 | 新增: go func() { _ = cmd.Wait(); close(exited) }() | |
| 230 | 新增: ticker := time.NewTicker(100 * time.Millisecond) | |
| 231 | 新增: defer ticker.Stop() | |
| 232 | 新增: timeout := time.NewTimer(15 * time.Second) | |
| 233 | 新增: defer timeout.Stop() | |
| 234 | 新增: for { | |
| 235 | 新增: select { | |
| 236 | 新增: case <-ctx.Done(): | |
| 237 | 新增: _ = stopLinuxCore(profile) | |
| 238 | 新增: return ctx.Err() | |
| 239 | 新增: case <-exited: | |
| 240 | 新增: _ = stopLinuxCore(profile) | |
| 241 | 新增: return errors.New("代理核心启动失败,请查看私有代理日志") | |
| 242 | 新增: case <-timeout.C: | |
| 243 | 新增: _ = stopLinuxCore(profile) | |
| 244 | 新增: return errors.New("代理核心启动超时,请查看私有代理日志") | |
| 245 | 新增: case <-ticker.C: | |
| 246 | 新增: if Running(ctx, profile, s) { | |
| 247 | 新增: if err := host.ProtectFile(Socket(profile)); err != nil { | |
| 248 | 新增: _ = stopLinuxCore(profile) | |
| 249 | 新增: return err | |
| 250 | 新增: } | |
| 251 | 新增: return nil | |
| 252 | 新增: } | |
| 253 | 新增: } | |
| 254 | 新增: } | |
| 255 | 新增:} | |
| @@ -0,0 +1,210 @@ | ||
| 1 | 新增:package managedproxy | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "fmt" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net" | |
| 9 | 新增: "net/http" | |
| 10 | 新增: "net/http/httptest" | |
| 11 | 新增: "net/url" | |
| 12 | 新增: "os" | |
| 13 | 新增: "os/exec" | |
| 14 | 新增: "strings" | |
| 15 | 新增: "sync/atomic" | |
| 16 | 新增: "testing" | |
| 17 | 新增: "time" | |
| 18 | 新增: | |
| 19 | 新增: "golang.org/x/sys/unix" | |
| 20 | 新增:) | |
| 21 | 新增: | |
| 22 | 新增:// Run from beside the bundled mihomo with CAGE_LINUX_INTEGRATION=1. A local | |
| 23 | 新增:// upstream proxy proves routing and fail-closed behavior without external I/O. | |
| 24 | 新增:func TestLinuxBundledProxyLifecycle(t *testing.T) { | |
| 25 | 新增: if os.Getenv("CAGE_LINUX_INTEGRATION") != "1" { | |
| 26 | 新增: t.Skip("requires a bundled Linux mihomo and host network interfaces") | |
| 27 | 新增: } | |
| 28 | 新增: profile := t.TempDir() | |
| 29 | 新增: s, err := Load(profile) | |
| 30 | 新增: if err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: listener, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 34 | 新增: if err != nil { | |
| 35 | 新增: t.Fatal(err) | |
| 36 | 新增: } | |
| 37 | 新增: s.Port = listener.Addr().(*net.TCPAddr).Port | |
| 38 | 新增: listener.Close() | |
| 39 | 新增: var targetRequests, proxyRequests atomic.Int32 | |
| 40 | 新增: target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { | |
| 41 | 新增: targetRequests.Add(1) | |
| 42 | 新增: w.Header().Set("Connection", "close") | |
| 43 | 新增: _, _ = io.WriteString(w, "local-target-response") | |
| 44 | 新增: })) | |
| 45 | 新增: defer target.Close() | |
| 46 | 新增: targetAddress := strings.TrimPrefix(target.URL, "http://") | |
| 47 | 新增: upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 48 | 新增: proxyRequests.Add(1) | |
| 49 | 新增: if r.Method != http.MethodConnect || r.Host != targetAddress { | |
| 50 | 新增: t.Errorf("upstream received unexpected request %s %q", r.Method, r.Host) | |
| 51 | 新增: http.Error(w, "refused", http.StatusForbidden) | |
| 52 | 新增: return | |
| 53 | 新增: } | |
| 54 | 新增: remote, err := net.DialTimeout("tcp4", targetAddress, time.Second) | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: http.Error(w, "target unavailable", http.StatusBadGateway) | |
| 57 | 新增: return | |
| 58 | 新增: } | |
| 59 | 新增: defer remote.Close() | |
| 60 | 新增: client, buffered, err := w.(http.Hijacker).Hijack() | |
| 61 | 新增: if err != nil { | |
| 62 | 新增: return | |
| 63 | 新增: } | |
| 64 | 新增: defer client.Close() | |
| 65 | 新增: _, _ = io.WriteString(client, "HTTP/1.1 200 Connection Established\r\n\r\n") | |
| 66 | 新增: go func() { _, _ = io.Copy(remote, buffered); _ = remote.Close() }() | |
| 67 | 新增: _, _ = io.Copy(client, remote) | |
| 68 | 新增: })) | |
| 69 | 新增: defer upstream.Close() | |
| 70 | 新增: upstreamPort := upstream.Listener.Addr().(*net.TCPAddr).Port | |
| 71 | 新增: if err := s.Import("local smoke node", "", []byte(fmt.Sprintf("proxies:\n - {name: smoke, type: http, server: 127.0.0.1, port: %d}\n", upstreamPort)), "smoke", 0, ""); err != nil { | |
| 72 | 新增: t.Fatal(err) | |
| 73 | 新增: } | |
| 74 | 新增: s.Selected = s.Sources[0].Nodes[0].ID | |
| 75 | 新增: ctx, cancel := context.WithTimeout(context.Background(), time.Minute) | |
| 76 | 新增: defer cancel() | |
| 77 | 新增: t.Cleanup(func() { | |
| 78 | 新增: if err := Stop(profile); err != nil { | |
| 79 | 新增: t.Error(err) | |
| 80 | 新增: } | |
| 81 | 新增: }) | |
| 82 | 新增: readRecord := func() linuxCoreRecord { | |
| 83 | 新增: t.Helper() | |
| 84 | 新增: b, err := os.ReadFile(linuxCoreRecordPath(profile)) | |
| 85 | 新增: var record linuxCoreRecord | |
| 86 | 新增: if err != nil || json.Unmarshal(b, &record) != nil { | |
| 87 | 新增: t.Fatal("missing proxy process record", err) | |
| 88 | 新增: } | |
| 89 | 新增: return record | |
| 90 | 新增: } | |
| 91 | 新增: if err := Start(ctx, profile, s); err != nil { | |
| 92 | 新增: t.Fatal(err) | |
| 93 | 新增: } | |
| 94 | 新增: first := readRecord() | |
| 95 | 新增: if !Running(ctx, profile, s) { | |
| 96 | 新增: t.Fatal("bundled core did not expose its authenticated local state") | |
| 97 | 新增: } | |
| 98 | 新增: if info, err := os.Stat(Socket(profile)); err != nil || info.Mode().Perm() != 0600 { | |
| 99 | 新增: t.Fatal("proxy control socket is not private", err) | |
| 100 | 新增: } | |
| 101 | 新增: if err := Start(ctx, profile, s); err != nil { | |
| 102 | 新增: t.Fatal(err) | |
| 103 | 新增: } | |
| 104 | 新增: if readRecord() != first { | |
| 105 | 新增: t.Fatal("idempotent start replaced the running core") | |
| 106 | 新增: } | |
| 107 | 新增: proxyURL, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", s.Port)) | |
| 108 | 新增: proxyURL.User = url.UserPassword("cage", s.Auth) | |
| 109 | 新增: transport := &http.Transport{Proxy: http.ProxyURL(proxyURL), DisableKeepAlives: true} | |
| 110 | 新增: defer transport.CloseIdleConnections() | |
| 111 | 新增: client := &http.Client{Transport: transport, Timeout: 5 * time.Second} | |
| 112 | 新增: res, err := client.Get(target.URL + "/cage-linux-smoke") | |
| 113 | 新增: if err != nil { | |
| 114 | 新增: t.Fatal("selected proxy did not carry the request", err) | |
| 115 | 新增: } | |
| 116 | 新增: body, err := io.ReadAll(res.Body) | |
| 117 | 新增: res.Body.Close() | |
| 118 | 新增: if err != nil || string(body) != "local-target-response" || proxyRequests.Load() != 1 || targetRequests.Load() != 1 { | |
| 119 | 新增: t.Fatal("request bypassed the selected proxy", err) | |
| 120 | 新增: } | |
| 121 | 新增: upstream.Close() | |
| 122 | 新增: res, err = client.Get(target.URL + "/cage-linux-smoke") | |
| 123 | 新增: if err == nil { | |
| 124 | 新增: body, _ = io.ReadAll(res.Body) | |
| 125 | 新增: res.Body.Close() | |
| 126 | 新增: if res.StatusCode == http.StatusOK || strings.Contains(string(body), "local-target-response") { | |
| 127 | 新增: t.Fatal("core fell back to direct after the upstream stopped") | |
| 128 | 新增: } | |
| 129 | 新增: } | |
| 130 | 新增: if targetRequests.Load() != 1 { | |
| 131 | 新增: t.Fatal("target was contacted directly after the upstream stopped") | |
| 132 | 新增: } | |
| 133 | 新增: if err := Stop(profile); err != nil { | |
| 134 | 新增: t.Fatal(err) | |
| 135 | 新增: } | |
| 136 | 新增: if Running(ctx, profile, s) { | |
| 137 | 新增: t.Fatal("core still responds after stop") | |
| 138 | 新增: } | |
| 139 | 新增: if _, err := os.Stat(linuxCoreRecordPath(profile)); !os.IsNotExist(err) { | |
| 140 | 新增: t.Fatal("stop retained its process record", err) | |
| 141 | 新增: } | |
| 142 | 新增: if err := Start(ctx, profile, s); err != nil { | |
| 143 | 新增: t.Fatal("could not restart bundled core", err) | |
| 144 | 新增: } | |
| 145 | 新增: if readRecord() == first { | |
| 146 | 新增: t.Fatal("restart reused the old process identity") | |
| 147 | 新增: } | |
| 148 | 新增: second := readRecord() | |
| 149 | 新增: fd, err := unix.PidfdOpen(second.PID, 0) | |
| 150 | 新增: if err != nil { | |
| 151 | 新增: t.Fatal(err) | |
| 152 | 新增: } | |
| 153 | 新增: defer unix.Close(fd) | |
| 154 | 新增: if err := unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); err != nil { | |
| 155 | 新增: t.Fatal(err) | |
| 156 | 新增: } | |
| 157 | 新增: if n, err := unix.Poll([]unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}, 5000); err != nil || n == 0 { | |
| 158 | 新增: t.Fatal("core did not exit after simulated crash", err) | |
| 159 | 新增: } | |
| 160 | 新增: if err := Start(ctx, profile, s); err != nil { | |
| 161 | 新增: t.Fatal("stale record prevented restart after a core crash", err) | |
| 162 | 新增: } | |
| 163 | 新增: if readRecord() == second || !Running(ctx, profile, s) { | |
| 164 | 新增: t.Fatal("core did not recover after a crash") | |
| 165 | 新增: } | |
| 166 | 新增:} | |
| 167 | 新增: | |
| 168 | 新增:func TestLinuxCoreStopPinsAndChecksProcessIdentity(t *testing.T) { | |
| 169 | 新增: cmd := exec.Command("sleep", "60") | |
| 170 | 新增: if err := cmd.Start(); err != nil { | |
| 171 | 新增: t.Fatal(err) | |
| 172 | 新增: } | |
| 173 | 新增: done := make(chan struct{}) | |
| 174 | 新增: go func() { _ = cmd.Wait(); close(done) }() | |
| 175 | 新增: t.Cleanup(func() { _ = cmd.Process.Kill(); <-done }) | |
| 176 | 新增: record, err := identifyLinuxCore(cmd.Process.Pid) | |
| 177 | 新增: if err != nil { | |
| 178 | 新增: t.Fatal(err) | |
| 179 | 新增: } | |
| 180 | 新增: stale := record | |
| 181 | 新增: stale.Started++ | |
| 182 | 新增: if err := stopLinuxProcess(stale, record.Executable); err != nil { | |
| 183 | 新增: t.Fatal("stale record prevented recovery", err) | |
| 184 | 新增: } | |
| 185 | 新增: if err := unix.Kill(cmd.Process.Pid, 0); err != nil { | |
| 186 | 新增: t.Fatal("stopped a process with a different identity", err) | |
| 187 | 新增: } | |
| 188 | 新增: if err := stopLinuxProcess(record, "/proc/self/exe"); err == nil { | |
| 189 | 新增: t.Fatal("accepted a different executable") | |
| 190 | 新增: } | |
| 191 | 新增: previousBoot := record | |
| 192 | 新增: previousBoot.BootID = "a-previous-boot" | |
| 193 | 新增: if err := stopLinuxProcess(previousBoot, record.Executable); err != nil { | |
| 194 | 新增: t.Fatal("could not discard previous boot record", err) | |
| 195 | 新增: } | |
| 196 | 新增: if err := unix.Kill(cmd.Process.Pid, 0); err != nil { | |
| 197 | 新增: t.Fatal("stopped a process referenced by a previous boot", err) | |
| 198 | 新增: } | |
| 199 | 新增: if err := stopLinuxProcess(record, record.Executable); err != nil { | |
| 200 | 新增: t.Fatal(err) | |
| 201 | 新增: } | |
| 202 | 新增: select { | |
| 203 | 新增: case <-done: | |
| 204 | 新增: case <-time.After(2 * time.Second): | |
| 205 | 新增: t.Fatal("proxy process was not reaped") | |
| 206 | 新增: } | |
| 207 | 新增: if err := stopLinuxProcess(record, record.Executable); err != nil { | |
| 208 | 新增: t.Fatal("stopping an exited process should succeed", err) | |
| 209 | 新增: } | |
| 210 | 新增:} | |
| @@ -0,0 +1,16 @@ | ||
| 1 | 新增://go:build !linux | |
| 2 | 新增: | |
| 3 | 新增:package managedproxy | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func startLinuxCore(context.Context, string, Store) error { | |
| 11 | 新增: return errors.New("Linux core is unavailable on this platform") | |
| 12 | 新增:} | |
| 13 | 新增:func stopLinuxCore(string) error { return errors.New("Linux core is unavailable on this platform") } | |
| 14 | 新增:func linuxPhysicalInterface(context.Context) (string, error) { | |
| 15 | 新增: return "", errors.New("Linux interface is unavailable on this platform") | |
| 16 | 新增:} | |
| @@ -0,0 +1,17 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package managedproxy | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func coreEnvironment(dir string) []string { return []string{"PATH=/usr/bin:/bin", "HOME=" + dir} } | |
| 11 | 新增:func startWindowsCore(context.Context, string, Store) error { | |
| 12 | 新增: return errors.New("Windows core is unavailable on this platform") | |
| 13 | 新增:} | |
| 14 | 新增:func stopWindowsCore(string) error { return errors.New("Windows core is unavailable on this platform") } | |
| 15 | 新增:func windowsPhysicalInterface(context.Context) (string, error) { | |
| 16 | 新增: return "", errors.New("Windows interface is unavailable on this platform") | |
| 17 | 新增:} | |
| @@ -0,0 +1,244 @@ | ||
| 1 | 新增:package managedproxy | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "net" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "syscall" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 17 | 新增: "golang.org/x/sys/windows" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:type windowsCoreRecord struct { | |
| 21 | 新增: PID uint32 `json:"pid"` | |
| 22 | 新增: Executable string `json:"executable"` | |
| 23 | 新增: Created int64 `json:"created"` | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:func windowsCoreRecordPath(profile string) string { | |
| 27 | 新增: return filepath.Join(Dir(profile), "managed-process.json") | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:func coreEnvironment(dir string) []string { | |
| 31 | 新增: env := []string{"HOME=" + dir, "USERPROFILE=" + dir} | |
| 32 | 新增: for _, key := range []string{"SystemRoot", "WINDIR", "TEMP", "TMP"} { | |
| 33 | 新增: if value := os.Getenv(key); value != "" { | |
| 34 | 新增: env = append(env, key+"="+value) | |
| 35 | 新增: } | |
| 36 | 新增: } | |
| 37 | 新增: return env | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:func identifyCore(handle windows.Handle) (string, int64, error) { | |
| 41 | 新增: name := make([]uint16, 32768) | |
| 42 | 新增: size := uint32(len(name)) | |
| 43 | 新增: if err := windows.QueryFullProcessImageName(handle, 0, &name[0], &size); err != nil { | |
| 44 | 新增: return "", 0, err | |
| 45 | 新增: } | |
| 46 | 新增: var created, exited, kernel, user windows.Filetime | |
| 47 | 新增: if err := windows.GetProcessTimes(handle, &created, &exited, &kernel, &user); err != nil { | |
| 48 | 新增: return "", 0, err | |
| 49 | 新增: } | |
| 50 | 新增: return windows.UTF16ToString(name[:size]), created.Nanoseconds(), nil | |
| 51 | 新增:} | |
| 52 | 新增: | |
| 53 | 新增:// Stop opens one process handle and validates both its image and creation time | |
| 54 | 新增:// before termination. A reused PID cannot terminate an unrelated application. | |
| 55 | 新增:func stopWindowsCore(profile string) error { | |
| 56 | 新增: path := windowsCoreRecordPath(profile) | |
| 57 | 新增: if _, err := os.Lstat(path); os.IsNotExist(err) { | |
| 58 | 新增: return nil | |
| 59 | 新增: } | |
| 60 | 新增: if err := host.CheckPrivateFile(path); err != nil { | |
| 61 | 新增: return err | |
| 62 | 新增: } | |
| 63 | 新增: b, err := os.ReadFile(path) | |
| 64 | 新增: if err != nil { | |
| 65 | 新增: return err | |
| 66 | 新增: } | |
| 67 | 新增: var record windowsCoreRecord | |
| 68 | 新增: if len(b) > 4096 || json.Unmarshal(b, &record) != nil || record.PID == 0 || record.Created == 0 { | |
| 69 | 新增: return errors.New("Cage 代理进程记录无效") | |
| 70 | 新增: } | |
| 71 | 新增: core, err := CorePath() | |
| 72 | 新增: if err != nil { | |
| 73 | 新增: return err | |
| 74 | 新增: } | |
| 75 | 新增: if !strings.EqualFold(filepath.Clean(core), filepath.Clean(record.Executable)) { | |
| 76 | 新增: return errors.New("Cage 代理进程不属于当前安装目录") | |
| 77 | 新增: } | |
| 78 | 新增: handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.PROCESS_TERMINATE|windows.SYNCHRONIZE, false, record.PID) | |
| 79 | 新增: if errors.Is(err, windows.ERROR_INVALID_PARAMETER) { | |
| 80 | 新增: return os.Remove(path) | |
| 81 | 新增: } | |
| 82 | 新增: if err != nil { | |
| 83 | 新增: return err | |
| 84 | 新增: } | |
| 85 | 新增: defer windows.CloseHandle(handle) | |
| 86 | 新增: image, created, err := identifyCore(handle) | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: return err | |
| 89 | 新增: } | |
| 90 | 新增: if !strings.EqualFold(filepath.Clean(image), filepath.Clean(record.Executable)) || created != record.Created { | |
| 91 | 新增: return errors.New("代理进程身份已变化,未停止其他进程") | |
| 92 | 新增: } | |
| 93 | 新增: var code uint32 | |
| 94 | 新增: if err := windows.GetExitCodeProcess(handle, &code); err != nil { | |
| 95 | 新增: return err | |
| 96 | 新增: } | |
| 97 | 新增: if code == 259 { | |
| 98 | 新增: if err := windows.TerminateProcess(handle, 0); err != nil { | |
| 99 | 新增: return err | |
| 100 | 新增: } | |
| 101 | 新增: state, err := windows.WaitForSingleObject(handle, 5000) | |
| 102 | 新增: if err != nil { | |
| 103 | 新增: return err | |
| 104 | 新增: } | |
| 105 | 新增: if state != windows.WAIT_OBJECT_0 { | |
| 106 | 新增: return errors.New("Cage 代理进程未能及时停止") | |
| 107 | 新增: } | |
| 108 | 新增: } | |
| 109 | 新增: _ = os.Remove(Socket(profile)) | |
| 110 | 新增: return os.Remove(path) | |
| 111 | 新增:} | |
| 112 | 新增: | |
| 113 | 新增:func startWindowsCore(ctx context.Context, profile string, s Store) error { | |
| 114 | 新增: name, err := PhysicalInterface(ctx) | |
| 115 | 新增: if err != nil { | |
| 116 | 新增: return err | |
| 117 | 新增: } | |
| 118 | 新增: path := filepath.Join(Dir(profile), "config.yaml") | |
| 119 | 新增: bound, _ := BoundInterface(path) | |
| 120 | 新增: if bound == name && Running(ctx, profile, s) { | |
| 121 | 新增: return nil | |
| 122 | 新增: } | |
| 123 | 新增: if err := Validate(ctx, profile, s); err != nil { | |
| 124 | 新增: return err | |
| 125 | 新增: } | |
| 126 | 新增: if err := stopWindowsCore(profile); err != nil { | |
| 127 | 新增: return err | |
| 128 | 新增: } | |
| 129 | 新增: l, err := net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", s.Port)) | |
| 130 | 新增: if err != nil { | |
| 131 | 新增: return errors.New("Cage 代理端口已被占用,请更换独立端口") | |
| 132 | 新增: } | |
| 133 | 新增: l.Close() | |
| 134 | 新增: core, err := CorePath() | |
| 135 | 新增: if err != nil { | |
| 136 | 新增: return err | |
| 137 | 新增: } | |
| 138 | 新增: if err := host.EnsurePrivateDir(filepath.Dir(Socket(profile))); err != nil { | |
| 139 | 新增: return err | |
| 140 | 新增: } | |
| 141 | 新增: b, err := s.Runtime(profile) | |
| 142 | 新增: if err != nil { | |
| 143 | 新增: return err | |
| 144 | 新增: } | |
| 145 | 新增: b, err = BindInterface(b, name) | |
| 146 | 新增: if err != nil { | |
| 147 | 新增: return err | |
| 148 | 新增: } | |
| 149 | 新增: if err := Write(path, b); err != nil { | |
| 150 | 新增: return err | |
| 151 | 新增: } | |
| 152 | 新增: _ = os.Remove(Socket(profile)) | |
| 153 | 新增: logPath := filepath.Join(Dir(profile), "runtime.log") | |
| 154 | 新增: if err := Write(logPath, nil); err != nil { | |
| 155 | 新增: return err | |
| 156 | 新增: } | |
| 157 | 新增: log, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND, 0600) | |
| 158 | 新增: if err != nil { | |
| 159 | 新增: return err | |
| 160 | 新增: } | |
| 161 | 新增: defer log.Close() | |
| 162 | 新增: cmd := exec.Command(core, "-d", Dir(profile), "-f", path) | |
| 163 | 新增: cmd.Env, cmd.Stdout, cmd.Stderr = coreEnvironment(Dir(profile)), log, log | |
| 164 | 新增: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NEW_PROCESS_GROUP | windows.DETACHED_PROCESS} | |
| 165 | 新增: if err := cmd.Start(); err != nil { | |
| 166 | 新增: return err | |
| 167 | 新增: } | |
| 168 | 新增: handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(cmd.Process.Pid)) | |
| 169 | 新增: if err != nil { | |
| 170 | 新增: _ = cmd.Process.Kill() | |
| 171 | 新增: _ = cmd.Wait() | |
| 172 | 新增: return err | |
| 173 | 新增: } | |
| 174 | 新增: image, created, err := identifyCore(handle) | |
| 175 | 新增: windows.CloseHandle(handle) | |
| 176 | 新增: if err != nil { | |
| 177 | 新增: _ = cmd.Process.Kill() | |
| 178 | 新增: _ = cmd.Wait() | |
| 179 | 新增: return err | |
| 180 | 新增: } | |
| 181 | 新增: record, _ := json.Marshal(windowsCoreRecord{PID: uint32(cmd.Process.Pid), Executable: image, Created: created}) | |
| 182 | 新增: if err := Write(windowsCoreRecordPath(profile), record); err != nil { | |
| 183 | 新增: _ = cmd.Process.Kill() | |
| 184 | 新增: _ = cmd.Wait() | |
| 185 | 新增: return err | |
| 186 | 新增: } | |
| 187 | 新增: go func() { _ = cmd.Wait() }() | |
| 188 | 新增: ticker := time.NewTicker(100 * time.Millisecond) | |
| 189 | 新增: defer ticker.Stop() | |
| 190 | 新增: timeout := time.NewTimer(15 * time.Second) | |
| 191 | 新增: defer timeout.Stop() | |
| 192 | 新增: for { | |
| 193 | 新增: select { | |
| 194 | 新增: case <-ctx.Done(): | |
| 195 | 新增: _ = stopWindowsCore(profile) | |
| 196 | 新增: return ctx.Err() | |
| 197 | 新增: case <-timeout.C: | |
| 198 | 新增: _ = stopWindowsCore(profile) | |
| 199 | 新增: return errors.New("代理核心启动超时,请查看私有代理日志") | |
| 200 | 新增: case <-ticker.C: | |
| 201 | 新增: if Running(ctx, profile, s) { | |
| 202 | 新增: if err := host.ProtectFile(Socket(profile)); err != nil { | |
| 203 | 新增: _ = stopWindowsCore(profile) | |
| 204 | 新增: return err | |
| 205 | 新增: } | |
| 206 | 新增: return nil | |
| 207 | 新增: } | |
| 208 | 新增: } | |
| 209 | 新增: } | |
| 210 | 新增:} | |
| 211 | 新增: | |
| 212 | 新增:func windowsPhysicalInterface(ctx context.Context) (string, error) { | |
| 213 | 新增: ctx, cancel := context.WithTimeout(ctx, 10*time.Second) | |
| 214 | 新增: defer cancel() | |
| 215 | 新增: // Select only hardware adapters with a usable IPv4 default route. Virtual | |
| 216 | 新增: // VPN/TUN adapters never become the proxy's underlying host connection. | |
| 217 | 新增: const script = `$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); $candidates=@(Get-NetAdapter -Physical | Where-Object Status -eq 'Up' | ForEach-Object { $a=$_; $ip=Get-NetIPAddress -InterfaceIndex $a.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.AddressState -eq 'Preferred' -and $_.IPAddress -notlike '169.254.*' }; $routes=Get-NetRoute -InterfaceIndex $a.ifIndex -AddressFamily IPv4 -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue; if ($ip) { $routes | Where-Object { $_.NextHop -ne '0.0.0.0' } | ForEach-Object { [pscustomobject]@{Name=$a.Name;Index=$a.ifIndex;Metric=($_.RouteMetric+$_.InterfaceMetric)} } } }); $best=$candidates | Sort-Object Metric,Index | Select-Object -First 1; if (!$best) { exit 2 }; $best | ConvertTo-Json -Compress` | |
| 218 | 新增: root := os.Getenv("SystemRoot") | |
| 219 | 新增: if root == "" { | |
| 220 | 新增: root = `C:\Windows` | |
| 221 | 新增: } | |
| 222 | 新增: cmd := exec.CommandContext(ctx, filepath.Join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), "-NoProfile", "-NonInteractive", "-Command", script) | |
| 223 | 新增: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} | |
| 224 | 新增: out, err := cmd.Output() | |
| 225 | 新增: if err != nil { | |
| 226 | 新增: var exited *exec.ExitError | |
| 227 | 新增: if errors.As(err, &exited) && exited.ExitCode() == 2 { | |
| 228 | 新增: return "", errors.New("未找到可用的物理 IPv4 网卡。请连接以太网或 Wi-Fi;仅有虚拟网卡的 Windows 虚拟机和云主机暂不可用。Cage 外网保持关闭") | |
| 229 | 新增: } | |
| 230 | 新增: return "", errors.New("无法读取 Windows 物理网卡信息,请确认系统网络服务正常后重试;Cage 外网保持关闭") | |
| 231 | 新增: } | |
| 232 | 新增: var selected struct { | |
| 233 | 新增: Name string | |
| 234 | 新增: Index int | |
| 235 | 新增: } | |
| 236 | 新增: if json.Unmarshal(out, &selected) != nil || selected.Name == "" || selected.Index <= 0 { | |
| 237 | 新增: return "", errors.New("Windows 物理网卡信息无效") | |
| 238 | 新增: } | |
| 239 | 新增: iface, err := net.InterfaceByIndex(selected.Index) | |
| 240 | 新增: if err != nil || iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { | |
| 241 | 新增: return "", errors.New("物理网卡已断开,请重试") | |
| 242 | 新增: } | |
| 243 | 新增: return iface.Name, nil | |
| 244 | 新增:} | |
| @@ -11,9 +11,11 @@ import ( | ||
| 11 | 11 | "io" |
| 12 | 12 | "os" |
| 13 | 13 | "path/filepath" |
| 14 | 新增: "runtime" | |
| 14 | 15 | "strings" |
| 15 | 16 | "time" |
| 16 | 17 | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 17 | 19 | "go.yaml.in/yaml/v3" |
| 18 | 20 | ) |
| 19 | 21 | |
| @@ -57,6 +59,9 @@ func Token() string { | ||
| 57 | 59 | func Dir(profile string) string { return filepath.Join(profile, "proxy") } |
| 58 | 60 | func Socket(profile string) string { |
| 59 | 61 | h := sha256.Sum256([]byte(filepath.Clean(profile))) |
| 62 | 新增: if runtime.GOOS == "windows" { | |
| 63 | 新增: return filepath.Join(os.TempDir(), fmt.Sprintf("cage-proxy-%x", h[:8]), "control.sock") | |
| 64 | 新增: } | |
| 60 | 65 | return filepath.Join("/tmp", fmt.Sprintf("cage-proxy-%d-%x", os.Getuid(), h[:8]), "control.sock") |
| 61 | 66 | } |
| 62 | 67 | func Load(profile string) (Store, error) { |
| @@ -79,7 +84,7 @@ func Load(profile string) (Store, error) { | ||
| 79 | 84 | return s, nil |
| 80 | 85 | } |
| 81 | 86 | func Write(path string, data []byte) error { |
| 82 | 删除: if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { | |
| 87 | 新增: if err := host.EnsurePrivateDir(filepath.Dir(path)); err != nil { | |
| 83 | 88 | return err |
| 84 | 89 | } |
| 85 | 90 | f, err := os.CreateTemp(filepath.Dir(path), ".proxy-*") |
| @@ -87,7 +92,7 @@ func Write(path string, data []byte) error { | ||
| 87 | 92 | return err |
| 88 | 93 | } |
| 89 | 94 | defer os.Remove(f.Name()) |
| 90 | 删除: if err = f.Chmod(0600); err == nil { | |
| 95 | 新增: if err = host.ProtectFile(f.Name()); err == nil { | |
| 91 | 96 | _, err = f.Write(data) |
| 92 | 97 | } |
| 93 | 98 | if err == nil { |
| @@ -270,7 +275,7 @@ func (s Store) Runtime(profile string) ([]byte, error) { | ||
| 270 | 275 | } |
| 271 | 276 | // Infrastructure DNS bootstraps only the core's server domains. Guest DNS |
| 272 | 277 | // remains behind Cage Egress, and there is no host-system resolver fallback. |
| 273 | 删除: dns := map[string]any{"enable": true, "ipv6": false, "use-hosts": false, "use-system-hosts": false, "default-nameserver": []string{"https://1.1.1.1/dns-query"}, "proxy-server-nameserver": []string{"https://1.1.1.1/dns-query"}, "nameserver": []string{"https://1.1.1.1/dns-query#" + Group}} | |
| 278 | 新增: dns := map[string]any{"enable": true, "ipv6": false, "use-hosts": false, "use-system-hosts": false, "default-nameserver": BootstrapDNSURLs(), "proxy-server-nameserver": BootstrapDNSURLs(), "nameserver": []string{"https://1.1.1.1/dns-query#" + Group}} | |
| 274 | 279 | config := map[string]any{"mixed-port": s.Port, "bind-address": "127.0.0.1", "allow-lan": false, "authentication": []string{"cage:" + s.Auth}, "skip-auth-prefixes": []string{}, "mode": "rule", "ipv6": false, "log-level": "warning", "find-process-mode": "off", "external-controller-unix": Socket(profile), "tun": map[string]any{"enable": false}, "dns": dns, "geo-auto-update": false, "profile": map[string]any{"store-selected": false}, "proxies": proxies, "proxy-groups": []any{map[string]any{"name": Group, "type": "select", "proxies": []string{s.Selected}}}, "rules": []string{"MATCH," + Group}} |
| 275 | 280 | return yaml.Marshal(config) |
| 276 | 281 | } |
| @@ -13,6 +13,7 @@ import ( | ||
| 13 | 13 | "strings" |
| 14 | 14 | "testing" |
| 15 | 15 | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 16 | 17 | "go.yaml.in/yaml/v3" |
| 17 | 18 | ) |
| 18 | 19 | |
| @@ -140,9 +141,8 @@ func TestImportCompilesOnlyOwnedNetworkBoundary(t *testing.T) { | ||
| 140 | 141 | if err = s.Save(profile); err != nil { |
| 141 | 142 | t.Fatal(err) |
| 142 | 143 | } |
| 143 | 删除: info, _ := os.Stat(filepath.Join(Dir(profile), "sources.json")) | |
| 144 | 删除: if info.Mode().Perm() != 0600 { | |
| 145 | 删除: t.Fatal("source credentials not private") | |
| 144 | 新增: if err := host.CheckPrivateFile(filepath.Join(Dir(profile), "sources.json")); err != nil { | |
| 145 | 新增: t.Fatalf("source credentials not private: %v", err) | |
| 146 | 146 | } |
| 147 | 147 | loaded, err := Load(profile) |
| 148 | 148 | if err != nil || loaded.Endpoint() != s.Endpoint() { |
| @@ -0,0 +1,119 @@ | ||
| 1 | 新增://go:build e2e | |
| 2 | 新增: | |
| 3 | 新增:package vm | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strconv" | |
| 12 | 新增: "testing" | |
| 13 | 新增: "time" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:// An isolated VM and X11 application verify actual PNG ownership, key delivery, | |
| 17 | 新增:// large INCR transfers, repeated paste, and private terminal attachment storage. | |
| 18 | 新增:func TestImageInput(t *testing.T) { | |
| 19 | 新增: for _, key := range []string{"http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "all_proxy"} { | |
| 20 | 新增: t.Setenv(key, "") | |
| 21 | 新增: } | |
| 22 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) | |
| 23 | 新增: defer cancel() | |
| 24 | 新增: l := newTestLima(t) | |
| 25 | 新增: state := t.TempDir() | |
| 26 | 新增: t.Setenv("AGENT_VM_STATE_DIR", state) | |
| 27 | 新增: if port := os.Getenv("CAGE_TEST_PROXY_PORT"); port != "" { | |
| 28 | 新增: n, err := strconv.Atoi(port) | |
| 29 | 新增: if err != nil || n < 1 || n > 65535 { | |
| 30 | 新增: t.Fatal("invalid CAGE_TEST_PROXY_PORT") | |
| 31 | 新增: } | |
| 32 | 新增: if err := os.WriteFile(filepath.Join(state, "network"), []byte("allow 127.0.0.1:"+port+"\n"), 0600); err != nil { | |
| 33 | 新增: t.Fatal(err) | |
| 34 | 新增: } | |
| 35 | 新增: for _, key := range []string{"http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY"} { | |
| 36 | 新增: t.Setenv(key, "http://127.0.0.1:"+port) | |
| 37 | 新增: } | |
| 38 | 新增: } | |
| 39 | 新增: mounts := []Mount{} | |
| 40 | 新增: name := "image-input-test" | |
| 41 | 新增: if err := l.Create(ctx, name, "template:debian-13", Settings{CPUs: 2, MemoryGiB: 2, DiskGiB: 10, Mounts: &mounts, NoContainerd: true}, io.Discard); err != nil { | |
| 42 | 新增: t.Fatal(err) | |
| 43 | 新增: } | |
| 44 | 新增: t.Cleanup(func() { _ = l.Delete(context.Background(), name) }) | |
| 45 | 新增: var log bytes.Buffer | |
| 46 | 新增: if err := l.Start(ctx, name, &log); err != nil { | |
| 47 | 新增: t.Fatalf("start: %v\n%s", err, log.String()) | |
| 48 | 新增: } | |
| 49 | 新增: run := func(script string, input []byte) { | |
| 50 | 新增: t.Helper() | |
| 51 | 新增: var output bytes.Buffer | |
| 52 | 新增: code, err := l.Shell(ctx, name, ShellOpts{Workdir: "/tmp", Args: []string{"bash", "-c", script}, Stdin: bytes.NewReader(input), Stdout: &output, Stderr: &output}) | |
| 53 | 新增: if err != nil || code != 0 { | |
| 54 | 新增: t.Fatalf("guest: %v / %d\n%s", err, code, output.String()) | |
| 55 | 新增: } | |
| 56 | 新增: text := output.String() | |
| 57 | 新增: if len(text) > 1600 { | |
| 58 | 新增: text = text[len(text)-1600:] | |
| 59 | 新增: } | |
| 60 | 新增: t.Log(text) | |
| 61 | 新增: } | |
| 62 | 新增: run("sudo apt-get update -qq && sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libgtk-3-0 xdotool xvfb xauth python3-gi gir1.2-gtk-3.0", nil) | |
| 63 | 新增: helper, err := os.ReadFile("../cage/image-input.py") | |
| 64 | 新增: if err != nil { | |
| 65 | 新增: t.Fatal(err) | |
| 66 | 新增: } | |
| 67 | 新增: run("cat > /tmp/cage-image-input.py", helper) | |
| 68 | 新增: run("xvfb-run -a python3 -", []byte(imageInputAcceptance)) | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:const imageInputAcceptance = ` | |
| 72 | 新增:import gi | |
| 73 | 新增:gi.require_version('Gtk', '3.0') | |
| 74 | 新增:from gi.repository import Gtk, Gdk, GLib | |
| 75 | 新增:import hashlib, json, os, pathlib, struct, subprocess, threading, zlib | |
| 76 | 新增: | |
| 77 | 新增:def png(seed): | |
| 78 | 新增: def chunk(kind, data): | |
| 79 | 新增: return struct.pack('!I',len(data))+kind+data+struct.pack('!I',zlib.crc32(kind+data)) | |
| 80 | 新增: # Over 3 MB: this must traverse X11's INCR protocol. | |
| 81 | 新增: raw=b''.join(b'\0'+hashlib.shake_256(bytes([seed,i%256])).digest(1024*3) for i in range(1024)) | |
| 82 | 新增: return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!2I5B',1024,1024,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(raw))+chunk(b'IEND',b'') | |
| 83 | 新增:images=[png(1),png(2)] | |
| 84 | 新增:received=[] | |
| 85 | 新增:errors=[] | |
| 86 | 新增:window=Gtk.Window() | |
| 87 | 新增:window.set_title('Cage image input test') | |
| 88 | 新增:field=Gtk.TextView() | |
| 89 | 新增:window.add(field) | |
| 90 | 新增:def key(_widget,event): | |
| 91 | 新增: if event.keyval==Gdk.KEY_v and event.state & Gdk.ModifierType.CONTROL_MASK: | |
| 92 | 新增: def contents(_clipboard,data,_unused): | |
| 93 | 新增: received.append(bytes(data.get_data() or b'')) | |
| 94 | 新增: Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).request_contents(Gdk.Atom.intern('image/png',False),contents,None) | |
| 95 | 新增: return True | |
| 96 | 新增:field.connect('key-press-event',key) | |
| 97 | 新增:window.show_all() | |
| 98 | 新增:field.grab_focus() | |
| 99 | 新增:def worker(): | |
| 100 | 新增: try: | |
| 101 | 新增: subprocess.run(['xdotool','search','--name','Cage image input test','windowfocus','--sync'],check=True,timeout=3) | |
| 102 | 新增: for image in images: | |
| 103 | 新增: result=subprocess.run(['python3','/tmp/cage-image-input.py','paste'],input=image,capture_output=True,timeout=15) | |
| 104 | 新增: assert result.returncode==0,(result.returncode,result.stderr) | |
| 105 | 新增: result=subprocess.run(['python3','/tmp/cage-image-input.py','save'],input=images[0],capture_output=True,check=True) | |
| 106 | 新增: path=pathlib.Path(json.loads(result.stdout)['path']) | |
| 107 | 新增: assert path.read_bytes()==images[0] | |
| 108 | 新增: assert path.stat().st_mode & 0o777 == 0o600 | |
| 109 | 新增: path.unlink() | |
| 110 | 新增: except BaseException as error: | |
| 111 | 新增: errors.append(repr(error)) | |
| 112 | 新增: GLib.timeout_add(1000, Gtk.main_quit) | |
| 113 | 新增:GLib.timeout_add(300,lambda:(threading.Thread(target=worker).start(),False)[1]) | |
| 114 | 新增:GLib.timeout_add(35000,Gtk.main_quit) | |
| 115 | 新增:Gtk.main() | |
| 116 | 新增:assert not errors,errors | |
| 117 | 新增:assert received==images,[len(item) for item in received] | |
| 118 | 新增:print('PASS: two real X11 image pastes, >3 MB PNG integrity, private saved attachment') | |
| 119 | 新增:` | |
| @@ -524,11 +524,13 @@ func (l *Lima) Stop(ctx context.Context, name string) error { | ||
| 524 | 524 | switch { |
| 525 | 525 | case inst.Status == limatype.StatusRunning: |
| 526 | 526 | return withLog(io.Discard, func() error { |
| 527 | 删除: return errors.Join(instance.StopGracefully(ctx, inst, false), reconcile.Reconcile(ctx, "")) | |
| 527 | 新增: return errors.Join(stopInstance(ctx, inst), reconcile.Reconcile(ctx, "")) | |
| 528 | 528 | }) |
| 529 | 529 | case fromLima(inst).Orphaned: |
| 530 | 530 | return withLog(io.Discard, func() error { |
| 531 | 删除: instance.StopForcibly(inst) | |
| 531 | 新增: if err := stopOrphanedInstance(ctx, inst); err != nil { | |
| 532 | 新增: return err | |
| 533 | 新增: } | |
| 532 | 534 | return reconcile.Reconcile(ctx, "") |
| 533 | 535 | }) |
| 534 | 536 | } |
| @@ -542,7 +544,13 @@ func (l *Lima) Delete(ctx context.Context, name string) error { | ||
| 542 | 544 | } |
| 543 | 545 | return withLog(io.Discard, func() error { |
| 544 | 546 | if inst.Status == limatype.StatusRunning { |
| 545 | 删除: _ = instance.StopGracefully(ctx, inst, false) | |
| 547 | 新增: if err := stopInstance(ctx, inst); err != nil { | |
| 548 | 新增: return err | |
| 549 | 新增: } | |
| 550 | 新增: } else if fromLima(inst).Orphaned { | |
| 551 | 新增: if err := stopOrphanedInstance(ctx, inst); err != nil { | |
| 552 | 新增: return err | |
| 553 | 新增: } | |
| 546 | 554 | } |
| 547 | 555 | return errors.Join(instance.Delete(ctx, inst, true), reconcile.Reconcile(ctx, "")) |
| 548 | 556 | }) |
| @@ -43,7 +43,11 @@ func TestLimaBoot(t *testing.T) { | ||
| 43 | 43 | SSHFS: &SSHFS{SFTPDriver: "builtin", Cache: &off, ReadonlyNames: []string{".git", ".hg"}}}} |
| 44 | 44 | rev := ReverseSSHFS |
| 45 | 45 | name := "agent-vm-e2e-00000000" |
| 46 | 删除: if err := l.Create(ctx, name, "template:debian-13", Settings{CPUs: 1, MemoryGiB: 2, DiskGiB: 10, Mounts: &mounts, MountType: &rev, NoContainerd: true}, io.Discard); err != nil { | |
| 46 | 新增: template := strings.TrimSpace(os.Getenv("AGENT_VM_E2E_TEMPLATE")) | |
| 47 | 新增: if template == "" { | |
| 48 | 新增: template = "template:debian-13" | |
| 49 | 新增: } | |
| 50 | 新增: if err := l.Create(ctx, name, template, Settings{CPUs: 1, MemoryGiB: 2, DiskGiB: 10, Mounts: &mounts, MountType: &rev, NoContainerd: true}, io.Discard); err != nil { | |
| 47 | 51 | t.Fatal(err) |
| 48 | 52 | } |
| 49 | 53 | t.Cleanup(func() { _ = l.Delete(context.Background(), name) }) |
| @@ -16,6 +16,12 @@ var ErrNetworkOpen = errors.New("agent-vm starts no VM with a network besides it | ||
| 16 | 16 | // (a shared usernet, a socket, vzNAT, a vmnet one): its traffic does not go |
| 17 | 17 | // through the netstack that the policy is applied to. |
| 18 | 18 | func NetworkConfined(cfg *limatype.LimaYAML) error { |
| 19 | 新增: // Only these drivers attach the VM's NIC to our host-side netstack. | |
| 20 | 新增: // WSL2 and HCS have separate host-managed networking, even with no | |
| 21 | 新增: // explicit networks entry, so they cannot enforce the Cage egress gate. | |
| 22 | 新增: if cfg.VMType != nil && *cfg.VMType != limatype.QEMU && *cfg.VMType != limatype.VZ { | |
| 23 | 新增: return fmt.Errorf("%w: VM driver %q does not use the confined network", ErrNetworkOpen, *cfg.VMType) | |
| 24 | 新增: } | |
| 19 | 25 | for i, n := range cfg.Networks { |
| 20 | 26 | what := "a network" |
| 21 | 27 | switch { |
| @@ -31,6 +31,19 @@ func TestNetworkConfined(t *testing.T) { | ||
| 31 | 31 | } |
| 32 | 32 | } |
| 33 | 33 | |
| 34 | 新增:func TestNetworkConfinedRejectsDriversThatBypassNetstack(t *testing.T) { | |
| 35 | 新增: for _, driver := range []limatype.VMType{limatype.WSL2, limatype.HCS, "external"} { | |
| 36 | 新增: if err := NetworkConfined(&limatype.LimaYAML{VMType: &driver}); !errors.Is(err, ErrNetworkOpen) { | |
| 37 | 新增: t.Fatalf("driver %q without explicit networks bypassed the egress policy: %v", driver, err) | |
| 38 | 新增: } | |
| 39 | 新增: } | |
| 40 | 新增: for _, driver := range []limatype.VMType{limatype.QEMU, limatype.VZ} { | |
| 41 | 新增: if err := NetworkConfined(&limatype.LimaYAML{VMType: &driver}); err != nil { | |
| 42 | 新增: t.Fatalf("confined driver %q rejected: %v", driver, err) | |
| 43 | 新增: } | |
| 44 | 新增: } | |
| 45 | 新增:} | |
| 46 | 新增: | |
| 34 | 47 | // Start refuses a VM whose config has a network, before booting anything. |
| 35 | 48 | func TestLimaStartRefusesNetworks(t *testing.T) { |
| 36 | 49 | ctx := context.Background() |
| @@ -26,12 +26,7 @@ func isQEMU(pid int, dir, name string) bool { | ||
| 26 | 26 | } |
| 27 | 27 | args = strings.ReplaceAll(string(b), "\x00", " ") |
| 28 | 28 | case "windows": |
| 29 | 删除: out, err := exec.Command("powershell", "-NoProfile", "-Command", | |
| 30 | 删除: "(Get-CimInstance Win32_Process -Filter 'ProcessId="+strconv.Itoa(pid)+"').CommandLine").Output() | |
| 31 | 删除: if err != nil { | |
| 32 | 删除: return false | |
| 33 | 删除: } | |
| 34 | 删除: args = string(out) | |
| 29 | 新增: return isWindowsQEMU(pid, dir, name) | |
| 35 | 30 | default: |
| 36 | 31 | out, err := exec.Command("ps", "-p", strconv.Itoa(pid), "-o", "args=").Output() |
| 37 | 32 | if err != nil { |
| @@ -0,0 +1,5 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package vm | |
| 4 | 新增: | |
| 5 | 新增:func isWindowsQEMU(int, string, string) bool { return false } | |
| @@ -0,0 +1,55 @@ | ||
| 1 | 新增:package vm | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "os" | |
| 7 | 新增: "os/exec" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "strconv" | |
| 10 | 新增: "strings" | |
| 11 | 新增: "syscall" | |
| 12 | 新增: "time" | |
| 13 | 新增: | |
| 14 | 新增: "golang.org/x/sys/windows" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func isWindowsQEMU(pid int, dir, name string) bool { | |
| 18 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 19 | 新增: defer cancel() | |
| 20 | 新增: root := os.Getenv("SystemRoot") | |
| 21 | 新增: if root == "" { | |
| 22 | 新增: root = `C:\Windows` | |
| 23 | 新增: } | |
| 24 | 新增: cmd := exec.CommandContext(ctx, filepath.Join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), "-NoProfile", "-NonInteractive", "-Command", | |
| 25 | 新增: `[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); (Get-CimInstance Win32_Process -Filter 'ProcessId=`+strconv.Itoa(pid)+`').CommandLine | ConvertTo-Json -Compress`) | |
| 26 | 新增: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} | |
| 27 | 新增: out, err := cmd.Output() | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: return false | |
| 30 | 新增: } | |
| 31 | 新增: var command string | |
| 32 | 新增: if json.Unmarshal(out, &command) != nil { | |
| 33 | 新增: return false | |
| 34 | 新增: } | |
| 35 | 新增: return windowsQEMUCommandMatches(command, dir, name) | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func windowsQEMUCommandMatches(command, dir, name string) bool { | |
| 39 | 新增: args, err := windows.DecomposeCommandLine(command) | |
| 40 | 新增: if err != nil || len(args) == 0 || !strings.EqualFold(filepath.Base(args[0]), "qemu-system-x86_64.exe") { | |
| 41 | 新增: return false | |
| 42 | 新增: } | |
| 43 | 新增: gotName, gotPID := false, false | |
| 44 | 新增: for i := 1; i+1 < len(args); i++ { | |
| 45 | 新增: switch args[i] { | |
| 46 | 新增: case "-name": | |
| 47 | 新增: gotName = args[i+1] == "lima-"+name | |
| 48 | 新增: i++ | |
| 49 | 新增: case "-pidfile": | |
| 50 | 新增: gotPID = strings.EqualFold(filepath.Clean(args[i+1]), filepath.Join(dir, "qemu.pid")) | |
| 51 | 新增: i++ | |
| 52 | 新增: } | |
| 53 | 新增: } | |
| 54 | 新增: return gotName && gotPID | |
| 55 | 新增:} | |
| @@ -0,0 +1,22 @@ | ||
| 1 | 新增:package vm | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "testing" | |
| 5 | 新增: | |
| 6 | 新增: "golang.org/x/sys/windows" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestWindowsQEMUIdentityHandlesSpacesAndRequiresInstance(t *testing.T) { | |
| 10 | 新增: dir := `C:\Users\测试 User\.claude-cage\state\lima\test` | |
| 11 | 新增: args := []string{`C:\Program Files\Cage\resources\runtime\qemu\qemu-system-x86_64.exe`, "-name", "lima-test", "-pidfile", dir + `\qemu.pid`} | |
| 12 | 新增: if !windowsQEMUCommandMatches(windows.ComposeCommandLine(args), dir, "test") { | |
| 13 | 新增: t.Fatal("quoted Unicode QEMU identity not recognized") | |
| 14 | 新增: } | |
| 15 | 新增: if windowsQEMUCommandMatches(windows.ComposeCommandLine(args), dir, "other") { | |
| 16 | 新增: t.Fatal("another instance was accepted") | |
| 17 | 新增: } | |
| 18 | 新增: args[4] = dir + `-other\qemu.pid` | |
| 19 | 新增: if windowsQEMUCommandMatches(windows.ComposeCommandLine(args), dir, "test") { | |
| 20 | 新增: t.Fatal("another instance PID file was accepted") | |
| 21 | 新增: } | |
| 22 | 新增:} | |
| @@ -0,0 +1,19 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package vm | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: | |
| 8 | 新增: "github.com/lima-vm/lima/v2/pkg/instance" | |
| 9 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func stopInstance(ctx context.Context, inst *limatype.Instance) error { | |
| 13 | 新增: return instance.StopGracefully(ctx, inst, false) | |
| 14 | 新增:} | |
| 15 | 新增: | |
| 16 | 新增:func stopOrphanedInstance(_ context.Context, inst *limatype.Instance) error { | |
| 17 | 新增: instance.StopForcibly(inst) | |
| 18 | 新增: return nil | |
| 19 | 新增:} | |
| @@ -0,0 +1,72 @@ | ||
| 1 | 新增:package vm | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "fmt" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "time" | |
| 9 | 新增: | |
| 10 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 11 | 新增: "github.com/lima-vm/lima/v2/pkg/store" | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 13 | 新增: "golang.org/x/sys/windows" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:func stopInstance(ctx context.Context, inst *limatype.Instance) error { | |
| 17 | 新增: requested, err := host.RequestInstanceStop(inst.Dir) | |
| 18 | 新增: if err != nil { | |
| 19 | 新增: return err | |
| 20 | 新增: } | |
| 21 | 新增: if !requested { | |
| 22 | 新增: return fmt.Errorf("Cage 环境的停止通知不可用;保留环境,请查看 hostagent 日志") | |
| 23 | 新增: } | |
| 24 | 新增: ctx, cancel := context.WithTimeout(ctx, 3*time.Minute+10*time.Second) | |
| 25 | 新增: defer cancel() | |
| 26 | 新增: ticker := time.NewTicker(250 * time.Millisecond) | |
| 27 | 新增: defer ticker.Stop() | |
| 28 | 新增: for { | |
| 29 | 新增: select { | |
| 30 | 新增: case <-ctx.Done(): | |
| 31 | 新增: return fmt.Errorf("等待 Cage 环境保存并停止超时: %w", ctx.Err()) | |
| 32 | 新增: case <-ticker.C: | |
| 33 | 新增: current, err := store.Inspect(ctx, inst.Name) | |
| 34 | 新增: if err != nil { | |
| 35 | 新增: return err | |
| 36 | 新增: } | |
| 37 | 新增: if current.Status == limatype.StatusStopped { | |
| 38 | 新增: return nil | |
| 39 | 新增: } | |
| 40 | 新增: } | |
| 41 | 新增: } | |
| 42 | 新增:} | |
| 43 | 新增: | |
| 44 | 新增:func stopOrphanedInstance(_ context.Context, inst *limatype.Instance) error { | |
| 45 | 新增: if inst.VMType != limatype.QEMU || inst.DriverPID <= 0 { | |
| 46 | 新增: return fmt.Errorf("unsupported orphaned VM driver") | |
| 47 | 新增: } | |
| 48 | 新增: handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.PROCESS_TERMINATE|windows.SYNCHRONIZE, false, uint32(inst.DriverPID)) | |
| 49 | 新增: if err != nil { | |
| 50 | 新增: return err | |
| 51 | 新增: } | |
| 52 | 新增: defer windows.CloseHandle(handle) | |
| 53 | 新增: image := make([]uint16, 32768) | |
| 54 | 新增: size := uint32(len(image)) | |
| 55 | 新增: if err := windows.QueryFullProcessImageName(handle, 0, &image[0], &size); err != nil { | |
| 56 | 新增: return err | |
| 57 | 新增: } | |
| 58 | 新增: if !strings.EqualFold(filepath.Base(windows.UTF16ToString(image[:size])), "qemu-system-x86_64.exe") || !isQEMU(inst.DriverPID, inst.Dir, inst.Name) { | |
| 59 | 新增: return fmt.Errorf("orphaned VM process identity changed; no process was stopped") | |
| 60 | 新增: } | |
| 61 | 新增: if err := windows.TerminateProcess(handle, 1); err != nil { | |
| 62 | 新增: return err | |
| 63 | 新增: } | |
| 64 | 新增: state, err := windows.WaitForSingleObject(handle, 5000) | |
| 65 | 新增: if err != nil { | |
| 66 | 新增: return err | |
| 67 | 新增: } | |
| 68 | 新增: if state != windows.WAIT_OBJECT_0 { | |
| 69 | 新增: return fmt.Errorf("orphaned QEMU did not stop") | |
| 70 | 新增: } | |
| 71 | 新增: return nil | |
| 72 | 新增:} | |
| @@ -0,0 +1,83 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "net/http" | |
| 5 | 新增:) | |
| 6 | 新增: | |
| 7 | 新增:func (s *Server) accountStatus(w http.ResponseWriter, r *http.Request) { | |
| 8 | 新增: v := s.account.view() | |
| 9 | 新增: v.BackgroundRunning = s.vmRunning() | |
| 10 | 新增: jsonReply(w, v) | |
| 11 | 新增:} | |
| 12 | 新增: | |
| 13 | 新增:func (s *Server) accountAction(w http.ResponseWriter, r *http.Request) { | |
| 14 | 新增: if s.account == nil { | |
| 15 | 新增: http.Error(w, "本地账户尚未初始化", 503) | |
| 16 | 新增: return | |
| 17 | 新增: } | |
| 18 | 新增: action := r.PathValue("action") | |
| 19 | 新增: if action != "create" && action != "unlock" && action != "profile" && action != "password" && action != "lock" && action != "logout" && action != "suspend" && action != "device-enroll" && action != "device-revoke" && action != "device-unlock" { | |
| 20 | 新增: http.NotFound(w, r) | |
| 21 | 新增: return | |
| 22 | 新增: } | |
| 23 | 新增: if action != "create" && action != "unlock" && action != "device-unlock" { | |
| 24 | 新增: if _, ok := s.account.access(); !ok { | |
| 25 | 新增: http.Error(w, "请先解锁 Cage", http.StatusLocked) | |
| 26 | 新增: return | |
| 27 | 新增: } | |
| 28 | 新增: } | |
| 29 | 新增: var input struct { | |
| 30 | 新增: Username string `json:"username"` | |
| 31 | 新增: Password string `json:"password"` | |
| 32 | 新增: ConfirmPassword string `json:"confirm_password"` | |
| 33 | 新增: OldPassword string `json:"old_password"` | |
| 34 | 新增: Avatar string `json:"avatar"` | |
| 35 | 新增: Kind string `json:"kind"` | |
| 36 | 新增: Credential deviceCredential `json:"credential"` | |
| 37 | 新增: } | |
| 38 | 新增: if !readJSON(w, r, &input, 3<<20) { | |
| 39 | 新增: return | |
| 40 | 新增: } | |
| 41 | 新增: var err error | |
| 42 | 新增: switch action { | |
| 43 | 新增: case "create": | |
| 44 | 新增: if input.Password != input.ConfirmPassword { | |
| 45 | 新增: http.Error(w, "两次密码不一致", 400) | |
| 46 | 新增: return | |
| 47 | 新增: } | |
| 48 | 新增: err = s.account.create(input.Username, input.Password, input.Avatar) | |
| 49 | 新增: case "unlock": | |
| 50 | 新增: err = s.account.unlock(input.Password) | |
| 51 | 新增: case "profile": | |
| 52 | 新增: err = s.account.updateProfile(input.Username, input.Avatar) | |
| 53 | 新增: case "password": | |
| 54 | 新增: if input.Password != input.ConfirmPassword { | |
| 55 | 新增: http.Error(w, "两次密码不一致", 400) | |
| 56 | 新增: return | |
| 57 | 新增: } | |
| 58 | 新增: err = s.account.changePassword(input.OldPassword, input.Password) | |
| 59 | 新增: case "lock": | |
| 60 | 新增: err = s.account.lockAccess(false) | |
| 61 | 新增: case "suspend": | |
| 62 | 新增: s.account.lock() | |
| 63 | 新增: case "device-enroll": | |
| 64 | 新增: var credential deviceCredential | |
| 65 | 新增: credential, err = s.account.enrollDevice(input.Kind) | |
| 66 | 新增: if err == nil { | |
| 67 | 新增: jsonReply(w, credential) | |
| 68 | 新增: return | |
| 69 | 新增: } | |
| 70 | 新增: case "device-revoke": | |
| 71 | 新增: err = s.account.revokeDevice(input.Kind) | |
| 72 | 新增: case "device-unlock": | |
| 73 | 新增: err = s.account.unlockDevice(input.Kind, input.Credential) | |
| 74 | 新增: case "logout": | |
| 75 | 新增: s.requestStop(w, true) | |
| 76 | 新增: return | |
| 77 | 新增: } | |
| 78 | 新增: if err != nil { | |
| 79 | 新增: requestError(w, err) | |
| 80 | 新增: return | |
| 81 | 新增: } | |
| 82 | 新增: s.accountStatus(w, r) | |
| 83 | 新增:} | |
| @@ -0,0 +1,151 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/aes" | |
| 5 | 新增: "crypto/cipher" | |
| 6 | 新增: "crypto/rand" | |
| 7 | 新增: "crypto/sha256" | |
| 8 | 新增: "encoding/base64" | |
| 9 | 新增: "encoding/hex" | |
| 10 | 新增: "errors" | |
| 11 | 新增: "maps" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:type accountDevice struct { | |
| 15 | 新增: ID string `json:"id"` | |
| 16 | 新增: Nonce []byte `json:"nonce"` | |
| 17 | 新增: SealedKey []byte `json:"sealed_key"` | |
| 18 | 新增:} | |
| 19 | 新增:type deviceCredential struct { | |
| 20 | 新增: ID string `json:"id"` | |
| 21 | 新增: Secret string `json:"secret"` | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:func validDeviceKind(kind string) bool { return kind == "automatic" || kind == "biometric" } | |
| 25 | 新增:func fmtAccountBinding(path string) string { | |
| 26 | 新增: sum := sha256.Sum256([]byte(path)) | |
| 27 | 新增: return hex.EncodeToString(sum[:]) | |
| 28 | 新增:} | |
| 29 | 新增:func deviceAEAD(secret []byte) (cipher.AEAD, error) { | |
| 30 | 新增: block, err := aes.NewCipher(secret) | |
| 31 | 新增: if err != nil { | |
| 32 | 新增: return nil, err | |
| 33 | 新增: } | |
| 34 | 新增: return cipher.NewGCM(block) | |
| 35 | 新增:} | |
| 36 | 新增:func (a *localAccount) enrollDevice(kind string) (deviceCredential, error) { | |
| 37 | 新增: a.mu.Lock() | |
| 38 | 新增: defer a.mu.Unlock() | |
| 39 | 新增: if !validDeviceKind(kind) || len(a.key) != 32 { | |
| 40 | 新增: return deviceCredential{}, errors.New("请先解锁 Cage,再设置快捷登录") | |
| 41 | 新增: } | |
| 42 | 新增: secret := make([]byte, 32) | |
| 43 | 新增: if _, err := rand.Read(secret); err != nil { | |
| 44 | 新增: return deviceCredential{}, err | |
| 45 | 新增: } | |
| 46 | 新增: defer clear(secret) | |
| 47 | 新增: id := make([]byte, 16) | |
| 48 | 新增: if _, err := rand.Read(id); err != nil { | |
| 49 | 新增: return deviceCredential{}, err | |
| 50 | 新增: } | |
| 51 | 新增: device := accountDevice{ID: hex.EncodeToString(id), Nonce: make([]byte, 12)} | |
| 52 | 新增: if _, err := rand.Read(device.Nonce); err != nil { | |
| 53 | 新增: return deviceCredential{}, err | |
| 54 | 新增: } | |
| 55 | 新增: aead, _ := deviceAEAD(secret) | |
| 56 | 新增: device.SealedKey = aead.Seal(nil, device.Nonce, a.key, []byte(kind+":"+device.ID)) | |
| 57 | 新增: record := *a.record | |
| 58 | 新增: record.Devices = maps.Clone(record.Devices) | |
| 59 | 新增: if record.Devices == nil { | |
| 60 | 新增: record.Devices = map[string]accountDevice{} | |
| 61 | 新增: } | |
| 62 | 新增: record.Devices[kind] = device | |
| 63 | 新增: if err := writePrivate(a.path, record); err != nil { | |
| 64 | 新增: return deviceCredential{}, errors.New("快捷登录未能保存,请重试") | |
| 65 | 新增: } | |
| 66 | 新增: a.record = &record | |
| 67 | 新增: return deviceCredential{ID: device.ID, Secret: base64.RawStdEncoding.EncodeToString(secret)}, nil | |
| 68 | 新增:} | |
| 69 | 新增:func (a *localAccount) revokeDevice(kind string) error { | |
| 70 | 新增: a.mu.Lock() | |
| 71 | 新增: defer a.mu.Unlock() | |
| 72 | 新增: if !validDeviceKind(kind) || len(a.key) != 32 { | |
| 73 | 新增: return errors.New("请先解锁 Cage") | |
| 74 | 新增: } | |
| 75 | 新增: record := *a.record | |
| 76 | 新增: record.Devices = maps.Clone(record.Devices) | |
| 77 | 新增: delete(record.Devices, kind) | |
| 78 | 新增: if err := writePrivate(a.path, record); err != nil { | |
| 79 | 新增: return errors.New("快捷登录未能关闭,请重试") | |
| 80 | 新增: } | |
| 81 | 新增: a.record = &record | |
| 82 | 新增: return nil | |
| 83 | 新增:} | |
| 84 | 新增: | |
| 85 | 新增:// Called with a.mu held. The disk flag prevents reopening the app or restarting | |
| 86 | 新增:// the controller from turning an explicit lock into automatic login. | |
| 87 | 新增:func (a *localAccount) clearAuthenticationRequirement() error { | |
| 88 | 新增: if !a.record.RequireAuthentication { | |
| 89 | 新增: return nil | |
| 90 | 新增: } | |
| 91 | 新增: record := *a.record | |
| 92 | 新增: record.RequireAuthentication = false | |
| 93 | 新增: if err := writePrivate(a.path, record); err != nil { | |
| 94 | 新增: return errors.New("无法保存解锁状态,请重试") | |
| 95 | 新增: } | |
| 96 | 新增: a.record = &record | |
| 97 | 新增: return nil | |
| 98 | 新增:} | |
| 99 | 新增:func (a *localAccount) unlockDevice(kind string, credential deviceCredential) error { | |
| 100 | 新增: a.mu.Lock() | |
| 101 | 新增: defer a.mu.Unlock() | |
| 102 | 新增: if a.record == nil || !validDeviceKind(kind) { | |
| 103 | 新增: return errors.New("快捷登录不可用,请使用密码") | |
| 104 | 新增: } | |
| 105 | 新增: if kind == "automatic" && a.record.RequireAuthentication { | |
| 106 | 新增: return errors.New("Cage 已手动锁定,请使用指纹或密码") | |
| 107 | 新增: } | |
| 108 | 新增: device, ok := a.record.Devices[kind] | |
| 109 | 新增: if !ok || device.ID != credential.ID { | |
| 110 | 新增: return errors.New("快捷登录授权已失效,请使用密码") | |
| 111 | 新增: } | |
| 112 | 新增: secret, err := base64.RawStdEncoding.DecodeString(credential.Secret) | |
| 113 | 新增: if err != nil || len(secret) != 32 { | |
| 114 | 新增: return errors.New("快捷登录凭据无效") | |
| 115 | 新增: } | |
| 116 | 新增: defer clear(secret) | |
| 117 | 新增: aead, _ := deviceAEAD(secret) | |
| 118 | 新增: key, err := aead.Open(nil, device.Nonce, device.SealedKey, []byte(kind+":"+device.ID)) | |
| 119 | 新增: if err != nil { | |
| 120 | 新增: return errors.New("快捷登录凭据无效") | |
| 121 | 新增: } | |
| 122 | 新增: if err = a.clearAuthenticationRequirement(); err != nil { | |
| 123 | 新增: clear(key) | |
| 124 | 新增: return err | |
| 125 | 新增: } | |
| 126 | 新增: a.setKey(key) | |
| 127 | 新增: return nil | |
| 128 | 新增:} | |
| 129 | 新增:func (a *localAccount) lockAccess(logout bool) error { | |
| 130 | 新增: a.mu.Lock() | |
| 131 | 新增: defer a.mu.Unlock() | |
| 132 | 新增: if a.record == nil { | |
| 133 | 新增: return nil | |
| 134 | 新增: } | |
| 135 | 新增: record := *a.record | |
| 136 | 新增: record.RequireAuthentication = true | |
| 137 | 新增: if logout { | |
| 138 | 新增: record.Devices = nil | |
| 139 | 新增: } | |
| 140 | 新增: if err := writePrivate(a.path, record); err != nil { | |
| 141 | 新增: return errors.New("无法保存账户锁定状态,请重试") | |
| 142 | 新增: } | |
| 143 | 新增: a.record = &record | |
| 144 | 新增: if a.cancel != nil { | |
| 145 | 新增: a.cancel() | |
| 146 | 新增: a.cancel = nil | |
| 147 | 新增: } | |
| 148 | 新增: clear(a.key) | |
| 149 | 新增: a.key = nil | |
| 150 | 新增: return nil | |
| 151 | 新增:} | |
| @@ -0,0 +1,113 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "os" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "testing" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func TestDeviceLoginRespectsPersistentManualLock(t *testing.T) { | |
| 11 | 新增: a := newTestAccount(t) | |
| 12 | 新增: automatic, err := a.enrollDevice("automatic") | |
| 13 | 新增: if err != nil { | |
| 14 | 新增: t.Fatal(err) | |
| 15 | 新增: } | |
| 16 | 新增: biometric, err := a.enrollDevice("biometric") | |
| 17 | 新增: if err != nil { | |
| 18 | 新增: t.Fatal(err) | |
| 19 | 新增: } | |
| 20 | 新增: original, _ := a.desktopKey() | |
| 21 | 新增: defer clear(original) | |
| 22 | 新增: data, _ := os.ReadFile(a.path) | |
| 23 | 新增: if bytes.Contains(data, []byte(automatic.Secret)) || bytes.Contains(data, original) { | |
| 24 | 新增: t.Fatal("device secret stored outside keychain") | |
| 25 | 新增: } | |
| 26 | 新增: a.lock() // App exit clears memory but allows the authorized automatic reopen. | |
| 27 | 新增: reopened, err := loadLocalAccount(filepath.Dir(a.path)) | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: defer reopened.lock() | |
| 32 | 新增: if err = reopened.unlockDevice("automatic", automatic); err != nil { | |
| 33 | 新增: t.Fatal(err) | |
| 34 | 新增: } | |
| 35 | 新增: if err = reopened.lockAccess(false); err != nil { | |
| 36 | 新增: t.Fatal(err) | |
| 37 | 新增: } | |
| 38 | 新增: locked, err := loadLocalAccount(filepath.Dir(a.path)) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: t.Fatal(err) | |
| 41 | 新增: } | |
| 42 | 新增: defer locked.lock() | |
| 43 | 新增: if err = locked.unlockDevice("automatic", automatic); err == nil { | |
| 44 | 新增: t.Fatal("reopening bypassed manual lock") | |
| 45 | 新增: } | |
| 46 | 新增: if err = locked.unlockDevice("biometric", automatic); err == nil { | |
| 47 | 新增: t.Fatal("automatic token accepted as biometric proof") | |
| 48 | 新增: } | |
| 49 | 新增: if err = locked.unlockDevice("biometric", biometric); err != nil { | |
| 50 | 新增: t.Fatal(err) | |
| 51 | 新增: } | |
| 52 | 新增: after, _ := locked.desktopKey() | |
| 53 | 新增: defer clear(after) | |
| 54 | 新增: if !bytes.Equal(after, original) { | |
| 55 | 新增: t.Fatal("device unlock changed guest key") | |
| 56 | 新增: } | |
| 57 | 新增: if locked.view().RequireAuthentication { | |
| 58 | 新增: t.Fatal("authenticated unlock did not clear manual lock") | |
| 59 | 新增: } | |
| 60 | 新增: if err = locked.revokeDevice("biometric"); err != nil { | |
| 61 | 新增: t.Fatal(err) | |
| 62 | 新增: } | |
| 63 | 新增: locked.lock() | |
| 64 | 新增: if err = locked.unlockDevice("biometric", biometric); err == nil { | |
| 65 | 新增: t.Fatal("revoked credential accepted") | |
| 66 | 新增: } | |
| 67 | 新增: if err = locked.unlockDevice("automatic", automatic); err != nil { | |
| 68 | 新增: t.Fatal(err) | |
| 69 | 新增: } | |
| 70 | 新增: if err = locked.lockAccess(true); err != nil { | |
| 71 | 新增: t.Fatal(err) | |
| 72 | 新增: } | |
| 73 | 新增: if err = locked.unlockDevice("automatic", automatic); err == nil { | |
| 74 | 新增: t.Fatal("logout retained automatic authority") | |
| 75 | 新增: } | |
| 76 | 新增: if err = locked.unlock("initial-test-password"); err != nil { | |
| 77 | 新增: t.Fatal("password fallback lost", err) | |
| 78 | 新增: } | |
| 79 | 新增: if len(locked.view().Devices) != 0 { | |
| 80 | 新增: t.Fatal("logout retained device enrollment") | |
| 81 | 新增: } | |
| 82 | 新增:} | |
| 83 | 新增: | |
| 84 | 新增:func TestDeviceEnrollmentRequiresAccountAndAuthenticToken(t *testing.T) { | |
| 85 | 新增: a := newTestAccount(t) | |
| 86 | 新增: credential, err := a.enrollDevice("automatic") | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: t.Fatal(err) | |
| 89 | 新增: } | |
| 90 | 新增: a.lock() | |
| 91 | 新增: if _, err = a.enrollDevice("biometric"); err == nil { | |
| 92 | 新增: t.Fatal("locked account issued a device token") | |
| 93 | 新增: } | |
| 94 | 新增: tampered := credential | |
| 95 | 新增: tampered.Secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" | |
| 96 | 新增: if err = a.unlockDevice("automatic", tampered); err == nil { | |
| 97 | 新增: t.Fatal("forged device credential accepted") | |
| 98 | 新增: } | |
| 99 | 新增: if err = a.unlockDevice("automatic", credential); err != nil { | |
| 100 | 新增: t.Fatal(err) | |
| 101 | 新增: } | |
| 102 | 新增: replacement, err := a.enrollDevice("automatic") | |
| 103 | 新增: if err != nil { | |
| 104 | 新增: t.Fatal(err) | |
| 105 | 新增: } | |
| 106 | 新增: a.lock() | |
| 107 | 新增: if err = a.unlockDevice("automatic", credential); err == nil { | |
| 108 | 新增: t.Fatal("replaced device credential accepted") | |
| 109 | 新增: } | |
| 110 | 新增: if err = a.unlockDevice("automatic", replacement); err != nil { | |
| 111 | 新增: t.Fatal(err) | |
| 112 | 新增: } | |
| 113 | 新增:} | |
| @@ -0,0 +1,347 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/aes" | |
| 7 | 新增: "crypto/cipher" | |
| 8 | 新增: "crypto/rand" | |
| 9 | 新增: "encoding/base64" | |
| 10 | 新增: "encoding/json" | |
| 11 | 新增: "errors" | |
| 12 | 新增: "image" | |
| 13 | 新增: _ "image/jpeg" | |
| 14 | 新增: "image/png" | |
| 15 | 新增: "os" | |
| 16 | 新增: "path/filepath" | |
| 17 | 新增: "strings" | |
| 18 | 新增: "sync" | |
| 19 | 新增: "time" | |
| 20 | 新增: "unicode/utf8" | |
| 21 | 新增: | |
| 22 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 23 | 新增: "golang.org/x/crypto/argon2" | |
| 24 | 新增:) | |
| 25 | 新增: | |
| 26 | 新增:type accountRecord struct { | |
| 27 | 新增: Version int `json:"version"` | |
| 28 | 新增: Username string `json:"username"` | |
| 29 | 新增: Avatar string `json:"avatar,omitempty"` | |
| 30 | 新增: Salt []byte `json:"salt"` | |
| 31 | 新增: Nonce []byte `json:"nonce"` | |
| 32 | 新增: SealedKey []byte `json:"sealed_key"` | |
| 33 | 新增: Devices map[string]accountDevice `json:"devices,omitempty"` | |
| 34 | 新增: RequireAuthentication bool `json:"require_authentication,omitempty"` | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:type localAccount struct { | |
| 38 | 新增: mu sync.Mutex | |
| 39 | 新增: path string | |
| 40 | 新增: record *accountRecord | |
| 41 | 新增: key []byte | |
| 42 | 新增: epoch context.Context | |
| 43 | 新增: cancel context.CancelFunc | |
| 44 | 新增: nextAttempt time.Time | |
| 45 | 新增:} | |
| 46 | 新增: | |
| 47 | 新增:type accountView struct { | |
| 48 | 新增: Exists bool `json:"exists"` | |
| 49 | 新增: Unlocked bool `json:"unlocked"` | |
| 50 | 新增: Username string `json:"username"` | |
| 51 | 新增: Avatar string `json:"avatar,omitempty"` | |
| 52 | 新增: BackgroundRunning bool `json:"background_running"` | |
| 53 | 新增: DeviceBinding string `json:"device_binding"` | |
| 54 | 新增: Devices map[string]string `json:"devices,omitempty"` | |
| 55 | 新增: RequireAuthentication bool `json:"require_authentication"` | |
| 56 | 新增:} | |
| 57 | 新增: | |
| 58 | 新增:func loadLocalAccount(profile string) (*localAccount, error) { | |
| 59 | 新增: a := &localAccount{path: filepath.Join(profile, "account.json")} | |
| 60 | 新增: b, err := os.ReadFile(a.path) | |
| 61 | 新增: if os.IsNotExist(err) { | |
| 62 | 新增: return a, nil | |
| 63 | 新增: } | |
| 64 | 新增: if err != nil { | |
| 65 | 新增: return nil, errors.New("无法读取本地账户,请检查配置目录") | |
| 66 | 新增: } | |
| 67 | 新增: if err = host.CheckPrivateFile(a.path); err != nil { | |
| 68 | 新增: return nil, errors.New("本地账户文件权限不安全,请恢复私有文件权限") | |
| 69 | 新增: } | |
| 70 | 新增: var record accountRecord | |
| 71 | 新增: if len(b) > 256<<10 || json.Unmarshal(b, &record) != nil || record.Version != 1 || len(record.Salt) != 16 || len(record.Nonce) != 12 || len(record.SealedKey) != 48 || validAccountName(record.Username) != nil { | |
| 72 | 新增: return nil, errors.New("本地账户文件损坏,请从备份恢复;已有数据未修改") | |
| 73 | 新增: } | |
| 74 | 新增: a.record = &record | |
| 75 | 新增: for kind, device := range record.Devices { | |
| 76 | 新增: if !validDeviceKind(kind) || len(device.ID) != 32 || len(device.Nonce) != 12 || len(device.SealedKey) != 48 { | |
| 77 | 新增: return nil, errors.New("本地账户快捷登录记录损坏,请从备份恢复") | |
| 78 | 新增: } | |
| 79 | 新增: } | |
| 80 | 新增: return a, nil | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:func validAccountName(name string) error { | |
| 84 | 新增: if strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 40 || strings.ContainsAny(name, "\x00\r\n") { | |
| 85 | 新增: return errors.New("用户名需要 1–40 个字符,不能包含换行") | |
| 86 | 新增: } | |
| 87 | 新增: return nil | |
| 88 | 新增:} | |
| 89 | 新增: | |
| 90 | 新增:func validAccountPassword(password string) error { | |
| 91 | 新增: if utf8.RuneCountInString(password) < 8 || len(password) > 1024 || strings.ContainsRune(password, 0) { | |
| 92 | 新增: return errors.New("密码至少 8 个字符,最多 1024 字节") | |
| 93 | 新增: } | |
| 94 | 新增: return nil | |
| 95 | 新增:} | |
| 96 | 新增: | |
| 97 | 新增:func sealAccountKey(record *accountRecord, password string, key []byte) error { | |
| 98 | 新增: record.Salt = make([]byte, 16) | |
| 99 | 新增: if _, err := rand.Read(record.Salt); err != nil { | |
| 100 | 新增: return err | |
| 101 | 新增: } | |
| 102 | 新增: derived := argon2.IDKey([]byte(password), record.Salt, 3, 64*1024, 2, 32) | |
| 103 | 新增: defer clear(derived) | |
| 104 | 新增: block, err := aes.NewCipher(derived) | |
| 105 | 新增: if err != nil { | |
| 106 | 新增: return err | |
| 107 | 新增: } | |
| 108 | 新增: aead, err := cipher.NewGCM(block) | |
| 109 | 新增: if err != nil { | |
| 110 | 新增: return err | |
| 111 | 新增: } | |
| 112 | 新增: record.Nonce = make([]byte, aead.NonceSize()) | |
| 113 | 新增: if _, err = rand.Read(record.Nonce); err != nil { | |
| 114 | 新增: return err | |
| 115 | 新增: } | |
| 116 | 新增: record.SealedKey = aead.Seal(nil, record.Nonce, key, []byte("Cage local account v1")) | |
| 117 | 新增: return nil | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 120 | 新增:func openAccountKey(record *accountRecord, password string) ([]byte, error) { | |
| 121 | 新增: if len(password) > 1024 { | |
| 122 | 新增: return nil, errors.New("密码不正确") | |
| 123 | 新增: } | |
| 124 | 新增: derived := argon2.IDKey([]byte(password), record.Salt, 3, 64*1024, 2, 32) | |
| 125 | 新增: defer clear(derived) | |
| 126 | 新增: block, _ := aes.NewCipher(derived) | |
| 127 | 新增: aead, _ := cipher.NewGCM(block) | |
| 128 | 新增: key, err := aead.Open(nil, record.Nonce, record.SealedKey, []byte("Cage local account v1")) | |
| 129 | 新增: if err != nil { | |
| 130 | 新增: return nil, errors.New("密码不正确") | |
| 131 | 新增: } | |
| 132 | 新增: return key, nil | |
| 133 | 新增:} | |
| 134 | 新增: | |
| 135 | 新增:func (a *localAccount) view() accountView { | |
| 136 | 新增: if a == nil { | |
| 137 | 新增: return accountView{} | |
| 138 | 新增: } | |
| 139 | 新增: a.mu.Lock() | |
| 140 | 新增: defer a.mu.Unlock() | |
| 141 | 新增: v := accountView{Exists: a.record != nil, Unlocked: len(a.key) == 32} | |
| 142 | 新增: v.DeviceBinding = fmtAccountBinding(a.path) | |
| 143 | 新增: if a.record != nil { | |
| 144 | 新增: v.Username = a.record.Username | |
| 145 | 新增: v.Avatar = a.record.Avatar | |
| 146 | 新增: v.RequireAuthentication = a.record.RequireAuthentication | |
| 147 | 新增: v.Devices = make(map[string]string) | |
| 148 | 新增: for kind, device := range a.record.Devices { | |
| 149 | 新增: v.Devices[kind] = device.ID | |
| 150 | 新增: } | |
| 151 | 新增: } | |
| 152 | 新增: return v | |
| 153 | 新增:} | |
| 154 | 新增: | |
| 155 | 新增:func (a *localAccount) access() (context.Context, bool) { | |
| 156 | 新增: if a == nil { | |
| 157 | 新增: return nil, false | |
| 158 | 新增: } | |
| 159 | 新增: a.mu.Lock() | |
| 160 | 新增: defer a.mu.Unlock() | |
| 161 | 新增: return a.epoch, len(a.key) == 32 | |
| 162 | 新增:} | |
| 163 | 新增: | |
| 164 | 新增:func (a *localAccount) setKey(key []byte) { | |
| 165 | 新增: if a.cancel != nil { | |
| 166 | 新增: a.cancel() | |
| 167 | 新增: } | |
| 168 | 新增: clear(a.key) | |
| 169 | 新增: a.key = key | |
| 170 | 新增: a.epoch, a.cancel = context.WithCancel(context.Background()) | |
| 171 | 新增:} | |
| 172 | 新增: | |
| 173 | 新增:func (a *localAccount) lock() { | |
| 174 | 新增: if a == nil { | |
| 175 | 新增: return | |
| 176 | 新增: } | |
| 177 | 新增: a.mu.Lock() | |
| 178 | 新增: defer a.mu.Unlock() | |
| 179 | 新增: if a.cancel != nil { | |
| 180 | 新增: a.cancel() | |
| 181 | 新增: a.cancel = nil | |
| 182 | 新增: } | |
| 183 | 新增: clear(a.key) | |
| 184 | 新增: a.key = nil | |
| 185 | 新增:} | |
| 186 | 新增: | |
| 187 | 新增:func (a *localAccount) create(name, password, avatar string) error { | |
| 188 | 新增: name = strings.TrimSpace(name) | |
| 189 | 新增: if err := validAccountName(name); err != nil { | |
| 190 | 新增: return err | |
| 191 | 新增: } | |
| 192 | 新增: if err := validAccountPassword(password); err != nil { | |
| 193 | 新增: return err | |
| 194 | 新增: } | |
| 195 | 新增: normalized, err := normalizeAccountAvatar(avatar) | |
| 196 | 新增: if err != nil { | |
| 197 | 新增: return err | |
| 198 | 新增: } | |
| 199 | 新增: a.mu.Lock() | |
| 200 | 新增: defer a.mu.Unlock() | |
| 201 | 新增: if a.record != nil { | |
| 202 | 新增: return errors.New("此配置已创建本地账户,请登录") | |
| 203 | 新增: } | |
| 204 | 新增: key := make([]byte, 32) | |
| 205 | 新增: if _, err = rand.Read(key); err != nil { | |
| 206 | 新增: return err | |
| 207 | 新增: } | |
| 208 | 新增: defer clear(key) | |
| 209 | 新增: record := &accountRecord{Version: 1, Username: name, Avatar: normalized} | |
| 210 | 新增: if err = sealAccountKey(record, password, key); err != nil { | |
| 211 | 新增: return err | |
| 212 | 新增: } | |
| 213 | 新增: if err = writePrivate(a.path, record); err != nil { | |
| 214 | 新增: return errors.New("账户未能保存,请检查磁盘空间与目录权限") | |
| 215 | 新增: } | |
| 216 | 新增: a.record = record | |
| 217 | 新增: a.setKey(append([]byte(nil), key...)) | |
| 218 | 新增: return nil | |
| 219 | 新增:} | |
| 220 | 新增: | |
| 221 | 新增:func (a *localAccount) unlock(password string) error { | |
| 222 | 新增: a.mu.Lock() | |
| 223 | 新增: defer a.mu.Unlock() | |
| 224 | 新增: if a.record == nil { | |
| 225 | 新增: return errors.New("请先创建本地账户") | |
| 226 | 新增: } | |
| 227 | 新增: if time.Now().Before(a.nextAttempt) { | |
| 228 | 新增: return errors.New("请稍后再试") | |
| 229 | 新增: } | |
| 230 | 新增: key, err := openAccountKey(a.record, password) | |
| 231 | 新增: if err != nil { | |
| 232 | 新增: a.nextAttempt = time.Now().Add(time.Second) | |
| 233 | 新增: return err | |
| 234 | 新增: } | |
| 235 | 新增: a.nextAttempt = time.Time{} | |
| 236 | 新增: if err = a.clearAuthenticationRequirement(); err != nil { | |
| 237 | 新增: clear(key) | |
| 238 | 新增: return err | |
| 239 | 新增: } | |
| 240 | 新增: a.setKey(key) | |
| 241 | 新增: return nil | |
| 242 | 新增:} | |
| 243 | 新增: | |
| 244 | 新增:func (a *localAccount) updateProfile(name, avatar string) error { | |
| 245 | 新增: name = strings.TrimSpace(name) | |
| 246 | 新增: if err := validAccountName(name); err != nil { | |
| 247 | 新增: return err | |
| 248 | 新增: } | |
| 249 | 新增: normalized, err := normalizeAccountAvatar(avatar) | |
| 250 | 新增: if err != nil { | |
| 251 | 新增: return err | |
| 252 | 新增: } | |
| 253 | 新增: a.mu.Lock() | |
| 254 | 新增: defer a.mu.Unlock() | |
| 255 | 新增: if len(a.key) != 32 { | |
| 256 | 新增: return errors.New("请先解锁 Cage") | |
| 257 | 新增: } | |
| 258 | 新增: record := *a.record | |
| 259 | 新增: record.Username = name | |
| 260 | 新增: record.Avatar = normalized | |
| 261 | 新增: if err = writePrivate(a.path, record); err != nil { | |
| 262 | 新增: return errors.New("资料未能保存,请重试") | |
| 263 | 新增: } | |
| 264 | 新增: a.record = &record | |
| 265 | 新增: return nil | |
| 266 | 新增:} | |
| 267 | 新增: | |
| 268 | 新增:func (a *localAccount) changePassword(oldPassword, newPassword string) error { | |
| 269 | 新增: if err := validAccountPassword(newPassword); err != nil { | |
| 270 | 新增: return err | |
| 271 | 新增: } | |
| 272 | 新增: a.mu.Lock() | |
| 273 | 新增: defer a.mu.Unlock() | |
| 274 | 新增: if len(a.key) != 32 { | |
| 275 | 新增: return errors.New("请先解锁 Cage") | |
| 276 | 新增: } | |
| 277 | 新增: if time.Now().Before(a.nextAttempt) { | |
| 278 | 新增: return errors.New("请稍后再试") | |
| 279 | 新增: } | |
| 280 | 新增: key, err := openAccountKey(a.record, oldPassword) | |
| 281 | 新增: if err != nil { | |
| 282 | 新增: a.nextAttempt = time.Now().Add(time.Second) | |
| 283 | 新增: return err | |
| 284 | 新增: } | |
| 285 | 新增: defer clear(key) | |
| 286 | 新增: record := *a.record | |
| 287 | 新增: if err = sealAccountKey(&record, newPassword, key); err != nil { | |
| 288 | 新增: return err | |
| 289 | 新增: } | |
| 290 | 新增: if err = writePrivate(a.path, record); err != nil { | |
| 291 | 新增: return errors.New("新密码未能保存,原密码仍然有效") | |
| 292 | 新增: } | |
| 293 | 新增: a.record = &record | |
| 294 | 新增: a.nextAttempt = time.Time{} | |
| 295 | 新增: return nil | |
| 296 | 新增:} | |
| 297 | 新增: | |
| 298 | 新增:func (a *localAccount) desktopKey() ([]byte, error) { | |
| 299 | 新增: a.mu.Lock() | |
| 300 | 新增: defer a.mu.Unlock() | |
| 301 | 新增: if len(a.key) != 32 { | |
| 302 | 新增: return nil, errors.New("请先登录 Cage,再打开 Claude Desktop") | |
| 303 | 新增: } | |
| 304 | 新增: // Base64 is accepted by the keyring without newline/encoding ambiguity. | |
| 305 | 新增: encoded := make([]byte, base64.RawStdEncoding.EncodedLen(len(a.key))) | |
| 306 | 新增: base64.RawStdEncoding.Encode(encoded, a.key) | |
| 307 | 新增: return encoded, nil | |
| 308 | 新增:} | |
| 309 | 新增: | |
| 310 | 新增:func normalizeAccountAvatar(value string) (string, error) { | |
| 311 | 新增: if value == "" { | |
| 312 | 新增: return "", nil | |
| 313 | 新增: } | |
| 314 | 新增: const maxBytes = 2 << 20 | |
| 315 | 新增: if len(value) > maxBytes*4/3+100 { | |
| 316 | 新增: return "", errors.New("头像图片不能超过 2 MB") | |
| 317 | 新增: } | |
| 318 | 新增: _, payload, ok := strings.Cut(value, ",") | |
| 319 | 新增: if !ok || (!strings.HasPrefix(value, "data:image/png;base64,") && !strings.HasPrefix(value, "data:image/jpeg;base64,")) { | |
| 320 | 新增: return "", errors.New("请选择 PNG 或 JPEG 图片") | |
| 321 | 新增: } | |
| 322 | 新增: b, err := base64.StdEncoding.DecodeString(payload) | |
| 323 | 新增: if err != nil || len(b) > maxBytes { | |
| 324 | 新增: return "", errors.New("头像图片无效") | |
| 325 | 新增: } | |
| 326 | 新增: cfg, _, err := image.DecodeConfig(bytes.NewReader(b)) | |
| 327 | 新增: if err != nil || cfg.Width < 1 || cfg.Height < 1 || cfg.Width > 4096 || cfg.Height > 4096 || cfg.Width*cfg.Height > 8_000_000 { | |
| 328 | 新增: return "", errors.New("头像图片尺寸无效或过大") | |
| 329 | 新增: } | |
| 330 | 新增: src, _, err := image.Decode(bytes.NewReader(b)) | |
| 331 | 新增: if err != nil { | |
| 332 | 新增: return "", errors.New("无法读取头像图片") | |
| 333 | 新增: } | |
| 334 | 新增: size := min(cfg.Width, cfg.Height) | |
| 335 | 新增: x0, y0 := (cfg.Width-size)/2, (cfg.Height-size)/2 | |
| 336 | 新增: dst := image.NewRGBA(image.Rect(0, 0, 128, 128)) | |
| 337 | 新增: for y := 0; y < 128; y++ { | |
| 338 | 新增: for x := 0; x < 128; x++ { | |
| 339 | 新增: dst.Set(x, y, src.At(x0+x*size/128, y0+y*size/128)) | |
| 340 | 新增: } | |
| 341 | 新增: } | |
| 342 | 新增: var out bytes.Buffer | |
| 343 | 新增: if err = png.Encode(&out, dst); err != nil { | |
| 344 | 新增: return "", err | |
| 345 | 新增: } | |
| 346 | 新增: return "data:image/png;base64," + base64.StdEncoding.EncodeToString(out.Bytes()), nil | |
| 347 | 新增:} | |
| @@ -0,0 +1,241 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "encoding/base64" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "image" | |
| 8 | 新增: "image/color" | |
| 9 | 新增: "image/png" | |
| 10 | 新增: "net/http" | |
| 11 | 新增: "net/http/httptest" | |
| 12 | 新增: "os" | |
| 13 | 新增: "path/filepath" | |
| 14 | 新增: "strings" | |
| 15 | 新增: "testing" | |
| 16 | 新增: "time" | |
| 17 | 新增: | |
| 18 | 新增: "github.com/gorilla/websocket" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:func newTestAccount(t *testing.T) *localAccount { | |
| 22 | 新增: t.Helper() | |
| 23 | 新增: a, err := loadLocalAccount(t.TempDir()) | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: if err = a.create("林间工作室", "initial-test-password", ""); err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: t.Cleanup(a.lock) | |
| 31 | 新增: return a | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:func TestLocalAccountEncryptionPasswordChangeAndReload(t *testing.T) { | |
| 35 | 新增: a := newTestAccount(t) | |
| 36 | 新增: key, _ := a.desktopKey() | |
| 37 | 新增: defer clear(key) | |
| 38 | 新增: data, err := os.ReadFile(a.path) | |
| 39 | 新增: if err != nil || bytes.Contains(data, []byte("initial-test-password")) || bytes.Contains(data, key) { | |
| 40 | 新增: t.Fatal("plaintext credentials persisted", err) | |
| 41 | 新增: } | |
| 42 | 新增: if err = a.changePassword("initial-test-password", "replacement-test-password"); err != nil { | |
| 43 | 新增: t.Fatal(err) | |
| 44 | 新增: } | |
| 45 | 新增: a.lock() | |
| 46 | 新增: reloaded, err := loadLocalAccount(filepath.Dir(a.path)) | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: t.Fatal(err) | |
| 49 | 新增: } | |
| 50 | 新增: defer reloaded.lock() | |
| 51 | 新增: if reloaded.view().Unlocked { | |
| 52 | 新增: t.Fatal("reloaded account must be locked") | |
| 53 | 新增: } | |
| 54 | 新增: if err = reloaded.unlock("initial-test-password"); err == nil { | |
| 55 | 新增: t.Fatal("old password accepted") | |
| 56 | 新增: } | |
| 57 | 新增: reloaded.nextAttempt = time.Time{} | |
| 58 | 新增: if err = reloaded.unlock("replacement-test-password"); err != nil { | |
| 59 | 新增: t.Fatal(err) | |
| 60 | 新增: } | |
| 61 | 新增: after, _ := reloaded.desktopKey() | |
| 62 | 新增: defer clear(after) | |
| 63 | 新增: if !bytes.Equal(after, key) { | |
| 64 | 新增: t.Fatal("password change rotated the guest key and lost existing login access") | |
| 65 | 新增: } | |
| 66 | 新增: if err = reloaded.create("other", "new-password", ""); err == nil { | |
| 67 | 新增: t.Fatal("second account replaced the existing account") | |
| 68 | 新增: } | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:func TestLocalAccountFailedSavePreservesExistingPassword(t *testing.T) { | |
| 72 | 新增: a := newTestAccount(t) | |
| 73 | 新增: path := a.path | |
| 74 | 新增: a.path = t.TempDir() | |
| 75 | 新增: if err := a.changePassword("initial-test-password", "replacement-test-password"); err == nil { | |
| 76 | 新增: t.Fatal("save unexpectedly succeeded") | |
| 77 | 新增: } | |
| 78 | 新增: a.path = path | |
| 79 | 新增: a.lock() | |
| 80 | 新增: if err := a.unlock("initial-test-password"); err != nil { | |
| 81 | 新增: t.Fatal("failed save changed the active password", err) | |
| 82 | 新增: } | |
| 83 | 新增:} | |
| 84 | 新增: | |
| 85 | 新增:func TestLocalAccountProfileAndAvatarPersistWithoutRekey(t *testing.T) { | |
| 86 | 新增: a := newTestAccount(t) | |
| 87 | 新增: before, _ := a.desktopKey() | |
| 88 | 新增: defer clear(before) | |
| 89 | 新增: img := image.NewRGBA(image.Rect(0, 0, 200, 100)) | |
| 90 | 新增: img.Set(100, 50, color.RGBA{R: 240, G: 100, B: 40, A: 255}) | |
| 91 | 新增: var b bytes.Buffer | |
| 92 | 新增: _ = png.Encode(&b, img) | |
| 93 | 新增: avatar := "data:image/png;base64," + base64.StdEncoding.EncodeToString(b.Bytes()) | |
| 94 | 新增: if err := a.updateProfile(" 山雀 ", avatar); err != nil { | |
| 95 | 新增: t.Fatal(err) | |
| 96 | 新增: } | |
| 97 | 新增: data, _ := base64.StdEncoding.DecodeString(strings.SplitN(a.view().Avatar, ",", 2)[1]) | |
| 98 | 新增: cfg, _, err := image.DecodeConfig(bytes.NewReader(data)) | |
| 99 | 新增: if err != nil || cfg.Width != 128 || cfg.Height != 128 { | |
| 100 | 新增: t.Fatal("avatar was not normalized", cfg, err) | |
| 101 | 新增: } | |
| 102 | 新增: loaded, err := loadLocalAccount(filepath.Dir(a.path)) | |
| 103 | 新增: if err != nil { | |
| 104 | 新增: t.Fatal(err) | |
| 105 | 新增: } | |
| 106 | 新增: if loaded.view().Username != "山雀" || loaded.view().Avatar != a.view().Avatar { | |
| 107 | 新增: t.Fatal("profile did not persist") | |
| 108 | 新增: } | |
| 109 | 新增: after, _ := a.desktopKey() | |
| 110 | 新增: defer clear(after) | |
| 111 | 新增: if !bytes.Equal(before, after) { | |
| 112 | 新增: t.Fatal("profile edit changed credential key") | |
| 113 | 新增: } | |
| 114 | 新增: if err := a.updateProfile("山雀", "data:image/svg+xml;base64,PHN2Zy8+"); err == nil { | |
| 115 | 新增: t.Fatal("active content accepted as avatar") | |
| 116 | 新增: } | |
| 117 | 新增:} | |
| 118 | 新增: | |
| 119 | 新增:func TestLocalAccountCorruptionCannotBecomeFirstRun(t *testing.T) { | |
| 120 | 新增: a := newTestAccount(t) | |
| 121 | 新增: if err := os.WriteFile(a.path, []byte(`{"version":1}`), 0600); err != nil { | |
| 122 | 新增: t.Fatal(err) | |
| 123 | 新增: } | |
| 124 | 新增: if _, err := loadLocalAccount(filepath.Dir(a.path)); err == nil { | |
| 125 | 新增: t.Fatal("corrupt account silently became setup/unlocked") | |
| 126 | 新增: } | |
| 127 | 新增:} | |
| 128 | 新增: | |
| 129 | 新增:func TestAccountLockBlocksRoutesAndCancelsAccess(t *testing.T) { | |
| 130 | 新增: s := testServer(t) | |
| 131 | 新增: ctx, ok := s.account.access() | |
| 132 | 新增: if !ok { | |
| 133 | 新增: t.Fatal("fixture locked") | |
| 134 | 新增: } | |
| 135 | 新增: w := request(s, "POST", "/api/account/lock", s.origin, "{}", true) | |
| 136 | 新增: if w.Code != 200 { | |
| 137 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 138 | 新增: } | |
| 139 | 新增: select { | |
| 140 | 新增: case <-ctx.Done(): | |
| 141 | 新增: default: | |
| 142 | 新增: t.Fatal("active requests not cancelled") | |
| 143 | 新增: } | |
| 144 | 新增: for _, path := range []string{"/api/settings", "/api/terminals", "/api/vnc-credentials", "/api/claude-desktop/vnc-credentials", "/api/audio"} { | |
| 145 | 新增: if w = request(s, "GET", path, "", "", true); w.Code != 423 { | |
| 146 | 新增: t.Fatal(path, w.Code) | |
| 147 | 新增: } | |
| 148 | 新增: } | |
| 149 | 新增: if w = request(s, "GET", "/api/account", "", "", true); w.Code != 200 { | |
| 150 | 新增: t.Fatal("lock screen cannot read public profile") | |
| 151 | 新增: } | |
| 152 | 新增: if w = request(s, "GET", "/api/account", "", "", false); w.Code != 401 { | |
| 153 | 新增: t.Fatal("account bypassed host session") | |
| 154 | 新增: } | |
| 155 | 新增:} | |
| 156 | 新增: | |
| 157 | 新增:func TestLockDisconnectsTerminalViewerWithoutEndingSession(t *testing.T) { | |
| 158 | 新增: s := testServer(t) | |
| 159 | 新增: term := &terminalSession{id: "keep", title: "ongoing work", history: []byte("still running"), clients: map[chan []byte]bool{}} | |
| 160 | 新增: s.terminals[term.id] = term | |
| 161 | 新增: server := httptest.NewServer(s.handler()) | |
| 162 | 新增: defer server.Close() | |
| 163 | 新增: s.origin = server.URL | |
| 164 | 新增: headers := http.Header{"Origin": {server.URL}, "Cookie": {s.cookieName() + "=" + s.session}} | |
| 165 | 新增: ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+"/api/terminals/keep/stream", headers) | |
| 166 | 新增: if err != nil { | |
| 167 | 新增: t.Fatal(err) | |
| 168 | 新增: } | |
| 169 | 新增: defer ws.Close() | |
| 170 | 新增: _, data, err := ws.ReadMessage() | |
| 171 | 新增: if err != nil || string(data) != "still running" { | |
| 172 | 新增: t.Fatal("viewer did not attach", err) | |
| 173 | 新增: } | |
| 174 | 新增: s.account.lock() | |
| 175 | 新增: _ = ws.SetReadDeadline(time.Now().Add(time.Second)) | |
| 176 | 新增: if _, _, err = ws.ReadMessage(); err == nil { | |
| 177 | 新增: t.Fatal("locked viewer retained its connection") | |
| 178 | 新增: } | |
| 179 | 新增: term.mu.Lock() | |
| 180 | 新增: defer term.mu.Unlock() | |
| 181 | 新增: if term.closed || string(term.history) != "still running" { | |
| 182 | 新增: t.Fatal("locking destroyed the background terminal") | |
| 183 | 新增: } | |
| 184 | 新增:} | |
| 185 | 新增: | |
| 186 | 新增:func TestLoginRequiresValidPasswordBeforeProtectedAPIs(t *testing.T) { | |
| 187 | 新增: s := testServer(t) | |
| 188 | 新增: a := newTestAccount(t) | |
| 189 | 新增: a.lock() | |
| 190 | 新增: s.account = a | |
| 191 | 新增: w := request(s, "POST", "/api/account/unlock", s.origin, `{"password":"wrong-password"}`, true) | |
| 192 | 新增: if w.Code != 400 { | |
| 193 | 新增: t.Fatal(w.Code) | |
| 194 | 新增: } | |
| 195 | 新增: if w = request(s, "GET", "/api/settings", "", "", true); w.Code != 423 { | |
| 196 | 新增: t.Fatal("wrong password granted access") | |
| 197 | 新增: } | |
| 198 | 新增: a.nextAttempt = time.Time{} | |
| 199 | 新增: w = request(s, "POST", "/api/account/unlock", s.origin, `{"password":"initial-test-password"}`, true) | |
| 200 | 新增: if w.Code != 200 { | |
| 201 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 202 | 新增: } | |
| 203 | 新增: if w = request(s, "GET", "/api/settings", "", "", true); w.Code != 200 { | |
| 204 | 新增: t.Fatal(w.Code) | |
| 205 | 新增: } | |
| 206 | 新增: ctx, ok := a.access() | |
| 207 | 新增: if !ok || ctx.Err() != nil { | |
| 208 | 新增: t.Fatal("unlock did not establish fresh access context") | |
| 209 | 新增: } | |
| 210 | 新增:} | |
| 211 | 新增: | |
| 212 | 新增:func TestLogoutJoinsActiveStopAndLocksOnlyOnSuccess(t *testing.T) { | |
| 213 | 新增: for _, failed := range []bool{false, true} { | |
| 214 | 新增: t.Run(map[bool]string{false: "success", true: "failure"}[failed], func(t *testing.T) { | |
| 215 | 新增: s := testServer(t) | |
| 216 | 新增: started, finish := make(chan struct{}), make(chan struct{}) | |
| 217 | 新增: s.launch(httptest.NewRecorder(), "stop", func() error { | |
| 218 | 新增: close(started) | |
| 219 | 新增: <-finish | |
| 220 | 新增: if failed { | |
| 221 | 新增: return errors.New("stop failed") | |
| 222 | 新增: } | |
| 223 | 新增: return nil | |
| 224 | 新增: }) | |
| 225 | 新增: <-started | |
| 226 | 新增: w := request(s, "POST", "/api/account/logout", s.origin, "{}", true) | |
| 227 | 新增: if w.Code != 200 { | |
| 228 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 229 | 新增: } | |
| 230 | 新增: if !s.account.view().Unlocked { | |
| 231 | 新增: t.Fatal("logout locked before stop completed") | |
| 232 | 新增: } | |
| 233 | 新增: close(finish) | |
| 234 | 新增: s.op.Lock() | |
| 235 | 新增: defer s.op.Unlock() | |
| 236 | 新增: if s.account.view().Unlocked != failed { | |
| 237 | 新增: t.Fatal("logout did not follow the active stop result") | |
| 238 | 新增: } | |
| 239 | 新增: }) | |
| 240 | 新增: } | |
| 241 | 新增:} | |
| @@ -8,6 +8,7 @@ import ( | ||
| 8 | 8 | "path/filepath" |
| 9 | 9 | "regexp" |
| 10 | 10 | "strings" |
| 11 | 新增: "unicode/utf8" | |
| 11 | 12 | |
| 12 | 13 | "github.com/pelletier/go-toml/v2" |
| 13 | 14 | ) |
| @@ -17,23 +18,32 @@ type AppearanceFonts struct { | ||
| 17 | 18 | Code string `json:"code" toml:"code"` |
| 18 | 19 | } |
| 19 | 20 | type AppearanceTheme struct { |
| 20 | 删除: Preset string `json:"preset"` | |
| 21 | 删除: Accent string `json:"accent" toml:"accent"` | |
| 22 | 删除: Surface string `json:"surface" toml:"surface"` | |
| 23 | 删除: Ink string `json:"ink" toml:"ink"` | |
| 24 | 删除: Contrast int `json:"contrast" toml:"contrast"` | |
| 25 | 删除: OpaqueWindows bool `json:"opaqueWindows" toml:"opaqueWindows"` | |
| 26 | 删除: Fonts AppearanceFonts `json:"fonts" toml:"fonts"` | |
| 21 | 新增: Preset string `json:"preset"` | |
| 22 | 新增: Accent string `json:"accent" toml:"accent"` | |
| 23 | 新增: Surface string `json:"surface" toml:"surface"` | |
| 24 | 新增: Ink string `json:"ink" toml:"ink"` | |
| 25 | 新增: Contrast int `json:"contrast" toml:"contrast"` | |
| 26 | 新增: OpaqueWindows bool `json:"opaqueWindows" toml:"opaqueWindows"` | |
| 27 | 新增: Fonts AppearanceFonts `json:"fonts" toml:"fonts"` | |
| 28 | 新增: Colors map[string]string `json:"colors,omitempty"` | |
| 29 | 新增: Terminal map[string]string `json:"terminal,omitempty"` | |
| 30 | 新增:} | |
| 31 | 新增:type SavedAppearanceTheme struct { | |
| 32 | 新增: ID string `json:"id"` | |
| 33 | 新增: Name string `json:"name"` | |
| 34 | 新增: Light AppearanceTheme `json:"lightTheme"` | |
| 35 | 新增: Dark AppearanceTheme `json:"darkTheme"` | |
| 27 | 36 | } |
| 28 | 37 | type Appearance struct { |
| 29 | 删除: Mode string `json:"mode"` | |
| 30 | 删除: Light AppearanceTheme `json:"lightTheme"` | |
| 31 | 删除: Dark AppearanceTheme `json:"darkTheme"` | |
| 32 | 删除: UIFontSize int `json:"uiFontSize"` | |
| 33 | 删除: CodeFontSize int `json:"codeFontSize"` | |
| 34 | 删除: PointerCursors bool `json:"pointerCursors"` | |
| 35 | 删除: FontSmoothing bool `json:"fontSmoothing"` | |
| 36 | 删除: ReducedMotion string `json:"reducedMotion"` | |
| 38 | 新增: CustomThemes []SavedAppearanceTheme `json:"customThemes,omitempty"` | |
| 39 | 新增: Mode string `json:"mode"` | |
| 40 | 新增: Light AppearanceTheme `json:"lightTheme"` | |
| 41 | 新增: Dark AppearanceTheme `json:"darkTheme"` | |
| 42 | 新增: UIFontSize int `json:"uiFontSize"` | |
| 43 | 新增: CodeFontSize int `json:"codeFontSize"` | |
| 44 | 新增: PointerCursors bool `json:"pointerCursors"` | |
| 45 | 新增: FontSmoothing bool `json:"fontSmoothing"` | |
| 46 | 新增: ReducedMotion string `json:"reducedMotion"` | |
| 37 | 47 | } |
| 38 | 48 | |
| 39 | 49 | func defaultAppearance() Appearance { |
| @@ -50,20 +60,68 @@ func (a Appearance) validate() error { | ||
| 50 | 60 | if a.ReducedMotion != "system" && a.ReducedMotion != "on" && a.ReducedMotion != "off" { |
| 51 | 61 | return errors.New("减少动态效果选项无效") |
| 52 | 62 | } |
| 53 | 删除: color := regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) | |
| 54 | 删除: for _, theme := range []AppearanceTheme{a.Light, a.Dark} { | |
| 55 | 删除: if !color.MatchString(theme.Accent) || !color.MatchString(theme.Surface) || !color.MatchString(theme.Ink) { | |
| 56 | 删除: return errors.New("颜色须为六位十六进制值,例如 #fdf6e3") | |
| 63 | 新增: if err := validateAppearanceTheme(a.Light); err != nil { | |
| 64 | 新增: return err | |
| 65 | 新增: } | |
| 66 | 新增: if err := validateAppearanceTheme(a.Dark); err != nil { | |
| 67 | 新增: return err | |
| 68 | 新增: } | |
| 69 | 新增: if len(a.CustomThemes) > 50 { | |
| 70 | 新增: return errors.New("最多保存 50 个自定义主题,请先删除不需要的主题") | |
| 71 | 新增: } | |
| 72 | 新增: ids := make(map[string]bool) | |
| 73 | 新增: for _, saved := range a.CustomThemes { | |
| 74 | 新增: if !regexp.MustCompile(`^[a-zA-Z0-9_-]{1,80}$`).MatchString(saved.ID) || ids[saved.ID] { | |
| 75 | 新增: return errors.New("自定义主题标识无效或重复") | |
| 76 | 新增: } | |
| 77 | 新增: ids[saved.ID] = true | |
| 78 | 新增: if strings.TrimSpace(saved.Name) == "" || utf8.RuneCountInString(saved.Name) > 80 { | |
| 79 | 新增: return errors.New("请输入 1–80 个字符的主题名称") | |
| 57 | 80 | } |
| 58 | 删除: if theme.Contrast < 0 || theme.Contrast > 100 { | |
| 59 | 删除: return errors.New("对比度范围为 0–100") | |
| 81 | 新增: if err := validateAppearanceTheme(saved.Light); err != nil { | |
| 82 | 新增: return err | |
| 60 | 83 | } |
| 61 | 删除: if len(theme.Preset) > 80 { | |
| 62 | 删除: return errors.New("主题名称过长") | |
| 84 | 新增: if err := validateAppearanceTheme(saved.Dark); err != nil { | |
| 85 | 新增: return err | |
| 63 | 86 | } |
| 64 | 删除: for _, font := range []string{theme.Fonts.UI, theme.Fonts.Code} { | |
| 65 | 删除: if len(font) > 200 || strings.ContainsAny(font, ";{}<>\r\n") { | |
| 66 | 删除: return errors.New("字体名称无效") | |
| 87 | 新增: } | |
| 88 | 新增: return nil | |
| 89 | 新增:} | |
| 90 | 新增: | |
| 91 | 新增:var appearanceColorKeys = strings.Fields("sidebar sidebarInk toolbar toolbarInk chrome chromeDark strong muted line input button buttonInk accentInk link focus hover selected selection success warning danger inactive") | |
| 92 | 新增:var terminalColorKeys = strings.Fields("background foreground cursor cursorAccent selectionBackground black red green yellow blue magenta cyan white brightBlack brightRed brightGreen brightYellow brightBlue brightMagenta brightCyan brightWhite") | |
| 93 | 新增:var appearanceColor = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) | |
| 94 | 新增: | |
| 95 | 新增:func validateAppearanceTheme(theme AppearanceTheme) error { | |
| 96 | 新增: if !appearanceColor.MatchString(theme.Accent) || !appearanceColor.MatchString(theme.Surface) || !appearanceColor.MatchString(theme.Ink) { | |
| 97 | 新增: return errors.New("颜色须为六位十六进制值,例如 #fdf6e3") | |
| 98 | 新增: } | |
| 99 | 新增: if theme.Contrast < 0 || theme.Contrast > 100 { | |
| 100 | 新增: return errors.New("对比度范围为 0–100") | |
| 101 | 新增: } | |
| 102 | 新增: if utf8.RuneCountInString(theme.Preset) > 80 { | |
| 103 | 新增: return errors.New("主题名称过长") | |
| 104 | 新增: } | |
| 105 | 新增: for _, font := range []string{theme.Fonts.UI, theme.Fonts.Code} { | |
| 106 | 新增: if utf8.RuneCountInString(font) > 200 || strings.ContainsAny(font, ";{}<>\r\n") { | |
| 107 | 新增: return errors.New("字体名称无效") | |
| 108 | 新增: } | |
| 109 | 新增: } | |
| 110 | 新增: for field, colors := range map[string]map[string]string{"colors": theme.Colors, "terminal": theme.Terminal} { | |
| 111 | 新增: allowed := appearanceColorKeys | |
| 112 | 新增: if field == "terminal" { | |
| 113 | 新增: allowed = terminalColorKeys | |
| 114 | 新增: } | |
| 115 | 新增: for key, value := range colors { | |
| 116 | 新增: found := false | |
| 117 | 新增: for _, candidate := range allowed { | |
| 118 | 新增: if key == candidate { | |
| 119 | 新增: found = true | |
| 120 | 新增: break | |
| 121 | 新增: } | |
| 122 | 新增: } | |
| 123 | 新增: if !found || !appearanceColor.MatchString(value) { | |
| 124 | 新增: return errors.New("元素颜色无效或包含不支持的颜色项目") | |
| 67 | 125 | } |
| 68 | 126 | } |
| 69 | 127 | } |
| @@ -89,7 +147,7 @@ func (s *Server) getAppearance(w http.ResponseWriter, r *http.Request) { | ||
| 89 | 147 | |
| 90 | 148 | func (s *Server) saveAppearance(w http.ResponseWriter, r *http.Request) { |
| 91 | 149 | var a Appearance |
| 92 | 删除: if !readJSON(w, r, &a) { | |
| 150 | 新增: if !readJSON(w, r, &a, 512<<10) { | |
| 93 | 151 | return |
| 94 | 152 | } |
| 95 | 153 | if err := a.validate(); err != nil { |
| @@ -3,9 +3,12 @@ package workbench | ||
| 3 | 3 | import ( |
| 4 | 4 | "bytes" |
| 5 | 5 | "encoding/json" |
| 6 | 新增: "fmt" | |
| 6 | 7 | "net/http/httptest" |
| 7 | 8 | "os" |
| 8 | 9 | "path/filepath" |
| 10 | 新增: "reflect" | |
| 11 | 新增: "strings" | |
| 9 | 12 | "testing" |
| 10 | 13 | ) |
| 11 | 14 | |
| @@ -71,7 +74,7 @@ func TestAppearanceSaveDoesNotChangeEnvironmentAndRejectsBadInput(t *testing.T) | ||
| 71 | 74 | w = httptest.NewRecorder() |
| 72 | 75 | s.getAppearance(w, httptest.NewRequest("GET", "/api/appearance", nil)) |
| 73 | 76 | var saved Appearance |
| 74 | 删除: if err := json.Unmarshal(w.Body.Bytes(), &saved); err != nil || saved != a { | |
| 77 | 新增: if err := json.Unmarshal(w.Body.Bytes(), &saved); err != nil || !reflect.DeepEqual(saved, a) { | |
| 75 | 78 | t.Fatalf("appearance did not round trip: %s", w.Body.String()) |
| 76 | 79 | } |
| 77 | 80 | a.UIFontSize = 400 |
| @@ -88,3 +91,100 @@ func TestAppearanceSaveDoesNotChangeEnvironmentAndRejectsBadInput(t *testing.T) | ||
| 88 | 91 | t.Fatal("invalid settings replaced saved appearance") |
| 89 | 92 | } |
| 90 | 93 | } |
| 94 | 新增: | |
| 95 | 新增:func TestAppearanceCustomThemesPersistAndInvalidUpdatesKeepFile(t *testing.T) { | |
| 96 | 新增: s := &Server{profile: t.TempDir()} | |
| 97 | 新增: a := defaultAppearance() | |
| 98 | 新增: a.Light.Colors = map[string]string{"chrome": "#123456", "buttonInk": "#abcdef"} | |
| 99 | 新增: a.Dark.Terminal = map[string]string{"background": "#112233", "brightRed": "#aabbcc"} | |
| 100 | 新增: a.CustomThemes = []SavedAppearanceTheme{{ID: "my-theme", Name: "我的配色", Light: a.Light, Dark: a.Dark}} | |
| 101 | 新增: save := func(a Appearance) *httptest.ResponseRecorder { | |
| 102 | 新增: b, _ := json.Marshal(a) | |
| 103 | 新增: req := httptest.NewRequest("POST", "/api/appearance", bytes.NewReader(b)) | |
| 104 | 新增: req.Header.Set("Content-Type", "application/json") | |
| 105 | 新增: w := httptest.NewRecorder() | |
| 106 | 新增: s.saveAppearance(w, req) | |
| 107 | 新增: return w | |
| 108 | 新增: } | |
| 109 | 新增: if w := save(a); w.Code != 200 { | |
| 110 | 新增: t.Fatal(w.Body.String()) | |
| 111 | 新增: } | |
| 112 | 新增: original, err := os.ReadFile(filepath.Join(s.profile, "appearance.json")) | |
| 113 | 新增: if err != nil { | |
| 114 | 新增: t.Fatal(err) | |
| 115 | 新增: } | |
| 116 | 新增: restarted := &Server{profile: s.profile} | |
| 117 | 新增: w := httptest.NewRecorder() | |
| 118 | 新增: restarted.getAppearance(w, httptest.NewRequest("GET", "/api/appearance", nil)) | |
| 119 | 新增: var loaded Appearance | |
| 120 | 新增: if err := json.Unmarshal(w.Body.Bytes(), &loaded); err != nil || !reflect.DeepEqual(loaded, a) { | |
| 121 | 新增: t.Fatalf("lost saved themes: %s", w.Body.String()) | |
| 122 | 新增: } | |
| 123 | 新增: for _, mutate := range []func(*Appearance){ | |
| 124 | 新增: func(a *Appearance) { a.Light.Colors["chrome"] = "red" }, | |
| 125 | 新增: func(a *Appearance) { a.Dark.Terminal["unknown"] = "#ffffff" }, | |
| 126 | 新增: func(a *Appearance) { a.CustomThemes[0].Name = " " }, | |
| 127 | 新增: func(a *Appearance) { a.CustomThemes = append(a.CustomThemes, a.CustomThemes[0]) }, | |
| 128 | 新增: func(a *Appearance) { a.CustomThemes[0].Dark.Colors = map[string]string{"line": "#abc"} }, | |
| 129 | 新增: } { | |
| 130 | 新增: var invalid Appearance | |
| 131 | 新增: if err := json.Unmarshal(original, &invalid); err != nil { | |
| 132 | 新增: t.Fatal(err) | |
| 133 | 新增: } | |
| 134 | 新增: mutate(&invalid) | |
| 135 | 新增: if w := save(invalid); w.Code == 200 { | |
| 136 | 新增: t.Fatal("invalid theme accepted") | |
| 137 | 新增: } | |
| 138 | 新增: stored, _ := os.ReadFile(filepath.Join(s.profile, "appearance.json")) | |
| 139 | 新增: if !bytes.Equal(stored, original) { | |
| 140 | 新增: t.Fatal("invalid input replaced valid theme file") | |
| 141 | 新增: } | |
| 142 | 新增: } | |
| 143 | 新增: // The library can exceed the old 64 KB appearance request limit. | |
| 144 | 新增: for i := 1; i < 50; i++ { | |
| 145 | 新增: item := SavedAppearanceTheme{ID: fmt.Sprintf("theme-%d", i), Name: "配色", Light: a.Light, Dark: a.Dark} | |
| 146 | 新增: item.Light.Fonts.UI = strings.Repeat("a", 200) | |
| 147 | 新增: item.Light.Fonts.Code = strings.Repeat("b", 200) | |
| 148 | 新增: item.Dark.Fonts = item.Light.Fonts | |
| 149 | 新增: for _, theme := range []*AppearanceTheme{&item.Light, &item.Dark} { | |
| 150 | 新增: theme.Colors = make(map[string]string) | |
| 151 | 新增: theme.Terminal = make(map[string]string) | |
| 152 | 新增: for _, key := range appearanceColorKeys { | |
| 153 | 新增: theme.Colors[key] = "#123456" | |
| 154 | 新增: } | |
| 155 | 新增: for _, key := range terminalColorKeys { | |
| 156 | 新增: theme.Terminal[key] = "#abcdef" | |
| 157 | 新增: } | |
| 158 | 新增: } | |
| 159 | 新增: a.CustomThemes = append(a.CustomThemes, item) | |
| 160 | 新增: } | |
| 161 | 新增: b, _ := json.Marshal(a) | |
| 162 | 新增: if len(b) <= 64<<10 { | |
| 163 | 新增: t.Fatal("fixture must exceed old request limit") | |
| 164 | 新增: } | |
| 165 | 新增: if w := save(a); w.Code != 200 { | |
| 166 | 新增: t.Fatal(w.Body.String()) | |
| 167 | 新增: } | |
| 168 | 新增: a.CustomThemes = append(a.CustomThemes, SavedAppearanceTheme{ID: "overflow", Name: "超限", Light: a.Light, Dark: a.Dark}) | |
| 169 | 新增: if w := save(a); w.Code == 200 { | |
| 170 | 新增: t.Fatal("library limit not enforced") | |
| 171 | 新增: } | |
| 172 | 新增:} | |
| 173 | 新增: | |
| 174 | 新增:func TestAppearanceLegacyFileKeepsDerivedDefaults(t *testing.T) { | |
| 175 | 新增: s := &Server{profile: t.TempDir()} | |
| 176 | 新增: old := defaultAppearance() | |
| 177 | 新增: b, _ := json.Marshal(old) | |
| 178 | 新增: if err := os.WriteFile(filepath.Join(s.profile, "appearance.json"), b, 0600); err != nil { | |
| 179 | 新增: t.Fatal(err) | |
| 180 | 新增: } | |
| 181 | 新增: w := httptest.NewRecorder() | |
| 182 | 新增: s.getAppearance(w, httptest.NewRequest("GET", "/api/appearance", nil)) | |
| 183 | 新增: if w.Code != 200 { | |
| 184 | 新增: t.Fatal(w.Body.String()) | |
| 185 | 新增: } | |
| 186 | 新增: var loaded Appearance | |
| 187 | 新增: if err := json.Unmarshal(w.Body.Bytes(), &loaded); err != nil || !reflect.DeepEqual(loaded, old) { | |
| 188 | 新增: t.Fatalf("legacy appearance lost: %s", w.Body.String()) | |
| 189 | 新增: } | |
| 190 | 新增:} | |
| @@ -0,0 +1,97 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "io" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "time" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/gorilla/websocket" | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:const audioCaptureCommand = "exec /usr/bin/parec --server=unix:/run/cage-audio/native --record --raw --format=s16le --rate=48000 --channels=2 --device=cage_output.monitor --latency-msec=20" | |
| 14 | 新增: | |
| 15 | 新增:var audioFormat = struct { | |
| 16 | 新增: Format string `json:"format"` | |
| 17 | 新增: SampleRate int `json:"sample_rate"` | |
| 18 | 新增: Channels int `json:"channels"` | |
| 19 | 新增:}{"s16le", 48000, 2} | |
| 20 | 新增: | |
| 21 | 新增:// Audio is a local output stream. It does not grant guest Internet access and | |
| 22 | 新增:// cannot select a microphone, arbitrary guest command, or host audio source. | |
| 23 | 新增:func (s *Server) audio(w http.ResponseWriter, r *http.Request) { | |
| 24 | 新增: s.mu.Lock() | |
| 25 | 新增: available := !s.closing && !s.guestUpdateRequired | |
| 26 | 新增: s.mu.Unlock() | |
| 27 | 新增: if !available || !s.vmRunning() { | |
| 28 | 新增: http.Error(w, "请先启动并更新 Cage 环境", http.StatusConflict) | |
| 29 | 新增: return | |
| 30 | 新增: } | |
| 31 | 新增: if !websocket.IsWebSocketUpgrade(r) { | |
| 32 | 新增: jsonReply(w, audioFormat) | |
| 33 | 新增: return | |
| 34 | 新增: } | |
| 35 | 新增: s.mu.Lock() | |
| 36 | 新增: if s.audioClients >= 4 { | |
| 37 | 新增: s.mu.Unlock() | |
| 38 | 新增: http.Error(w, "声音连接过多,请关闭重复的工作台窗口", http.StatusConflict) | |
| 39 | 新增: return | |
| 40 | 新增: } | |
| 41 | 新增: s.audioClients++ | |
| 42 | 新增: s.mu.Unlock() | |
| 43 | 新增: defer func() { s.mu.Lock(); s.audioClients--; s.mu.Unlock() }() | |
| 44 | 新增: ctx, cancel := context.WithCancel(r.Context()) | |
| 45 | 新增: defer cancel() | |
| 46 | 新增: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", audioCaptureCommand) | |
| 47 | 新增: pipe, err := cmd.StdoutPipe() | |
| 48 | 新增: if err != nil { | |
| 49 | 新增: http.Error(w, "声音连接未能建立", http.StatusBadGateway) | |
| 50 | 新增: return | |
| 51 | 新增: } | |
| 52 | 新增: if err = cmd.Start(); err != nil { | |
| 53 | 新增: http.Error(w, "声音连接未能建立", http.StatusBadGateway) | |
| 54 | 新增: return | |
| 55 | 新增: } | |
| 56 | 新增: defer func() { cancel(); pipe.Close(); _ = cmd.Wait() }() | |
| 57 | 新增: s.streamAudio(w, r.WithContext(ctx), pipe) | |
| 58 | 新增:} | |
| 59 | 新增: | |
| 60 | 新增:func (s *Server) streamAudio(w http.ResponseWriter, r *http.Request, source io.Reader) { | |
| 61 | 新增: ws, err := s.upgrade(w, r) | |
| 62 | 新增: if err != nil { | |
| 63 | 新增: return | |
| 64 | 新增: } | |
| 65 | 新增: defer ws.Close() | |
| 66 | 新增: ws.SetReadLimit(1024) | |
| 67 | 新增: _ = ws.SetWriteDeadline(time.Now().Add(2 * time.Second)) | |
| 68 | 新增: if ws.WriteJSON(audioFormat) != nil { | |
| 69 | 新增: return | |
| 70 | 新增: } | |
| 71 | 新增: // Reading is necessary to observe the client disconnect. The client sends | |
| 72 | 新增: // no audio or commands; any data message closes this output-only stream. | |
| 73 | 新增: go func() { | |
| 74 | 新增: defer ws.Close() | |
| 75 | 新增: _ = sendAudioPCM(ws, source) | |
| 76 | 新增: }() | |
| 77 | 新增: _, _, _ = ws.ReadMessage() | |
| 78 | 新增: // source belongs to the request's SSH process; the caller cancels it when | |
| 79 | 新增: // this handler returns, releasing a blocked read after a disconnect. | |
| 80 | 新增:} | |
| 81 | 新增: | |
| 82 | 新增:func sendAudioPCM(ws *websocket.Conn, source io.Reader) error { | |
| 83 | 新增: packet := make([]byte, 48000*2*2/50) // 20 ms, complete stereo frames. | |
| 84 | 新增: for { | |
| 85 | 新增: n, err := io.ReadFull(source, packet) | |
| 86 | 新增: n -= n % 4 | |
| 87 | 新增: if n > 0 { | |
| 88 | 新增: _ = ws.SetWriteDeadline(time.Now().Add(2 * time.Second)) | |
| 89 | 新增: if writeErr := ws.WriteMessage(websocket.BinaryMessage, packet[:n]); writeErr != nil { | |
| 90 | 新增: return writeErr | |
| 91 | 新增: } | |
| 92 | 新增: } | |
| 93 | 新增: if err != nil { | |
| 94 | 新增: return err | |
| 95 | 新增: } | |
| 96 | 新增: } | |
| 97 | 新增:} | |
| @@ -0,0 +1,76 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "net/http/httptest" | |
| 10 | 新增: "strings" | |
| 11 | 新增: "testing" | |
| 12 | 新增: "time" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/gorilla/websocket" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func TestAudioBoundary(t *testing.T) { | |
| 18 | 新增: s := testServer(t) | |
| 19 | 新增: if w := request(s, "GET", "/api/audio", "", "", false); w.Code != 401 { | |
| 20 | 新增: t.Fatal("audio allowed without session", w.Code) | |
| 21 | 新增: } | |
| 22 | 新增: s.account.lock() | |
| 23 | 新增: if w := request(s, "GET", "/api/audio", "", "", true); w.Code != 423 { | |
| 24 | 新增: t.Fatal("audio allowed while locked", w.Code) | |
| 25 | 新增: } | |
| 26 | 新增: r := httptest.NewRequest("GET", s.origin+"/api/audio", nil) | |
| 27 | 新增: r.Header.Set("Upgrade", "websocket") | |
| 28 | 新增: r.Header.Set("Origin", "https://other.example") | |
| 29 | 新增: w := httptest.NewRecorder() | |
| 30 | 新增: s.handler().ServeHTTP(w, r) | |
| 31 | 新增: if w.Code != 403 { | |
| 32 | 新增: t.Fatal("cross-origin audio allowed", w.Code) | |
| 33 | 新增: } | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 36 | 新增:func TestAudioStreamsWholeFramesAndClosesOnCancellation(t *testing.T) { | |
| 37 | 新增: s := testServer(t) | |
| 38 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 39 | 新增: defer cancel() | |
| 40 | 新增: reader, writer := io.Pipe() | |
| 41 | 新增: defer reader.Close() | |
| 42 | 新增: defer writer.Close() | |
| 43 | 新增: finished := make(chan struct{}) | |
| 44 | 新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 45 | 新增: defer close(finished) | |
| 46 | 新增: s.streamAudio(w, r.WithContext(ctx), reader) | |
| 47 | 新增: })) | |
| 48 | 新增: defer server.Close() | |
| 49 | 新增: s.origin = server.URL | |
| 50 | 新增: ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http"), http.Header{"Origin": {server.URL}}) | |
| 51 | 新增: if err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: defer ws.Close() | |
| 55 | 新增: _, header, err := ws.ReadMessage() | |
| 56 | 新增: var format map[string]any | |
| 57 | 新增: if err != nil || json.Unmarshal(header, &format) != nil || format["sample_rate"] != float64(48000) { | |
| 58 | 新增: t.Fatal("missing audio format", err) | |
| 59 | 新增: } | |
| 60 | 新增: packet := bytes.Repeat([]byte{0, 128, 255, 127}, 960) | |
| 61 | 新增: go func() { _, _ = writer.Write(packet[:13]); _, _ = writer.Write(packet[13:]) }() | |
| 62 | 新增: kind, data, err := ws.ReadMessage() | |
| 63 | 新增: if err != nil || kind != websocket.BinaryMessage || !bytes.Equal(data, packet) { | |
| 64 | 新增: t.Fatal("PCM frame changed", err) | |
| 65 | 新增: } | |
| 66 | 新增: cancel() | |
| 67 | 新增: _ = ws.SetReadDeadline(time.Now().Add(time.Second)) | |
| 68 | 新增: if _, _, err = ws.ReadMessage(); err == nil { | |
| 69 | 新增: t.Fatal("cancelled stream stayed open") | |
| 70 | 新增: } | |
| 71 | 新增: select { | |
| 72 | 新增: case <-finished: | |
| 73 | 新增: case <-time.After(time.Second): | |
| 74 | 新增: t.Fatal("audio handler leaked") | |
| 75 | 新增: } | |
| 76 | 新增:} | |
| @@ -0,0 +1,218 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "io" | |
| 7 | 新增: "net/http" | |
| 8 | 新增: "net/url" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "runtime" | |
| 13 | 新增: "sort" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:type SavedDownload struct { | |
| 20 | 新增: ID string `json:"id"` | |
| 21 | 新增: Name string `json:"name"` | |
| 22 | 新增: Path string `json:"path"` | |
| 23 | 新增: SavedAt time.Time `json:"saved_at"` | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:func savedDownloadPath(profile, id string) string { | |
| 27 | 新增: return filepath.Join(profile, "browser-downloads", id+".json") | |
| 28 | 新增:} | |
| 29 | 新增:func readSavedDownload(profile, id string) (SavedDownload, error) { | |
| 30 | 新增: var saved SavedDownload | |
| 31 | 新增: if !browserFileID.MatchString(id) { | |
| 32 | 新增: return saved, errors.New("下载标识无效") | |
| 33 | 新增: } | |
| 34 | 新增: path := savedDownloadPath(profile, id) | |
| 35 | 新增: if err := host.CheckPrivateFile(path); err != nil { | |
| 36 | 新增: return saved, err | |
| 37 | 新增: } | |
| 38 | 新增: f, err := os.Open(path) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return saved, err | |
| 41 | 新增: } | |
| 42 | 新增: defer f.Close() | |
| 43 | 新增: if err = json.NewDecoder(io.LimitReader(f, 16384)).Decode(&saved); err != nil { | |
| 44 | 新增: return saved, err | |
| 45 | 新增: } | |
| 46 | 新增: if saved.ID != id || !filepath.IsAbs(saved.Path) || !browserDownloadName(saved.Name) { | |
| 47 | 新增: return saved, errors.New("下载位置记录无效") | |
| 48 | 新增: } | |
| 49 | 新增: return saved, nil | |
| 50 | 新增:} | |
| 51 | 新增:func rememberDownload(profile string, saved SavedDownload, firstOnly bool) error { | |
| 52 | 新增: if !browserFileID.MatchString(saved.ID) { | |
| 53 | 新增: return errors.New("下载标识无效") | |
| 54 | 新增: } | |
| 55 | 新增: directory := filepath.Join(profile, "browser-downloads") | |
| 56 | 新增: if err := host.EnsurePrivateDir(directory); err != nil { | |
| 57 | 新增: return err | |
| 58 | 新增: } | |
| 59 | 新增: lock, err := os.OpenFile(filepath.Join(directory, ".lock"), os.O_CREATE|os.O_RDWR, 0600) | |
| 60 | 新增: if err != nil { | |
| 61 | 新增: return err | |
| 62 | 新增: } | |
| 63 | 新增: defer lock.Close() | |
| 64 | 新增: for attempts := 0; ; attempts++ { | |
| 65 | 新增: if err = lockController(lock); err == nil { | |
| 66 | 新增: break | |
| 67 | 新增: } | |
| 68 | 新增: if attempts >= 40 { | |
| 69 | 新增: return errors.New("下载位置正在更新,请重试") | |
| 70 | 新增: } | |
| 71 | 新增: time.Sleep(25 * time.Millisecond) | |
| 72 | 新增: } | |
| 73 | 新增: defer unlockController(lock) | |
| 74 | 新增: if firstOnly { | |
| 75 | 新增: if _, err = readSavedDownload(profile, saved.ID); err == nil { | |
| 76 | 新增: return nil | |
| 77 | 新增: } | |
| 78 | 新增: } | |
| 79 | 新增: saved.SavedAt = time.Now().UTC() | |
| 80 | 新增: return writePrivate(savedDownloadPath(profile, saved.ID), saved) | |
| 81 | 新增:} | |
| 82 | 新增:func (s *Server) savedBrowserDownloads(w http.ResponseWriter, r *http.Request) { | |
| 83 | 新增: entries, err := os.ReadDir(filepath.Join(s.profile, "browser-downloads")) | |
| 84 | 新增: if err != nil && !os.IsNotExist(err) { | |
| 85 | 新增: http.Error(w, "无法读取已保存的位置", 500) | |
| 86 | 新增: return | |
| 87 | 新增: } | |
| 88 | 新增: records := []SavedDownload{} | |
| 89 | 新增: for _, entry := range entries { | |
| 90 | 新增: name := entry.Name() | |
| 91 | 新增: if len(name) != 41 { | |
| 92 | 新增: continue | |
| 93 | 新增: } | |
| 94 | 新增: if saved, err := readSavedDownload(s.profile, name[:36]); err == nil { | |
| 95 | 新增: records = append(records, saved) | |
| 96 | 新增: } | |
| 97 | 新增: } | |
| 98 | 新增: sort.Slice(records, func(i, j int) bool { return records[i].SavedAt.After(records[j].SavedAt) }) | |
| 99 | 新增: if len(records) > 100 { | |
| 100 | 新增: records = records[:100] | |
| 101 | 新增: } | |
| 102 | 新增: jsonReply(w, records) | |
| 103 | 新增:} | |
| 104 | 新增: | |
| 105 | 新增:// BrowserFile is called by native dialogs, which supply the chosen path. HTTP | |
| 106 | 新增:// clients can stream known downloads but cannot supply an arbitrary host path. | |
| 107 | 新增:func BrowserFile(configPath, action, id, destination string) (SavedDownload, error) { | |
| 108 | 新增: var result SavedDownload | |
| 109 | 新增: if !browserFileID.MatchString(id) || (action != "save" && action != "open" && action != "reveal") { | |
| 110 | 新增: return result, errors.New("下载操作无效") | |
| 111 | 新增: } | |
| 112 | 新增: client, err := connectController(filepath.Dir(configPath)) | |
| 113 | 新增: if err != nil { | |
| 114 | 新增: return result, err | |
| 115 | 新增: } | |
| 116 | 新增: defer client.close() | |
| 117 | 新增: entry, _ := url.Parse(client.launch.URL) | |
| 118 | 新增: status, err := client.call("POST", "/api/session", map[string]string{"token": entry.Fragment}, nil) | |
| 119 | 新增: if err != nil || status != 200 { | |
| 120 | 新增: return result, errors.New("无法连接下载会话") | |
| 121 | 新增: } | |
| 122 | 新增: var item browserDownloadInfo | |
| 123 | 新增: status, err = client.call("GET", "/api/browser/files/downloads/"+id, nil, &item) | |
| 124 | 新增: if err != nil || status != 200 { | |
| 125 | 新增: return result, errors.New("下载文件不可用,请确认 Cage 已解锁且下载已完成") | |
| 126 | 新增: } | |
| 127 | 新增: result = SavedDownload{ID: id, Name: item.Name, Path: item.Path} | |
| 128 | 新增: if action == "save" { | |
| 129 | 新增: if !filepath.IsAbs(destination) || filepath.Base(destination) == "." { | |
| 130 | 新增: return result, errors.New("保存位置无效") | |
| 131 | 新增: } | |
| 132 | 新增: parent, resolveErr := filepath.EvalSymlinks(filepath.Dir(destination)) | |
| 133 | 新增: if resolveErr != nil { | |
| 134 | 新增: return result, errors.New("所选保存文件夹已不可用") | |
| 135 | 新增: } | |
| 136 | 新增: destination = filepath.Join(parent, filepath.Base(destination)) | |
| 137 | 新增: request, _ := http.NewRequest("GET", client.origin+"/api/browser/files/downloads/"+id+"/content", nil) | |
| 138 | 新增: request.Header.Set("Origin", client.origin) | |
| 139 | 新增: client.client.Timeout = 30 * time.Minute | |
| 140 | 新增: response, err := client.client.Do(request) | |
| 141 | 新增: if err != nil { | |
| 142 | 新增: return result, errors.New("无法读取下载文件,请重试") | |
| 143 | 新增: } | |
| 144 | 新增: defer response.Body.Close() | |
| 145 | 新增: if response.StatusCode != 200 { | |
| 146 | 新增: return result, errors.New("下载源文件已不可用,请从原网页重新下载") | |
| 147 | 新增: } | |
| 148 | 新增: if err = saveDownloadedStream(destination, response.Body, response.ContentLength); err != nil { | |
| 149 | 新增: return result, err | |
| 150 | 新增: } | |
| 151 | 新增: result.Path = destination | |
| 152 | 新增: result.Name = filepath.Base(destination) | |
| 153 | 新增: if err = rememberDownload(client.profile, result, false); err != nil { | |
| 154 | 新增: return result, err | |
| 155 | 新增: } | |
| 156 | 新增: } else { | |
| 157 | 新增: file, err := openDownloadedFile(result.Path) | |
| 158 | 新增: if err != nil { | |
| 159 | 新增: return result, errors.New("文件已移动、删除或无法访问") | |
| 160 | 新增: } | |
| 161 | 新增: file.Close() | |
| 162 | 新增: var cmd *exec.Cmd | |
| 163 | 新增: switch runtime.GOOS { | |
| 164 | 新增: case "darwin": | |
| 165 | 新增: args := []string{"--", result.Path} | |
| 166 | 新增: if action == "reveal" { | |
| 167 | 新增: args = []string{"-R", "--", result.Path} | |
| 168 | 新增: } | |
| 169 | 新增: cmd = exec.Command("/usr/bin/open", args...) | |
| 170 | 新增: case "windows": | |
| 171 | 新增: if action == "reveal" { | |
| 172 | 新增: cmd = exec.Command("explorer.exe", "/select,"+result.Path) | |
| 173 | 新增: } else { | |
| 174 | 新增: cmd = exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", result.Path) | |
| 175 | 新增: } | |
| 176 | 新增: default: | |
| 177 | 新增: path := result.Path | |
| 178 | 新增: if action == "reveal" { | |
| 179 | 新增: path = filepath.Dir(path) | |
| 180 | 新增: } | |
| 181 | 新增: cmd = exec.Command("gio", "open", path) | |
| 182 | 新增: } | |
| 183 | 新增: hideCommand(cmd) | |
| 184 | 新增: if err = cmd.Run(); err != nil { | |
| 185 | 新增: return result, errors.New("无法打开文件,请通过显示的位置手动查看") | |
| 186 | 新增: } | |
| 187 | 新增: } | |
| 188 | 新增: return result, nil | |
| 189 | 新增:} | |
| 190 | 新增: | |
| 191 | 新增:func saveDownloadedStream(destination string, source io.Reader, size int64) error { | |
| 192 | 新增: if existing, err := os.Lstat(destination); err == nil && !existing.Mode().IsRegular() { | |
| 193 | 新增: return errors.New("请选择普通文件保存位置") | |
| 194 | 新增: } | |
| 195 | 新增: temporary, err := os.CreateTemp(filepath.Dir(destination), ".cage-download-*.part") | |
| 196 | 新增: if err != nil { | |
| 197 | 新增: return errors.New("无法写入所选文件夹") | |
| 198 | 新增: } | |
| 199 | 新增: defer os.Remove(temporary.Name()) | |
| 200 | 新增: count, err := io.Copy(temporary, source) | |
| 201 | 新增: if err == nil && size >= 0 && count != size { | |
| 202 | 新增: err = io.ErrUnexpectedEOF | |
| 203 | 新增: } | |
| 204 | 新增: if err == nil { | |
| 205 | 新增: err = temporary.Sync() | |
| 206 | 新增: } | |
| 207 | 新增: closeErr := temporary.Close() | |
| 208 | 新增: if err == nil { | |
| 209 | 新增: err = closeErr | |
| 210 | 新增: } | |
| 211 | 新增: if err != nil { | |
| 212 | 新增: return errors.New("保存未完成,原文件未覆盖;请检查空间或连接后重试") | |
| 213 | 新增: } | |
| 214 | 新增: if err = os.Rename(temporary.Name(), destination); err != nil { | |
| 215 | 新增: return errors.New("无法保存到所选位置,原文件未覆盖") | |
| 216 | 新增: } | |
| 217 | 新增: return nil | |
| 218 | 新增:} | |
| @@ -0,0 +1,235 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "io" | |
| 8 | 新增: "mime" | |
| 9 | 新增: "net/http" | |
| 10 | 新增: "net/url" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "regexp" | |
| 14 | 新增: "strings" | |
| 15 | 新增: "time" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:const browserFileLimit int64 = 2 << 30 | |
| 19 | 新增: | |
| 20 | 新增:var browserFileID = regexp.MustCompile(`^[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}$`) | |
| 21 | 新增: | |
| 22 | 新增:func browserFileName(name string) bool { | |
| 23 | 新增: return len(name) <= 255 && browserDownloadName(name) | |
| 24 | 新增:} | |
| 25 | 新增:func browserDownloadName(name string) bool { | |
| 26 | 新增: return name != "" && len(name) <= 1024 && name != "." && name != ".." && !strings.ContainsAny(name, "/\\\x00\r\n") | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:func (s *Server) browserUpload(w http.ResponseWriter, r *http.Request) { | |
| 30 | 新增: id, name := r.PathValue("id"), r.URL.Query().Get("name") | |
| 31 | 新增: if !browserFileID.MatchString(id) || !browserFileName(name) { | |
| 32 | 新增: http.Error(w, "文件名或上传窗口无效", 400) | |
| 33 | 新增: return | |
| 34 | 新增: } | |
| 35 | 新增: if r.ContentLength > browserFileLimit { | |
| 36 | 新增: http.Error(w, "每个文件不能超过 2 GB", 413) | |
| 37 | 新增: return | |
| 38 | 新增: } | |
| 39 | 新增: s.mu.Lock() | |
| 40 | 新增: ready, token := s.ready, s.credentials.Token | |
| 41 | 新增: s.mu.Unlock() | |
| 42 | 新增: if !ready { | |
| 43 | 新增: http.Error(w, "环境尚未就绪", 409) | |
| 44 | 新增: return | |
| 45 | 新增: } | |
| 46 | 新增: // The snapshot also initializes the existing guest transport. Never accept a | |
| 47 | 新增: // file without a live chooser owned by the remote browser. | |
| 48 | 新增: snapshot, err := s.guestAPI(r.Context(), token, "GET", "/tabs", nil) | |
| 49 | 新增: var state struct { | |
| 50 | 新增: Uploads []struct { | |
| 51 | 新增: ID string `json:"id"` | |
| 52 | 新增: } `json:"uploads"` | |
| 53 | 新增: } | |
| 54 | 新增: if err != nil || json.Unmarshal(snapshot, &state) != nil { | |
| 55 | 新增: http.Error(w, "无法连接上传窗口", 502) | |
| 56 | 新增: return | |
| 57 | 新增: } | |
| 58 | 新增: found := false | |
| 59 | 新增: for _, upload := range state.Uploads { | |
| 60 | 新增: if upload.ID == id { | |
| 61 | 新增: found = true | |
| 62 | 新增: } | |
| 63 | 新增: } | |
| 64 | 新增: if !found { | |
| 65 | 新增: http.Error(w, "上传窗口已关闭,请重新点击网页上传按钮", 409) | |
| 66 | 新增: return | |
| 67 | 新增: } | |
| 68 | 新增: query := url.Values{"id": {id}, "name": {name}} | |
| 69 | 新增: r.Body = http.MaxBytesReader(w, r.Body, browserFileLimit) | |
| 70 | 新增: s.proxyBrowserFile(w, r, token, "POST", "/upload-file?"+query.Encode(), r.Body) | |
| 71 | 新增:} | |
| 72 | 新增: | |
| 73 | 新增:func (s *Server) proxyBrowserFile(w http.ResponseWriter, r *http.Request, token, method, path string, body io.Reader) { | |
| 74 | 新增: s.mu.Lock() | |
| 75 | 新增: client := *s.guestClient | |
| 76 | 新增: s.mu.Unlock() | |
| 77 | 新增: client.Timeout = 30 * time.Minute | |
| 78 | 新增: req, err := http.NewRequestWithContext(r.Context(), method, "http://127.0.0.1:18500"+path, body) | |
| 79 | 新增: if err != nil { | |
| 80 | 新增: http.Error(w, "文件传递请求无效", 400) | |
| 81 | 新增: return | |
| 82 | 新增: } | |
| 83 | 新增: req.Header.Set("Authorization", "Bearer "+token) | |
| 84 | 新增: if body != nil { | |
| 85 | 新增: req.ContentLength = r.ContentLength | |
| 86 | 新增: req.Header.Set("Content-Type", "application/octet-stream") | |
| 87 | 新增: } | |
| 88 | 新增: response, err := client.Do(req) | |
| 89 | 新增: if err != nil { | |
| 90 | 新增: http.Error(w, "文件传递中断,请重试", 502) | |
| 91 | 新增: return | |
| 92 | 新增: } | |
| 93 | 新增: defer response.Body.Close() | |
| 94 | 新增: if response.StatusCode != 200 { | |
| 95 | 新增: http.Error(w, "文件不可用或上传窗口已关闭,请重试", 502) | |
| 96 | 新增: return | |
| 97 | 新增: } | |
| 98 | 新增: if method == "POST" { | |
| 99 | 新增: w.Header().Set("Content-Type", "application/json") | |
| 100 | 新增: _, _ = io.Copy(w, io.LimitReader(response.Body, 4096)) | |
| 101 | 新增: return | |
| 102 | 新增: } | |
| 103 | 新增: w.Header().Set("Content-Type", "application/octet-stream") | |
| 104 | 新增: if length := response.Header.Get("Content-Length"); length != "" { | |
| 105 | 新增: w.Header().Set("Content-Length", length) | |
| 106 | 新增: } | |
| 107 | 新增: _, _ = io.Copy(w, response.Body) | |
| 108 | 新增:} | |
| 109 | 新增: | |
| 110 | 新增:type browserDownloadInfo struct { | |
| 111 | 新增: ID string `json:"id"` | |
| 112 | 新增: Name string `json:"name"` | |
| 113 | 新增: State string `json:"state"` | |
| 114 | 新增: Path string `json:"path,omitempty"` | |
| 115 | 新增: Retryable bool `json:"retryable,omitempty"` | |
| 116 | 新增:} | |
| 117 | 新增: | |
| 118 | 新增:func (s *Server) downloadInfo(ctx context.Context, id string) (browserDownloadInfo, error) { | |
| 119 | 新增: if !browserFileID.MatchString(id) { | |
| 120 | 新增: return browserDownloadInfo{}, errors.New("下载标识无效") | |
| 121 | 新增: } | |
| 122 | 新增: if saved, err := readSavedDownload(s.profile, id); err == nil { | |
| 123 | 新增: return browserDownloadInfo{ID: id, Name: saved.Name, Path: saved.Path, State: "saved"}, nil | |
| 124 | 新增: } | |
| 125 | 新增: s.mu.Lock() | |
| 126 | 新增: ready, token := s.ready, s.credentials.Token | |
| 127 | 新增: s.mu.Unlock() | |
| 128 | 新增: if !ready { | |
| 129 | 新增: return browserDownloadInfo{}, errors.New("请先启动环境或从已保存的位置打开文件") | |
| 130 | 新增: } | |
| 131 | 新增: data, err := s.guestAPI(ctx, token, "GET", "/tabs", nil) | |
| 132 | 新增: if err != nil { | |
| 133 | 新增: return browserDownloadInfo{}, err | |
| 134 | 新增: } | |
| 135 | 新增: var state struct { | |
| 136 | 新增: Downloads []browserDownloadInfo `json:"downloads"` | |
| 137 | 新增: } | |
| 138 | 新增: if json.Unmarshal(data, &state) != nil { | |
| 139 | 新增: return browserDownloadInfo{}, errors.New("下载列表无效") | |
| 140 | 新增: } | |
| 141 | 新增: for _, item := range state.Downloads { | |
| 142 | 新增: if item.ID != id || !browserDownloadName(item.Name) { | |
| 143 | 新增: continue | |
| 144 | 新增: } | |
| 145 | 新增: if item.State == "saved" { | |
| 146 | 新增: root := s.environmentDir() | |
| 147 | 新增: expected := strings.TrimRight(guestPath(root), "/") + "/Downloads/" + item.Name | |
| 148 | 新增: if item.Path != expected { | |
| 149 | 新增: return browserDownloadInfo{}, errors.New("下载保存位置无效") | |
| 150 | 新增: } | |
| 151 | 新增: item.Path = filepath.Join(root, "Downloads", item.Name) | |
| 152 | 新增: if err = rememberDownload(s.profile, SavedDownload{ID: id, Name: item.Name, Path: item.Path}, true); err != nil { | |
| 153 | 新增: return browserDownloadInfo{}, err | |
| 154 | 新增: } | |
| 155 | 新增: } else { | |
| 156 | 新增: item.Path = "" | |
| 157 | 新增: } | |
| 158 | 新增: return item, nil | |
| 159 | 新增: } | |
| 160 | 新增: return browserDownloadInfo{}, errors.New("下载记录已不存在,请从原网页重新下载") | |
| 161 | 新增:} | |
| 162 | 新增: | |
| 163 | 新增:func (s *Server) browserDownload(w http.ResponseWriter, r *http.Request) { | |
| 164 | 新增: if action := r.PathValue("action"); action != "" && action != "content" { | |
| 165 | 新增: http.NotFound(w, r) | |
| 166 | 新增: return | |
| 167 | 新增: } | |
| 168 | 新增: item, err := s.downloadInfo(r.Context(), r.PathValue("id")) | |
| 169 | 新增: if err != nil { | |
| 170 | 新增: http.Error(w, err.Error(), 409) | |
| 171 | 新增: return | |
| 172 | 新增: } | |
| 173 | 新增: if r.PathValue("action") != "content" { | |
| 174 | 新增: jsonReply(w, item) | |
| 175 | 新增: return | |
| 176 | 新增: } | |
| 177 | 新增: w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": item.Name})) | |
| 178 | 新增: if item.Path != "" { | |
| 179 | 新增: file, err := openDownloadedFile(item.Path) | |
| 180 | 新增: if err != nil { | |
| 181 | 新增: http.Error(w, "文件已移动、删除或暂时无法读取", 404) | |
| 182 | 新增: return | |
| 183 | 新增: } | |
| 184 | 新增: defer file.Close() | |
| 185 | 新增: info, _ := file.Stat() | |
| 186 | 新增: http.ServeContent(w, r, item.Name, info.ModTime(), cancelableDownload{ReadSeeker: file, ctx: r.Context()}) | |
| 187 | 新增: return | |
| 188 | 新增: } | |
| 189 | 新增: if item.State != "failed" || !item.Retryable { | |
| 190 | 新增: http.Error(w, "文件尚未下载完成或已不可用", 409) | |
| 191 | 新增: return | |
| 192 | 新增: } | |
| 193 | 新增: s.mu.Lock() | |
| 194 | 新增: token := s.credentials.Token | |
| 195 | 新增: s.mu.Unlock() | |
| 196 | 新增: s.proxyBrowserFile(w, r, token, "GET", "/download-file?id="+url.QueryEscape(item.ID), nil) | |
| 197 | 新增:} | |
| 198 | 新增: | |
| 199 | 新增:type cancelableDownload struct { | |
| 200 | 新增: io.ReadSeeker | |
| 201 | 新增: ctx context.Context | |
| 202 | 新增:} | |
| 203 | 新增: | |
| 204 | 新增:func (reader cancelableDownload) Read(buffer []byte) (int, error) { | |
| 205 | 新增: if err := reader.ctx.Err(); err != nil { | |
| 206 | 新增: return 0, err | |
| 207 | 新增: } | |
| 208 | 新增: return reader.ReadSeeker.Read(buffer) | |
| 209 | 新增:} | |
| 210 | 新增: | |
| 211 | 新增:// A file replaced by a symlink must not turn a download action into an arbitrary | |
| 212 | 新增:// host read. The selected file is checked again after opening it. | |
| 213 | 新增:func openDownloadedFile(path string) (*os.File, error) { | |
| 214 | 新增: before, err := os.Lstat(path) | |
| 215 | 新增: if err != nil || !before.Mode().IsRegular() { | |
| 216 | 新增: return nil, errors.New("下载文件不可用") | |
| 217 | 新增: } | |
| 218 | 新增: parent, err := filepath.EvalSymlinks(filepath.Dir(path)) | |
| 219 | 新增: if err != nil { | |
| 220 | 新增: return nil, err | |
| 221 | 新增: } | |
| 222 | 新增: if filepath.Clean(parent) != filepath.Clean(filepath.Dir(path)) { | |
| 223 | 新增: return nil, errors.New("下载目录已被替换") | |
| 224 | 新增: } | |
| 225 | 新增: file, err := os.Open(path) | |
| 226 | 新增: if err != nil { | |
| 227 | 新增: return nil, err | |
| 228 | 新增: } | |
| 229 | 新增: after, err := file.Stat() | |
| 230 | 新增: if err != nil || !os.SameFile(before, after) { | |
| 231 | 新增: file.Close() | |
| 232 | 新增: return nil, errors.New("下载文件已变化") | |
| 233 | 新增: } | |
| 234 | 新增: return file, nil | |
| 235 | 新增:} | |
| @@ -0,0 +1,213 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增: "net/http" | |
| 10 | 新增: "net/http/httptest" | |
| 11 | 新增: "net/url" | |
| 12 | 新增: "os" | |
| 13 | 新增: "path/filepath" | |
| 14 | 新增: "strconv" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "testing" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:const testBrowserFileID = "34e399c1-78fe-4cf1-93b0-d7fef431b211" | |
| 20 | 新增: | |
| 21 | 新增:func TestBrowserUploadStreamsOnlyToLiveChooser(t *testing.T) { | |
| 22 | 新增: s := testServer(t) | |
| 23 | 新增: s.ready = true | |
| 24 | 新增: s.credentials.Token = "guest-token" | |
| 25 | 新增: data := bytes.Repeat([]byte{0, 1, 255, 0, 127}, 1<<18) | |
| 26 | 新增: posts := 0 | |
| 27 | 新增: s.guestClient = &http.Client{Transport: browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 28 | 新增: if r.Header.Get("Authorization") != "Bearer guest-token" { | |
| 29 | 新增: t.Fatal("missing guest authentication") | |
| 30 | 新增: } | |
| 31 | 新增: body := `{"uploads":[{"id":"` + testBrowserFileID + `"}]}` | |
| 32 | 新增: if r.Method == "POST" { | |
| 33 | 新增: posts++ | |
| 34 | 新增: if r.URL.Path != "/upload-file" || r.URL.Query().Get("id") != testBrowserFileID || r.URL.Query().Get("name") != "参考视频.mp4" { | |
| 35 | 新增: t.Fatal("wrong upload target", r.URL) | |
| 36 | 新增: } | |
| 37 | 新增: got, err := io.ReadAll(r.Body) | |
| 38 | 新增: if err != nil || !bytes.Equal(got, data) { | |
| 39 | 新增: t.Fatal("binary bytes changed", err) | |
| 40 | 新增: } | |
| 41 | 新增: body = `{"ok":true}` | |
| 42 | 新增: } | |
| 43 | 新增: return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))}, nil | |
| 44 | 新增: })} | |
| 45 | 新增: call := func(origin string, auth bool, name string, size int64) int { | |
| 46 | 新增: r := httptest.NewRequest("POST", s.origin+"/api/browser/files/uploads/"+testBrowserFileID+"?name="+name, bytes.NewReader(data)) | |
| 47 | 新增: r.Host = "localhost:17777" | |
| 48 | 新增: r.Header.Set("Origin", origin) | |
| 49 | 新增: r.ContentLength = size | |
| 50 | 新增: if auth { | |
| 51 | 新增: r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) | |
| 52 | 新增: } | |
| 53 | 新增: w := httptest.NewRecorder() | |
| 54 | 新增: s.handler().ServeHTTP(w, r) | |
| 55 | 新增: return w.Code | |
| 56 | 新增: } | |
| 57 | 新增: if code := call(s.origin, false, "video.mp4", int64(len(data))); code != 401 { | |
| 58 | 新增: t.Fatal(code) | |
| 59 | 新增: } | |
| 60 | 新增: if code := call("https://example.com", true, "video.mp4", int64(len(data))); code != 403 { | |
| 61 | 新增: t.Fatal(code) | |
| 62 | 新增: } | |
| 63 | 新增: if code := call(s.origin, true, "../private", 1); code != 400 { | |
| 64 | 新增: t.Fatal(code) | |
| 65 | 新增: } | |
| 66 | 新增: if code := call(s.origin, true, "video.mp4", browserFileLimit+1); code != 413 { | |
| 67 | 新增: t.Fatal(code) | |
| 68 | 新增: } | |
| 69 | 新增: if posts != 0 { | |
| 70 | 新增: t.Fatal("rejected stream reached guest") | |
| 71 | 新增: } | |
| 72 | 新增: if code := call(s.origin, true, "%E5%8F%82%E8%80%83%E8%A7%86%E9%A2%91.mp4", int64(len(data))); code != 200 || posts != 1 { | |
| 73 | 新增: t.Fatal(code, posts) | |
| 74 | 新增: } | |
| 75 | 新增:} | |
| 76 | 新增: | |
| 77 | 新增:type failedDownloadReader struct{} | |
| 78 | 新增: | |
| 79 | 新增:func (failedDownloadReader) Read([]byte) (int, error) { return 0, errors.New("interrupted") } | |
| 80 | 新增: | |
| 81 | 新增:func TestSaveDownloadNeverPublishesPartialOrClobbersOnFailure(t *testing.T) { | |
| 82 | 新增: directory := t.TempDir() | |
| 83 | 新增: path := filepath.Join(directory, "video.mp4") | |
| 84 | 新增: if err := os.WriteFile(path, []byte("original"), 0600); err != nil { | |
| 85 | 新增: t.Fatal(err) | |
| 86 | 新增: } | |
| 87 | 新增: for _, reader := range []io.Reader{failedDownloadReader{}, strings.NewReader("short")} { | |
| 88 | 新增: if err := saveDownloadedStream(path, reader, 100); err == nil { | |
| 89 | 新增: t.Fatal("partial save accepted") | |
| 90 | 新增: } | |
| 91 | 新增: got, _ := os.ReadFile(path) | |
| 92 | 新增: if string(got) != "original" { | |
| 93 | 新增: t.Fatal("original overwritten") | |
| 94 | 新增: } | |
| 95 | 新增: } | |
| 96 | 新增: data := bytes.Repeat([]byte{0, 255, 77}, 1<<19) | |
| 97 | 新增: if err := saveDownloadedStream(path, bytes.NewReader(data), int64(len(data))); err != nil { | |
| 98 | 新增: t.Fatal(err) | |
| 99 | 新增: } | |
| 100 | 新增: got, _ := os.ReadFile(path) | |
| 101 | 新增: if !bytes.Equal(got, data) { | |
| 102 | 新增: t.Fatal("saved content changed") | |
| 103 | 新增: } | |
| 104 | 新增: files, _ := filepath.Glob(filepath.Join(directory, ".cage-download-*.part")) | |
| 105 | 新增: if len(files) != 0 { | |
| 106 | 新增: t.Fatal("partial files retained") | |
| 107 | 新增: } | |
| 108 | 新增:} | |
| 109 | 新增: | |
| 110 | 新增:func TestSavedDownloadLocationSurvivesDefaultSnapshot(t *testing.T) { | |
| 111 | 新增: profile := t.TempDir() | |
| 112 | 新增: chosen := SavedDownload{ID: testBrowserFileID, Name: "movie.mp4", Path: filepath.Join(t.TempDir(), "movie.mp4")} | |
| 113 | 新增: if err := rememberDownload(profile, chosen, false); err != nil { | |
| 114 | 新增: t.Fatal(err) | |
| 115 | 新增: } | |
| 116 | 新增: fallback := chosen | |
| 117 | 新增: fallback.Path = filepath.Join(t.TempDir(), "fallback.mp4") | |
| 118 | 新增: if err := rememberDownload(profile, fallback, true); err != nil { | |
| 119 | 新增: t.Fatal(err) | |
| 120 | 新增: } | |
| 121 | 新增: got, err := readSavedDownload(profile, testBrowserFileID) | |
| 122 | 新增: if err != nil || got.Path != chosen.Path { | |
| 123 | 新增: t.Fatal("chosen destination lost", err) | |
| 124 | 新增: } | |
| 125 | 新增: if _, err := readSavedDownload(profile, "../outside"); err == nil { | |
| 126 | 新增: t.Fatal("path escape accepted") | |
| 127 | 新增: } | |
| 128 | 新增:} | |
| 129 | 新增: | |
| 130 | 新增:func TestCompletedDownloadsRemainAvailableAfterVMStops(t *testing.T) { | |
| 131 | 新增: s := testServer(t) | |
| 132 | 新增: directory, err := filepath.EvalSymlinks(t.TempDir()) | |
| 133 | 新增: if err != nil { | |
| 134 | 新增: t.Fatal(err) | |
| 135 | 新增: } | |
| 136 | 新增: if err = writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": directory}); err != nil { | |
| 137 | 新增: t.Fatal(err) | |
| 138 | 新增: } | |
| 139 | 新增: if err = os.Mkdir(filepath.Join(directory, "Downloads"), 0700); err != nil { | |
| 140 | 新增: t.Fatal(err) | |
| 141 | 新增: } | |
| 142 | 新增: path := filepath.Join(directory, "Downloads", "video.mp4") | |
| 143 | 新增: data := []byte{0, 1, 255, 0, 127} | |
| 144 | 新增: if err = os.WriteFile(path, data, 0600); err != nil { | |
| 145 | 新增: t.Fatal(err) | |
| 146 | 新增: } | |
| 147 | 新增: snapshot, _ := json.Marshal(map[string]any{"tabs": []any{}, "downloads": []browserDownloadInfo{{ID: testBrowserFileID, Name: "video.mp4", State: "saved", Path: guestPath(path)}}}) | |
| 148 | 新增: if _, err = s.browserStateForHost(snapshot); err != nil { | |
| 149 | 新增: t.Fatal(err) | |
| 150 | 新增: } | |
| 151 | 新增: s.ready = false | |
| 152 | 新增: route := "/api/browser/files/downloads/" + testBrowserFileID + "/content" | |
| 153 | 新增: w := request(s, "GET", route, "", "", true) | |
| 154 | 新增: if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), data) { | |
| 155 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 156 | 新增: } | |
| 157 | 新增: s.account.lock() | |
| 158 | 新增: if w = request(s, "GET", route, "", "", true); w.Code != 423 { | |
| 159 | 新增: t.Fatal("locked file read accepted") | |
| 160 | 新增: } | |
| 161 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 162 | 新增: cancel() | |
| 163 | 新增: reader := cancelableDownload{ReadSeeker: bytes.NewReader(data), ctx: ctx} | |
| 164 | 新增: if _, err = reader.Read(make([]byte, 16)); !errors.Is(err, context.Canceled) { | |
| 165 | 新增: t.Fatal("canceled file read continued", err) | |
| 166 | 新增: } | |
| 167 | 新增:} | |
| 168 | 新增: | |
| 169 | 新增:func TestNativeSaveUsesAuthenticatedControllerAndPersistsChosenPath(t *testing.T) { | |
| 170 | 新增: s := testServer(t) | |
| 171 | 新增: server := httptest.NewServer(s.handler()) | |
| 172 | 新增: defer server.Close() | |
| 173 | 新增: endpoint, _ := url.Parse(server.URL) | |
| 174 | 新增: port, _ := strconv.Atoi(endpoint.Port()) | |
| 175 | 新增: s.origin = "http://localhost:" + endpoint.Port() | |
| 176 | 新增: if err := writePrivate(filepath.Join(s.profile, "control.json"), controlFile{Port: port, Token: s.token, PID: os.Getpid()}); err != nil { | |
| 177 | 新增: t.Fatal(err) | |
| 178 | 新增: } | |
| 179 | 新增: directory, err := filepath.EvalSymlinks(t.TempDir()) | |
| 180 | 新增: if err != nil { | |
| 181 | 新增: t.Fatal(err) | |
| 182 | 新增: } | |
| 183 | 新增: source := filepath.Join(directory, "source.mp4") | |
| 184 | 新增: destination := filepath.Join(directory, "另存视频.mp4") | |
| 185 | 新增: data := bytes.Repeat([]byte{0, 255, 42, 77}, 1<<18) | |
| 186 | 新增: if err = os.WriteFile(source, data, 0600); err != nil { | |
| 187 | 新增: t.Fatal(err) | |
| 188 | 新增: } | |
| 189 | 新增: if err = rememberDownload(s.profile, SavedDownload{ID: testBrowserFileID, Name: "source.mp4", Path: source}, false); err != nil { | |
| 190 | 新增: t.Fatal(err) | |
| 191 | 新增: } | |
| 192 | 新增: result, err := BrowserFile(s.configPath, "save", testBrowserFileID, destination) | |
| 193 | 新增: if err != nil || result.Path != destination { | |
| 194 | 新增: t.Fatal(result, err) | |
| 195 | 新增: } | |
| 196 | 新增: saved, _ := os.ReadFile(destination) | |
| 197 | 新增: original, _ := os.ReadFile(source) | |
| 198 | 新增: if !bytes.Equal(saved, data) || !bytes.Equal(original, data) { | |
| 199 | 新增: t.Fatal("save changed source or bytes") | |
| 200 | 新增: } | |
| 201 | 新增: record, err := readSavedDownload(s.profile, testBrowserFileID) | |
| 202 | 新增: if err != nil || record.Path != destination { | |
| 203 | 新增: t.Fatal("chosen path not persisted", err) | |
| 204 | 新增: } | |
| 205 | 新增: s.account.lock() | |
| 206 | 新增: refused := filepath.Join(directory, "locked.mp4") | |
| 207 | 新增: if _, err = BrowserFile(s.configPath, "save", testBrowserFileID, refused); err == nil { | |
| 208 | 新增: t.Fatal("locked native export accepted") | |
| 209 | 新增: } | |
| 210 | 新增: if _, err = os.Stat(refused); !os.IsNotExist(err) { | |
| 211 | 新增: t.Fatal("locked export wrote a file") | |
| 212 | 新增: } | |
| 213 | 新增:} | |
| @@ -0,0 +1,111 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bufio" | |
| 5 | 新增: "bytes" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增: "net/http" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:// Browser URLs use guest paths. The workbench's project and terminal actions | |
| 16 | 新增:// use host paths, so an editor's workspace must identify its existing grant. | |
| 17 | 新增:// Never infer a host drive or a new grant from an arbitrary guest path. | |
| 18 | 新增:func (s *Server) browserStateForHost(body []byte) ([]byte, error) { | |
| 19 | 新增: var state map[string]json.RawMessage | |
| 20 | 新增: if err := json.Unmarshal(body, &state); err != nil { | |
| 21 | 新增: return nil, errors.New("浏览器状态无效") | |
| 22 | 新增: } | |
| 23 | 新增: // Cache completed default saves on the host so Open/Reveal continue to work | |
| 24 | 新增: // after the VM stops. A user-selected Save As location always wins. | |
| 25 | 新增: var downloads []map[string]json.RawMessage | |
| 26 | 新增: downloadsChanged := false | |
| 27 | 新增: if json.Unmarshal(state["downloads"], &downloads) == nil { | |
| 28 | 新增: root := s.environmentDir() | |
| 29 | 新增: for _, record := range downloads { | |
| 30 | 新增: encoded, _ := json.Marshal(record) | |
| 31 | 新增: var item browserDownloadInfo | |
| 32 | 新增: if json.Unmarshal(encoded, &item) != nil { | |
| 33 | 新增: continue | |
| 34 | 新增: } | |
| 35 | 新增: if item.State != "saved" || !browserFileID.MatchString(item.ID) || !browserDownloadName(item.Name) || item.Path != guestPath(filepath.Join(root, "Downloads", item.Name)) { | |
| 36 | 新增: continue | |
| 37 | 新增: } | |
| 38 | 新增: hostPath := filepath.Join(root, "Downloads", item.Name) | |
| 39 | 新增: if _, err := readSavedDownload(s.profile, item.ID); err != nil { | |
| 40 | 新增: _ = rememberDownload(s.profile, SavedDownload{ID: item.ID, Name: item.Name, Path: hostPath}, true) | |
| 41 | 新增: } | |
| 42 | 新增: if paths.Windows() && hostPath != item.Path { | |
| 43 | 新增: record["path"], _ = json.Marshal(hostPath) | |
| 44 | 新增: downloadsChanged = true | |
| 45 | 新增: } | |
| 46 | 新增: } | |
| 47 | 新增: } | |
| 48 | 新增: if !paths.Windows() { | |
| 49 | 新增: return body, nil | |
| 50 | 新增: } | |
| 51 | 新增: var tabs []map[string]json.RawMessage | |
| 52 | 新增: if err := json.Unmarshal(state["tabs"], &tabs); err != nil { | |
| 53 | 新增: return nil, errors.New("浏览器标签状态无效") | |
| 54 | 新增: } | |
| 55 | 新增: authorized, err := s.projectPaths() | |
| 56 | 新增: if err != nil { | |
| 57 | 新增: return nil, errors.New("无法读取项目列表") | |
| 58 | 新增: } | |
| 59 | 新增: byGuest := make(map[string]string, len(authorized)) | |
| 60 | 新增: for _, hostPath := range authorized { | |
| 61 | 新增: byGuest[guestPath(hostPath)] = hostPath | |
| 62 | 新增: } | |
| 63 | 新增: changed := downloadsChanged | |
| 64 | 新增: for _, tab := range tabs { | |
| 65 | 新增: var kind, workspace string | |
| 66 | 新增: if json.Unmarshal(tab["kind"], &kind) != nil || kind != "editor" || json.Unmarshal(tab["workspace"], &workspace) != nil { | |
| 67 | 新增: continue | |
| 68 | 新增: } | |
| 69 | 新增: if hostPath, ok := byGuest[workspace]; ok && hostPath != workspace { | |
| 70 | 新增: tab["workspace"], _ = json.Marshal(hostPath) | |
| 71 | 新增: changed = true | |
| 72 | 新增: } | |
| 73 | 新增: } | |
| 74 | 新增: if !changed { | |
| 75 | 新增: return body, nil | |
| 76 | 新增: } | |
| 77 | 新增: if downloadsChanged { | |
| 78 | 新增: state["downloads"], _ = json.Marshal(downloads) | |
| 79 | 新增: } | |
| 80 | 新增: state["tabs"], err = json.Marshal(tabs) | |
| 81 | 新增: if err != nil { | |
| 82 | 新增: return nil, err | |
| 83 | 新增: } | |
| 84 | 新增: return json.Marshal(state) | |
| 85 | 新增:} | |
| 86 | 新增: | |
| 87 | 新增:// The guest emits one compact JSON snapshot per data line, plus heartbeat | |
| 88 | 新增:// comments. Resolve grants for each snapshot so an already-open stream also | |
| 89 | 新增:// recognizes projects added after it connected. | |
| 90 | 新增:func (s *Server) writeBrowserEvents(w http.ResponseWriter, body io.Reader) error { | |
| 91 | 新增: scanner := bufio.NewScanner(body) | |
| 92 | 新增: scanner.Buffer(make([]byte, 16<<10), (1<<20)+16) | |
| 93 | 新增: flusher := w.(http.Flusher) | |
| 94 | 新增: for scanner.Scan() { | |
| 95 | 新增: line := scanner.Bytes() | |
| 96 | 新增: if bytes.HasPrefix(line, []byte("data: ")) { | |
| 97 | 新增: mapped, err := s.browserStateForHost(line[len("data: "):]) | |
| 98 | 新增: if err != nil { | |
| 99 | 新增: return err | |
| 100 | 新增: } | |
| 101 | 新增: line = append([]byte("data: "), mapped...) | |
| 102 | 新增: } | |
| 103 | 新增: if _, err := w.Write(append(line, '\n')); err != nil { | |
| 104 | 新增: return err | |
| 105 | 新增: } | |
| 106 | 新增: if len(line) == 0 { | |
| 107 | 新增: flusher.Flush() | |
| 108 | 新增: } | |
| 109 | 新增: } | |
| 110 | 新增: return scanner.Err() | |
| 111 | 新增:} | |
| @@ -0,0 +1,127 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bufio" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "io" | |
| 7 | 新增: "net/http" | |
| 8 | 新增: "net/http/httptest" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "reflect" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "testing" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func windowsBrowserWorkspaceServer(t *testing.T) *Server { | |
| 18 | 新增: t.Helper() | |
| 19 | 新增: previous := paths.Windows | |
| 20 | 新增: paths.Windows = func() bool { return true } | |
| 21 | 新增: t.Cleanup(func() { paths.Windows = previous }) | |
| 22 | 新增: s := testServer(t) | |
| 23 | 新增: s.ready = true | |
| 24 | 新增: s.preferences.Workspace = `C:\Users\甲 用户\项目 一` | |
| 25 | 新增: s.credentials.Token = "private-test-token" | |
| 26 | 新增: return s | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:func TestBrowserEditorWorkspaceRESTUsesAuthorizedWindowsProjects(t *testing.T) { | |
| 30 | 新增: s := windowsBrowserWorkspaceServer(t) | |
| 31 | 新增: second := `D:\跨盘 项目\two` | |
| 32 | 新增: if err := writePrivate(filepath.Join(s.profile, "projects.json"), sharedProjects{Paths: []string{second}}); err != nil { | |
| 33 | 新增: t.Fatal(err) | |
| 34 | 新增: } | |
| 35 | 新增: snapshot := `{"active":"first","downloads":[{"id":"download","url":"https://example.test/a"}],"tabs":[` + | |
| 36 | 新增: `{"id":"first","kind":"editor","workspace":"/c/Users/甲 用户/项目 一","url":"http://127.0.0.1:18080/?folder=%2Fc%2FUsers%2F甲%20用户%2F项目%20一"},` + | |
| 37 | 新增: `{"id":"second","kind":"editor","workspace":"/d/跨盘 项目/two","url":"http://127.0.0.1:18080/?folder=%2Fd%2F跨盘%20项目%2Ftwo"},` + | |
| 38 | 新增: `{"id":"web","kind":"web","workspace":"/c/Users/甲 用户/项目 一","url":"https://example.test/"},` + | |
| 39 | 新增: `{"id":"unshared","kind":"editor","workspace":"/e/private","url":"http://127.0.0.1:18080/?folder=%2Fe%2Fprivate"}]}` | |
| 40 | 新增: s.guestClient = &http.Client{Transport: browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 41 | 新增: if r.Method != "GET" || r.URL.Path != "/tabs" || r.Header.Get("Authorization") != "Bearer private-test-token" { | |
| 42 | 新增: t.Fatalf("unexpected guest snapshot request: %s %s", r.Method, r.URL.Path) | |
| 43 | 新增: } | |
| 44 | 新增: return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(snapshot))}, nil | |
| 45 | 新增: })} | |
| 46 | 新增: w := request(s, "GET", "/api/browser/tabs", "", "", true) | |
| 47 | 新增: if w.Code != http.StatusOK { | |
| 48 | 新增: t.Fatalf("snapshot: %d %s", w.Code, w.Body.String()) | |
| 49 | 新增: } | |
| 50 | 新增: var got, want map[string]any | |
| 51 | 新增: if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: if err := json.Unmarshal([]byte(snapshot), &want); err != nil { | |
| 55 | 新增: t.Fatal(err) | |
| 56 | 新增: } | |
| 57 | 新增: wantTabs := want["tabs"].([]any) | |
| 58 | 新增: wantTabs[0].(map[string]any)["workspace"] = s.workspace() | |
| 59 | 新增: wantTabs[1].(map[string]any)["workspace"] = second | |
| 60 | 新增: if !reflect.DeepEqual(got, want) { | |
| 61 | 新增: t.Fatalf("snapshot changed a URL/non-editor/unshared path or lost a granted host path:\ngot: %s", w.Body.String()) | |
| 62 | 新增: } | |
| 63 | 新增: if _, err := s.projectWorkspace("/e/private"); err == nil { | |
| 64 | 新增: t.Fatal("an unshared editor path became a host project grant") | |
| 65 | 新增: } | |
| 66 | 新增: stream := httptest.NewRecorder() | |
| 67 | 新增: if err := s.writeBrowserEvents(stream, strings.NewReader(": heartbeat\n\ndata: "+snapshot+"\n\n")); err != nil { | |
| 68 | 新增: t.Fatal(err) | |
| 69 | 新增: } | |
| 70 | 新增: if !strings.HasPrefix(stream.Body.String(), ": heartbeat\n\n") { | |
| 71 | 新增: t.Fatal("SSE heartbeat was lost") | |
| 72 | 新增: } | |
| 73 | 新增: lines := strings.Split(stream.Body.String(), "\n") | |
| 74 | 新增: var event map[string]any | |
| 75 | 新增: if err := json.Unmarshal([]byte(strings.TrimPrefix(lines[2], "data: ")), &event); err != nil { | |
| 76 | 新增: t.Fatal(err) | |
| 77 | 新增: } | |
| 78 | 新增: if !reflect.DeepEqual(event, got) { | |
| 79 | 新增: t.Fatal("SSE and REST expose different editor workspaces") | |
| 80 | 新增: } | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:type browserGrantReader struct { | |
| 84 | 新增: reader io.Reader | |
| 85 | 新增: next func() io.Reader | |
| 86 | 新增:} | |
| 87 | 新增: | |
| 88 | 新增:func (r *browserGrantReader) Read(p []byte) (int, error) { | |
| 89 | 新增: n, err := r.reader.Read(p) | |
| 90 | 新增: if err == io.EOF && r.next != nil { | |
| 91 | 新增: r.reader, r.next = r.next(), nil | |
| 92 | 新增: return r.reader.Read(p) | |
| 93 | 新增: } | |
| 94 | 新增: return n, err | |
| 95 | 新增:} | |
| 96 | 新增: | |
| 97 | 新增:func TestBrowserEditorWorkspaceSSESeesProjectsAddedAfterConnection(t *testing.T) { | |
| 98 | 新增: s := windowsBrowserWorkspaceServer(t) | |
| 99 | 新增: second := `D:\跨盘 项目\two` | |
| 100 | 新增: payload := `{"tabs":[{"kind":"editor","workspace":"/d/跨盘 项目/two","url":"http://127.0.0.1:18080/?folder=%2Fd%2F跨盘%20项目%2Ftwo"}]}` | |
| 101 | 新增: frame := "data: " + payload + "\n\n" | |
| 102 | 新增: reader := &browserGrantReader{reader: strings.NewReader(frame), next: func() io.Reader { | |
| 103 | 新增: if err := writePrivate(filepath.Join(s.profile, "projects.json"), sharedProjects{Paths: []string{second}}); err != nil { | |
| 104 | 新增: t.Fatal(err) | |
| 105 | 新增: } | |
| 106 | 新增: return strings.NewReader(frame) | |
| 107 | 新增: }} | |
| 108 | 新增: w := httptest.NewRecorder() | |
| 109 | 新增: if err := s.writeBrowserEvents(w, reader); err != nil { | |
| 110 | 新增: t.Fatal(err) | |
| 111 | 新增: } | |
| 112 | 新增: var workspaces []string | |
| 113 | 新增: scanner := bufio.NewScanner(strings.NewReader(w.Body.String())) | |
| 114 | 新增: for scanner.Scan() { | |
| 115 | 新增: if !strings.HasPrefix(scanner.Text(), "data: ") { | |
| 116 | 新增: continue | |
| 117 | 新增: } | |
| 118 | 新增: var state struct{ Tabs []struct{ Workspace string } } | |
| 119 | 新增: if err := json.Unmarshal([]byte(strings.TrimPrefix(scanner.Text(), "data: ")), &state); err != nil { | |
| 120 | 新增: t.Fatal(err) | |
| 121 | 新增: } | |
| 122 | 新增: workspaces = append(workspaces, state.Tabs[0].Workspace) | |
| 123 | 新增: } | |
| 124 | 新增: if !reflect.DeepEqual(workspaces, []string{"/d/跨盘 项目/two", second}) { | |
| 125 | 新增: t.Fatalf("SSE cached or guessed project grants: %#v", workspaces) | |
| 126 | 新增: } | |
| 127 | 新增:} | |
| @@ -0,0 +1,224 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "net/http" | |
| 10 | 新增: "strings" | |
| 11 | 新增: "time" | |
| 12 | 新增: | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:type claudeDesktopState struct { | |
| 18 | 新增: Installed bool `json:"installed"` | |
| 19 | 新增: Version string `json:"version"` | |
| 20 | 新增: Running bool `json:"running"` | |
| 21 | 新增: Failed bool `json:"failed"` | |
| 22 | 新增: Managed bool `json:"managed"` | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:const claudeDesktopSnapshot = `python3 - <<'CAGE_DESKTOP_STATE' | |
| 26 | 新增:import json, subprocess | |
| 27 | 新增:from pathlib import Path | |
| 28 | 新增:def run(*args): | |
| 29 | 新增: return subprocess.run(args, capture_output=True, text=True).stdout.strip() | |
| 30 | 新增:package=run('dpkg-query','-W','-f=${Status}\n${Version}','claude-desktop').splitlines() | |
| 31 | 新增:installed=bool(package and package[0]=='install ok installed') | |
| 32 | 新增:state=run('systemctl','is-active','cage-claude-desktop.service') | |
| 33 | 新增:print(json.dumps({'installed':installed,'version':package[1] if installed else '', 'running':state=='active','failed':state=='failed','managed':Path('/run/cage-desktop/keyring-ready').exists()})) | |
| 34 | 新增:CAGE_DESKTOP_STATE` | |
| 35 | 新增: | |
| 36 | 新增:func (s *Server) claudeDesktopStatus(w http.ResponseWriter, r *http.Request) { | |
| 37 | 新增: if !s.vmRunning() { | |
| 38 | 新增: http.Error(w, "请先启动 Cage 环境", 409) | |
| 39 | 新增: return | |
| 40 | 新增: } | |
| 41 | 新增: ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) | |
| 42 | 新增: defer cancel() | |
| 43 | 新增: b, err := s.guest(ctx, claudeDesktopSnapshot) | |
| 44 | 新增: var state claudeDesktopState | |
| 45 | 新增: if err != nil || json.Unmarshal(b, &state) != nil { | |
| 46 | 新增: http.Error(w, "无法读取 Claude Desktop 状态,请重试", 502) | |
| 47 | 新增: return | |
| 48 | 新增: } | |
| 49 | 新增: jsonReply(w, state) | |
| 50 | 新增:} | |
| 51 | 新增: | |
| 52 | 新增:func (s *Server) claudeDesktopAction(w http.ResponseWriter, r *http.Request) { | |
| 53 | 新增: action := r.PathValue("action") | |
| 54 | 新增: if action != "install" && action != "start" && action != "stop" { | |
| 55 | 新增: http.NotFound(w, r) | |
| 56 | 新增: return | |
| 57 | 新增: } | |
| 58 | 新增: var input struct{} | |
| 59 | 新增: if !readJSON(w, r, &input) { | |
| 60 | 新增: return | |
| 61 | 新增: } | |
| 62 | 新增: if !s.vmRunning() { | |
| 63 | 新增: http.Error(w, "请先启动 Cage 环境", 409) | |
| 64 | 新增: return | |
| 65 | 新增: } | |
| 66 | 新增: s.launch(w, "claude-desktop-"+action, func() error { | |
| 67 | 新增: switch action { | |
| 68 | 新增: case "install": | |
| 69 | 新增: s.mu.Lock() | |
| 70 | 新增: allowed := s.toolsNetworkAllowedLocked() | |
| 71 | 新增: s.mu.Unlock() | |
| 72 | 新增: if !allowed { | |
| 73 | 新增: return errors.New("工作台正在退出,请稍后重试安装") | |
| 74 | 新增: } | |
| 75 | 新增: monitorContext, stopMonitor := context.WithCancel(s.operationContext()) | |
| 76 | 新增: done := make(chan struct{}) | |
| 77 | 新增: go func() { | |
| 78 | 新增: defer close(done) | |
| 79 | 新增: ticker := time.NewTicker(10 * time.Second) | |
| 80 | 新增: defer ticker.Stop() | |
| 81 | 新增: for { | |
| 82 | 新增: select { | |
| 83 | 新增: case <-monitorContext.Done(): | |
| 84 | 新增: return | |
| 85 | 新增: case <-ticker.C: | |
| 86 | 新增: s.monitorSafety() | |
| 87 | 新增: } | |
| 88 | 新增: } | |
| 89 | 新增: }() | |
| 90 | 新增: defer func() { | |
| 91 | 新增: stopMonitor() | |
| 92 | 新增: s.mu.Lock() | |
| 93 | 新增: if s.monitorCancel != nil { | |
| 94 | 新增: s.monitorCancel() | |
| 95 | 新增: } | |
| 96 | 新增: s.mu.Unlock() | |
| 97 | 新增: <-done | |
| 98 | 新增: }() | |
| 99 | 新增: s.setMessage("正在下载并安装 Claude Desktop,可在操作详情查看进度…") | |
| 100 | 新增: return RunMaintenanceScript(s.operationContext(), s.configPath, cage.ClaudeDesktopInstallScript(), jobOutput{s}, jobOutput{s}) | |
| 101 | 新增: case "start": | |
| 102 | 新增: s.setMessage("正在打开 Claude Desktop…") | |
| 103 | 新增: key, err := s.account.desktopKey() | |
| 104 | 新增: if err != nil { | |
| 105 | 新增: return err | |
| 106 | 新增: } | |
| 107 | 新增: defer clear(key) | |
| 108 | 新增: script := `test "$(dpkg-query -W -f='${Status}' claude-desktop 2>/dev/null)" = 'install ok installed' || { echo '请先安装 Claude Desktop。'; exit 1; } | |
| 109 | 新增:` + cage.ClaudeDesktopProvisionScript() | |
| 110 | 新增: if err = s.runDesktopScript(script, 20*time.Second); err != nil { | |
| 111 | 新增: return err | |
| 112 | 新增: } | |
| 113 | 新增: ctx, cancel := context.WithTimeout(s.operationContext(), 55*time.Second) | |
| 114 | 新增: defer cancel() | |
| 115 | 新增: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", "/usr/local/bin/cage-claude-start") | |
| 116 | 新增: cmd.Stdin = bytes.NewReader(key) | |
| 117 | 新增: cmd.Stdout, cmd.Stderr = jobOutput{s}, jobOutput{s} | |
| 118 | 新增: if err = cmd.Run(); err != nil { | |
| 119 | 新增: return errors.New("Claude Desktop 未能启动,请查看操作详情;已有登录数据保持不变") | |
| 120 | 新增: } | |
| 121 | 新增: return nil | |
| 122 | 新增: default: | |
| 123 | 新增: s.setMessage("正在关闭 Claude Desktop…") | |
| 124 | 新增: return s.runDesktopScript("sudo systemctl stop cage-claude-desktop.service", 30*time.Second) | |
| 125 | 新增: } | |
| 126 | 新增: }) | |
| 127 | 新增:} | |
| 128 | 新增: | |
| 129 | 新增:func (s *Server) runDesktopScript(script string, timeout time.Duration) error { | |
| 130 | 新增: ctx, cancel := context.WithTimeout(s.operationContext(), timeout) | |
| 131 | 新增: defer cancel() | |
| 132 | 新增: // A guest cgroup owns apt and all descendants, including across SSH loss. | |
| 133 | 新增: // The application's persistent service is separate from this operation. | |
| 134 | 新增: command := fmt.Sprintf("sudo systemd-run --quiet --pipe --wait --collect --unit=cage-desktop-operation --property=User=cage --property=RuntimeMaxSec=%d --property=KillMode=control-group --setenv=HOME=/home/cage --working-directory=/home/cage /bin/bash -se", int(timeout.Seconds())) | |
| 135 | 新增: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", command) | |
| 136 | 新增: cmd.Stdin = strings.NewReader(script) | |
| 137 | 新增: cmd.Stdout, cmd.Stderr = jobOutput{s}, jobOutput{s} | |
| 138 | 新增: if err := cmd.Run(); err != nil { | |
| 139 | 新增: if ctx.Err() != nil { | |
| 140 | 新增: cleanup, finish := context.WithTimeout(context.Background(), 5*time.Second) | |
| 141 | 新增: defer finish() | |
| 142 | 新增: _, _ = s.guest(cleanup, "sudo systemctl stop cage-desktop-operation.service") | |
| 143 | 新增: return ctx.Err() | |
| 144 | 新增: } | |
| 145 | 新增: return errors.New("Claude Desktop 操作未完成,请查看操作详情;安装失败可重试,已有浏览器和终端不受影响") | |
| 146 | 新增: } | |
| 147 | 新增: return nil | |
| 148 | 新增:} | |
| 149 | 新增: | |
| 150 | 新增:func (s *Server) claudeDesktopCredentials(w http.ResponseWriter, r *http.Request) { | |
| 151 | 新增: ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) | |
| 152 | 新增: defer cancel() | |
| 153 | 新增: b, err := s.guest(ctx, "systemctl is-active --quiet cage-claude-desktop.service && cat /home/cage/.config/claude-cage/desktop-password") | |
| 154 | 新增: password := strings.TrimSpace(string(b)) | |
| 155 | 新增: if err != nil || len(password) != 8 { | |
| 156 | 新增: http.Error(w, "Claude Desktop 尚未启动", 409) | |
| 157 | 新增: return | |
| 158 | 新增: } | |
| 159 | 新增: jsonReply(w, map[string]string{"password": password}) | |
| 160 | 新增:} | |
| 161 | 新增: | |
| 162 | 新增:func (s *Server) claudeDesktopResize(w http.ResponseWriter, r *http.Request) { | |
| 163 | 新增: var input struct { | |
| 164 | 新增: Width int `json:"width"` | |
| 165 | 新增: Height int `json:"height"` | |
| 166 | 新增: } | |
| 167 | 新增: if !readJSON(w, r, &input) { | |
| 168 | 新增: return | |
| 169 | 新增: } | |
| 170 | 新增: if input.Width < 320 || input.Height < 240 || input.Width > 4096 || input.Height > 4096 { | |
| 171 | 新增: http.Error(w, "画面尺寸无效", 400) | |
| 172 | 新增: return | |
| 173 | 新增: } | |
| 174 | 新增: // Fixed commands and validated integers only; no host shell executes input. | |
| 175 | 新增: wid, hei := input.Width, input.Height | |
| 176 | 新增: script := fmt.Sprintf(`set -eu | |
| 177 | 新增:export DISPLAY=:78 XAUTHORITY=/run/cage-desktop/Xauthority | |
| 178 | 新增:exec 9>/run/cage-desktop/resize.lock | |
| 179 | 新增:flock 9 | |
| 180 | 新增:name=cage-%dx%d | |
| 181 | 新增:if ! xrandr --query | grep -q " $name "; then | |
| 182 | 新增: xrandr --newmode "$name" %.3f %d %d %d %d %d %d %d %d +HSync -VSync | |
| 183 | 新增: xrandr --addmode VNC-0 "$name" | |
| 184 | 新增:fi | |
| 185 | 新增:xrandr --output VNC-0 --mode "$name" | |
| 186 | 新增:for old in $(xrandr --query | awk '/^ +cage-/ {print $1}'); do | |
| 187 | 新增: if [ "$old" != "$name" ]; then xrandr --delmode VNC-0 "$old"; xrandr --rmmode "$old"; fi | |
| 188 | 新增:done`, wid, hei, float64((wid+32)*(hei+8)*60)/1000000, wid, wid+8, wid+16, wid+32, hei, hei+1, hei+2, hei+8) | |
| 189 | 新增: ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) | |
| 190 | 新增: defer cancel() | |
| 191 | 新增: if _, err := s.guest(ctx, script); err != nil { | |
| 192 | 新增: http.Error(w, "Claude Desktop 画面尺寸未能调整", 502) | |
| 193 | 新增: return | |
| 194 | 新增: } | |
| 195 | 新增: jsonReply(w, map[string]bool{"ok": true}) | |
| 196 | 新增:} | |
| 197 | 新增: | |
| 198 | 新增:func (s *Server) claudeDesktopVNC(w http.ResponseWriter, r *http.Request) { | |
| 199 | 新增: if !s.vmRunning() { | |
| 200 | 新增: http.Error(w, "环境尚未启动", 409) | |
| 201 | 新增: return | |
| 202 | 新增: } | |
| 203 | 新增: ctx, cancel := context.WithCancel(r.Context()) | |
| 204 | 新增: defer cancel() | |
| 205 | 新增: // No extra localhost port or public VNC listener on the host. SSH is bound | |
| 206 | 新增: // to this profile's single guest and carries the authenticated RFB session. | |
| 207 | 新增: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", "exec socat STDIO UNIX-CONNECT:/run/cage-desktop/vnc.sock") | |
| 208 | 新增: reader, err := cmd.StdoutPipe() | |
| 209 | 新增: if err != nil { | |
| 210 | 新增: http.Error(w, "无法连接应用画面", 502) | |
| 211 | 新增: return | |
| 212 | 新增: } | |
| 213 | 新增: writer, err := cmd.StdinPipe() | |
| 214 | 新增: if err != nil { | |
| 215 | 新增: http.Error(w, "无法连接应用画面", 502) | |
| 216 | 新增: return | |
| 217 | 新增: } | |
| 218 | 新增: if err = cmd.Start(); err != nil { | |
| 219 | 新增: http.Error(w, "无法连接应用画面", 502) | |
| 220 | 新增: return | |
| 221 | 新增: } | |
| 222 | 新增: defer func() { cancel(); writer.Close(); reader.Close(); _ = cmd.Wait() }() | |
| 223 | 新增: s.streamVNC(w, r, reader, writer) | |
| 224 | 新增:} | |
| @@ -0,0 +1,26 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import "testing" | |
| 4 | 新增: | |
| 5 | 新增:func TestClaudeDesktopControlBoundary(t *testing.T) { | |
| 6 | 新增: s := testServer(t) | |
| 7 | 新增: for _, path := range []string{"/api/claude-desktop/install", "/api/claude-desktop/start", "/api/claude-desktop/stop"} { | |
| 8 | 新增: if w := request(s, "POST", path, s.origin, "{}", false); w.Code != 401 { | |
| 9 | 新增: t.Fatalf("%s without session: %d", path, w.Code) | |
| 10 | 新增: } | |
| 11 | 新增: if w := request(s, "POST", path, "https://claude.ai", "{}", true); w.Code != 403 { | |
| 12 | 新增: t.Fatalf("%s cross-origin: %d", path, w.Code) | |
| 13 | 新增: } | |
| 14 | 新增: if w := request(s, "POST", path, s.origin, `{"command":"touch /tmp/untrusted"}`, true); w.Code != 400 { | |
| 15 | 新增: t.Fatalf("%s accepted arbitrary command: %d", path, w.Code) | |
| 16 | 新增: } | |
| 17 | 新增: if w := request(s, "POST", path, s.origin, "{}", true); w.Code != 409 { | |
| 18 | 新增: t.Fatalf("%s must require running VM: %d", path, w.Code) | |
| 19 | 新增: } | |
| 20 | 新增: } | |
| 21 | 新增: for _, body := range []string{`{"width":1,"height":1000}`, `{"width":5000,"height":1000}`, `{"width":"1024;command","height":768}`} { | |
| 22 | 新增: if w := request(s, "POST", "/api/claude-desktop/resize", s.origin, body, true); w.Code != 400 { | |
| 23 | 新增: t.Fatalf("invalid geometry: %d", w.Code) | |
| 24 | 新增: } | |
| 25 | 新增: } | |
| 26 | 新增:} | |
| @@ -0,0 +1,68 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "os/exec" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "runtime" | |
| 8 | 新增: "strings" | |
| 9 | 新增: "testing" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func TestClaudeTerminalRunsSavedCommandOnceAndReturnsToShell(t *testing.T) { | |
| 15 | 新增: if runtime.GOOS == "windows" { | |
| 16 | 新增: t.Skip("guest Bash integration runs on Unix") | |
| 17 | 新增: } | |
| 18 | 新增: dir := filepath.Join(t.TempDir(), "project with ' quotes") | |
| 19 | 新增: if err := os.Mkdir(dir, 0700); err != nil { | |
| 20 | 新增: t.Fatal(err) | |
| 21 | 新增: } | |
| 22 | 新增: command := `printf '%s\n' 'argument with spaces; $(not-executed)' >> command-result` | |
| 23 | 新增: cmd := exec.Command("bash", "-c", terminalScript(dir, "claude", command)) | |
| 24 | 新增: cmd.Env = append(os.Environ(), "HOME="+t.TempDir()) | |
| 25 | 新增: cmd.Stdin = strings.NewReader("printf shell-returned > shell-result\nexit\n") | |
| 26 | 新增: if out, err := cmd.CombinedOutput(); err != nil { | |
| 27 | 新增: t.Fatalf("%v: %s", err, out) | |
| 28 | 新增: } | |
| 29 | 新增: b, err := os.ReadFile(filepath.Join(dir, "command-result")) | |
| 30 | 新增: if err != nil || string(b) != "argument with spaces; $(not-executed)\n" { | |
| 31 | 新增: t.Fatalf("startup command quoting/repetition: %q, %v", b, err) | |
| 32 | 新增: } | |
| 33 | 新增: b, err = os.ReadFile(filepath.Join(dir, "shell-result")) | |
| 34 | 新增: if err != nil || string(b) != "shell-returned" { | |
| 35 | 新增: t.Fatalf("terminal did not return to shell: %q, %v", b, err) | |
| 36 | 新增: } | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:func TestClaudeTerminalPreferenceValidationAndPersistence(t *testing.T) { | |
| 40 | 新增: s := testServer(t) | |
| 41 | 新增: cfg, _ := cage.Load(s.configPath) | |
| 42 | 新增: if settingsView(cfg, s.preferences).ClaudeTerminalCommand != "claude" { | |
| 43 | 新增: t.Fatal("missing default") | |
| 44 | 新增: } | |
| 45 | 新增: input := settingsView(cfg, s.preferences) | |
| 46 | 新增: input.ClaudeTerminalCommand = "claude --continue --model sonnet" | |
| 47 | 新增: _, p, err := proposedSettings(input, cfg, s.profile) | |
| 48 | 新增: if err != nil { | |
| 49 | 新增: t.Fatal(err) | |
| 50 | 新增: } | |
| 51 | 新增: if err = s.apply(savedProfile{cfg, p}, true); err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: data, err := os.ReadFile(filepath.Join(s.profile, "workbench.json")) | |
| 55 | 新增: if err != nil || !strings.Contains(string(data), input.ClaudeTerminalCommand) { | |
| 56 | 新增: t.Fatalf("command not saved: %v", err) | |
| 57 | 新增: } | |
| 58 | 新增: after, _ := cage.Load(s.configPath) | |
| 59 | 新增: if after != cfg { | |
| 60 | 新增: t.Fatal("terminal preference modified environment configuration") | |
| 61 | 新增: } | |
| 62 | 新增: for _, bad := range []string{"claude\nexit", "claude\r", "claude\x00", strings.Repeat("x", 4097)} { | |
| 63 | 新增: input.ClaudeTerminalCommand = bad | |
| 64 | 新增: if _, _, err := proposedSettings(input, cfg, s.profile); err == nil { | |
| 65 | 新增: t.Fatal("invalid command accepted") | |
| 66 | 新增: } | |
| 67 | 新增: } | |
| 68 | 新增:} | |
| @@ -5,7 +5,6 @@ import ( | ||
| 5 | 5 | "net/http" |
| 6 | 6 | "os" |
| 7 | 7 | "path/filepath" |
| 8 | 删除: "syscall" | |
| 9 | 8 | |
| 10 | 9 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 11 | 10 | "github.com/sylvinus/agent-vm/internal/version" |
| @@ -101,7 +100,7 @@ func controllerHasVM(profile string) bool { | ||
| 101 | 100 | if json.Unmarshal(b, &record) != nil || record.PID <= 0 { |
| 102 | 101 | return true |
| 103 | 102 | } |
| 104 | 删除: if err := syscall.Kill(record.PID, 0); err == nil || err != syscall.ESRCH { | |
| 103 | 新增: if processExists(record.PID) { | |
| 105 | 104 | return true |
| 106 | 105 | } |
| 107 | 106 | } |
| @@ -8,7 +8,6 @@ import ( | ||
| 8 | 8 | "path/filepath" |
| 9 | 9 | "strconv" |
| 10 | 10 | "sync/atomic" |
| 11 | 删除: "syscall" | |
| 12 | 11 | "testing" |
| 13 | 12 | "time" |
| 14 | 13 | ) |
| @@ -138,10 +137,10 @@ func TestPrepareUpdateDoesNotAcceptUnresponsiveLockedController(t *testing.T) { | ||
| 138 | 137 | t.Fatal(err) |
| 139 | 138 | } |
| 140 | 139 | defer f.Close() |
| 141 | 删除: if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { | |
| 140 | 新增: if err = lockController(f); err != nil { | |
| 142 | 141 | t.Fatal(err) |
| 143 | 142 | } |
| 144 | 删除: defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN) | |
| 143 | 新增: defer unlockController(f) | |
| 145 | 144 | if _, err := PrepareUpdate(filepath.Join(profile, "config.json"), false); err == nil { |
| 146 | 145 | t.Fatal("locked offline service accepted as safe to replace") |
| 147 | 146 | } |
| @@ -6,6 +6,7 @@ import ( | ||
| 6 | 6 | "errors" |
| 7 | 7 | "fmt" |
| 8 | 8 | "github.com/sylvinus/agent-vm/internal/cage" |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 9 | 10 | "io" |
| 10 | 11 | "net/http" |
| 11 | 12 | "net/http/cookiejar" |
| @@ -13,7 +14,6 @@ import ( | ||
| 13 | 14 | "os" |
| 14 | 15 | "os/exec" |
| 15 | 16 | "path/filepath" |
| 16 | 删除: "syscall" | |
| 17 | 17 | "time" |
| 18 | 18 | ) |
| 19 | 19 | |
| @@ -35,7 +35,14 @@ type controllerClient struct { | ||
| 35 | 35 | var errControllerUnavailable = errors.New("control service is unavailable") |
| 36 | 36 | |
| 37 | 37 | func connectController(profile string) (*controllerClient, error) { |
| 38 | 删除: b, err := os.ReadFile(filepath.Join(profile, "control.json")) | |
| 38 | 新增: path := filepath.Join(profile, "control.json") | |
| 39 | 新增: if err := host.CheckPrivateFile(path); err != nil { | |
| 40 | 新增: if os.IsNotExist(err) { | |
| 41 | 新增: return nil, errControllerUnavailable | |
| 42 | 新增: } | |
| 43 | 新增: return nil, err | |
| 44 | 新增: } | |
| 45 | 新增: b, err := os.ReadFile(path) | |
| 39 | 46 | if os.IsNotExist(err) { |
| 40 | 47 | return nil, errControllerUnavailable |
| 41 | 48 | } |
| @@ -168,10 +175,10 @@ func PrepareUpdate(configPath string, stop bool) (DesktopResult, error) { | ||
| 168 | 175 | lock, lockErr := os.OpenFile(filepath.Join(filepath.Dir(configPath), "control.lock"), os.O_RDWR, 0600) |
| 169 | 176 | if lockErr == nil { |
| 170 | 177 | defer lock.Close() |
| 171 | 删除: if syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) != nil { | |
| 178 | 新增: if lockController(lock) != nil { | |
| 172 | 179 | return DesktopResult{}, errors.New("后台暂时无法连接且尚未退出,请恢复连接后重试更新。") |
| 173 | 180 | } |
| 174 | 删除: defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) | |
| 181 | 新增: defer unlockController(lock) | |
| 175 | 182 | } else if !os.IsNotExist(lockErr) { |
| 176 | 183 | return DesktopResult{}, lockErr |
| 177 | 184 | } |
| @@ -284,7 +291,7 @@ func (c *controllerClient) stopAndHandoff() error { | ||
| 284 | 291 | if err != nil || status != http.StatusOK || final.VMRunning == nil || *final.VMRunning || final.Job.ID != requested.ID || final.Job.Running || final.Job.Error != "" || controllerHasVM(c.profile) { |
| 285 | 292 | return errors.New("停止后又有环境工作,未终止旧后台;请保存停止后重试。") |
| 286 | 293 | } |
| 287 | 删除: if err = syscall.Kill(owner.PID, syscall.SIGTERM); err != nil { | |
| 294 | 新增: if err = terminateLegacy(owner.PID); err != nil { | |
| 288 | 295 | return errors.New("旧后台未能退出,未替换应用。") |
| 289 | 296 | } |
| 290 | 297 | } else { |
| @@ -305,8 +312,8 @@ func (c *controllerClient) waitForExit() error { | ||
| 305 | 312 | } |
| 306 | 313 | defer f.Close() |
| 307 | 314 | for i := 0; i < 100; i++ { |
| 308 | 删除: if syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) == nil { | |
| 309 | 删除: _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN) | |
| 315 | 新增: if lockController(f) == nil { | |
| 316 | 新增: _ = unlockController(f) | |
| 310 | 317 | return nil |
| 311 | 318 | } |
| 312 | 319 | time.Sleep(100 * time.Millisecond) |
| @@ -315,7 +322,7 @@ func (c *controllerClient) waitForExit() error { | ||
| 315 | 322 | } |
| 316 | 323 | func startController(configPath string) error { |
| 317 | 324 | profile := filepath.Dir(configPath) |
| 318 | 删除: if err := os.MkdirAll(profile, 0700); err != nil { | |
| 325 | 新增: if err := host.EnsurePrivateDir(profile); err != nil { | |
| 319 | 326 | return err |
| 320 | 327 | } |
| 321 | 328 | exe, err := os.Executable() |
| @@ -331,7 +338,7 @@ func startController(configPath string) error { | ||
| 331 | 338 | cmd.Dir = profile |
| 332 | 339 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+configPath) |
| 333 | 340 | cmd.Stdout, cmd.Stderr = log, log |
| 334 | 删除: cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} | |
| 341 | 新增: detachController(cmd) | |
| 335 | 342 | if err = cmd.Start(); err != nil { |
| 336 | 343 | return err |
| 337 | 344 | } |
| @@ -151,8 +151,7 @@ func (s *Server) synchronizeEnvironment() error { | ||
| 151 | 151 | } |
| 152 | 152 | |
| 153 | 153 | func (s *Server) toolsNetworkAllowedLocked() bool { |
| 154 | 删除: gate := s.safety.Gate | |
| 155 | 删除: return s.ready && !s.networkPaused && gate != nil && gate.Mode == cage.GateOpen && gate.Until.After(time.Now()) | |
| 154 | 新增: return !s.closing | |
| 156 | 155 | } |
| 157 | 156 | func (s *Server) upgradeEnvironmentTools() error { |
| 158 | 157 | if !s.vmRunning() { |
| @@ -163,19 +162,11 @@ func (s *Server) upgradeEnvironmentTools() error { | ||
| 163 | 162 | manifest := s.guestManifest |
| 164 | 163 | s.mu.Unlock() |
| 165 | 164 | if !allowed { |
| 166 | 删除: return errors.New("工具升级需要已放行的网络。请先恢复外网并通过检查,再重新点击更新。") | |
| 165 | 新增: return errors.New("工作台正在退出,请稍后重试工具更新。") | |
| 167 | 166 | } |
| 168 | 167 | if manifest == nil || !manifest.Current() { |
| 169 | 168 | return errGuestUpdateRequired |
| 170 | 169 | } |
| 171 | 删除: client, err := s.gateClient() | |
| 172 | 删除: if err != nil { | |
| 173 | 删除: return err | |
| 174 | 删除: } | |
| 175 | 删除: state, err := client.Status(s.operationContext()) | |
| 176 | 删除: if err != nil || state.Mode != cage.GateOpen || !state.Until.After(time.Now()) { | |
| 177 | 删除: return errors.New("网络放行已失效,请先重新检查再更新工具。") | |
| 178 | 删除: } | |
| 179 | 170 | monitorContext, stopMonitor := context.WithCancel(s.operationContext()) |
| 180 | 171 | monitorDone := make(chan struct{}) |
| 181 | 172 | go func() { |
| @@ -201,7 +192,7 @@ func (s *Server) upgradeEnvironmentTools() error { | ||
| 201 | 192 | <-monitorDone |
| 202 | 193 | } |
| 203 | 194 | s.setMessage("正在更新 Chromium、编辑器和开发工具,工作台终端与磁盘保持运行…") |
| 204 | 删除: err = s.runCage("run", "bash", "-c", cage.ToolsUpdateScript()) | |
| 195 | 新增: err := s.runCage("update-tools") | |
| 205 | 196 | finishMonitor() |
| 206 | 197 | if err != nil { |
| 207 | 198 | return err |
| @@ -61,49 +61,54 @@ func grantedToolUpdateServer(t *testing.T) (*Server, *cage.EgressGate) { | ||
| 61 | 61 | } |
| 62 | 62 | |
| 63 | 63 | func TestToolUpdateLeaseHonorsPauseStopAndConfigurationAtRenewal(t *testing.T) { |
| 64 | 删除: for _, condition := range []string{"allowed", "paused", "stop", "configuration-changed"} { | |
| 65 | 删除: t.Run(condition, func(t *testing.T) { | |
| 66 | 删除: s, gate := grantedToolUpdateServer(t) | |
| 67 | 删除: client, err := s.gateClient() | |
| 68 | 删除: if err != nil { | |
| 69 | 删除: t.Fatal(err) | |
| 70 | 删除: } | |
| 71 | 删除: before := gate.Status() | |
| 72 | 删除: switch condition { | |
| 73 | 删除: case "paused": | |
| 74 | 删除: if err := s.pauseNetworkNow("test user pause"); err != nil { | |
| 75 | 删除: t.Fatal(err) | |
| 76 | 删除: } | |
| 77 | 删除: case "stop": | |
| 78 | 删除: s.job = Job{ID: "stop", Kind: "stop", Running: true} | |
| 79 | 删除: case "configuration-changed": | |
| 80 | 删除: cfg, err := loadConfig(s.configPath) | |
| 81 | 删除: if err != nil { | |
| 82 | 删除: t.Fatal(err) | |
| 83 | 删除: } | |
| 84 | 删除: cfg.Timezone = "Etc/UTC" | |
| 85 | 删除: if cfg.Fingerprint() == before.Configuration { | |
| 86 | 删除: cfg.Timezone = "Asia/Tokyo" | |
| 87 | 删除: } | |
| 88 | 删除: if err := writePrivate(s.configPath, cfg); err != nil { | |
| 89 | 删除: t.Fatal(err) | |
| 90 | 删除: } | |
| 91 | 删除: } | |
| 92 | 删除: s.finishSafetyMonitor(context.Background(), client, before, "192.0.2.1", "") | |
| 93 | 删除: after := gate.Status() | |
| 94 | 删除: switch condition { | |
| 95 | 删除: case "allowed": | |
| 96 | 删除: if after.Mode != cage.GateOpen || !after.Until.After(before.Until) { | |
| 97 | 删除: t.Fatal("tool update lease was not renewed") | |
| 98 | 删除: } | |
| 99 | 删除: case "paused", "configuration-changed": | |
| 100 | 删除: if after.Mode != cage.GateClosed { | |
| 101 | 删除: t.Fatal("denied network was renewed") | |
| 102 | 删除: } | |
| 103 | 删除: case "stop": | |
| 104 | 删除: if after.Until != before.Until { | |
| 105 | 删除: t.Fatal("stopping job allowed a lease renewal") | |
| 106 | 删除: } | |
| 64 | 新增: for _, jobKind := range []string{"environment-tools", "claude-desktop-install"} { | |
| 65 | 新增: t.Run(jobKind, func(t *testing.T) { | |
| 66 | 新增: for _, condition := range []string{"allowed", "paused", "stop", "configuration-changed"} { | |
| 67 | 新增: t.Run(condition, func(t *testing.T) { | |
| 68 | 新增: s, gate := grantedToolUpdateServer(t) | |
| 69 | 新增: s.job.Kind = jobKind | |
| 70 | 新增: client, err := s.gateClient() | |
| 71 | 新增: if err != nil { | |
| 72 | 新增: t.Fatal(err) | |
| 73 | 新增: } | |
| 74 | 新增: before := gate.Status() | |
| 75 | 新增: switch condition { | |
| 76 | 新增: case "paused": | |
| 77 | 新增: if err := s.pauseNetworkNow("test user pause"); err != nil { | |
| 78 | 新增: t.Fatal(err) | |
| 79 | 新增: } | |
| 80 | 新增: case "stop": | |
| 81 | 新增: s.job = Job{ID: "stop", Kind: "stop", Running: true} | |
| 82 | 新增: case "configuration-changed": | |
| 83 | 新增: cfg, err := loadConfig(s.configPath) | |
| 84 | 新增: if err != nil { | |
| 85 | 新增: t.Fatal(err) | |
| 86 | 新增: } | |
| 87 | 新增: cfg.Timezone = "Etc/UTC" | |
| 88 | 新增: if cfg.Fingerprint() == before.Configuration { | |
| 89 | 新增: cfg.Timezone = "Asia/Tokyo" | |
| 90 | 新增: } | |
| 91 | 新增: if err := writePrivate(s.configPath, cfg); err != nil { | |
| 92 | 新增: t.Fatal(err) | |
| 93 | 新增: } | |
| 94 | 新增: } | |
| 95 | 新增: s.finishSafetyMonitor(context.Background(), client, before, "192.0.2.1", "") | |
| 96 | 新增: after := gate.Status() | |
| 97 | 新增: switch condition { | |
| 98 | 新增: case "allowed": | |
| 99 | 新增: if after.Mode != cage.GateOpen || !after.Until.After(before.Until) { | |
| 100 | 新增: t.Fatal("tool update lease was not renewed") | |
| 101 | 新增: } | |
| 102 | 新增: case "paused", "configuration-changed": | |
| 103 | 新增: if after.Mode != cage.GateClosed { | |
| 104 | 新增: t.Fatal("denied network was renewed") | |
| 105 | 新增: } | |
| 106 | 新增: case "stop": | |
| 107 | 新增: if after.Until != before.Until { | |
| 108 | 新增: t.Fatal("stopping job allowed a lease renewal") | |
| 109 | 新增: } | |
| 110 | 新增: } | |
| 111 | 新增: }) | |
| 107 | 112 | } |
| 108 | 113 | }) |
| 109 | 114 | } |
| @@ -119,9 +124,11 @@ func TestToolUpdateDoesNotRestorePausedOrExpiredNetworking(t *testing.T) { | ||
| 119 | 124 | } else { |
| 120 | 125 | gate.Close("expired") |
| 121 | 126 | } |
| 122 | 删除: err := s.upgradeEnvironmentTools() | |
| 123 | 删除: if err == nil || !strings.Contains(err.Error(), "网络") { | |
| 124 | 删除: t.Fatalf("closed gate accepted: %v", err) | |
| 127 | 新增: s.mu.Lock() | |
| 128 | 新增: allowed := s.toolsNetworkAllowedLocked() | |
| 129 | 新增: s.mu.Unlock() | |
| 130 | 新增: if !allowed { | |
| 131 | 新增: t.Fatal("business network pause blocked maintenance") | |
| 125 | 132 | } |
| 126 | 133 | if gate.Status().Mode != cage.GateClosed { |
| 127 | 134 | t.Fatal("tool update restored closed network") |
| @@ -3,6 +3,7 @@ package workbench | ||
| 3 | 3 | import ( |
| 4 | 4 | "encoding/json" |
| 5 | 5 | "fmt" |
| 6 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 6 | 7 | "os" |
| 7 | 8 | "path/filepath" |
| 8 | 9 | "sync" |
| @@ -42,8 +43,7 @@ func TestFavoritesPersistenceAndFolders(t *testing.T) { | ||
| 42 | 43 | if err != nil || f.Folders[0].Title != "工作" || f.Items[0].URL != "https://example.com/new" { |
| 43 | 44 | t.Fatalf("persistence: %+v %v", f, err) |
| 44 | 45 | } |
| 45 | 删除: info, err := os.Stat(filepath.Join(s.profile, "favorites.json")) | |
| 46 | 删除: if err != nil || info.Mode().Perm() != 0600 { | |
| 46 | 新增: if host.CheckPrivateFile(filepath.Join(s.profile, "favorites.json")) != nil { | |
| 47 | 47 | t.Fatal("favorites file must be private") |
| 48 | 48 | } |
| 49 | 49 | f = post(fmt.Sprintf(`{"action":"delete_folder","id":%q}`, folder)) |
| @@ -33,7 +33,7 @@ func inspectHostGit(ctx context.Context) hostGitState { | ||
| 33 | 33 | case gitguard.BareOld: |
| 34 | 34 | view.Message = "本机 Git 版本过旧,请升级到 2.38 或更新版本后重新检查。" |
| 35 | 35 | default: |
| 36 | 删除: view.Message = "暂时无法检查本机 Git。请确认 Git 或 Xcode Command Line Tools 安装完整,再重新检查;Cage 不会自动打开安装器。" | |
| 36 | 新增: view.Message = "暂时无法检查本机 Git。请确认 Git 安装完整,再重新检查;Cage 不会自动打开安装器。" | |
| 37 | 37 | } |
| 38 | 38 | return view |
| 39 | 39 | } |
| @@ -70,7 +70,7 @@ func (s *Server) enableHostGit(w http.ResponseWriter, r *http.Request) { | ||
| 70 | 70 | return |
| 71 | 71 | } |
| 72 | 72 | cmd := gitx.Untrusted(ctx, "config", "--global", "--replace-all", "safe.bareRepository", "explicit") |
| 73 | 删除: cmd.Dir = "/" | |
| 73 | 新增: cmd.Dir = s.profile | |
| 74 | 74 | if err := cmd.Run(); err != nil { |
| 75 | 75 | http.Error(w, "未能保存 Git 安全设置。请检查全局 Git 配置的写入权限,关闭其他 Git 设置操作后重试。", http.StatusInternalServerError) |
| 76 | 76 | return |
| @@ -0,0 +1,129 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/base64" | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "image/png" | |
| 10 | 新增: "io" | |
| 11 | 新增: "net/http" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:const maxImageBytes = 20 << 20 | |
| 19 | 新增: | |
| 20 | 新增:func decodeInputImage(encoded string) ([]byte, error) { | |
| 21 | 新增: if len(encoded) > base64.StdEncoding.EncodedLen(maxImageBytes) { | |
| 22 | 新增: return nil, errors.New("图片不能超过 20 MB") | |
| 23 | 新增: } | |
| 24 | 新增: data, err := base64.StdEncoding.Strict().DecodeString(encoded) | |
| 25 | 新增: if err != nil || len(data) == 0 || len(data) > maxImageBytes { | |
| 26 | 新增: return nil, errors.New("图片数据无效") | |
| 27 | 新增: } | |
| 28 | 新增: config, err := png.DecodeConfig(bytes.NewReader(data)) | |
| 29 | 新增: if err != nil || config.Width <= 0 || config.Height <= 0 || int64(config.Width)*int64(config.Height) > 40_000_000 { | |
| 30 | 新增: return nil, errors.New("需要有效的 PNG 图片,且不能超过 4000 万像素") | |
| 31 | 新增: } | |
| 32 | 新增: if _, err := png.Decode(bytes.NewReader(data)); err != nil { | |
| 33 | 新增: return nil, errors.New("图片已损坏,请重新复制或选择图片") | |
| 34 | 新增: } | |
| 35 | 新增: return data, nil | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func (s *Server) imageInput(w http.ResponseWriter, r *http.Request) { | |
| 39 | 新增: var input struct { | |
| 40 | 新增: PNG string `json:"png"` | |
| 41 | 新增: Target string `json:"target"` | |
| 42 | 新增: ID string `json:"id"` | |
| 43 | 新增: } | |
| 44 | 新增: if !readJSON(w, r, &input, int64(base64.StdEncoding.EncodedLen(maxImageBytes)+4096)) { | |
| 45 | 新增: return | |
| 46 | 新增: } | |
| 47 | 新增: if (input.Target != "browser" && input.Target != "desktop" && input.Target != "terminal") || (input.Target != "desktop" && input.ID == "") || len(input.ID) > 256 { | |
| 48 | 新增: http.Error(w, "图片目标无效", 400) | |
| 49 | 新增: return | |
| 50 | 新增: } | |
| 51 | 新增: s.mu.Lock() | |
| 52 | 新增: ready, token, terminal := s.ready, s.credentials.Token, s.terminals[input.ID] | |
| 53 | 新增: s.mu.Unlock() | |
| 54 | 新增: if !ready { | |
| 55 | 新增: http.Error(w, "环境尚未就绪", 409) | |
| 56 | 新增: return | |
| 57 | 新增: } | |
| 58 | 新增: if input.Target == "terminal" { | |
| 59 | 新增: if terminal == nil { | |
| 60 | 新增: http.Error(w, "终端已关闭", 409) | |
| 61 | 新增: return | |
| 62 | 新增: } | |
| 63 | 新增: terminal.mu.Lock() | |
| 64 | 新增: closed := terminal.closed | |
| 65 | 新增: terminal.mu.Unlock() | |
| 66 | 新增: if closed { | |
| 67 | 新增: http.Error(w, "终端已关闭", 409) | |
| 68 | 新增: return | |
| 69 | 新增: } | |
| 70 | 新增: } | |
| 71 | 新增: data, err := decodeInputImage(input.PNG) | |
| 72 | 新增: if err != nil { | |
| 73 | 新增: requestError(w, err) | |
| 74 | 新增: return | |
| 75 | 新增: } | |
| 76 | 新增: ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) | |
| 77 | 新增: defer cancel() | |
| 78 | 新增: if input.Target == "browser" { | |
| 79 | 新增: body, _ := json.Marshal(map[string]string{"id": input.ID, "png": input.PNG}) | |
| 80 | 新增: if _, err = s.guestAPI(ctx, token, "POST", "/paste-image", body); err != nil { | |
| 81 | 新增: http.Error(w, "图片未能粘贴,请点击支持图片的输入框后重试;环境组件过旧时请先更新环境", 502) | |
| 82 | 新增: return | |
| 83 | 新增: } | |
| 84 | 新增: jsonReply(w, map[string]bool{"ok": true}) | |
| 85 | 新增: return | |
| 86 | 新增: } | |
| 87 | 新增: result, err := s.guestImage(ctx, input.Target, data) | |
| 88 | 新增: if err != nil { | |
| 89 | 新增: http.Error(w, err.Error(), 502) | |
| 90 | 新增: return | |
| 91 | 新增: } | |
| 92 | 新增: jsonReply(w, result) | |
| 93 | 新增:} | |
| 94 | 新增: | |
| 95 | 新增:func (s *Server) guestImage(ctx context.Context, target string, data []byte) (map[string]any, error) { | |
| 96 | 新增: script := "sudo -H -u cage /usr/local/bin/cage-image-input save" | |
| 97 | 新增: if target == "desktop" { | |
| 98 | 新增: script = "systemctl is-active --quiet cage-claude-desktop.service && sudo -H -u cage env DISPLAY=:78 XAUTHORITY=/run/cage-desktop/Xauthority /usr/local/bin/cage-image-input paste" | |
| 99 | 新增: } | |
| 100 | 新增: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", script) | |
| 101 | 新增: cmd.Stdin = bytes.NewReader(data) | |
| 102 | 新增: pipe, err := cmd.StdoutPipe() | |
| 103 | 新增: if err != nil { | |
| 104 | 新增: return nil, err | |
| 105 | 新增: } | |
| 106 | 新增: if err = cmd.Start(); err != nil { | |
| 107 | 新增: return nil, errors.New("无法连接 Cage 环境") | |
| 108 | 新增: } | |
| 109 | 新增: output, readErr := io.ReadAll(io.LimitReader(pipe, 4097)) | |
| 110 | 新增: if readErr != nil || len(output) > 4096 { | |
| 111 | 新增: _ = cmd.Process.Kill() | |
| 112 | 新增: _ = cmd.Wait() | |
| 113 | 新增: return nil, errors.New("图片传递响应无效") | |
| 114 | 新增: } | |
| 115 | 新增: if err = cmd.Wait(); err != nil { | |
| 116 | 新增: return nil, errors.New("图片未能传入 Cage,请确认目标已打开并支持图片;环境组件过旧时请先更新环境") | |
| 117 | 新增: } | |
| 118 | 新增: var result map[string]any | |
| 119 | 新增: if json.Unmarshal(output, &result) != nil { | |
| 120 | 新增: return nil, errors.New("图片传递响应无效") | |
| 121 | 新增: } | |
| 122 | 新增: if target == "terminal" { | |
| 123 | 新增: path, ok := result["path"].(string) | |
| 124 | 新增: if !ok || !strings.HasPrefix(path, "/home/cage/.local/share/cage/attachments/image-") || strings.ContainsAny(path, "'\r\n\x00") { | |
| 125 | 新增: return nil, errors.New("图片保存路径无效") | |
| 126 | 新增: } | |
| 127 | 新增: } | |
| 128 | 新增: return result, nil | |
| 129 | 新增:} | |
| @@ -0,0 +1,88 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "encoding/base64" | |
| 6 | 新增: "encoding/binary" | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "hash/crc32" | |
| 9 | 新增: "image" | |
| 10 | 新增: "image/png" | |
| 11 | 新增: "io" | |
| 12 | 新增: "net/http" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "testing" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func testPNG(t *testing.T) string { | |
| 18 | 新增: t.Helper() | |
| 19 | 新增: var data bytes.Buffer | |
| 20 | 新增: if err := png.Encode(&data, image.NewNRGBA(image.Rect(0, 0, 2, 2))); err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: return base64.StdEncoding.EncodeToString(data.Bytes()) | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:func TestInputImageValidation(t *testing.T) { | |
| 27 | 新增: valid := testPNG(t) | |
| 28 | 新增: if _, err := decodeInputImage(valid); err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: for _, input := range []string{"", "!", base64.StdEncoding.EncodeToString([]byte("not PNG")), valid[:len(valid)-16], strings.Repeat("A", base64.StdEncoding.EncodedLen(maxImageBytes)+4)} { | |
| 32 | 新增: if _, err := decodeInputImage(input); err == nil { | |
| 33 | 新增: t.Fatal("invalid image accepted") | |
| 34 | 新增: } | |
| 35 | 新增: } | |
| 36 | 新增: oversized, _ := base64.StdEncoding.DecodeString(valid) | |
| 37 | 新增: binary.BigEndian.PutUint32(oversized[16:20], 40_000_001) | |
| 38 | 新增: binary.BigEndian.PutUint32(oversized[29:33], crc32.ChecksumIEEE(oversized[12:29])) | |
| 39 | 新增: if _, err := decodeInputImage(base64.StdEncoding.EncodeToString(oversized)); err == nil { | |
| 40 | 新增: t.Fatal("oversized dimensions accepted") | |
| 41 | 新增: } | |
| 42 | 新增:} | |
| 43 | 新增: | |
| 44 | 新增:func TestImageInputAuthenticationAndDestination(t *testing.T) { | |
| 45 | 新增: s := testServer(t) | |
| 46 | 新增: s.ready = true | |
| 47 | 新增: s.credentials.Token = "guest-test-token" | |
| 48 | 新增: calls := 0 | |
| 49 | 新增: s.guestClient = &http.Client{Transport: browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 50 | 新增: calls++ | |
| 51 | 新增: if r.URL.Path != "/paste-image" || r.Header.Get("Authorization") != "Bearer guest-test-token" { | |
| 52 | 新增: t.Fatal("wrong destination or credentials") | |
| 53 | 新增: } | |
| 54 | 新增: var input map[string]string | |
| 55 | 新增: if err := json.NewDecoder(r.Body).Decode(&input); err != nil || input["id"] != "tab-1" || input["png"] != testPNG(t) { | |
| 56 | 新增: t.Fatal("image or target changed", err) | |
| 57 | 新增: } | |
| 58 | 新增: return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"ok":true}`))}, nil | |
| 59 | 新增: })} | |
| 60 | 新增: body := `{"target":"browser","id":"tab-1","png":"` + testPNG(t) + `"}` | |
| 61 | 新增: path := "/api/input/image" | |
| 62 | 新增: if w := request(s, "POST", path, s.origin, body, false); w.Code != 401 { | |
| 63 | 新增: t.Fatal(w.Code) | |
| 64 | 新增: } | |
| 65 | 新增: if w := request(s, "POST", path, "https://example.com", body, true); w.Code != 403 { | |
| 66 | 新增: t.Fatal(w.Code) | |
| 67 | 新增: } | |
| 68 | 新增: for _, bad := range []string{`{"target":"browser","png":"` + testPNG(t) + `"}`, `{"target":"host","id":"tab-1"}`, `{"target":"terminal","id":"missing","png":"` + testPNG(t) + `"}`, `{"target":"browser","id":"tab-1","png":"broken"}`} { | |
| 69 | 新增: if w := request(s, "POST", path, s.origin, bad, true); w.Code < 400 { | |
| 70 | 新增: t.Fatal("invalid image accepted") | |
| 71 | 新增: } | |
| 72 | 新增: } | |
| 73 | 新增: if calls != 0 { | |
| 74 | 新增: t.Fatal("invalid input reached guest") | |
| 75 | 新增: } | |
| 76 | 新增: if w := request(s, "POST", path, s.origin, body, true); w.Code != 200 || calls != 1 { | |
| 77 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 78 | 新增: } | |
| 79 | 新增: s.ready = false | |
| 80 | 新增: if w := request(s, "POST", path, s.origin, body, true); w.Code != 409 || calls != 1 { | |
| 81 | 新增: t.Fatal("offline input accepted") | |
| 82 | 新增: } | |
| 83 | 新增: s.ready = true | |
| 84 | 新增: s.account.lock() | |
| 85 | 新增: if w := request(s, "POST", path, s.origin, body, true); w.Code != 423 || calls != 1 { | |
| 86 | 新增: t.Fatal("locked account accepted an image") | |
| 87 | 新增: } | |
| 88 | 新增:} | |
| @@ -0,0 +1,93 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "io" | |
| 9 | 新增: "net" | |
| 10 | 新增: "net/http" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "time" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:// Both providers look up the measured address, never their connection's exit. | |
| 16 | 新增:// The caller supplies the shared proxy-only client, including for fallback. | |
| 17 | 新增:func lookupLocation(ctx context.Context, client *http.Client, address net.IP) (Location, error) { | |
| 18 | 新增: providers := []struct{ name, url string }{ | |
| 19 | 新增: {"ipwho.is", "https://ipwho.is/" + address.String() + "?fields=success,ip,country,country_code,region,region_code,city,timezone.id"}, | |
| 20 | 新增: {"IP.SB", "https://api.ip.sb/geoip/" + address.String()}, | |
| 21 | 新增: } | |
| 22 | 新增: failures := make([]string, 0, len(providers)) | |
| 23 | 新增: for _, provider := range providers { | |
| 24 | 新增: if err := ctx.Err(); err != nil { | |
| 25 | 新增: return Location{}, err | |
| 26 | 新增: } | |
| 27 | 新增: loc, err := queryLocation(ctx, client, provider.url, provider.name == "ipwho.is", address) | |
| 28 | 新增: if err == nil { | |
| 29 | 新增: return loc, nil | |
| 30 | 新增: } | |
| 31 | 新增: // Only our own summaries reach the UI; transport errors may contain | |
| 32 | 新增: // local network details and provider bodies are untrusted text. | |
| 33 | 新增: failures = append(failures, provider.name+":"+err.Error()) | |
| 34 | 新增: } | |
| 35 | 新增: if err := ctx.Err(); err != nil { | |
| 36 | 新增: return Location{}, err | |
| 37 | 新增: } | |
| 38 | 新增: return Location{}, fmt.Errorf("已测得出口 IP,但位置查询均失败(%s);请重试或切换节点。未使用直连回退", strings.Join(failures, ";")) | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:func queryLocation(ctx context.Context, client *http.Client, endpoint string, requireSuccess bool, address net.IP) (Location, error) { | |
| 42 | 新增: req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) | |
| 43 | 新增: if err != nil { | |
| 44 | 新增: return Location{}, errors.New("查询地址无效") | |
| 45 | 新增: } | |
| 46 | 新增: req.Header.Set("User-Agent", "Cage-network-check/1") | |
| 47 | 新增: r, err := client.Do(req) | |
| 48 | 新增: if err != nil { | |
| 49 | 新增: return Location{}, errors.New("连接失败或超时") | |
| 50 | 新增: } | |
| 51 | 新增: defer r.Body.Close() | |
| 52 | 新增: if r.StatusCode != http.StatusOK { | |
| 53 | 新增: return Location{}, fmt.Errorf("HTTP %d", r.StatusCode) | |
| 54 | 新增: } | |
| 55 | 新增: var v struct { | |
| 56 | 新增: Success *bool `json:"success"` | |
| 57 | 新增: IP string `json:"ip"` | |
| 58 | 新增: Country string `json:"country"` | |
| 59 | 新增: CountryCode string `json:"country_code"` | |
| 60 | 新增: Region string `json:"region"` | |
| 61 | 新增: RegionCode string `json:"region_code"` | |
| 62 | 新增: City string `json:"city"` | |
| 63 | 新增: Timezone json.RawMessage `json:"timezone"` | |
| 64 | 新增: } | |
| 65 | 新增: if json.NewDecoder(io.LimitReader(r.Body, 128<<10)).Decode(&v) != nil || | |
| 66 | 新增: (requireSuccess && (v.Success == nil || !*v.Success)) || | |
| 67 | 新增: net.ParseIP(v.IP) == nil || !net.ParseIP(v.IP).Equal(address) { | |
| 68 | 新增: return Location{}, errors.New("响应无效或 IP 不匹配") | |
| 69 | 新增: } | |
| 70 | 新增: country := strings.ToUpper(strings.TrimSpace(v.CountryCode)) | |
| 71 | 新增: if len(country) != 2 || country[0] < 'A' || country[0] > 'Z' || country[1] < 'A' || country[1] > 'Z' { | |
| 72 | 新增: return Location{}, errors.New("缺少有效国家或地区") | |
| 73 | 新增: } | |
| 74 | 新增: var timezone string | |
| 75 | 新增: if requireSuccess { | |
| 76 | 新增: var zone struct { | |
| 77 | 新增: ID string `json:"id"` | |
| 78 | 新增: } | |
| 79 | 新增: if json.Unmarshal(v.Timezone, &zone) == nil { | |
| 80 | 新增: timezone = zone.ID | |
| 81 | 新增: } | |
| 82 | 新增: } else { | |
| 83 | 新增: _ = json.Unmarshal(v.Timezone, &timezone) | |
| 84 | 新增: } | |
| 85 | 新增: if timezone == "" || timezone == "Local" { | |
| 86 | 新增: return Location{}, errors.New("缺少有效时区") | |
| 87 | 新增: } | |
| 88 | 新增: if _, err = time.LoadLocation(timezone); err != nil { | |
| 89 | 新增: return Location{}, errors.New("缺少有效时区") | |
| 90 | 新增: } | |
| 91 | 新增: locale, browser := languageSuggestion(country) | |
| 92 | 新增: return Location{IP: address.String(), Country: v.Country, CountryCode: country, Region: v.Region, RegionCode: v.RegionCode, City: v.City, Timezone: timezone, CheckedAt: time.Now(), SuggestedLocale: locale, SuggestedBrowserLanguage: browser}, nil | |
| 93 | 新增:} | |
| @@ -0,0 +1,344 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "io" | |
| 7 | 新增: "net" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "net/http/httptest" | |
| 10 | 新增: "net/url" | |
| 11 | 新增: "os" | |
| 12 | 新增: "os/exec" | |
| 13 | 新增: "path/filepath" | |
| 14 | 新增: "strconv" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "testing" | |
| 17 | 新增: "time" | |
| 18 | 新增: | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 20 | 新增: "github.com/sylvinus/agent-vm/internal/managedproxy" | |
| 21 | 新增:) | |
| 22 | 新增: | |
| 23 | 新增:const primaryLocationJSON = `{"success":true,"ip":"8.8.8.8","country":"United States","country_code":"US","region":"California","city":"Mountain View","timezone":{"id":"America/Los_Angeles"}}` | |
| 24 | 新增:const backupLocationJSON = `{"ip":"8.8.8.8","country":"United States","country_code":"US","region":"California","region_code":"CA","city":"Mountain View","timezone":"America/Los_Angeles"}` | |
| 25 | 新增: | |
| 26 | 新增:func locationResponse(status int, body string) *http.Response { | |
| 27 | 新增: return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))} | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:func TestLocationFallbackUsesMeasuredIP(t *testing.T) { | |
| 31 | 新增: for _, tc := range []struct { | |
| 32 | 新增: name string | |
| 33 | 新增: status int | |
| 34 | 新增: body string | |
| 35 | 新增: }{ | |
| 36 | 新增: {"connection interrupted", 0, ""}, | |
| 37 | 新增: {"timed out", -1, ""}, | |
| 38 | 新增: {"rate limited", 429, ""}, | |
| 39 | 新增: {"unavailable", 503, ""}, | |
| 40 | 新增: {"malformed", 200, "not json"}, | |
| 41 | 新增: {"rejected", 200, strings.Replace(primaryLocationJSON, `"success":true`, `"success":false`, 1)}, | |
| 42 | 新增: {"wrong IP", 200, strings.Replace(primaryLocationJSON, "8.8.8.8", "9.9.9.9", 1)}, | |
| 43 | 新增: {"missing country", 200, strings.Replace(primaryLocationJSON, `"US"`, `""`, 1)}, | |
| 44 | 新增: {"invalid timezone", 200, strings.Replace(primaryLocationJSON, "America/Los_Angeles", "Not/AZone", 1)}, | |
| 45 | 新增: } { | |
| 46 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 47 | 新增: var hosts []string | |
| 48 | 新增: client := &http.Client{Timeout: 50 * time.Millisecond, Transport: browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 49 | 新增: hosts = append(hosts, r.URL.Host) | |
| 50 | 新增: if r.URL.Scheme != "https" || r.Method != "GET" || r.Header.Get("User-Agent") != "Cage-network-check/1" { | |
| 51 | 新增: t.Fatal("lookup changed its fixed HTTPS request contract") | |
| 52 | 新增: } | |
| 53 | 新增: switch r.URL.Host { | |
| 54 | 新增: case "ipwho.is": | |
| 55 | 新增: if r.URL.Path != "/8.8.8.8" { | |
| 56 | 新增: t.Fatal("primary did not query measured IP") | |
| 57 | 新增: } | |
| 58 | 新增: if tc.status == 0 { | |
| 59 | 新增: return nil, errors.New("private transport detail") | |
| 60 | 新增: } | |
| 61 | 新增: if tc.status == -1 { | |
| 62 | 新增: <-r.Context().Done() | |
| 63 | 新增: return nil, r.Context().Err() | |
| 64 | 新增: } | |
| 65 | 新增: return locationResponse(tc.status, tc.body), nil | |
| 66 | 新增: case "api.ip.sb": | |
| 67 | 新增: if r.URL.Path != "/geoip/8.8.8.8" { | |
| 68 | 新增: t.Fatal("fallback did not query measured IP") | |
| 69 | 新增: } | |
| 70 | 新增: return locationResponse(200, backupLocationJSON), nil | |
| 71 | 新增: default: | |
| 72 | 新增: t.Fatal("unexpected location provider") | |
| 73 | 新增: return nil, errors.New("unexpected host") | |
| 74 | 新增: } | |
| 75 | 新增: })} | |
| 76 | 新增: loc, err := lookupLocation(context.Background(), client, net.ParseIP("8.8.8.8")) | |
| 77 | 新增: if err != nil || loc.IP != "8.8.8.8" || loc.CountryCode != "US" || loc.RegionCode != "CA" || loc.Timezone != "America/Los_Angeles" || loc.SuggestedLocale != "en_US.UTF-8" || loc.CheckedAt.IsZero() { | |
| 78 | 新增: t.Fatalf("fallback location: %+v, %v", loc, err) | |
| 79 | 新增: } | |
| 80 | 新增: if strings.Join(hosts, ",") != "ipwho.is,api.ip.sb" { | |
| 81 | 新增: t.Fatalf("incorrect fallback order: %v", hosts) | |
| 82 | 新增: } | |
| 83 | 新增: }) | |
| 84 | 新增: } | |
| 85 | 新增:} | |
| 86 | 新增: | |
| 87 | 新增:func TestLocationFallbackStaysOnConfiguredProxy(t *testing.T) { | |
| 88 | 新增: targets := make(chan string, 2) | |
| 89 | 新增: proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 90 | 新增: if r.Method != http.MethodConnect { | |
| 91 | 新增: t.Error("location query did not establish a proxy tunnel") | |
| 92 | 新增: } | |
| 93 | 新增: targets <- r.Host | |
| 94 | 新增: w.WriteHeader(http.StatusBadGateway) | |
| 95 | 新增: })) | |
| 96 | 新增: defer proxy.Close() | |
| 97 | 新增: cfg := cage.DefaultConfig() | |
| 98 | 新增: cfg.ProxyURL = proxy.URL | |
| 99 | 新增: if _, err := probeLocationForIP(context.Background(), cfg, "8.8.8.8"); err == nil { | |
| 100 | 新增: t.Fatal("rejected proxy requests produced a location") | |
| 101 | 新增: } | |
| 102 | 新增: for _, want := range []string{"ipwho.is:443", "api.ip.sb:443"} { | |
| 103 | 新增: select { | |
| 104 | 新增: case target := <-targets: | |
| 105 | 新增: if target != want { | |
| 106 | 新增: t.Fatal("unexpected proxy destination", target) | |
| 107 | 新增: } | |
| 108 | 新增: default: | |
| 109 | 新增: t.Fatal("location provider bypassed configured proxy", want) | |
| 110 | 新增: } | |
| 111 | 新增: } | |
| 112 | 新增:} | |
| 113 | 新增: | |
| 114 | 新增:func TestSuccessfulPrimaryLocationDoesNotQueryBackup(t *testing.T) { | |
| 115 | 新增: client := &http.Client{Transport: browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 116 | 新增: if r.URL.Host != "ipwho.is" { | |
| 117 | 新增: t.Fatal("backup queried despite valid primary") | |
| 118 | 新增: } | |
| 119 | 新增: return locationResponse(200, primaryLocationJSON), nil | |
| 120 | 新增: })} | |
| 121 | 新增: if _, err := lookupLocation(context.Background(), client, net.ParseIP("8.8.8.8")); err != nil { | |
| 122 | 新增: t.Fatal(err) | |
| 123 | 新增: } | |
| 124 | 新增:} | |
| 125 | 新增: | |
| 126 | 新增:func TestLocationRejectsInvalidBackupAndKeepsErrorsPrivate(t *testing.T) { | |
| 127 | 新增: for _, body := range []string{ | |
| 128 | 新增: strings.Replace(backupLocationJSON, "8.8.8.8", "9.9.9.9", 1), | |
| 129 | 新增: strings.Replace(backupLocationJSON, "America/Los_Angeles", "Local", 1), | |
| 130 | 新增: strings.Replace(backupLocationJSON, "America/Los_Angeles", "", 1), | |
| 131 | 新增: strings.Replace(backupLocationJSON, `"US"`, `""`, 1), | |
| 132 | 新增: } { | |
| 133 | 新增: client := &http.Client{Transport: browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 134 | 新增: if r.URL.Host == "ipwho.is" { | |
| 135 | 新增: return nil, errors.New("private-secret") | |
| 136 | 新增: } | |
| 137 | 新增: return locationResponse(200, body), nil | |
| 138 | 新增: })} | |
| 139 | 新增: loc, err := lookupLocation(context.Background(), client, net.ParseIP("8.8.8.8")) | |
| 140 | 新增: if err == nil || loc != (Location{}) || strings.Contains(err.Error(), "private-secret") || !strings.Contains(err.Error(), "位置查询均失败") { | |
| 141 | 新增: t.Fatalf("invalid backup accepted or error leaked: %+v, %v", loc, err) | |
| 142 | 新增: } | |
| 143 | 新增: } | |
| 144 | 新增:} | |
| 145 | 新增: | |
| 146 | 新增:func TestLocationCancellationStopsFallback(t *testing.T) { | |
| 147 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 148 | 新增: defer cancel() | |
| 149 | 新增: calls := 0 | |
| 150 | 新增: client := &http.Client{Transport: browserTransport(func(*http.Request) (*http.Response, error) { | |
| 151 | 新增: calls++ | |
| 152 | 新增: cancel() | |
| 153 | 新增: return nil, context.Canceled | |
| 154 | 新增: })} | |
| 155 | 新增: _, err := lookupLocation(ctx, client, net.ParseIP("8.8.8.8")) | |
| 156 | 新增: if !errors.Is(err, context.Canceled) || calls != 1 { | |
| 157 | 新增: t.Fatal("canceled lookup continued to fallback", calls, err) | |
| 158 | 新增: } | |
| 159 | 新增:} | |
| 160 | 新增: | |
| 161 | 新增:func TestLocationProvidersLiveIntegration(t *testing.T) { | |
| 162 | 新增: path := os.Getenv("CAGE_TEST_CONFIG") | |
| 163 | 新增: if path == "" { | |
| 164 | 新增: t.Skip("explicit proxy profile required") | |
| 165 | 新增: } | |
| 166 | 新增: cfg, err := cage.Load(path) | |
| 167 | 新增: if err != nil { | |
| 168 | 新增: t.Fatal(err) | |
| 169 | 新增: } | |
| 170 | 新增: if core := os.Getenv("CAGE_TEST_CORE"); core != "" { | |
| 171 | 新增: cfg = isolatedLocationProxy(t, path, core, cfg) | |
| 172 | 新增: } | |
| 173 | 新增: egress, err := cage.NewEgress(cfg) | |
| 174 | 新增: if err != nil { | |
| 175 | 新增: t.Fatal(err) | |
| 176 | 新增: } | |
| 177 | 新增: transport := &http.Transport{Proxy: nil, DialContext: egress.DialContext} | |
| 178 | 新增: defer transport.CloseIdleConnections() | |
| 179 | 新增: client := &http.Client{Transport: transport, Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }} | |
| 180 | 新增: t.Run("measured exit", func(t *testing.T) { | |
| 181 | 新增: loc, err := probeLocation(context.Background(), cfg) | |
| 182 | 新增: if err != nil || loc.IP == "" || loc.Timezone == "" { | |
| 183 | 新增: t.Fatal("measured-exit location lookup failed", err) | |
| 184 | 新增: } | |
| 185 | 新增: }) | |
| 186 | 新增: for _, policy := range []cage.ExitPolicy{ | |
| 187 | 新增: {Mode: "static", Scope: "country"}, | |
| 188 | 新增: {Mode: "dynamic", Scope: "any"}, | |
| 189 | 新增: } { | |
| 190 | 新增: t.Run("manual settings "+policy.Mode, func(t *testing.T) { | |
| 191 | 新增: manual := cfg | |
| 192 | 新增: manual.ExitPolicy = policy | |
| 193 | 新增: manual.Timezone, manual.Locale, manual.BrowserLanguage = "Asia/Shanghai", "zh_CN.UTF-8", "zh-CN" | |
| 194 | 新增: loc, err := probeEnvironmentLocation(context.Background(), manual, Preferences{}) | |
| 195 | 新增: if err != nil || loc.IP == "" || loc.Timezone != "" || loc.CountryCode != "" { | |
| 196 | 新增: t.Fatal("manual settings required geolocation or lost measured exit", err) | |
| 197 | 新增: } | |
| 198 | 新增: if manual.Timezone != "Asia/Shanghai" || manual.Locale != "zh_CN.UTF-8" || manual.BrowserLanguage != "zh-CN" { | |
| 199 | 新增: t.Fatal("manual settings changed during probe") | |
| 200 | 新增: } | |
| 201 | 新增: }) | |
| 202 | 新增: } | |
| 203 | 新增: t.Run("manual settings retain country verification", func(t *testing.T) { | |
| 204 | 新增: restricted := cfg | |
| 205 | 新增: restricted.ExitPolicy = cage.ExitPolicy{Mode: "dynamic", Scope: "country", CountryCode: "US"} | |
| 206 | 新增: loc, err := probeEnvironmentLocation(context.Background(), restricted, Preferences{}) | |
| 207 | 新增: if err != nil || loc.CountryCode == "" || loc.Timezone == "" { | |
| 208 | 新增: t.Fatal("manual settings skipped required country lookup", err) | |
| 209 | 新增: } | |
| 210 | 新增: }) | |
| 211 | 新增: t.Run("manual settings persist through validated save", func(t *testing.T) { | |
| 212 | 新增: s := testServer(t) | |
| 213 | 新增: store, err := managedproxy.Load(filepath.Dir(path)) | |
| 214 | 新增: if err != nil { | |
| 215 | 新增: t.Fatal("cannot load test source") | |
| 216 | 新增: } | |
| 217 | 新增: endpoint, _ := url.Parse(cfg.ProxyURL) | |
| 218 | 新增: store.Port, _ = strconv.Atoi(endpoint.Port()) | |
| 219 | 新增: store.Auth, _ = endpoint.User.Password() | |
| 220 | 新增: if err := store.Save(s.profile); err != nil { | |
| 221 | 新增: t.Fatal("cannot save isolated proxy source") | |
| 222 | 新增: } | |
| 223 | 新增: before := cfg | |
| 224 | 新增: before.ExitPolicy = cage.ExitPolicy{Mode: "dynamic", Scope: "any"} | |
| 225 | 新增: if err := writePrivate(s.configPath, before); err != nil { | |
| 226 | 新增: t.Fatal(err) | |
| 227 | 新增: } | |
| 228 | 新增: if err := before.RequireManagedProxy(s.profile); err != nil { | |
| 229 | 新增: t.Fatal("test proxy source is not applied") | |
| 230 | 新增: } | |
| 231 | 新增: after := before | |
| 232 | 新增: after.Timezone, after.Locale, after.BrowserLanguage = "Asia/Tokyo", "ja_JP.UTF-8", "ja-JP" | |
| 233 | 新增: preferences := Preferences{Keyboard: "mac"} | |
| 234 | 新增: if err := s.apply(savedProfile{Config: after, Preferences: preferences}, true); err != nil { | |
| 235 | 新增: t.Fatal("validated manual settings save failed", err) | |
| 236 | 新增: } | |
| 237 | 新增: saved, err := cage.Load(s.configPath) | |
| 238 | 新增: if err != nil || saved.Timezone != after.Timezone || saved.Locale != after.Locale || saved.BrowserLanguage != after.BrowserLanguage || saved.ExitPolicy != before.ExitPolicy { | |
| 239 | 新增: t.Fatal("manual settings were not persisted or exit rule changed") | |
| 240 | 新增: } | |
| 241 | 新增: if s.preferences.AutoTimezone || s.preferences.AutoLanguage { | |
| 242 | 新增: t.Fatal("manual mode was not applied") | |
| 243 | 新增: } | |
| 244 | 新增: }) | |
| 245 | 新增: for _, provider := range []struct { | |
| 246 | 新增: name, url string | |
| 247 | 新增: primary bool | |
| 248 | 新增: }{ | |
| 249 | 新增: {"primary", "https://ipwho.is/8.8.8.8?fields=success,ip,country,country_code,region,region_code,city,timezone.id", true}, | |
| 250 | 新增: {"backup", "https://api.ip.sb/geoip/8.8.8.8", false}, | |
| 251 | 新增: } { | |
| 252 | 新增: t.Run(provider.name, func(t *testing.T) { | |
| 253 | 新增: if _, err := queryLocation(context.Background(), client, provider.url, provider.primary, net.ParseIP("8.8.8.8")); err != nil { | |
| 254 | 新增: t.Fatal(err) | |
| 255 | 新增: } | |
| 256 | 新增: }) | |
| 257 | 新增: } | |
| 258 | 新增: t.Run("forced primary failure", func(t *testing.T) { | |
| 259 | 新增: fallbackClient := *client | |
| 260 | 新增: fallbackClient.Transport = browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 261 | 新增: if r.URL.Host == "ipwho.is" { | |
| 262 | 新增: return nil, errors.New("simulated primary outage") | |
| 263 | 新增: } | |
| 264 | 新增: return transport.RoundTrip(r) | |
| 265 | 新增: }) | |
| 266 | 新增: if _, err := lookupLocation(context.Background(), &fallbackClient, net.ParseIP("8.8.8.8")); err != nil { | |
| 267 | 新增: t.Fatal("real backup through selected proxy failed", err) | |
| 268 | 新增: } | |
| 269 | 新增: }) | |
| 270 | 新增:} | |
| 271 | 新增: | |
| 272 | 新增:// Run the generated config with a fresh port, credentials and directory. The | |
| 273 | 新增:// daily core and its node selection are never stopped or reconfigured. | |
| 274 | 新增:func isolatedLocationProxy(t *testing.T, configPath, core string, cfg cage.Config) cage.Config { | |
| 275 | 新增: t.Helper() | |
| 276 | 新增: store, err := managedproxy.Load(filepath.Dir(configPath)) | |
| 277 | 新增: if err != nil { | |
| 278 | 新增: t.Fatal("cannot load test proxy source") | |
| 279 | 新增: } | |
| 280 | 新增: if node, ok := store.Find(store.Selected); ok { | |
| 281 | 新增: server, _ := node.Config["server"].(string) | |
| 282 | 新增: t.Logf("Selected test node requires domain bootstrap: %t", net.ParseIP(server) == nil) | |
| 283 | 新增: } | |
| 284 | 新增: listener, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 285 | 新增: if err != nil { | |
| 286 | 新增: t.Fatal(err) | |
| 287 | 新增: } | |
| 288 | 新增: store.Port = listener.Addr().(*net.TCPAddr).Port | |
| 289 | 新增: _ = listener.Close() | |
| 290 | 新增: store.Auth = managedproxy.Token() | |
| 291 | 新增: profile := t.TempDir() | |
| 292 | 新增: wire, err := store.Runtime(profile) | |
| 293 | 新增: if err != nil { | |
| 294 | 新增: t.Fatal("cannot generate isolated core config", err) | |
| 295 | 新增: } | |
| 296 | 新增: name, err := managedproxy.PhysicalInterface(context.Background()) | |
| 297 | 新增: if err != nil { | |
| 298 | 新增: t.Fatal(err) | |
| 299 | 新增: } | |
| 300 | 新增: wire, err = managedproxy.BindInterface(wire, name) | |
| 301 | 新增: if err != nil { | |
| 302 | 新增: t.Fatal(err) | |
| 303 | 新增: } | |
| 304 | 新增: socketDir := filepath.Dir(managedproxy.Socket(profile)) | |
| 305 | 新增: if err := os.MkdirAll(socketDir, 0700); err != nil { | |
| 306 | 新增: t.Fatal(err) | |
| 307 | 新增: } | |
| 308 | 新增: t.Cleanup(func() { _ = os.RemoveAll(socketDir) }) | |
| 309 | 新增: file := filepath.Join(managedproxy.Dir(profile), "config.yaml") | |
| 310 | 新增: if err := managedproxy.Write(file, wire); err != nil { | |
| 311 | 新增: t.Fatal(err) | |
| 312 | 新增: } | |
| 313 | 新增: log, err := os.OpenFile(filepath.Join(profile, "core.log"), os.O_CREATE|os.O_WRONLY, 0600) | |
| 314 | 新增: if err != nil { | |
| 315 | 新增: t.Fatal(err) | |
| 316 | 新增: } | |
| 317 | 新增: t.Cleanup(func() { _ = log.Close() }) | |
| 318 | 新增: validate := exec.Command(core, "-t", "-d", managedproxy.Dir(profile), "-f", file) | |
| 319 | 新增: validate.Stdout, validate.Stderr = log, log | |
| 320 | 新增: if err := validate.Run(); err != nil { | |
| 321 | 新增: t.Fatal("bundled core rejected generated config") | |
| 322 | 新增: } | |
| 323 | 新增: cmd := exec.Command(core, "-d", managedproxy.Dir(profile), "-f", file) | |
| 324 | 新增: cmd.Stdout, cmd.Stderr = log, log | |
| 325 | 新增: if err := cmd.Start(); err != nil { | |
| 326 | 新增: t.Fatal("cannot start isolated core") | |
| 327 | 新增: } | |
| 328 | 新增: done := make(chan error, 1) | |
| 329 | 新增: go func() { done <- cmd.Wait() }() | |
| 330 | 新增: t.Cleanup(func() { _ = cmd.Process.Kill(); <-done }) | |
| 331 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 332 | 新增: defer cancel() | |
| 333 | 新增: for { | |
| 334 | 新增: if managedproxy.Running(ctx, profile, store) { | |
| 335 | 新增: cfg.ProxyURL = store.Endpoint() | |
| 336 | 新增: return cfg | |
| 337 | 新增: } | |
| 338 | 新增: select { | |
| 339 | 新增: case <-ctx.Done(): | |
| 340 | 新增: t.Fatal("isolated proxy did not become ready") | |
| 341 | 新增: case <-time.After(50 * time.Millisecond): | |
| 342 | 新增: } | |
| 343 | 新增: } | |
| 344 | 新增:} | |
| @@ -0,0 +1,221 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/subtle" | |
| 6 | 新增: "encoding/base64" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "io" | |
| 10 | 新增: "net" | |
| 11 | 新增: "net/http" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "sync" | |
| 15 | 新增: "time" | |
| 16 | 新增: | |
| 17 | 新增: "al.essio.dev/pkg/shellescape" | |
| 18 | 新增: | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 20 | 新增: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 21 | 新增:) | |
| 22 | 新增: | |
| 23 | 新增:// Only distribution/tool origins are reachable through this temporary channel. | |
| 24 | 新增:// Guest business traffic continues through EgressGate without any grant here. | |
| 25 | 新增:var maintenanceOrigins = map[string]bool{ | |
| 26 | 新增: "deb.debian.org": true, "security.debian.org": true, | |
| 27 | 新增: "github.com": true, "objects.githubusercontent.com": true, "release-assets.githubusercontent.com": true, | |
| 28 | 新增: "registry.npmjs.org": true, "downloads.claude.ai": true, "deb.nodesource.com": true, | |
| 29 | 新增:} | |
| 30 | 新增: | |
| 31 | 新增:type maintenanceProxy struct { | |
| 32 | 新增: token string | |
| 33 | 新增: ctx context.Context | |
| 34 | 新增: dial func(context.Context, string, string) (net.Conn, error) | |
| 35 | 新增: transport *http.Transport | |
| 36 | 新增: mu sync.Mutex | |
| 37 | 新增: connections map[net.Conn]bool | |
| 38 | 新增: closed bool | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:func maintenanceDestination(address string, connect bool) bool { | |
| 42 | 新增: host, port, err := net.SplitHostPort(address) | |
| 43 | 新增: if err != nil { | |
| 44 | 新增: return false | |
| 45 | 新增: } | |
| 46 | 新增: if connect && port != "443" { | |
| 47 | 新增: return false | |
| 48 | 新增: } | |
| 49 | 新增: if !connect && port != "80" { | |
| 50 | 新增: return false | |
| 51 | 新增: } | |
| 52 | 新增: return maintenanceOrigins[strings.ToLower(host)] | |
| 53 | 新增:} | |
| 54 | 新增:func (p *maintenanceProxy) track(conn net.Conn) bool { | |
| 55 | 新增: p.mu.Lock() | |
| 56 | 新增: defer p.mu.Unlock() | |
| 57 | 新增: if p.closed { | |
| 58 | 新增: conn.Close() | |
| 59 | 新增: return false | |
| 60 | 新增: } | |
| 61 | 新增: p.connections[conn] = true | |
| 62 | 新增: return true | |
| 63 | 新增:} | |
| 64 | 新增:func (p *maintenanceProxy) close() { | |
| 65 | 新增: p.mu.Lock() | |
| 66 | 新增: defer p.mu.Unlock() | |
| 67 | 新增: p.closed = true | |
| 68 | 新增: for conn := range p.connections { | |
| 69 | 新增: conn.Close() | |
| 70 | 新增: } | |
| 71 | 新增: p.transport.CloseIdleConnections() | |
| 72 | 新增:} | |
| 73 | 新增:func (p *maintenanceProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
| 74 | 新增: expected := "Basic " + base64.StdEncoding.EncodeToString([]byte("cage-install:"+p.token)) | |
| 75 | 新增: if subtle.ConstantTimeCompare([]byte(r.Header.Get("Proxy-Authorization")), []byte(expected)) != 1 { | |
| 76 | 新增: w.Header().Set("Proxy-Authenticate", `Basic realm="Cage maintenance"`) | |
| 77 | 新增: http.Error(w, "Maintenance authentication required", 407) | |
| 78 | 新增: return | |
| 79 | 新增: } | |
| 80 | 新增: if r.Method == http.MethodConnect { | |
| 81 | 新增: if !maintenanceDestination(r.Host, true) { | |
| 82 | 新增: http.Error(w, "Not a Cage software source", 403) | |
| 83 | 新增: return | |
| 84 | 新增: } | |
| 85 | 新增: remote, err := p.dial(p.ctx, "tcp", r.Host) | |
| 86 | 新增: if err != nil { | |
| 87 | 新增: http.Error(w, "Software source proxy unavailable", 502) | |
| 88 | 新增: return | |
| 89 | 新增: } | |
| 90 | 新增: if !p.track(remote) { | |
| 91 | 新增: return | |
| 92 | 新增: } | |
| 93 | 新增: defer func() { remote.Close(); p.mu.Lock(); delete(p.connections, remote); p.mu.Unlock() }() | |
| 94 | 新增: hijacker, ok := w.(http.Hijacker) | |
| 95 | 新增: if !ok { | |
| 96 | 新增: http.Error(w, "Tunnel unavailable", 500) | |
| 97 | 新增: return | |
| 98 | 新增: } | |
| 99 | 新增: local, buffer, err := hijacker.Hijack() | |
| 100 | 新增: if err != nil { | |
| 101 | 新增: return | |
| 102 | 新增: } | |
| 103 | 新增: if !p.track(local) { | |
| 104 | 新增: return | |
| 105 | 新增: } | |
| 106 | 新增: defer func() { local.Close(); p.mu.Lock(); delete(p.connections, local); p.mu.Unlock() }() | |
| 107 | 新增: if _, err = buffer.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil { | |
| 108 | 新增: return | |
| 109 | 新增: } | |
| 110 | 新增: if err = buffer.Flush(); err != nil { | |
| 111 | 新增: return | |
| 112 | 新增: } | |
| 113 | 新增: done := make(chan struct{}) | |
| 114 | 新增: go func() { _, _ = io.Copy(remote, buffer); remote.Close(); close(done) }() | |
| 115 | 新增: _, _ = io.Copy(local, remote) | |
| 116 | 新增: local.Close() | |
| 117 | 新增: remote.Close() | |
| 118 | 新增: <-done | |
| 119 | 新增: return | |
| 120 | 新增: } | |
| 121 | 新增: if r.Method != http.MethodGet && r.Method != http.MethodHead { | |
| 122 | 新增: http.Error(w, "Read-only software source", 405) | |
| 123 | 新增: return | |
| 124 | 新增: } | |
| 125 | 新增: address := r.URL.Host | |
| 126 | 新增: if r.URL.Port() == "" { | |
| 127 | 新增: address = net.JoinHostPort(r.URL.Hostname(), "80") | |
| 128 | 新增: } | |
| 129 | 新增: if r.URL.Scheme != "http" || r.URL.User != nil || !maintenanceDestination(address, false) { | |
| 130 | 新增: http.Error(w, "Not a Cage software source", 403) | |
| 131 | 新增: return | |
| 132 | 新增: } | |
| 133 | 新增: request := r.Clone(p.ctx) | |
| 134 | 新增: request.RequestURI = "" | |
| 135 | 新增: request.Header = r.Header.Clone() | |
| 136 | 新增: request.Header.Del("Proxy-Authorization") | |
| 137 | 新增: request.Header.Del("Proxy-Connection") | |
| 138 | 新增: response, err := p.transport.RoundTrip(request) | |
| 139 | 新增: if err != nil { | |
| 140 | 新增: http.Error(w, "Software source proxy unavailable", 502) | |
| 141 | 新增: return | |
| 142 | 新增: } | |
| 143 | 新增: defer response.Body.Close() | |
| 144 | 新增: for name, values := range response.Header { | |
| 145 | 新增: if strings.EqualFold(name, "Connection") { | |
| 146 | 新增: continue | |
| 147 | 新增: } | |
| 148 | 新增: for _, value := range values { | |
| 149 | 新增: w.Header().Add(name, value) | |
| 150 | 新增: } | |
| 151 | 新增: } | |
| 152 | 新增: w.WriteHeader(response.StatusCode) | |
| 153 | 新增: _, _ = io.Copy(w, response.Body) | |
| 154 | 新增:} | |
| 155 | 新增: | |
| 156 | 新增:const maintenancePort = 18961 | |
| 157 | 新增: | |
| 158 | 新增:// The script and one-use local credential travel on SSH stdin, never argv. | |
| 159 | 新增:// APT_CONFIG is passed explicitly through sudo by the owned install scripts. | |
| 160 | 新增:func maintenanceScript(script, token string) string { | |
| 161 | 新增: return fmt.Sprintf(`set -euo pipefail | |
| 162 | 新增:umask 077 | |
| 163 | 新增:cage_maintenance_dir=$(mktemp -d) | |
| 164 | 新增:trap 'rm -rf "$cage_maintenance_dir"' EXIT | |
| 165 | 新增:export CAGE_INSTALL_PROXY='http://cage-install:%[email protected]:%d' | |
| 166 | 新增:export CAGE_APT_CONFIG="$cage_maintenance_dir/apt.conf" | |
| 167 | 新增:printf 'Acquire::http::Proxy "%%s";\nAcquire::https::Proxy "%%s";\n' "$CAGE_INSTALL_PROXY" "$CAGE_INSTALL_PROXY" > "$CAGE_APT_CONFIG" | |
| 168 | 新增:unset ALL_PROXY all_proxy NO_PROXY no_proxy FTP_PROXY ftp_proxy | |
| 169 | 新增:export http_proxy="$CAGE_INSTALL_PROXY" https_proxy="$CAGE_INSTALL_PROXY" HTTP_PROXY="$CAGE_INSTALL_PROXY" HTTPS_PROXY="$CAGE_INSTALL_PROXY" | |
| 170 | 新增:( | |
| 171 | 新增:umask 022 | |
| 172 | 新增:%s | |
| 173 | 新增:) | |
| 174 | 新增:`, token, maintenancePort, script) | |
| 175 | 新增:} | |
| 176 | 新增: | |
| 177 | 新增:func RunMaintenanceScript(ctx context.Context, configPath, script string, stdout, stderr io.Writer) error { | |
| 178 | 新增: cfg, err := cage.Load(configPath) | |
| 179 | 新增: if err != nil { | |
| 180 | 新增: return err | |
| 181 | 新增: } | |
| 182 | 新增: profile := filepath.Dir(configPath) | |
| 183 | 新增: if err = cfg.RequireManagedProxy(profile); err != nil { | |
| 184 | 新增: return err | |
| 185 | 新增: } | |
| 186 | 新增: egress, err := cage.NewEgress(cfg) | |
| 187 | 新增: if err != nil { | |
| 188 | 新增: return err | |
| 189 | 新增: } | |
| 190 | 新增: ctx, cancel := context.WithTimeout(ctx, 30*time.Minute) | |
| 191 | 新增: defer cancel() | |
| 192 | 新增: listener, err := net.Listen("tcp", "127.0.0.1:0") | |
| 193 | 新增: if err != nil { | |
| 194 | 新增: return err | |
| 195 | 新增: } | |
| 196 | 新增: proxy := &maintenanceProxy{token: randomToken(), ctx: ctx, dial: egress.DialContext, connections: make(map[net.Conn]bool)} | |
| 197 | 新增: proxy.transport = &http.Transport{Proxy: nil, DialContext: egress.DialContext, DisableKeepAlives: true} | |
| 198 | 新增: server := &http.Server{Handler: proxy, ReadHeaderTimeout: 10 * time.Second} | |
| 199 | 新增: go func() { _ = server.Serve(listener) }() | |
| 200 | 新增: defer server.Close() | |
| 201 | 新增: defer proxy.close() | |
| 202 | 新增: stop := context.AfterFunc(ctx, func() { _ = server.Close(); proxy.close() }) | |
| 203 | 新增: defer stop() | |
| 204 | 新增: s := &Server{profile: profile} | |
| 205 | 新增: forward := fmt.Sprintf("127.0.0.1:%d:%s", maintenancePort, listener.Addr().String()) | |
| 206 | 新增: command := "sudo systemd-run --quiet --pipe --wait --collect --unit=cage-maintenance-operation --property=User=cage --property=RuntimeMaxSec=1800 --property=KillMode=control-group --setenv=HOME=/home/cage --working-directory=" + shellescape.Quote(guestPath(s.environmentDir())) + " /bin/bash -se" | |
| 207 | 新增: cmd := s.sshCommandWithForwarding(ctx, "-o", "ExitOnForwardFailure=yes", "-R", forward, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", command) | |
| 208 | 新增: cmd.Stdin = strings.NewReader(maintenanceScript(script, proxy.token)) | |
| 209 | 新增: cmd.Stdout = stdout | |
| 210 | 新增: cmd.Stderr = stderr | |
| 211 | 新增: if err = cmd.Run(); err != nil { | |
| 212 | 新增: if ctx.Err() != nil { | |
| 213 | 新增: cleanup, finish := context.WithTimeout(context.Background(), 5*time.Second) | |
| 214 | 新增: defer finish() | |
| 215 | 新增: _, _ = s.guest(cleanup, "sudo systemctl stop cage-maintenance-operation.service") | |
| 216 | 新增: return ctx.Err() | |
| 217 | 新增: } | |
| 218 | 新增: return errors.New("依赖安装通道未完成,请检查已选代理与操作详情;业务网络状态保持不变") | |
| 219 | 新增: } | |
| 220 | 新增: return nil | |
| 221 | 新增:} | |
| @@ -0,0 +1,153 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bufio" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/base64" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "io" | |
| 10 | 新增: "net" | |
| 11 | 新增: "net/http" | |
| 12 | 新增: "net/http/httptest" | |
| 13 | 新增: "net/url" | |
| 14 | 新增: "os" | |
| 15 | 新增: "os/exec" | |
| 16 | 新增: "runtime" | |
| 17 | 新增: "strings" | |
| 18 | 新增: "sync/atomic" | |
| 19 | 新增: "testing" | |
| 20 | 新增: "time" | |
| 21 | 新增: | |
| 22 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 23 | 新增:) | |
| 24 | 新增: | |
| 25 | 新增:func TestMaintenanceRequiresAuthenticationAndSoftwareSource(t *testing.T) { | |
| 26 | 新增: var calls atomic.Int32 | |
| 27 | 新增: upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 28 | 新增: calls.Add(1) | |
| 29 | 新增: if r.Header.Get("Proxy-Authorization") != "" { | |
| 30 | 新增: t.Error("installer credential reached software origin") | |
| 31 | 新增: } | |
| 32 | 新增: _, _ = io.WriteString(w, "package bytes") | |
| 33 | 新增: })) | |
| 34 | 新增: defer upstream.Close() | |
| 35 | 新增: destination, _ := url.Parse(upstream.URL) | |
| 36 | 新增: dial := func(ctx context.Context, network, address string) (net.Conn, error) { | |
| 37 | 新增: if address != "deb.debian.org:80" && address != "deb.nodesource.com:80" { | |
| 38 | 新增: return nil, errors.New("unexpected destination") | |
| 39 | 新增: } | |
| 40 | 新增: return (&net.Dialer{}).DialContext(ctx, network, destination.Host) | |
| 41 | 新增: } | |
| 42 | 新增: proxy := &maintenanceProxy{token: "fixture-only", ctx: context.Background(), dial: dial, connections: map[net.Conn]bool{}, transport: &http.Transport{Proxy: nil, DialContext: dial}} | |
| 43 | 新增: server := httptest.NewServer(proxy) | |
| 44 | 新增: defer server.Close() | |
| 45 | 新增: defer proxy.close() | |
| 46 | 新增: gate, err := cage.NewEgressGate(cage.DefaultConfig()) | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: t.Fatal(err) | |
| 49 | 新增: } | |
| 50 | 新增: for _, test := range []struct { | |
| 51 | 新增: target, method string | |
| 52 | 新增: auth bool | |
| 53 | 新增: status int | |
| 54 | 新增: }{ | |
| 55 | 新增: {"http://deb.debian.org/debian/pool/file.deb", "GET", false, 407}, | |
| 56 | 新增: {"http://example.com/private", "GET", true, 403}, | |
| 57 | 新增: {"http://127.0.0.1/private", "GET", true, 403}, | |
| 58 | 新增: {"http://deb.debian.org:8080/private", "GET", true, 403}, | |
| 59 | 新增: {"http://deb.debian.org/debian/pool/file.deb", "POST", true, 405}, | |
| 60 | 新增: {"http://deb.debian.org/debian/pool/file.deb", "GET", true, 200}, | |
| 61 | 新增: {"http://deb.nodesource.com/node_24.x/dists/nodistro/InRelease", "GET", true, 200}, | |
| 62 | 新增: } { | |
| 63 | 新增: proxyURL, _ := url.Parse(server.URL) | |
| 64 | 新增: if test.auth { | |
| 65 | 新增: proxyURL.User = url.UserPassword("cage-install", "fixture-only") | |
| 66 | 新增: } | |
| 67 | 新增: transport := &http.Transport{Proxy: http.ProxyURL(proxyURL)} | |
| 68 | 新增: client := &http.Client{Transport: transport, Timeout: time.Second} | |
| 69 | 新增: request, _ := http.NewRequest(test.method, test.target, nil) | |
| 70 | 新增: response, err := client.Do(request) | |
| 71 | 新增: if err != nil { | |
| 72 | 新增: t.Fatal(err) | |
| 73 | 新增: } | |
| 74 | 新增: body, _ := io.ReadAll(response.Body) | |
| 75 | 新增: response.Body.Close() | |
| 76 | 新增: transport.CloseIdleConnections() | |
| 77 | 新增: if response.StatusCode != test.status { | |
| 78 | 新增: t.Fatalf("%s: %d", test.target, response.StatusCode) | |
| 79 | 新增: } | |
| 80 | 新增: if test.status == 200 && string(body) != "package bytes" { | |
| 81 | 新增: t.Fatal("download bytes changed") | |
| 82 | 新增: } | |
| 83 | 新增: } | |
| 84 | 新增: if calls.Load() != 2 { | |
| 85 | 新增: t.Fatal("rejected request reached origin") | |
| 86 | 新增: } | |
| 87 | 新增: if gate.Status().Mode != cage.GateClosed { | |
| 88 | 新增: t.Fatal("maintenance changed business gate") | |
| 89 | 新增: } | |
| 90 | 新增:} | |
| 91 | 新增: | |
| 92 | 新增:func TestMaintenanceClosesTLSConnectionsAndRefusesBusinessHosts(t *testing.T) { | |
| 93 | 新增: proxy := &maintenanceProxy{token: "fixture", ctx: context.Background(), connections: map[net.Conn]bool{}, transport: &http.Transport{}} | |
| 94 | 新增: proxy.dial = func(context.Context, string, string) (net.Conn, error) { | |
| 95 | 新增: a, b := net.Pipe() | |
| 96 | 新增: go func() { defer b.Close(); _, _ = io.Copy(b, b) }() | |
| 97 | 新增: return a, nil | |
| 98 | 新增: } | |
| 99 | 新增: server := httptest.NewServer(proxy) | |
| 100 | 新增: defer server.Close() | |
| 101 | 新增: defer proxy.close() | |
| 102 | 新增: address, _ := url.Parse(server.URL) | |
| 103 | 新增: connection, err := net.Dial("tcp", address.Host) | |
| 104 | 新增: if err != nil { | |
| 105 | 新增: t.Fatal(err) | |
| 106 | 新增: } | |
| 107 | 新增: defer connection.Close() | |
| 108 | 新增: _ = connection.SetDeadline(time.Now().Add(3 * time.Second)) | |
| 109 | 新增: auth := base64.StdEncoding.EncodeToString([]byte("cage-install:fixture")) | |
| 110 | 新增: _, _ = fmt.Fprintf(connection, "CONNECT deb.debian.org:443 HTTP/1.1\r\nHost: deb.debian.org:443\r\nProxy-Authorization: Basic %s\r\n\r\n", auth) | |
| 111 | 新增: reader := bufio.NewReader(connection) | |
| 112 | 新增: response, err := http.ReadResponse(reader, nil) | |
| 113 | 新增: if err != nil || response.StatusCode != 200 { | |
| 114 | 新增: t.Fatal(response, err) | |
| 115 | 新增: } | |
| 116 | 新增: _, _ = connection.Write([]byte("abc")) | |
| 117 | 新增: bytes := make([]byte, 3) | |
| 118 | 新增: if _, err = io.ReadFull(reader, bytes); err != nil || string(bytes) != "abc" { | |
| 119 | 新增: t.Fatal("tunnel failed", err) | |
| 120 | 新增: } | |
| 121 | 新增: proxy.close() | |
| 122 | 新增: if _, err = reader.ReadByte(); err == nil { | |
| 123 | 新增: t.Fatal("maintenance left a live tunnel") | |
| 124 | 新增: } | |
| 125 | 新增: for _, address := range []string{"claude.ai:443", "api.anthropic.com:443", "deb.debian.org:22", "127.0.0.1:443", "github.com.evil.test:443"} { | |
| 126 | 新增: if maintenanceDestination(address, true) { | |
| 127 | 新增: t.Fatal("business or non-HTTPS destination accepted", address) | |
| 128 | 新增: } | |
| 129 | 新增: } | |
| 130 | 新增:} | |
| 131 | 新增: | |
| 132 | 新增:func TestMaintenanceScriptUsesPrivateTemporaryConfiguration(t *testing.T) { | |
| 133 | 新增: if runtime.GOOS == "windows" { | |
| 134 | 新增: t.Skip("the installer Bash script runs in the Linux guest, not the Windows host") | |
| 135 | 新增: } | |
| 136 | 新增: shell, err := exec.LookPath("bash") | |
| 137 | 新增: if err != nil { | |
| 138 | 新增: t.Skip("bash not available") | |
| 139 | 新增: } | |
| 140 | 新增: command := exec.Command(shell, "-se") | |
| 141 | 新增: command.Stdin = strings.NewReader(maintenanceScript(`test -s "$CAGE_APT_CONFIG" | |
| 142 | 新增:test "$http_proxy" = "$CAGE_INSTALL_PROXY" | |
| 143 | 新增:test "$(umask)" = 0022 | |
| 144 | 新增:printf '%s' "$CAGE_APT_CONFIG" | |
| 145 | 新增:`, "fixture-token")) | |
| 146 | 新增: output, err := command.Output() | |
| 147 | 新增: if err != nil { | |
| 148 | 新增: t.Fatal(err) | |
| 149 | 新增: } | |
| 150 | 新增: if _, err = os.Stat(string(output)); !os.IsNotExist(err) { | |
| 151 | 新增: t.Fatal("maintenance credential was retained") | |
| 152 | 新增: } | |
| 153 | 新增:} | |
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | package workbench |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 4 | 5 | "net/http/httptest" |
| 5 | 6 | "os" |
| 6 | 7 | "path/filepath" |
| @@ -47,8 +48,7 @@ func TestReloadedManualPauseSurvivesAutomaticSubscriptionRefresh(t *testing.T) { | ||
| 47 | 48 | t.Fatal("service reload discarded manual pause") |
| 48 | 49 | } |
| 49 | 50 | if record == "saved" { |
| 50 | 删除: stat, err := os.Stat(intentPath) | |
| 51 | 删除: if err != nil || stat.Mode().Perm() != 0600 { | |
| 51 | 新增: if err := host.CheckPrivateFile(intentPath); err != nil { | |
| 52 | 52 | t.Fatal("intent is not private", err) |
| 53 | 53 | } |
| 54 | 54 | if reloaded.safety.pauseVersion != original.safety.pauseVersion { |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import "testing" | |
| 4 | 新增: | |
| 5 | 新增:func TestLinuxUsesNativeKeyboardByDefault(t *testing.T) { | |
| 6 | 新增: if got := defaultKeyboard(); got != "native" { | |
| 7 | 新增: t.Fatalf("Linux desktop must use native Ctrl shortcuts, got %q", got) | |
| 8 | 新增: } | |
| 9 | 新增:} | |
| @@ -0,0 +1,57 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 6 | 新增: "testing" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestWindowsGuestPathsMatchVMSharePaths(t *testing.T) { | |
| 10 | 新增: previous := paths.Windows | |
| 11 | 新增: paths.Windows = func() bool { return true } | |
| 12 | 新增: t.Cleanup(func() { paths.Windows = previous }) | |
| 13 | 新增: for _, path := range []string{`C:\Users\甲 用户\project`, "C:/Users/甲 用户/project"} { | |
| 14 | 新增: if got := guestPath(path); got != "/c/Users/甲 用户/project" { | |
| 15 | 新增: t.Fatalf("guestPath(%q) = %q", path, got) | |
| 16 | 新增: } | |
| 17 | 新增: } | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:func TestBoundaryProbeUsesGuestFilePaths(t *testing.T) { | |
| 21 | 新增: previous := paths.Windows | |
| 22 | 新增: t.Cleanup(func() { paths.Windows = previous }) | |
| 23 | 新增: for _, tc := range []struct { | |
| 24 | 新增: name string | |
| 25 | 新增: windows bool | |
| 26 | 新增: private, shared, wantPrivate, wantShared string | |
| 27 | 新增: }{ | |
| 28 | 新增: {"Windows backslashes and another drive", true, `C:\Users\甲 用户\Cage\private-probe`, `D:\项目 工作区\shared-probe`, "/c/Users/甲 用户/Cage/private-probe", "/d/项目 工作区/shared-probe"}, | |
| 29 | 新增: {"Windows forward slashes", true, "C:/Users/user/Cage/private-probe", "C:/Users/user/work/shared-probe", "/c/Users/user/Cage/private-probe", "/c/Users/user/work/shared-probe"}, | |
| 30 | 新增: {"POSIX", false, "/Users/user/Cage/private-probe", "/Users/user/work/shared-probe", "/Users/user/Cage/private-probe", "/Users/user/work/shared-probe"}, | |
| 31 | 新增: } { | |
| 32 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 33 | 新增: paths.Windows = func() bool { return tc.windows } | |
| 34 | 新增: wire, err := json.Marshal(boundaryProbeInput(17777, "check-id", tc.private, tc.shared, "challenge")) | |
| 35 | 新增: if err != nil { | |
| 36 | 新增: t.Fatal(err) | |
| 37 | 新增: } | |
| 38 | 新增: var input struct { | |
| 39 | 新增: Stage string `json:"stage"` | |
| 40 | 新增: Port int `json:"control_port"` | |
| 41 | 新增: Nonce string `json:"nonce"` | |
| 42 | 新增: Private string `json:"private_file"` | |
| 43 | 新增: Shared string `json:"shared_file"` | |
| 44 | 新增: Challenge string `json:"challenge"` | |
| 45 | 新增: } | |
| 46 | 新增: if err := json.Unmarshal(wire, &input); err != nil { | |
| 47 | 新增: t.Fatal(err) | |
| 48 | 新增: } | |
| 49 | 新增: if input.Private != tc.wantPrivate || input.Shared != tc.wantShared { | |
| 50 | 新增: t.Fatalf("Linux file probe received host paths: private=%q shared=%q", input.Private, input.Shared) | |
| 51 | 新增: } | |
| 52 | 新增: if input.Stage != "boundary" || input.Port != 17777 || input.Nonce != "check-id" || input.Challenge != "challenge" { | |
| 53 | 新增: t.Fatalf("path conversion changed the probe identity: %+v", input) | |
| 54 | 新增: } | |
| 55 | 新增: }) | |
| 56 | 新增: } | |
| 57 | 新增:} | |
| @@ -0,0 +1,35 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package workbench | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "os" | |
| 7 | 新增: "os/exec" | |
| 8 | 新增: "runtime" | |
| 9 | 新增: "syscall" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func lockController(f *os.File) error { | |
| 13 | 新增: return syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) | |
| 14 | 新增:} | |
| 15 | 新增:func unlockController(f *os.File) error { return syscall.Flock(int(f.Fd()), syscall.LOCK_UN) } | |
| 16 | 新增:func processExists(pid int) bool { | |
| 17 | 新增: if pid <= 0 { | |
| 18 | 新增: return false | |
| 19 | 新增: } | |
| 20 | 新增: err := syscall.Kill(pid, 0) | |
| 21 | 新增: return err == nil || err != syscall.ESRCH | |
| 22 | 新增:} | |
| 23 | 新增:func terminateLegacy(pid int) error { return syscall.Kill(pid, syscall.SIGTERM) } | |
| 24 | 新增:func detachController(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} } | |
| 25 | 新增:func hideCommand(cmd *exec.Cmd) {} | |
| 26 | 新增:func sshExecutable() string { return "/usr/bin/ssh" } | |
| 27 | 新增:func sshEnvironment() []string { | |
| 28 | 新增: return []string{"PATH=/usr/bin:/bin:/usr/sbin:/sbin", "LANG=C", "LC_ALL=C", "TERM=xterm-256color"} | |
| 29 | 新增:} | |
| 30 | 新增:func defaultKeyboard() string { | |
| 31 | 新增: if runtime.GOOS == "darwin" { | |
| 32 | 新增: return "mac" | |
| 33 | 新增: } | |
| 34 | 新增: return "native" | |
| 35 | 新增:} | |
| @@ -0,0 +1,56 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "os" | |
| 6 | 新增: "os/exec" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "syscall" | |
| 9 | 新增: | |
| 10 | 新增: "golang.org/x/sys/windows" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func lockController(f *os.File) error { | |
| 14 | 新增: return windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, new(windows.Overlapped)) | |
| 15 | 新增:} | |
| 16 | 新增:func unlockController(f *os.File) error { | |
| 17 | 新增: return windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, new(windows.Overlapped)) | |
| 18 | 新增:} | |
| 19 | 新增:func processExists(pid int) bool { | |
| 20 | 新增: if pid <= 0 { | |
| 21 | 新增: return false | |
| 22 | 新增: } | |
| 23 | 新增: h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid)) | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: return !errors.Is(err, windows.ERROR_INVALID_PARAMETER) | |
| 26 | 新增: } | |
| 27 | 新增: defer windows.CloseHandle(h) | |
| 28 | 新增: var code uint32 | |
| 29 | 新增: return windows.GetExitCodeProcess(h, &code) != nil || code == 259 | |
| 30 | 新增:} | |
| 31 | 新增:func terminateLegacy(pid int) error { | |
| 32 | 新增: return errors.New("Windows 不支持接管未验证的旧版后台") | |
| 33 | 新增:} | |
| 34 | 新增:func detachController(cmd *exec.Cmd) { | |
| 35 | 新增: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NEW_PROCESS_GROUP | windows.DETACHED_PROCESS} | |
| 36 | 新增:} | |
| 37 | 新增:func hideCommand(cmd *exec.Cmd) { | |
| 38 | 新增: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW} | |
| 39 | 新增:} | |
| 40 | 新增:func sshExecutable() string { | |
| 41 | 新增: exe, _ := os.Executable() | |
| 42 | 新增: bundled := filepath.Join(filepath.Dir(exe), "runtime", "openssh", "ssh.exe") | |
| 43 | 新增: if st, err := os.Stat(bundled); err == nil && st.Mode().IsRegular() { | |
| 44 | 新增: return bundled | |
| 45 | 新增: } | |
| 46 | 新增: // Source tests and standalone developer builds can use Windows' official | |
| 47 | 新增: // optional client. Do not search a project-controlled PATH for ssh.exe. | |
| 48 | 新增: return filepath.Join(os.Getenv("SystemRoot"), "System32", "OpenSSH", "ssh.exe") | |
| 49 | 新增:} | |
| 50 | 新增:func sshEnvironment() []string { | |
| 51 | 新增: // OpenSSH needs Windows system directories but must not inherit keys, | |
| 52 | 新增: // SSH_AUTH_SOCK, proxy settings or user-supplied SSH configuration. | |
| 53 | 新增: // Win32-OpenSSH requires ProgramData before it initializes stderr. | |
| 54 | 新增: return []string{"SystemRoot=" + os.Getenv("SystemRoot"), "WINDIR=" + os.Getenv("WINDIR"), "ProgramData=" + os.Getenv("ProgramData"), "TEMP=" + os.TempDir(), "TMP=" + os.TempDir(), "PATH=" + filepath.Dir(sshExecutable()), "LANG=C", "LC_ALL=C", "TERM=xterm-256color"} | |
| 55 | 新增:} | |
| 56 | 新增:func defaultKeyboard() string { return "native" } | |
| @@ -45,7 +45,12 @@ func (p *projectShare) close() { | ||
| 45 | 45 | |
| 46 | 46 | // Called under the lifecycle lock. Each SFTP server is rooted in exactly the |
| 47 | 47 | // directory the user opened; switching projects keeps existing mounts alive. |
| 48 | 删除:func (s *Server) ensureProjectShare(path string) error { | |
| 48 | 新增:func (s *Server) ensureProjectShare(path string) (returned error) { | |
| 49 | 新增: defer func() { | |
| 50 | 新增: if returned == nil { | |
| 51 | 新增: s.clearProjectError(path) | |
| 52 | 新增: } | |
| 53 | 新增: }() | |
| 49 | 54 | path, err := validateWorkspace(path, s.profile) |
| 50 | 55 | if err != nil { |
| 51 | 56 | return err |
| @@ -66,7 +71,7 @@ func (s *Server) ensureProjectShare(path string) error { | ||
| 66 | 71 | } |
| 67 | 72 | ctx, cancel := context.WithTimeout(s.operationContext(), 15*time.Second) |
| 68 | 73 | defer cancel() |
| 69 | 删除: quoted := shellescape.Quote(path) | |
| 74 | 新增: quoted := shellescape.Quote(guestPath(path)) | |
| 70 | 75 | // Stale FUSE mounts can remain after a control-service restart. Only reconnect |
| 71 | 76 | // this explicitly authorized path, without changing other projects' mounts. |
| 72 | 77 | if _, err = s.guest(ctx, "if mountpoint -q "+quoted+"; then fusermount3 -uz "+quoted+"; fi; sudo mkdir -p "+quoted+" && sudo chown \"$(id -u):$(id -g)\" "+quoted); err != nil { |
| @@ -85,7 +90,7 @@ func (s *Server) ensureProjectShare(path string) error { | ||
| 85 | 90 | if err = probe.Close(); err != nil { |
| 86 | 91 | return err |
| 87 | 92 | } |
| 88 | 删除: script := "exec sshfs " + shellescape.Quote(":"+path) + " " + quoted + " -o slave,allow_other,cache=no,nodev,nosuid" | |
| 93 | 新增: script := "exec sshfs " + shellescape.Quote(":"+filepath.ToSlash(path)) + " " + quoted + " -o slave,allow_other,cache=no,nodev,nosuid" | |
| 89 | 94 | cmd := s.sshCommand(context.Background(), "-T", "lima-"+vmname.Name(s.environmentDir()), "--", script) |
| 90 | 95 | output, err := cmd.StdoutPipe() |
| 91 | 96 | if err != nil { |
| @@ -107,7 +112,7 @@ func (s *Server) ensureProjectShare(path string) error { | ||
| 107 | 112 | close(share.done) |
| 108 | 113 | }() |
| 109 | 114 | for { |
| 110 | 删除: if _, err = s.guest(ctx, "mountpoint -q "+quoted+" && test \"$(cat "+shellescape.Quote(probe.Name())+")\" = "+shellescape.Quote(challenge)); err == nil { | |
| 115 | 新增: if _, err = s.guest(ctx, "mountpoint -q "+quoted+" && test \"$(cat "+shellescape.Quote(guestPath(probe.Name()))+")\" = "+shellescape.Quote(challenge)); err == nil { | |
| 111 | 116 | break |
| 112 | 117 | } |
| 113 | 118 | select { |
| @@ -133,6 +138,22 @@ type sharedProjects struct { | ||
| 133 | 138 | Paths []string `json:"paths"` |
| 134 | 139 | } |
| 135 | 140 | |
| 141 | 新增:type projectShareError struct { | |
| 142 | 新增: Path string `json:"path"` | |
| 143 | 新增: Message string `json:"message"` | |
| 144 | 新增:} | |
| 145 | 新增: | |
| 146 | 新增:func (s *Server) clearProjectError(path string) { | |
| 147 | 新增: s.mu.Lock() | |
| 148 | 新增: defer s.mu.Unlock() | |
| 149 | 新增: for i, failure := range s.projectErrors { | |
| 150 | 新增: if failure.Path == path { | |
| 151 | 新增: s.projectErrors = append(s.projectErrors[:i], s.projectErrors[i+1:]...) | |
| 152 | 新增: return | |
| 153 | 新增: } | |
| 154 | 新增: } | |
| 155 | 新增:} | |
| 156 | 新增: | |
| 136 | 157 | // The saved directory grants are the project list. Include the default and |
| 137 | 158 | // current directories for profiles created before projects.json existed. |
| 138 | 159 | func (s *Server) projectPaths() ([]string, error) { |
| @@ -208,19 +229,16 @@ func (s *Server) restoreProjectShares() { | ||
| 208 | 229 | saved.Paths = append(saved.Paths, current) |
| 209 | 230 | } |
| 210 | 231 | } |
| 211 | 删除: var failures []error | |
| 232 | 新增: var failures []projectShareError | |
| 212 | 233 | for _, path := range saved.Paths { |
| 213 | 234 | if err := s.ensureProjectShare(path); err != nil { |
| 214 | 删除: failures = append(failures, err) | |
| 235 | 新增: failures = append(failures, projectShareError{Path: path, Message: err.Error()}) | |
| 215 | 236 | } else if err := s.rememberSharedProject(path); err != nil { |
| 216 | 删除: failures = append(failures, err) | |
| 237 | 新增: failures = append(failures, projectShareError{Path: path, Message: "项目已连接,但未能保存项目记录:" + err.Error()}) | |
| 217 | 238 | } |
| 218 | 239 | } |
| 219 | 240 | s.mu.Lock() |
| 220 | 删除: s.projectError = "" | |
| 221 | 删除: if len(failures) > 0 { | |
| 222 | 删除: s.projectError = "部分项目文件夹未能恢复连接,请重新打开对应项目。环境和浏览器可继续使用。" | |
| 223 | 删除: } | |
| 241 | 新增: s.projectErrors = failures | |
| 224 | 242 | s.mu.Unlock() |
| 225 | 243 | } |
| 226 | 244 | func (s *Server) closeProjectShares() { |
| @@ -146,6 +146,70 @@ func TestProjectListComesFromSavedDirectories(t *testing.T) { | ||
| 146 | 146 | } |
| 147 | 147 | } |
| 148 | 148 | |
| 149 | 新增:func TestRestoreProjectSharesReportsTheFailedDirectoryAndReason(t *testing.T) { | |
| 150 | 新增: s := testServer(t) | |
| 151 | 新增: connected, _ := filepath.EvalSymlinks(t.TempDir()) | |
| 152 | 新增: executable, err := os.Executable() | |
| 153 | 新增: if err != nil { | |
| 154 | 新增: t.Fatal(err) | |
| 155 | 新增: } | |
| 156 | 新增: executable, err = filepath.EvalSymlinks(executable) | |
| 157 | 新增: if err != nil { | |
| 158 | 新增: t.Fatal(err) | |
| 159 | 新增: } | |
| 160 | 新增: blocked := filepath.Dir(executable) | |
| 161 | 新增: s.preferences.Workspace = connected | |
| 162 | 新增: s.projectShares = map[string]*projectShare{connected: {done: make(chan struct{})}} | |
| 163 | 新增: for _, path := range []string{blocked, connected} { | |
| 164 | 新增: if err := s.rememberSharedProject(path); err != nil { | |
| 165 | 新增: t.Fatal(err) | |
| 166 | 新增: } | |
| 167 | 新增: } | |
| 168 | 新增: s.restoreProjectShares() | |
| 169 | 新增: w := request(s, "GET", "/api/status", "", "", true) | |
| 170 | 新增: var status struct { | |
| 171 | 新增: ProjectError string `json:"project_error"` | |
| 172 | 新增: ProjectErrors []projectShareError `json:"project_errors"` | |
| 173 | 新增: } | |
| 174 | 新增: if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &status) != nil { | |
| 175 | 新增: t.Fatalf("cannot read project status: %s", w.Body.String()) | |
| 176 | 新增: } | |
| 177 | 新增: if status.ProjectError == "" || len(status.ProjectErrors) != 1 || status.ProjectErrors[0].Path != blocked || !strings.Contains(status.ProjectErrors[0].Message, "正在运行的工作台程序") { | |
| 178 | 新增: t.Fatalf("failure did not identify the blocked project and executable protection: %+v", status) | |
| 179 | 新增: } | |
| 180 | 新增: if s.projectShares[connected] == nil { | |
| 181 | 新增: t.Fatal("one failed directory disconnected a healthy project") | |
| 182 | 新增: } | |
| 183 | 新增:} | |
| 184 | 新增: | |
| 185 | 新增:func TestProjectReconnectClearsOnlyItsOwnWarning(t *testing.T) { | |
| 186 | 新增: s := testServer(t) | |
| 187 | 新增: connected, _ := filepath.EvalSymlinks(t.TempDir()) | |
| 188 | 新增: parent, _ := filepath.EvalSymlinks(t.TempDir()) | |
| 189 | 新增: missing := filepath.Join(parent, "missing") | |
| 190 | 新增: s.projectErrors = []projectShareError{ | |
| 191 | 新增: {Path: connected, Message: "previous connection failed"}, | |
| 192 | 新增: {Path: missing, Message: "directory unavailable"}, | |
| 193 | 新增: } | |
| 194 | 新增: s.projectShares = map[string]*projectShare{connected: {done: make(chan struct{})}} | |
| 195 | 新增: if err := s.ensureProjectShare(missing); err == nil || len(s.projectErrors) != 2 { | |
| 196 | 新增: t.Fatal("a failed reconnect cleared a warning") | |
| 197 | 新增: } | |
| 198 | 新增: if err := s.ensureProjectShare(connected); err != nil { | |
| 199 | 新增: t.Fatal(err) | |
| 200 | 新增: } | |
| 201 | 新增: if len(s.projectErrors) != 1 || s.projectErrors[0].Path != missing { | |
| 202 | 新增: t.Fatalf("reconnect did not preserve the other directory's warning: %+v", s.projectErrors) | |
| 203 | 新增: } | |
| 204 | 新增: if err := os.Mkdir(missing, 0700); err != nil { | |
| 205 | 新增: t.Fatal(err) | |
| 206 | 新增: } | |
| 207 | 新增: s.projectShares[missing] = &projectShare{done: make(chan struct{})} | |
| 208 | 新增: if err := s.ensureProjectShare(missing); err != nil || len(s.projectErrors) != 0 { | |
| 209 | 新增: t.Fatalf("successful reconnect left a stale warning: %v, %+v", err, s.projectErrors) | |
| 210 | 新增: } | |
| 211 | 新增:} | |
| 212 | 新增: | |
| 149 | 213 | func TestProjectActionsUseExplicitDirectoryWithoutSwitchingProject(t *testing.T) { |
| 150 | 214 | s := testServer(t) |
| 151 | 215 | a, _ := filepath.EvalSymlinks(t.TempDir()) |
| @@ -169,7 +233,7 @@ func TestProjectActionsUseExplicitDirectoryWithoutSwitchingProject(t *testing.T) | ||
| 169 | 233 | } |
| 170 | 234 | session := s.terminals[terminal.ID] |
| 171 | 235 | defer session.close() |
| 172 | 删除: if script := session.cmd.Args[len(session.cmd.Args)-1]; !strings.HasPrefix(script, "cd "+shellescape.Quote(a)+" &&") { | |
| 236 | 新增: if script := session.cmd.Args[len(session.cmd.Args)-1]; !strings.HasPrefix(script, "cd "+shellescape.Quote(guestPath(a))+" &&") { | |
| 173 | 237 | t.Fatalf("terminal command opened a different directory: %s", script) |
| 174 | 238 | } |
| 175 | 239 | var editorWorkspace string |
| @@ -185,7 +249,7 @@ func TestProjectActionsUseExplicitDirectoryWithoutSwitchingProject(t *testing.T) | ||
| 185 | 249 | })} |
| 186 | 250 | for _, action := range []string{"editor", "editor-restart"} { |
| 187 | 251 | w = request(s, "POST", "/api/browser/"+action, s.origin, string(body), true) |
| 188 | 删除: if w.Code != 200 || editorWorkspace != a || s.workspace() != b { | |
| 252 | 新增: if w.Code != 200 || editorWorkspace != guestPath(a) || s.workspace() != b { | |
| 189 | 253 | t.Fatalf("%s changed the selected project or ignored its directory: %s", action, w.Body.String()) |
| 190 | 254 | } |
| 191 | 255 | } |
| @@ -87,7 +87,7 @@ func (s *Server) proxyStatus(w http.ResponseWriter, r *http.Request) { | ||
| 87 | 87 | _ = managedproxy.API(ctx, s.profile, "GET", "/version", nil, &version) |
| 88 | 88 | } |
| 89 | 89 | _, coreErr := managedproxy.CorePath() |
| 90 | 删除: jsonReply(w, map[string]any{"sources": sources, "selected": p.Selected, "port": p.Port, "running": running, "active": active, "state": state, "state_label": label, "network_open": state == "ready", "core_available": coreErr == nil, "version": version.Version, "revision": p.Revision, "bootstrap_dns": "https://1.1.1.1/dns-query", "udp_blocked": true, "ipv6_blocked": true}) | |
| 90 | 新增: jsonReply(w, map[string]any{"sources": sources, "selected": p.Selected, "port": p.Port, "running": running, "active": active, "state": state, "state_label": label, "network_open": state == "ready", "core_available": coreErr == nil, "version": version.Version, "revision": p.Revision, "bootstrap_dns": strings.Join(managedproxy.BootstrapDNSURLs(), "、"), "udp_blocked": true, "ipv6_blocked": true}) | |
| 91 | 91 | } |
| 92 | 92 | func (s *Server) proxyMutation(w http.ResponseWriter, r *http.Request) { |
| 93 | 93 | var input proxyInput |
| @@ -432,7 +432,7 @@ func (s *Server) proxyLogs(w http.ResponseWriter, r *http.Request) { | ||
| 432 | 432 | } |
| 433 | 433 | // Whitelisted lifecycle messages avoid publishing upstream raw log lines, |
| 434 | 434 | // which can contain subscription secrets, credentials and host paths. |
| 435 | 删除: lines := []string{"客机公网 UDP、IPv6、ICMP:阻断", "业务 DNS:经选定节点转发", "代理基础设施 DNS:https://1.1.1.1/dns-query(主机网络)"} | |
| 435 | 新增: lines := []string{"客机公网 UDP、IPv6、ICMP:阻断", "业务 DNS:经选定节点转发", "代理基础设施 DNS:" + strings.Join(managedproxy.BootstrapDNSURLs(), "、") + "(主机网络,并行查询)"} | |
| 436 | 436 | if managedproxy.Running(r.Context(), s.profile, p) { |
| 437 | 437 | lines = append(lines, "内置核心运行中;已读回当前节点选择") |
| 438 | 438 | } else { |
| @@ -12,7 +12,6 @@ import ( | ||
| 12 | 12 | "os" |
| 13 | 13 | "os/exec" |
| 14 | 14 | "path/filepath" |
| 15 | 删除: "syscall" | |
| 16 | 15 | "time" |
| 17 | 16 | |
| 18 | 17 | "github.com/sylvinus/agent-vm/internal/cage" |
| @@ -31,12 +30,26 @@ type guestCredentials struct { | ||
| 31 | 30 | func (s *Server) workspace() string { s.mu.Lock(); defer s.mu.Unlock(); return s.preferences.Workspace } |
| 32 | 31 | func (s *Server) environmentDir() string { return environmentWorkspace(s.profile) } |
| 33 | 32 | func (s *Server) sshCommand(ctx context.Context, args ...string) *exec.Cmd { |
| 33 | 新增: return s.sshCommandOptions(ctx, false, args...) | |
| 34 | 新增:} | |
| 35 | 新增:func (s *Server) sshCommandWithForwarding(ctx context.Context, args ...string) *exec.Cmd { | |
| 36 | 新增: return s.sshCommandOptions(ctx, true, args...) | |
| 37 | 新增:} | |
| 38 | 新增:func (s *Server) sshCommandOptions(ctx context.Context, maintenance bool, args ...string) *exec.Cmd { | |
| 34 | 39 | name := vmname.Name(s.environmentDir()) |
| 35 | 40 | cfg := filepath.Join(s.profile, "state", "lima", name, "ssh.config") |
| 36 | 41 | base := []string{"-q", "-e", "none", "-F", cfg, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "PermitLocalCommand=no", "-o", "PasswordAuthentication=no", "-o", "KbdInteractiveAuthentication=no", "-o", "ProxyCommand=none", "-o", "ProxyJump=none", "-o", "ConnectTimeout=3", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=2", "-o", "ForwardAgent=no", "-o", "IdentityAgent=none", "-o", "ForwardX11=no", "-o", "ClearAllForwardings=yes", "-o", "ControlPath=none"} |
| 42 | 新增: if maintenance { | |
| 43 | 新增: for index, value := range base { | |
| 44 | 新增: if value == "ClearAllForwardings=yes" { | |
| 45 | 新增: base[index] = "ClearAllForwardings=no" | |
| 46 | 新增: } | |
| 47 | 新增: } | |
| 48 | 新增: } | |
| 37 | 49 | base = append(base, args...) |
| 38 | 删除: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", base...) | |
| 39 | 删除: cmd.Env = []string{"PATH=/usr/bin:/bin:/usr/sbin:/sbin", "LANG=C", "LC_ALL=C", "TERM=xterm-256color"} | |
| 50 | 新增: cmd := exec.CommandContext(ctx, sshExecutable(), base...) | |
| 51 | 新增: cmd.Env = sshEnvironment() | |
| 52 | 新增: hideCommand(cmd) | |
| 40 | 53 | return cmd |
| 41 | 54 | } |
| 42 | 55 | func (s *Server) guest(ctx context.Context, script string) ([]byte, error) { |
| @@ -148,6 +161,7 @@ func (s *Server) runCage(args ...string) error { | ||
| 148 | 161 | ctx, cancel := context.WithTimeout(s.operationContext(), 30*time.Minute) |
| 149 | 162 | defer cancel() |
| 150 | 163 | cmd := exec.CommandContext(ctx, s.exe, args...) |
| 164 | 新增: hideCommand(cmd) | |
| 151 | 165 | cmd.Dir = s.environmentDir() |
| 152 | 166 | if cmd.Dir == "" { |
| 153 | 167 | cmd.Dir = s.profile |
| @@ -233,7 +247,7 @@ func (s *Server) startEnvironment(syncTimezone bool) error { | ||
| 233 | 247 | auto := preferences.AutoTimezone || preferences.AutoLanguage |
| 234 | 248 | s.mu.Unlock() |
| 235 | 249 | s.setMessage("正在验证代理出口…") |
| 236 | 删除: loc, probeErr := probeLocation(s.operationContext(), cfg) | |
| 250 | 新增: loc, probeErr := probeEnvironmentLocation(s.operationContext(), cfg, preferences) | |
| 237 | 251 | if s.operationContext().Err() != nil { |
| 238 | 252 | return s.operationContext().Err() |
| 239 | 253 | } |
| @@ -373,7 +387,7 @@ func (s *Server) apply(v savedProfile, validate bool) error { | ||
| 373 | 387 | changed := old != v.Config || oldPrefs.AutoTimezone != v.Preferences.AutoTimezone || oldPrefs.AutoLanguage != v.Preferences.AutoLanguage |
| 374 | 388 | if changed && validate && old.RequireManagedProxy(s.profile) == nil { |
| 375 | 389 | s.setMessage("正在验证新出口,现有环境保持运行…") |
| 376 | 删除: loc, e := probeLocation(s.operationContext(), v.Config) | |
| 390 | 新增: loc, e := probeEnvironmentLocation(s.operationContext(), v.Config, v.Preferences) | |
| 377 | 391 | if e != nil { |
| 378 | 392 | if v.Preferences.AutoTimezone || v.Preferences.AutoLanguage || loc.IP == "" { |
| 379 | 393 | return e |
| @@ -391,6 +405,9 @@ func (s *Server) apply(v savedProfile, validate bool) error { | ||
| 391 | 405 | v.Config.ExitPolicy = v.Config.ExitPolicy.BindMissing(loc.exitLocation()) |
| 392 | 406 | observed := loc.exitLocation() |
| 393 | 407 | if result, message := v.Config.ExitPolicy.Evaluate(loc.IP, &observed); result != cage.CheckPassed { |
| 408 | 新增: if result == cage.CheckUnknown && e != nil && !v.Preferences.AutoTimezone && !v.Preferences.AutoLanguage { | |
| 409 | 新增: return errors.New("时区和语言已选择手动设置,但出口规则仍要求确认国家或城市。请重试位置检测,或在“IP 变化规则”中明确选择静态 IP 或不限制地区;原配置保持不变") | |
| 410 | 新增: } | |
| 394 | 411 | return errors.New(message) |
| 395 | 412 | } |
| 396 | 413 | } |
| @@ -456,7 +473,7 @@ func (s *Server) guestAPI(ctx context.Context, token, method, path string, body | ||
| 456 | 473 | } |
| 457 | 474 | client := s.guestClient |
| 458 | 475 | s.mu.Unlock() |
| 459 | 删除: if path == "/audit" { | |
| 476 | 新增: if path == "/audit" || path == "/paste-image" { | |
| 460 | 477 | auditClient := *client |
| 461 | 478 | auditClient.Timeout = 20 * time.Second |
| 462 | 479 | client = &auditClient |
| @@ -490,7 +507,7 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) { | ||
| 490 | 507 | if r.Method == "GET" { |
| 491 | 508 | action = "tabs" |
| 492 | 509 | } |
| 493 | 删除: allowed := map[string]bool{"tabs": true, "new": true, "activate": true, "close": true, "navigate": true, "back": true, "forward": true, "reload": true, "editor": true, "editor-restart": true, "download-retry": true, "resize": true, "insert-text": true} | |
| 510 | 新增: allowed := map[string]bool{"tabs": true, "new": true, "activate": true, "close": true, "navigate": true, "back": true, "forward": true, "reload": true, "editor": true, "editor-restart": true, "download-retry": true, "upload-finish": true, "upload-cancel": true, "resize": true, "insert-text": true} | |
| 494 | 511 | if !allowed[action] { |
| 495 | 512 | http.NotFound(w, r) |
| 496 | 513 | return |
| @@ -540,6 +557,7 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) { | ||
| 540 | 557 | requestError(w, err) |
| 541 | 558 | return |
| 542 | 559 | } |
| 560 | 新增: input.Workspace = guestPath(workspace) | |
| 543 | 561 | } |
| 544 | 562 | body, _ = json.Marshal(input) |
| 545 | 563 | } |
| @@ -548,6 +566,13 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) { | ||
| 548 | 566 | http.Error(w, err.Error(), 502) |
| 549 | 567 | return |
| 550 | 568 | } |
| 569 | 新增: if action == "tabs" { | |
| 570 | 新增: b, err = s.browserStateForHost(b) | |
| 571 | 新增: if err != nil { | |
| 572 | 新增: http.Error(w, err.Error(), 502) | |
| 573 | 新增: return | |
| 574 | 新增: } | |
| 575 | 新增: } | |
| 551 | 576 | w.Header().Set("Content-Type", "application/json") |
| 552 | 577 | w.Write(b) |
| 553 | 578 | } |
| @@ -596,19 +621,7 @@ func (s *Server) browserEvents(w http.ResponseWriter, r *http.Request) { | ||
| 596 | 621 | w.Header().Set("Connection", "keep-alive") |
| 597 | 622 | flusher := w.(http.Flusher) |
| 598 | 623 | flusher.Flush() |
| 599 | 删除: buffer := make([]byte, 16<<10) | |
| 600 | 删除: for { | |
| 601 | 删除: n, e := response.Body.Read(buffer) | |
| 602 | 删除: if n > 0 { | |
| 603 | 删除: if _, err = w.Write(buffer[:n]); err != nil { | |
| 604 | 删除: return | |
| 605 | 删除: } | |
| 606 | 删除: flusher.Flush() | |
| 607 | 删除: } | |
| 608 | 删除: if e != nil { | |
| 609 | 删除: return | |
| 610 | 删除: } | |
| 611 | 删除: } | |
| 624 | 新增: _ = s.writeBrowserEvents(w, response.Body) | |
| 612 | 625 | } |
| 613 | 626 | |
| 614 | 627 | func vmAlive(profile, workspace string) bool { |
| @@ -625,11 +638,6 @@ func vmAlive(profile, workspace string) bool { | ||
| 625 | 638 | if json.Unmarshal(b, &record) != nil || record.PID < 1 { |
| 626 | 639 | return false |
| 627 | 640 | } |
| 628 | 删除: p, e := os.FindProcess(record.PID) | |
| 629 | 删除: if e != nil { | |
| 630 | 删除: return false | |
| 631 | 删除: } | |
| 632 | 删除: defer p.Release() | |
| 633 | 删除: return p.Signal(syscall.Signal(0)) == nil | |
| 641 | 新增: return processExists(record.PID) | |
| 634 | 642 | } |
| 635 | 643 | func (s *Server) vmRunning() bool { return vmAlive(s.profile, s.environmentDir()) } |
| @@ -17,6 +17,7 @@ import ( | ||
| 17 | 17 | |
| 18 | 18 | "al.essio.dev/pkg/shellescape" |
| 19 | 19 | "github.com/sylvinus/agent-vm/internal/cage" |
| 20 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 20 | 21 | "github.com/sylvinus/agent-vm/internal/vmname" |
| 21 | 22 | "go.yaml.in/yaml/v3" |
| 22 | 23 | ) |
| @@ -143,6 +144,13 @@ func (s *Server) safetyExport(w http.ResponseWriter, r *http.Request) { | ||
| 143 | 144 | jsonReply(w, map[string]any{"policy": report.Policy, "created_at": report.CreatedAt, "checks": report.Checks, "scope": "采样与运行时策略检查;不代表平台账号资格或完整虚拟化审计"}) |
| 144 | 145 | } |
| 145 | 146 | |
| 147 | 新增:// The probe runs in Linux, while its files are created on the host. Use the | |
| 148 | 新增:// same guest path mapping as the VM's mounts for both sides of the boundary. | |
| 149 | 新增:func boundaryProbeInput(port int, nonce, privateFile, sharedFile, challenge string) map[string]any { | |
| 150 | 新增: return map[string]any{"stage": "boundary", "control_port": port, "nonce": nonce, | |
| 151 | 新增: "private_file": guestPath(privateFile), "shared_file": guestPath(sharedFile), "challenge": challenge} | |
| 152 | 新增:} | |
| 153 | 新增: | |
| 146 | 154 | func (s *Server) guestObservation(ctx context.Context, input map[string]any) (guestObservation, error) { |
| 147 | 155 | var observation guestObservation |
| 148 | 156 | data, err := json.Marshal(input) |
| @@ -205,7 +213,7 @@ func (s *Server) inspectVMLayout() (bool, bool) { | ||
| 205 | 213 | shares := len(spec.Mounts) == 1 && spec.MountType == "reverse-sshfs" |
| 206 | 214 | if shares { |
| 207 | 215 | m := spec.Mounts[0] |
| 208 | 删除: shares = m.Location == workspace && m.MountPoint == workspace && m.Writable && m.SSHFS.Driver == "builtin" | |
| 216 | 新增: shares = paths.Equal(paths.Host(m.Location), paths.Host(workspace)) && m.MountPoint == guestPath(workspace) && m.Writable && m.SSHFS.Driver == "builtin" | |
| 209 | 217 | gitProtected := false |
| 210 | 218 | for _, name := range m.SSHFS.ReadonlyNames { |
| 211 | 219 | if name == ".git" { |
| @@ -394,7 +402,7 @@ func (s *Server) runSafetyCheck() (returned error) { | ||
| 394 | 402 | control, _ := url.Parse(s.origin) |
| 395 | 403 | port, _ := strconv.Atoi(control.Port()) |
| 396 | 404 | s.setMessage("正在验证离线约束、共享文件与系统配置…") |
| 397 | 删除: boundary, boundaryErr := s.guestObservation(ctx, map[string]any{"stage": "boundary", "control_port": port, "nonce": report.ID, "private_file": private.Name(), "shared_file": shared.Name(), "challenge": challenge}) | |
| 405 | 新增: boundary, boundaryErr := s.guestObservation(ctx, boundaryProbeInput(port, report.ID, private.Name(), shared.Name(), challenge)) | |
| 398 | 406 | after, err := client.Status(ctx) |
| 399 | 407 | if err != nil { |
| 400 | 408 | return err |
| @@ -532,9 +540,13 @@ func (s *Server) runSafetyCheck() (returned error) { | ||
| 532 | 540 | |
| 533 | 541 | // Monitoring renews a short host-owned lease without replaying the disruptive |
| 534 | 542 | // failure drill. Lost supervision eventually closes existing guest connections. |
| 543 | 新增:func (s *Server) networkMonitorBlockedLocked() bool { | |
| 544 | 新增: return s.networkPaused || (s.job.Running && s.job.Kind != "environment-tools" && s.job.Kind != "claude-desktop-install") | |
| 545 | 新增:} | |
| 546 | 新增: | |
| 535 | 547 | func (s *Server) monitorSafety() { |
| 536 | 548 | s.mu.Lock() |
| 537 | 删除: ready, busy, last := s.ready, (s.job.Running && s.job.Kind != "environment-tools") || s.networkPaused, s.safety.VerifiedAt | |
| 549 | 新增: ready, busy, last := s.ready, s.networkMonitorBlockedLocked(), s.safety.VerifiedAt | |
| 538 | 550 | s.mu.Unlock() |
| 539 | 551 | if !ready || busy || time.Since(last) < 30*time.Second { |
| 540 | 552 | return |
| @@ -606,7 +618,7 @@ func (s *Server) finishSafetyMonitor(ctx context.Context, client *cage.GateClien | ||
| 606 | 618 | s.safetyOp.Lock() |
| 607 | 619 | defer s.safetyOp.Unlock() |
| 608 | 620 | s.mu.Lock() |
| 609 | 删除: busy := (s.job.Running && s.job.Kind != "environment-tools") || s.networkPaused | |
| 621 | 新增: busy := s.networkMonitorBlockedLocked() | |
| 610 | 622 | s.mu.Unlock() |
| 611 | 623 | if busy { |
| 612 | 624 | return |
| @@ -10,6 +10,7 @@ import ( | ||
| 10 | 10 | "errors" |
| 11 | 11 | "fmt" |
| 12 | 12 | "github.com/sylvinus/agent-vm/internal/cage" |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 13 | 14 | "github.com/sylvinus/agent-vm/internal/vmname" |
| 14 | 15 | "io" |
| 15 | 16 | "io/fs" |
| @@ -20,7 +21,6 @@ import ( | ||
| 20 | 21 | "path/filepath" |
| 21 | 22 | "strings" |
| 22 | 23 | "sync" |
| 23 | 删除: "syscall" | |
| 24 | 24 | "time" |
| 25 | 25 | ) |
| 26 | 26 | |
| @@ -37,6 +37,7 @@ type controlFile struct { | ||
| 37 | 37 | } |
| 38 | 38 | type Job struct { |
| 39 | 39 | pauseVersion uint64 |
| 40 | 新增: lockAccount bool | |
| 40 | 41 | ID string `json:"id"` |
| 41 | 42 | Kind string `json:"kind"` |
| 42 | 43 | Running bool `json:"running"` |
| @@ -45,6 +46,7 @@ type Job struct { | ||
| 45 | 46 | Log string `json:"log,omitempty"` |
| 46 | 47 | } |
| 47 | 48 | type Server struct { |
| 49 | 新增: account *localAccount | |
| 48 | 50 | identity ControllerIdentity |
| 49 | 51 | guestManifest *cage.GuestManifest |
| 50 | 52 | guestUpdateRequired bool |
| @@ -65,8 +67,9 @@ type Server struct { | ||
| 65 | 67 | networkError string |
| 66 | 68 | credentials guestCredentials |
| 67 | 69 | terminals map[string]*terminalSession |
| 70 | 新增: audioClients int | |
| 68 | 71 | projectShares map[string]*projectShare |
| 69 | 删除: projectError string | |
| 72 | 新增: projectErrors []projectShareError | |
| 70 | 73 | safety safetyState |
| 71 | 74 | locations map[string]Location |
| 72 | 75 | monitorCancel context.CancelFunc |
| @@ -92,7 +95,7 @@ func equalSecret(a, b string) bool { | ||
| 92 | 95 | } |
| 93 | 96 | func Serve(configPath string) error { |
| 94 | 97 | profile := filepath.Dir(configPath) |
| 95 | 删除: if err := os.MkdirAll(profile, 0700); err != nil { | |
| 98 | 新增: if err := host.EnsurePrivateDir(profile); err != nil { | |
| 96 | 99 | return err |
| 97 | 100 | } |
| 98 | 101 | lock, err := os.OpenFile(filepath.Join(profile, "control.lock"), os.O_CREATE|os.O_RDWR, 0600) |
| @@ -100,7 +103,7 @@ func Serve(configPath string) error { | ||
| 100 | 103 | return err |
| 101 | 104 | } |
| 102 | 105 | defer lock.Close() |
| 103 | 删除: if err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { | |
| 106 | 新增: if err = lockController(lock); err != nil { | |
| 104 | 107 | return errors.New("此配置已有工作台服务正在运行") |
| 105 | 108 | } |
| 106 | 109 | exe, err := os.Executable() |
| @@ -119,7 +122,12 @@ func Serve(configPath string) error { | ||
| 119 | 122 | return err |
| 120 | 123 | } |
| 121 | 124 | defer listener.Close() |
| 122 | 删除: s := &Server{profile: profile, configPath: configPath, exe: exe, origin: fmt.Sprintf("http://localhost:%d", port), token: randomToken(), session: randomToken(), preferences: Preferences{Keyboard: "mac"}, terminals: map[string]*terminalSession{}} | |
| 125 | 新增: s := &Server{profile: profile, configPath: configPath, exe: exe, origin: fmt.Sprintf("http://localhost:%d", port), token: randomToken(), session: randomToken(), preferences: Preferences{Keyboard: defaultKeyboard()}, terminals: map[string]*terminalSession{}} | |
| 126 | 新增: s.account, err = loadLocalAccount(profile) | |
| 127 | 新增: if err != nil { | |
| 128 | 新增: return err | |
| 129 | 新增: } | |
| 130 | 新增: defer s.account.lock() | |
| 123 | 131 | s.identity, err = currentController() |
| 124 | 132 | if err != nil { |
| 125 | 133 | return err |
| @@ -134,7 +142,7 @@ func Serve(configPath string) error { | ||
| 134 | 142 | s.networkError = intentErr.Error() |
| 135 | 143 | } |
| 136 | 144 | if s.preferences.Keyboard == "" { |
| 137 | 删除: s.preferences.Keyboard = "mac" | |
| 145 | 新增: s.preferences.Keyboard = defaultKeyboard() | |
| 138 | 146 | } |
| 139 | 147 | if _, e := os.Stat(configPath); os.IsNotExist(e) { |
| 140 | 148 | if e = writePrivate(configPath, defaultConfig()); e != nil { |
| @@ -194,6 +202,8 @@ func (s *Server) handler() http.Handler { | ||
| 194 | 202 | jsonReply(w, map[string]bool{"ok": true}) |
| 195 | 203 | }) |
| 196 | 204 | mux.HandleFunc("GET /api/status", s.status) |
| 205 | 新增: mux.HandleFunc("GET /api/account", s.accountStatus) | |
| 206 | 新增: mux.HandleFunc("POST /api/account/{action}", s.accountAction) | |
| 197 | 207 | mux.HandleFunc("GET /api/settings", s.getSettings) |
| 198 | 208 | mux.HandleFunc("GET /api/environment/versions", s.environmentVersions) |
| 199 | 209 | mux.HandleFunc("POST /api/environment/update", s.updateEnvironment) |
| @@ -221,6 +231,11 @@ func (s *Server) handler() http.Handler { | ||
| 221 | 231 | mux.HandleFunc("GET /api/browser/tabs", s.browser) |
| 222 | 232 | mux.HandleFunc("GET /api/browser/events", s.browserEvents) |
| 223 | 233 | mux.HandleFunc("POST /api/browser/{action}", s.browser) |
| 234 | 新增: mux.HandleFunc("POST /api/input/image", s.imageInput) | |
| 235 | 新增: mux.HandleFunc("POST /api/browser/files/uploads/{id}", s.browserUpload) | |
| 236 | 新增: mux.HandleFunc("GET /api/browser/files/downloads/{id}", s.browserDownload) | |
| 237 | 新增: mux.HandleFunc("GET /api/browser/files/downloads/{id}/{action}", s.browserDownload) | |
| 238 | 新增: mux.HandleFunc("GET /api/browser/files/saved", s.savedBrowserDownloads) | |
| 224 | 239 | mux.HandleFunc("GET /api/vnc-credentials", func(w http.ResponseWriter, r *http.Request) { |
| 225 | 240 | s.mu.Lock() |
| 226 | 241 | defer s.mu.Unlock() |
| @@ -231,7 +246,13 @@ func (s *Server) handler() http.Handler { | ||
| 231 | 246 | jsonReply(w, map[string]string{"password": s.credentials.VNCPassword}) |
| 232 | 247 | }) |
| 233 | 248 | mux.HandleFunc("GET /api/vnc", s.vnc) |
| 249 | 新增: mux.HandleFunc("GET /api/claude-desktop", s.claudeDesktopStatus) | |
| 250 | 新增: mux.HandleFunc("GET /api/claude-desktop/vnc-credentials", s.claudeDesktopCredentials) | |
| 251 | 新增: mux.HandleFunc("GET /api/claude-desktop/vnc", s.claudeDesktopVNC) | |
| 252 | 新增: mux.HandleFunc("POST /api/claude-desktop/resize", s.claudeDesktopResize) | |
| 253 | 新增: mux.HandleFunc("POST /api/claude-desktop/{action}", s.claudeDesktopAction) | |
| 234 | 254 | mux.HandleFunc("GET /api/terminals", s.listTerminals) |
| 255 | 新增: mux.HandleFunc("GET /api/audio", s.audio) | |
| 235 | 256 | mux.HandleFunc("POST /api/terminals", s.newTerminal) |
| 236 | 257 | mux.HandleFunc("DELETE /api/terminals/{id}", s.closeTerminal) |
| 237 | 258 | mux.HandleFunc("GET /api/terminals/{id}/stream", s.terminalStream) |
| @@ -268,6 +289,19 @@ func (s *Server) handler() http.Handler { | ||
| 268 | 289 | http.Error(w, "后台正在更新,请重新打开 Cage。", http.StatusServiceUnavailable) |
| 269 | 290 | return |
| 270 | 291 | } |
| 292 | 新增: accountRoute := r.URL.Path == "/api/account" || strings.HasPrefix(r.URL.Path, "/api/account/") | |
| 293 | 新增: bootstrapRoute := r.URL.Path == "/api/session" || r.URL.Path == "/api/launch" || r.URL.Path == "/api/handoff" | |
| 294 | 新增: if strings.HasPrefix(r.URL.Path, "/api/") && !accountRoute && !bootstrapRoute && !(r.Method == "GET" && r.URL.Path == "/api/appearance") { | |
| 295 | 新增: epoch, unlocked := s.account.access() | |
| 296 | 新增: if !unlocked { | |
| 297 | 新增: http.Error(w, "Cage 已锁定,请先登录", http.StatusLocked) | |
| 298 | 新增: return | |
| 299 | 新增: } | |
| 300 | 新增: ctx, cancel := context.WithCancel(r.Context()) | |
| 301 | 新增: stop := context.AfterFunc(epoch, cancel) | |
| 302 | 新增: defer func() { stop(); cancel() }() | |
| 303 | 新增: r = r.WithContext(ctx) | |
| 304 | 新增: } | |
| 271 | 305 | mux.ServeHTTP(w, r) |
| 272 | 306 | }) |
| 273 | 307 | } |
| @@ -302,6 +336,10 @@ func requestError(w http.ResponseWriter, err error) { | ||
| 302 | 336 | } |
| 303 | 337 | func (s *Server) busy() bool { s.mu.Lock(); defer s.mu.Unlock(); return s.job.Running } |
| 304 | 338 | func (s *Server) launch(w http.ResponseWriter, kind string, fn func() error) { |
| 339 | 新增: lockAccount := kind == "logout" | |
| 340 | 新增: if lockAccount { | |
| 341 | 新增: kind = "stop" | |
| 342 | 新增: } | |
| 305 | 343 | s.mu.Lock() |
| 306 | 344 | if s.closing { |
| 307 | 345 | s.mu.Unlock() |
| @@ -310,6 +348,7 @@ func (s *Server) launch(w http.ResponseWriter, kind string, fn func() error) { | ||
| 310 | 348 | } |
| 311 | 349 | if s.job.Running { |
| 312 | 350 | if kind == "stop" && s.job.Kind == "stop" { |
| 351 | 新增: s.job.lockAccount = s.job.lockAccount || lockAccount | |
| 313 | 352 | job := s.job |
| 314 | 353 | s.mu.Unlock() |
| 315 | 354 | jsonReply(w, job) |
| @@ -334,7 +373,7 @@ func (s *Server) launch(w http.ResponseWriter, kind string, fn func() error) { | ||
| 334 | 373 | } |
| 335 | 374 | ctx, cancel := context.WithCancel(context.Background()) |
| 336 | 375 | s.jobCancel = cancel |
| 337 | 删除: s.job = Job{ID: randomToken()[:12], Kind: kind, Running: true, Message: "正在准备…", pauseVersion: s.safety.pauseVersion} | |
| 376 | 新增: s.job = Job{ID: randomToken()[:12], Kind: kind, Running: true, Message: "正在准备…", pauseVersion: s.safety.pauseVersion, lockAccount: lockAccount} | |
| 338 | 377 | if s.monitorCancel != nil { |
| 339 | 378 | s.monitorCancel() |
| 340 | 379 | } |
| @@ -362,6 +401,9 @@ func (s *Server) launch(w http.ResponseWriter, kind string, fn func() error) { | ||
| 362 | 401 | } |
| 363 | 402 | s.jobCancel = nil |
| 364 | 403 | s.job.Running = false |
| 404 | 新增: if err == nil && s.job.lockAccount { | |
| 405 | 新增: err = s.account.lockAccess(true) | |
| 406 | 新增: } | |
| 365 | 407 | if errors.Is(err, context.Canceled) { |
| 366 | 408 | s.job.Message = "已取消" |
| 367 | 409 | } else if err != nil { |
| @@ -399,7 +441,11 @@ func (s *Server) status(w http.ResponseWriter, r *http.Request) { | ||
| 399 | 441 | s.mu.Lock() |
| 400 | 442 | defer s.mu.Unlock() |
| 401 | 443 | _, e := os.Stat(filepath.Join(s.profile, "previous-profile.json")) |
| 402 | 删除: jsonReply(w, map[string]any{"projects": projects, "ready": s.ready, "vm_running": vmAlive(s.profile, s.environmentDir()), "workspace": s.preferences.Workspace, "environment_workspace": s.preferences.Workspace == s.environmentDir(), "environment_directory": s.environmentDir(), "project_error": s.projectError, "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.job, "location": s.location, "network_error": s.networkError, "can_restore": e == nil, "safety": s.safety, "environment_update_required": s.guestUpdateRequired, "environment_update_error": s.guestUpdateError}) | |
| 444 | 新增: projectError := "" | |
| 445 | 新增: if len(s.projectErrors) > 0 { | |
| 446 | 新增: projectError = "部分项目文件夹尚未连接,环境和浏览器可继续使用。" | |
| 447 | 新增: } | |
| 448 | 新增: jsonReply(w, map[string]any{"projects": projects, "ready": s.ready, "vm_running": vmAlive(s.profile, s.environmentDir()), "workspace": s.preferences.Workspace, "environment_workspace": s.preferences.Workspace == s.environmentDir(), "environment_directory": s.environmentDir(), "project_error": projectError, "project_errors": s.projectErrors, "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.job, "location": s.location, "network_error": s.networkError, "can_restore": e == nil, "safety": s.safety, "environment_update_required": s.guestUpdateRequired, "environment_update_error": s.guestUpdateError}) | |
| 403 | 449 | } |
| 404 | 450 | func (s *Server) getSettings(w http.ResponseWriter, r *http.Request) { |
| 405 | 451 | c, err := loadConfig(s.configPath) |
| @@ -490,6 +536,10 @@ func (s *Server) start(w http.ResponseWriter, r *http.Request) { | ||
| 490 | 536 | }) |
| 491 | 537 | } |
| 492 | 538 | func (s *Server) stop(w http.ResponseWriter, r *http.Request) { |
| 539 | 新增: s.requestStop(w, false) | |
| 540 | 新增:} | |
| 541 | 新增: | |
| 542 | 新增:func (s *Server) requestStop(w http.ResponseWriter, logout bool) { | |
| 493 | 543 | for _, name := range []string{vmname.Name(s.environmentDir()), "base-building"} { |
| 494 | 544 | if owner := cage.InstanceJobID(filepath.Join(s.profile, "state"), name); owner != "" { |
| 495 | 545 | _ = cage.RequestJobStop(s.profile, owner) |
| @@ -505,7 +555,11 @@ func (s *Server) stop(w http.ResponseWriter, r *http.Request) { | ||
| 505 | 555 | _ = cage.RequestJobStop(s.profile, jobID) |
| 506 | 556 | } |
| 507 | 557 | _ = s.pauseNetworkNow("正在停止环境") |
| 508 | 删除: s.launch(w, "stop", s.stopEnvironment) | |
| 558 | 新增: kind := "stop" | |
| 559 | 新增: if logout { | |
| 560 | 新增: kind = "logout" | |
| 561 | 新增: } | |
| 562 | 新增: s.launch(w, kind, s.stopEnvironment) | |
| 509 | 563 | } |
| 510 | 564 | |
| 511 | 565 | // Short-lived contexts for guest controls are separate from VM lifecycle jobs. |
| @@ -3,6 +3,7 @@ package workbench | ||
| 3 | 3 | import ( |
| 4 | 4 | "context" |
| 5 | 5 | "encoding/json" |
| 6 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 6 | 7 | "net/http" |
| 7 | 8 | "net/http/httptest" |
| 8 | 9 | "os" |
| @@ -35,7 +36,12 @@ func testServer(t *testing.T) *Server { | ||
| 35 | 36 | if e := writePrivate(path, c); e != nil { |
| 36 | 37 | t.Fatal(e) |
| 37 | 38 | } |
| 38 | 删除: return &Server{profile: profile, configPath: path, origin: "http://localhost:17777", token: strings.Repeat("a", 64), session: strings.Repeat("b", 64), preferences: Preferences{Keyboard: "mac"}, terminals: map[string]*terminalSession{}} | |
| 39 | 新增: // Non-account tests exercise an already unlocked workbench. Account tests | |
| 40 | 新增: // replace this in-memory fixture with the real persisted account store. | |
| 41 | 新增: account := &localAccount{path: filepath.Join(profile, "account.json"), record: &accountRecord{Version: 1, Username: "Test"}} | |
| 42 | 新增: account.setKey(make([]byte, 32)) | |
| 43 | 新增: t.Cleanup(account.lock) | |
| 44 | 新增: return &Server{account: account, profile: profile, configPath: path, origin: "http://localhost:17777", token: strings.Repeat("a", 64), session: strings.Repeat("b", 64), preferences: Preferences{Keyboard: "mac"}, terminals: map[string]*terminalSession{}} | |
| 39 | 45 | } |
| 40 | 46 | func request(s *Server, method, path, origin, body string, auth bool) *httptest.ResponseRecorder { |
| 41 | 47 | r := httptest.NewRequest(method, s.origin+path, strings.NewReader(body)) |
| @@ -175,8 +181,7 @@ func TestKeyboardPreferenceDoesNotRestartOrChangeNetwork(t *testing.T) { | ||
| 175 | 181 | if saved.Keyboard != "native" { |
| 176 | 182 | t.Fatal("preference not persisted") |
| 177 | 183 | } |
| 178 | 删除: st, _ := os.Stat(s.configPath) | |
| 179 | 删除: if st.Mode().Perm() != 0600 { | |
| 184 | 新增: if host.CheckPrivateFile(s.configPath) != nil { | |
| 180 | 185 | t.Fatal("profile permissions") |
| 181 | 186 | } |
| 182 | 187 | } |
| @@ -223,7 +228,7 @@ func TestRestoreCannotReplaceManagedEndpoint(t *testing.T) { | ||
| 223 | 228 | } |
| 224 | 229 | |
| 225 | 230 | func TestSSHIsolationOverridesLocalClientSettings(t *testing.T) { |
| 226 | 删除: if _, err := os.Stat("/usr/bin/ssh"); err != nil { | |
| 231 | 新增: if _, err := os.Stat(sshExecutable()); err != nil { | |
| 227 | 232 | t.Skip("OpenSSH is required") |
| 228 | 233 | } |
| 229 | 234 | s := testServer(t) |
| @@ -5,8 +5,6 @@ import ( | ||
| 5 | 5 | "context" |
| 6 | 6 | "encoding/json" |
| 7 | 7 | "errors" |
| 8 | 删除: "fmt" | |
| 9 | 删除: "io" | |
| 10 | 8 | "net" |
| 11 | 9 | "net/http" |
| 12 | 10 | "net/url" |
| @@ -16,20 +14,30 @@ import ( | ||
| 16 | 14 | "time" |
| 17 | 15 | |
| 18 | 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 19 | 18 | "github.com/sylvinus/agent-vm/internal/mounts" |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 20 | 20 | "github.com/sylvinus/agent-vm/internal/vmname" |
| 21 | 21 | ) |
| 22 | 22 | |
| 23 | 23 | type Preferences struct { |
| 24 | 删除: Workspace string `json:"workspace"` | |
| 25 | 删除: BrowserHomeURL string `json:"browser_home_url"` | |
| 26 | 删除: Keyboard string `json:"keyboard"` | |
| 27 | 删除: AutoTimezone bool `json:"auto_timezone"` | |
| 28 | 删除: AutoLanguage bool `json:"auto_language"` | |
| 24 | 新增: Workspace string `json:"workspace"` | |
| 25 | 新增: BrowserHomeURL string `json:"browser_home_url"` | |
| 26 | 新增: ClaudeTerminalCommand string `json:"claude_terminal_command"` | |
| 27 | 新增: Keyboard string `json:"keyboard"` | |
| 28 | 新增: AutoTimezone bool `json:"auto_timezone"` | |
| 29 | 新增: AutoLanguage bool `json:"auto_language"` | |
| 29 | 30 | } |
| 30 | 31 | |
| 31 | 32 | const defaultBrowserHomeURL = "https://www.bing.com/" |
| 32 | 33 | |
| 34 | 新增:func claudeTerminalCommand(p Preferences) string { | |
| 35 | 新增: if strings.TrimSpace(p.ClaudeTerminalCommand) == "" { | |
| 36 | 新增: return "claude" | |
| 37 | 新增: } | |
| 38 | 新增: return strings.TrimSpace(p.ClaudeTerminalCommand) | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 33 | 41 | func browserHomeURL(p Preferences) string { |
| 34 | 42 | if p.BrowserHomeURL == "" { |
| 35 | 43 | return defaultBrowserHomeURL |
| @@ -40,6 +48,8 @@ func browserHomeURL(p Preferences) string { | ||
| 40 | 48 | // The environment workspace is separate from the private control profile. |
| 41 | 49 | func environmentWorkspace(profile string) string { return cage.EnvironmentDir(profile) } |
| 42 | 50 | |
| 51 | 新增:func guestPath(path string) string { return paths.Guest(paths.Host(path)) } | |
| 52 | 新增: | |
| 43 | 53 | func (s *Server) prepareEnvironment() error { |
| 44 | 54 | path := environmentWorkspace(s.profile) |
| 45 | 55 | // Promote an existing installation's VM once, preserving its disk and login state. |
| @@ -106,7 +116,7 @@ func writePrivate(path string, v any) error { | ||
| 106 | 116 | if err != nil { |
| 107 | 117 | return err |
| 108 | 118 | } |
| 109 | 删除: if err = os.MkdirAll(filepath.Dir(path), 0700); err != nil { | |
| 119 | 新增: if err = host.EnsurePrivateDir(filepath.Dir(path)); err != nil { | |
| 110 | 120 | return err |
| 111 | 121 | } |
| 112 | 122 | f, err := os.CreateTemp(filepath.Dir(path), ".cage-write-*") |
| @@ -114,7 +124,7 @@ func writePrivate(path string, v any) error { | ||
| 114 | 124 | return err |
| 115 | 125 | } |
| 116 | 126 | defer os.Remove(f.Name()) |
| 117 | 删除: if err = f.Chmod(0600); err == nil { | |
| 127 | 新增: if err = host.ProtectFile(f.Name()); err == nil { | |
| 118 | 128 | _, err = f.Write(append(b, '\n')) |
| 119 | 129 | } |
| 120 | 130 | if err == nil { |
| @@ -131,6 +141,7 @@ func writePrivate(path string, v any) error { | ||
| 131 | 141 | } |
| 132 | 142 | func settingsView(c cage.Config, p Preferences) Settings { |
| 133 | 143 | p.BrowserHomeURL = browserHomeURL(p) |
| 144 | 新增: p.ClaudeTerminalCommand = claudeTerminalCommand(p) | |
| 134 | 145 | return Settings{Preferences: p, DNSURL: c.DNSURL, Timezone: c.Timezone, Locale: c.Locale, BrowserLanguage: c.BrowserLanguage, ExitPolicy: c.ExitPolicy.Normalized()} |
| 135 | 146 | } |
| 136 | 147 | func proposedSettings(input Settings, old cage.Config, profile string) (cage.Config, Preferences, error) { |
| @@ -145,6 +156,10 @@ func proposedSettings(input Settings, old cage.Config, profile string) (cage.Con | ||
| 145 | 156 | return c, input.Preferences, errors.New("请选择 Mac 或原生 Linux 按键习惯") |
| 146 | 157 | } |
| 147 | 158 | p := input.Preferences |
| 159 | 新增: if len(p.ClaudeTerminalCommand) > 4096 || strings.ContainsAny(p.ClaudeTerminalCommand, "\x00\r\n") { | |
| 160 | 新增: return c, p, errors.New("Claude 终端命令必须为一行,且不超过 4096 字节") | |
| 161 | 新增: } | |
| 162 | 新增: p.ClaudeTerminalCommand = claudeTerminalCommand(p) | |
| 148 | 163 | p.BrowserHomeURL = strings.TrimSpace(browserHomeURL(p)) |
| 149 | 164 | home, e := url.Parse(p.BrowserHomeURL) |
| 150 | 165 | if e != nil || home == nil || (home.Scheme != "https" && home.Scheme != "http") || home.Hostname() == "" || home.User != nil { |
| @@ -186,7 +201,7 @@ func validateWorkspace(path, profile string) (string, error) { | ||
| 186 | 201 | } |
| 187 | 202 | if executable, e := os.Executable(); e == nil { |
| 188 | 203 | if real, e := filepath.EvalSymlinks(executable); e == nil && contains(abs, real) { |
| 189 | 删除: return "", errors.New("不能共享正在运行的工作台程序所在目录。请将安装版 Cage.app 放在项目外,并重启控制服务后选择此项目。") | |
| 204 | 新增: return "", errors.New("不能共享正在运行的工作台程序所在目录。请将安装版 Cage 放在项目外,并重启控制服务后选择此项目。") | |
| 190 | 205 | } |
| 191 | 206 | } |
| 192 | 207 | if mounts.UnderName(filepath.ToSlash(abs), nil) { |
| @@ -212,6 +227,20 @@ func probeLocation(ctx context.Context, c cage.Config) (Location, error) { | ||
| 212 | 227 | return loc, nil |
| 213 | 228 | } |
| 214 | 229 | |
| 230 | 新增:// Manual timezone/language and an IP-only exit rule need no geolocation. | |
| 231 | 新增:// The proxy's exit IP is still measured and checked against the saved rule. | |
| 232 | 新增:func probeEnvironmentLocation(ctx context.Context, c cage.Config, p Preferences) (Location, error) { | |
| 233 | 新增: policy := c.ExitPolicy.Normalized() | |
| 234 | 新增: if p.AutoTimezone || p.AutoLanguage || (policy.Mode != "static" && policy.Scope != "any") { | |
| 235 | 新增: return probeLocation(ctx, c) | |
| 236 | 新增: } | |
| 237 | 新增: ip, err := cage.ProbeExitIP(ctx, c) | |
| 238 | 新增: if err != nil { | |
| 239 | 新增: return Location{}, err | |
| 240 | 新增: } | |
| 241 | 新增: return Location{IP: ip, CheckedAt: time.Now()}, nil | |
| 242 | 新增:} | |
| 243 | 新增: | |
| 215 | 244 | func (l Location) exitLocation() cage.ExitLocation { |
| 216 | 245 | return cage.ExitLocation{IP: l.IP, CountryCode: l.CountryCode, Region: l.Region, City: l.City} |
| 217 | 246 | } |
| @@ -227,34 +256,6 @@ func probeLocationForIP(ctx context.Context, c cage.Config, ip string) (Location | ||
| 227 | 256 | } |
| 228 | 257 | transport := &http.Transport{Proxy: nil, DialContext: e.DialContext, ForceAttemptHTTP2: true} |
| 229 | 258 | defer transport.CloseIdleConnections() |
| 230 | 删除: client := &http.Client{Transport: transport, Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }} | |
| 231 | 删除: req, _ := http.NewRequestWithContext(ctx, "GET", "https://ipwho.is/"+address.String()+"?fields=success,ip,country,country_code,region,region_code,city,timezone.id", nil) | |
| 232 | 删除: r, err := client.Do(req) | |
| 233 | 删除: if err != nil { | |
| 234 | 删除: return Location{}, errors.New("无法经指定代理查询出口;请检查代理是否运行。没有使用直连回退。") | |
| 235 | 删除: } | |
| 236 | 删除: defer r.Body.Close() | |
| 237 | 删除: if r.StatusCode != 200 { | |
| 238 | 删除: return Location{}, fmt.Errorf("出口定位服务返回 HTTP %d;原配置保持不变", r.StatusCode) | |
| 239 | 删除: } | |
| 240 | 删除: var v struct { | |
| 241 | 删除: Success bool `json:"success"` | |
| 242 | 删除: IP string `json:"ip"` | |
| 243 | 删除: Country string `json:"country"` | |
| 244 | 删除: CountryCode string `json:"country_code"` | |
| 245 | 删除: Region string `json:"region"` | |
| 246 | 删除: RegionCode string `json:"region_code"` | |
| 247 | 删除: City string `json:"city"` | |
| 248 | 删除: Timezone struct { | |
| 249 | 删除: ID string `json:"id"` | |
| 250 | 删除: } `json:"timezone"` | |
| 251 | 删除: } | |
| 252 | 删除: if json.NewDecoder(io.LimitReader(r.Body, 128<<10)).Decode(&v) != nil || !v.Success || net.ParseIP(v.IP) == nil || !net.ParseIP(v.IP).Equal(address) { | |
| 253 | 删除: return Location{}, errors.New("出口定位服务未返回有效位置;可关闭自动时区后手动设置") | |
| 254 | 删除: } | |
| 255 | 删除: if _, err = time.LoadLocation(v.Timezone.ID); err != nil { | |
| 256 | 删除: return Location{}, errors.New("出口位置未包含有效时区;请手动选择时区") | |
| 257 | 删除: } | |
| 258 | 删除: locale, browser := languageSuggestion(v.CountryCode) | |
| 259 | 删除: return Location{IP: v.IP, Country: v.Country, CountryCode: v.CountryCode, Region: v.Region, RegionCode: v.RegionCode, City: v.City, Timezone: v.Timezone.ID, CheckedAt: time.Now(), SuggestedLocale: locale, SuggestedBrowserLanguage: browser}, nil | |
| 259 | 新增: client := &http.Client{Transport: transport, Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }} | |
| 260 | 新增: return lookupLocation(ctx, client, address) | |
| 260 | 261 | } |
| @@ -7,23 +7,28 @@ import ( | ||
| 7 | 7 | "io" |
| 8 | 8 | "net" |
| 9 | 9 | "net/http" |
| 10 | 删除: "os" | |
| 11 | 10 | "os/exec" |
| 12 | 11 | "sync" |
| 13 | 12 | "time" |
| 14 | 13 | |
| 15 | 14 | "al.essio.dev/pkg/shellescape" |
| 16 | 删除: "github.com/creack/pty" | |
| 17 | 15 | "github.com/gorilla/websocket" |
| 18 | 16 | "github.com/sylvinus/agent-vm/internal/vmname" |
| 19 | 17 | ) |
| 20 | 18 | |
| 19 | 新增:type terminalPTY interface { | |
| 20 | 新增: io.ReadWriteCloser | |
| 21 | 新增: Resize(cols, rows uint16) error | |
| 22 | 新增: Wait() error | |
| 23 | 新增: Kill() error | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 21 | 26 | type terminalSession struct { |
| 22 | 27 | mu sync.Mutex |
| 23 | 28 | id, title string |
| 24 | 29 | workspace string |
| 25 | 30 | cmd *exec.Cmd |
| 26 | 删除: file *os.File | |
| 31 | 新增: file terminalPTY | |
| 27 | 32 | history []byte |
| 28 | 33 | closed bool |
| 29 | 34 | clients map[chan []byte]bool |
| @@ -38,10 +43,8 @@ func (t *terminalSession) close() { | ||
| 38 | 43 | t.mu.Lock() |
| 39 | 44 | if !t.closed { |
| 40 | 45 | t.closed = true |
| 46 | 新增: _ = t.file.Kill() | |
| 41 | 47 | _ = t.file.Close() |
| 42 | 删除: if t.cmd.Process != nil { | |
| 43 | 删除: _ = t.cmd.Process.Kill() | |
| 44 | 删除: } | |
| 45 | 48 | } |
| 46 | 49 | t.mu.Unlock() |
| 47 | 50 | } |
| @@ -70,7 +73,7 @@ func (t *terminalSession) read() { | ||
| 70 | 73 | break |
| 71 | 74 | } |
| 72 | 75 | } |
| 73 | 删除: _ = t.cmd.Wait() | |
| 76 | 新增: _ = t.file.Wait() | |
| 74 | 77 | t.mu.Lock() |
| 75 | 78 | t.closed = true |
| 76 | 79 | for ch := range t.clients { |
| @@ -108,10 +111,15 @@ func (s *Server) newTerminal(w http.ResponseWriter, r *http.Request) { | ||
| 108 | 111 | } |
| 109 | 112 | var input struct { |
| 110 | 113 | Workspace string `json:"workspace"` |
| 114 | 新增: Kind string `json:"kind"` | |
| 111 | 115 | } |
| 112 | 116 | if !readJSON(w, r, &input) { |
| 113 | 117 | return |
| 114 | 118 | } |
| 119 | 新增: if input.Kind != "" && input.Kind != "shell" && input.Kind != "claude" { | |
| 120 | 新增: http.Error(w, "终端类型无效", http.StatusBadRequest) | |
| 121 | 新增: return | |
| 122 | 新增: } | |
| 115 | 123 | workspace, err := s.projectWorkspace(input.Workspace) |
| 116 | 124 | if err != nil { |
| 117 | 125 | requestError(w, err) |
| @@ -122,9 +130,12 @@ func (s *Server) newTerminal(w http.ResponseWriter, r *http.Request) { | ||
| 122 | 130 | return |
| 123 | 131 | } |
| 124 | 132 | name := vmname.Name(s.environmentDir()) |
| 125 | 删除: script := "cd " + shellescape.Quote(workspace) + " && exec env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 bash -l" | |
| 133 | 新增: s.mu.Lock() | |
| 134 | 新增: command := claudeTerminalCommand(s.preferences) | |
| 135 | 新增: s.mu.Unlock() | |
| 136 | 新增: script := terminalScript(guestPath(workspace), input.Kind, command) | |
| 126 | 137 | cmd := s.sshCommand(context.Background(), "-tt", "lima-"+name, "--", script) |
| 127 | 删除: file, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: 100, Rows: 30}) | |
| 138 | 新增: file, err := startTerminal(cmd, 100, 30) | |
| 128 | 139 | if err != nil { |
| 129 | 140 | http.Error(w, "无法创建终端连接", 500) |
| 130 | 141 | return |
| @@ -134,12 +145,25 @@ func (s *Server) newTerminal(w http.ResponseWriter, r *http.Request) { | ||
| 134 | 145 | number := s.terminalSequence |
| 135 | 146 | s.mu.Unlock() |
| 136 | 147 | t := &terminalSession{workspace: workspace, id: randomToken()[:16], title: fmt.Sprintf("终端 %d", number), cmd: cmd, file: file, clients: map[chan []byte]bool{}} |
| 148 | 新增: if input.Kind == "claude" { | |
| 149 | 新增: t.title = fmt.Sprintf("Claude %d", number) | |
| 150 | 新增: } | |
| 137 | 151 | s.mu.Lock() |
| 138 | 152 | s.terminals[t.id] = t |
| 139 | 153 | s.mu.Unlock() |
| 140 | 154 | go t.read() |
| 141 | 155 | jsonReply(w, t.summary()) |
| 142 | 156 | } |
| 157 | 新增: | |
| 158 | 新增:// The saved command is interpreted only by the guest's interactive shell. | |
| 159 | 新增:// Reconnecting a viewer never executes it again; exiting Claude leaves a shell. | |
| 160 | 新增:func terminalScript(workspace, kind, command string) string { | |
| 161 | 新增: prefix := "cd " + shellescape.Quote(workspace) + " && exec env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 " | |
| 162 | 新增: if kind != "claude" { | |
| 163 | 新增: return prefix + "bash -l" | |
| 164 | 新增: } | |
| 165 | 新增: return prefix + "CAGE_TERMINAL_COMMAND=" + shellescape.Quote(command) + " bash -lic " + shellescape.Quote("eval \"$CAGE_TERMINAL_COMMAND\"; unset CAGE_TERMINAL_COMMAND; exec bash -il") | |
| 166 | 新增:} | |
| 143 | 167 | func (s *Server) closeTerminal(w http.ResponseWriter, r *http.Request) { |
| 144 | 168 | s.mu.Lock() |
| 145 | 169 | t := s.terminals[r.PathValue("id")] |
| @@ -152,7 +176,11 @@ func (s *Server) closeTerminal(w http.ResponseWriter, r *http.Request) { | ||
| 152 | 176 | } |
| 153 | 177 | func (s *Server) upgrade(w http.ResponseWriter, r *http.Request) (*websocket.Conn, error) { |
| 154 | 178 | up := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return r.Header.Get("Origin") == s.origin }, ReadBufferSize: 16384, WriteBufferSize: 16384} |
| 155 | 删除: return up.Upgrade(w, r, nil) | |
| 179 | 新增: ws, err := up.Upgrade(w, r, nil) | |
| 180 | 新增: if err == nil { | |
| 181 | 新增: context.AfterFunc(r.Context(), func() { _ = ws.Close() }) | |
| 182 | 新增: } | |
| 183 | 新增: return ws, err | |
| 156 | 184 | } |
| 157 | 185 | func (s *Server) terminalStream(w http.ResponseWriter, r *http.Request) { |
| 158 | 186 | s.mu.Lock() |
| @@ -215,7 +243,7 @@ func (s *Server) terminalStream(w http.ResponseWriter, r *http.Request) { | ||
| 215 | 243 | _, _ = io.WriteString(t.file, v.Data) |
| 216 | 244 | case "resize": |
| 217 | 245 | if v.Cols > 1 && v.Cols < 600 && v.Rows > 1 && v.Rows < 400 { |
| 218 | 删除: _ = pty.Setsize(t.file, &pty.Winsize{Cols: v.Cols, Rows: v.Rows}) | |
| 246 | 新增: _ = t.file.Resize(v.Cols, v.Rows) | |
| 219 | 247 | } |
| 220 | 248 | } |
| 221 | 249 | } |
| @@ -241,6 +269,10 @@ func (s *Server) vnc(w http.ResponseWriter, r *http.Request) { | ||
| 241 | 269 | return |
| 242 | 270 | } |
| 243 | 271 | defer remote.Close() |
| 272 | 新增: s.streamVNC(w, r, remote, remote) | |
| 273 | 新增:} | |
| 274 | 新增: | |
| 275 | 新增:func (s *Server) streamVNC(w http.ResponseWriter, r *http.Request, reader io.Reader, writer io.Writer) { | |
| 244 | 276 | ws, e := s.upgrade(w, r) |
| 245 | 277 | if e != nil { |
| 246 | 278 | return |
| @@ -251,7 +283,7 @@ func (s *Server) vnc(w http.ResponseWriter, r *http.Request) { | ||
| 251 | 283 | defer ws.Close() |
| 252 | 284 | b := make([]byte, 64<<10) |
| 253 | 285 | for { |
| 254 | 删除: n, e := remote.Read(b) | |
| 286 | 新增: n, e := reader.Read(b) | |
| 255 | 287 | if n > 0 { |
| 256 | 288 | _ = ws.SetWriteDeadline(time.Now().Add(10 * time.Second)) |
| 257 | 289 | if ws.WriteMessage(websocket.BinaryMessage, b[:n]) != nil { |
| @@ -269,7 +301,7 @@ func (s *Server) vnc(w http.ResponseWriter, r *http.Request) { | ||
| 269 | 301 | return |
| 270 | 302 | } |
| 271 | 303 | if kind == websocket.BinaryMessage { |
| 272 | 删除: if _, e = remote.Write(b); e != nil { | |
| 304 | 新增: if _, e = writer.Write(b); e != nil { | |
| 273 | 305 | return |
| 274 | 306 | } |
| 275 | 307 | } |
| @@ -0,0 +1,28 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package workbench | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "os" | |
| 7 | 新增: "os/exec" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/creack/pty" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:type unixTerminal struct { | |
| 13 | 新增: *os.File | |
| 14 | 新增: cmd *exec.Cmd | |
| 15 | 新增:} | |
| 16 | 新增: | |
| 17 | 新增:func startTerminal(cmd *exec.Cmd, cols, rows uint16) (terminalPTY, error) { | |
| 18 | 新增: f, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: cols, Rows: rows}) | |
| 19 | 新增: if err != nil { | |
| 20 | 新增: return nil, err | |
| 21 | 新增: } | |
| 22 | 新增: return &unixTerminal{File: f, cmd: cmd}, nil | |
| 23 | 新增:} | |
| 24 | 新增:func (p *unixTerminal) Resize(cols, rows uint16) error { | |
| 25 | 新增: return pty.Setsize(p.File, &pty.Winsize{Cols: cols, Rows: rows}) | |
| 26 | 新增:} | |
| 27 | 新增:func (p *unixTerminal) Wait() error { return p.cmd.Wait() } | |
| 28 | 新增:func (p *unixTerminal) Kill() error { return p.cmd.Process.Kill() } | |
| @@ -0,0 +1,148 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "os" | |
| 6 | 新增: "os/exec" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "sync" | |
| 9 | 新增: "syscall" | |
| 10 | 新增: "unicode/utf16" | |
| 11 | 新增: "unsafe" | |
| 12 | 新增: | |
| 13 | 新增: "golang.org/x/sys/windows" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:// ConPTY gives OpenSSH an actual Windows terminal. Pipes alone cannot deliver | |
| 17 | 新增:// window resize, raw input, Ctrl+C, or full-screen programs correctly. | |
| 18 | 新增:type windowsTerminal struct { | |
| 19 | 新增: input, output *os.File | |
| 20 | 新增: console windows.Handle | |
| 21 | 新增: process *os.Process | |
| 22 | 新增: once sync.Once | |
| 23 | 新增: consoleOnce sync.Once | |
| 24 | 新增: consoleMu sync.Mutex | |
| 25 | 新增: done chan struct{} | |
| 26 | 新增: waitErr error | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:func startTerminal(cmd *exec.Cmd, cols, rows uint16) (terminalPTY, error) { | |
| 30 | 新增: inputRead, inputWrite, err := os.Pipe() | |
| 31 | 新增: if err != nil { | |
| 32 | 新增: return nil, err | |
| 33 | 新增: } | |
| 34 | 新增: defer inputRead.Close() | |
| 35 | 新增: outputRead, outputWrite, err := os.Pipe() | |
| 36 | 新增: if err != nil { | |
| 37 | 新增: inputWrite.Close() | |
| 38 | 新增: return nil, err | |
| 39 | 新增: } | |
| 40 | 新增: defer outputWrite.Close() | |
| 41 | 新增: p := &windowsTerminal{input: inputWrite, output: outputRead, done: make(chan struct{})} | |
| 42 | 新增: success := false | |
| 43 | 新增: defer func() { | |
| 44 | 新增: if !success { | |
| 45 | 新增: p.Close() | |
| 46 | 新增: } | |
| 47 | 新增: }() | |
| 48 | 新增: if err = windows.CreatePseudoConsole(windows.Coord{X: int16(cols), Y: int16(rows)}, windows.Handle(inputRead.Fd()), windows.Handle(outputWrite.Fd()), 0, &p.console); err != nil { | |
| 49 | 新增: return nil, err | |
| 50 | 新增: } | |
| 51 | 新增: attrs, err := windows.NewProcThreadAttributeList(1) | |
| 52 | 新增: if err != nil { | |
| 53 | 新增: return nil, err | |
| 54 | 新增: } | |
| 55 | 新增: defer attrs.Delete() | |
| 56 | 新增: // This attribute takes the opaque HPCON value as lpValue, not a pointer | |
| 57 | 新增: // to it. Pass the integer handle to the syscall without forging a Go pointer. | |
| 58 | 新增: update := windows.NewLazySystemDLL("kernel32.dll").NewProc("UpdateProcThreadAttribute") | |
| 59 | 新增: if ok, _, callErr := update.Call(uintptr(unsafe.Pointer(attrs.List())), 0, windows.PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, uintptr(p.console), unsafe.Sizeof(p.console), 0, 0); ok == 0 { | |
| 60 | 新增: return nil, callErr | |
| 61 | 新增: } | |
| 62 | 新增: startup := windows.StartupInfoEx{} | |
| 63 | 新增: startup.Cb = uint32(unsafe.Sizeof(startup)) | |
| 64 | 新增: // With redirected parent stdio, explicitly request fresh console handles. | |
| 65 | 新增: // Leaving this flag unset can retain the parent's pipes despite ConPTY. | |
| 66 | 新增: startup.Flags = windows.STARTF_USESTDHANDLES | |
| 67 | 新增: startup.ProcThreadAttributeList = attrs.List() | |
| 68 | 新增: app, err := windows.UTF16PtrFromString(cmd.Path) | |
| 69 | 新增: if err != nil { | |
| 70 | 新增: return nil, err | |
| 71 | 新增: } | |
| 72 | 新增: parts := make([]string, len(cmd.Args)) | |
| 73 | 新增: for i, arg := range cmd.Args { | |
| 74 | 新增: parts[i] = syscall.EscapeArg(arg) | |
| 75 | 新增: } | |
| 76 | 新增: commandLine, err := windows.UTF16PtrFromString(strings.Join(parts, " ")) | |
| 77 | 新增: if err != nil { | |
| 78 | 新增: return nil, err | |
| 79 | 新增: } | |
| 80 | 新增: var directory *uint16 | |
| 81 | 新增: if cmd.Dir != "" { | |
| 82 | 新增: directory, err = windows.UTF16PtrFromString(cmd.Dir) | |
| 83 | 新增: if err != nil { | |
| 84 | 新增: return nil, err | |
| 85 | 新增: } | |
| 86 | 新增: } | |
| 87 | 新增: env := cmd.Env | |
| 88 | 新增: if env == nil { | |
| 89 | 新增: env = os.Environ() | |
| 90 | 新增: } | |
| 91 | 新增: for _, entry := range env { | |
| 92 | 新增: if strings.ContainsRune(entry, 0) { | |
| 93 | 新增: return nil, errors.New("invalid terminal environment") | |
| 94 | 新增: } | |
| 95 | 新增: } | |
| 96 | 新增: block := utf16.Encode([]rune(strings.Join(env, "\x00") + "\x00\x00")) | |
| 97 | 新增: var info windows.ProcessInformation | |
| 98 | 新增: err = windows.CreateProcess(app, commandLine, nil, nil, false, windows.EXTENDED_STARTUPINFO_PRESENT|windows.CREATE_UNICODE_ENVIRONMENT, &block[0], directory, &startup.StartupInfo, &info) | |
| 99 | 新增: if err != nil { | |
| 100 | 新增: return nil, err | |
| 101 | 新增: } | |
| 102 | 新增: defer windows.CloseHandle(info.Thread) | |
| 103 | 新增: defer windows.CloseHandle(info.Process) | |
| 104 | 新增: p.process, err = os.FindProcess(int(info.ProcessId)) | |
| 105 | 新增: if err != nil { | |
| 106 | 新增: windows.TerminateProcess(info.Process, 1) | |
| 107 | 新增: return nil, err | |
| 108 | 新增: } | |
| 109 | 新增: success = true | |
| 110 | 新增: go func() { | |
| 111 | 新增: _, p.waitErr = p.process.Wait() | |
| 112 | 新增: p.closeConsole() | |
| 113 | 新增: close(p.done) | |
| 114 | 新增: }() | |
| 115 | 新增: return p, nil | |
| 116 | 新增:} | |
| 117 | 新增:func (p *windowsTerminal) Read(b []byte) (int, error) { return p.output.Read(b) } | |
| 118 | 新增:func (p *windowsTerminal) Write(b []byte) (int, error) { return p.input.Write(b) } | |
| 119 | 新增:func (p *windowsTerminal) Resize(cols, rows uint16) error { | |
| 120 | 新增: p.consoleMu.Lock() | |
| 121 | 新增: defer p.consoleMu.Unlock() | |
| 122 | 新增: if p.console == 0 { | |
| 123 | 新增: return os.ErrClosed | |
| 124 | 新增: } | |
| 125 | 新增: return windows.ResizePseudoConsole(p.console, windows.Coord{X: int16(cols), Y: int16(rows)}) | |
| 126 | 新增:} | |
| 127 | 新增:func (p *windowsTerminal) Wait() error { <-p.done; return p.waitErr } | |
| 128 | 新增:func (p *windowsTerminal) Kill() error { return p.process.Kill() } | |
| 129 | 新增:func (p *windowsTerminal) closeConsole() { | |
| 130 | 新增: p.consoleOnce.Do(func() { | |
| 131 | 新增: p.consoleMu.Lock() | |
| 132 | 新增: defer p.consoleMu.Unlock() | |
| 133 | 新增: if p.console != 0 { | |
| 134 | 新增: windows.ClosePseudoConsole(p.console) | |
| 135 | 新增: p.console = 0 | |
| 136 | 新增: } | |
| 137 | 新增: }) | |
| 138 | 新增:} | |
| 139 | 新增:func (p *windowsTerminal) Close() error { | |
| 140 | 新增: p.once.Do(func() { | |
| 141 | 新增: p.input.Close() | |
| 142 | 新增: p.output.Close() | |
| 143 | 新增: // Closing a ConPTY can wait for output delivery. The reader is closed | |
| 144 | 新增: // first, so shutdown never waits on the WebSocket consumer. | |
| 145 | 新增: p.closeConsole() | |
| 146 | 新增: }) | |
| 147 | 新增: return nil | |
| 148 | 新增:} | |
| @@ -0,0 +1,37 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "io" | |
| 5 | 新增: "os/exec" | |
| 6 | 新增: "strings" | |
| 7 | 新增: "testing" | |
| 8 | 新增: "time" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestWindowsTerminalInputResizeAndExit(t *testing.T) { | |
| 12 | 新增: cmd := exec.Command("powershell.exe", "-NoProfile", "-NonInteractive", "-Command", "$v=[Console]::ReadLine(); [Console]::WriteLine('received:'+$v)") | |
| 13 | 新增: terminal, err := startTerminal(cmd, 80, 24) | |
| 14 | 新增: if err != nil { | |
| 15 | 新增: t.Fatal(err) | |
| 16 | 新增: } | |
| 17 | 新增: t.Cleanup(func() { _ = terminal.Kill(); _ = terminal.Close() }) | |
| 18 | 新增: if err = terminal.Resize(120, 40); err != nil { | |
| 19 | 新增: t.Fatal(err) | |
| 20 | 新增: } | |
| 21 | 新增: output := make(chan string, 1) | |
| 22 | 新增: go func() { b, _ := io.ReadAll(terminal); output <- string(b) }() | |
| 23 | 新增: if _, err = io.WriteString(terminal, "cage-terminal\r"); err != nil { | |
| 24 | 新增: t.Fatal(err) | |
| 25 | 新增: } | |
| 26 | 新增: select { | |
| 27 | 新增: case text := <-output: | |
| 28 | 新增: if !strings.Contains(text, "received:cage-terminal") { | |
| 29 | 新增: t.Fatalf("ConPTY input did not reach child: %q", text) | |
| 30 | 新增: } | |
| 31 | 新增: if err := terminal.Wait(); err != nil { | |
| 32 | 新增: t.Fatal(err) | |
| 33 | 新增: } | |
| 34 | 新增: case <-time.After(15 * time.Second): | |
| 35 | 新增: t.Fatal("ConPTY did not drain and close after child exit") | |
| 36 | 新增: } | |
| 37 | 新增:} | |
| @@ -0,0 +1,14 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "architecture": "amd64", | |
| 3 | 新增: "mihomo": { | |
| 4 | 新增: "version": "v1.19.33", | |
| 5 | 新增: "file": "mihomo-linux-amd64-compatible-v1.19.33.gz", | |
| 6 | 新增: "url": "https://github.com/MetaCubeX/mihomo/releases/download/v1.19.33/mihomo-linux-amd64-compatible-v1.19.33.gz", | |
| 7 | 新增: "sha256": "386508bfb1c72c43b6a0eda73708ecdce82546581b0ebcb16366c53757c622b6" | |
| 8 | 新增: }, | |
| 9 | 新增: "mihomoSource": { | |
| 10 | 新增: "file": "mihomo-v1.19.33-source.tar.gz", | |
| 11 | 新增: "url": "https://github.com/MetaCubeX/mihomo/archive/refs/tags/v1.19.33.tar.gz", | |
| 12 | 新增: "sha256": "e7c596b37ff27ec487d19b1920f73e0c97a78067ea35766530ee9659ade72711" | |
| 13 | 新增: } | |
| 14 | 新增:} | |
| @@ -0,0 +1,11 @@ | ||
| 1 | 新增:[Desktop Entry] | |
| 2 | 新增:Type=Application | |
| 3 | 新增:Name=Cage | |
| 4 | 新增:Comment=Isolated coding workspace | |
| 5 | 新增:Comment[zh_CN]=隔离编码工作区 | |
| 6 | 新增:Exec=/usr/bin/cage-desktop | |
| 7 | 新增:Icon=io.github.lee_xeo.Cage | |
| 8 | 新增:Terminal=false | |
| 9 | 新增:Categories=Development; | |
| 10 | 新增:StartupNotify=true | |
| 11 | 新增:StartupWMClass=cage-desktop | |
| @@ -0,0 +1,21 @@ | ||
| 1 | 新增:#!/bin/sh | |
| 2 | 新增:set -eu | |
| 3 | 新增:# Replacing a running controller or proxy would break its verified identity. | |
| 4 | 新增:# Do not stop another user's work from a privileged package script. | |
| 5 | 新增:if [ "${1:-}" = upgrade ] || [ "${1:-}" = install ] || [ "${1:-}" = remove ]; then | |
| 6 | 新增: for process in /proc/[0-9]*; do | |
| 7 | 新增: executable=$(readlink "$process/exe" 2>/dev/null || true) | |
| 8 | 新增: # Restricted /proc setups may hide another user's executable link from | |
| 9 | 新增: # package scripts. Check the launch path too; never silently bypass a | |
| 10 | 新增: # running packaged program just because readlink was denied. | |
| 11 | 新增: if [ -z "$executable" ]; then | |
| 12 | 新增: executable=$(tr '\000' '\n' < "$process/cmdline" 2>/dev/null | head -n 1) || executable= | |
| 13 | 新增: fi | |
| 14 | 新增: case "$executable" in | |
| 15 | 新增: /usr/bin/claude-cage|/usr/bin/cage-desktop|/usr/lib/claude-cage/cage|/usr/lib/claude-cage/cage-desktop|/usr/lib/claude-cage/mihomo|/usr/lib/claude-cage/*' (deleted)') | |
| 16 | 新增: echo 'Cage is running. Save work, stop the environment, and quit Cage before changing the installation.' >&2 | |
| 17 | 新增: exit 1 | |
| 18 | 新增: ;; | |
| 19 | 新增: esac | |
| 20 | 新增: done | |
| 21 | 新增:fi | |
二进制文件,不显示改动。
| @@ -0,0 +1,247 @@ | ||
| 1 | 新增:Unicode true | |
| 2 | 新增:RequestExecutionLevel user | |
| 3 | 新增:SetCompressor /SOLID lzma | |
| 4 | 新增:SetCompressorDictSize 32 | |
| 5 | 新增:ManifestDPIAware true | |
| 6 | 新增:ManifestSupportedOS all | |
| 7 | 新增:Icon "Cage.ico" | |
| 8 | 新增:UninstallIcon "Cage.ico" | |
| 9 | 新增: | |
| 10 | 新增:!include MUI2.nsh | |
| 11 | 新增:!include LogicLib.nsh | |
| 12 | 新增:!include FileFunc.nsh | |
| 13 | 新增:!include x64.nsh | |
| 14 | 新增:!include WinVer.nsh | |
| 15 | 新增: | |
| 16 | 新增:!ifndef APP_DIR | |
| 17 | 新增: !error "APP_DIR is required" | |
| 18 | 新增:!endif | |
| 19 | 新增:!ifndef VERSION | |
| 20 | 新增: !error "VERSION is required" | |
| 21 | 新增:!endif | |
| 22 | 新增:!ifndef VERSION_NUMERIC | |
| 23 | 新增: !error "VERSION_NUMERIC is required" | |
| 24 | 新增:!endif | |
| 25 | 新增:!ifndef OUTPUT_FILE | |
| 26 | 新增: !error "OUTPUT_FILE is required" | |
| 27 | 新增:!endif | |
| 28 | 新增: | |
| 29 | 新增:!define APP_ID "io.github.lee-xeo.claude-cage" | |
| 30 | 新增:!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\ClaudeCage" | |
| 31 | 新增:!define WEBVIEW2_APP_ID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" | |
| 32 | 新增:Name "Cage ${VERSION}" | |
| 33 | 新增:OutFile "${OUTPUT_FILE}" | |
| 34 | 新增:InstallDir "$LOCALAPPDATA\Programs\Cage" | |
| 35 | 新增:InstallDirRegKey HKCU "${UNINSTALL_KEY}" "InstallLocation" | |
| 36 | 新增:VIProductVersion "${VERSION_NUMERIC}" | |
| 37 | 新增:VIAddVersionKey /LANG=1033 "ProductName" "Cage" | |
| 38 | 新增:VIAddVersionKey /LANG=1033 "ProductVersion" "${VERSION}" | |
| 39 | 新增:VIAddVersionKey /LANG=1033 "FileVersion" "${VERSION}" | |
| 40 | 新增:VIAddVersionKey /LANG=1033 "FileDescription" "Cage Windows Installer" | |
| 41 | 新增:VIAddVersionKey /LANG=1033 "LegalCopyright" "Cage contributors" | |
| 42 | 新增: | |
| 43 | 新增:!ifdef SIGNTOOL | |
| 44 | 新增: !uninstfinalize '"${SIGNTOOL}" sign /sha1 "${CERT_SHA1}" /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 "%1"' = 0 | |
| 45 | 新增:!endif | |
| 46 | 新增: | |
| 47 | 新增:!define MUI_ABORTWARNING | |
| 48 | 新增:!define MUI_FINISHPAGE_RUN "$INSTDIR\Cage.exe" | |
| 49 | 新增:!define MUI_FINISHPAGE_RUN_NOTCHECKED | |
| 50 | 新增:!define MUI_FINISHPAGE_TEXT "Cage is installed.$\r$\n$\r$\nIf virtualization is unavailable, enable Windows Hypervisor Platform in Windows Features and restart Windows. Your projects and Cage data are preserved during upgrades and uninstall." | |
| 51 | 新增:!insertmacro MUI_PAGE_WELCOME | |
| 52 | 新增:!insertmacro MUI_PAGE_LICENSE "${APP_DIR}/LICENSE.txt" | |
| 53 | 新增:!insertmacro MUI_PAGE_DIRECTORY | |
| 54 | 新增:!insertmacro MUI_PAGE_INSTFILES | |
| 55 | 新增:!insertmacro MUI_PAGE_FINISH | |
| 56 | 新增:!insertmacro MUI_UNPAGE_CONFIRM | |
| 57 | 新增:!insertmacro MUI_UNPAGE_INSTFILES | |
| 58 | 新增:!insertmacro MUI_LANGUAGE "English" | |
| 59 | 新增:!insertmacro MUI_LANGUAGE "SimpChinese" | |
| 60 | 新增: | |
| 61 | 新增:Var UpdateMode | |
| 62 | 新增:Var StageDir | |
| 63 | 新增:Var BackupDir | |
| 64 | 新增:Var ExistingInstall | |
| 65 | 新增: | |
| 66 | 新增:!macro CheckStopped FILE | |
| 67 | 新增: ${If} ${FileExists} "$INSTDIR\${FILE}" | |
| 68 | 新增: ; Exclusive write access also detects images whose VM/controller has no window. | |
| 69 | 新增: System::Call 'kernel32::CreateFileW(w "$INSTDIR\${FILE}", i 0x40000000, i 0, p 0, i 3, i 0, p 0) p .r0' | |
| 70 | 新增: ${If} $0 == -1 | |
| 71 | 新增: SetErrorLevel 2 | |
| 72 | 新增: Abort "Quit Cage and stop its environment before installing or uninstalling." | |
| 73 | 新增: ${EndIf} | |
| 74 | 新增: System::Call 'kernel32::CloseHandle(p r0)' | |
| 75 | 新增: ${EndIf} | |
| 76 | 新增:!macroend | |
| 77 | 新增: | |
| 78 | 新增:Function .onInit | |
| 79 | 新增: SetShellVarContext current | |
| 80 | 新增: SetRegView 64 | |
| 81 | 新增: ${IfNot} ${IsNativeAMD64} | |
| 82 | 新增: MessageBox MB_ICONSTOP "This Cage package requires an Intel/AMD 64-bit version of Windows. Windows on ARM and 32-bit Windows are not supported." | |
| 83 | 新增: SetErrorLevel 1633 | |
| 84 | 新增: Quit | |
| 85 | 新增: ${EndIf} | |
| 86 | 新增: ReadRegStr $0 HKLM "SOFTWARE\Microsoft\Windows NT\CurrentVersion" "CurrentBuildNumber" | |
| 87 | 新增: ${If} $0 < 19045 | |
| 88 | 新增: MessageBox MB_ICONSTOP "Cage requires Windows 10 22H2 (build 19045) or Windows 11. Update Windows and try again." | |
| 89 | 新增: SetErrorLevel 1633 | |
| 90 | 新增: Quit | |
| 91 | 新增: ${EndIf} | |
| 92 | 新增: StrCpy $UpdateMode "0" | |
| 93 | 新增: ${GetParameters} $0 | |
| 94 | 新增: ClearErrors | |
| 95 | 新增: ${GetOptions} $0 "/UPDATE" $1 | |
| 96 | 新增: ${IfNot} ${Errors} | |
| 97 | 新增: StrCpy $UpdateMode "1" | |
| 98 | 新增: SetSilent silent | |
| 99 | 新增: ${EndIf} | |
| 100 | 新增:FunctionEnd | |
| 101 | 新增: | |
| 102 | 新增:Function CheckDestination | |
| 103 | 新增: ${GetRoot} "$INSTDIR" $0 | |
| 104 | 新增: ${If} $0 == "" | |
| 105 | 新增: ${OrIf} $INSTDIR == $0 | |
| 106 | 新增: ${OrIf} $INSTDIR == "$0\" | |
| 107 | 新增: SetErrorLevel 2 | |
| 108 | 新增: Abort "Choose a dedicated application folder." | |
| 109 | 新增: ${EndIf} | |
| 110 | 新增: StrCpy $ExistingInstall "0" | |
| 111 | 新增: IfFileExists "$INSTDIR\Cage.install-id" existing | |
| 112 | 新增: IfFileExists "$INSTDIR\*.*" foreign done | |
| 113 | 新增: existing: | |
| 114 | 新增: FileOpen $0 "$INSTDIR\Cage.install-id" r | |
| 115 | 新增: FileRead $0 $1 | |
| 116 | 新增: FileClose $0 | |
| 117 | 新增: ${If} $1 != "${APP_ID}" | |
| 118 | 新增: Goto foreign | |
| 119 | 新增: ${EndIf} | |
| 120 | 新增: StrCpy $ExistingInstall "1" | |
| 121 | 新增: ; Never stop processes by their name or force-close user workloads. | |
| 122 | 新增: !insertmacro CheckStopped "Cage.exe" | |
| 123 | 新增: !insertmacro CheckStopped "resources\cage.exe" | |
| 124 | 新增: !insertmacro CheckStopped "resources\mihomo.exe" | |
| 125 | 新增: !insertmacro CheckStopped "resources\runtime\qemu\qemu-system-x86_64.exe" | |
| 126 | 新增: Goto done | |
| 127 | 新增: foreign: | |
| 128 | 新增: SetErrorLevel 2 | |
| 129 | 新增: Abort "The destination contains files from another installation. Choose an empty folder." | |
| 130 | 新增: done: | |
| 131 | 新增:FunctionEnd | |
| 132 | 新增: | |
| 133 | 新增:Section "Cage" Main | |
| 134 | 新增: Call CheckDestination | |
| 135 | 新增: ${GetParent} "$INSTDIR" $0 | |
| 136 | 新增: CreateDirectory "$0" | |
| 137 | 新增: GetTempFileName $StageDir "$0" | |
| 138 | 新增: Delete "$StageDir" | |
| 139 | 新增: CreateDirectory "$StageDir" | |
| 140 | 新增: SetOutPath "$StageDir" | |
| 141 | 新增: ClearErrors | |
| 142 | 新增: File /r "${APP_DIR}/*" | |
| 143 | 新增: WriteUninstaller "$StageDir\Uninstall.exe" | |
| 144 | 新增: ${If} ${Errors} | |
| 145 | 新增: SetOutPath "$TEMP" | |
| 146 | 新增: RMDir /r "$StageDir" | |
| 147 | 新增: SetErrorLevel 2 | |
| 148 | 新增: Abort "Could not unpack Cage. Check free disk space and folder permissions." | |
| 149 | 新增: ${EndIf} | |
| 150 | 新增: | |
| 151 | 新增: ; Install the bundled offline runtime only when WebView2 is absent. | |
| 152 | 新增: SetRegView 32 | |
| 153 | 新增: ReadRegStr $0 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_APP_ID}" "pv" | |
| 154 | 新增: ReadRegStr $1 HKCU "Software\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_APP_ID}" "pv" | |
| 155 | 新增: SetRegView 64 | |
| 156 | 新增: ${If} $0 == "" | |
| 157 | 新增: ${OrIf} $0 == "0.0.0.0" | |
| 158 | 新增: ${If} $1 == "" | |
| 159 | 新增: ${OrIf} $1 == "0.0.0.0" | |
| 160 | 新增: DetailPrint "Installing the bundled Microsoft WebView2 runtime..." | |
| 161 | 新增: ExecWait '"$StageDir\resources\runtime\MicrosoftEdgeWebView2RuntimeInstallerX64.exe" /silent /install' $0 | |
| 162 | 新增: ${If} $0 != 0 | |
| 163 | 新增: SetOutPath "$TEMP" | |
| 164 | 新增: RMDir /r "$StageDir" | |
| 165 | 新增: SetErrorLevel 2 | |
| 166 | 新增: Abort "Microsoft WebView2 installation failed ($0). Install the runtime and retry." | |
| 167 | 新增: ${EndIf} | |
| 168 | 新增: ${EndIf} | |
| 169 | 新增: ${EndIf} | |
| 170 | 新增: | |
| 171 | 新增: SetOutPath "$TEMP" | |
| 172 | 新增: StrCpy $BackupDir "" | |
| 173 | 新增: ${If} $ExistingInstall == "1" | |
| 174 | 新增: ${GetParent} "$INSTDIR" $0 | |
| 175 | 新增: GetTempFileName $BackupDir "$0" | |
| 176 | 新增: Delete "$BackupDir" | |
| 177 | 新增: ClearErrors | |
| 178 | 新增: Rename "$INSTDIR" "$BackupDir" | |
| 179 | 新增: ${If} ${Errors} | |
| 180 | 新增: RMDir /r "$StageDir" | |
| 181 | 新增: SetErrorLevel 2 | |
| 182 | 新增: Abort "Could not move the installed application. Quit Cage and retry." | |
| 183 | 新增: ${EndIf} | |
| 184 | 新增: ${Else} | |
| 185 | 新增: RMDir "$INSTDIR" | |
| 186 | 新增: ${EndIf} | |
| 187 | 新增: ClearErrors | |
| 188 | 新增: Rename "$StageDir" "$INSTDIR" | |
| 189 | 新增: ${If} ${Errors} | |
| 190 | 新增: ${If} $BackupDir != "" | |
| 191 | 新增: ClearErrors | |
| 192 | 新增: Rename "$BackupDir" "$INSTDIR" | |
| 193 | 新增: ${If} ${Errors} | |
| 194 | 新增: RMDir /r "$StageDir" | |
| 195 | 新增: SetErrorLevel 2 | |
| 196 | 新增: Abort "Installation failed. The previous application is preserved at $BackupDir; restore that folder before retrying." | |
| 197 | 新增: ${EndIf} | |
| 198 | 新增: ${EndIf} | |
| 199 | 新增: RMDir /r "$StageDir" | |
| 200 | 新增: SetErrorLevel 2 | |
| 201 | 新增: Abort "Could not install Cage. The previous installation has been restored." | |
| 202 | 新增: ${EndIf} | |
| 203 | 新增: ${If} $BackupDir != "" | |
| 204 | 新增: ; BackupDir came from the verified Cage installation above. User data lives elsewhere. | |
| 205 | 新增: RMDir /r "$BackupDir" | |
| 206 | 新增: ${EndIf} | |
| 207 | 新增: WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "Cage" | |
| 208 | 新增: WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}" | |
| 209 | 新增: WriteRegStr HKCU "${UNINSTALL_KEY}" "Publisher" "Cage contributors" | |
| 210 | 新增: WriteRegStr HKCU "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR" | |
| 211 | 新增: WriteRegStr HKCU "${UNINSTALL_KEY}" "UninstallString" '$\"$INSTDIR\Uninstall.exe$\"' | |
| 212 | 新增: WriteRegStr HKCU "${UNINSTALL_KEY}" "QuietUninstallString" '$\"$INSTDIR\Uninstall.exe$\" /S' | |
| 213 | 新增: WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\Cage.exe,0" | |
| 214 | 新增: WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1 | |
| 215 | 新增: WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1 | |
| 216 | 新增: CreateDirectory "$SMPROGRAMS\Cage" | |
| 217 | 新增: CreateShortcut "$SMPROGRAMS\Cage\Cage.lnk" "$INSTDIR\Cage.exe" | |
| 218 | 新增: CreateShortcut "$SMPROGRAMS\Cage\Uninstall Cage.lnk" "$INSTDIR\Uninstall.exe" | |
| 219 | 新增: SetErrorLevel 0 | |
| 220 | 新增:SectionEnd | |
| 221 | 新增: | |
| 222 | 新增:Function un.onInit | |
| 223 | 新增: SetShellVarContext current | |
| 224 | 新增: SetRegView 64 | |
| 225 | 新增: FileOpen $0 "$INSTDIR\Cage.install-id" r | |
| 226 | 新增: FileRead $0 $1 | |
| 227 | 新增: FileClose $0 | |
| 228 | 新增: ${If} $1 != "${APP_ID}" | |
| 229 | 新增: SetErrorLevel 2 | |
| 230 | 新增: Abort "This is not a Cage installation folder." | |
| 231 | 新增: ${EndIf} | |
| 232 | 新增: !insertmacro CheckStopped "Cage.exe" | |
| 233 | 新增: !insertmacro CheckStopped "resources\cage.exe" | |
| 234 | 新增: !insertmacro CheckStopped "resources\mihomo.exe" | |
| 235 | 新增: !insertmacro CheckStopped "resources\runtime\qemu\qemu-system-x86_64.exe" | |
| 236 | 新增:FunctionEnd | |
| 237 | 新增: | |
| 238 | 新增:Section "Uninstall" | |
| 239 | 新增: Delete "$SMPROGRAMS\Cage\Cage.lnk" | |
| 240 | 新增: Delete "$SMPROGRAMS\Cage\Uninstall Cage.lnk" | |
| 241 | 新增: RMDir "$SMPROGRAMS\Cage" | |
| 242 | 新增: DeleteRegKey HKCU "${UNINSTALL_KEY}" | |
| 243 | 新增: ; Delete only files shipped in this build. Preserve user-created files and all external data. | |
| 244 | 新增: !include "${UNINSTALL_MANIFEST}" | |
| 245 | 新增: Delete "$INSTDIR\Uninstall.exe" | |
| 246 | 新增: RMDir "$INSTDIR" | |
| 247 | 新增:SectionEnd | |
| @@ -0,0 +1,29 @@ | ||
| 1 | 新增:Cage for Windows 10 and Windows 11 (x64) | |
| 2 | 新增: | |
| 3 | 新增:Install Cage for the current Windows user, then open it from the Start menu. | |
| 4 | 新增:No Go, Node.js, .NET SDK, QEMU, OpenSSH or Clash installation is required. | |
| 5 | 新增:The installer includes the Microsoft WebView2 offline runtime installer. | |
| 6 | 新增: | |
| 7 | 新增:Requirements: Windows 10 22H2 (build 19045) or Windows 11, Intel/AMD 64-bit | |
| 8 | 新增:processor with hardware virtualization enabled, and Windows Hypervisor Platform. | |
| 9 | 新增:Enable Windows Hypervisor Platform in "Turn Windows features on or off", then | |
| 10 | 新增:restart Windows if Cage reports that the hypervisor is unavailable. | |
| 11 | 新增:Windows on ARM and 32-bit Windows are not supported by this package. | |
| 12 | 新增: | |
| 13 | 新增:In Cage, configure your own proxy and start the environment. Initial setup | |
| 14 | 新增:downloads the Linux image and development tools. Proxy service and Claude | |
| 15 | 新增:account are not included. Changes to shared projects affect the original files. | |
| 16 | 新增: | |
| 17 | 新增:Updates preserve the Cage configuration, virtual disk and project files. | |
| 18 | 新增:Stop the environment and quit Cage before running an installer manually. | |
| 19 | 新增:In-app updates stop the environment after your confirmation, verify the new | |
| 20 | 新增:installer and publisher, and restart the application after installation. | |
| 21 | 新增:Unsigned development builds cannot install automatic updates. | |
| 22 | 新增: | |
| 23 | 新增:Uninstall using Windows Settings > Apps > Installed apps (Windows 11) or | |
| 24 | 新增:Apps & features (Windows 10). Uninstall removes application files and shortcuts. | |
| 25 | 新增:It preserves user data in %USERPROFILE%\.claude-cage and all shared projects. | |
| 26 | 新增:Microsoft WebView2 is a shared runtime and is not removed by Cage uninstall. | |
| 27 | 新增: | |
| 28 | 新增:Getting started: https://github.com/Lee-xeo/Claude-Cage/blob/main/docs/windows.md | |
| 29 | 新增:Issues: https://github.com/Lee-xeo/Claude-Cage/issues | |
| @@ -0,0 +1,52 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "architecture": "amd64", | |
| 3 | 新增: "dotnet": { | |
| 4 | 新增: "runtimeVersion": "10.0.14" | |
| 5 | 新增: }, | |
| 6 | 新增: "mihomo": { | |
| 7 | 新增: "version": "v1.19.33", | |
| 8 | 新增: "file": "mihomo-windows-amd64-compatible-v1.19.33.zip", | |
| 9 | 新增: "url": "https://github.com/MetaCubeX/mihomo/releases/download/v1.19.33/mihomo-windows-amd64-compatible-v1.19.33.zip", | |
| 10 | 新增: "algorithm": "SHA256", | |
| 11 | 新增: "hash": "7aaf636a4f2172dcd8ec34ac4f52797b059195e5afd6409508c963e545f8864d", | |
| 12 | 新增: "source": "https://github.com/MetaCubeX/mihomo/archive/refs/tags/v1.19.33.tar.gz" | |
| 13 | 新增: }, | |
| 14 | 新增: "mihomoSource": { | |
| 15 | 新增: "version": "v1.19.33", | |
| 16 | 新增: "file": "mihomo-v1.19.33-source.tar.gz", | |
| 17 | 新增: "url": "https://github.com/MetaCubeX/mihomo/archive/refs/tags/v1.19.33.tar.gz", | |
| 18 | 新增: "algorithm": "SHA256", | |
| 19 | 新增: "hash": "e7c596b37ff27ec487d19b1920f73e0c97a78067ea35766530ee9659ade72711" | |
| 20 | 新增: }, | |
| 21 | 新增: "openssh": { | |
| 22 | 新增: "version": "10.4.0.0p1-Preview", | |
| 23 | 新增: "file": "OpenSSH-Win64.zip", | |
| 24 | 新增: "url": "https://github.com/PowerShell/Win32-OpenSSH/releases/download/10.4.0.0p1-Preview/OpenSSH-Win64.zip", | |
| 25 | 新增: "algorithm": "SHA256", | |
| 26 | 新增: "hash": "b67ff8becd203502190ec42ac7787c24c2cd3325ed7700485fe7a1c83d2a7957", | |
| 27 | 新增: "source": "https://github.com/PowerShell/openssh-portable" | |
| 28 | 新增: }, | |
| 29 | 新增: "webview2": { | |
| 30 | 新增: "version": "Evergreen snapshot 2026-11-01", | |
| 31 | 新增: "file": "MicrosoftEdgeWebView2RuntimeInstallerX64.exe", | |
| 32 | 新增: "url": "https://msedge.sf.dl.delivery.mp.microsoft.com/filestreamingservice/files/d5cc3c1c-bb59-4158-aedc-db0035e44466/MicrosoftEdgeWebView2RuntimeInstallerX64.exe", | |
| 33 | 新增: "algorithm": "SHA256", | |
| 34 | 新增: "hash": "62863f0f0611a16ccf124b4f15650c3b66624504eba74d7cde1e2ae5d951249b", | |
| 35 | 新增: "source": "https://developer.microsoft.com/en-us/microsoft-edge/webview2/" | |
| 36 | 新增: }, | |
| 37 | 新增: "qemu": { | |
| 38 | 新增: "version": "11.1.0", | |
| 39 | 新增: "file": "qemu-w64-setup-20260811.exe", | |
| 40 | 新增: "url": "https://qemu.weilnetz.de/w64/2026/qemu-w64-setup-20260811.exe", | |
| 41 | 新增: "algorithm": "SHA512", | |
| 42 | 新增: "hash": "5bcf9eed634e8575a37b74f445af41a2fe4106da512d0c30c368301d4c105037fdfab40a5287367a28a957624cddebbc8c07e16c88ab6634f554cdf3d16bf543", | |
| 43 | 新增: "source": "https://repo.or.cz/qemu/ar7.git/commit/e470268ff446ec56728215a987ed166d5ed8fb64" | |
| 44 | 新增: }, | |
| 45 | 新增: "qemuSource": { | |
| 46 | 新增: "repository": "https://repo.or.cz/qemu/ar7.git", | |
| 47 | 新增: "commit": "e470268ff446ec56728215a987ed166d5ed8fb64", | |
| 48 | 新增: "prefix": "qemu-e470268ff446ec56728215a987ed166d5ed8fb64/", | |
| 49 | 新增: "file": "qemu-e470268ff446ec56728215a987ed166d5ed8fb64-source.tar", | |
| 50 | 新增: "hash": "b16ca2d09d66de17269f4b85d7823e82e8a42c591fc7b75047047170d095da03" | |
| 51 | 新增: } | |
| 52 | 新增:} | |
| @@ -50,6 +50,7 @@ It runs inside the Lima hostagent, which with vz also runs the VM: a panic there | ||
| 50 | 50 | | `lima/0007-qemu-features-own-outputs` | lima-vm/lima | not sent | `inspectFeatures` ran its four help requests into the same buffers: each feature text held the earlier ones'. One buffer per request (`qemuHelp`). Test `TestInspectFeaturesOwnOutputs`. | |
| 51 | 51 | | `lima/0008-qemu-dgram-netdev` | lima-vm/lima | not sent; the issue to open at QEMU is the patch's header | Bug 22: QEMU gets the netstack through a datagram socketpair (`-netdev dgram`, `GVisorNetstackOpts.DgramConn`), as vz does; the `socket` netdev, and its unix socket listener, only for a QEMU older than 7.2, and Windows (the `stream` netdev has the bug too). Tests `TestDgramConn`, `TestDgramPair`, `TestFdDgramTemplate`; the netdev choice is covered by agent-vm's e2e. | |
| 52 | 52 | | `lima/0009-start-channels-buffered` | lima-vm/lima | not sent | `StartWithPaths` left the losing goroutine of its race blocked on an unbuffered send, for as long as the program lives. No test: it starts a hostagent. | |
| 53 | 新增:| `lima/0011-windows-native-usernet-socket` | lima-vm/lima | not sent | Opens the per-instance network control endpoint with its native filesystem path. Constructing `unix://C:\\...` fails URL parsing on Windows. `TestNetstackWindowsNativeSocketPaths` connects to both control and QEMU AF_UNIX listeners on Windows. | | |
| 53 | 54 | | `sshocker/0001-rooted-server-readonly-names` | lima-vm/sshocker | fork branch `readonly-names` | The builtin server serves only the mounted directory, and `ReadonlyNames`. | |
| 54 | 55 | | `sshocker/0002-expect-remove` | lima-vm/sshocker | fork branch `expect-remove` | `ExpectRemove`, for 0002 of Lima. | |
| 55 | 56 | | `sshocker/0003-append-fix` | lima-vm/sshocker | not sent | Bug 1. Tests `TestRootedOpenAppend`, `TestRootedOpenMode`. No pkg/sftp dependency: send first. | |
| @@ -0,0 +1,73 @@ | ||
| 1 | 新增:From: Cage maintainers | |
| 2 | 新增:Subject: [PATCH] usernet: listen on native socket paths without URL parsing | |
| 3 | 新增: | |
| 4 | 新增:On Windows an absolute socket path contains a drive letter and backslashes. | |
| 5 | 新增:Constructing unix://C:\\... treats the drive as a URL host and rejects the | |
| 6 | 新增:backslashes. The endpoint is always a Unix socket; pass the path directly to | |
| 7 | 新增:net.Listen, which supports AF_UNIX on Windows 10 1803 and newer. | |
| 8 | 新增: | |
| 9 | 新增:diff --git a/pkg/networks/usernet/gvproxy.go b/pkg/networks/usernet/gvproxy.go | |
| 10 | 新增:--- a/pkg/networks/usernet/gvproxy.go | |
| 11 | 新增:+++ b/pkg/networks/usernet/gvproxy.go | |
| 12 | 新增:@@ -20,7 +20,6 @@ import ( | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/balajiv113/fd" | |
| 16 | 新增:- "github.com/containers/gvisor-tap-vsock/pkg/transport" | |
| 17 | 新增: "github.com/containers/gvisor-tap-vsock/pkg/types" | |
| 18 | 新增: "github.com/containers/gvisor-tap-vsock/pkg/virtualnetwork" | |
| 19 | 新增: "github.com/miekg/dns" | |
| 20 | 新增:@@ -166,7 +165,7 @@ func run(ctx context.Context, g *errgroup.Group, configuration *types.Configuration | |
| 21 | 新增: return err | |
| 22 | 新增: } | |
| 23 | 新增: | |
| 24 | 新增:- ln, err := transport.Listen(fmt.Sprintf("unix://%s", opts.Endpoint)) | |
| 25 | 新增:+ ln, err := net.Listen("unix", opts.Endpoint) | |
| 26 | 新增: if err != nil { | |
| 27 | 新增: return err | |
| 28 | 新增: } | |
| 29 | 新增:diff --git a/pkg/networks/usernet/endpoint_windows_test.go b/pkg/networks/usernet/endpoint_windows_test.go | |
| 30 | 新增:new file mode 100644 | |
| 31 | 新增:--- /dev/null | |
| 32 | 新增:+++ b/pkg/networks/usernet/endpoint_windows_test.go | |
| 33 | 新增:@@ -0,0 +1,40 @@ | |
| 34 | 新增:+//go:build windows | |
| 35 | 新增:+ | |
| 36 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 37 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 38 | 新增:+ | |
| 39 | 新增:+package usernet | |
| 40 | 新增:+ | |
| 41 | 新增:+import ( | |
| 42 | 新增:+ "context" | |
| 43 | 新增:+ "net" | |
| 44 | 新增:+ "os" | |
| 45 | 新增:+ "path/filepath" | |
| 46 | 新增:+ "testing" | |
| 47 | 新增:+) | |
| 48 | 新增:+ | |
| 49 | 新增:+func TestNetstackWindowsNativeSocketPaths(t *testing.T) { | |
| 50 | 新增:+ // A drive letter, spaces and URL punctuation must remain a file path. | |
| 51 | 新增:+ dir, err := os.MkdirTemp("", "cage %23-") | |
| 52 | 新增:+ if err != nil { | |
| 53 | 新增:+ t.Fatal(err) | |
| 54 | 新增:+ } | |
| 55 | 新增:+ defer os.RemoveAll(dir) | |
| 56 | 新增:+ ctx, cancel := context.WithCancel(context.Background()) | |
| 57 | 新增:+ defer cancel() | |
| 58 | 新增:+ endpoint := filepath.Join(dir, "ep.sock") | |
| 59 | 新增:+ qemu := filepath.Join(dir, "qemu.sock") | |
| 60 | 新增:+ if err := StartGVisorNetstack(ctx, &GVisorNetstackOpts{ | |
| 61 | 新增:+ MTU: 1500, Endpoint: endpoint, QemuSocket: qemu, | |
| 62 | 新增:+ Subnet: "192.168.127.0/24", Async: true, | |
| 63 | 新增:+ }); err != nil { | |
| 64 | 新增:+ t.Fatal(err) | |
| 65 | 新增:+ } | |
| 66 | 新增:+ for _, path := range []string{endpoint, qemu} { | |
| 67 | 新增:+ conn, err := net.Dial("unix", path) | |
| 68 | 新增:+ if err != nil { | |
| 69 | 新增:+ t.Fatalf("cannot connect to native socket %q: %v", path, err) | |
| 70 | 新增:+ } | |
| 71 | 新增:+ conn.Close() | |
| 72 | 新增:+ } | |
| 73 | 新增:+} | |
| @@ -14,7 +14,7 @@ check_destination() { | ||
| 14 | 14 | local running_pids |
| 15 | 15 | running_pids="$(/usr/sbin/lsof -t "$target/Contents/MacOS/Cage" "$target/Contents/Resources/cage" 2>/dev/null || true)" |
| 16 | 16 | if [[ -n "$running_pids" ]]; then |
| 17 | 删除: echo 'Cage is running from this destination. Quit it, or choose a separate CAGE_BUILD_OUTPUT.' >&2; exit 1 | |
| 17 | 新增: echo 'Cage is running from this destination. Quit it before replacing the App.' >&2; exit 1 | |
| 18 | 18 | fi |
| 19 | 19 | } |
| 20 | 20 | check_destination "$app_destination" |
| @@ -37,7 +37,7 @@ install_stage='' | ||
| 37 | 37 | trap 'rm -rf "$build_stage"; if [[ -n "$install_stage" ]]; then rm -rf "$install_stage"; fi' EXIT |
| 38 | 38 | bundle="$build_stage/Cage.app" |
| 39 | 39 | mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources" |
| 40 | 删除:swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework WebKit -framework Security desktop/Cage.swift desktop/Updates.swift -o "$bundle/Contents/MacOS/Cage" | |
| 40 | 新增:swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework WebKit -framework Security -framework LocalAuthentication desktop/Cage.swift desktop/Updates.swift desktop/AccountDevice.swift -o "$bundle/Contents/MacOS/Cage" | |
| 41 | 41 | swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework Security desktop/Updates.swift desktop/UpdateInstaller.swift -o "$bundle/Contents/Resources/CageUpdateInstaller" |
| 42 | 42 | cp _output/bin/cage "$bundle/Contents/Resources/cage" |
| 43 | 43 | cp _output/proxy-core/mihomo "$bundle/Contents/Resources/mihomo" |
| @@ -74,10 +74,18 @@ PLIST | ||
| 74 | 74 | sign=(codesign --force --sign "$identity") |
| 75 | 75 | if [[ "$identity" != - ]]; then sign+=(--timestamp --options runtime); fi |
| 76 | 76 | "${sign[@]}" --entitlements third_party/lima/vz.entitlements "$bundle/Contents/Resources/cage" |
| 77 | 新增:account_signing=("${sign[@]}") | |
| 78 | 新增:if [[ -n "${CAGE_PROVISIONING_PROFILE:-}" ]]; then | |
| 79 | 新增: [[ "$identity" != - ]] || { echo 'Biometric provisioning requires a Developer ID signature.' >&2; exit 1; } | |
| 80 | 新增: signing_team="$(codesign -dv --verbose=4 "$bundle/Contents/Resources/cage" 2>&1 | sed -n 's/^TeamIdentifier=//p')" | |
| 81 | 新增: bash scripts/prepare-account-signing.sh "$CAGE_PROVISIONING_PROFILE" "$signing_team" "$build_stage/account.entitlements" | |
| 82 | 新增: cp "$CAGE_PROVISIONING_PROFILE" "$bundle/Contents/embedded.provisionprofile" | |
| 83 | 新增: account_signing+=(--entitlements "$build_stage/account.entitlements") | |
| 84 | 新增:fi | |
| 77 | 85 | "${sign[@]}" "$bundle/Contents/Resources/mihomo" |
| 78 | 86 | "${sign[@]}" "$bundle/Contents/Resources/CageUpdateInstaller" |
| 79 | 删除:"${sign[@]}" "$bundle/Contents/MacOS/Cage" | |
| 80 | 删除:"${sign[@]}" "$bundle" | |
| 87 | 新增:"${account_signing[@]}" "$bundle/Contents/MacOS/Cage" | |
| 88 | 新增:"${account_signing[@]}" "$bundle" | |
| 81 | 89 | codesign --verify --deep --strict --verbose=2 "$bundle" |
| 82 | 90 | # Keep the working App until the replacement has passed signature verification. |
| 83 | 91 | check_destination "$app_destination" |
| @@ -101,8 +109,12 @@ if [[ "${1:-}" == "--install" ]]; then | ||
| 101 | 109 | exit 1 |
| 102 | 110 | fi |
| 103 | 111 | printf 'Installed: %s/Applications/Cage.app\n' "$HOME" |
| 104 | 删除: node scripts/cleanup-apps.mjs --keep "$bundle" --keep "$HOME/Applications/Cage.app" \ | |
| 105 | 删除: --root "$PWD/_output" --root "$HOME/Applications" --root /Applications | |
| 112 | 新增: # An installed build has one launchable copy. Remove the staging build too, | |
| 113 | 新增: # along with historical validation copies, after the installed App verifies. | |
| 114 | 新增: codesign --verify --deep --strict --verbose=2 "$HOME/Applications/Cage.app" | |
| 115 | 新增: node scripts/cleanup-apps.mjs --keep "$HOME/Applications/Cage.app" \ | |
| 116 | 新增: --root "$bundle" --root "$PWD/_output" --root "$HOME/Applications" \ | |
| 117 | 新增: --root /Applications --root "$HOME/.claude-cage-validation" | |
| 106 | 118 | else |
| 107 | 119 | if [[ -z "${CAGE_BUILD_OUTPUT:-}" ]]; then |
| 108 | 120 | node scripts/cleanup-apps.mjs --keep "$bundle" --root "$PWD/_output" |
| @@ -0,0 +1,44 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:cd "$(dirname "$0")/.." | |
| 4 | 新增:[[ "$(uname -s)" == Linux && "$(uname -m)" == x86_64 ]] || { echo 'Build on x86_64 Linux (Debian 12 baseline).' >&2; exit 1; } | |
| 5 | 新增:case "${1:-}" in ''|--prebuilt-backend) ;; *) echo 'Usage: scripts/build-linux.sh [--prebuilt-backend]' >&2; exit 2 ;; esac | |
| 6 | 新增:version=$(tr -d '\r\n' < VERSION) | |
| 7 | 新增:[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]] || { echo 'Invalid VERSION.' >&2; exit 1; } | |
| 8 | 新增:pkg-config --atleast-version=2.40 webkit2gtk-4.1 | |
| 9 | 新增:pkg-config --exists gtk+-3.0 json-glib-1.0 | |
| 10 | 新增:bash scripts/fetch-linux-proxy-core.sh | |
| 11 | 新增:if [[ "${1:-}" != --prebuilt-backend ]]; then | |
| 12 | 新增: make cage GOOS=linux GOARCH=amd64 CGO_ENABLED=0 VERSION="$version" | |
| 13 | 新增:else | |
| 14 | 新增: # For constrained remote test hosts. The caller supplies the backend built | |
| 15 | 新增: # from this exact source tree, and npm licenses from a locked npm ci. | |
| 16 | 新增: [[ -x _output/bin/cage ]] || { echo 'Missing prebuilt Linux backend.' >&2; exit 1; } | |
| 17 | 新增: _output/bin/cage help >/dev/null | |
| 18 | 新增:fi | |
| 19 | 新增:mkdir -p _output/linux-amd64 | |
| 20 | 新增:stage=$(mktemp -d "$PWD/_output/linux-amd64/build.XXXXXX") | |
| 21 | 新增:trap 'rm -rf "$stage"' EXIT | |
| 22 | 新增:app="$stage/app" | |
| 23 | 新增:mkdir -p "$app/licenses/mihomo" | |
| 24 | 新增:cc -std=c11 -O2 -Wall -Wextra -Werror -Wno-deprecated-declarations \ | |
| 25 | 新增: "-DCAGE_VERSION=\"$version\"" desktop/linux/cage-desktop.c \ | |
| 26 | 新增: $(pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.1 json-glib-1.0) \ | |
| 27 | 新增: -o "$app/cage-desktop" | |
| 28 | 新增:install -m 755 _output/bin/cage "$app/cage" | |
| 29 | 新增:install -m 755 _output/linux-deps/mihomo "$app/mihomo" | |
| 30 | 新增:cp _output/linux-deps/{LICENSE,NOTICE} "$app/licenses/mihomo/" | |
| 31 | 新增:if [[ "${1:-}" == --prebuilt-backend && -d _output/linux-amd64/prebuilt-licenses ]]; then | |
| 32 | 新增: cp -a _output/linux-amd64/prebuilt-licenses/. "$app/licenses/" | |
| 33 | 新增:else | |
| 34 | 新增: node scripts/collect-app-licenses.mjs "$app/licenses" | |
| 35 | 新增:fi | |
| 36 | 新增:"$app/cage" help >/dev/null | |
| 37 | 新增:"$app/cage-desktop" --version | |
| 38 | 新增:"$app/cage-desktop" --self-test | |
| 39 | 新增:"$app/mihomo" -v | |
| 40 | 新增:printf '%s\n' "$version" > "$app/VERSION" | |
| 41 | 新增:# Build output only; installed files are changed exclusively by dpkg/apt. | |
| 42 | 新增:rm -rf _output/linux-amd64/app | |
| 43 | 新增:mv "$app" _output/linux-amd64/app | |
| 44 | 新增:printf 'Built: %s/_output/linux-amd64/app\n' "$PWD" | |
| @@ -0,0 +1,152 @@ | ||
| 1 | 新增:#requires -Version 7.0 | |
| 2 | 新增:[CmdletBinding()] | |
| 3 | 新增:param( | |
| 4 | 新增: [switch]$Release, | |
| 5 | 新增: [switch]$SkipUI, | |
| 6 | 新增: [string]$OutputDirectory, | |
| 7 | 新增: [string]$DependencyCache | |
| 8 | 新增:) | |
| 9 | 新增:. (Join-Path $PSScriptRoot 'windows-common.ps1') | |
| 10 | 新增:$repository = Split-Path $PSScriptRoot -Parent | |
| 11 | 新增:if (-not $OutputDirectory) { $OutputDirectory = Join-Path $repository '_output/windows-amd64/app' } | |
| 12 | 新增:if (-not $DependencyCache) { $DependencyCache = Join-Path $repository '_output/windows-deps' } | |
| 13 | 新增:$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory) | |
| 14 | 新增:if (Test-Path -LiteralPath (Join-Path $OutputDirectory 'Uninstall.exe')) { throw 'Do not build over an installed application. Choose a separate output directory and use the installer to upgrade.' } | |
| 15 | 新增:$version = Get-CageVersion $repository | |
| 16 | 新增:if ($Release -and (-not $IsWindows -or $env:CAGE_WINDOWS_CERT_SHA1 -notmatch '^[0-9A-Fa-f]{40}$')) { | |
| 17 | 新增: throw 'A release build requires Windows and CAGE_WINDOWS_CERT_SHA1 for a trusted code-signing certificate in the current user certificate store.' | |
| 18 | 新增:} | |
| 19 | 新增:$go = Get-BuildCommand @('go') | |
| 20 | 新增:$dotnet = Get-BuildCommand @('dotnet') | |
| 21 | 新增:$node = Get-BuildCommand @('node') | |
| 22 | 新增:$npm = Get-BuildCommand @('npm.cmd', 'npm') | |
| 23 | 新增:$sevenZip = Get-BuildCommand @('7z.exe', '7zz', '7z') | |
| 24 | 新增:$dependencies = Get-Content -LiteralPath (Join-Path $repository 'packaging/windows/dependencies.json') -Raw | ConvertFrom-Json | |
| 25 | 新增:$stage = Join-Path $repository ("_output/windows-build-" + [guid]::NewGuid().ToString('N')) | |
| 26 | 新增:$savedGoOS, $savedGoArch, $savedCGO = $env:GOOS, $env:GOARCH, $env:CGO_ENABLED | |
| 27 | 新增:New-Item -ItemType Directory -Path $stage -Force | Out-Null | |
| 28 | 新增:Push-Location $repository | |
| 29 | 新增:try { | |
| 30 | 新增: if (-not $SkipUI) { | |
| 31 | 新增: Invoke-BuildTool $npm @('--prefix', 'ui', 'ci', '--no-audit', '--no-fund') | |
| 32 | 新增: Invoke-BuildTool $npm @('run', '--prefix', 'ui', 'build') | |
| 33 | 新增: } | |
| 34 | 新增: $limaVersion = ((Get-Content 'third_party/SOURCES' | Where-Object { $_ -match '^lima\s' }) -split '\s+')[3] | |
| 35 | 新增: $assets = Join-Path $repository 'internal/limaembed/assets' | |
| 36 | 新增: $guest = Join-Path $assets 'lima-guestagent.Linux-x86_64' | |
| 37 | 新增: $env:GOOS = 'linux'; $env:GOARCH = 'amd64'; $env:CGO_ENABLED = '0' | |
| 38 | 新增: Invoke-BuildTool $go @('build', '-trimpath', '-ldflags', "-s -w -X github.com/lima-vm/lima/v2/pkg/version.Version=$limaVersion", '-o', $guest, 'github.com/lima-vm/lima/v2/cmd/lima-guestagent') | |
| 39 | 新增: $inputStream = [IO.File]::OpenRead($guest) | |
| 40 | 新增: $outputStream = [IO.File]::Create("$guest.gz") | |
| 41 | 新增: try { | |
| 42 | 新增: $gzip = [IO.Compression.GZipStream]::new($outputStream, [IO.Compression.CompressionLevel]::SmallestSize, $true) | |
| 43 | 新增: try { $inputStream.CopyTo($gzip) } finally { $gzip.Dispose() } | |
| 44 | 新增: } finally { $inputStream.Dispose(); $outputStream.Dispose() } | |
| 45 | 新增: Remove-Item -LiteralPath $guest | |
| 46 | 新增: New-Item -ItemType Directory -Path (Join-Path $assets 'templates') -Force | Out-Null | |
| 47 | 新增: Copy-Item 'third_party/lima/templates/*' (Join-Path $assets 'templates') -Recurse -Force | |
| 48 | 新增: $app = Join-Path $stage 'app' | |
| 49 | 新增: $resources = Join-Path $app 'resources' | |
| 50 | 新增: New-Item -ItemType Directory -Path $resources -Force | Out-Null | |
| 51 | 新增: New-Item -ItemType Directory -Path (Join-Path $resources 'runtime') -Force | Out-Null | |
| 52 | 新增: $env:GOOS = 'windows' | |
| 53 | 新增: $tags = 'external_hcs,external_wsl2,yq_noxml,yq_nolua,yq_noini,yq_nohcl,yq_notoml,yq_noprops,yq_nocsv,yq_nouri,yq_nobase64,yq_nosh,yq_noshell' | |
| 54 | 新增: $ldflags = "-s -w -X github.com/sylvinus/agent-vm/internal/version.Version=$version -X github.com/lima-vm/lima/v2/pkg/version.Version=$limaVersion" | |
| 55 | 新增: Invoke-BuildTool $go @('build', '-trimpath', '-tags', $tags, '-ldflags', $ldflags, '-o', (Join-Path $resources 'cage.exe'), './cmd/cage') | |
| 56 | 新增: Invoke-BuildTool $dotnet @('publish', 'desktop/windows/Cage.Windows.csproj', '-c', 'Release', '-r', 'win-x64', '--self-contained', 'true', | |
| 57 | 新增: '-p:EnableWindowsTargeting=true', '-p:PublishSingleFile=true', '-p:RestoreLockedMode=true', "-p:Version=$version", "-p:InformationalVersion=$version", '-o', $app) | |
| 58 | 新增: Get-ChildItem -LiteralPath $app -File | Where-Object { $_.Extension -in @('.pdb', '.xml') } | Remove-Item -Force | |
| 59 | 新增: $coreArchive = Get-VerifiedDependency $dependencies.mihomo $DependencyCache | |
| 60 | 新增: $core = Join-Path $stage 'mihomo' | |
| 61 | 新增: Expand-BuildArchive $coreArchive $core $sevenZip | |
| 62 | 新增: $coreExe = @(Get-ChildItem -LiteralPath $core -Filter '*.exe' -Recurse) | |
| 63 | 新增: if ($coreExe.Count -ne 1) { throw 'Unexpected Mihomo archive layout.' } | |
| 64 | 新增: Copy-Item -LiteralPath $coreExe[0].FullName -Destination (Join-Path $resources 'mihomo.exe') | |
| 65 | 新增: $sshArchive = Get-VerifiedDependency $dependencies.openssh $DependencyCache | |
| 66 | 新增: $ssh = Join-Path $stage 'openssh' | |
| 67 | 新增: Expand-BuildArchive $sshArchive $ssh $sevenZip | |
| 68 | 新增: $sshTarget = Join-Path $resources 'runtime/openssh' | |
| 69 | 新增: Copy-Item -LiteralPath (Join-Path $ssh 'OpenSSH-Win64') -Destination $sshTarget -Recurse | |
| 70 | 新增: # No SSH service is installed. Only the client is used by Cage/Lima. | |
| 71 | 新增: foreach ($serverFile in @('sshd.exe', 'sshd-session.exe', 'sshd-auth.exe', 'install-sshd.ps1', 'uninstall-sshd.ps1')) { | |
| 72 | 新增: Remove-Item -LiteralPath (Join-Path $sshTarget $serverFile) -Force -ErrorAction SilentlyContinue | |
| 73 | 新增: } | |
| 74 | 新增: $qemuArchive = Get-VerifiedDependency $dependencies.qemu $DependencyCache | |
| 75 | 新增: $qemuTarget = Join-Path $resources 'runtime/qemu' | |
| 76 | 新增: Expand-BuildArchive $qemuArchive $qemuTarget $sevenZip | |
| 77 | 新增: # Ship the x64 VM only, with its original firmware, DLLs and notices. | |
| 78 | 新增: Get-ChildItem -LiteralPath $qemuTarget -Filter 'qemu-system-*.exe' | Where-Object { $_.Name -ne 'qemu-system-x86_64.exe' } | Remove-Item -Force | |
| 79 | 新增: Get-ChildItem -LiteralPath (Join-Path $qemuTarget 'share') -File | | |
| 80 | 新增: Where-Object { $_.Name -match '^edk2-(?:aarch64|arm|loongarch64|riscv)-.*\.fd$' } | Remove-Item -Force | |
| 81 | 新增: foreach ($file in @('qemu-system-x86_64.exe', 'qemu-img.exe')) { | |
| 82 | 新增: if (-not (Test-Path -LiteralPath (Join-Path $qemuTarget $file))) { throw "QEMU archive lacks $file" } | |
| 83 | 新增: } | |
| 84 | 新增: Remove-Item -LiteralPath (Join-Path $qemuTarget '$PLUGINSDIR') -Recurse -Force -ErrorAction SilentlyContinue | |
| 85 | 新增: Remove-Item -LiteralPath (Join-Path $qemuTarget 'qemu-uninstall.exe') -Force -ErrorAction SilentlyContinue | |
| 86 | 新增: $webviewArchive = Get-VerifiedDependency $dependencies.webview2 $DependencyCache | |
| 87 | 新增: Copy-Item -LiteralPath $webviewArchive -Destination (Join-Path $resources 'runtime/MicrosoftEdgeWebView2RuntimeInstallerX64.exe') | |
| 88 | 新增: Invoke-BuildTool $node @('scripts/collect-app-licenses.mjs', (Join-Path $resources 'licenses')) | |
| 89 | 新增: $coreSourceArchive = Get-VerifiedDependency $dependencies.mihomoSource $DependencyCache | |
| 90 | 新增: $coreSource = Join-Path $stage 'mihomo-source' | |
| 91 | 新增: Expand-BuildArchive $coreSourceArchive $coreSource $sevenZip | |
| 92 | 新增: $coreTar = @(Get-ChildItem -LiteralPath $coreSource -Filter '*.tar') | |
| 93 | 新增: if ($coreTar.Count -ne 1) { throw 'Unexpected Mihomo source archive layout.' } | |
| 94 | 新增: Expand-BuildArchive $coreTar[0].FullName $coreSource $sevenZip | |
| 95 | 新增: $coreLicense = Join-Path $coreSource ("mihomo-" + $dependencies.mihomo.version.TrimStart('v') + '/LICENSE') | |
| 96 | 新增: if (-not (Test-Path -LiteralPath $coreLicense -PathType Leaf)) { throw 'Mihomo source license is missing.' } | |
| 97 | 新增: $coreNotices = Join-Path $resources 'licenses/mihomo' | |
| 98 | 新增: New-Item -ItemType Directory -Path $coreNotices -Force | Out-Null | |
| 99 | 新增: Copy-Item -LiteralPath $coreLicense -Destination (Join-Path $coreNotices 'LICENSE') | |
| 100 | 新增: [IO.File]::WriteAllText((Join-Path $coreNotices 'NOTICE'), "Mihomo $($dependencies.mihomo.version), unmodified separate executable.`nSource: $($dependencies.mihomo.source)`nLicense: GPL-3.0; corresponding source accompanies the installer.`n") | |
| 101 | 新增: # Runtime packs and WebView2 are absent from the frontend license collector. | |
| 102 | 新增: $resolvedAssets = Get-Content -LiteralPath 'desktop/windows/obj/project.assets.json' -Raw | ConvertFrom-Json | |
| 103 | 新增: $nuget = @($resolvedAssets.packageFolders.PSObject.Properties.Name)[0] | |
| 104 | 新增: $runtimeVersion = $dependencies.dotnet.runtimeVersion | |
| 105 | 新增: $runtimePacks = @($resolvedAssets.project.frameworks.PSObject.Properties.Value.downloadDependencies | | |
| 106 | 新增: Where-Object { $_.name -in @('Microsoft.NETCore.App.Runtime.win-x64', 'Microsoft.WindowsDesktop.App.Runtime.win-x64') }) | |
| 107 | 新增: if ($runtimePacks.Count -ne 2 -or @($runtimePacks | Where-Object { $_.version -ne "[$runtimeVersion, $runtimeVersion]" }).Count -ne 0) { | |
| 108 | 新增: throw 'Resolved .NET runtime differs from packaging/windows/dependencies.json. Use SDK 10.0.403 or review and update the runtime pin.' | |
| 109 | 新增: } | |
| 110 | 新增: $webviewVersion = ((Get-Content -LiteralPath 'desktop/windows/packages.lock.json' -Raw | ConvertFrom-Json).dependencies.PSObject.Properties.Value | | |
| 111 | 新增: ForEach-Object { $_.PSObject.Properties } | Where-Object { $_.Name -eq 'Microsoft.Web.WebView2' } | Select-Object -First 1).Value.resolved | |
| 112 | 新增: foreach ($package in @("microsoft.netcore.app.runtime.win-x64/$runtimeVersion", "microsoft.windowsdesktop.app.runtime.win-x64/$runtimeVersion", "microsoft.web.webview2/$webviewVersion")) { | |
| 113 | 新增: $source = Join-Path $nuget $package | |
| 114 | 新增: $target = Join-Path $resources "licenses/nuget/$package" | |
| 115 | 新增: New-Item -ItemType Directory -Path $target -Force | Out-Null | |
| 116 | 新增: $notices = @(Get-ChildItem -LiteralPath $source -File | Where-Object { $_.Name -match '^(LICENSE|NOTICE|THIRD.?PARTY)' }) | |
| 117 | 新增: if ($notices.Count -eq 0) { throw "Missing runtime license: $package" } | |
| 118 | 新增: $notices | Copy-Item -Destination $target | |
| 119 | 新增: } | |
| 120 | 新增: Copy-Item -LiteralPath 'packaging/windows/dependencies.json' -Destination (Join-Path $resources 'dependencies.json') | |
| 121 | 新增: Copy-Item -LiteralPath 'packaging/windows/README.txt' -Destination (Join-Path $app 'README.txt') | |
| 122 | 新增: Copy-Item -LiteralPath 'LICENSE' -Destination (Join-Path $app 'LICENSE.txt') | |
| 123 | 新增: [IO.File]::WriteAllText((Join-Path $app 'Cage.install-id'), 'io.github.lee-xeo.claude-cage') | |
| 124 | 新增: [IO.File]::WriteAllText((Join-Path $app 'version.txt'), $version) | |
| 125 | 新增: if ($Release) { | |
| 126 | 新增: $signTool = Get-SigningTool | |
| 127 | 新增: foreach ($file in @('Cage.exe', 'resources/cage.exe', 'resources/mihomo.exe')) { Sign-CageFile (Join-Path $app $file) $signTool } | |
| 128 | 新增: } else { | |
| 129 | 新增: [IO.File]::WriteAllText((Join-Path $app 'DEVELOPMENT-BUILD.txt'), "Unsigned development build. Automatic update installation is disabled. Windows 10/11 runtime acceptance is still required.`n") | |
| 130 | 新增: } | |
| 131 | 新增: $previousOutput = $null | |
| 132 | 新增: if (Test-Path -LiteralPath $OutputDirectory) { | |
| 133 | 新增: $marker = Join-Path $OutputDirectory 'Cage.install-id' | |
| 134 | 新增: if (-not (Test-Path -LiteralPath $marker) -or (Get-Content -LiteralPath $marker -Raw) -ne 'io.github.lee-xeo.claude-cage') { | |
| 135 | 新增: throw 'Output directory exists and is not a Cage build.' | |
| 136 | 新增: } | |
| 137 | 新增: $previousOutput = $OutputDirectory + '.previous-' + [guid]::NewGuid().ToString('N') | |
| 138 | 新增: Move-Item -LiteralPath $OutputDirectory -Destination $previousOutput | |
| 139 | 新增: } | |
| 140 | 新增: New-Item -ItemType Directory -Path (Split-Path $OutputDirectory -Parent) -Force | Out-Null | |
| 141 | 新增: try { Move-Item -LiteralPath $app -Destination $OutputDirectory } | |
| 142 | 新增: catch { | |
| 143 | 新增: if ($previousOutput -and -not (Test-Path -LiteralPath $OutputDirectory)) { Move-Item -LiteralPath $previousOutput -Destination $OutputDirectory } | |
| 144 | 新增: throw | |
| 145 | 新增: } | |
| 146 | 新增: if ($previousOutput) { Remove-Item -LiteralPath $previousOutput -Recurse -Force } | |
| 147 | 新增: Write-Host "Built Windows x64 application: $OutputDirectory" | |
| 148 | 新增:} finally { | |
| 149 | 新增: Pop-Location | |
| 150 | 新增: $env:GOOS = $savedGoOS; $env:GOARCH = $savedGoArch; $env:CGO_ENABLED = $savedCGO | |
| 151 | 新增: if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } | |
| 152 | 新增:} | |
| @@ -0,0 +1,21 @@ | ||
| 1 | 新增:// Inspect presence only. Never print or persist credential values. | |
| 2 | 新增:const required = [ | |
| 3 | 新增: 'CAGE_MACOS_P12_BASE64', 'CAGE_MACOS_P12_PASSWORD', 'CAGE_MACOS_SIGNING_IDENTITY', | |
| 4 | 新增: 'CAGE_MACOS_NOTARY_KEY_BASE64', 'CAGE_MACOS_NOTARY_KEY_ID', 'CAGE_MACOS_NOTARY_ISSUER_ID', | |
| 5 | 新增: 'CAGE_WINDOWS_PFX_BASE64', 'CAGE_WINDOWS_PFX_PASSWORD', | |
| 6 | 新增: 'CAGE_WINDOWS_QEMU_SOURCE_URL', 'CAGE_WINDOWS_QEMU_SOURCE_SHA256', | |
| 7 | 新增:]; | |
| 8 | 新增:const missing = required.filter(name => !process.env[name]?.trim()); | |
| 9 | 新增:if (missing.length) { | |
| 10 | 新增: console.error(`Configure these cage-release environment secrets/variables before requesting a release:\n${missing.join('\n')}`); | |
| 11 | 新增: process.exitCode = 1; | |
| 12 | 新增:} else { | |
| 13 | 新增: let source; | |
| 14 | 新增: try { source = new URL(process.env.CAGE_WINDOWS_QEMU_SOURCE_URL); } | |
| 15 | 新增: catch { throw new Error('Reviewed QEMU source requires a valid public HTTPS URL.'); } | |
| 16 | 新增: if (source.protocol !== 'https:' || source.username || source.password || source.search || source.hash || !/^[0-9a-f]{64}$/i.test(process.env.CAGE_WINDOWS_QEMU_SOURCE_SHA256)) { | |
| 17 | 新增: throw new Error('Reviewed QEMU source requires a credential-free HTTPS URL and SHA-256.'); | |
| 18 | 新增: } | |
| 19 | 新增: if (!process.env.CAGE_MACOS_SIGNING_IDENTITY.startsWith('Developer ID Application:')) throw new Error('macOS releases require a Developer ID Application identity.'); | |
| 20 | 新增: console.log('Release configuration is present. Platform jobs will verify the credentials, signatures and corresponding sources.'); | |
| 21 | 新增:} | |
| @@ -0,0 +1,120 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:# Keep signing material in a temporary CI keychain, including on failure. | |
| 3 | 新增:set +x | |
| 4 | 新增:set -euo pipefail | |
| 5 | 新增:cd "$(dirname "$0")/.." | |
| 6 | 新增: | |
| 7 | 新增:usage() { echo 'Usage: scripts/ci-macos-signing.sh run|cleanup' >&2; } | |
| 8 | 新增:case "${1:-}" in run|cleanup) ;; *) usage; exit 2 ;; esac | |
| 9 | 新增:[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'Apple Silicon macOS is required.' >&2; exit 1; } | |
| 10 | 新增:[[ "${GITHUB_ACTIONS:-}" == true && -n "${RUNNER_TEMP:-}" && -d "$RUNNER_TEMP" ]] || { | |
| 11 | 新增: echo 'This helper is restricted to a GitHub Actions runner.' >&2; exit 1; | |
| 12 | 新增:} | |
| 13 | 新增: | |
| 14 | 新增:cleanup() { | |
| 15 | 新增: local state="${CAGE_MACOS_SIGNING_STATE:-}" keychain failed=0 | |
| 16 | 新增: [[ -n "$state" ]] || return 0 | |
| 17 | 新增: case "$state" in "$RUNNER_TEMP"/cage-macos-signing.*) ;; *) echo 'Refusing an unexpected signing state directory.' >&2; return 1 ;; esac | |
| 18 | 新增: [[ -d "$state" && ! -L "$state" ]] || return 0 | |
| 19 | 新增: [[ -f "$state/owned-by-cage-ci" ]] || { echo 'Signing state marker is missing.' >&2; return 1; } | |
| 20 | 新增: keychain="$state/signing.keychain-db" | |
| 21 | 新增: if [[ -f "$state/original-keychains" ]]; then | |
| 22 | 新增: local originals=() entry | |
| 23 | 新增: while IFS= read -r entry; do | |
| 24 | 新增: [[ -n "$entry" ]] && originals+=("$entry") | |
| 25 | 新增: done < "$state/original-keychains" | |
| 26 | 新增: if [[ ${#originals[@]} -gt 0 ]]; then | |
| 27 | 新增: security list-keychains -d user -s "${originals[@]}" || failed=1 | |
| 28 | 新增: else | |
| 29 | 新增: security list-keychains -d user -s || failed=1 | |
| 30 | 新增: fi | |
| 31 | 新增: fi | |
| 32 | 新增: if [[ -f "$keychain" ]]; then security delete-keychain "$keychain" || failed=1; fi | |
| 33 | 新增: rm -f "$state/certificate.p12" "$state/notary.p8" "$state/Cage.provisionprofile" | |
| 34 | 新增: # Retain only cleanup state if Security.framework needs the workflow's | |
| 35 | 新增: # always() step to retry restoring the search list or deleting the keychain. | |
| 36 | 新增: if [[ "$failed" == 0 ]]; then rm -rf "$state"; fi | |
| 37 | 新增: return "$failed" | |
| 38 | 新增:} | |
| 39 | 新增:if [[ "$1" == cleanup ]]; then cleanup; exit; fi | |
| 40 | 新增: | |
| 41 | 新增:for required in CAGE_MACOS_P12_BASE64 CAGE_MACOS_P12_PASSWORD CAGE_MACOS_SIGNING_IDENTITY \ | |
| 42 | 新增: CAGE_MACOS_NOTARY_KEY_BASE64 CAGE_MACOS_NOTARY_KEY_ID CAGE_MACOS_NOTARY_ISSUER_ID; do | |
| 43 | 新增: [[ -n "${!required:-}" ]] || { printf 'Missing cage-release secret: %s\n' "$required" >&2; exit 1; } | |
| 44 | 新增:done | |
| 45 | 新增:[[ -n "${GITHUB_ENV:-}" ]] || { echo 'GITHUB_ENV is required for the final cleanup step.' >&2; exit 1; } | |
| 46 | 新增:umask 077 | |
| 47 | 新增:CAGE_MACOS_SIGNING_STATE="$(mktemp -d "$RUNNER_TEMP/cage-macos-signing.XXXXXX")" | |
| 48 | 新增:export CAGE_MACOS_SIGNING_STATE | |
| 49 | 新增:: > "$CAGE_MACOS_SIGNING_STATE/owned-by-cage-ci" | |
| 50 | 新增:finish() { | |
| 51 | 新增: local status=$? | |
| 52 | 新增: trap - EXIT | |
| 53 | 新增: if ! cleanup; then | |
| 54 | 新增: echo 'Temporary signing cleanup did not fully complete.' >&2 | |
| 55 | 新增: [[ "$status" != 0 ]] || status=1 | |
| 56 | 新增: fi | |
| 57 | 新增: exit "$status" | |
| 58 | 新增:} | |
| 59 | 新增:trap finish EXIT | |
| 60 | 新增:trap 'exit 130' INT | |
| 61 | 新增:trap 'exit 143' TERM | |
| 62 | 新增:printf 'CAGE_MACOS_SIGNING_STATE=%s\n' "$CAGE_MACOS_SIGNING_STATE" >> "$GITHUB_ENV" | |
| 63 | 新增: | |
| 64 | 新增:# Preserve the runner's search list. Never replace its default keychain. | |
| 65 | 新增:security list-keychains -d user > "$CAGE_MACOS_SIGNING_STATE/original-keychains.raw" | |
| 66 | 新增:sed -E 's/^[[:space:]]*"(.*)"[[:space:]]*$/\1/' \ | |
| 67 | 新增: "$CAGE_MACOS_SIGNING_STATE/original-keychains.raw" > "$CAGE_MACOS_SIGNING_STATE/original-keychains" | |
| 68 | 新增:keychain="$CAGE_MACOS_SIGNING_STATE/signing.keychain-db" | |
| 69 | 新增:keychain_password="$(openssl rand -hex 32)" | |
| 70 | 新增:certificate="$CAGE_MACOS_SIGNING_STATE/certificate.p12" | |
| 71 | 新增:notary_key="$CAGE_MACOS_SIGNING_STATE/notary.p8" | |
| 72 | 新增:printf '%s' "$CAGE_MACOS_P12_BASE64" | base64 --decode > "$certificate" | |
| 73 | 新增:printf '%s' "$CAGE_MACOS_NOTARY_KEY_BASE64" | base64 --decode > "$notary_key" | |
| 74 | 新增:security create-keychain -p "$keychain_password" "$keychain" | |
| 75 | 新增:security set-keychain-settings -lut 7200 "$keychain" | |
| 76 | 新增:security unlock-keychain -p "$keychain_password" "$keychain" | |
| 77 | 新增:security import "$certificate" -P "$CAGE_MACOS_P12_PASSWORD" -t cert -f pkcs12 -k "$keychain" \ | |
| 78 | 新增: -T /usr/bin/codesign -T /usr/bin/security | |
| 79 | 新增:security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$keychain_password" "$keychain" > /dev/null | |
| 80 | 新增: | |
| 81 | 新增:original_keychains=() | |
| 82 | 新增:while IFS= read -r entry; do [[ -n "$entry" ]] && original_keychains+=("$entry"); done \ | |
| 83 | 新增: < "$CAGE_MACOS_SIGNING_STATE/original-keychains" | |
| 84 | 新增:if [[ ${#original_keychains[@]} -gt 0 ]]; then | |
| 85 | 新增: security list-keychains -d user -s "$keychain" "${original_keychains[@]}" | |
| 86 | 新增:else | |
| 87 | 新增: security list-keychains -d user -s "$keychain" | |
| 88 | 新增:fi | |
| 89 | 新增:# Resolve the selected Developer ID certificate inside this keychain only. | |
| 90 | 新增:# The build receives its fingerprint, so another keychain cannot satisfy it. | |
| 91 | 新增:identity='' | |
| 92 | 新增:while IFS= read -r entry; do | |
| 93 | 新增: [[ "$entry" == *'"Developer ID Application: '* ]] || continue | |
| 94 | 新增: fingerprint="$(printf '%s\n' "$entry" | awk '{ print $2 }')" | |
| 95 | 新增: [[ "$fingerprint" =~ ^[[:xdigit:]]{40}$ ]] || continue | |
| 96 | 新增: if [[ "$CAGE_MACOS_SIGNING_IDENTITY" == "$fingerprint" || "$entry" == *"\"$CAGE_MACOS_SIGNING_IDENTITY\""* ]]; then | |
| 97 | 新增: [[ -z "$identity" ]] || { echo 'More than one Developer ID certificate matches the signing identity.' >&2; exit 1; } | |
| 98 | 新增: identity="$fingerprint" | |
| 99 | 新增: fi | |
| 100 | 新增:done < <(security find-identity -v -p codesigning "$keychain") | |
| 101 | 新增:[[ -n "$identity" ]] || { echo 'The requested Developer ID Application identity is not present in the temporary keychain.' >&2; exit 1; } | |
| 102 | 新增: | |
| 103 | 新增:export CAGE_SIGNING_IDENTITY="$identity" | |
| 104 | 新增:export CAGE_NOTARY_PROFILE=Cage-CI | |
| 105 | 新增:export CAGE_NOTARY_KEYCHAIN="$keychain" | |
| 106 | 新增:xcrun notarytool store-credentials "$CAGE_NOTARY_PROFILE" --keychain "$keychain" \ | |
| 107 | 新增: --key "$notary_key" --key-id "$CAGE_MACOS_NOTARY_KEY_ID" --issuer "$CAGE_MACOS_NOTARY_ISSUER_ID" | |
| 108 | 新增:unset CAGE_PROVISIONING_PROFILE CAGE_BUILD_OUTPUT | |
| 109 | 新增:if [[ -n "${CAGE_MACOS_PROVISIONING_PROFILE_BASE64:-}" ]]; then | |
| 110 | 新增: export CAGE_PROVISIONING_PROFILE="$CAGE_MACOS_SIGNING_STATE/Cage.provisionprofile" | |
| 111 | 新增: printf '%s' "$CAGE_MACOS_PROVISIONING_PROFILE_BASE64" | base64 --decode > "$CAGE_PROVISIONING_PROFILE" | |
| 112 | 新增:fi | |
| 113 | 新增:rm -f "$certificate" "$notary_key" | |
| 114 | 新增:unset CAGE_MACOS_P12_BASE64 CAGE_MACOS_P12_PASSWORD CAGE_MACOS_SIGNING_IDENTITY \ | |
| 115 | 新增: CAGE_MACOS_NOTARY_KEY_BASE64 CAGE_MACOS_NOTARY_KEY_ID CAGE_MACOS_NOTARY_ISSUER_ID \ | |
| 116 | 新增: CAGE_MACOS_PROVISIONING_PROFILE_BASE64 keychain_password | |
| 117 | 新增: | |
| 118 | 新增:bash scripts/package-macos.sh | |
| 119 | 新增:version="$(tr -d '\r\n' < VERSION)" | |
| 120 | 新增:bash scripts/verify-macos-release.sh "$PWD/_output/releases/$version" | |
| @@ -0,0 +1,85 @@ | ||
| 1 | 新增:#requires -Version 7.0 | |
| 2 | 新增:# CI orchestration only. Builds the checked-out version and never publishes it. | |
| 3 | 新增:[CmdletBinding()] | |
| 4 | 新增:param([switch]$Release) | |
| 5 | 新增:. (Join-Path $PSScriptRoot 'windows-common.ps1') | |
| 6 | 新增:if (-not $IsWindows) { throw 'This CI entry point requires a disposable Windows runner.' } | |
| 7 | 新增:if ($env:CAGE_BUILD_REF -notmatch '^[0-9A-Fa-f]{40}$') { throw 'CAGE_BUILD_REF must be a complete commit SHA.' } | |
| 8 | 新增:$repository = Split-Path $PSScriptRoot -Parent | |
| 9 | 新增:Push-Location $repository | |
| 10 | 新增:$pfx = $null | |
| 11 | 新增:$certificate = $null | |
| 12 | 新增:$certificates = @() | |
| 13 | 新增:$qemuSource = $null | |
| 14 | 新增:$savedPath = $env:PATH | |
| 15 | 新增:$savedCertificate = $env:CAGE_WINDOWS_CERT_SHA1 | |
| 16 | 新增:try { | |
| 17 | 新增: $actual = (& git rev-parse HEAD).Trim() | |
| 18 | 新增: if ($LASTEXITCODE -ne 0 -or $actual -ne $env:CAGE_BUILD_REF) { throw 'Checkout differs from the requested commit.' } | |
| 19 | 新增: if ($Release) { | |
| 20 | 新增: if ($env:GITHUB_EVENT_NAME -ne 'workflow_dispatch') { throw 'Release candidates require an explicitly dispatched release workflow.' } | |
| 21 | 新增: if (-not $env:CAGE_WINDOWS_PFX_BASE64 -or -not $env:CAGE_WINDOWS_PFX_PASSWORD) { | |
| 22 | 新增: throw 'Configure CAGE_WINDOWS_PFX_BASE64 and CAGE_WINDOWS_PFX_PASSWORD in the cage-release environment.' | |
| 23 | 新增: } | |
| 24 | 新增: $sourceUri = $null | |
| 25 | 新增: if (-not [Uri]::TryCreate($env:CAGE_WINDOWS_QEMU_SOURCE_URL, [UriKind]::Absolute, [ref]$sourceUri) -or | |
| 26 | 新增: $sourceUri.Scheme -ne 'https' -or $sourceUri.UserInfo -or $sourceUri.Query -or $sourceUri.Fragment -or | |
| 27 | 新增: $env:CAGE_WINDOWS_QEMU_SOURCE_SHA256 -notmatch '^[0-9A-Fa-f]{64}$') { | |
| 28 | 新增: throw 'Configure CAGE_WINDOWS_QEMU_SOURCE_URL (HTTPS) and CAGE_WINDOWS_QEMU_SOURCE_SHA256 for the reviewed complete source archive.' | |
| 29 | 新增: } | |
| 30 | 新增: $extension = [IO.Path]::GetExtension($sourceUri.AbsolutePath).ToLowerInvariant() | |
| 31 | 新增: if ($extension -notin @('.zip', '.7z', '.tar', '.gz', '.xz', '.bz2', '.zst')) { | |
| 32 | 新增: throw 'The reviewed source URL must name a ZIP, 7z, tar or compressed tar archive.' | |
| 33 | 新增: } | |
| 34 | 新增: $qemuSource = Join-Path $env:RUNNER_TEMP ('qemu-windows-source-' + [guid]::NewGuid().ToString('N') + $extension) | |
| 35 | 新增: Invoke-WebRequest -Uri $sourceUri -OutFile $qemuSource -TimeoutSec 600 -MaximumRedirection 5 | |
| 36 | 新增: if ((Get-FileHash -LiteralPath $qemuSource -Algorithm SHA256).Hash -ne $env:CAGE_WINDOWS_QEMU_SOURCE_SHA256) { | |
| 37 | 新增: throw 'Reviewed corresponding-source archive checksum mismatch.' | |
| 38 | 新增: } | |
| 39 | 新增: $pfx = Join-Path $env:RUNNER_TEMP ('cage-signing-' + [guid]::NewGuid().ToString('N') + '.pfx') | |
| 40 | 新增: [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:CAGE_WINDOWS_PFX_BASE64)) | |
| 41 | 新增: $password = ConvertTo-SecureString $env:CAGE_WINDOWS_PFX_PASSWORD -AsPlainText -Force | |
| 42 | 新增: $certificates = @(Import-PfxCertificate -FilePath $pfx -CertStoreLocation Cert:\CurrentUser\My -Password $password) | |
| 43 | 新增: Remove-Item -LiteralPath $pfx -Force | |
| 44 | 新增: $signers = @($certificates | Where-Object { | |
| 45 | 新增: $_.HasPrivateKey -and @($_.EnhancedKeyUsageList | Where-Object { $_.ObjectId -eq '1.3.6.1.5.5.7.3.3' }).Count -gt 0 | |
| 46 | 新增: }) | |
| 47 | 新增: if ($signers.Count -ne 1) { throw 'PFX must contain exactly one code-signing certificate with its private key.' } | |
| 48 | 新增: $certificate = $signers[0] | |
| 49 | 新增: $env:CAGE_WINDOWS_CERT_SHA1 = $certificate.Thumbprint | |
| 50 | 新增: Remove-Item Env:CAGE_WINDOWS_PFX_BASE64, Env:CAGE_WINDOWS_PFX_PASSWORD | |
| 51 | 新增: } | |
| 52 | 新增: | |
| 53 | 新增: & (Join-Path $PSScriptRoot 'install-nsis.ps1') -Destination $env:RUNNER_TEMP | |
| 54 | 新增: $env:PATH = (Join-Path $env:RUNNER_TEMP 'nsis-3.13') + [IO.Path]::PathSeparator + $env:PATH | |
| 55 | 新增: Invoke-BuildTool 'node' @('scripts/check-version.mjs') | |
| 56 | 新增: & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release | |
| 57 | 新增: Invoke-BuildTool 'dotnet' @('run', '--project', 'desktop/windows.tests/Cage.Windows.Tests.csproj') | |
| 58 | 新增: Invoke-BuildTool 'go' @('test', './internal/workbench', './internal/appupdate', './internal/host', './internal/managedproxy', './internal/env', './internal/paths', './internal/mounts') | |
| 59 | 新增: Invoke-BuildTool 'go' @('test', './internal/cage', '-run', 'Test(Gate|ProxyRevision|ConfigChange|JobStop|CONNECT|SOCKS|DNS|RejectHostLAN|Credentials|ProxyHostname|SafetyReport|Renew)') | |
| 60 | 新增: Invoke-BuildTool 'go' @('test', './internal/vm', '-run', 'Test(NetworkConfined|WindowsQEMUIdentity)') | |
| 61 | 新增: Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/networks/usernet', '-run', 'TestNetstackWindowsNativeSocketPaths') | |
| 62 | 新增: Invoke-BuildTool 'go' @('vet', './cmd/cage', './internal/cage', './internal/workbench', './internal/appupdate', './internal/host') | |
| 63 | 新增: $packageArguments = @{ Release = $Release; SkipBuild = $true } | |
| 64 | 新增: if ($Release) { $packageArguments.QemuSourceArchive = $qemuSource } | |
| 65 | 新增: & (Join-Path $PSScriptRoot 'package-windows.ps1') @packageArguments | |
| 66 | 新增: $version = Get-CageVersion $repository | |
| 67 | 新增: $suffix = if ($Release) { '' } else { '-unsigned' } | |
| 68 | 新增: & (Join-Path $PSScriptRoot 'test-windows-install.ps1') -Installer "$repository/_output/releases/$version/windows/Cage-$version-windows-amd64-setup$suffix.exe" | |
| 69 | 新增: if ($Release) { | |
| 70 | 新增: Invoke-BuildTool 'node' @('scripts/release-version.mjs', 'metadata', 'windows', "_output/releases/$version/windows/build-metadata.json") | |
| 71 | 新增: } | |
| 72 | 新增:} finally { | |
| 73 | 新增: if ($pfx) { Remove-Item -LiteralPath $pfx -Force -ErrorAction SilentlyContinue } | |
| 74 | 新增: foreach ($imported in $certificates) { | |
| 75 | 新增: if ($imported.HasPrivateKey) { | |
| 76 | 新增: Remove-Item "Cert:\CurrentUser\My\$($imported.Thumbprint)" -DeleteKey -Force -ErrorAction SilentlyContinue | |
| 77 | 新增: } else { | |
| 78 | 新增: Remove-Item "Cert:\CurrentUser\My\$($imported.Thumbprint)" -Force -ErrorAction SilentlyContinue | |
| 79 | 新增: } | |
| 80 | 新增: } | |
| 81 | 新增: if ($qemuSource) { Remove-Item -LiteralPath $qemuSource -Force -ErrorAction SilentlyContinue } | |
| 82 | 新增: $env:PATH = $savedPath | |
| 83 | 新增: $env:CAGE_WINDOWS_CERT_SHA1 = $savedCertificate | |
| 84 | 新增: Pop-Location | |
| 85 | 新增:} | |
| @@ -34,7 +34,7 @@ function inUse(bundle) { | ||
| 34 | 34 | } |
| 35 | 35 | } |
| 36 | 36 | |
| 37 | 删除:export async function cleanupApps({ keep, roots }) { | |
| 37 | 新增:export async function cleanupApps({ keep, roots, onInUse = () => {} }) { | |
| 38 | 38 | if (!keep.length) |
| 39 | 39 | throw new Error("At least one verified Cage.app must be kept."); |
| 40 | 40 | const retained = new Set(); |
| @@ -55,7 +55,11 @@ export async function cleanupApps({ keep, roots }) { | ||
| 55 | 55 | const canonical = await realpath(directory); |
| 56 | 56 | if (retained.has(canonical)) return; |
| 57 | 57 | if (directory.endsWith(".app")) { |
| 58 | 删除: if (isCage(directory) && !inUse(directory)) { | |
| 58 | 新增: if (isCage(directory)) { | |
| 59 | 新增: if (inUse(directory)) { | |
| 60 | 新增: onInUse(directory); | |
| 61 | 新增: return; | |
| 62 | 新增: } | |
| 59 | 63 | await rm(directory, { recursive: true }); |
| 60 | 64 | removed.push(directory); |
| 61 | 65 | } |
| @@ -84,6 +88,9 @@ if ( | ||
| 84 | 88 | (flag === "--keep" ? keep : roots).push(value); |
| 85 | 89 | } |
| 86 | 90 | if (!roots.length) throw new Error("At least one cleanup root is required."); |
| 87 | 删除: for (const bundle of await cleanupApps({ keep, roots })) | |
| 91 | 新增: for (const bundle of await cleanupApps({ | |
| 92 | 新增: keep, roots, | |
| 93 | 新增: onInUse: (bundle) => console.error(`Old Cage App is still running; quit it and rerun cleanup: ${bundle}`), | |
| 94 | 新增: })) | |
| 88 | 95 | console.log(`Removed old App: ${bundle}`); |
| 89 | 96 | } |
| @@ -26,7 +26,9 @@ test("cleanup preserves a Cage executable still in use", { skip: process.platfor | ||
| 26 | 26 | await copyFile("/bin/sleep", executable); |
| 27 | 27 | child = spawn(executable, ["30"], { stdio: "ignore" }); |
| 28 | 28 | await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); }); |
| 29 | 删除: assert.deepEqual(await cleanupApps({ keep: [latest], roots: [directory] }), []); | |
| 29 | 新增: const skipped = []; | |
| 30 | 新增: assert.deepEqual(await cleanupApps({ keep: [latest], roots: [directory], onInUse: (bundle) => skipped.push(bundle) }), []); | |
| 31 | 新增: assert.deepEqual(skipped, [running]); | |
| 30 | 32 | await access(executable); |
| 31 | 33 | await new Promise((resolve) => { child.once("exit", resolve); child.kill("SIGTERM"); }); |
| 32 | 34 | child = null; |
| @@ -0,0 +1,26 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:cd "$(dirname "$0")/.." | |
| 4 | 新增:directory="$PWD/_output/linux-deps" | |
| 5 | 新增:mkdir -p "$directory" | |
| 6 | 新增:for component in mihomo mihomoSource; do | |
| 7 | 新增: metadata=$(node -e 'const d=JSON.parse(require("fs").readFileSync("packaging/linux/dependencies.json"))[process.argv[1]]; console.log([d.file,d.url,d.sha256].join("\t"))' "$component") | |
| 8 | 新增: IFS=$'\t' read -r file url checksum <<< "$metadata" | |
| 9 | 新增: archive="$directory/$file" | |
| 10 | 新增: if [[ ! -f "$archive" ]]; then | |
| 11 | 新增: curl --fail --location --retry 2 --connect-timeout 15 --max-time 300 "$url" -o "$archive.part" | |
| 12 | 新增: mv "$archive.part" "$archive" | |
| 13 | 新增: fi | |
| 14 | 新增: actual=$(shasum -a 256 "$archive" | cut -d ' ' -f 1) | |
| 15 | 新增: [[ "$actual" == "$checksum" ]] || { echo "Checksum mismatch: $file" >&2; exit 1; } | |
| 16 | 新增:done | |
| 17 | 新增:gzip -dc "$directory/mihomo-linux-amd64-compatible-v1.19.33.gz" > "$directory/mihomo.part" | |
| 18 | 新增:chmod 755 "$directory/mihomo.part" | |
| 19 | 新增:mv "$directory/mihomo.part" "$directory/mihomo" | |
| 20 | 新增:tar -xOf "$directory/mihomo-v1.19.33-source.tar.gz" mihomo-1.19.33/LICENSE > "$directory/LICENSE" | |
| 21 | 新增:cat > "$directory/NOTICE" <<'EOF' | |
| 22 | 新增:Mihomo v1.19.33, unmodified executable distributed under GPL-3.0. | |
| 23 | 新增:Source: https://github.com/MetaCubeX/mihomo/tree/v1.19.33 | |
| 24 | 新增:Corresponding source accompanies the Cage Linux release as mihomo-v1.19.33-source.tar.gz. | |
| 25 | 新增:Binary checksum and download URL: packaging/linux/dependencies.json in Cage sources. | |
| 26 | 新增:EOF | |
| @@ -0,0 +1,37 @@ | ||
| 1 | 新增:#requires -Version 7.0 | |
| 2 | 新增:[CmdletBinding()] | |
| 3 | 新增:param([string]$Destination = $env:RUNNER_TEMP) | |
| 4 | 新增: | |
| 5 | 新增:$ErrorActionPreference = 'Stop' | |
| 6 | 新增:if (-not $Destination) { throw 'Set RUNNER_TEMP or pass -Destination for the NSIS tool directory.' } | |
| 7 | 新增:$version = '3.13' | |
| 8 | 新增:$expectedSHA256 = 'ba63dffc4410ee89193e1cb5a41989991bd77c61068da17e3156d136b7b0b3d8' | |
| 9 | 新增:$url = "https://downloads.sourceforge.net/project/nsis/NSIS%203/$version/nsis-$version.zip" | |
| 10 | 新增:New-Item -ItemType Directory -Path $Destination -Force | Out-Null | |
| 11 | 新增:$zip = Join-Path $Destination "nsis-$version.zip" | |
| 12 | 新增: | |
| 13 | 新增:# SourceForge returns a browser download page (HTTP 200 HTML) for PowerShell's | |
| 14 | 新增:# default user agent. Use the command-line downloader it redirects to the ZIP. | |
| 15 | 新增:$curl = if ($IsWindows) { 'curl.exe' } else { 'curl' } | |
| 16 | 新增:& $curl --fail --location --silent --show-error --retry 3 --connect-timeout 15 --max-time 120 --output $zip --write-out "NSIS download: HTTP %{http_code}, %{content_type}, %{size_download} bytes\n" $url | |
| 17 | 新增:if ($LASTEXITCODE -ne 0) { throw "NSIS download failed (curl exit $LASTEXITCODE)." } | |
| 18 | 新增: | |
| 19 | 新增:$stream = [IO.File]::OpenRead($zip) | |
| 20 | 新增:try { | |
| 21 | 新增: $magic = [byte[]]::new(4) | |
| 22 | 新增: $read = $stream.Read($magic, 0, 4) | |
| 23 | 新增:} finally { $stream.Dispose() } | |
| 24 | 新增:if ($read -ne 4 -or [Convert]::ToHexString($magic) -ne '504B0304') { | |
| 25 | 新增: throw 'NSIS download is not a ZIP. SourceForge may have returned an HTML page; the downloaded content will not be installed.' | |
| 26 | 新增:} | |
| 27 | 新增:$actualSHA256 = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash | |
| 28 | 新增:if ($actualSHA256 -ne $expectedSHA256) { | |
| 29 | 新增: throw "NSIS checksum mismatch. Expected $expectedSHA256; received $actualSHA256." | |
| 30 | 新增:} | |
| 31 | 新增:Expand-Archive -LiteralPath $zip -DestinationPath $Destination -Force | |
| 32 | 新增:$toolDirectory = Join-Path $Destination "nsis-$version" | |
| 33 | 新增:if (-not (Test-Path -LiteralPath (Join-Path $toolDirectory 'makensis.exe') -PathType Leaf)) { | |
| 34 | 新增: throw 'Verified NSIS ZIP did not contain the expected compiler.' | |
| 35 | 新增:} | |
| 36 | 新增:if ($env:GITHUB_PATH) { Add-Content -LiteralPath $env:GITHUB_PATH -Value $toolDirectory } | |
| 37 | 新增:Write-Host "Verified NSIS $version ZIP and extracted the compiler." | |
| @@ -42,10 +42,13 @@ trap 'rm -f "$list"' EXIT | ||
| 42 | 42 | { |
| 43 | 43 | modules linux amd64 0 ./cmd/agent-vm |
| 44 | 44 | modules linux arm64 0 ./cmd/agent-vm |
| 45 | 新增: modules linux amd64 0 ./cmd/cage | |
| 46 | 新增: modules linux arm64 0 ./cmd/cage | |
| 45 | 47 | modules darwin arm64 1 ./cmd/agent-vm |
| 46 | 48 | modules darwin arm64 1 ./cmd/cage |
| 47 | 49 | modules darwin amd64 1 ./cmd/agent-vm |
| 48 | 50 | modules windows amd64 0 ./cmd/agent-vm |
| 51 | 新增: modules windows amd64 0 ./cmd/cage | |
| 49 | 52 | modules windows arm64 0 ./cmd/agent-vm |
| 50 | 53 | modules linux arm64 0 github.com/lima-vm/lima/v2/cmd/lima-guestagent |
| 51 | 54 | modules linux amd64 0 github.com/lima-vm/lima/v2/cmd/lima-guestagent |
| @@ -0,0 +1,50 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:cd "$(dirname "$0")/.." | |
| 4 | 新增:[[ "$(uname -s)" == Linux && "$(uname -m)" == x86_64 ]] || { echo 'Package on x86_64 Linux.' >&2; exit 1; } | |
| 5 | 新增:case "${1:-}" in '') bash scripts/build-linux.sh ;; --skip-build) ;; *) echo 'Usage: scripts/package-linux.sh [--skip-build]' >&2; exit 2 ;; esac | |
| 6 | 新增:version=$(tr -d '\r\n' < VERSION) | |
| 7 | 新增:[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]] || { echo 'Invalid VERSION.' >&2; exit 1; } | |
| 8 | 新增:[[ "$(cat _output/linux-amd64/app/VERSION)" == "$version" ]] || { echo 'Build version does not match VERSION.' >&2; exit 1; } | |
| 9 | 新增:deb_version="${version/-/\~}" | |
| 10 | 新增:output="$PWD/_output/releases/$version/linux" | |
| 11 | 新增:mkdir -p "$output" | |
| 12 | 新增:stage=$(mktemp -d "$PWD/_output/linux-amd64/package.XXXXXX") | |
| 13 | 新增:trap 'rm -rf "$stage"' EXIT | |
| 14 | 新增:mkdir -p "$stage"/{DEBIAN,usr/bin,usr/lib/claude-cage,usr/share/applications,usr/share/icons/hicolor/512x512/apps,usr/share/doc/claude-cage} | |
| 15 | 新增:cp -a _output/linux-amd64/app/. "$stage/usr/lib/claude-cage/" | |
| 16 | 新增:# The distro already owns /usr/bin/cage (a Wayland compositor). | |
| 17 | 新增:# Keep the backend adjacent to Mihomo, with a distinct public command. | |
| 18 | 新增:ln -s ../lib/claude-cage/cage "$stage/usr/bin/claude-cage" | |
| 19 | 新增:ln -s ../lib/claude-cage/cage-desktop "$stage/usr/bin/cage-desktop" | |
| 20 | 新增:install -m 644 packaging/linux/io.github.lee_xeo.Cage.desktop "$stage/usr/share/applications/" | |
| 21 | 新增:install -m 644 logo.png "$stage/usr/share/icons/hicolor/512x512/apps/io.github.lee_xeo.Cage.png" | |
| 22 | 新增:install -m 644 docs/linux.md "$stage/usr/share/doc/claude-cage/README.md" | |
| 23 | 新增:install -m 755 packaging/linux/preinst "$stage/DEBIAN/preinst" | |
| 24 | 新增:install -m 755 packaging/linux/preinst "$stage/DEBIAN/prerm" | |
| 25 | 新增:# dpkg-shlibdeps derives glibc/GTK dependencies from the build distribution. | |
| 26 | 新增:# Use Debian 12 for releases; a newer build must not claim an older ABI. | |
| 27 | 新增:mkdir -p "$stage/debian" | |
| 28 | 新增:printf 'Source: claude-cage\nSection: devel\nPriority: optional\nMaintainer: Cage contributors <[email protected]>\n\nPackage: claude-cage\nArchitecture: amd64\nDescription: Cage desktop\n' > "$stage/debian/control" | |
| 29 | 新增:dependencies=$(cd "$stage" && dpkg-shlibdeps -O usr/lib/claude-cage/cage-desktop | sed -n 's/^shlibs:Depends=//p') | |
| 30 | 新增:[[ -n "$dependencies" ]] || { echo 'Cannot determine native dependencies.' >&2; exit 1; } | |
| 31 | 新增:rm -rf "$stage/debian" | |
| 32 | 新增:cat > "$stage/DEBIAN/control" <<EOF | |
| 33 | 新增:Package: claude-cage | |
| 34 | 新增:Version: $deb_version | |
| 35 | 新增:Section: devel | |
| 36 | 新增:Priority: optional | |
| 37 | 新增:Architecture: amd64 | |
| 38 | 新增:Maintainer: Cage contributors <[email protected]> | |
| 39 | 新增:Depends: $dependencies, libwebkit2gtk-4.1-0 (>= 2.40), libglib2.0-bin, qemu-system-x86, qemu-utils, ovmf, openssh-client, iproute2, ca-certificates, git | |
| 40 | 新增:Recommends: dbus-user-session, fonts-noto-cjk, libnotify-bin, zenity | kdialog | |
| 41 | 新增:Homepage: https://github.com/Lee-xeo/Claude-Cage | |
| 42 | 新增:Description: Isolated coding workspace with a persistent Linux VM | |
| 43 | 新增: Cage combines projects, terminals, a browser and an editor in a native | |
| 44 | 新增: desktop window. Hardware virtualization and a user-supplied proxy are required. | |
| 45 | 新增:EOF | |
| 46 | 新增:deb="$output/Cage-$version-linux-amd64.deb" | |
| 47 | 新增:dpkg-deb --root-owner-group --build "$stage" "$deb" | |
| 48 | 新增:cp _output/linux-deps/mihomo-v1.19.33-source.tar.gz "$output/" | |
| 49 | 新增:(cd "$output" && sha256sum "$(basename "$deb")" mihomo-v1.19.33-source.tar.gz > SHA256SUMS) | |
| 50 | 新增:printf 'Packaged: %s\n' "$deb" | |
| @@ -8,6 +8,10 @@ fi | ||
| 8 | 8 | case "${1:-}" in ''|--from-notarized-app) ;; *) echo 'Usage: scripts/package-macos.sh [--from-notarized-app]' >&2; exit 2 ;; esac |
| 9 | 9 | : "${CAGE_SIGNING_IDENTITY:?Set CAGE_SIGNING_IDENTITY to your Developer ID Application identity.}" |
| 10 | 10 | : "${CAGE_NOTARY_PROFILE:?Set CAGE_NOTARY_PROFILE to a notarytool keychain profile.}" |
| 11 | 新增:notary_credentials=(--keychain-profile "$CAGE_NOTARY_PROFILE") | |
| 12 | 新增:if [[ -n "${CAGE_NOTARY_KEYCHAIN:-}" ]]; then | |
| 13 | 新增: notary_credentials+=(--keychain "$CAGE_NOTARY_KEYCHAIN") | |
| 14 | 新增:fi | |
| 11 | 15 | if [[ "$CAGE_SIGNING_IDENTITY" == - ]]; then echo 'Release packages require a Developer ID identity.' >&2; exit 1; fi |
| 12 | 16 | version="$(tr -d '\n\r' < VERSION)" |
| 13 | 17 | release="$PWD/_output/releases/$version" |
| @@ -17,7 +21,7 @@ if [[ "${1:-}" != --from-notarized-app ]]; then | ||
| 17 | 21 | bash scripts/build-app.sh |
| 18 | 22 | ditto -c -k --keepParent "$bundle" "$release/Cage-notarization.zip" |
| 19 | 23 | xcrun notarytool submit "$release/Cage-notarization.zip" \ |
| 20 | 删除: --keychain-profile "$CAGE_NOTARY_PROFILE" --wait --timeout 20m \ | |
| 24 | 新增: "${notary_credentials[@]}" --wait --timeout 20m \ | |
| 21 | 25 | --output-format json > "$release/app-notarization.json" |
| 22 | 26 | node -e 'const r=JSON.parse(require("fs").readFileSync(process.argv[1])); if(r.status!=="Accepted") throw new Error(`Apple notarization: ${r.status}; submission ${r.id}`)' "$release/app-notarization.json" |
| 23 | 27 | xcrun stapler staple "$bundle" |
| @@ -58,7 +62,7 @@ EOF | ||
| 58 | 62 | artifact="Cage-$version-macos-arm64.dmg" |
| 59 | 63 | hdiutil create -volname Cage -srcfolder "$stage" -ov -format UDZO "$release/$artifact" |
| 60 | 64 | codesign --force --sign "$CAGE_SIGNING_IDENTITY" --timestamp "$release/$artifact" |
| 61 | 删除:xcrun notarytool submit "$release/$artifact" --keychain-profile "$CAGE_NOTARY_PROFILE" \ | |
| 65 | 新增:xcrun notarytool submit "$release/$artifact" "${notary_credentials[@]}" \ | |
| 62 | 66 | --wait --timeout 20m --output-format json > "$release/dmg-notarization.json" |
| 63 | 67 | node -e 'const r=JSON.parse(require("fs").readFileSync(process.argv[1])); if(r.status!=="Accepted") throw new Error(`Apple notarization: ${r.status}; submission ${r.id}`)' "$release/dmg-notarization.json" |
| 64 | 68 | xcrun stapler staple "$release/$artifact" |
| @@ -0,0 +1,90 @@ | ||
| 1 | 新增:#requires -Version 7.0 | |
| 2 | 新增:[CmdletBinding()] | |
| 3 | 新增:param( | |
| 4 | 新增: [switch]$Release, | |
| 5 | 新增: [switch]$SkipBuild, | |
| 6 | 新增: [string]$AppDirectory, | |
| 7 | 新增: [string]$OutputDirectory, | |
| 8 | 新增: [string]$QemuSourceArchive | |
| 9 | 新增:) | |
| 10 | 新增:. (Join-Path $PSScriptRoot 'windows-common.ps1') | |
| 11 | 新增:$repository = Split-Path $PSScriptRoot -Parent | |
| 12 | 新增:$version = Get-CageVersion $repository | |
| 13 | 新增:if (-not $AppDirectory) { $AppDirectory = Join-Path $repository '_output/windows-amd64/app' } | |
| 14 | 新增:if (-not $OutputDirectory) { $OutputDirectory = Join-Path $repository "_output/releases/$version/windows" } | |
| 15 | 新增:$AppDirectory = [IO.Path]::GetFullPath($AppDirectory) | |
| 16 | 新增:$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory) | |
| 17 | 新增:if (-not $SkipBuild) { & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release -OutputDirectory $AppDirectory } | |
| 18 | 新增:if ((Get-Content -LiteralPath (Join-Path $AppDirectory 'Cage.install-id') -Raw) -ne 'io.github.lee-xeo.claude-cage') { throw 'Invalid Cage app directory.' } | |
| 19 | 新增:if ((Get-Content -LiteralPath (Join-Path $AppDirectory 'version.txt') -Raw).Trim() -ne $version) { throw 'App version differs from VERSION; rebuild before packaging.' } | |
| 20 | 新增:$makeNSIS = Get-BuildCommand @('makensis.exe', 'makensis') | |
| 21 | 新增:$sevenZip = Get-BuildCommand @('7z.exe', '7zz', '7z') | |
| 22 | 新增:if ($IsWindows) { | |
| 23 | 新增: if ([Diagnostics.FileVersionInfo]::GetVersionInfo((Join-Path $AppDirectory 'Cage.exe')).ProductVersion -ne $version) { throw 'Cage.exe version differs from VERSION; rebuild before packaging.' } | |
| 24 | 新增:} else { | |
| 25 | 新增: $metadata = & $sevenZip 'l' '-tPE' (Join-Path $AppDirectory 'Cage.exe') | |
| 26 | 新增: if ($LASTEXITCODE -ne 0 -or -not ($metadata -match ('^ProductVersion: ' + [regex]::Escape($version) + '$'))) { throw 'Cage.exe version differs from VERSION; rebuild before packaging.' } | |
| 27 | 新增:} | |
| 28 | 新增:$signTool = $null | |
| 29 | 新增:if ($Release) { | |
| 30 | 新增: if (-not $IsWindows -or $env:CAGE_WINDOWS_CERT_SHA1 -notmatch '^[0-9A-Fa-f]{40}$') { throw 'Release packaging requires Windows and CAGE_WINDOWS_CERT_SHA1.' } | |
| 31 | 新增: if (Test-Path -LiteralPath (Join-Path $AppDirectory 'DEVELOPMENT-BUILD.txt')) { throw 'Use build-windows.ps1 -Release before packaging a release.' } | |
| 32 | 新增: if (-not $QemuSourceArchive -or -not (Test-Path -LiteralPath $QemuSourceArchive -PathType Leaf)) { | |
| 33 | 新增: throw 'Release packaging requires -QemuSourceArchive containing the corresponding patched QEMU and bundled library sources. A generic upstream QEMU tarball is not the source for the Weilnetz build.' | |
| 34 | 新增: } | |
| 35 | 新增: Invoke-BuildTool $sevenZip @('t', '-bso0', '-bsp0', $QemuSourceArchive) | |
| 36 | 新增: $signTool = Get-SigningTool | |
| 37 | 新增: foreach ($file in @('Cage.exe', 'resources/cage.exe', 'resources/mihomo.exe')) { | |
| 38 | 新增: $signature = Get-AuthenticodeSignature -LiteralPath (Join-Path $AppDirectory $file) | |
| 39 | 新增: if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Thumbprint -ne $env:CAGE_WINDOWS_CERT_SHA1) { throw "Invalid release signature: $file" } | |
| 40 | 新增: } | |
| 41 | 新增: $webview = Get-AuthenticodeSignature -LiteralPath (Join-Path $AppDirectory 'resources/runtime/MicrosoftEdgeWebView2RuntimeInstallerX64.exe') | |
| 42 | 新增: if ($webview.Status -ne 'Valid' -or $webview.SignerCertificate.Subject -notmatch 'O=Microsoft Corporation') { throw 'WebView2 installer must have a valid Microsoft signature.' } | |
| 43 | 新增:} | |
| 44 | 新增:New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null | |
| 45 | 新增:$suffix = if ($Release) { '' } else { '-unsigned' } | |
| 46 | 新增:$artifact = Join-Path $OutputDirectory "Cage-$version-windows-amd64-setup$suffix.exe" | |
| 47 | 新增:$manifest = Join-Path $OutputDirectory 'uninstall-files.nsh' | |
| 48 | 新增:$files = @(Get-ChildItem -LiteralPath $AppDirectory -File -Recurse) | |
| 49 | 新增:$lines = [Collections.Generic.List[string]]::new() | |
| 50 | 新增:foreach ($file in $files) { | |
| 51 | 新增: $relative = [IO.Path]::GetRelativePath($AppDirectory, $file.FullName).Replace('/', '\').Replace('$', '$$').Replace('"', '$\"') | |
| 52 | 新增: $lines.Add('Delete "$INSTDIR\' + $relative + '"') | |
| 53 | 新增:} | |
| 54 | 新增:foreach ($directory in (Get-ChildItem -LiteralPath $AppDirectory -Directory -Recurse | Sort-Object { $_.FullName.Length } -Descending)) { | |
| 55 | 新增: $relative = [IO.Path]::GetRelativePath($AppDirectory, $directory.FullName).Replace('/', '\').Replace('$', '$$').Replace('"', '$\"') | |
| 56 | 新增: $lines.Add('RMDir "$INSTDIR\' + $relative + '"') | |
| 57 | 新增:} | |
| 58 | 新增:[IO.File]::WriteAllLines($manifest, $lines) | |
| 59 | 新增:$numericVersion = ($version -split '-')[0] + '.0' | |
| 60 | 新增:$prefix = if ($IsWindows) { '/' } else { '-' } | |
| 61 | 新增:$arguments = @("${prefix}V3", "${prefix}DAPP_DIR=$AppDirectory", "${prefix}DVERSION=$version", "${prefix}DVERSION_NUMERIC=$numericVersion", "${prefix}DOUTPUT_FILE=$artifact", "${prefix}DUNINSTALL_MANIFEST=$manifest") | |
| 62 | 新增:if ($Release) { $arguments += @("${prefix}DSIGNTOOL=$signTool", "${prefix}DCERT_SHA1=$env:CAGE_WINDOWS_CERT_SHA1") } | |
| 63 | 新增:$arguments += (Join-Path $repository 'packaging/windows/Cage.nsi') | |
| 64 | 新增:Invoke-BuildTool $makeNSIS $arguments | |
| 65 | 新增:if ($Release) { Sign-CageFile $artifact $signTool } | |
| 66 | 新增:if ((Get-Item -LiteralPath $artifact).Length -gt 512MB) { throw 'Installer exceeds the application updater 512 MiB limit.' } | |
| 67 | 新增: | |
| 68 | 新增:# Source materials travel beside the binary, not inside the application directory. | |
| 69 | 新增:$dependencies = Get-Content -LiteralPath (Join-Path $repository 'packaging/windows/dependencies.json') -Raw | ConvertFrom-Json | |
| 70 | 新增:$coreSource = Join-Path $OutputDirectory "mihomo-$($dependencies.mihomo.version)-source.tar.gz" | |
| 71 | 新增:$verifiedCoreSource = Get-VerifiedDependency $dependencies.mihomoSource (Join-Path $repository '_output/windows-deps') | |
| 72 | 新增:Copy-Item -LiteralPath $verifiedCoreSource -Destination $coreSource -Force | |
| 73 | 新增:Invoke-BuildTool $sevenZip @('t', '-bso0', '-bsp0', $coreSource) | |
| 74 | 新增:$releaseFiles = @($artifact, $coreSource) | |
| 75 | 新增:$qemuTar = Get-VerifiedGitArchive $dependencies.qemuSource (Join-Path $repository '_output/windows-deps') | |
| 76 | 新增:$qemuSource = Join-Path $OutputDirectory ($dependencies.qemuSource.file + '.gz') | |
| 77 | 新增:if (Test-Path -LiteralPath $qemuSource) { Remove-Item -LiteralPath $qemuSource } | |
| 78 | 新增:Invoke-BuildTool $sevenZip @('a', '-tgzip', '-mx=9', '-bso0', '-bsp0', $qemuSource, $qemuTar) | |
| 79 | 新增:Invoke-BuildTool $sevenZip @('t', '-bso0', '-bsp0', $qemuSource) | |
| 80 | 新增:$releaseFiles += $qemuSource | |
| 81 | 新增:if ($Release) { | |
| 82 | 新增: $qemuSourceTarget = Join-Path $OutputDirectory ('qemu-' + $dependencies.qemu.version + '-windows-full-source' + [IO.Path]::GetExtension($QemuSourceArchive)) | |
| 83 | 新增: Copy-Item -LiteralPath $QemuSourceArchive -Destination $qemuSourceTarget -Force | |
| 84 | 新增: $releaseFiles += $qemuSourceTarget | |
| 85 | 新增:} | |
| 86 | 新增:$sums = foreach ($file in $releaseFiles) { (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() + ' ' + [IO.Path]::GetFileName($file) } | |
| 87 | 新增:[IO.File]::WriteAllLines((Join-Path $OutputDirectory 'SHA256SUMS'), $sums) | |
| 88 | 新增:Remove-Item -LiteralPath $manifest | |
| 89 | 新增:Write-Host "Windows installer: $artifact" | |
| 90 | 新增:if (-not $Release) { Write-Warning 'Unsigned development installer. Do not publish it as an automatic update; Windows VM and installation acceptance are still required.' } | |
| @@ -0,0 +1,21 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:# Optional Developer ID provisioning for macOS biometric Keychain access. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:profile="$1" | |
| 5 | 新增:team="$2" | |
| 6 | 新增:output="$3" | |
| 7 | 新增:bundle_id=io.github.lee-xeo.claude-cage | |
| 8 | 新增:[[ "$team" =~ ^[A-Z0-9]{10}$ ]] || { echo 'A valid Developer ID team is required.' >&2; exit 1; } | |
| 9 | 新增:security cms -D -i "$profile" -o "$output.profile.plist" | |
| 10 | 新增:profile_team=$(/usr/libexec/PlistBuddy -c 'Print :TeamIdentifier:0' "$output.profile.plist") | |
| 11 | 新增:profile_app=$(/usr/libexec/PlistBuddy -c 'Print :Entitlements:com.apple.application-identifier' "$output.profile.plist") | |
| 12 | 新增:[[ "$profile_team" == "$team" && "$profile_app" == "$team.$bundle_id" ]] || { echo 'Provisioning profile does not match the signing team and Cage bundle.' >&2; exit 1; } | |
| 13 | 新增:cat > "$output" <<PLIST | |
| 14 | 新增:<?xml version="1.0" encoding="UTF-8"?> | |
| 15 | 新增:<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | |
| 16 | 新增:<plist version="1.0"><dict> | |
| 17 | 新增:<key>com.apple.application-identifier</key><string>$team.$bundle_id</string> | |
| 18 | 新增:<key>com.apple.developer.team-identifier</key><string>$team</string> | |
| 19 | 新增:<key>keychain-access-groups</key><array><string>$team.$bundle_id</string></array> | |
| 20 | 新增:</dict></plist> | |
| 21 | 新增:PLIST | |
| @@ -0,0 +1,180 @@ | ||
| 1 | 新增:// Assemble local assets produced by the platform release packagers. Those | |
| 2 | 新增:// packagers and the native updater own signature verification; this script | |
| 3 | 新增:// checks the release names, complete source materials and exact file digests. | |
| 4 | 新增:import { createHash } from 'node:crypto'; | |
| 5 | 新增:import { constants, createWriteStream } from 'node:fs'; | |
| 6 | 新增:import { copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, rm, rmdir, unlink, writeFile } from 'node:fs/promises'; | |
| 7 | 新增:import { tmpdir } from 'node:os'; | |
| 8 | 新增:import { dirname, join, resolve } from 'node:path'; | |
| 9 | 新增:import { Transform, Writable } from 'node:stream'; | |
| 10 | 新增:import { pipeline } from 'node:stream/promises'; | |
| 11 | 新增:import { pathToFileURL } from 'node:url'; | |
| 12 | 新增:import { parseArgs } from 'node:util'; | |
| 13 | 新增: | |
| 14 | 新增:const maxChecksums = 64 * 1024; | |
| 15 | 新增:const maxInstaller = 512 * 1024 * 1024; | |
| 16 | 新增: | |
| 17 | 新增:async function releaseNames() { | |
| 18 | 新增: const version = (await readFile(new URL('../VERSION', import.meta.url), 'utf8')).trim(); | |
| 19 | 新增: if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) throw new Error('Invalid repository VERSION'); | |
| 20 | 新增: const dependencies = JSON.parse(await readFile(new URL('../packaging/windows/dependencies.json', import.meta.url), 'utf8')); | |
| 21 | 新增: const linuxDependencies = JSON.parse(await readFile(new URL('../packaging/linux/dependencies.json', import.meta.url), 'utf8')); | |
| 22 | 新增: const macCoreScript = await readFile(new URL('./fetch-proxy-core.sh', import.meta.url), 'utf8'); | |
| 23 | 新增: const macCore = macCoreScript.match(/^version=(v[\d.]+)$/m)?.[1]; | |
| 24 | 新增: if (!macCore || !/^v[\d.]+$/.test(dependencies.mihomo.version) || !/^[\d.]+$/.test(dependencies.qemu.version)) { | |
| 25 | 新增: throw new Error('Cannot identify the pinned release dependencies'); | |
| 26 | 新增: } | |
| 27 | 新增: return { | |
| 28 | 新增: version, | |
| 29 | 新增: mac: `Cage-${version}-macos-arm64.dmg`, | |
| 30 | 新增: windows: `Cage-${version}-windows-amd64-setup.exe`, | |
| 31 | 新增: linux: `Cage-${version}-linux-amd64.deb`, | |
| 32 | 新增: linuxSource: linuxDependencies.mihomoSource.file, | |
| 33 | 新增: macSource: `mihomo-${macCore}-source.tar.gz`, | |
| 34 | 新增: windowsSource: `mihomo-${dependencies.mihomo.version}-source.tar.gz`, | |
| 35 | 新增: qemuPrefix: `qemu-${dependencies.qemu.version}-windows-full-source.`, | |
| 36 | 新增: qemuSource: dependencies.qemuSource?.file, | |
| 37 | 新增: }; | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:async function regularFile(path) { | |
| 41 | 新增: const info = await lstat(path); | |
| 42 | 新增: if (!info.isFile() || info.isSymbolicLink()) throw new Error(`Expected a regular file: ${path}`); | |
| 43 | 新增: return info; | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:async function readManifest(directory) { | |
| 47 | 新增: const path = join(directory, 'SHA256SUMS'); | |
| 48 | 新增: const info = await regularFile(path); | |
| 49 | 新增: if (!info.size || info.size > maxChecksums) throw new Error(`Invalid SHA256SUMS size: ${directory}`); | |
| 50 | 新增: const text = (await readFile(path, 'utf8')).replace(/^\uFEFF/, ''); | |
| 51 | 新增: const entries = new Map(); | |
| 52 | 新增: for (const line of text.split(/\r?\n/)) { | |
| 53 | 新增: if (!line) continue; | |
| 54 | 新增: const match = /^([a-f0-9]{64}) [ *]([A-Za-z0-9][A-Za-z0-9._-]*)$/i.exec(line); | |
| 55 | 新增: if (!match || entries.has(match[2])) throw new Error(`Invalid or duplicate SHA256SUMS entry: ${directory}`); | |
| 56 | 新增: entries.set(match[2], match[1].toLowerCase()); | |
| 57 | 新增: } | |
| 58 | 新增: if (!entries.size) throw new Error(`Empty SHA256SUMS: ${directory}`); | |
| 59 | 新增: return entries; | |
| 60 | 新增:} | |
| 61 | 新增: | |
| 62 | 新增:function isQemuArchive(name, names) { | |
| 63 | 新增: return name.startsWith(names.qemuPrefix) && /^(?:tar\.)?(?:gz|xz|bz2|zst|zip|7z|tar)$/.test(name.slice(names.qemuPrefix.length)); | |
| 64 | 新增:} | |
| 65 | 新增: | |
| 66 | 新增:async function verifyAndStage(source, digest, destination, installer) { | |
| 67 | 新增: const before = await regularFile(source); | |
| 68 | 新增: if (!before.size || (installer && before.size > maxInstaller)) throw new Error(`Invalid release asset size: ${source}`); | |
| 69 | 新增: const file = await open(source, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); | |
| 70 | 新增: try { | |
| 71 | 新增: const opened = await file.stat(); | |
| 72 | 新增: if (!opened.isFile() || before.ino !== opened.ino || before.dev !== opened.dev) throw new Error(`Release asset changed while opening: ${source}`); | |
| 73 | 新增: const hash = createHash('sha256'); | |
| 74 | 新增: let size = 0; | |
| 75 | 新增: const sink = destination ? createWriteStream(destination, { flags: 'wx', mode: 0o600 }) : new Writable({ write(_chunk, _encoding, callback) { callback(); } }); | |
| 76 | 新增: await pipeline(file.createReadStream({ autoClose: false }), new Transform({ | |
| 77 | 新增: transform(chunk, _encoding, callback) { | |
| 78 | 新增: size += chunk.length; | |
| 79 | 新增: if (size > opened.size) return callback(new Error(`Release asset changed while reading: ${source}`)); | |
| 80 | 新增: hash.update(chunk); | |
| 81 | 新增: callback(null, chunk); | |
| 82 | 新增: }, | |
| 83 | 新增: }), sink); | |
| 84 | 新增: if (size !== opened.size || hash.digest('hex') !== digest) throw new Error(`SHA-256 mismatch: ${source}`); | |
| 85 | 新增: } finally { | |
| 86 | 新增: await file.close(); | |
| 87 | 新增: } | |
| 88 | 新增:} | |
| 89 | 新增: | |
| 90 | 新增:export async function prepareReleaseAssets({ inputs, output }) { | |
| 91 | 新增: if (!Array.isArray(inputs) || !inputs.length || !output) throw new Error('Provide --output and at least one platform release directory'); | |
| 92 | 新增: const target = resolve(output); | |
| 93 | 新增: try { | |
| 94 | 新增: await lstat(target); | |
| 95 | 新增: throw new Error(`Output must be a new directory; existing release assets are never overwritten: ${target}`); | |
| 96 | 新增: } catch (error) { | |
| 97 | 新增: if (error.code !== 'ENOENT') throw error; | |
| 98 | 新增: } | |
| 99 | 新增: const names = await releaseNames(); | |
| 100 | 新增: const all = new Map(); | |
| 101 | 新增: const inputsToVerify = []; | |
| 102 | 新增: for (const input of inputs) { | |
| 103 | 新增: const directory = resolve(input); | |
| 104 | 新增: const info = await lstat(directory); | |
| 105 | 新增: if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`Expected a platform release directory: ${directory}`); | |
| 106 | 新增: const files = await readdir(directory); | |
| 107 | 新增: if (files.some(name => /^Cage-.*-windows-.*-unsigned\.exe$/i.test(name) || name === 'DEVELOPMENT-BUILD.txt')) { | |
| 108 | 新增: throw new Error(`Unsigned Windows development build cannot be prepared for release: ${directory}`); | |
| 109 | 新增: } | |
| 110 | 新增: const entries = await readManifest(directory); | |
| 111 | 新增: const mac = entries.has(names.mac); | |
| 112 | 新增: const windows = entries.has(names.windows); | |
| 113 | 新增: const linux = entries.has(names.linux); | |
| 114 | 新增: if (!mac && !windows && !linux) throw new Error(`No supported package name for VERSION ${names.version}: ${directory}`); | |
| 115 | 新增: if (linux && !entries.has(names.linuxSource)) throw new Error(`Missing Linux Mihomo source in SHA256SUMS: ${directory}`); | |
| 116 | 新增: if (mac && !entries.has(names.macSource)) throw new Error(`Missing macOS Mihomo source in SHA256SUMS: ${directory}`); | |
| 117 | 新增: if (windows && (!entries.has(names.windowsSource) || ![...entries.keys()].some(name => isQemuArchive(name, names)))) { | |
| 118 | 新增: throw new Error(`Windows release requires its Mihomo and complete QEMU source archives in the same SHA256SUMS: ${directory}`); | |
| 119 | 新增: } | |
| 120 | 新增: for (const [name, digest] of entries) { | |
| 121 | 新增: const installer = name === names.mac || name === names.windows || name === names.linux; | |
| 122 | 新增: if (!installer && name !== names.macSource && name !== names.windowsSource && name !== names.linuxSource && name !== names.qemuSource && !isQemuArchive(name, names)) { | |
| 123 | 新增: throw new Error(`Unsupported asset or version in SHA256SUMS: ${name}`); | |
| 124 | 新增: } | |
| 125 | 新增: const existing = all.get(name); | |
| 126 | 新增: if (existing && existing !== digest) throw new Error(`Conflicting same-name release asset: ${name}`); | |
| 127 | 新增: inputsToVerify.push({ source: join(directory, name), digest, name, installer, first: !existing }); | |
| 128 | 新增: all.set(name, digest); | |
| 129 | 新增: } | |
| 130 | 新增: } | |
| 131 | 新增: | |
| 132 | 新增: const staging = await mkdtemp(join(tmpdir(), 'cage-release-assets-')); | |
| 133 | 新增: const created = []; | |
| 134 | 新增: let ownsTarget = false; | |
| 135 | 新增: try { | |
| 136 | 新增: // Validate every input, including identical-name duplicates. The output | |
| 137 | 新增: // gets these verified snapshots, never a second read of mutable inputs. | |
| 138 | 新增: for (const asset of inputsToVerify) { | |
| 139 | 新增: await verifyAndStage(asset.source, asset.digest, asset.first ? join(staging, asset.name) : undefined, asset.installer); | |
| 140 | 新增: } | |
| 141 | 新增: const sorted = [...all].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); | |
| 142 | 新增: const checksums = sorted.map(([name, digest]) => `${digest} ${name}\n`).join(''); | |
| 143 | 新增: if (Buffer.byteLength(checksums) > maxChecksums) throw new Error('Merged SHA256SUMS exceeds the updater limit'); | |
| 144 | 新增: await mkdir(dirname(target), { recursive: true }); | |
| 145 | 新增: await mkdir(target); // Exclusive creation also closes the preflight race. | |
| 146 | 新增: ownsTarget = true; | |
| 147 | 新增: for (const [name] of sorted) { | |
| 148 | 新增: await copyFile(join(staging, name), join(target, name), constants.COPYFILE_EXCL); | |
| 149 | 新增: created.push(name); | |
| 150 | 新增: } | |
| 151 | 新增: await writeFile(join(target, 'SHA256SUMS'), checksums, { flag: 'wx', mode: 0o644 }); | |
| 152 | 新增: created.push('SHA256SUMS'); | |
| 153 | 新增: return { version: names.version, directory: target, assets: sorted.map(([name]) => name) }; | |
| 154 | 新增: } catch (error) { | |
| 155 | 新增: if (ownsTarget) { | |
| 156 | 新增: // Delete only our files. Preserve any unexpected concurrently added file. | |
| 157 | 新增: for (const name of created) await unlink(join(target, name)).catch(() => {}); | |
| 158 | 新增: await rmdir(target).catch(() => {}); | |
| 159 | 新增: } | |
| 160 | 新增: throw error; | |
| 161 | 新增: } finally { | |
| 162 | 新增: await rm(staging, { recursive: true, force: true }); | |
| 163 | 新增: } | |
| 164 | 新增:} | |
| 165 | 新增: | |
| 166 | 新增:async function main() { | |
| 167 | 新增: const { values, positionals } = parseArgs({ allowPositionals: true, options: { | |
| 168 | 新增: output: { type: 'string' }, help: { type: 'boolean', short: 'h' }, | |
| 169 | 新增: } }); | |
| 170 | 新增: if (values.help) { | |
| 171 | 新增: console.log('Usage: node scripts/prepare-release-assets.mjs --output NEW_DIRECTORY PLATFORM_DIRECTORY [...]\nAccepts macOS, Windows and Linux release outputs with SHA256SUMS. Checks current VERSION, source archives and hashes; macOS/Windows signature verification belongs to their packagers. Linux packages use manual system installation. Never uploads or overwrites an existing output directory.'); | |
| 172 | 新增: return; | |
| 173 | 新增: } | |
| 174 | 新增: const result = await prepareReleaseAssets({ inputs: positionals, output: values.output }); | |
| 175 | 新增: console.log(`Prepared Cage ${result.version}: ${result.assets.length} verified assets and one SHA256SUMS in ${result.directory}`); | |
| 176 | 新增:} | |
| 177 | 新增: | |
| 178 | 新增:if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { | |
| 179 | 新增: main().catch(error => { console.error(error.message); process.exitCode = 1; }); | |
| 180 | 新增:} | |
| @@ -0,0 +1,139 @@ | ||
| 1 | 新增:import assert from 'node:assert/strict'; | |
| 2 | 新增:import { createHash } from 'node:crypto'; | |
| 3 | 新增:import { lstat, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'; | |
| 4 | 新增:import { tmpdir } from 'node:os'; | |
| 5 | 新增:import { join } from 'node:path'; | |
| 6 | 新增:import test from 'node:test'; | |
| 7 | 新增:import { prepareReleaseAssets } from './prepare-release-assets.mjs'; | |
| 8 | 新增:import { checksumFor } from '../www/scripts/sync-release.mjs'; | |
| 9 | 新增: | |
| 10 | 新增:const version = (await readFile(new URL('../VERSION', import.meta.url), 'utf8')).trim(); | |
| 11 | 新增:const dependencies = JSON.parse(await readFile(new URL('../packaging/windows/dependencies.json', import.meta.url), 'utf8')); | |
| 12 | 新增:const macCore = (await readFile(new URL('./fetch-proxy-core.sh', import.meta.url), 'utf8')).match(/^version=(v[\d.]+)$/m)[1]; | |
| 13 | 新增:const names = { | |
| 14 | 新增: mac: `Cage-${version}-macos-arm64.dmg`, | |
| 15 | 新增: windows: `Cage-${version}-windows-amd64-setup.exe`, | |
| 16 | 新增: macSource: `mihomo-${macCore}-source.tar.gz`, | |
| 17 | 新增: windowsSource: `mihomo-${dependencies.mihomo.version}-source.tar.gz`, | |
| 18 | 新增: qemu: `qemu-${dependencies.qemu.version}-windows-full-source.zip`, | |
| 19 | 新增:}; | |
| 20 | 新增:const digest = data => createHash('sha256').update(data).digest('hex'); | |
| 21 | 新增: | |
| 22 | 新增:async function fixture(t) { | |
| 23 | 新增: const root = await mkdtemp(join(tmpdir(), 'cage-release-test-')); | |
| 24 | 新增: t.after(() => rm(root, { recursive: true, force: true })); | |
| 25 | 新增: return { root, mac: join(root, 'mac'), windows: join(root, 'windows'), output: join(root, 'publish') }; | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:async function platform(directory, assets) { | |
| 29 | 新增: await mkdir(directory, { recursive: true }); | |
| 30 | 新增: for (const [name, data] of Object.entries(assets)) await writeFile(join(directory, name), data); | |
| 31 | 新增: await writeFile(join(directory, 'SHA256SUMS'), Object.entries(assets).map(([name, data]) => `${digest(data)} ${name}\n`).join('')); | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:const macAssets = () => ({ [names.mac]: 'mac package fixture', [names.macSource]: 'Mihomo source fixture' }); | |
| 35 | 新增:const windowsAssets = () => ({ [names.windows]: 'Windows package fixture', [names.windowsSource]: 'Mihomo source fixture', [names.qemu]: 'complete QEMU source fixture' }); | |
| 36 | 新增: | |
| 37 | 新增:test('includes Linux deb only with its verified corresponding source and merges common sources', async t => { | |
| 38 | 新增: const f = await fixture(t); | |
| 39 | 新增: const linux = join(f.root, 'linux'); | |
| 40 | 新增: const dependencies = JSON.parse(await readFile(new URL('../packaging/linux/dependencies.json', import.meta.url), 'utf8')); | |
| 41 | 新增: const deb = `Cage-${version}-linux-amd64.deb`; | |
| 42 | 新增: await platform(linux, { [deb]: 'Linux package fixture' }); | |
| 43 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [linux], output: f.output }), /Missing Linux Mihomo source/); | |
| 44 | 新增: await platform(linux, { [deb]: 'Linux package fixture', [dependencies.mihomoSource.file]: 'Mihomo source fixture' }); | |
| 45 | 新增: await platform(f.mac, macAssets()); | |
| 46 | 新增: const prepared = await prepareReleaseAssets({ inputs: [f.mac, linux], output: f.output }); | |
| 47 | 新增: assert.ok(prepared.assets.includes(deb)); | |
| 48 | 新增: assert.equal(await readFile(join(f.output, deb), 'utf8'), 'Linux package fixture'); | |
| 49 | 新增: assert.equal(prepared.assets.filter(name => name === dependencies.mihomoSource.file).length, 1); | |
| 50 | 新增:}); | |
| 51 | 新增: | |
| 52 | 新增:test('combines both platforms, deduplicates identical sources and keeps website checksum lookup valid', async t => { | |
| 53 | 新增: const f = await fixture(t); | |
| 54 | 新增: const extraSource = dependencies.qemuSource.file; | |
| 55 | 新增: await platform(f.mac, macAssets()); | |
| 56 | 新增: await platform(f.windows, { ...windowsAssets(), [extraSource]: 'patched QEMU source fixture' }); | |
| 57 | 新增: const result = await prepareReleaseAssets({ inputs: [f.mac, f.windows], output: f.output }); | |
| 58 | 新增: const expected = new Map(Object.entries({ ...macAssets(), ...windowsAssets(), [extraSource]: 'patched QEMU source fixture' })); | |
| 59 | 新增: assert.deepEqual(new Set(await readdir(f.output)), new Set([...expected.keys(), 'SHA256SUMS'])); | |
| 60 | 新增: assert.equal(result.version, version); | |
| 61 | 新增: const sums = await readFile(join(f.output, 'SHA256SUMS'), 'utf8'); | |
| 62 | 新增: for (const [name, data] of expected) { | |
| 63 | 新增: assert.equal(await readFile(join(f.output, name), 'utf8'), data); | |
| 64 | 新增: assert.equal(checksumFor(sums, { name }), digest(data)); | |
| 65 | 新增: } | |
| 66 | 新增: assert.equal(sums.trimEnd().split('\n').length, expected.size); | |
| 67 | 新增:}); | |
| 68 | 新增: | |
| 69 | 新增:test('supports a single Windows or macOS platform with its corresponding sources', async t => { | |
| 70 | 新增: const f = await fixture(t); | |
| 71 | 新增: await platform(f.mac, macAssets()); | |
| 72 | 新增: await platform(f.windows, windowsAssets()); | |
| 73 | 新增: assert.equal((await prepareReleaseAssets({ inputs: [f.mac], output: f.output })).assets.length, 2); | |
| 74 | 新增: assert.equal((await prepareReleaseAssets({ inputs: [f.windows], output: join(f.root, 'windows-only') })).assets.length, 3); | |
| 75 | 新增:}); | |
| 76 | 新增: | |
| 77 | 新增:test('rejects corrupted bytes before creating the output', async t => { | |
| 78 | 新增: const f = await fixture(t); | |
| 79 | 新增: await platform(f.mac, macAssets()); | |
| 80 | 新增: await writeFile(join(f.mac, names.mac), 'changed after packaging'); | |
| 81 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [f.mac], output: f.output }), /SHA-256 mismatch/); | |
| 82 | 新增: await assert.rejects(lstat(f.output), { code: 'ENOENT' }); | |
| 83 | 新增:}); | |
| 84 | 新增: | |
| 85 | 新增:test('rejects conflicting contents under the same asset name', async t => { | |
| 86 | 新增: const f = await fixture(t); | |
| 87 | 新增: const second = join(f.root, 'second-mac'); | |
| 88 | 新增: await platform(f.mac, macAssets()); | |
| 89 | 新增: await platform(second, { ...macAssets(), [names.macSource]: 'different source archive' }); | |
| 90 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [f.mac, second], output: f.output }), /Conflicting same-name/); | |
| 91 | 新增:}); | |
| 92 | 新增: | |
| 93 | 新增:test('checks duplicate input bytes even when their manifests claim identical digests', async t => { | |
| 94 | 新增: const f = await fixture(t); | |
| 95 | 新增: const second = join(f.root, 'second-mac'); | |
| 96 | 新增: await platform(f.mac, macAssets()); | |
| 97 | 新增: await platform(second, macAssets()); | |
| 98 | 新增: await writeFile(join(second, names.macSource), 'corrupted duplicate'); | |
| 99 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [f.mac, second], output: f.output }), /SHA-256 mismatch/); | |
| 100 | 新增:}); | |
| 101 | 新增: | |
| 102 | 新增:test('rejects unsigned development installers including unlisted leftovers', async t => { | |
| 103 | 新增: const f = await fixture(t); | |
| 104 | 新增: const unsigned = names.windows.replace(/\.exe$/, '-unsigned.exe'); | |
| 105 | 新增: const assets = windowsAssets(); | |
| 106 | 新增: assets[unsigned] = assets[names.windows]; | |
| 107 | 新增: delete assets[names.windows]; | |
| 108 | 新增: await platform(f.windows, assets); | |
| 109 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [f.windows], output: f.output }), /Unsigned Windows development/); | |
| 110 | 新增: await platform(f.windows, windowsAssets()); | |
| 111 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [f.windows], output: f.output }), /Unsigned Windows development/); | |
| 112 | 新增:}); | |
| 113 | 新增: | |
| 114 | 新增:test('requires Windows complete QEMU source in the same verified manifest', async t => { | |
| 115 | 新增: const f = await fixture(t); | |
| 116 | 新增: const assets = windowsAssets(); | |
| 117 | 新增: delete assets[names.qemu]; | |
| 118 | 新增: await platform(f.windows, assets); | |
| 119 | 新增: await writeFile(join(f.windows, names.qemu), 'unlisted source is not verified'); | |
| 120 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [f.windows], output: f.output }), /complete QEMU source/); | |
| 121 | 新增:}); | |
| 122 | 新增: | |
| 123 | 新增:test('rejects wrong versions and manifest paths outside the release directory', async t => { | |
| 124 | 新增: const f = await fixture(t); | |
| 125 | 新增: await platform(f.mac, { ...macAssets(), 'Cage-99.0.0-macos-arm64.dmg': 'wrong version' }); | |
| 126 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [f.mac], output: f.output }), /Unsupported asset or version/); | |
| 127 | 新增: await writeFile(join(f.mac, 'SHA256SUMS'), `${digest('outside')} ../escape.dmg\n`); | |
| 128 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [f.mac], output: f.output }), /Invalid or duplicate/); | |
| 129 | 新增:}); | |
| 130 | 新增: | |
| 131 | 新增:test('never overwrites an existing output, including an empty one', async t => { | |
| 132 | 新增: const f = await fixture(t); | |
| 133 | 新增: await platform(f.mac, macAssets()); | |
| 134 | 新增: await mkdir(f.output); | |
| 135 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [f.mac], output: f.output }), /Output must be a new directory/); | |
| 136 | 新增: await writeFile(join(f.output, 'published-asset'), 'keep'); | |
| 137 | 新增: await assert.rejects(prepareReleaseAssets({ inputs: [f.mac], output: f.output }), /Output must be a new directory/); | |
| 138 | 新增: assert.equal(await readFile(join(f.output, 'published-asset'), 'utf8'), 'keep'); | |
| 139 | 新增:}); | |
| @@ -0,0 +1,283 @@ | ||
| 1 | 新增:import { createHash } from 'node:crypto'; | |
| 2 | 新增:import { execFileSync, spawnSync } from 'node:child_process'; | |
| 3 | 新增:import { createReadStream } from 'node:fs'; | |
| 4 | 新增:import { appendFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'; | |
| 5 | 新增:import { tmpdir } from 'node:os'; | |
| 6 | 新增:import { dirname, join, relative, resolve } from 'node:path'; | |
| 7 | 新增:import { fileURLToPath, pathToFileURL } from 'node:url'; | |
| 8 | 新增:import { Readable } from 'node:stream'; | |
| 9 | 新增:import { compareVersions, nextVersion, parseVersion, versionFiles } from './release-version.mjs'; | |
| 10 | 新增:import { prepareReleaseAssets } from './prepare-release-assets.mjs'; | |
| 11 | 新增: | |
| 12 | 新增:export const versionPaths = ['VERSION', 'ui/package.json', 'ui/package-lock.json', 'www/package.json', 'www/package-lock.json']; | |
| 13 | 新增:const repoRoot = fileURLToPath(new URL('../', import.meta.url)); | |
| 14 | 新增:const shaPattern = /^[0-9a-f]{40}$/; | |
| 15 | 新增:const platforms = ['macos', 'windows', 'linux']; | |
| 16 | 新增: | |
| 17 | 新增:function checkContext(context) { | |
| 18 | 新增: if (context.repository !== 'Lee-xeo/Claude-Cage' || !shaPattern.test(context.sourceSha) || !/^\d+$/.test(context.runId) || context.defaultBranch !== 'main') { | |
| 19 | 新增: throw new Error('Invalid release repository, source commit, run ID or default branch.'); | |
| 20 | 新增: } | |
| 21 | 新增:} | |
| 22 | 新增:const marker = context => `<!-- cage-release-run:${context.runId}; commit:${context.commitSha} -->`; | |
| 23 | 新增:const message = (version, runId) => `chore(release): v${version}\n\nCage-Release-Run: ${runId}`; | |
| 24 | 新增:const branch = runId => `codex/release/${runId}`; | |
| 25 | 新增:const apiRoot = context => `/repos/${context.repository}`; | |
| 26 | 新增:async function optional(api, path) { | |
| 27 | 新增: try { return await api('GET', path); } | |
| 28 | 新增: catch (error) { if (error.status === 404) return null; throw error; } | |
| 29 | 新增:} | |
| 30 | 新增: | |
| 31 | 新增:// The tag endpoint only returns published Releases. Authenticated pagination | |
| 32 | 新增:// also includes drafts, which must be found before retrying an interrupted run. | |
| 33 | 新增:async function findRelease(api, base, tag) { | |
| 34 | 新增: let found = null; | |
| 35 | 新增: for (let page = 1; ; page++) { | |
| 36 | 新增: const releases = await api('GET', `${base}/releases?per_page=100&page=${page}`); | |
| 37 | 新增: for (const release of releases) { | |
| 38 | 新增: if (release.tag_name !== tag) continue; | |
| 39 | 新增: if (found) throw new Error(`Multiple Releases reserve ${tag}; review them before retrying.`); | |
| 40 | 新增: found = release; | |
| 41 | 新增: } | |
| 42 | 新增: if (releases.length < 100) return found; | |
| 43 | 新增: } | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:// Build expected version files from the immutable source commit, even when | |
| 47 | 新增:// publish is checking out the candidate. This catches unrelated file edits. | |
| 48 | 新增:export async function expectedFiles(root, sourceSha, version) { | |
| 49 | 新增: if (!shaPattern.test(sourceSha)) throw new Error('Invalid source commit.'); | |
| 50 | 新增: const fixture = await mkdtemp(join(tmpdir(), 'cage-release-version-')); | |
| 51 | 新增: try { | |
| 52 | 新增: for (const path of versionPaths) { | |
| 53 | 新增: const content = execFileSync('git', ['show', `${sourceSha}:${path}`], { cwd: root, maxBuffer: 20 << 20 }); | |
| 54 | 新增: await mkdir(dirname(join(fixture, path)), { recursive: true }); | |
| 55 | 新增: await writeFile(join(fixture, path), content); | |
| 56 | 新增: } | |
| 57 | 新增: return new Map([...versionFiles(fixture, version)].map(([path, text]) => [relative(fixture, path).replaceAll('\\', '/'), text])); | |
| 58 | 新增: } finally { await rm(fixture, { recursive: true, force: true }); } | |
| 59 | 新增:} | |
| 60 | 新增: | |
| 61 | 新增:export async function verifyCandidate(api, context, expected) { | |
| 62 | 新增: checkContext(context); | |
| 63 | 新增: parseVersion(context.version); | |
| 64 | 新增: if (!shaPattern.test(context.commitSha)) throw new Error('Invalid candidate commit.'); | |
| 65 | 新增: const base = apiRoot(context); | |
| 66 | 新增: const commit = await api('GET', `${base}/git/commits/${context.commitSha}`); | |
| 67 | 新增: if (commit.message !== message(context.version, context.runId) || commit.parents?.length !== 1 || commit.parents[0].sha !== context.sourceSha) { | |
| 68 | 新增: throw new Error('Candidate does not belong to this release run and source commit.'); | |
| 69 | 新增: } | |
| 70 | 新增: const diff = await api('GET', `${base}/compare/${context.sourceSha}...${context.commitSha}`); | |
| 71 | 新增: if (diff.status !== 'ahead' || diff.ahead_by !== 1 || diff.files?.length !== versionPaths.length || | |
| 72 | 新增: diff.files.some(file => file.status !== 'modified' || !versionPaths.includes(file.filename))) { | |
| 73 | 新增: throw new Error('Release candidate must change only the five application version files.'); | |
| 74 | 新增: } | |
| 75 | 新增: for (const [path, content] of expected) { | |
| 76 | 新增: const file = await api('GET', `${base}/contents/${path}?ref=${context.commitSha}`); | |
| 77 | 新增: if (file.type !== 'file' || file.encoding !== 'base64' || Buffer.from(file.content, 'base64').toString('utf8') !== content) { | |
| 78 | 新增: throw new Error(`Candidate contains an unexpected change: ${path}`); | |
| 79 | 新增: } | |
| 80 | 新增: } | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:export async function prepareRelease({ api, root, ...context }) { | |
| 84 | 新增: checkContext(context); | |
| 85 | 新增: const base = apiRoot(context); | |
| 86 | 新增: const main = await api('GET', `${base}/git/ref/heads/${context.defaultBranch}`); | |
| 87 | 新增: const existing = await optional(api, `${base}/git/ref/heads/${branch(context.runId)}`); | |
| 88 | 新增: if (existing) { | |
| 89 | 新增: const commit = await api('GET', `${base}/git/commits/${existing.object.sha}`); | |
| 90 | 新增: const version = /^chore\(release\): v([^\n]+)\n\nCage-Release-Run: \d+$/.exec(commit.message)?.[1]; | |
| 91 | 新增: parseVersion(version); | |
| 92 | 新增: if (main.object.sha !== context.sourceSha && main.object.sha !== existing.object.sha) throw new Error('Main advanced; start a new explicitly requested release.'); | |
| 93 | 新增: const result = { ...context, version, commitSha: existing.object.sha }; | |
| 94 | 新增: await verifyCandidate(api, result, await expectedFiles(root, context.sourceSha, version)); | |
| 95 | 新增: return result; | |
| 96 | 新增: } | |
| 97 | 新增: if (main.object.sha !== context.sourceSha) throw new Error('Main advanced after dispatch; no version was changed. Start a new release.'); | |
| 98 | 新增: const current = execFileSync('git', ['show', `${context.sourceSha}:VERSION`], { cwd: root, encoding: 'utf8' }).trim(); | |
| 99 | 新增: const refs = await api('GET', `${base}/git/matching-refs/tags/v`); | |
| 100 | 新增: const reserved = refs.map(ref => ref.ref.replace('refs/tags/', '')); | |
| 101 | 新增: for (let page = 1; ; page++) { | |
| 102 | 新增: const releases = await api('GET', `${base}/releases?per_page=100&page=${page}`); | |
| 103 | 新增: reserved.push(...releases.map(release => release.tag_name)); | |
| 104 | 新增: if (releases.length < 100) break; | |
| 105 | 新增: } | |
| 106 | 新增: const version = nextVersion(current, context.bump, reserved); | |
| 107 | 新增: if (compareVersions(version, current) <= 0) throw new Error('Release version must advance.'); | |
| 108 | 新增: // Tags and draft Releases reserve their version. Never reuse someone else's draft. | |
| 109 | 新增: if (await findRelease(api, base, `v${version}`)) throw new Error(`Release v${version} is already reserved.`); | |
| 110 | 新增: const files = await expectedFiles(root, context.sourceSha, version); | |
| 111 | 新增: const source = await api('GET', `${base}/git/commits/${context.sourceSha}`); | |
| 112 | 新增: const tree = await api('POST', `${base}/git/trees`, { | |
| 113 | 新增: base_tree: source.tree.sha, | |
| 114 | 新增: tree: [...files].map(([path, content]) => ({ path, mode: '100644', type: 'blob', content })), | |
| 115 | 新增: }); | |
| 116 | 新增: const candidate = await api('POST', `${base}/git/commits`, { | |
| 117 | 新增: message: message(version, context.runId), tree: tree.sha, parents: [context.sourceSha], | |
| 118 | 新增: }); | |
| 119 | 新增: await api('POST', `${base}/git/refs`, { ref: `refs/heads/${branch(context.runId)}`, sha: candidate.sha }); | |
| 120 | 新增: const result = { ...context, version, commitSha: candidate.sha }; | |
| 121 | 新增: await verifyCandidate(api, result, files); | |
| 122 | 新增: return result; | |
| 123 | 新增:} | |
| 124 | 新增: | |
| 125 | 新增:export async function assembleRelease({ directory, output, version, commitSha, assemble = prepareReleaseAssets }) { | |
| 126 | 新增: parseVersion(version); | |
| 127 | 新增: if (!shaPattern.test(commitSha)) throw new Error('Invalid artifact commit.'); | |
| 128 | 新增: for (const platform of platforms) { | |
| 129 | 新增: const metadata = JSON.parse(await readFile(join(directory, platform, 'build-metadata.json'), 'utf8')); | |
| 130 | 新增: if (metadata.schema !== 1 || metadata.platform !== platform || metadata.version !== version || metadata.commitSha !== commitSha) { | |
| 131 | 新增: throw new Error(`${platform} artifact was not built from the selected version and commit.`); | |
| 132 | 新增: } | |
| 133 | 新增: } | |
| 134 | 新增: const result = await assemble({ inputs: platforms.map(platform => join(directory, platform)), output }); | |
| 135 | 新增: const required = [`Cage-${version}-macos-arm64.dmg`, `Cage-${version}-windows-amd64-setup.exe`, `Cage-${version}-linux-amd64.deb`]; | |
| 136 | 新增: if (result.version !== version || required.some(name => !result.assets.includes(name))) throw new Error('All three verified platform installers are required.'); | |
| 137 | 新增: return result; | |
| 138 | 新增:} | |
| 139 | 新增: | |
| 140 | 新增:async function sha256(path) { | |
| 141 | 新增: const hash = createHash('sha256'); | |
| 142 | 新增: for await (const chunk of createReadStream(path)) hash.update(chunk); | |
| 143 | 新增: return hash.digest('hex'); | |
| 144 | 新增:} | |
| 145 | 新增:export async function releaseFiles(directory) { | |
| 146 | 新增: const manifest = await readFile(join(directory, 'SHA256SUMS'), 'utf8'); | |
| 147 | 新增: const files = new Map(); | |
| 148 | 新增: for (const line of manifest.trim().split(/\r?\n/)) { | |
| 149 | 新增: const match = /^([a-f0-9]{64}) ([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(line); | |
| 150 | 新增: if (!match || files.has(match[2])) throw new Error('Invalid release checksum manifest.'); | |
| 151 | 新增: files.set(match[2], match[1]); | |
| 152 | 新增: } | |
| 153 | 新增: files.set('SHA256SUMS', await sha256(join(directory, 'SHA256SUMS'))); | |
| 154 | 新增: const actual = await readdir(directory); | |
| 155 | 新增: if (actual.length !== files.size || actual.some(name => !files.has(name))) throw new Error('Release output contains unlisted files.'); | |
| 156 | 新增: const result = []; | |
| 157 | 新增: for (const [name, digest] of files) { | |
| 158 | 新增: const path = join(directory, name); | |
| 159 | 新增: const info = await stat(path); | |
| 160 | 新增: if (!info.isFile() || !info.size || await sha256(path) !== digest) throw new Error(`Invalid release file: ${name}`); | |
| 161 | 新增: result.push({ name, path, digest: `sha256:${digest}`, size: info.size }); | |
| 162 | 新增: } | |
| 163 | 新增: return result; | |
| 164 | 新增:} | |
| 165 | 新增: | |
| 166 | 新增:function assertOwned(release, context) { | |
| 167 | 新增: if (!release.body?.includes(marker(context)) || release.tag_name !== `v${context.version}`) throw new Error('Existing Release belongs to another operation; refusing to change it.'); | |
| 168 | 新增:} | |
| 169 | 新增:function correctAsset(asset, file) { return asset?.state === 'uploaded' && asset.size === file.size && asset.digest === file.digest; } | |
| 170 | 新增:function assertAssets(assets, files) { | |
| 171 | 新增: if (assets.length !== files.length || files.some(file => !correctAsset(assets.find(asset => asset.name === file.name), file))) { | |
| 172 | 新增: throw new Error('GitHub uploaded assets do not match the complete verified release.'); | |
| 173 | 新增: } | |
| 174 | 新增:} | |
| 175 | 新增: | |
| 176 | 新增:export async function publishRelease({ api, upload, promote, root, files, ...context }) { | |
| 177 | 新增: checkContext(context); | |
| 178 | 新增: await verifyCandidate(api, context, await expectedFiles(root, context.sourceSha, context.version)); | |
| 179 | 新增: const base = apiRoot(context); | |
| 180 | 新增: const main = await api('GET', `${base}/git/ref/heads/${context.defaultBranch}`); | |
| 181 | 新增: if (![context.sourceSha, context.commitSha].includes(main.object.sha)) throw new Error('Main changed during the build; no Release was published.'); | |
| 182 | 新增: const tag = await optional(api, `${base}/git/ref/tags/v${context.version}`); | |
| 183 | 新增: if (tag && tag.object.sha !== context.commitSha) throw new Error('Version tag already points to another commit.'); | |
| 184 | 新增: let release = await findRelease(api, base, `v${context.version}`); | |
| 185 | 新增: if (release) { | |
| 186 | 新增: assertOwned(release, context); | |
| 187 | 新增: if (!release.draft) { | |
| 188 | 新增: if (!tag || main.object.sha !== context.commitSha) throw new Error('Published Release has unexpected Git references.'); | |
| 189 | 新增: assertAssets(await api('GET', `${base}/releases/${release.id}/assets?per_page=100`), files); | |
| 190 | 新增: return release; // A failed website deployment may safely retry this job. | |
| 191 | 新增: } | |
| 192 | 新增: } | |
| 193 | 新增: await promote(context); // Atomic, fast-forward-only main + tag; never force-push. | |
| 194 | 新增: if (!release) { | |
| 195 | 新增: const notes = await api('POST', `${base}/releases/generate-notes`, { tag_name: `v${context.version}`, target_commitish: context.commitSha }); | |
| 196 | 新增: release = await api('POST', `${base}/releases`, { | |
| 197 | 新增: tag_name: `v${context.version}`, target_commitish: context.commitSha, | |
| 198 | 新增: name: `Cage ${context.version}`, draft: true, prerelease: context.version.includes('-'), | |
| 199 | 新增: body: `${marker(context)}\n\n${notes.body || ''}\n\nThree platform builds, package verification and automated checks completed for ${context.commitSha}. Hardware virtualization and real Claude account acceptance are separate checks; see the platform guides.`, | |
| 200 | 新增: }); | |
| 201 | 新增: } | |
| 202 | 新增: const assets = await api('GET', `${base}/releases/${release.id}/assets?per_page=100`); | |
| 203 | 新增: if (assets.some(asset => !files.some(file => file.name === asset.name))) throw new Error('Draft contains unexpected assets; review them before retrying.'); | |
| 204 | 新增: for (const file of files) { | |
| 205 | 新增: const prior = assets.find(asset => asset.name === file.name); | |
| 206 | 新增: if (correctAsset(prior, file)) continue; | |
| 207 | 新增: // Only this run's still-private draft may replace a partial or rebuilt asset. | |
| 208 | 新增: const current = await api('GET', `${base}/releases/${release.id}`); | |
| 209 | 新增: assertOwned(current, context); | |
| 210 | 新增: if (!current.draft) throw new Error('Published assets cannot be replaced.'); | |
| 211 | 新增: if (prior) await api('DELETE', `${base}/releases/assets/${prior.id}`); | |
| 212 | 新增: await upload(context.repository, release.id, file); | |
| 213 | 新增: } | |
| 214 | 新增: assertAssets(await api('GET', `${base}/releases/${release.id}/assets?per_page=100`), files); | |
| 215 | 新增: return api('PATCH', `${base}/releases/${release.id}`, { draft: false, make_latest: context.version.includes('-') ? 'false' : 'true' }); | |
| 216 | 新增:} | |
| 217 | 新增: | |
| 218 | 新增:export function workflowContext(env, event) { | |
| 219 | 新增: const context = { | |
| 220 | 新增: repository: env.GITHUB_REPOSITORY, sourceSha: env.RELEASE_SOURCE_SHA || env.GITHUB_SHA, | |
| 221 | 新增: runId: env.GITHUB_RUN_ID, defaultBranch: event.repository?.default_branch, bump: event.inputs?.bump, | |
| 222 | 新增: version: env.RELEASE_VERSION, commitSha: env.RELEASE_COMMIT_SHA, | |
| 223 | 新增: }; | |
| 224 | 新增: checkContext(context); | |
| 225 | 新增: if (env.GITHUB_ACTIONS !== 'true' || env.GITHUB_EVENT_NAME !== 'workflow_dispatch' || env.GITHUB_REF !== 'refs/heads/main') { | |
| 226 | 新增: throw new Error('Release mutations require an explicit workflow dispatch on main.'); | |
| 227 | 新增: } | |
| 228 | 新增: return context; | |
| 229 | 新增:} | |
| 230 | 新增: | |
| 231 | 新增:async function main() { | |
| 232 | 新增: const context = workflowContext(process.env, JSON.parse(await readFile(process.env.GITHUB_EVENT_PATH, 'utf8'))); | |
| 233 | 新增: const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN; | |
| 234 | 新增: if (!token) throw new Error('Missing release token.'); | |
| 235 | 新增: const headers = { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }; | |
| 236 | 新增: const api = async (method, path, body) => { | |
| 237 | 新增: const response = await fetch(`https://api.github.com${path}`, { | |
| 238 | 新增: method, headers: { ...headers, 'content-type': 'application/json' }, redirect: 'error', | |
| 239 | 新增: body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(60000), | |
| 240 | 新增: }); | |
| 241 | 新增: if (!response.ok) { | |
| 242 | 新增: const error = new Error(`GitHub ${method} ${path.split('?')[0]} failed (${response.status}).`); | |
| 243 | 新增: error.status = response.status; throw error; | |
| 244 | 新增: } | |
| 245 | 新增: return response.status === 204 ? null : response.json(); | |
| 246 | 新增: }; | |
| 247 | 新增: const output = async values => { | |
| 248 | 新增: if (!process.env.GITHUB_OUTPUT) throw new Error('Missing workflow output file.'); | |
| 249 | 新增: await appendFile(process.env.GITHUB_OUTPUT, Object.entries(values).map(([key, value]) => `${key}=${value}\n`).join('')); | |
| 250 | 新增: }; | |
| 251 | 新增: if (process.argv[2] === 'prepare') { | |
| 252 | 新增: const prepared = await prepareRelease({ api, root: repoRoot, ...context }); | |
| 253 | 新增: await output({ version: prepared.version, commit_sha: prepared.commitSha, source_sha: prepared.sourceSha }); | |
| 254 | 新增: console.log(`Prepared v${prepared.version} from ${prepared.sourceSha}; candidate ${prepared.commitSha}.`); | |
| 255 | 新增: } else if (process.argv[2] === 'publish') { | |
| 256 | 新增: const directory = resolve('_output/release-artifacts'); | |
| 257 | 新增: const destination = resolve('_output/publish'); | |
| 258 | 新增: await assembleRelease({ directory, output: destination, version: context.version, commitSha: context.commitSha }); | |
| 259 | 新增: const files = await releaseFiles(destination); | |
| 260 | 新增: const release = await publishRelease({ api, root: repoRoot, files, ...context, | |
| 261 | 新增: promote: async candidate => { | |
| 262 | 新增: const result = spawnSync('git', ['-c', 'credential.helper=!gh auth git-credential', 'push', '--atomic', | |
| 263 | 新增: `https://github.com/${candidate.repository}.git`, `${candidate.commitSha}:refs/heads/main`, `${candidate.commitSha}:refs/tags/v${candidate.version}`], | |
| 264 | 新增: { cwd: repoRoot, env: { ...process.env, GH_TOKEN: token }, encoding: 'utf8' }); | |
| 265 | 新增: if (result.status !== 0) throw new Error('Atomic main/tag promotion failed; no public Release was created. Check branch rules and newer commits.'); | |
| 266 | 新增: }, | |
| 267 | 新增: upload: async (repository, id, file) => { | |
| 268 | 新增: const response = await fetch(`https://uploads.github.com/repos/${repository}/releases/${id}/assets?name=${encodeURIComponent(file.name)}`, { | |
| 269 | 新增: method: 'POST', headers: { ...headers, 'content-type': 'application/octet-stream', 'content-length': String(file.size) }, | |
| 270 | 新增: redirect: 'error', body: Readable.toWeb(createReadStream(file.path)), duplex: 'half', signal: AbortSignal.timeout(20 * 60 * 1000), | |
| 271 | 新增: }); | |
| 272 | 新增: if (!response.ok) throw new Error(`Uploading ${file.name} failed (${response.status}); the draft remains private.`); | |
| 273 | 新增: if (!correctAsset(await response.json(), file)) throw new Error(`GitHub did not confirm the checksum of ${file.name}; the draft remains private.`); | |
| 274 | 新增: }, | |
| 275 | 新增: }); | |
| 276 | 新增: await output({ tag: `v${context.version}`, url: release.html_url }); | |
| 277 | 新增: console.log(`Published ${release.html_url}`); | |
| 278 | 新增: } else throw new Error('Usage: release-control.mjs prepare|publish (explicit release workflow only).'); | |
| 279 | 新增:} | |
| 280 | 新增: | |
| 281 | 新增:if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { | |
| 282 | 新增: main().catch(error => { console.error(error.message); process.exitCode = 1; }); | |
| 283 | 新增:} | |
| @@ -0,0 +1,377 @@ | ||
| 1 | 新增:import assert from 'node:assert/strict'; | |
| 2 | 新增:import { execFileSync } from 'node:child_process'; | |
| 3 | 新增:import { createHash, randomUUID } from 'node:crypto'; | |
| 4 | 新增:import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; | |
| 5 | 新增:import { tmpdir } from 'node:os'; | |
| 6 | 新增:import { dirname, join } from 'node:path'; | |
| 7 | 新增:import test from 'node:test'; | |
| 8 | 新增:import { | |
| 9 | 新增: assembleRelease, expectedFiles, prepareRelease, publishRelease, releaseFiles, | |
| 10 | 新增: verifyCandidate, versionPaths, workflowContext, | |
| 11 | 新增:} from './release-control.mjs'; | |
| 12 | 新增: | |
| 13 | 新增:const repository = 'Lee-xeo/Claude-Cage'; | |
| 14 | 新增:const base = `/repos/${repository}`; | |
| 15 | 新增:const currentVersion = (await readFile(new URL('../VERSION', import.meta.url), 'utf8')).trim(); | |
| 16 | 新增:const windowsDependencies = JSON.parse(await readFile(new URL('../packaging/windows/dependencies.json', import.meta.url), 'utf8')); | |
| 17 | 新增:const linuxDependencies = JSON.parse(await readFile(new URL('../packaging/linux/dependencies.json', import.meta.url), 'utf8')); | |
| 18 | 新增:const macCoreVersion = (await readFile(new URL('./fetch-proxy-core.sh', import.meta.url), 'utf8')).match(/^version=(v[\d.]+)$/m)[1]; | |
| 19 | 新增:const digest = value => createHash('sha256').update(value).digest('hex'); | |
| 20 | 新增:const copy = value => structuredClone(value); | |
| 21 | 新增: | |
| 22 | 新增:async function temporary(t) { | |
| 23 | 新增: const root = await mkdtemp(join(tmpdir(), 'cage-release-control-')); | |
| 24 | 新增: t.after(() => rm(root, { recursive: true, force: true })); | |
| 25 | 新增: return root; | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:// Git trees and commits are real. Only the GitHub transport and remote refs | |
| 29 | 新增:// are simulated, so changes to version files can be checked against Git data. | |
| 30 | 新增:async function repositoryFixture(t) { | |
| 31 | 新增: const root = await temporary(t); | |
| 32 | 新增: const environment = { | |
| 33 | 新增: ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: join(root, 'no-global-config'), | |
| 34 | 新增: GIT_AUTHOR_NAME: 'Release Test', GIT_AUTHOR_EMAIL: '[email protected]', | |
| 35 | 新增: GIT_COMMITTER_NAME: 'Release Test', GIT_COMMITTER_EMAIL: '[email protected]', | |
| 36 | 新增: }; | |
| 37 | 新增: const git = (args, options = {}) => execFileSync('git', args, { | |
| 38 | 新增: cwd: root, encoding: 'utf8', env: environment, stdio: ['pipe', 'pipe', 'pipe'], ...options, | |
| 39 | 新增: }).trimEnd(); | |
| 40 | 新增: git(['init', '--quiet', '--initial-branch=main']); | |
| 41 | 新增: await writeFile(join(root, 'VERSION'), currentVersion + '\n'); | |
| 42 | 新增: for (const directory of ['ui', 'www']) { | |
| 43 | 新增: await mkdir(join(root, directory)); | |
| 44 | 新增: const manifest = { name: directory, version: currentVersion, dependencies: { fixture: '1.0.0' } }; | |
| 45 | 新增: const lock = { ...manifest, lockfileVersion: 3, packages: { '': manifest, 'node_modules/fixture': { version: '1.0.0', integrity: 'keep-this-integrity' } } }; | |
| 46 | 新增: await writeFile(join(root, directory, 'package.json'), JSON.stringify(manifest, null, 2) + '\n'); | |
| 47 | 新增: await writeFile(join(root, directory, 'package-lock.json'), JSON.stringify(lock, null, 2) + '\n'); | |
| 48 | 新增: } | |
| 49 | 新增: git(['add', '--', ...versionPaths]); | |
| 50 | 新增: git(['commit', '--quiet', '-m', 'Fixture source']); | |
| 51 | 新增: const sourceSha = git(['rev-parse', 'HEAD']); | |
| 52 | 新增: const context = { repository, sourceSha, runId: '1042', defaultBranch: 'main', bump: 'prerelease' }; | |
| 53 | 新增: const state = { main: sourceSha, refs: new Map(), release: null, otherReleases: [], nextReleaseId: 42, assets: [], calls: [], uploads: [], promotions: [] }; | |
| 54 | 新增: async function tree(baseTree, entries) { | |
| 55 | 新增: const index = join(root, '.git', `test-index-${randomUUID()}`); | |
| 56 | 新增: const env = { ...environment, GIT_INDEX_FILE: index }; | |
| 57 | 新增: try { | |
| 58 | 新增: git(['read-tree', baseTree], { env }); | |
| 59 | 新增: for (const entry of entries) { | |
| 60 | 新增: const blob = git(['hash-object', '-w', '--stdin'], { input: entry.content, env }); | |
| 61 | 新增: git(['update-index', '--add', '--cacheinfo', entry.mode || '100644', blob, entry.path], { env }); | |
| 62 | 新增: } | |
| 63 | 新增: return git(['write-tree'], { env }); | |
| 64 | 新增: } finally { await rm(index, { force: true }); } | |
| 65 | 新增: } | |
| 66 | 新增: const notFound = () => { throw Object.assign(new Error('Not found'), { status: 404 }); }; | |
| 67 | 新增: const api = async (method, fullPath, body) => { | |
| 68 | 新增: state.calls.push({ method, path: fullPath, body: copy(body) }); | |
| 69 | 新增: assert.ok(fullPath.startsWith(base + '/'), 'API must stay in the configured repository'); | |
| 70 | 新增: const path = fullPath.slice(base.length); | |
| 71 | 新增: if (method === 'GET' && path.startsWith('/git/ref/')) { | |
| 72 | 新增: const ref = path.slice('/git/ref/'.length); | |
| 73 | 新增: const sha = ref === 'heads/main' ? state.main : state.refs.get(ref); | |
| 74 | 新增: return sha ? { object: { sha } } : notFound(); | |
| 75 | 新增: } | |
| 76 | 新增: if (method === 'GET' && path.startsWith('/git/commits/')) { | |
| 77 | 新增: const sha = path.slice('/git/commits/'.length); | |
| 78 | 新增: return { sha, message: git(['show', '-s', '--format=%B', sha]), tree: { sha: git(['rev-parse', `${sha}^{tree}`]) }, | |
| 79 | 新增: parents: git(['show', '-s', '--format=%P', sha]).split(' ').filter(Boolean).map(parent => ({ sha: parent })) }; | |
| 80 | 新增: } | |
| 81 | 新增: if (method === 'GET' && path.startsWith('/compare/')) { | |
| 82 | 新增: const [from, to] = path.slice('/compare/'.length).split('...'); | |
| 83 | 新增: const files = git(['diff', '--name-status', from, to]).split('\n').filter(Boolean).map(line => { | |
| 84 | 新增: const [status, filename] = line.split('\t'); | |
| 85 | 新增: return { status: status === 'M' ? 'modified' : 'added', filename }; | |
| 86 | 新增: }); | |
| 87 | 新增: return { status: 'ahead', ahead_by: Number(git(['rev-list', '--count', `${from}..${to}`])), files }; | |
| 88 | 新增: } | |
| 89 | 新增: if (method === 'GET' && path.startsWith('/contents/')) { | |
| 90 | 新增: const [filename, sha] = path.slice('/contents/'.length).split('?ref='); | |
| 91 | 新增: const content = execFileSync('git', ['show', `${sha}:${filename}`], { cwd: root, env: environment }); | |
| 92 | 新增: return { type: 'file', encoding: 'base64', content: content.toString('base64') }; | |
| 93 | 新增: } | |
| 94 | 新增: if (method === 'GET' && path === '/git/matching-refs/tags/v') return []; | |
| 95 | 新增: if (method === 'GET' && path.startsWith('/releases?')) { | |
| 96 | 新增: const query = new URL(path, 'https://api.example.invalid').searchParams; | |
| 97 | 新增: const page = Number(query.get('page') || 1); | |
| 98 | 新增: const size = Number(query.get('per_page') || 30); | |
| 99 | 新增: const releases = [...state.otherReleases, ...(state.release ? [state.release] : [])]; | |
| 100 | 新增: return copy(releases.slice((page - 1) * size, page * size)); | |
| 101 | 新增: } | |
| 102 | 新增: if (method === 'POST' && path === '/git/trees') return { sha: await tree(body.base_tree, body.tree) }; | |
| 103 | 新增: if (method === 'POST' && path === '/git/commits') { | |
| 104 | 新增: return { sha: git(['commit-tree', body.tree, '-p', body.parents[0]], { input: body.message }) }; | |
| 105 | 新增: } | |
| 106 | 新增: if (method === 'POST' && path === '/git/refs') { | |
| 107 | 新增: state.refs.set(body.ref.replace('refs/', ''), body.sha); | |
| 108 | 新增: return { object: { sha: body.sha } }; | |
| 109 | 新增: } | |
| 110 | 新增: // GitHub's tag lookup exposes published Releases only, even when this | |
| 111 | 新增: // token can list private drafts. Resume logic must use the list endpoint. | |
| 112 | 新增: if (method === 'GET' && path.startsWith('/releases/tags/')) { | |
| 113 | 新增: const tag = decodeURIComponent(path.slice('/releases/tags/'.length)); | |
| 114 | 新增: const found = [...state.otherReleases, ...(state.release ? [state.release] : [])] | |
| 115 | 新增: .find(release => !release.draft && release.tag_name === tag); | |
| 116 | 新增: return found ? copy(found) : notFound(); | |
| 117 | 新增: } | |
| 118 | 新增: if (method === 'POST' && path === '/releases/generate-notes') return { body: 'Fixture release notes' }; | |
| 119 | 新增: if (method === 'POST' && path === '/releases') { | |
| 120 | 新增: if (state.release) state.otherReleases.push(copy(state.release)); | |
| 121 | 新增: const id = state.nextReleaseId++; | |
| 122 | 新增: state.release = { ...body, id, html_url: `https://example.invalid/release/${id}` }; | |
| 123 | 新增: state.assets = []; | |
| 124 | 新增: return copy(state.release); | |
| 125 | 新增: } | |
| 126 | 新增: if (method === 'GET' && path === `/releases/${state.release?.id}/assets?per_page=100`) return copy(state.assets); | |
| 127 | 新增: if (method === 'GET' && path === `/releases/${state.release?.id}`) return copy(state.release); | |
| 128 | 新增: if (method === 'DELETE' && path.startsWith('/releases/assets/')) { | |
| 129 | 新增: state.assets = state.assets.filter(asset => asset.id !== Number(path.split('/').at(-1))); | |
| 130 | 新增: return null; | |
| 131 | 新增: } | |
| 132 | 新增: if (method === 'PATCH' && path === `/releases/${state.release?.id}`) { | |
| 133 | 新增: Object.assign(state.release, body); | |
| 134 | 新增: return copy(state.release); | |
| 135 | 新增: } | |
| 136 | 新增: throw new Error(`Unexpected fake API request: ${method} ${path}`); | |
| 137 | 新增: }; | |
| 138 | 新增: const promote = async candidate => { | |
| 139 | 新增: state.promotions.push(copy(candidate)); | |
| 140 | 新增: state.main = candidate.commitSha; | |
| 141 | 新增: state.refs.set(`tags/v${candidate.version}`, candidate.commitSha); | |
| 142 | 新增: }; | |
| 143 | 新增: const upload = async (_repository, _id, file) => { | |
| 144 | 新增: state.uploads.push(file.name); | |
| 145 | 新增: state.assets.push({ id: state.assets.length + 1, name: file.name, state: 'uploaded', size: file.size, digest: file.digest }); | |
| 146 | 新增: }; | |
| 147 | 新增: const candidate = () => prepareRelease({ api, root, ...context }); | |
| 148 | 新增: return { root, git, tree, api, context, state, promote, upload, candidate }; | |
| 149 | 新增:} | |
| 150 | 新增: | |
| 151 | 新增:async function uploadFiles(root, version) { | |
| 152 | 新增: const directory = join(root, 'publish'); | |
| 153 | 新增: await mkdir(directory); | |
| 154 | 新增: const names = [`Cage-${version}-macos-arm64.dmg`, `Cage-${version}-windows-amd64-setup.exe`, `Cage-${version}-linux-amd64.deb`]; | |
| 155 | 新增: for (const name of names) await writeFile(join(directory, name), `fixture ${name}`); | |
| 156 | 新增: await writeFile(join(directory, 'SHA256SUMS'), names.map(name => `${digest(`fixture ${name}`)} ${name}\n`).join('')); | |
| 157 | 新增: return releaseFiles(directory); | |
| 158 | 新增:} | |
| 159 | 新增: | |
| 160 | 新增:function publish(fixture, candidate, files, overrides = {}) { | |
| 161 | 新增: const { api, root, promote, upload } = fixture; | |
| 162 | 新增: return publishRelease({ api, root, promote, upload, ...candidate, files, ...overrides }); | |
| 163 | 新增:} | |
| 164 | 新增: | |
| 165 | 新增:function published(fixture, candidate, files, runId = candidate.runId) { | |
| 166 | 新增: fixture.state.main = candidate.commitSha; | |
| 167 | 新增: fixture.state.refs.set(`tags/v${candidate.version}`, candidate.commitSha); | |
| 168 | 新增: fixture.state.release = { id: 42, tag_name: `v${candidate.version}`, draft: false, | |
| 169 | 新增: body: `<!-- cage-release-run:${runId}; commit:${candidate.commitSha} -->` }; | |
| 170 | 新增: fixture.state.assets = files.map((file, index) => ({ id: index + 1, name: file.name, state: 'uploaded', size: file.size, digest: file.digest })); | |
| 171 | 新增:} | |
| 172 | 新增: | |
| 173 | 新增:test('release context rejects ordinary pushes, forks and non-main dispatches', () => { | |
| 174 | 新增: const env = { GITHUB_ACTIONS: 'true', GITHUB_EVENT_NAME: 'workflow_dispatch', GITHUB_REF: 'refs/heads/main', | |
| 175 | 新增: GITHUB_REPOSITORY: repository, GITHUB_SHA: 'a'.repeat(40), GITHUB_RUN_ID: '1042' }; | |
| 176 | 新增: const event = { repository: { default_branch: 'main' }, inputs: { bump: 'prerelease' } }; | |
| 177 | 新增: assert.equal(workflowContext(env, event).sourceSha, env.GITHUB_SHA); | |
| 178 | 新增: for (const change of [{ GITHUB_EVENT_NAME: 'push' }, { GITHUB_REPOSITORY: 'someone/fork' }, { GITHUB_REF: 'refs/heads/feature' }, { GITHUB_ACTIONS: 'false' }, { GITHUB_SHA: 'main' }]) { | |
| 179 | 新增: assert.throws(() => workflowContext({ ...env, ...change }, event)); | |
| 180 | 新增: } | |
| 181 | 新增:}); | |
| 182 | 新增: | |
| 183 | 新增:test('prepare leaves the working version unchanged and reuses the same run candidate', async t => { | |
| 184 | 新增: const f = await repositoryFixture(t); | |
| 185 | 新增: const before = await readFile(join(f.root, 'VERSION'), 'utf8'); | |
| 186 | 新增: const first = await f.candidate(); | |
| 187 | 新增: assert.notEqual(first.version, currentVersion); | |
| 188 | 新增: assert.equal(await readFile(join(f.root, 'VERSION'), 'utf8'), before); | |
| 189 | 新增: assert.equal(f.git(['status', '--porcelain']), ''); | |
| 190 | 新增: assert.equal(f.state.main, f.context.sourceSha); | |
| 191 | 新增: const second = await f.candidate(); | |
| 192 | 新增: assert.equal(second.commitSha, first.commitSha); | |
| 193 | 新增: assert.equal(second.version, first.version); | |
| 194 | 新增: assert.equal(f.state.calls.filter(call => call.method === 'POST' && call.path.endsWith('/git/commits')).length, 1); | |
| 195 | 新增:}); | |
| 196 | 新增: | |
| 197 | 新增:test('main movement prevents candidate creation and later publication', async t => { | |
| 198 | 新增: const f = await repositoryFixture(t); | |
| 199 | 新增: f.state.main = 'b'.repeat(40); | |
| 200 | 新增: await assert.rejects(f.candidate(), /Main advanced/); | |
| 201 | 新增: assert.equal(f.state.calls.some(call => call.method !== 'GET'), false); | |
| 202 | 新增: f.state.main = f.context.sourceSha; | |
| 203 | 新增: const candidate = await f.candidate(); | |
| 204 | 新增: const files = await uploadFiles(f.root, candidate.version); | |
| 205 | 新增: f.state.main = 'b'.repeat(40); | |
| 206 | 新增: await assert.rejects(publish(f, candidate, files), /Main changed/); | |
| 207 | 新增: assert.equal(f.state.promotions.length, 0); | |
| 208 | 新增: assert.equal(f.state.uploads.length, 0); | |
| 209 | 新增: assert.equal(f.state.release, null); | |
| 210 | 新增:}); | |
| 211 | 新增: | |
| 212 | 新增:test('candidate verification rejects extra files and dependency edits hidden in version files', async t => { | |
| 213 | 新增: for (const kind of ['extra file', 'dependency change']) await t.test(kind, async t => { | |
| 214 | 新增: const f = await repositoryFixture(t); | |
| 215 | 新增: const candidate = await f.candidate(); | |
| 216 | 新增: const expected = await expectedFiles(f.root, candidate.sourceSha, candidate.version); | |
| 217 | 新增: const changed = new Map(expected); | |
| 218 | 新增: if (kind === 'extra file') changed.set('unexpected-script.sh', 'echo unauthorized\n'); | |
| 219 | 新增: else changed.set('ui/package.json', changed.get('ui/package.json').replace('"fixture": "1.0.0"', '"fixture": "9.9.9"')); | |
| 220 | 新增: const treeSha = await f.tree(f.git(['rev-parse', `${candidate.sourceSha}^{tree}`]), [...changed].map(([path, content]) => ({ path, content }))); | |
| 221 | 新增: const message = f.git(['show', '-s', '--format=%B', candidate.commitSha]); | |
| 222 | 新增: const commitSha = f.git(['commit-tree', treeSha, '-p', candidate.sourceSha], { input: message }); | |
| 223 | 新增: await assert.rejects(verifyCandidate(f.api, { ...candidate, commitSha }, expected), /only the five|unexpected change/); | |
| 224 | 新增: }); | |
| 225 | 新增:}); | |
| 226 | 新增: | |
| 227 | 新增:async function artifactFixture(t) { | |
| 228 | 新增: const root = await temporary(t); | |
| 229 | 新增: const commitSha = 'a'.repeat(40); | |
| 230 | 新增: const packages = { | |
| 231 | 新增: macos: { [`Cage-${currentVersion}-macos-arm64.dmg`]: 'mac installer', [`mihomo-${macCoreVersion}-source.tar.gz`]: 'same core source' }, | |
| 232 | 新增: windows: { [`Cage-${currentVersion}-windows-amd64-setup.exe`]: 'windows installer', [`mihomo-${windowsDependencies.mihomo.version}-source.tar.gz`]: 'same core source', [`qemu-${windowsDependencies.qemu.version}-windows-full-source.zip`]: 'complete qemu source' }, | |
| 233 | 新增: linux: { [`Cage-${currentVersion}-linux-amd64.deb`]: 'linux installer', [linuxDependencies.mihomoSource.file]: 'same core source' }, | |
| 234 | 新增: }; | |
| 235 | 新增: for (const [platform, entries] of Object.entries(packages)) { | |
| 236 | 新增: const directory = join(root, platform); | |
| 237 | 新增: await mkdir(directory); | |
| 238 | 新增: for (const [name, content] of Object.entries(entries)) await writeFile(join(directory, name), content); | |
| 239 | 新增: await writeFile(join(directory, 'SHA256SUMS'), Object.entries(entries).map(([name, content]) => `${digest(content)} ${name}\n`).join('')); | |
| 240 | 新增: await writeFile(join(directory, 'build-metadata.json'), JSON.stringify({ schema: 1, platform, version: currentVersion, commitSha })); | |
| 241 | 新增: } | |
| 242 | 新增: return { directory: root, output: join(root, 'assembled'), version: currentVersion, commitSha }; | |
| 243 | 新增:} | |
| 244 | 新增: | |
| 245 | 新增:test('all three platform identities are required before any assets are assembled', async t => { | |
| 246 | 新增: for (const kind of ['missing metadata', 'different commit', 'different version']) await t.test(kind, async t => { | |
| 247 | 新增: const f = await artifactFixture(t); | |
| 248 | 新增: const path = join(f.directory, 'linux', 'build-metadata.json'); | |
| 249 | 新增: if (kind === 'missing metadata') await rm(path); | |
| 250 | 新增: else { | |
| 251 | 新增: const metadata = JSON.parse(await readFile(path, 'utf8')); | |
| 252 | 新增: if (kind === 'different commit') metadata.commitSha = 'b'.repeat(40); | |
| 253 | 新增: else metadata.version = '99.0.0'; | |
| 254 | 新增: await writeFile(path, JSON.stringify(metadata)); | |
| 255 | 新增: } | |
| 256 | 新增: let assembled = false; | |
| 257 | 新增: await assert.rejects(assembleRelease({ ...f, assemble: async () => { assembled = true; throw new Error('must not assemble'); } })); | |
| 258 | 新增: assert.equal(assembled, false); | |
| 259 | 新增: }); | |
| 260 | 新增:}); | |
| 261 | 新增: | |
| 262 | 新增:test('assembly accepts matching platforms but excludes metadata from public assets', async t => { | |
| 263 | 新增: const f = await artifactFixture(t); | |
| 264 | 新增: const result = await assembleRelease(f); | |
| 265 | 新增: assert.ok(result.assets.includes(`Cage-${currentVersion}-linux-amd64.deb`)); | |
| 266 | 新增: assert.ok(!result.assets.some(name => name.includes('metadata'))); | |
| 267 | 新增: assert.ok((await releaseFiles(f.output)).length > 3); | |
| 268 | 新增:}); | |
| 269 | 新增: | |
| 270 | 新增:test('an installer for an unsupported version cannot enter the public release', async t => { | |
| 271 | 新增: const f = await artifactFixture(t); | |
| 272 | 新增: const wrong = 'Cage-99999.0.0-linux-amd64.deb'; | |
| 273 | 新增: const path = join(f.directory, 'linux'); | |
| 274 | 新增: await writeFile(join(path, wrong), 'wrong version'); | |
| 275 | 新增: const manifest = await readFile(join(path, 'SHA256SUMS'), 'utf8'); | |
| 276 | 新增: await writeFile(join(path, 'SHA256SUMS'), manifest + `${digest('wrong version')} ${wrong}\n`); | |
| 277 | 新增: await assert.rejects(assembleRelease(f), /Unsupported asset or version/); | |
| 278 | 新增:}); | |
| 279 | 新增: | |
| 280 | 新增:test('a public release owned by another run is never overwritten', async t => { | |
| 281 | 新增: const f = await repositoryFixture(t); | |
| 282 | 新增: const candidate = await f.candidate(); | |
| 283 | 新增: const files = await uploadFiles(f.root, candidate.version); | |
| 284 | 新增: published(f, candidate, files, '9999'); | |
| 285 | 新增: const before = copy(f.state.release); | |
| 286 | 新增: await assert.rejects(publish(f, candidate, files), /another operation/); | |
| 287 | 新增: assert.deepEqual(f.state.release, before); | |
| 288 | 新增: assert.equal(f.state.promotions.length, 0); | |
| 289 | 新增: assert.equal(f.state.uploads.length, 0); | |
| 290 | 新增:}); | |
| 291 | 新增: | |
| 292 | 新增:test('an upload failure retains a private draft and never publishes partial assets', async t => { | |
| 293 | 新增: const f = await repositoryFixture(t); | |
| 294 | 新增: const candidate = await f.candidate(); | |
| 295 | 新增: const files = await uploadFiles(f.root, candidate.version); | |
| 296 | 新增: let attempts = 0; | |
| 297 | 新增: await assert.rejects(publish(f, candidate, files, { upload: async (...args) => { | |
| 298 | 新增: if (++attempts === 2) throw new Error('fixture upload failure'); | |
| 299 | 新增: await f.upload(...args); | |
| 300 | 新增: } }), /fixture upload failure/); | |
| 301 | 新增: assert.equal(f.state.release.draft, true); | |
| 302 | 新增: assert.equal(f.state.assets.length, 1); | |
| 303 | 新增: assert.equal(f.state.calls.some(call => call.method === 'PATCH'), false); | |
| 304 | 新增:}); | |
| 305 | 新增: | |
| 306 | 新增:test('retry after an interrupted upload resumes the same private draft, including on the second page', async t => { | |
| 307 | 新增: for (const precedingReleases of [0, 100]) await t.test(precedingReleases ? 'draft on page two' : 'draft on page one', async t => { | |
| 308 | 新增: const f = await repositoryFixture(t); | |
| 309 | 新增: const candidate = await f.candidate(); | |
| 310 | 新增: const files = await uploadFiles(f.root, candidate.version); | |
| 311 | 新增: let attempts = 0; | |
| 312 | 新增: await assert.rejects(publish(f, candidate, files, { upload: async (...args) => { | |
| 313 | 新增: if (++attempts === 2) throw new Error('fixture interrupted upload'); | |
| 314 | 新增: await f.upload(...args); | |
| 315 | 新增: } }), /fixture interrupted upload/); | |
| 316 | 新增: const draftId = f.state.release.id; | |
| 317 | 新增: assert.equal(f.state.release.draft, true); | |
| 318 | 新增: assert.equal(f.state.assets.length, 1); | |
| 319 | 新增: const completedAsset = f.state.assets[0].name; | |
| 320 | 新增: await assert.rejects(f.api('GET', `${base}/releases/tags/v${candidate.version}`), { status: 404 }); | |
| 321 | 新增: f.state.otherReleases = Array.from({ length: precedingReleases }, (_, i) => ({ | |
| 322 | 新增: id: 1000 + i, tag_name: `v0.0.0-fixture.${i}`, draft: false, body: 'Unrelated older release', | |
| 323 | 新增: })); | |
| 324 | 新增: const resumed = await publish(f, candidate, files); | |
| 325 | 新增: assert.equal(resumed.id, draftId); | |
| 326 | 新增: assert.equal(resumed.draft, false); | |
| 327 | 新增: assert.equal(f.state.calls.filter(call => call.method === 'POST' && call.path === `${base}/releases`).length, 1); | |
| 328 | 新增: assert.equal(f.state.uploads.filter(name => name === completedAsset).length, 1); | |
| 329 | 新增: assert.deepEqual(new Set(f.state.assets.map(asset => asset.name)), new Set(files.map(file => file.name))); | |
| 330 | 新增: }); | |
| 331 | 新增:}); | |
| 332 | 新增: | |
| 333 | 新增:test('multiple drafts reserving the same tag are left untouched', async t => { | |
| 334 | 新增: const f = await repositoryFixture(t); | |
| 335 | 新增: const candidate = await f.candidate(); | |
| 336 | 新增: const files = await uploadFiles(f.root, candidate.version); | |
| 337 | 新增: published(f, candidate, files); | |
| 338 | 新增: f.state.release.draft = true; | |
| 339 | 新增: f.state.otherReleases.push({ ...copy(f.state.release), id: 43 }); | |
| 340 | 新增: const before = copy([f.state.release, ...f.state.otherReleases]); | |
| 341 | 新增: f.state.calls.length = 0; | |
| 342 | 新增: await assert.rejects(publish(f, candidate, files), /Multiple Releases reserve/); | |
| 343 | 新增: assert.deepEqual([f.state.release, ...f.state.otherReleases], before); | |
| 344 | 新增: assert.equal(f.state.calls.some(call => call.method !== 'GET'), false); | |
| 345 | 新增: assert.equal(f.state.promotions.length, 0); | |
| 346 | 新增: assert.equal(f.state.uploads.length, 0); | |
| 347 | 新增:}); | |
| 348 | 新增: | |
| 349 | 新增:test('missing or incorrect server digests prevent publication even after successful upload requests', async t => { | |
| 350 | 新增: for (const receivedDigest of [undefined, `sha256:${'0'.repeat(64)}`]) await t.test(receivedDigest ? 'wrong digest' : 'missing digest', async t => { | |
| 351 | 新增: const f = await repositoryFixture(t); | |
| 352 | 新增: const candidate = await f.candidate(); | |
| 353 | 新增: const files = await uploadFiles(f.root, candidate.version); | |
| 354 | 新增: await assert.rejects(publish(f, candidate, files, { upload: async (...args) => { | |
| 355 | 新增: await f.upload(...args); | |
| 356 | 新增: f.state.assets.at(-1).digest = receivedDigest; | |
| 357 | 新增: } }), /uploaded assets do not match/); | |
| 358 | 新增: assert.equal(f.state.release.draft, true); | |
| 359 | 新增: assert.equal(f.state.calls.some(call => call.method === 'PATCH'), false); | |
| 360 | 新增: }); | |
| 361 | 新增:}); | |
| 362 | 新增: | |
| 363 | 新增:test('retrying this run after publication checks identical assets without uploading or changing refs', async t => { | |
| 364 | 新增: const f = await repositoryFixture(t); | |
| 365 | 新增: const candidate = await f.candidate(); | |
| 366 | 新增: const files = await uploadFiles(f.root, candidate.version); | |
| 367 | 新增: const first = await publish(f, candidate, files); | |
| 368 | 新增: assert.equal(first.draft, false); | |
| 369 | 新增: const uploaded = [...f.state.uploads]; | |
| 370 | 新增: const promotions = f.state.promotions.length; | |
| 371 | 新增: const mutations = f.state.calls.filter(call => call.method !== 'GET').length; | |
| 372 | 新增: const again = await publish(f, candidate, files); | |
| 373 | 新增: assert.equal(again.id, first.id); | |
| 374 | 新增: assert.deepEqual(f.state.uploads, uploaded); | |
| 375 | 新增: assert.equal(f.state.promotions.length, promotions); | |
| 376 | 新增: assert.equal(f.state.calls.filter(call => call.method !== 'GET').length, mutations); | |
| 377 | 新增:}); | |
| @@ -0,0 +1,156 @@ | ||
| 1 | 新增:import { execFileSync } from 'node:child_process'; | |
| 2 | 新增:import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; | |
| 3 | 新增:import { dirname, resolve } from 'node:path'; | |
| 4 | 新增:import { fileURLToPath, pathToFileURL } from 'node:url'; | |
| 5 | 新增: | |
| 6 | 新增:const numeric = /^(?:0|[1-9][0-9]*)$/; | |
| 7 | 新增:const syntax = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/; | |
| 8 | 新增: | |
| 9 | 新增:export function parseVersion(version) { | |
| 10 | 新增: if (typeof version !== 'string' || version !== version.trim()) throw new Error('Expected a canonical SemVer without build metadata'); | |
| 11 | 新增: const match = syntax.exec(version); | |
| 12 | 新增: if (!match) throw new Error(`Invalid version: ${version}`); | |
| 13 | 新增: const prerelease = match[4] ? match[4].split('.') : []; | |
| 14 | 新增: if (prerelease.some(part => /^[0-9]+$/.test(part) && !numeric.test(part))) throw new Error(`Invalid numeric prerelease identifier: ${version}`); | |
| 15 | 新增: return { major: BigInt(match[1]), minor: BigInt(match[2]), patch: BigInt(match[3]), prerelease }; | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:function compare(a, b) { | |
| 19 | 新增: return a === b ? 0 : a < b ? -1 : 1; | |
| 20 | 新增:} | |
| 21 | 新增: | |
| 22 | 新增:export function compareVersions(a, b) { | |
| 23 | 新增: const left = parseVersion(a); | |
| 24 | 新增: const right = parseVersion(b); | |
| 25 | 新增: for (const part of ['major', 'minor', 'patch']) { | |
| 26 | 新增: const order = compare(left[part], right[part]); | |
| 27 | 新增: if (order) return order; | |
| 28 | 新增: } | |
| 29 | 新增: if (!left.prerelease.length || !right.prerelease.length) { | |
| 30 | 新增: return compare(Number(!left.prerelease.length), Number(!right.prerelease.length)); | |
| 31 | 新增: } | |
| 32 | 新增: for (let index = 0; index < Math.max(left.prerelease.length, right.prerelease.length); index++) { | |
| 33 | 新增: const x = left.prerelease[index]; | |
| 34 | 新增: const y = right.prerelease[index]; | |
| 35 | 新增: if (x === undefined || y === undefined) return compare(left.prerelease.length, right.prerelease.length); | |
| 36 | 新增: const xNumeric = numeric.test(x); | |
| 37 | 新增: const yNumeric = numeric.test(y); | |
| 38 | 新增: const order = xNumeric && yNumeric ? compare(BigInt(x), BigInt(y)) | |
| 39 | 新增: : xNumeric !== yNumeric ? (xNumeric ? -1 : 1) : compare(x, y); | |
| 40 | 新增: if (order) return order; | |
| 41 | 新增: } | |
| 42 | 新增: return 0; | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:export function nextVersion(current, bump, existingTags = []) { | |
| 46 | 新增: parseVersion(current); | |
| 47 | 新增: if (!['prerelease', 'patch', 'minor', 'major'].includes(bump)) throw new Error(`Unsupported version bump: ${bump}`); | |
| 48 | 新增: if (!Array.isArray(existingTags)) throw new TypeError('existingTags must be an array'); | |
| 49 | 新增: let highest = current; | |
| 50 | 新增: for (const tag of existingTags) { | |
| 51 | 新增: if (typeof tag !== 'string' || !tag.startsWith('v')) continue; | |
| 52 | 新增: const version = tag.slice(1); | |
| 53 | 新增: try { parseVersion(version); } catch { continue; } | |
| 54 | 新增: if (compareVersions(version, highest) > 0) highest = version; | |
| 55 | 新增: } | |
| 56 | 新增: let { major, minor, patch, prerelease } = parseVersion(highest); | |
| 57 | 新增: if (bump === 'major') { | |
| 58 | 新增: major++; | |
| 59 | 新增: minor = patch = 0n; | |
| 60 | 新增: prerelease = []; | |
| 61 | 新增: } else if (bump === 'minor') { | |
| 62 | 新增: minor++; | |
| 63 | 新增: patch = 0n; | |
| 64 | 新增: prerelease = []; | |
| 65 | 新增: } else if (bump === 'patch') { | |
| 66 | 新增: if (!prerelease.length) patch++; | |
| 67 | 新增: prerelease = []; | |
| 68 | 新增: } else if (!prerelease.length) { | |
| 69 | 新增: patch++; | |
| 70 | 新增: prerelease = ['alpha', '1']; | |
| 71 | 新增: } else { | |
| 72 | 新增: const last = prerelease.length - 1; | |
| 73 | 新增: if (numeric.test(prerelease[last])) prerelease[last] = String(BigInt(prerelease[last]) + 1n); | |
| 74 | 新增: else prerelease.push('1'); | |
| 75 | 新增: } | |
| 76 | 新增: return `${major}.${minor}.${patch}${prerelease.length ? `-${prerelease.join('.')}` : ''}`; | |
| 77 | 新增:} | |
| 78 | 新增: | |
| 79 | 新增:// JSON.parse validates the document first. Locate only the requested string | |
| 80 | 新增:// values so dependency data, escaped strings and all formatting stay intact. | |
| 81 | 新增:function replaceVersions(text, paths, version) { | |
| 82 | 新增: const tokens = [...text.matchAll(/"(?:\\.|[^"\\])*"|[{}\[\]:,]|-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|true|false|null/g)]; | |
| 83 | 新增: const changes = []; | |
| 84 | 新增: const counts = paths.map(() => 0); | |
| 85 | 新增: let index = 0; | |
| 86 | 新增: function value(path) { | |
| 87 | 新增: const token = tokens[index++]; | |
| 88 | 新增: const target = paths.findIndex(candidate => candidate.length === path.length && candidate.every((part, i) => part === path[i])); | |
| 89 | 新增: if (target !== -1) { | |
| 90 | 新增: if (!token[0].startsWith('"')) throw new Error('Package version fields must be strings'); | |
| 91 | 新增: counts[target]++; | |
| 92 | 新增: changes.push({ start: token.index, end: token.index + token[0].length }); | |
| 93 | 新增: } | |
| 94 | 新增: if (token[0] === '{') { | |
| 95 | 新增: if (tokens[index][0] === '}') { index++; return; } | |
| 96 | 新增: do { | |
| 97 | 新增: const key = JSON.parse(tokens[index++][0]); | |
| 98 | 新增: index++; // Colon. | |
| 99 | 新增: value([...path, key]); | |
| 100 | 新增: } while (tokens[index++][0] !== '}'); | |
| 101 | 新增: } else if (token[0] === '[') { | |
| 102 | 新增: if (tokens[index][0] === ']') { index++; return; } | |
| 103 | 新增: let item = 0; | |
| 104 | 新增: do { value([...path, item++]); } while (tokens[index++][0] !== ']'); | |
| 105 | 新增: } | |
| 106 | 新增: } | |
| 107 | 新增: value([]); | |
| 108 | 新增: if (counts.some(count => count !== 1)) throw new Error('Expected exactly one value for each package version field'); | |
| 109 | 新增: let result = text; | |
| 110 | 新增: for (const { start, end } of changes.sort((a, b) => b.start - a.start)) { | |
| 111 | 新增: result = result.slice(0, start) + JSON.stringify(version) + result.slice(end); | |
| 112 | 新增: } | |
| 113 | 新增: return result; | |
| 114 | 新增:} | |
| 115 | 新增: | |
| 116 | 新增:export function versionFiles(root, version) { | |
| 117 | 新增: parseVersion(version); | |
| 118 | 新增: const versionPath = resolve(root, 'VERSION'); | |
| 119 | 新增: const original = readFileSync(versionPath, 'utf8'); | |
| 120 | 新增: const current = original.trim(); | |
| 121 | 新增: parseVersion(current); | |
| 122 | 新增: const result = new Map([[versionPath, original.replace(current, version)]]); | |
| 123 | 新增: for (const directory of ['ui', 'www']) { | |
| 124 | 新增: for (const filename of ['package.json', 'package-lock.json']) { | |
| 125 | 新增: const path = resolve(root, directory, filename); | |
| 126 | 新增: const text = readFileSync(path, 'utf8'); | |
| 127 | 新增: const document = JSON.parse(text); | |
| 128 | 新增: const lock = filename === 'package-lock.json'; | |
| 129 | 新增: if (document?.version !== current || (lock && document?.packages?.['']?.version !== current)) { | |
| 130 | 新增: throw new Error(`${directory}/${filename}: version fields must match VERSION (${current})`); | |
| 131 | 新增: } | |
| 132 | 新增: const paths = lock ? [['version'], ['packages', '', 'version']] : [['version']]; | |
| 133 | 新增: result.set(path, replaceVersions(text, paths, version)); | |
| 134 | 新增: } | |
| 135 | 新增: } | |
| 136 | 新增: return result; | |
| 137 | 新增:} | |
| 138 | 新增: | |
| 139 | 新增:function main(args) { | |
| 140 | 新增: const [command, platform, output] = args; | |
| 141 | 新增: if (args.length !== 3 || command !== 'metadata' || !['macos', 'windows', 'linux'].includes(platform)) { | |
| 142 | 新增: throw new Error('Usage: node scripts/release-version.mjs metadata <macos|windows|linux> <output>'); | |
| 143 | 新增: } | |
| 144 | 新增: const root = fileURLToPath(new URL('../', import.meta.url)); | |
| 145 | 新增: const version = readFileSync(resolve(root, 'VERSION'), 'utf8').trim(); | |
| 146 | 新增: parseVersion(version); | |
| 147 | 新增: const commitSha = execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); | |
| 148 | 新增: if (!/^[0-9a-f]{40}$/.test(commitSha)) throw new Error('Release metadata requires a 40-character Git commit SHA'); | |
| 149 | 新增: const destination = resolve(output); | |
| 150 | 新增: mkdirSync(dirname(destination), { recursive: true }); | |
| 151 | 新增: writeFileSync(destination, `${JSON.stringify({ schema: 1, platform, version, commitSha }, null, 2)}\n`); | |
| 152 | 新增:} | |
| 153 | 新增: | |
| 154 | 新增:if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { | |
| 155 | 新增: try { main(process.argv.slice(2)); } catch (error) { console.error(error.message); process.exitCode = 1; } | |
| 156 | 新增:} | |
| @@ -0,0 +1,148 @@ | ||
| 1 | 新增:import assert from 'node:assert/strict'; | |
| 2 | 新增:import { execFileSync, spawnSync } from 'node:child_process'; | |
| 3 | 新增:import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; | |
| 4 | 新增:import { tmpdir } from 'node:os'; | |
| 5 | 新增:import { join } from 'node:path'; | |
| 6 | 新增:import { fileURLToPath } from 'node:url'; | |
| 7 | 新增:import test from 'node:test'; | |
| 8 | 新增:import { compareVersions, nextVersion, parseVersion, versionFiles } from './release-version.mjs'; | |
| 9 | 新增: | |
| 10 | 新增:function fixture(t) { | |
| 11 | 新增: const root = mkdtempSync(join(tmpdir(), 'cage-release-version-')); | |
| 12 | 新增: t.after(() => rmSync(root, { recursive: true, force: true })); | |
| 13 | 新增: writeFileSync(join(root, 'VERSION'), '1.2.3-alpha.9\r\n'); | |
| 14 | 新增: for (const directory of ['ui', 'www']) { | |
| 15 | 新增: mkdirSync(join(root, directory)); | |
| 16 | 新增: writeFileSync(join(root, directory, 'package.json'), '{\r\n\t"name" : "fixture",\r\n\t"version": "1.2.3-alpha.9",\r\n\t"dependencies": {"same-version": "1.2.3-alpha.9"},\r\n\t"number": 900719925474099312345\r\n}\r\n'); | |
| 17 | 新增: writeFileSync(join(root, directory, 'package-lock.json'), JSON.stringify({ | |
| 18 | 新增: name: 'fixture', version: '1.2.3-alpha.9', lockfileVersion: 3, | |
| 19 | 新增: packages: { | |
| 20 | 新增: '': { name: 'fixture', version: '1.2.3-alpha.9', dependencies: { library: '^2.0.0' } }, | |
| 21 | 新增: 'node_modules/library': { version: '1.2.3-alpha.9', resolved: 'https://example.invalid/library.tgz', integrity: 'sha512-fixture', engines: { node: '>=24' } }, | |
| 22 | 新增: }, | |
| 23 | 新增: metadata: [{ version: '1.2.3-alpha.9' }, true, null, 1.2e-3], | |
| 24 | 新增: }, null, 4) + '\n'); | |
| 25 | 新增: } | |
| 26 | 新增: return root; | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:test('parses canonical SemVer and rejects ambiguous or unsupported forms', () => { | |
| 30 | 新增: assert.deepEqual(parseVersion('1.2.3-alpha.10'), { major: 1n, minor: 2n, patch: 3n, prerelease: ['alpha', '10'] }); | |
| 31 | 新增: assert.deepEqual(parseVersion('0.0.0-0'), { major: 0n, minor: 0n, patch: 0n, prerelease: ['0'] }); | |
| 32 | 新增: assert.deepEqual(parseVersion('1.0.0-01a'), { major: 1n, minor: 0n, patch: 0n, prerelease: ['01a'] }); | |
| 33 | 新增: for (const invalid of [null, 1, '', 'v1.2.3', '1.2', '01.2.3', '1.02.3', '1.2.03', '1.2.3-01', '1.2.3-a.00', '1.2.3-', '1.2.3-a..b', '1.2.3+build', '1.2.3-a+b', ' 1.2.3', '1.2.3\n', '1.2.3-中文']) { | |
| 34 | 新增: assert.throws(() => parseVersion(invalid), /version|SemVer|prerelease/i, String(invalid)); | |
| 35 | 新增: } | |
| 36 | 新增:}); | |
| 37 | 新增: | |
| 38 | 新增:test('orders prereleases numerically and compares large identifiers without rounding', () => { | |
| 39 | 新增: const ordered = ['1.0.0-alpha', '1.0.0-alpha.1', '1.0.0-alpha.beta', '1.0.0-beta', '1.0.0-beta.2', '1.0.0-beta.11', '1.0.0-rc.1', '1.0.0', '1.0.1', '1.1.0', '2.0.0']; | |
| 40 | 新增: for (let i = 0; i < ordered.length; i++) { | |
| 41 | 新增: assert.equal(compareVersions(ordered[i], ordered[i]), 0); | |
| 42 | 新增: for (let j = i + 1; j < ordered.length; j++) { | |
| 43 | 新增: assert.equal(compareVersions(ordered[i], ordered[j]), -1); | |
| 44 | 新增: assert.equal(compareVersions(ordered[j], ordered[i]), 1); | |
| 45 | 新增: } | |
| 46 | 新增: } | |
| 47 | 新增: assert.equal(compareVersions('1.0.0-999999999999999999', '1.0.0-1000000000000000000'), -1); | |
| 48 | 新增: assert.equal(compareVersions('9007199254740992.0.0', '9007199254740993.0.0'), -1); | |
| 49 | 新增: assert.equal(compareVersions('1.0.0-1', '1.0.0-A'), -1); | |
| 50 | 新增:}); | |
| 51 | 新增: | |
| 52 | 新增:test('applies the four bump policies to stable and prerelease versions', () => { | |
| 53 | 新增: const cases = [ | |
| 54 | 新增: ['1.2.3', 'prerelease', '1.2.4-alpha.1'], | |
| 55 | 新增: ['1.2.3-alpha.9', 'prerelease', '1.2.3-alpha.10'], | |
| 56 | 新增: ['1.2.3-rc', 'prerelease', '1.2.3-rc.1'], | |
| 57 | 新增: ['1.2.3-alpha.beta', 'prerelease', '1.2.3-alpha.beta.1'], | |
| 58 | 新增: ['1.2.3-alpha.999999999999999999', 'prerelease', '1.2.3-alpha.1000000000000000000'], | |
| 59 | 新增: ['1.2.3-alpha.9', 'patch', '1.2.3'], | |
| 60 | 新增: ['1.2.3', 'patch', '1.2.4'], | |
| 61 | 新增: ['1.2.3-alpha.9', 'minor', '1.3.0'], | |
| 62 | 新增: ['1.2.3', 'minor', '1.3.0'], | |
| 63 | 新增: ['1.2.3-alpha.9', 'major', '2.0.0'], | |
| 64 | 新增: ['1.2.3', 'major', '2.0.0'], | |
| 65 | 新增: ]; | |
| 66 | 新增: for (const [current, bump, expected] of cases) assert.equal(nextVersion(current, bump), expected); | |
| 67 | 新增: assert.throws(() => nextVersion('1.2.3', 'build'), /Unsupported/); | |
| 68 | 新增:}); | |
| 69 | 新增: | |
| 70 | 新增:test('reserves existing tags including future draft tags and ignores noncanonical tags', () => { | |
| 71 | 新增: const tags = ['windows-preview-20261102', 'v0.2.0-alpha.1', 'v0.2.0-alpha.10', 'v0.2.0-alpha.2', 'v999.0', 'v01.0.0', 'v900.0.0+build', '2.0.0']; | |
| 72 | 新增: assert.equal(nextVersion('0.1.0-alpha.1', 'prerelease', tags), '0.2.0-alpha.11'); | |
| 73 | 新增: assert.equal(nextVersion('0.1.0-alpha.1', 'patch', tags), '0.2.0'); | |
| 74 | 新增: assert.equal(nextVersion('0.1.0-alpha.1', 'prerelease', [...tags, 'v0.2.0']), '0.2.1-alpha.1'); | |
| 75 | 新增: assert.equal(nextVersion('0.3.0-alpha.2', 'prerelease', tags), '0.3.0-alpha.3'); | |
| 76 | 新增: assert.equal(nextVersion('0.1.0', 'minor', ['v2.4.9-rc.3']), '2.5.0'); | |
| 77 | 新增: assert.equal(nextVersion('0.1.0', 'major', ['v2.4.9-rc.3']), '3.0.0'); | |
| 78 | 新增:}); | |
| 79 | 新增: | |
| 80 | 新增:test('returns five edits without writing files or changing dependency data and formatting', t => { | |
| 81 | 新增: const root = fixture(t); | |
| 82 | 新增: const paths = ['VERSION', 'ui/package.json', 'ui/package-lock.json', 'www/package.json', 'www/package-lock.json']; | |
| 83 | 新增: const before = new Map(paths.map(path => [join(root, path), readFileSync(join(root, path), 'utf8')])); | |
| 84 | 新增: const edits = versionFiles(root, '1.2.3'); | |
| 85 | 新增: assert.equal(edits.size, 5); | |
| 86 | 新增: assert.deepEqual([...edits.keys()], [...before.keys()]); | |
| 87 | 新增: assert.equal(edits.get(join(root, 'VERSION')), '1.2.3\r\n'); | |
| 88 | 新增: for (const [path, original] of before) { | |
| 89 | 新增: assert.equal(readFileSync(path, 'utf8'), original, 'The function must not write its inputs'); | |
| 90 | 新增: if (path.endsWith('package.json')) { | |
| 91 | 新增: assert.equal(edits.get(path), original.replace('"version": "1.2.3-alpha.9"', '"version": "1.2.3"')); | |
| 92 | 新增: } else if (path.endsWith('package-lock.json')) { | |
| 93 | 新增: assert.equal(edits.get(path), original.replace('"version": "1.2.3-alpha.9"', '"version": "1.2.3"').replace('"version": "1.2.3-alpha.9"', '"version": "1.2.3"')); | |
| 94 | 新增: const lock = JSON.parse(edits.get(path)); | |
| 95 | 新增: const old = JSON.parse(original); | |
| 96 | 新增: assert.deepEqual(lock.packages['node_modules/library'], old.packages['node_modules/library']); | |
| 97 | 新增: assert.deepEqual(lock.metadata, old.metadata); | |
| 98 | 新增: } | |
| 99 | 新增: } | |
| 100 | 新增:}); | |
| 101 | 新增: | |
| 102 | 新增:test('rejects inconsistent versions in any package or lockfile root without writing', t => { | |
| 103 | 新增: for (const path of ['ui/package.json', 'ui/package-lock.json', 'www/package.json', 'www/package-lock.json']) { | |
| 104 | 新增: const root = fixture(t); | |
| 105 | 新增: const file = join(root, path); | |
| 106 | 新增: const original = readFileSync(file, 'utf8'); | |
| 107 | 新增: const changed = original.replace('"version": "1.2.3-alpha.9"', '"version": "9.0.0"'); | |
| 108 | 新增: writeFileSync(file, changed); | |
| 109 | 新增: assert.throws(() => versionFiles(root, '2.0.0'), /must match VERSION/); | |
| 110 | 新增: assert.equal(readFileSync(file, 'utf8'), changed); | |
| 111 | 新增: assert.equal(readFileSync(join(root, 'VERSION'), 'utf8'), '1.2.3-alpha.9\r\n'); | |
| 112 | 新增: } | |
| 113 | 新增: const root = fixture(t); | |
| 114 | 新增: const path = join(root, 'ui/package-lock.json'); | |
| 115 | 新增: const lock = JSON.parse(readFileSync(path, 'utf8')); | |
| 116 | 新增: lock.packages[''].version = '1.2.3'; | |
| 117 | 新增: writeFileSync(path, JSON.stringify(lock)); | |
| 118 | 新增: assert.throws(() => versionFiles(root, '2.0.0'), /must match VERSION/); | |
| 119 | 新增:}); | |
| 120 | 新增: | |
| 121 | 新增:test('handles escaped JSON keys and rejects duplicate target version fields', t => { | |
| 122 | 新增: const root = fixture(t); | |
| 123 | 新增: const path = join(root, 'ui/package.json'); | |
| 124 | 新增: writeFileSync(path, '{"ver\\u0073ion":"1.2.3-alpha.9","data":"escaped \\\"version\\\": text"}\n'); | |
| 125 | 新增: assert.equal(versionFiles(root, '1.2.3').get(path), '{"ver\\u0073ion":"1.2.3","data":"escaped \\\"version\\\": text"}\n'); | |
| 126 | 新增: writeFileSync(path, '{"version":"1.2.3-alpha.9","version":"1.2.3-alpha.9"}'); | |
| 127 | 新增: assert.throws(() => versionFiles(root, '1.2.3'), /exactly one/); | |
| 128 | 新增: writeFileSync(path, '{"version":{},"version":"1.2.3-alpha.9"}'); | |
| 129 | 新增: assert.throws(() => versionFiles(root, '1.2.3'), /must be strings/); | |
| 130 | 新增:}); | |
| 131 | 新增: | |
| 132 | 新增:test('metadata CLI reads the repository root even from a different working directory', t => { | |
| 133 | 新增: const destination = fixture(t); | |
| 134 | 新增: const modulePath = fileURLToPath(new URL('./release-version.mjs', import.meta.url)); | |
| 135 | 新增: const root = fileURLToPath(new URL('../', import.meta.url)); | |
| 136 | 新增: const version = readFileSync(join(root, 'VERSION'), 'utf8').trim(); | |
| 137 | 新增: const output = join(destination, 'artifacts', 'release-build.json'); | |
| 138 | 新增: const result = spawnSync(process.execPath, [modulePath, 'metadata', 'linux', output], { cwd: destination, encoding: 'utf8' }); | |
| 139 | 新增: assert.equal(result.status, 0, result.stderr); | |
| 140 | 新增: assert.deepEqual(JSON.parse(readFileSync(output, 'utf8')), { | |
| 141 | 新增: schema: 1, platform: 'linux', version, | |
| 142 | 新增: commitSha: execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(), | |
| 143 | 新增: }); | |
| 144 | 新增: const invalidOutput = join(destination, 'invalid.json'); | |
| 145 | 新增: const invalid = spawnSync(process.execPath, [modulePath, 'metadata', 'unknown', invalidOutput], { cwd: destination, encoding: 'utf8' }); | |
| 146 | 新增: assert.notEqual(invalid.status, 0); | |
| 147 | 新增: assert.equal(existsSync(invalidOutput), false); | |
| 148 | 新增:}); | |
| @@ -0,0 +1,44 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:cd "$(dirname "$0")/.." | |
| 4 | 新增:[[ -f /.dockerenv && $(id -u) == 0 ]] || { echo 'Run this destructive package test as root in a disposable Docker container.' >&2; exit 2; } | |
| 5 | 新增:[[ $# == 1 && -f "$1" ]] || { echo 'Usage: test-linux-install.sh /path/to/Cage-linux-amd64.deb' >&2; exit 2; } | |
| 6 | 新增:package=$(realpath "$1") | |
| 7 | 新增:test_user=cage-package-test | |
| 8 | 新增:id "$test_user" >/dev/null 2>&1 || useradd -m -s /bin/bash "$test_user" | |
| 9 | 新增:test_home=$(getent passwd "$test_user" | cut -d: -f6) | |
| 10 | 新增:report_dir="$test_home/reports" | |
| 11 | 新增:profile="$test_home/upgrade-guard/config.json" | |
| 12 | 新增:cleanup() { | |
| 13 | 新增: if [[ -x /usr/bin/claude-cage && -f "${profile%/*}/control.json" ]]; then | |
| 14 | 新增: runuser -u "$test_user" -- env CLAUDE_CAGE_CONFIG="$profile" /usr/bin/claude-cage prepare-update --json >/dev/null || true | |
| 15 | 新增: fi | |
| 16 | 新增:} | |
| 17 | 新增:trap cleanup EXIT | |
| 18 | 新增:install -d -m 700 -o "$test_user" -g "$test_user" "$report_dir" "$test_home/.claude-cage" "$test_home/.claude-cage-workspace" | |
| 19 | 新增:runuser -u "$test_user" -- sh -c 'printf "keep-profile\n" > "$1/.claude-cage/install-test-marker"; printf "keep-project\n" > "$1/.claude-cage-workspace/install-test-marker"' sh "$test_home" | |
| 20 | 新增:export DEBIAN_FRONTEND=noninteractive | |
| 21 | 新增:apt-get install --reinstall -y "$package" | |
| 22 | 新增:runuser -u "$test_user" -- /usr/lib/claude-cage/cage-desktop --self-test | |
| 23 | 新增:runuser -u "$test_user" -- xvfb-run -a dbus-run-session -- node "$PWD/desktop/linux/test-smoke.mjs" /usr/lib/claude-cage/cage-desktop "$report_dir/first-install.json" | |
| 24 | 新增:# Keep a real control service alive and confirm that preinst refuses replacement. | |
| 25 | 新增:runuser -u "$test_user" -- env CLAUDE_CAGE_CONFIG="$profile" /usr/bin/claude-cage desktop --json > /dev/null | |
| 26 | 新增:if dpkg -i "$package" > "$report_dir/running-upgrade.log" 2>&1; then | |
| 27 | 新增: echo 'FAIL: installer replaced a running Cage backend.' >&2 | |
| 28 | 新增: exit 1 | |
| 29 | 新增:fi | |
| 30 | 新增:grep -q 'Cage is running' "$report_dir/running-upgrade.log" | |
| 31 | 新增:if dpkg --remove claude-cage > "$report_dir/running-remove.log" 2>&1; then | |
| 32 | 新增: echo 'FAIL: uninstaller removed a running Cage backend.' >&2 | |
| 33 | 新增: exit 1 | |
| 34 | 新增:fi | |
| 35 | 新增:grep -q 'Cage is running' "$report_dir/running-remove.log" | |
| 36 | 新增:runuser -u "$test_user" -- env CLAUDE_CAGE_CONFIG="$profile" /usr/bin/claude-cage prepare-update --json > "$report_dir/guard-stop.json" | |
| 37 | 新增:dpkg -i "$package" | |
| 38 | 新增:runuser -u "$test_user" -- xvfb-run -a dbus-run-session -- node "$PWD/desktop/linux/test-smoke.mjs" /usr/lib/claude-cage/cage-desktop "$report_dir/after-reinstall.json" | |
| 39 | 新增:dpkg --remove claude-cage | |
| 40 | 新增:[[ ! -e /usr/bin/cage-desktop && ! -e /usr/lib/claude-cage/cage ]] || { echo 'Uninstall left installed executables.' >&2; exit 1; } | |
| 41 | 新增:[[ $(cat "$test_home/.claude-cage/install-test-marker") == keep-profile ]] | |
| 42 | 新增:[[ $(cat "$test_home/.claude-cage-workspace/install-test-marker") == keep-project ]] | |
| 43 | 新增:printf '{"success":true,"install":true,"nativeWorkbench":true,"runningUpgradeRefused":true,"runningRemovalRefused":true,"reinstall":true,"uninstallPreservedData":true}\n' > "$report_dir/install.json" | |
| 44 | 新增:printf 'PASS: package install, native workbench, running-update refusal, reinstall and data-preserving removal. Reports: %s\n' "$report_dir" | |
| @@ -0,0 +1,51 @@ | ||
| 1 | 新增:#requires -Version 7.0 | |
| 2 | 新增:# Runs only on a disposable Windows test user. Does not start a VM. | |
| 3 | 新增:[CmdletBinding()] | |
| 4 | 新增:param([Parameter(Mandatory)][string]$Installer) | |
| 5 | 新增:. (Join-Path $PSScriptRoot 'windows-common.ps1') | |
| 6 | 新增:if (-not $IsWindows) { throw 'Installation smoke tests must run on Windows.' } | |
| 7 | 新增:$target = Join-Path $env:LOCALAPPDATA ('Programs/Cage-test-' + [guid]::NewGuid().ToString('N')) | |
| 8 | 新增:$report = Join-Path ([IO.Path]::GetTempPath()) ('cage-smoke-' + [guid]::NewGuid().ToString('N') + '.json') | |
| 9 | 新增:$savedKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\ClaudeCage' | |
| 10 | 新增:if (Test-Path $savedKey) { throw 'Use a disposable Windows user without an existing Cage installation.' } | |
| 11 | 新增:function Run-Installer { | |
| 12 | 新增: param([switch]$Update, [int]$ExpectedExitCode = 0) | |
| 13 | 新增: $arguments = @('/S') | |
| 14 | 新增: if ($Update) { $arguments += '/UPDATE' } | |
| 15 | 新增: $arguments += "/D=$target" | |
| 16 | 新增: $process = Start-Process -FilePath $Installer -ArgumentList $arguments -PassThru | |
| 17 | 新增: if (-not $process.WaitForExit(300000)) { throw 'Installer exceeded five minutes.' } | |
| 18 | 新增: if ($process.ExitCode -ne $ExpectedExitCode) { throw "Installer returned $($process.ExitCode), expected $ExpectedExitCode" } | |
| 19 | 新增:} | |
| 20 | 新增:Run-Installer | |
| 21 | 新增:if (-not (Test-Path -LiteralPath (Join-Path $target 'Cage.exe'))) { throw 'Installer did not create Cage.exe.' } | |
| 22 | 新增:Invoke-BuildTool (Join-Path $target 'resources/cage.exe') @('--help') | |
| 23 | 新增:Invoke-BuildTool (Join-Path $target 'resources/mihomo.exe') @('-v') | |
| 24 | 新增:Invoke-BuildTool (Join-Path $target 'resources/runtime/qemu/qemu-system-x86_64.exe') @('--version') | |
| 25 | 新增:Invoke-BuildTool (Join-Path $target 'resources/runtime/openssh/ssh.exe') @('-V') | |
| 26 | 新增:$window = Start-Process -FilePath (Join-Path $target 'Cage.exe') -ArgumentList @('--smoke-test', "`"$report`"") -PassThru | |
| 27 | 新增:if (-not $window.WaitForExit(180000)) { throw 'Cage WebView2/workbench smoke test timed out.' } | |
| 28 | 新增:if ($window.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $report)) { throw "Cage desktop smoke test failed ($($window.ExitCode))." } | |
| 29 | 新增:Get-Content -LiteralPath $report | |
| 30 | 新增:# A locked installed executable must fail before replacing the installation. | |
| 31 | 新增:$before = (Get-FileHash -LiteralPath (Join-Path $target 'Cage.exe') -Algorithm SHA256).Hash | |
| 32 | 新增:$locked = [IO.File]::Open((Join-Path $target 'Cage.exe'), [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read) | |
| 33 | 新增:try { Run-Installer -Update -ExpectedExitCode 2 } finally { $locked.Dispose() } | |
| 34 | 新增:if ((Get-FileHash -LiteralPath (Join-Path $target 'Cage.exe') -Algorithm SHA256).Hash -ne $before) { throw 'Failed update replaced the existing application.' } | |
| 35 | 新增:# Reinstall through the real atomic replacement path. User data must survive. | |
| 36 | 新增:$state = Join-Path $env:USERPROFILE '.claude-cage' | |
| 37 | 新增:New-Item -ItemType Directory -Path $state -Force | Out-Null | |
| 38 | 新增:$sentinel = Join-Path $state ('installer-test-' + [guid]::NewGuid().ToString('N')) | |
| 39 | 新增:[IO.File]::WriteAllText($sentinel, 'preserve') | |
| 40 | 新增:Run-Installer -Update | |
| 41 | 新增:if ((Get-Content -LiteralPath $sentinel -Raw) -ne 'preserve') { throw 'Upgrade modified user data.' } | |
| 42 | 新增:$uninstall = Start-Process -FilePath (Join-Path $target 'Uninstall.exe') -ArgumentList @('/S') -PassThru | |
| 43 | 新增:if (-not $uninstall.WaitForExit(120000) -or $uninstall.ExitCode -ne 0) { throw 'Uninstall failed.' } | |
| 44 | 新增:# NSIS may relaunch its uninstaller from TEMP so that it can delete the original. | |
| 45 | 新增:$deadline = [DateTime]::UtcNow.AddSeconds(120) | |
| 46 | 新增:while ((Test-Path -LiteralPath (Join-Path $target 'Uninstall.exe')) -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 200 } | |
| 47 | 新增:if (Test-Path -LiteralPath (Join-Path $target 'Cage.exe')) { throw 'Uninstall left Cage.exe behind.' } | |
| 48 | 新增:if (Test-Path -LiteralPath (Join-Path $target 'Uninstall.exe')) { throw 'Uninstall left its launcher behind.' } | |
| 49 | 新增:if ((Get-Content -LiteralPath $sentinel -Raw) -ne 'preserve') { throw 'Uninstall modified user data.' } | |
| 50 | 新增:Remove-Item -LiteralPath $sentinel | |
| 51 | 新增:Write-Host 'Install, WebView2 workbench, reinstall, uninstall and user-data preservation passed. VM startup was not tested.' | |
| @@ -16,10 +16,23 @@ validate_ticket() { | ||
| 16 | 16 | shopt -s nullglob |
| 17 | 17 | archives=("$directory"/Cage-*-macos-arm64.dmg) |
| 18 | 18 | if [[ ${#archives[@]} != 1 ]]; then echo 'Expected exactly one Cage DMG.' >&2; exit 1; fi |
| 19 | 新增:sources=("$directory"/mihomo-v*-source.tar.gz) | |
| 20 | 新增:if [[ ${#sources[@]} != 1 ]]; then echo 'Expected exactly one Mihomo source archive.' >&2; exit 1; fi | |
| 19 | 21 | archive="${archives[0]}" |
| 20 | 22 | version="${archive##*/Cage-}" |
| 21 | 23 | version="${version%-macos-arm64.dmg}" |
| 22 | 删除:(cd "$directory" && shasum -a 256 --check SHA256SUMS) | |
| 24 | 新增:# The release may also contain Windows installers and their corresponding | |
| 25 | 新增:# sources. Validate this platform's downloaded files against the original list. | |
| 26 | 新增:checksum_input="$(mktemp)" | |
| 27 | 新增:trap 'rm -f "$checksum_input"' EXIT | |
| 28 | 新增:awk -v archive="${archive##*/}" -v source="${sources[0]##*/}" ' | |
| 29 | 新增: NF == 2 && ($2 == archive || $2 == "*" archive) { archives++; print } | |
| 30 | 新增: NF == 2 && ($2 == source || $2 == "*" source) { sources++; print } | |
| 31 | 新增: END { if (archives != 1 || sources != 1) exit 1 } | |
| 32 | 新增:' "$directory/SHA256SUMS" > "$checksum_input" | |
| 33 | 新增:(cd "$directory" && shasum -a 256 --check "$checksum_input") | |
| 34 | 新增:rm -f "$checksum_input" | |
| 35 | 新增:trap - EXIT | |
| 23 | 36 | codesign --verify --strict --verbose=2 "$archive" |
| 24 | 37 | validate_ticket "$archive" |
| 25 | 38 | spctl --assess --type open --context context:primary-signature --verbose=2 "$archive" |
| @@ -0,0 +1,94 @@ | ||
| 1 | 新增:# Shared build helpers. PowerShell 7 runs these scripts on Windows, macOS and Linux. | |
| 2 | 新增:Set-StrictMode -Version Latest | |
| 3 | 新增:$ErrorActionPreference = 'Stop' | |
| 4 | 新增:$PSNativeCommandUseErrorActionPreference = $true | |
| 5 | 新增: | |
| 6 | 新增:function Invoke-BuildTool { | |
| 7 | 新增: param([string]$Tool, [string[]]$Arguments) | |
| 8 | 新增: & $Tool @Arguments | |
| 9 | 新增: if ($LASTEXITCODE -ne 0) { throw "$Tool failed with exit code $LASTEXITCODE" } | |
| 10 | 新增:} | |
| 11 | 新增: | |
| 12 | 新增:function Get-CageVersion { | |
| 13 | 新增: param([string]$Repository) | |
| 14 | 新增: $value = (Get-Content -LiteralPath (Join-Path $Repository 'VERSION') -Raw).Trim() | |
| 15 | 新增: if ($value -notmatch '^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$') { throw 'Invalid VERSION.' } | |
| 16 | 新增: return $value | |
| 17 | 新增:} | |
| 18 | 新增: | |
| 19 | 新增:function Get-BuildCommand { | |
| 20 | 新增: param([string[]]$Names) | |
| 21 | 新增: foreach ($name in $Names) { | |
| 22 | 新增: $command = Get-Command $name -ErrorAction SilentlyContinue | |
| 23 | 新增: if ($command) { return $command.Source } | |
| 24 | 新增: } | |
| 25 | 新增: throw "Missing build tool: $($Names -join ' or ')" | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:function Get-VerifiedDependency { | |
| 29 | 新增: param($Dependency, [string]$Cache) | |
| 30 | 新增: if ($Dependency.url -notlike 'https://*') { throw 'Build dependencies must use HTTPS.' } | |
| 31 | 新增: $path = Join-Path $Cache $Dependency.file | |
| 32 | 新增: if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { | |
| 33 | 新增: New-Item -ItemType Directory -Path $Cache -Force | Out-Null | |
| 34 | 新增: $partial = "$path.partial" | |
| 35 | 新增: try { | |
| 36 | 新增: Invoke-WebRequest -Uri $Dependency.url -OutFile $partial -TimeoutSec 900 -MaximumRedirection 5 | |
| 37 | 新增: Move-Item -LiteralPath $partial -Destination $path -Force | |
| 38 | 新增: } finally { | |
| 39 | 新增: if (Test-Path -LiteralPath $partial) { Remove-Item -LiteralPath $partial -Force } | |
| 40 | 新增: } | |
| 41 | 新增: } | |
| 42 | 新增: $actual = (Get-FileHash -LiteralPath $path -Algorithm $Dependency.algorithm).Hash | |
| 43 | 新增: if ($actual -ne $Dependency.hash) { throw "Dependency checksum mismatch: $($Dependency.file). Remove the cached file and retry." } | |
| 44 | 新增: return $path | |
| 45 | 新增:} | |
| 46 | 新增: | |
| 47 | 新增:function Expand-BuildArchive { | |
| 48 | 新增: param([string]$Archive, [string]$Destination, [string]$SevenZip) | |
| 49 | 新增: New-Item -ItemType Directory -Path $Destination -Force | Out-Null | |
| 50 | 新增: Invoke-BuildTool $SevenZip @('x', '-y', '-bso0', '-bsp0', "-o$Destination", $Archive) | |
| 51 | 新增:} | |
| 52 | 新增: | |
| 53 | 新增:function Get-VerifiedGitArchive { | |
| 54 | 新增: param($Dependency, [string]$Cache) | |
| 55 | 新增: $archive = Join-Path $Cache $Dependency.file | |
| 56 | 新增: if (-not (Test-Path -LiteralPath $archive)) { | |
| 57 | 新增: $git = Get-BuildCommand @('git.exe', 'git') | |
| 58 | 新增: $checkout = Join-Path $Cache ('source-' + [guid]::NewGuid().ToString('N')) | |
| 59 | 新增: $partial = "$archive.partial" | |
| 60 | 新增: try { | |
| 61 | 新增: Invoke-BuildTool $git @('init', '--bare', '--quiet', $checkout) | |
| 62 | 新增: Invoke-BuildTool $git @('--git-dir', $checkout, 'fetch', '--depth=1', $Dependency.repository, $Dependency.commit) | |
| 63 | 新增: $actualCommit = & $git '--git-dir' $checkout 'rev-parse' 'FETCH_HEAD' | |
| 64 | 新增: if ($LASTEXITCODE -ne 0 -or $actualCommit -ne $Dependency.commit) { throw 'Fetched source commit does not match the pinned QEMU build.' } | |
| 65 | 新增: Invoke-BuildTool $git @('--git-dir', $checkout, 'archive', '--format=tar', "--prefix=$($Dependency.prefix)", "--output=$partial", $Dependency.commit) | |
| 66 | 新增: Move-Item -LiteralPath $partial -Destination $archive | |
| 67 | 新增: } finally { | |
| 68 | 新增: Remove-Item -LiteralPath $checkout -Recurse -Force -ErrorAction SilentlyContinue | |
| 69 | 新增: Remove-Item -LiteralPath $partial -Force -ErrorAction SilentlyContinue | |
| 70 | 新增: } | |
| 71 | 新增: } | |
| 72 | 新增: if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $Dependency.hash) { throw "Source archive checksum mismatch: $($Dependency.file)" } | |
| 73 | 新增: return $archive | |
| 74 | 新增:} | |
| 75 | 新增: | |
| 76 | 新增:function Get-SigningTool { | |
| 77 | 新增: $command = Get-Command signtool.exe -ErrorAction SilentlyContinue | |
| 78 | 新增: if ($command) { return $command.Source } | |
| 79 | 新增: if ($IsWindows) { | |
| 80 | 新增: $kits = Join-Path ${env:ProgramFiles(x86)} 'Windows Kits/10/bin' | |
| 81 | 新增: $candidate = Get-ChildItem -LiteralPath $kits -Directory -ErrorAction SilentlyContinue | | |
| 82 | 新增: Sort-Object Name -Descending | ForEach-Object { Join-Path $_.FullName 'x64/signtool.exe' } | | |
| 83 | 新增: Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 | |
| 84 | 新增: if ($candidate) { return $candidate } | |
| 85 | 新增: } | |
| 86 | 新增: throw 'Release signing requires Windows SDK signtool.exe on Windows.' | |
| 87 | 新增:} | |
| 88 | 新增: | |
| 89 | 新增:function Sign-CageFile { | |
| 90 | 新增: param([string]$Path, [string]$SignTool) | |
| 91 | 新增: Invoke-BuildTool $SignTool @('sign', '/sha1', $env:CAGE_WINDOWS_CERT_SHA1, '/fd', 'SHA256', | |
| 92 | 新增: '/tr', 'http://timestamp.digicert.com', '/td', 'SHA256', '/d', 'Cage', $Path) | |
| 93 | 新增: Invoke-BuildTool $SignTool @('verify', '/pa', '/all', $Path) | |
| 94 | 新增:} | |
| @@ -0,0 +1,40 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 4 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 5 | 新增: | |
| 6 | 新增:package usernet | |
| 7 | 新增: | |
| 8 | 新增:import ( | |
| 9 | 新增: "context" | |
| 10 | 新增: "net" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "testing" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:func TestNetstackWindowsNativeSocketPaths(t *testing.T) { | |
| 17 | 新增: // A drive letter, spaces and URL punctuation must remain a file path. | |
| 18 | 新增: dir, err := os.MkdirTemp("", "cage %23-") | |
| 19 | 新增: if err != nil { | |
| 20 | 新增: t.Fatal(err) | |
| 21 | 新增: } | |
| 22 | 新增: defer os.RemoveAll(dir) | |
| 23 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 24 | 新增: defer cancel() | |
| 25 | 新增: endpoint := filepath.Join(dir, "ep.sock") | |
| 26 | 新增: qemu := filepath.Join(dir, "qemu.sock") | |
| 27 | 新增: if err := StartGVisorNetstack(ctx, &GVisorNetstackOpts{ | |
| 28 | 新增: MTU: 1500, Endpoint: endpoint, QemuSocket: qemu, | |
| 29 | 新增: Subnet: "192.168.127.0/24", Async: true, | |
| 30 | 新增: }); err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: for _, path := range []string{endpoint, qemu} { | |
| 34 | 新增: conn, err := net.Dial("unix", path) | |
| 35 | 新增: if err != nil { | |
| 36 | 新增: t.Fatalf("cannot connect to native socket %q: %v", path, err) | |
| 37 | 新增: } | |
| 38 | 新增: conn.Close() | |
| 39 | 新增: } | |
| 40 | 新增:} | |
| @@ -19,7 +19,6 @@ import ( | ||
| 19 | 19 | "time" |
| 20 | 20 | |
| 21 | 21 | "github.com/balajiv113/fd" |
| 22 | 删除: "github.com/containers/gvisor-tap-vsock/pkg/transport" | |
| 23 | 22 | "github.com/containers/gvisor-tap-vsock/pkg/types" |
| 24 | 23 | "github.com/containers/gvisor-tap-vsock/pkg/virtualnetwork" |
| 25 | 24 | "github.com/miekg/dns" |
| @@ -166,7 +165,7 @@ func run(ctx context.Context, g *errgroup.Group, configuration *types.Configurat | ||
| 166 | 165 | return err |
| 167 | 166 | } |
| 168 | 167 | |
| 169 | 删除: ln, err := transport.Listen(fmt.Sprintf("unix://%s", opts.Endpoint)) | |
| 168 | 新增: ln, err := net.Listen("unix", opts.Endpoint) | |
| 170 | 169 | if err != nil { |
| 171 | 170 | return err |
| 172 | 171 | } |
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "cage-workbench", |
| 3 | 删除: "version": "0.1.0-alpha.1", | |
| 3 | 新增: "version": "0.1.1-alpha", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "cage-workbench", |
| 9 | 删除: "version": "0.1.0-alpha.1", | |
| 9 | 新增: "version": "0.1.1-alpha", | |
| 10 | 10 | "dependencies": { |
| 11 | 11 | "@xterm/addon-fit": "0.11.0", |
| 12 | 12 | "@xterm/xterm": "6.0.0", |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "cage-workbench", |
| 3 | 3 | "private": true, |
| 4 | 删除: "version": "0.1.0-alpha.1", | |
| 4 | 新增: "version": "0.1.1-alpha", | |
| 5 | 5 | "type": "module", |
| 6 | 6 | "scripts": { |
| 7 | 7 | "prepare-vnc": "node scripts/prepare-vnc.mjs", |
| @@ -0,0 +1,64 @@ | ||
| 1 | 新增:import assert from 'node:assert/strict'; | |
| 2 | 新增:import {createWorkbench} from './workbench-fixture.mjs'; | |
| 3 | 新增:let fixture; | |
| 4 | 新增:const calls=[]; | |
| 5 | 新增:let cancelBiometric=false; | |
| 6 | 新增:fixture=await createWorkbench({nativeRequest:async(body)=>{ | |
| 7 | 新增: if(body.action!=='accountDevice')return null; | |
| 8 | 新增: const {operation,kind}=body;calls.push({operation,kind}); | |
| 9 | 新增: if(operation==='status')return {supported:true,biometric_available:true}; | |
| 10 | 新增: const a=fixture.state.account;a.devices ||= {}; | |
| 11 | 新增: if(operation==='enable')a.devices[kind]='fixture-'+kind; | |
| 12 | 新增: if(operation==='disable')delete a.devices[kind]; | |
| 13 | 新增: if(operation==='unlock'){ | |
| 14 | 新增: if(kind==='biometric'&&cancelBiometric)throw Error('已取消指纹验证,可继续使用密码'); | |
| 15 | 新增: if(kind==='automatic'&&a.require_authentication)throw Error('手动锁定'); | |
| 16 | 新增: a.unlocked=true;a.require_authentication=false; | |
| 17 | 新增: } | |
| 18 | 新增: return {ok:true}; | |
| 19 | 新增:}}); | |
| 20 | 新增:const {page,state,browser,errors}=fixture; | |
| 21 | 新增:const menu=()=>page.getByRole('button',{name:/^账户菜单,/}); | |
| 22 | 新增:try { | |
| 23 | 新增: Object.assign(state.account,{exists:false,unlocked:false,username:'',devices:{}}); | |
| 24 | 新增: await page.reload(); | |
| 25 | 新增: const defaultRemember=page.getByRole('checkbox',{name:/记住登录/}); | |
| 26 | 新增: await defaultRemember.waitFor();assert.equal(await defaultRemember.isChecked(),true); | |
| 27 | 新增: await page.getByLabel('用户名',{exact:true}).fill('林间工作室'); | |
| 28 | 新增: await page.getByLabel('设置密码',{exact:true}).fill('fixture-password'); | |
| 29 | 新增: await page.getByLabel('确认密码',{exact:true}).fill('fixture-password'); | |
| 30 | 新增: await page.getByRole('button',{name:'创建本地账户',exact:true}).click();await menu().waitFor(); | |
| 31 | 新增: await menu().click();await page.getByRole('menuitem',{name:'账户设置',exact:true}).click(); | |
| 32 | 新增: const automatic=page.getByRole('checkbox',{name:/记住登录/}); | |
| 33 | 新增: const biometric=page.getByRole('checkbox',{name:/使用 Touch ID 解锁/}); | |
| 34 | 新增: await page.waitForFunction(()=>document.querySelector('.account-device-settings input')?.checked); | |
| 35 | 新增: assert.equal(await automatic.isChecked(),true); | |
| 36 | 新增: await biometric.click();await page.getByRole('status').filter({hasText:'已开启'}).waitFor(); | |
| 37 | 新增: assert.ok(state.account.devices.automatic&&state.account.devices.biometric); | |
| 38 | 新增: await page.screenshot({path:'.oil-ui/local-account/shots/device-settings.png'}); | |
| 39 | 新增: // A genuine reopen keeps enrollment but starts with a locked server. | |
| 40 | 新增: state.account.unlocked=false;await page.reload();await menu().waitFor(); | |
| 41 | 新增: assert.equal(calls.filter(x=>x.operation==='unlock'&&x.kind==='automatic').length,1); | |
| 42 | 新增: await menu().click();await page.getByRole('menuitem',{name:'账户设置',exact:true}).click(); | |
| 43 | 新增: await automatic.click();await page.getByRole('status').filter({hasText:'已关闭'}).waitFor(); | |
| 44 | 新增: await page.reload();await menu().click();await page.getByRole('menuitem',{name:'账户设置',exact:true}).click(); | |
| 45 | 新增: assert.equal(await automatic.isChecked(),false,'explicit opt-out was overridden'); | |
| 46 | 新增: await automatic.click();await page.getByRole('status').filter({hasText:'已开启'}).waitFor(); | |
| 47 | 新增: await page.getByRole('button',{name:'返回工作台',exact:true}).click(); | |
| 48 | 新增: await menu().click();await page.getByRole('menuitem',{name:/锁定 Cage/}).click(); | |
| 49 | 新增: await page.getByRole('region',{name:'解锁 Cage',exact:true}).waitFor(); | |
| 50 | 新增: await page.reload();await page.getByRole('button',{name:'使用 Touch ID 解锁',exact:true}).waitFor(); | |
| 51 | 新增: assert.equal(calls.filter(x=>x.operation==='unlock'&&x.kind==='automatic').length,1); | |
| 52 | 新增: cancelBiometric=true;await page.getByRole('button',{name:'使用 Touch ID 解锁',exact:true}).click(); | |
| 53 | 新增: await page.getByRole('alert').filter({hasText:'已取消指纹验证'}).waitFor(); | |
| 54 | 新增: assert.equal(state.account.unlocked,false); | |
| 55 | 新增: await page.screenshot({path:'.oil-ui/local-account/shots/touch-id-fallback.png'}); | |
| 56 | 新增: cancelBiometric=false;await page.getByRole('button',{name:'使用 Touch ID 解锁',exact:true}).click();await menu().waitFor(); | |
| 57 | 新增: await menu().click();await page.getByRole('menuitem',{name:'退出账户',exact:true}).click(); | |
| 58 | 新增: await page.getByRole('dialog').getByRole('button',{name:'停止环境并退出账户',exact:true}).click(); | |
| 59 | 新增: await page.getByRole('region',{name:'解锁 Cage',exact:true}).waitFor();await page.reload(); | |
| 60 | 新增: await page.getByLabel('账户密码',{exact:true}).waitFor();assert.deepEqual(state.account.devices,{}); | |
| 61 | 新增: assert.equal(await page.getByRole('button',{name:'使用 Touch ID 解锁',exact:true}).count(),0); | |
| 62 | 新增: assert.deepEqual(errors,[]); | |
| 63 | 新增: console.log('PASS: enrollment, automatic reopen, persistent manual lock, biometric cancellation/fallback, biometric unlock and logout revocation'); | |
| 64 | 新增:}finally{await browser.close();} | |
| @@ -0,0 +1,85 @@ | ||
| 1 | 新增:import assert from 'node:assert/strict'; | |
| 2 | 新增:import fs from 'node:fs/promises'; | |
| 3 | 新增:import { fileURLToPath } from 'node:url'; | |
| 4 | 新增:import { createWorkbench } from './workbench-fixture.mjs'; | |
| 5 | 新增:const output = fileURLToPath(new URL('../../.oil-ui/local-account/shots/', import.meta.url)); | |
| 6 | 新增:await fs.mkdir(output, { recursive: true }); | |
| 7 | 新增:let launchAcks = 0; | |
| 8 | 新增:const {browser,page,state,errors} = await createWorkbench({nativeRequest: async ({action}) => { | |
| 9 | 新增: if (action === 'workbenchReady') { launchAcks++; return true; } | |
| 10 | 新增: return null; | |
| 11 | 新增:}}); | |
| 12 | 新增:await page.exposeFunction('fixtureLaunchAcks', () => launchAcks); | |
| 13 | 新增:const accountMenu = () => page.getByRole('button', { name: /^账户菜单,/ }); | |
| 14 | 新增:try { | |
| 15 | 新增: Object.assign(state.account, {exists:false,unlocked:false,username:''}); | |
| 16 | 新增: const previousAcks = launchAcks; | |
| 17 | 新增: await page.reload(); | |
| 18 | 新增: await page.getByRole('heading',{name:'让 Cage 成为你的工作空间'}).waitFor(); | |
| 19 | 新增: await page.waitForFunction(async (previous) => await window.fixtureLaunchAcks() > previous, previousAcks); | |
| 20 | 新增: await page.screenshot({path:output+'create.png'}); | |
| 21 | 新增: await page.getByLabel('用户名',{exact:true}).fill('林间工作室'); | |
| 22 | 新增: await page.getByLabel('设置密码',{exact:true}).fill('fixture-password'); | |
| 23 | 新增: await page.getByLabel('确认密码',{exact:true}).fill('fixture-password'); | |
| 24 | 新增: await page.getByRole('button',{name:'创建本地账户',exact:true}).click(); | |
| 25 | 新增: await accountMenu().waitFor(); | |
| 26 | 新增: await accountMenu().click(); | |
| 27 | 新增: await page.screenshot({path:output+'menu.png'}); | |
| 28 | 新增: await page.getByRole('menuitem',{name:'账户设置',exact:true}).click(); | |
| 29 | 新增: await page.getByRole('heading',{name:'账户',exact:true}).waitFor(); | |
| 30 | 新增: await page.getByLabel('用户名',{exact:true}).fill('山雀的工作室'); | |
| 31 | 新增: await page.getByLabel('选择头像图片').setInputFiles(fileURLToPath(new URL('../src/logo.png',import.meta.url))); | |
| 32 | 新增: state.failAccountSave=true; | |
| 33 | 新增: await page.getByRole('button',{name:'保存资料',exact:true}).click(); | |
| 34 | 新增: await page.getByRole('alert').filter({hasText:'资料未能保存'}).waitFor(); | |
| 35 | 新增: assert.equal(await page.getByLabel('用户名',{exact:true}).inputValue(),'山雀的工作室'); | |
| 36 | 新增: assert.equal(state.account.username,'林间工作室'); | |
| 37 | 新增: state.failAccountSave=false; | |
| 38 | 新增: await page.getByRole('button',{name:'保存资料',exact:true}).click(); | |
| 39 | 新增: await page.getByRole('status').filter({hasText:'账户资料已保存'}).waitFor(); | |
| 40 | 新增: assert.equal(state.account.username,'山雀的工作室'); | |
| 41 | 新增: assert.match(state.account.avatar,/^data:image\/png;base64,/); | |
| 42 | 新增: await page.screenshot({path:output+'settings.png'}); | |
| 43 | 新增: await page.getByLabel('当前密码',{exact:true}).fill('fixture-password'); | |
| 44 | 新增: await page.getByLabel('新密码',{exact:true}).fill('changed-fixture-password'); | |
| 45 | 新增: await page.getByLabel('确认新密码',{exact:true}).fill('changed-fixture-password'); | |
| 46 | 新增: await page.getByRole('button',{name:'修改密码',exact:true}).click(); | |
| 47 | 新增: await page.getByRole('status').filter({hasText:'密码已修改'}).waitFor(); | |
| 48 | 新增: await page.getByRole('button',{name:'返回工作台',exact:true}).click(); | |
| 49 | 新增: state.status.vm_running=true;state.status.ready=true; | |
| 50 | 新增: await page.reload(); | |
| 51 | 新增: await page.getByRole('button',{name:/^在 .* 新建终端$/}).click(); | |
| 52 | 新增: await page.getByRole('button',{name:'新建普通终端',exact:true}).click(); | |
| 53 | 新增: const ids=state.terminals.map(x=>x.id); | |
| 54 | 新增: await accountMenu().click(); | |
| 55 | 新增: await page.getByRole('menuitem',{name:/锁定 Cage/}).click(); | |
| 56 | 新增: await page.getByRole('region',{name:'解锁 Cage',exact:true}).waitFor(); | |
| 57 | 新增: assert.equal(state.status.vm_running,true); | |
| 58 | 新增: assert.deepEqual(state.terminals.map(x=>x.id),ids); | |
| 59 | 新增: await page.getByText('后台环境仍在运行,任务没有停止',{exact:true}).waitFor(); | |
| 60 | 新增: await page.screenshot({path:output+'locked.png'}); | |
| 61 | 新增: await page.getByLabel('账户密码',{exact:true}).fill('fixture-password'); | |
| 62 | 新增: await page.getByRole('button',{name:'解锁 Cage',exact:true}).click(); | |
| 63 | 新增: await page.getByRole('alert').filter({hasText:'密码不正确'}).waitFor(); | |
| 64 | 新增: await page.getByLabel('账户密码',{exact:true}).fill('changed-fixture-password'); | |
| 65 | 新增: await page.getByRole('button',{name:'解锁 Cage',exact:true}).click(); | |
| 66 | 新增: await accountMenu().waitFor(); | |
| 67 | 新增: assert.deepEqual(state.terminals.map(x=>x.id),ids); | |
| 68 | 新增: await page.reload(); | |
| 69 | 新增: await accountMenu().waitFor(); | |
| 70 | 新增: assert.match(await accountMenu().getAttribute('aria-label'),/山雀的工作室/); | |
| 71 | 新增: await accountMenu().click(); | |
| 72 | 新增: await page.getByRole('menuitem',{name:'账户设置',exact:true}).click(); | |
| 73 | 新增: assert.equal(await page.getByLabel('用户名',{exact:true}).inputValue(),'山雀的工作室'); | |
| 74 | 新增: await page.setViewportSize({width:820,height:558}); | |
| 75 | 新增: await page.screenshot({path:output+'settings-small.png'}); | |
| 76 | 新增: await page.getByRole('button',{name:'返回工作台',exact:true}).click(); | |
| 77 | 新增: await accountMenu().click(); | |
| 78 | 新增: await page.getByRole('menuitem',{name:'退出账户',exact:true}).click(); | |
| 79 | 新增: await page.getByRole('dialog').getByRole('button',{name:'停止环境并退出账户',exact:true}).click(); | |
| 80 | 新增: await page.getByRole('region',{name:'解锁 Cage',exact:true}).waitFor(); | |
| 81 | 新增: assert.equal(state.status.vm_running,false); | |
| 82 | 新增: assert.equal(state.terminals.length,0); | |
| 83 | 新增: assert.deepEqual(errors,[]); | |
| 84 | 新增: console.log('PASS: account creation, avatar/profile persistence, save failure, password change, lock with live terminals, unlock and stop-on-logout'); | |
| 85 | 新增:} finally {await browser.close();} | |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增:import React, { useState } from "react"; | |
| 2 | 新增:import { createRoot } from "react-dom/client"; | |
| 3 | 新增:import { AudioControls, useAudioOutput } from "../src/audio"; | |
| 4 | 新增:function Fixture() { | |
| 5 | 新增: const [enabled, setEnabled] = useState(true); | |
| 6 | 新增: const audio = useAudioOutput(enabled); | |
| 7 | 新增: return <><AudioControls audio={audio} /><output>{audio.state}</output><button onClick={() => setEnabled(false)}>停止测试环境</button></>; | |
| 8 | 新增:} | |
| 9 | 新增:createRoot(document.getElementById("root")).render(<Fixture />); | |
| @@ -0,0 +1,65 @@ | ||
| 1 | 新增:// Explicitly target an unlocked local test installation and its existing VM. | |
| 2 | 新增:// This emits a short test tone; it does not read browser content or credentials. | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import { createRequire } from "node:module"; | |
| 5 | 新增:import { spawn, execFileSync } from "node:child_process"; | |
| 6 | 新增:const require = createRequire(import.meta.url); | |
| 7 | 新增:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"); | |
| 8 | 新增:const bundle = process.argv[2]; | |
| 9 | 新增:for (const key of ["CAGE_CONFIG", "CAGE_SSH_CONFIG", "CAGE_SSH_TARGET"]) assert.ok(process.env[key], `set ${key}`); | |
| 10 | 新增:assert.ok(bundle?.startsWith("/") && bundle.endsWith(".app")); | |
| 11 | 新增:const ssh = ["-q", "-F", process.env.CAGE_SSH_CONFIG, "-o", "BatchMode=yes", "-o", "ClearAllForwardings=yes", "-o", "ControlPath=none", "-o", "ConnectTimeout=3", process.env.CAGE_SSH_TARGET, "--"]; | |
| 12 | 新增:const capturePIDs = () => execFileSync("ssh", [...ssh, "pgrep -x parec || true"], { encoding: "utf8" }).trim().split(/\s+/).filter(Boolean); | |
| 13 | 新增:const before = new Set(capturePIDs()); | |
| 14 | 新增:const entry = JSON.parse(execFileSync(bundle + "/Contents/Resources/cage", ["desktop", "--json", "--existing"], { encoding: "utf8", env: { ...process.env, CLAUDE_CAGE_CONFIG: process.env.CAGE_CONFIG } })); | |
| 15 | 新增:const browser = await chromium.launch({ headless: true }); | |
| 16 | 新增:const page = await browser.newPage({ viewport: { width: 1280, height: 850 } }); | |
| 17 | 新增:let play; | |
| 18 | 新增:const errors = []; | |
| 19 | 新增:page.on("pageerror", e => errors.push(e.message)); | |
| 20 | 新增:await page.addInitScript(() => { | |
| 21 | 新增: const Original = window.AudioContext; | |
| 22 | 新增: window.AudioContext = class extends Original { | |
| 23 | 新增: constructor(...args) { super(...args); window.testAudioContext = this; } | |
| 24 | 新增: createGain() { const gain = super.createGain(); window.testAudioGain = gain; return gain; } | |
| 25 | 新增: }; | |
| 26 | 新增:}); | |
| 27 | 新增:try { | |
| 28 | 新增: await page.goto(entry.url); | |
| 29 | 新增: const volume = page.getByRole("slider", { name: "环境音量" }); | |
| 30 | 新增: await volume.press("End"); | |
| 31 | 新增: await page.waitForFunction(() => window.testAudioGain && window.testAudioContext.state === "running"); | |
| 32 | 新增: await page.evaluate(() => { | |
| 33 | 新增: window.testAudioAnalyser = window.testAudioContext.createAnalyser(); | |
| 34 | 新增: window.testAudioAnalyser.fftSize = 2048; | |
| 35 | 新增: window.testAudioGain.connect(window.testAudioAnalyser); | |
| 36 | 新增: }); | |
| 37 | 新增: const packet = Buffer.alloc(48000 * 4 * 3); | |
| 38 | 新增: for (let i = 0; i < 48000 * 3; i++) { | |
| 39 | 新增: const value = Math.round(Math.sin(i * 2 * Math.PI * 880 / 48000) * 8000); | |
| 40 | 新增: packet.writeInt16LE(value, i * 4); packet.writeInt16LE(value, i * 4 + 2); | |
| 41 | 新增: } | |
| 42 | 新增: play = spawn("ssh", [...ssh, "sudo -u cage-browser /usr/bin/pacat --server=unix:/run/cage-audio/native --playback --raw --format=s16le --rate=48000 --channels=2 --latency-msec=20"]); | |
| 43 | 新增: const completed = new Promise((resolve, reject) => { play.on("error", reject); play.on("close", code => code === 0 ? resolve() : reject(new Error(`guest playback exited ${code}`))); }); | |
| 44 | 新增: play.stdin.end(packet); | |
| 45 | 新增: const measured = await page.waitForFunction(() => { | |
| 46 | 新增: const samples = new Float32Array(2048); | |
| 47 | 新增: window.testAudioAnalyser.getFloatTimeDomainData(samples); | |
| 48 | 新增: const rms = Math.sqrt(samples.reduce((sum, v) => sum + v * v, 0) / samples.length); | |
| 49 | 新增: return rms > .14 && rms < .20 ? rms : false; | |
| 50 | 新增: }, null, { timeout: 10000 }); | |
| 51 | 新增: console.log(JSON.stringify({ installedAudio: "PASS", RMS: await measured.jsonValue(), chain: "guest application → PulseAudio → SSH → authenticated WebSocket → production AudioWorklet" })); | |
| 52 | 新增: await completed; | |
| 53 | 新增: assert.deepEqual(errors, []); | |
| 54 | 新增:} finally { | |
| 55 | 新增: play?.kill(); | |
| 56 | 新增: await browser.close(); | |
| 57 | 新增:} | |
| 58 | 新增:let remaining = []; | |
| 59 | 新增:for (let i = 0; i < 40; i++) { | |
| 60 | 新增: remaining = capturePIDs().filter(pid => !before.has(pid)); | |
| 61 | 新增: if (!remaining.length) break; | |
| 62 | 新增: await new Promise(r => setTimeout(r, 100)); | |
| 63 | 新增:} | |
| 64 | 新增:assert.deepEqual(remaining, [], "closing the player left a capture process"); | |
| 65 | 新增:console.log("PASS: closing the production viewer stops guest capture"); | |
| @@ -0,0 +1,81 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { createRequire } from "node:module"; | |
| 3 | 新增:import { fileURLToPath } from "node:url"; | |
| 4 | 新增:import { createServer } from "vite"; | |
| 5 | 新增:const require = createRequire(import.meta.url); | |
| 6 | 新增:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"); | |
| 7 | 新增:const vite = await createServer({ root: fileURLToPath(new URL("..", import.meta.url)), configFile: fileURLToPath(new URL("../vite.config.js", import.meta.url)), server: { host: "127.0.0.1", port: 0 } }); | |
| 8 | 新增:await vite.listen(); | |
| 9 | 新增:const origin = `http://127.0.0.1:${vite.httpServer.address().port}`; | |
| 10 | 新增:const browser = await chromium.launch({ headless: true, args: ["--autoplay-policy=user-gesture-required"] }); | |
| 11 | 新增:const page = await browser.newPage(); | |
| 12 | 新增:let connected = 0, open = 0; | |
| 13 | 新增:const timers = new Set(), errors = []; | |
| 14 | 新增:page.on("pageerror", e => errors.push(e.message)); | |
| 15 | 新增:await page.addInitScript(() => { | |
| 16 | 新增: const Original = window.AudioContext; | |
| 17 | 新增: window.AudioContext = class extends Original { | |
| 18 | 新增: constructor(...args) { super(...args); window.testAudioContext = this; } | |
| 19 | 新增: createGain() { const node = super.createGain(); window.testAudioGain = node; return node; } | |
| 20 | 新增: }; | |
| 21 | 新增:}); | |
| 22 | 新增:await page.route("**/audio-test", async route => route.fulfill({ contentType: "text/html", body: await vite.transformIndexHtml("/audio-test", '<div id="root"></div><script type="module" src="/scripts/audio-fixture.jsx"></script>') })); | |
| 23 | 新增:const format = { format: "s16le", sample_rate: 48000, channels: 2 }; | |
| 24 | 新增:await page.route("**/api/audio", route => route.fulfill({ json: format })); | |
| 25 | 新增:const packet = Buffer.alloc(3840); | |
| 26 | 新增:for (let i = 0; i < 960; i++) for (let channel = 0; channel < 2; channel++) packet.writeInt16LE(Math.round(Math.sin(i * 2 * Math.PI * 1000 / 48000) * 10000), i * 4 + channel * 2); | |
| 27 | 新增:await page.routeWebSocket("**/api/audio", socket => { | |
| 28 | 新增: connected++; open++; | |
| 29 | 新增: socket.send(JSON.stringify(format)); | |
| 30 | 新增: const timer = setInterval(() => socket.send(packet), 20); | |
| 31 | 新增: timers.add(timer); | |
| 32 | 新增: socket.onClose(() => { clearInterval(timer); timers.delete(timer); open--; }); | |
| 33 | 新增:}); | |
| 34 | 新增:const waitFor = async predicate => { | |
| 35 | 新增: for (let i = 0; i < 100; i++) { if (predicate()) return; await new Promise(r => setTimeout(r, 30)); } | |
| 36 | 新增: throw new Error("Audio lifecycle did not settle"); | |
| 37 | 新增:}; | |
| 38 | 新增:const rms = () => page.evaluate(() => { | |
| 39 | 新增: const analyser = window.testAudioAnalyser; | |
| 40 | 新增: const samples = new Float32Array(analyser.fftSize); | |
| 41 | 新增: analyser.getFloatTimeDomainData(samples); | |
| 42 | 新增: return Math.sqrt(samples.reduce((sum, v) => sum + v * v, 0) / samples.length); | |
| 43 | 新增:}); | |
| 44 | 新增:try { | |
| 45 | 新增: await page.goto(origin + "/audio-test"); | |
| 46 | 新增: await page.waitForFunction(() => !!window.testAudioContext); | |
| 47 | 新增: await page.locator('input[aria-label="环境音量"]').click(); | |
| 48 | 新增: await page.locator("output").filter({ hasText: "playing" }).waitFor(); | |
| 49 | 新增: await page.evaluate(() => { | |
| 50 | 新增: window.testAudioAnalyser = window.testAudioContext.createAnalyser(); | |
| 51 | 新增: window.testAudioAnalyser.fftSize = 2048; | |
| 52 | 新增: window.testAudioGain.connect(window.testAudioAnalyser); | |
| 53 | 新增: }); | |
| 54 | 新增: await page.locator('input[aria-label="环境音量"]').press("End"); | |
| 55 | 新增: await page.waitForFunction(() => window.testAudioGain.gain.value === 1); | |
| 56 | 新增: let full; | |
| 57 | 新增: for (let i = 0; i < 100; i++) { full = await rms(); if (full > .19) break; await new Promise(r => setTimeout(r, 20)); } | |
| 58 | 新增: assert.ok(full > .19 && full < .24, `real audio RMS ${full}`); | |
| 59 | 新增: for (let i = 0; i < 50; i++) await page.locator('input[aria-label="环境音量"]').press("ArrowLeft"); | |
| 60 | 新增: await page.waitForFunction(() => window.testAudioGain.gain.value === .5); | |
| 61 | 新增: let half; | |
| 62 | 新增: for (let i = 0; i < 100; i++) { half = await rms(); if (half > .09 && half < .13) break; await new Promise(r => setTimeout(r, 20)); } | |
| 63 | 新增: assert.ok(half > .09 && half < .13, `half-volume RMS ${half}`); | |
| 64 | 新增: await page.getByRole("button", { name: "静音", exact: true }).click(); | |
| 65 | 新增: await waitFor(() => open === 0); | |
| 66 | 新增: assert.equal(await page.evaluate(() => window.testAudioContext.state), "suspended"); | |
| 67 | 新增: await page.getByRole("button", { name: "取消静音", exact: true }).click(); | |
| 68 | 新增: await waitFor(() => connected === 2 && open === 1); | |
| 69 | 新增: await page.locator("output").filter({ hasText: "playing" }).waitFor(); | |
| 70 | 新增: await page.getByRole("button", { name: "停止测试环境" }).click(); | |
| 71 | 新增: await waitFor(() => open === 0); | |
| 72 | 新增: assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("cage.audio")).volume), .5); | |
| 73 | 新增: assert.deepEqual(errors, []); | |
| 74 | 新增: console.log(JSON.stringify({ result: "PASS", fullVolumeRMS: full, halfVolumeRMS: half, checks: ["real AudioWorklet PCM output", "volume", "mute closes stream", "unmute reconnects", "environment stop", "preference persistence"] })); | |
| 75 | 新增:} catch (error) { | |
| 76 | 新增: console.error({ pageErrors: errors, body: await page.locator("body").innerText() }); | |
| 77 | 新增: throw error; | |
| 78 | 新增:} finally { | |
| 79 | 新增: for (const timer of timers) clearInterval(timer); | |
| 80 | 新增: await browser.close(); await vite.close(); | |
| 81 | 新增:} | |
| @@ -0,0 +1,148 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { createRequire } from "node:module"; | |
| 3 | 新增:import http from "node:http"; | |
| 4 | 新增:import { mkdtemp, readFile, rm, mkdir, copyFile } from "node:fs/promises"; | |
| 5 | 新增:import { tmpdir } from "node:os"; | |
| 6 | 新增:import { join } from "node:path"; | |
| 7 | 新增:import { Readable } from "node:stream"; | |
| 8 | 新增:import { UploadManager } from "../../internal/cage/browser-uploads.mjs"; | |
| 9 | 新增:import { DownloadManager } from "../../internal/cage/browser-downloads.mjs"; | |
| 10 | 新增:const require = createRequire(import.meta.url); | |
| 11 | 新增:const { chromium } = require( | |
| 12 | 新增: process.env.CAGE_PLAYWRIGHT_MODULE || "playwright", | |
| 13 | 新增:); | |
| 14 | 新增:const directory = await mkdtemp(join(tmpdir(), "cage-browser-files-")); | |
| 15 | 新增:const bytes = Buffer.alloc(8 * 1024 * 1024); | |
| 16 | 新增:for (let i = 0; i < bytes.length; i++) bytes[i] = i % 251; | |
| 17 | 新增:const received = []; | |
| 18 | 新增:const server = http.createServer(async (request, response) => { | |
| 19 | 新增: const url = new URL(request.url, "http://localhost"); | |
| 20 | 新增: if (url.pathname === "/download") { | |
| 21 | 新增: response.writeHead(200, { | |
| 22 | 新增: "Content-Type": "application/octet-stream", | |
| 23 | 新增: "Content-Disposition": 'attachment; filename="video.mp4"', | |
| 24 | 新增: "Content-Length": bytes.length, | |
| 25 | 新增: }); | |
| 26 | 新增: response.end(bytes); | |
| 27 | 新增: return; | |
| 28 | 新增: } | |
| 29 | 新增: if (url.pathname === "/received") { | |
| 30 | 新增: const chunks = []; | |
| 31 | 新增: for await (const chunk of request) chunks.push(chunk); | |
| 32 | 新增: received.push({ | |
| 33 | 新增: name: url.searchParams.get("name"), | |
| 34 | 新增: bytes: Buffer.concat(chunks), | |
| 35 | 新增: }); | |
| 36 | 新增: response.end("ok"); | |
| 37 | 新增: return; | |
| 38 | 新增: } | |
| 39 | 新增: response.setHeader("Content-Type", "text/html;charset=utf-8"); | |
| 40 | 新增: response.end(`<label>上传文件<input type="file" multiple></label><p id="names"></p><button>发送附件</button><a href="/download">下载测试视频</a><script> | |
| 41 | 新增: const input=document.querySelector('input');input.onchange=()=>document.querySelector('#names').textContent=Array.from(input.files).map(f=>f.name).join(','); | |
| 42 | 新增: document.querySelector('button').onclick=async()=>{for(const file of input.files)await fetch('/received?name='+encodeURIComponent(file.name),{method:'POST',body:file});document.querySelector('button').textContent='发送完成'}; | |
| 43 | 新增: </script>`); | |
| 44 | 新增:}); | |
| 45 | 新增:await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); | |
| 46 | 新增:const browser = await chromium.launch({ | |
| 47 | 新增: headless: true, | |
| 48 | 新增: executablePath: process.env.CAGE_TEST_BROWSER_PATH, | |
| 49 | 新增:}); | |
| 50 | 新增:const context = await browser.newContext(); | |
| 51 | 新增:const page = await context.newPage(); | |
| 52 | 新增:const cdp = await context.newCDPSession(page); | |
| 53 | 新增:const errors = []; | |
| 54 | 新增:const uploads = new UploadManager({ | |
| 55 | 新增: directory: join(directory, "uploads"), | |
| 56 | 新增: cdp: (method, params) => cdp.send(method, params), | |
| 57 | 新增:}); | |
| 58 | 新增:cdp.on("Page.fileChooserOpened", (event) => { | |
| 59 | 新增: void uploads | |
| 60 | 新增: .opened("tab-1", "session-1", event) | |
| 61 | 新增: .catch((error) => errors.push(error.message)); | |
| 62 | 新增:}); | |
| 63 | 新增:cdp.on("Page.frameNavigated", (event) => { | |
| 64 | 新增: if (!event.frame.parentId) uploads.cancelTab("tab-1"); | |
| 65 | 新增:}); | |
| 66 | 新增:const waitFor = async (condition) => { | |
| 67 | 新增: for (let i = 0; i < 200; i++) { | |
| 68 | 新增: if (condition()) return; | |
| 69 | 新增: await new Promise((resolve) => setTimeout(resolve, 25)); | |
| 70 | 新增: } | |
| 71 | 新增: throw new Error("browser file operation timed out"); | |
| 72 | 新增:}; | |
| 73 | 新增:try { | |
| 74 | 新增: await cdp.send("Page.enable"); | |
| 75 | 新增: await cdp.send("Page.setInterceptFileChooserDialog", { enabled: true }); | |
| 76 | 新增: await page.goto(`http://127.0.0.1:${server.address().port}`); | |
| 77 | 新增: await page.getByLabel("上传文件").click(); | |
| 78 | 新增: await waitFor(() => uploads.snapshot().length === 1); | |
| 79 | 新增: let request = uploads.snapshot()[0]; | |
| 80 | 新增: await uploads.receive( | |
| 81 | 新增: request.id, | |
| 82 | 新增: "参考视频.mp4", | |
| 83 | 新增: Readable.from([bytes.subarray(0, 3000), bytes.subarray(3000)]), | |
| 84 | 新增: ); | |
| 85 | 新增: await uploads.receive( | |
| 86 | 新增: request.id, | |
| 87 | 新增: "参考文档.txt", | |
| 88 | 新增: Readable.from([Buffer.from("多文件上传\n中文🙂")]), | |
| 89 | 新增: ); | |
| 90 | 新增: await uploads.finish(request.id); | |
| 91 | 新增: await page | |
| 92 | 新增: .locator("#names") | |
| 93 | 新增: .filter({ hasText: "参考视频.mp4,参考文档.txt" }) | |
| 94 | 新增: .waitFor(); | |
| 95 | 新增: await page.getByRole("button", { name: "发送附件" }).click(); | |
| 96 | 新增: await page.getByRole("button", { name: "发送完成" }).waitFor(); | |
| 97 | 新增: assert.deepEqual(received[0].bytes, bytes); | |
| 98 | 新增: assert.equal(received[1].bytes.toString(), "多文件上传\n中文🙂"); | |
| 99 | 新增: await page.getByLabel("上传文件").click(); | |
| 100 | 新增: await waitFor(() => uploads.snapshot().length === 1); | |
| 101 | 新增: request = uploads.snapshot()[0]; | |
| 102 | 新增: uploads.cancel(request.id); | |
| 103 | 新增: assert.equal( | |
| 104 | 新增: await page.locator("input").evaluate((input) => input.files.length), | |
| 105 | 新增: 2, | |
| 106 | 新增: "cancel must retain the prior selection", | |
| 107 | 新增: ); | |
| 108 | 新增: await page.getByLabel("上传文件").click(); | |
| 109 | 新增: await waitFor(() => uploads.snapshot().length === 1); | |
| 110 | 新增: request = uploads.snapshot()[0]; | |
| 111 | 新增: await page.reload(); | |
| 112 | 新增: await assert.rejects(uploads.finish(request.id), /关闭/); | |
| 113 | 新增: | |
| 114 | 新增: const workspace = join(directory, "workspace"); | |
| 115 | 新增: await mkdir(workspace); | |
| 116 | 新增: const downloads = new DownloadManager({ | |
| 117 | 新增: directory, | |
| 118 | 新增: save: async (id, name) => { | |
| 119 | 新增: const path = join(workspace, name); | |
| 120 | 新增: await copyFile(join(directory, "Downloads", id), path); | |
| 121 | 新增: return { ok: true, name, path, bytes: bytes.length }; | |
| 122 | 新增: }, | |
| 123 | 新增: }); | |
| 124 | 新增: const root = await browser.newBrowserCDPSession(); | |
| 125 | 新增: const { targetInfo } = await cdp.send("Target.getTargetInfo"); | |
| 126 | 新增: root.on("Browser.downloadWillBegin", (event) => | |
| 127 | 新增: downloads.begin(event.guid, event.suggestedFilename), | |
| 128 | 新增: ); | |
| 129 | 新增: root.on("Browser.downloadProgress", (event) => downloads.progress(event)); | |
| 130 | 新增: await root.send("Browser.setDownloadBehavior", { | |
| 131 | 新增: behavior: "allowAndName", | |
| 132 | 新增: downloadPath: join(directory, "Downloads"), | |
| 133 | 新增: browserContextId: targetInfo.browserContextId, | |
| 134 | 新增: eventsEnabled: true, | |
| 135 | 新增: }); | |
| 136 | 新增: await page.getByRole("link", { name: "下载测试视频" }).click(); | |
| 137 | 新增: await waitFor(() => downloads.snapshot()[0]?.state === "saved"); | |
| 138 | 新增: assert.deepEqual(await readFile(downloads.snapshot()[0].path), bytes); | |
| 139 | 新增: assert.deepEqual(errors, []); | |
| 140 | 新增: console.log( | |
| 141 | 新增: "PASS: real Chromium chooser interception, 8 MB binary + Unicode file upload, cancel preserves selection, navigation cancels stale chooser, download progress and exact saved bytes", | |
| 142 | 新增: ); | |
| 143 | 新增:} finally { | |
| 144 | 新增: await browser.close(); | |
| 145 | 新增: server.closeAllConnections(); | |
| 146 | 新增: await new Promise((resolve) => server.close(resolve)); | |
| 147 | 新增: await rm(directory, { recursive: true, force: true }); | |
| 148 | 新增:} | |
| @@ -0,0 +1,178 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 3 | 新增:const id = "34e399c1-78fe-4cf1-93b0-d7fef431b211"; | |
| 4 | 新增:const chooser = "61c716bb-5e8f-4a32-b872-cfa099a695ef"; | |
| 5 | 新增:const nativeCalls = [], | |
| 6 | 新增: uploads = []; | |
| 7 | 新增:let saved = [], | |
| 8 | 新增: selections = [], | |
| 9 | 新增: cancelSave = true; | |
| 10 | 新增:const download = { | |
| 11 | 新增: id, | |
| 12 | 新增: name: "video.mp4", | |
| 13 | 新增: state: "downloading", | |
| 14 | 新增: receivedBytes: 3, | |
| 15 | 新增: totalBytes: 100, | |
| 16 | 新增:}; | |
| 17 | 新增:const fixture = await createWorkbench({ | |
| 18 | 新增: nativeRequest: async (body) => { | |
| 19 | 新增: if (body.action === "saveBrowserDownload") { | |
| 20 | 新增: nativeCalls.push(body); | |
| 21 | 新增: if (cancelSave) return { canceled: true }; | |
| 22 | 新增: saved = [ | |
| 23 | 新增: { id, name: "视频.mp4", path: "/Users/test/Downloads/视频.mp4" }, | |
| 24 | 新增: ]; | |
| 25 | 新增: return saved[0]; | |
| 26 | 新增: } | |
| 27 | 新增: if (body.action === "browserDownloadAction") { | |
| 28 | 新增: nativeCalls.push(body); | |
| 29 | 新增: return { ok: true }; | |
| 30 | 新增: } | |
| 31 | 新增: return null; | |
| 32 | 新增: }, | |
| 33 | 新增:}); | |
| 34 | 新增:const { browser, page, state, errors } = fixture; | |
| 35 | 新增:await page.route("**/api/browser/tabs", (route) => | |
| 36 | 新增: route.fulfill({ | |
| 37 | 新增: json: { | |
| 38 | 新增: tabs: state.tabs, | |
| 39 | 新增: active: state.active, | |
| 40 | 新增: downloads: [download], | |
| 41 | 新增: uploads: selections, | |
| 42 | 新增: }, | |
| 43 | 新增: }), | |
| 44 | 新增:); | |
| 45 | 新增:await page.route("**/api/browser/files/saved", (route) => | |
| 46 | 新增: route.fulfill({ json: saved }), | |
| 47 | 新增:); | |
| 48 | 新增:await page.route("**/api/browser/files/uploads/**", async (route) => { | |
| 49 | 新增: uploads.push({ | |
| 50 | 新增: name: new URL(route.request().url()).searchParams.get("name"), | |
| 51 | 新增: bytes: route.request().postDataBuffer(), | |
| 52 | 新增: }); | |
| 53 | 新增: await route.fulfill({ json: { ok: true } }); | |
| 54 | 新增:}); | |
| 55 | 新增:await page.route("**/api/browser/upload-finish", (route) => { | |
| 56 | 新增: assert.equal(route.request().postDataJSON().id, chooser); | |
| 57 | 新增: selections = []; | |
| 58 | 新增: return route.fulfill({ json: { ok: true } }); | |
| 59 | 新增:}); | |
| 60 | 新增:await page.route("**/api/browser/upload-cancel", (route) => { | |
| 61 | 新增: selections = []; | |
| 62 | 新增: return route.fulfill({ json: { ok: true } }); | |
| 63 | 新增:}); | |
| 64 | 新增:const poll = async (condition) => { | |
| 65 | 新增: for (let i = 0; i < 120; i++) { | |
| 66 | 新增: if (condition()) return; | |
| 67 | 新增: await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 68 | 新增: } | |
| 69 | 新增: throw new Error("UI state timeout"); | |
| 70 | 新增:}; | |
| 71 | 新增:try { | |
| 72 | 新增: state.status.ready = true; | |
| 73 | 新增: state.status.vm_running = true; | |
| 74 | 新增: await page.reload(); | |
| 75 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 76 | 新增: await page.getByRole("button", { name: "浏览器下载", exact: true }).click(); | |
| 77 | 新增: await page.getByText("正在下载", { exact: false }).waitFor(); | |
| 78 | 新增: await page | |
| 79 | 新增: .getByRole("dialog", { name: "浏览器下载" }) | |
| 80 | 新增: .getByRole("button", { name: "关闭面板" }) | |
| 81 | 新增: .click(); | |
| 82 | 新增: selections = [{ id: chooser, tabId: "tab-1", multiple: true }]; | |
| 83 | 新增: await page.getByRole("dialog", { name: "上传本机文件" }).waitFor(); | |
| 84 | 新增: Object.assign(download, { | |
| 85 | 新增: state: "saved", | |
| 86 | 新增: path: "/Users/test/Cage/Downloads/video.mp4", | |
| 87 | 新增: }); | |
| 88 | 新增: const first = Buffer.alloc(1024 * 1024, 217), | |
| 89 | 新增: second = Buffer.from("附件正文🙂"); | |
| 90 | 新增: await page.getByLabel("选择本机文件").setInputFiles([ | |
| 91 | 新增: { name: "参考视频.mp4", mimeType: "video/mp4", buffer: first }, | |
| 92 | 新增: { name: "参考.txt", mimeType: "text/plain", buffer: second }, | |
| 93 | 新增: ]); | |
| 94 | 新增: await page | |
| 95 | 新增: .getByRole("dialog", { name: "上传本机文件" }) | |
| 96 | 新增: .waitFor({ state: "hidden" }); | |
| 97 | 新增: assert.deepEqual( | |
| 98 | 新增: uploads.map((item) => item.name), | |
| 99 | 新增: ["参考视频.mp4", "参考.txt"], | |
| 100 | 新增: ); | |
| 101 | 新增: assert.deepEqual(uploads[0].bytes, first); | |
| 102 | 新增: assert.deepEqual(uploads[1].bytes, second); | |
| 103 | 新增: await poll(() => | |
| 104 | 新增: nativeCalls.some((call) => call.action === "saveBrowserDownload"), | |
| 105 | 新增: ); | |
| 106 | 新增: assert.equal(saved.length, 0, "cancel must not invent a save destination"); | |
| 107 | 新增: await page.getByRole("button", { name: "浏览器下载", exact: true }).click(); | |
| 108 | 新增: await page | |
| 109 | 新增: .getByText("/Users/test/Cage/Downloads/video.mp4", { exact: true }) | |
| 110 | 新增: .waitFor(); | |
| 111 | 新增: cancelSave = false; | |
| 112 | 新增: await page.getByRole("button", { name: "另存为…", exact: true }).click(); | |
| 113 | 新增: await page | |
| 114 | 新增: .getByText("/Users/test/Downloads/视频.mp4", { exact: true }) | |
| 115 | 新增: .waitFor(); | |
| 116 | 新增: await page | |
| 117 | 新增: .getByRole("dialog", { name: "浏览器下载" }) | |
| 118 | 新增: .getByRole("button", { name: "打开文件", exact: true }) | |
| 119 | 新增: .click(); | |
| 120 | 新增: await page | |
| 121 | 新增: .getByRole("button", { name: "在文件夹中显示", exact: true }) | |
| 122 | 新增: .click(); | |
| 123 | 新增: await poll( | |
| 124 | 新增: () => | |
| 125 | 新增: nativeCalls.filter((call) => call.action === "browserDownloadAction") | |
| 126 | 新增: .length === 2, | |
| 127 | 新增: ); | |
| 128 | 新增: assert.deepEqual( | |
| 129 | 新增: nativeCalls | |
| 130 | 新增: .filter((call) => call.action === "browserDownloadAction") | |
| 131 | 新增: .map((call) => [call.operation, call.id]), | |
| 132 | 新增: [ | |
| 133 | 新增: ["open", id], | |
| 134 | 新增: ["reveal", id], | |
| 135 | 新增: ], | |
| 136 | 新增: ); | |
| 137 | 新增: assert.ok( | |
| 138 | 新增: nativeCalls.every((call) => !("path" in call)), | |
| 139 | 新增: "web UI must not send arbitrary host paths", | |
| 140 | 新增: ); | |
| 141 | 新增: await page | |
| 142 | 新增: .getByRole("dialog", { name: "浏览器下载" }) | |
| 143 | 新增: .getByRole("button", { name: "关闭面板" }) | |
| 144 | 新增: .click(); | |
| 145 | 新增: selections = [{ id: chooser, tabId: "tab-1", multiple: false }]; | |
| 146 | 新增: await page | |
| 147 | 新增: .getByRole("dialog", { name: "上传本机文件" }) | |
| 148 | 新增: .getByRole("button", { name: "取消上传" }) | |
| 149 | 新增: .click(); | |
| 150 | 新增: await page | |
| 151 | 新增: .getByRole("dialog", { name: "上传本机文件" }) | |
| 152 | 新增: .waitFor({ state: "hidden" }); | |
| 153 | 新增: state.status.ready = false; | |
| 154 | 新增: state.status.vm_running = false; | |
| 155 | 新增: await page.waitForFunction( | |
| 156 | 新增: () => | |
| 157 | 新增: document.querySelector('[aria-label="打开浏览器"]')?.disabled === true, | |
| 158 | 新增: ); | |
| 159 | 新增: await page.getByRole("button", { name: "下载文件", exact: true }).click(); | |
| 160 | 新增: await page | |
| 161 | 新增: .getByText("/Users/test/Downloads/视频.mp4", { exact: true }) | |
| 162 | 新增: .waitFor(); | |
| 163 | 新增: await page | |
| 164 | 新增: .getByRole("dialog", { name: "浏览器下载" }) | |
| 165 | 新增: .getByRole("button", { name: "打开文件", exact: true }) | |
| 166 | 新增: .click(); | |
| 167 | 新增: await poll( | |
| 168 | 新增: () => | |
| 169 | 新增: nativeCalls.filter((call) => call.action === "browserDownloadAction") | |
| 170 | 新增: .length === 3, | |
| 171 | 新增: ); | |
| 172 | 新增: assert.deepEqual(errors, []); | |
| 173 | 新增: console.log( | |
| 174 | 新增: "PASS: workbench native-file input with exact binary POST, multiple files, cancel, deferred Save As, canceled Save As keeps fallback, saved path, Open/Reveal IDs", | |
| 175 | 新增: ); | |
| 176 | 新增:} finally { | |
| 177 | 新增: await browser.close(); | |
| 178 | 新增:} | |
| @@ -0,0 +1,219 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import fs from "node:fs/promises"; | |
| 3 | 新增:import { fileURLToPath } from "node:url"; | |
| 4 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 新增:import { | |
| 6 | 新增: presets, | |
| 7 | 新增: themeCatalog, | |
| 8 | 新增: parseThemeDocument, | |
| 9 | 新增: sameTheme, | |
| 10 | 新增:} from "../src/appearance-state.mjs"; | |
| 11 | 新增:const output = fileURLToPath( | |
| 12 | 新增: new URL( | |
| 13 | 新增: "../../docs/test-reports/2026-11-02-builtin-themes/", | |
| 14 | 新增: import.meta.url, | |
| 15 | 新增: ), | |
| 16 | 新增:); | |
| 17 | 新增:await fs.mkdir(output, { recursive: true }); | |
| 18 | 新增:let exported; | |
| 19 | 新增:const { browser, page, state, errors } = await createWorkbench({ | |
| 20 | 新增: nativeRequest: (body) => { | |
| 21 | 新增: if (body.action === "exportTheme") exported = body; | |
| 22 | 新增: return true; | |
| 23 | 新增: }, | |
| 24 | 新增:}); | |
| 25 | 新增:const checks = []; | |
| 26 | 新增:const open = async () => { | |
| 27 | 新增: await page.getByRole("button", { name: /^设置/ }).click(); | |
| 28 | 新增: await page.getByRole("button", { name: "外观", exact: true }).click(); | |
| 29 | 新增: await page.getByRole("heading", { name: "外观", exact: true }).waitFor(); | |
| 30 | 新增:}; | |
| 31 | 新增:const saved = () => | |
| 32 | 新增: page | |
| 33 | 新增: .locator(".appearance-save-state") | |
| 34 | 新增: .filter({ hasText: "更改自动保存,即时生效" }) | |
| 35 | 新增: .waitFor(); | |
| 36 | 新增:const select = async (variant, id) => { | |
| 37 | 新增: await page | |
| 38 | 新增: .getByLabel((variant === "light" ? "浅色" : "深色") + "主题预设", { | |
| 39 | 新增: exact: true, | |
| 40 | 新增: }) | |
| 41 | 新增: .selectOption(id); | |
| 42 | 新增: await saved(); | |
| 43 | 新增:}; | |
| 44 | 新增:const shot = async (name) => { | |
| 45 | 新增: await page.locator(".settings-content").evaluate((el) => el.scrollTo(0, 0)); | |
| 46 | 新增: await page.screenshot({ | |
| 47 | 新增: path: output + name + ".png", | |
| 48 | 新增: animations: "disabled", | |
| 49 | 新增: }); | |
| 50 | 新增:}; | |
| 51 | 新增:try { | |
| 52 | 新增: await page.emulateMedia({ colorScheme: "light" }); | |
| 53 | 新增: await open(); | |
| 54 | 新增: for (const variant of ["light", "dark"]) { | |
| 55 | 新增: const picker = page.getByLabel( | |
| 56 | 新增: (variant === "light" ? "浅色" : "深色") + "主题预设", | |
| 57 | 新增: { exact: true }, | |
| 58 | 新增: ); | |
| 59 | 新增: assert.equal(await picker.locator("optgroup").count(), 4); | |
| 60 | 新增: assert.equal( | |
| 61 | 新增: await picker.locator("option").count(), | |
| 62 | 新增: Object.keys(presets[variant]).length, | |
| 63 | 新增: ); | |
| 64 | 新增: // Every palette goes through the real picker, not just the model helper. | |
| 65 | 新增: for (const id of Object.keys(presets[variant])) { | |
| 66 | 新增: await select(variant, id); | |
| 67 | 新增: const theme = state.appearance[variant + "Theme"]; | |
| 68 | 新增: assert.equal(theme.preset, id); | |
| 69 | 新增: assert.deepEqual(theme.colors, presets[variant][id].colors); | |
| 70 | 新增: assert.deepEqual(theme.terminal, presets[variant][id].terminal); | |
| 71 | 新增: } | |
| 72 | 新增: } | |
| 73 | 新增: await select("light", "vscode-modern"); | |
| 74 | 新增: await select("dark", "vscode-modern"); | |
| 75 | 新增: assert.equal( | |
| 76 | 新增: await page.evaluate( | |
| 77 | 新增: () => | |
| 78 | 新增: getComputedStyle(document.querySelector(".settings-sidebar")) | |
| 79 | 新增: .backgroundColor, | |
| 80 | 新增: ), | |
| 81 | 新增: "rgb(248, 248, 248)", | |
| 82 | 新增: ); | |
| 83 | 新增: await shot("vscode-modern-light"); | |
| 84 | 新增: await page.getByRole("button", { name: "深色", exact: true }).click(); | |
| 85 | 新增: await saved(); | |
| 86 | 新增: await shot("vscode-modern-dark"); | |
| 87 | 新增: await select("light", "sepia"); | |
| 88 | 新增: await select("dark", "night"); | |
| 89 | 新增: await page.getByRole("button", { name: "浅色", exact: true }).click(); | |
| 90 | 新增: await saved(); | |
| 91 | 新增: await shot("reading-sepia"); | |
| 92 | 新增: checks.push( | |
| 93 | 新增: `真实下拉选取全部 ${Object.keys(presets.light).length + Object.keys(presets.dark).length} 套配色,四组分类、界面及终端色板完整应用`, | |
| 94 | 新增: ); | |
| 95 | 新增: await select("light", "color-vision"); | |
| 96 | 新增: await select("dark", "color-vision"); | |
| 97 | 新增: assert.equal( | |
| 98 | 新增: await page.evaluate(() => document.documentElement.dataset.translucent), | |
| 99 | 新增: "false", | |
| 100 | 新增: ); | |
| 101 | 新增: for (const label of ["浅色主题状态配色预览", "深色主题状态配色预览"]) { | |
| 102 | 新增: const preview = page.getByLabel(label, { exact: true }); | |
| 103 | 新增: for (const text of ["成功", "警告", "错误"]) | |
| 104 | 新增: await preview.getByText(text, { exact: true }).waitFor(); | |
| 105 | 新增: assert.equal(await preview.locator("svg").count(), 3); | |
| 106 | 新增: } | |
| 107 | 新增: assert.equal( | |
| 108 | 新增: await page.evaluate(() => | |
| 109 | 新增: getComputedStyle(document.documentElement).getPropertyValue("--success"), | |
| 110 | 新增: ), | |
| 111 | 新增: "#005a9c", | |
| 112 | 新增: ); | |
| 113 | 新增: assert.equal( | |
| 114 | 新增: await page.evaluate(() => | |
| 115 | 新增: getComputedStyle(document.documentElement).getPropertyValue("--danger"), | |
| 116 | 新增: ), | |
| 117 | 新增: "#a63b00", | |
| 118 | 新增: ); | |
| 119 | 新增: await shot("color-vision-light"); | |
| 120 | 新增: await page.getByRole("button", { name: "深色", exact: true }).click(); | |
| 121 | 新增: await saved(); | |
| 122 | 新增: await shot("color-vision-dark"); | |
| 123 | 新增: await select("light", "high-contrast"); | |
| 124 | 新增: await select("dark", "high-contrast"); | |
| 125 | 新增: await shot("high-contrast-dark"); | |
| 126 | 新增: await page.getByRole("button", { name: "浅色", exact: true }).click(); | |
| 127 | 新增: await saved(); | |
| 128 | 新增: await shot("high-contrast-light"); | |
| 129 | 新增: // Switching away must clear accessibility colors as well as earlier user overrides. | |
| 130 | 新增: await select("light", "paper"); | |
| 131 | 新增: assert.equal(state.appearance.lightTheme.colors.success, undefined); | |
| 132 | 新增: assert.equal(state.appearance.lightTheme.terminal.green, "#426e37"); | |
| 133 | 新增: await select("light", "color-vision"); | |
| 134 | 新增: await select("dark", "color-vision"); | |
| 135 | 新增: await page.getByLabel("主题名称", { exact: true }).fill("我的蓝橙搭配"); | |
| 136 | 新增: await page.getByRole("button", { name: "另存为主题", exact: true }).click(); | |
| 137 | 新增: await page.getByRole("status").filter({ hasText: "主题已保存" }).waitFor(); | |
| 138 | 新增: const snapshot = structuredClone(state.appearance); | |
| 139 | 新增: await page.getByRole("button", { name: "导出主题", exact: true }).click(); | |
| 140 | 新增: await page.getByRole("status").filter({ hasText: "主题已导出" }).waitFor(); | |
| 141 | 新增: assert.ok(sameTheme(parseThemeDocument(exported.text), snapshot)); | |
| 142 | 新增: await fs.writeFile( | |
| 143 | 新增: output + "accessible-export.cage-theme.json", | |
| 144 | 新增: exported.text, | |
| 145 | 新增: ); | |
| 146 | 新增: await page.reload(); | |
| 147 | 新增: await open(); | |
| 148 | 新增: assert.equal( | |
| 149 | 新增: await page.getByLabel("浅色主题预设", { exact: true }).inputValue(), | |
| 150 | 新增: "color-vision", | |
| 151 | 新增: ); | |
| 152 | 新增: assert.equal( | |
| 153 | 新增: await page.getByLabel("已保存的主题", { exact: true }).inputValue(), | |
| 154 | 新增: state.appearance.customThemes[0].id, | |
| 155 | 新增: ); | |
| 156 | 新增: assert.ok(sameTheme(state.appearance, snapshot)); | |
| 157 | 新增: checks.push( | |
| 158 | 新增: "蓝橙状态图标与文字、高对比不透明窗口、跨预设清除旧覆盖、命名保存/导出/刷新读回", | |
| 159 | 新增: ); | |
| 160 | 新增: await page.setViewportSize({ width: 820, height: 558 }); | |
| 161 | 新增: await shot("builtin-minimum"); | |
| 162 | 新增: assert.equal( | |
| 163 | 新增: await page.evaluate( | |
| 164 | 新增: () => document.documentElement.scrollWidth > innerWidth, | |
| 165 | 新增: ), | |
| 166 | 新增: false, | |
| 167 | 新增: ); | |
| 168 | 新增: await page.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 169 | 新增: await page | |
| 170 | 新增: .getByRole("button", { name: "启动 Cage 环境", exact: true }) | |
| 171 | 新增: .click(); | |
| 172 | 新增: await page | |
| 173 | 新增: .getByRole("button", { name: "新建终端", exact: true }) | |
| 174 | 新增: .first() | |
| 175 | 新增: .click(); | |
| 176 | 新增: await page.getByRole("button", { name: "新建普通终端", exact: true }).click(); | |
| 177 | 新增: await page.getByRole("tab", { name: "终端 1", exact: true }).waitFor(); | |
| 178 | 新增: await page.waitForFunction( | |
| 179 | 新增: () => | |
| 180 | 新增: getComputedStyle(document.querySelector(".xterm-scrollable-element")) | |
| 181 | 新增: .backgroundColor === "rgb(255, 255, 255)", | |
| 182 | 新增: ); | |
| 183 | 新增: const connections = state.terminalConnections; | |
| 184 | 新增: await open(); | |
| 185 | 新增: await select("light", "high-contrast"); | |
| 186 | 新增: await page.getByRole("button", { name: "深色", exact: true }).click(); | |
| 187 | 新增: await saved(); | |
| 188 | 新增: await page.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 189 | 新增: await page.waitForFunction( | |
| 190 | 新增: () => | |
| 191 | 新增: getComputedStyle(document.querySelector(".xterm-scrollable-element")) | |
| 192 | 新增: .backgroundColor === "rgb(18, 27, 36)", | |
| 193 | 新增: ); | |
| 194 | 新增: assert.equal(state.terminalConnections, connections); | |
| 195 | 新增: await page.setViewportSize({ width: 1280, height: 850 }); | |
| 196 | 新增: await page.screenshot({ | |
| 197 | 新增: path: output + "terminal-color-vision.png", | |
| 198 | 新增: animations: "disabled", | |
| 199 | 新增: }); | |
| 200 | 新增: checks.push("820px 无横向溢出;明暗切换实时更新已有终端,连接保持"); | |
| 201 | 新增: assert.deepEqual(errors, []); | |
| 202 | 新增: assert.ok( | |
| 203 | 新增: !state.requests.some( | |
| 204 | 新增: (request) => request.path === "/settings" && request.method === "POST", | |
| 205 | 新增: ), | |
| 206 | 新增: ); | |
| 207 | 新增: const result = { | |
| 208 | 新增: passed: true, | |
| 209 | 新增: families: themeCatalog.length, | |
| 210 | 新增: light: Object.keys(presets.light).length, | |
| 211 | 新增: dark: Object.keys(presets.dark).length, | |
| 212 | 新增: checks, | |
| 213 | 新增: scope: "真实前端、xterm 和隔离 API;不连接日常 VM", | |
| 214 | 新增: }; | |
| 215 | 新增: await fs.writeFile(output + "result.json", JSON.stringify(result, null, 2)); | |
| 216 | 新增: console.log(JSON.stringify(result)); | |
| 217 | 新增:} finally { | |
| 218 | 新增: await browser.close(); | |
| 219 | 新增:} | |
| @@ -0,0 +1,155 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import fs from "node:fs/promises"; | |
| 3 | 新增:import { fileURLToPath } from "node:url"; | |
| 4 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 新增:const output = new URL( | |
| 6 | 新增: "../../docs/test-reports/2026-11-02-claude-desktop/", | |
| 7 | 新增: import.meta.url, | |
| 8 | 新增:); | |
| 9 | 新增:await fs.mkdir(output, { recursive: true }); | |
| 10 | 新增:const { browser, page, state, errors } = await createWorkbench(); | |
| 11 | 新增:const desktop = { | |
| 12 | 新增: installed: false, | |
| 13 | 新增: running: false, | |
| 14 | 新增: version: "", | |
| 15 | 新增: failed: false, | |
| 16 | 新增:}; | |
| 17 | 新增:let failInstall = true; | |
| 18 | 新增:const actions = []; | |
| 19 | 新增:await page.route("**/api/claude-desktop**", async (route) => { | |
| 20 | 新增: const path = new URL(route.request().url()).pathname; | |
| 21 | 新增: if (path.endsWith("/vnc-credentials")) | |
| 22 | 新增: return route.fulfill({ json: { password: "fixture-only" } }); | |
| 23 | 新增: if (route.request().method() === "GET") | |
| 24 | 新增: return route.fulfill({ json: desktop }); | |
| 25 | 新增: if (path.endsWith("/resize")) return route.fulfill({ json: { ok: true } }); | |
| 26 | 新增: const action = path.split("/").at(-1); | |
| 27 | 新增: actions.push(action); | |
| 28 | 新增: const job = { | |
| 29 | 新增: id: "desktop-" + actions.length, | |
| 30 | 新增: kind: "claude-desktop-" + action, | |
| 31 | 新增: running: false, | |
| 32 | 新增: message: "已完成", | |
| 33 | 新增: }; | |
| 34 | 新增: if (action === "install" && failInstall) | |
| 35 | 新增: job.error = "测试:安装源暂时不可用,请重试"; | |
| 36 | 新增: else if (action === "install") | |
| 37 | 新增: Object.assign(desktop, { installed: true, version: "4.4212.0" }); | |
| 38 | 新增: else if (action === "start") desktop.running = true; | |
| 39 | 新增: else if (action === "stop") desktop.running = false; | |
| 40 | 新增: state.status.job = job; | |
| 41 | 新增: await route.fulfill({ json: job }); | |
| 42 | 新增:}); | |
| 43 | 新增:try { | |
| 44 | 新增: state.status.vm_running = true; | |
| 45 | 新增: state.status.ready = true; | |
| 46 | 新增: await page.reload(); | |
| 47 | 新增: await page.getByRole("button", { name: "claude.ai", exact: true }).click(); | |
| 48 | 新增: assert.equal( | |
| 49 | 新增: state.requests.find((x) => x.path === "/browser/new").body.url, | |
| 50 | 新增: "https://claude.ai/", | |
| 51 | 新增: ); | |
| 52 | 新增: await page | |
| 53 | 新增: .getByRole("button", { name: "Claude Desktop", exact: true }) | |
| 54 | 新增: .click(); | |
| 55 | 新增: await page.getByRole("button", { name: "下载并安装", exact: true }).waitFor(); | |
| 56 | 新增: assert.deepEqual( | |
| 57 | 新增: actions, | |
| 58 | 新增: [], | |
| 59 | 新增: "opening the entry must not download without clicking install", | |
| 60 | 新增: ); | |
| 61 | 新增: await page.screenshot({ | |
| 62 | 新增: path: fileURLToPath(new URL("desktop-install.png", output)), | |
| 63 | 新增: }); | |
| 64 | 新增: await page.getByRole("button", { name: "下载并安装", exact: true }).click(); | |
| 65 | 新增: await page | |
| 66 | 新增: .getByRole("alert") | |
| 67 | 新增: .filter({ hasText: "安装源暂时不可用" }) | |
| 68 | 新增: .waitFor(); | |
| 69 | 新增: assert.equal(desktop.installed, false); | |
| 70 | 新增: failInstall = false; | |
| 71 | 新增: await page.getByRole("button", { name: "下载并安装", exact: true }).click(); | |
| 72 | 新增: await page.getByRole("button", { name: "关闭应用", exact: true }).waitFor(); | |
| 73 | 新增: assert.deepEqual(actions, ["install", "install", "start"]); | |
| 74 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 75 | 新增: assert.equal( | |
| 76 | 新增: desktop.running, | |
| 77 | 新增: true, | |
| 78 | 新增: "changing views must not stop the desktop", | |
| 79 | 新增: ); | |
| 80 | 新增: await page | |
| 81 | 新增: .getByRole("button", { name: "Claude Desktop", exact: true }) | |
| 82 | 新增: .click(); | |
| 83 | 新增: await page.getByRole("button", { name: "关闭应用", exact: true }).click(); | |
| 84 | 新增: await page | |
| 85 | 新增: .getByRole("dialog") | |
| 86 | 新增: .getByRole("button", { name: "关闭应用", exact: true }) | |
| 87 | 新增: .click(); | |
| 88 | 新增: await page | |
| 89 | 新增: .getByRole("button", { name: "打开 Claude Desktop", exact: true }) | |
| 90 | 新增: .waitFor(); | |
| 91 | 新增: assert.equal(desktop.running, false); | |
| 92 | 新增: const stoppedActions = actions.length; | |
| 93 | 新增: await page.getByRole("button", { name: "刷新 Claude Desktop 状态" }).click(); | |
| 94 | 新增: assert.equal( | |
| 95 | 新增: actions.length, | |
| 96 | 新增: stoppedActions, | |
| 97 | 新增: "refresh must not reopen a stopped app", | |
| 98 | 新增: ); | |
| 99 | 新增: await page.getByRole("button", { name: /^设置/ }).click(); | |
| 100 | 新增: await page | |
| 101 | 新增: .getByLabel("Claude 终端启动命令", { exact: true }) | |
| 102 | 新增: .fill("claude --continue --model sonnet"); | |
| 103 | 新增: await page.getByRole("button", { name: "保存设置", exact: true }).click(); | |
| 104 | 新增: await page | |
| 105 | 新增: .getByLabel("Claude 终端启动命令", { exact: true }) | |
| 106 | 新增: .waitFor({ state: "hidden" }); | |
| 107 | 新增: assert.equal( | |
| 108 | 新增: state.settings.claude_terminal_command, | |
| 109 | 新增: "claude --continue --model sonnet", | |
| 110 | 新增: ); | |
| 111 | 新增: await page.getByRole("button", { name: /^在 .* 新建终端$/ }).click(); | |
| 112 | 新增: await page | |
| 113 | 新增: .getByRole("dialog") | |
| 114 | 新增: .getByText("claude --continue --model sonnet", { exact: true }) | |
| 115 | 新增: .waitFor(); | |
| 116 | 新增: await page.screenshot({ | |
| 117 | 新增: path: fileURLToPath(new URL("terminal-choice.png", output)), | |
| 118 | 新增: }); | |
| 119 | 新增: await page | |
| 120 | 新增: .getByRole("button", { name: "新建 Claude 终端", exact: true }) | |
| 121 | 新增: .click(); | |
| 122 | 新增: const terminalRequests = () => | |
| 123 | 新增: state.requests.filter( | |
| 124 | 新增: (x) => x.path === "/terminals" && x.method === "POST", | |
| 125 | 新增: ); | |
| 126 | 新增: assert.equal(terminalRequests().at(-1).body.kind, "claude"); | |
| 127 | 新增: assert.equal( | |
| 128 | 新增: terminalRequests().at(-1).body.workspace, | |
| 129 | 新增: state.settings.workspace, | |
| 130 | 新增: ); | |
| 131 | 新增: const before = terminalRequests().length; | |
| 132 | 新增: await page.reload(); | |
| 133 | 新增: await page.getByRole("button", { name: /^在 .* 新建终端$/ }).waitFor(); | |
| 134 | 新增: assert.equal( | |
| 135 | 新增: terminalRequests().length, | |
| 136 | 新增: before, | |
| 137 | 新增: "reconnect must not relaunch Claude", | |
| 138 | 新增: ); | |
| 139 | 新增: await page.getByRole("button", { name: /^在 .* 新建终端$/ }).click(); | |
| 140 | 新增: await page.getByRole("button", { name: "新建普通终端", exact: true }).click(); | |
| 141 | 新增: assert.equal(terminalRequests().at(-1).body.kind, "shell"); | |
| 142 | 新增: await page.setViewportSize({ width: 820, height: 558 }); | |
| 143 | 新增: await page | |
| 144 | 新增: .getByRole("button", { name: "Claude Desktop", exact: true }) | |
| 145 | 新增: .click(); | |
| 146 | 新增: await page.screenshot({ | |
| 147 | 新增: path: fileURLToPath(new URL("desktop-small.png", output)), | |
| 148 | 新增: }); | |
| 149 | 新增: assert.deepEqual(errors, []); | |
| 150 | 新增: console.log( | |
| 151 | 新增: "PASS: sidebar, optional installation, failure/retry, shared application lifecycle, terminal choice, command settings and reconnect", | |
| 152 | 新增: ); | |
| 153 | 新增:} finally { | |
| 154 | 新增: await browser.close(); | |
| 155 | 新增:} | |
| @@ -0,0 +1,20 @@ | ||
| 1 | 新增:import React from "react"; | |
| 2 | 新增:import { createRoot } from "react-dom/client"; | |
| 3 | 新增:import { AppearanceProvider } from "../src/appearance"; | |
| 4 | 新增:import { TerminalView } from "../src/views"; | |
| 5 | 新增:import "../src/style.css"; | |
| 6 | 新增: | |
| 7 | 新增:const root = createRoot(document.getElementById("terminal")); | |
| 8 | 新增:window.showTestTerminal = (visible = true) => | |
| 9 | 新增: root.render( | |
| 10 | 新增: <AppearanceProvider> | |
| 11 | 新增: <TerminalView | |
| 12 | 新增: session={{ id: "image-test" }} | |
| 13 | 新增: visible={visible} | |
| 14 | 新增: onStatus={(text) => { | |
| 15 | 新增: document.getElementById("status").textContent = text; | |
| 16 | 新增: }} | |
| 17 | 新增: /> | |
| 18 | 新增: </AppearanceProvider>, | |
| 19 | 新增: ); | |
| 20 | 新增:window.showTestTerminal(); | |
| @@ -0,0 +1,227 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { createRequire } from "node:module"; | |
| 3 | 新增:const require = createRequire(import.meta.url); | |
| 4 | 新增:const { chromium } = require( | |
| 5 | 新增: process.env.CAGE_PLAYWRIGHT_MODULE || "playwright", | |
| 6 | 新增:); | |
| 7 | 新增:const browser = await chromium.launch({ | |
| 8 | 新增: headless: true, | |
| 9 | 新增: executablePath: process.env.CAGE_TEST_BROWSER_PATH, | |
| 10 | 新增:}); | |
| 11 | 新增:const page = await browser.newPage(); | |
| 12 | 新增:const errors = []; | |
| 13 | 新增:page.on("pageerror", (error) => errors.push(error.message)); | |
| 14 | 新增:const origin = process.env.CAGE_UI_URL || "http://127.0.0.1:5173"; | |
| 15 | 新增:const received = []; | |
| 16 | 新增:let release, | |
| 17 | 新增: fail = false; | |
| 18 | 新增:await page.route("**/api/appearance", (route) => route.fulfill({ json: {} })); | |
| 19 | 新增:await page.route("**/api/input/image", async (route) => { | |
| 20 | 新增: received.push(route.request().postDataJSON()); | |
| 21 | 新增: await new Promise((resolve) => { | |
| 22 | 新增: release = resolve; | |
| 23 | 新增: }); | |
| 24 | 新增: await route.fulfill( | |
| 25 | 新增: fail | |
| 26 | 新增: ? { status: 502, body: "测试:图片传递失败" } | |
| 27 | 新增: : { | |
| 28 | 新增: json: { | |
| 29 | 新增: path: "/home/cage/.local/share/cage/attachments/image-test.png", | |
| 30 | 新增: ok: true, | |
| 31 | 新增: }, | |
| 32 | 新增: }, | |
| 33 | 新增: ); | |
| 34 | 新增:}); | |
| 35 | 新增:const messages = []; | |
| 36 | 新增:await page.routeWebSocket("**/api/terminals/**", (socket) => { | |
| 37 | 新增: socket.onMessage((data) => messages.push(JSON.parse(data))); | |
| 38 | 新增: socket.send(Buffer.from("\x1b[?2004hImage input acceptance\r\n$ ")); | |
| 39 | 新增:}); | |
| 40 | 新增:const html = `<div id="remote" style="height:220px"></div><input id="local" aria-label="本机输入框"><div id="terminal" style="height:400px"></div><div id="status" role="status"></div>`; | |
| 41 | 新增:await page.route("**/image-input-test", (route) => | |
| 42 | 新增: route.fulfill({ contentType: "text/html", body: html }), | |
| 43 | 新增:); | |
| 44 | 新增:const poll = async (predicate) => { | |
| 45 | 新增: for (let i = 0; i < 100; i++) { | |
| 46 | 新增: if (predicate()) return; | |
| 47 | 新增: await new Promise((r) => setTimeout(r, 30)); | |
| 48 | 新增: } | |
| 49 | 新增: throw new Error("fixture state timed out"); | |
| 50 | 新增:}; | |
| 51 | 新增:const imageEvent = (selector, type, image = true) => | |
| 52 | 新增: page.locator(selector).evaluate( | |
| 53 | 新增: async (element, { type, image }) => { | |
| 54 | 新增: const canvas = document.createElement("canvas"); | |
| 55 | 新增: canvas.width = 32; | |
| 56 | 新增: canvas.height = 24; | |
| 57 | 新增: canvas.getContext("2d").fillRect(0, 0, 32, 24); | |
| 58 | 新增: const blob = image | |
| 59 | 新增: ? await new Promise((resolve) => canvas.toBlob(resolve, "image/png")) | |
| 60 | 新增: : new Blob(["not an image"], { type: "text/plain" }); | |
| 61 | 新增: const data = new DataTransfer(); | |
| 62 | 新增: data.items.add( | |
| 63 | 新增: new File([blob], image ? "test.png" : "test.txt", { type: blob.type }), | |
| 64 | 新增: ); | |
| 65 | 新增: element.dispatchEvent( | |
| 66 | 新增: type === "paste" | |
| 67 | 新增: ? new ClipboardEvent("paste", { | |
| 68 | 新增: bubbles: true, | |
| 69 | 新增: cancelable: true, | |
| 70 | 新增: clipboardData: data, | |
| 71 | 新增: }) | |
| 72 | 新增: : new DragEvent("drop", { | |
| 73 | 新增: bubbles: true, | |
| 74 | 新增: cancelable: true, | |
| 75 | 新增: dataTransfer: data, | |
| 76 | 新增: }), | |
| 77 | 新增: ); | |
| 78 | 新增: }, | |
| 79 | 新增: { type, image }, | |
| 80 | 新增: ); | |
| 81 | 新增:try { | |
| 82 | 新增: await page.goto(origin + "/image-input-test"); | |
| 83 | 新增: await page.evaluate(async () => { | |
| 84 | 新增: const [{ default: RFB }, { installRemoteInput }, { sendImage }] = | |
| 85 | 新增: await Promise.all([ | |
| 86 | 新增: import("/.generated/novnc/core/rfb.js"), | |
| 87 | 新增: import("/src/remote-input.js"), | |
| 88 | 新增: import("/src/image-transfer.js"), | |
| 89 | 新增: ]); | |
| 90 | 新增: const rfb = new EventTarget(), | |
| 91 | 新增: container = document.getElementById("remote"), | |
| 92 | 新增: order = []; | |
| 93 | 新增: for (const name of ["_cageQueueInput", "cagePasteContent", "sendKey"]) | |
| 94 | 新增: rfb[name] = RFB.prototype[name].bind(rfb); | |
| 95 | 新增: rfb.cageSetKeyboardTarget = (target) => { | |
| 96 | 新增: rfb.target = target; | |
| 97 | 新增: }; | |
| 98 | 新增: rfb.focus = () => rfb.target?.focus(); | |
| 99 | 新增: rfb._cageRunInput = (action) => action(); | |
| 100 | 新增: rfb._cageSendKey = (sym) => order.push(sym); | |
| 101 | 新增: rfb._cagePasteText = (text) => { | |
| 102 | 新增: order.push(text); | |
| 103 | 新增: return Promise.resolve(); | |
| 104 | 新增: }; | |
| 105 | 新增: rfb.cagePasteText = (text) => | |
| 106 | 新增: rfb._cageQueueInput(() => rfb._cagePasteText(text)); | |
| 107 | 新增: let active = true; | |
| 108 | 新增: const input = installRemoteInput(rfb, container, { | |
| 109 | 新增: mode: () => "mac", | |
| 110 | 新增: isActive: () => active, | |
| 111 | 新增: insertText: async () => {}, | |
| 112 | 新增: onStatus: (text) => { | |
| 113 | 新增: document.getElementById("status").textContent = text; | |
| 114 | 新增: }, | |
| 115 | 新增: onFallback() {}, | |
| 116 | 新增: pasteContent: (content) => | |
| 117 | 新增: rfb.cagePasteContent( | |
| 118 | 新增: content, | |
| 119 | 新增: async (payload) => { | |
| 120 | 新增: await sendImage(payload, "browser", "tab-1"); | |
| 121 | 新增: order.push("image"); | |
| 122 | 新增: }, | |
| 123 | 新增: () => active && Boolean(rfb.target), | |
| 124 | 新增: ), | |
| 125 | 新增: }); | |
| 126 | 新增: window.probe = { | |
| 127 | 新增: rfb, | |
| 128 | 新增: order, | |
| 129 | 新增: input, | |
| 130 | 新增: deactivate: () => { | |
| 131 | 新增: active = false; | |
| 132 | 新增: }, | |
| 133 | 新增: }; | |
| 134 | 新增: rfb.focus(); | |
| 135 | 新增: }); | |
| 136 | 新增: await imageEvent("[aria-label='Cage 网页输入']", "paste"); | |
| 137 | 新增: await poll(() => received.length === 1); | |
| 138 | 新增: await page.evaluate(() => probe.rfb.sendKey(0xff0d, "Enter", true)); | |
| 139 | 新增: assert.deepEqual(await page.evaluate(() => probe.order), []); | |
| 140 | 新增: release(); | |
| 141 | 新增: await page.waitForFunction(() => probe.order.length === 2); | |
| 142 | 新增: assert.deepEqual(await page.evaluate(() => probe.order), ["image", 0xff0d]); | |
| 143 | 新增: assert.equal(received[0].target, "browser"); | |
| 144 | 新增: assert.equal( | |
| 145 | 新增: Buffer.from(received[0].png, "base64").subarray(1, 4).toString(), | |
| 146 | 新增: "PNG", | |
| 147 | 新增: ); | |
| 148 | 新增: await imageEvent("#remote", "drop"); | |
| 149 | 新增: await poll(() => received.length === 2); | |
| 150 | 新增: release(); | |
| 151 | 新增: await page.getByRole("status").filter({ hasText: "已传递" }).waitFor(); | |
| 152 | 新增: await imageEvent("#remote", "drop", false); | |
| 153 | 新增: await page.getByRole("status").filter({ hasText: "请选择 PNG" }).waitFor(); | |
| 154 | 新增: assert.equal(received.length, 2); | |
| 155 | 新增: await page.locator("#local").focus(); | |
| 156 | 新增: await imageEvent("#local", "paste"); | |
| 157 | 新增: assert.equal(received.length, 2, "local fields must not upload"); | |
| 158 | 新增: const cancelled = await page.evaluate(async () => { | |
| 159 | 新增: let finish; | |
| 160 | 新增: const delayed = new Promise((resolve) => { | |
| 161 | 新增: finish = resolve; | |
| 162 | 新增: }); | |
| 163 | 新增: const pending = probe.rfb.cagePasteContent( | |
| 164 | 新增: delayed, | |
| 165 | 新增: () => { | |
| 166 | 新增: throw new Error("stale image was sent"); | |
| 167 | 新增: }, | |
| 168 | 新增: () => false, | |
| 169 | 新增: ); | |
| 170 | 新增: finish({ png: "unused" }); | |
| 171 | 新增: try { | |
| 172 | 新增: await pending; | |
| 173 | 新增: return false; | |
| 174 | 新增: } catch (error) { | |
| 175 | 新增: return error.message === "Input target changed"; | |
| 176 | 新增: } | |
| 177 | 新增: }); | |
| 178 | 新增: assert.equal( | |
| 179 | 新增: cancelled, | |
| 180 | 新增: true, | |
| 181 | 新增: "clipboard completion after a target change must cancel", | |
| 182 | 新增: ); | |
| 183 | 新增: await page.evaluate(() => { | |
| 184 | 新增: probe.input.dispose(); | |
| 185 | 新增: }); | |
| 186 | 新增: await page.evaluate(async () => { | |
| 187 | 新增: const { default: RefreshRuntime } = await import("/@react-refresh"); | |
| 188 | 新增: RefreshRuntime.injectIntoGlobalHook(window); | |
| 189 | 新增: window.$RefreshReg$ = () => {}; | |
| 190 | 新增: window.$RefreshSig$ = () => (type) => type; | |
| 191 | 新增: window.__vite_plugin_react_preamble_installed__ = true; | |
| 192 | 新增: await import("/scripts/image-input-fixture.jsx"); | |
| 193 | 新增: }); | |
| 194 | 新增: await page.locator(".xterm-helper-textarea").waitFor(); | |
| 195 | 新增: await page.locator(".xterm-helper-textarea").focus(); | |
| 196 | 新增: await imageEvent(".xterm-helper-textarea", "paste"); | |
| 197 | 新增: await poll(() => received.length === 3); | |
| 198 | 新增: await page.keyboard.press("Enter"); | |
| 199 | 新增: assert.equal(messages.filter((m) => m.type === "input").length, 0); | |
| 200 | 新增: release(); | |
| 201 | 新增: await poll(() => messages.filter((m) => m.type === "input").length === 2); | |
| 202 | 新增: assert.deepEqual( | |
| 203 | 新增: messages.filter((m) => m.type === "input").map((m) => m.data), | |
| 204 | 新增: [ | |
| 205 | 新增: "\x1b[200~'/home/cage/.local/share/cage/attachments/image-test.png' \x1b[201~", | |
| 206 | 新增: "\r", | |
| 207 | 新增: ], | |
| 208 | 新增: ); | |
| 209 | 新增: assert.equal(received[2].target, "terminal"); | |
| 210 | 新增: fail = true; | |
| 211 | 新增: await imageEvent(".terminal-host", "drop"); | |
| 212 | 新增: await poll(() => received.length === 4); | |
| 213 | 新增: await page.keyboard.press("Enter"); | |
| 214 | 新增: release(); | |
| 215 | 新增: await page.getByRole("status").filter({ hasText: "图片传递失败" }).waitFor(); | |
| 216 | 新增: assert.equal( | |
| 217 | 新增: messages.filter((m) => m.type === "input").length, | |
| 218 | 新增: 2, | |
| 219 | 新增: "failed image cancels queued submit", | |
| 220 | 新增: ); | |
| 221 | 新增: assert.deepEqual(errors, []); | |
| 222 | 新增: console.log( | |
| 223 | 新增: "PASS: remote paste/drop PNG, image-before-Enter, unsupported files, local fields, real xterm bracketed path paste and failed-submit cancellation", | |
| 224 | 新增: ); | |
| 225 | 新增:} finally { | |
| 226 | 新增: await browser.close(); | |
| 227 | 新增:} | |
| @@ -0,0 +1,49 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import fs from "node:fs/promises"; | |
| 3 | 新增:import { fileURLToPath } from "node:url"; | |
| 4 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 新增: | |
| 6 | 新增:const output = new URL("../../docs/test-reports/2026-11-01-manual-region/", import.meta.url); | |
| 7 | 新增:await fs.mkdir(output, { recursive: true }); | |
| 8 | 新增:const { browser, page, state, errors } = await createWorkbench(); | |
| 9 | 新增:try { | |
| 10 | 新增: state.settings.auto_language = true; | |
| 11 | 新增: await page.reload(); | |
| 12 | 新增: await page.route("**/api/settings/probe", (route) => route.fulfill({ | |
| 13 | 新增: status: 400, | |
| 14 | 新增: json: { error: "已测得出口 IP,但位置查询均失败;未使用直连回退" }, | |
| 15 | 新增: })); | |
| 16 | 新增: const policy = structuredClone(state.settings.exit_policy); | |
| 17 | 新增: await page.getByRole("button", { name: /^设置/ }).click(); | |
| 18 | 新增: await page.getByRole("button", { name: "时区与语言", exact: true }).click(); | |
| 19 | 新增: await page.getByRole("button", { name: "现在检测", exact: true }).first().click(); | |
| 20 | 新增: await page.getByRole("alert").filter({ hasText: "位置查询均失败" }).waitFor(); | |
| 21 | 新增: await page.getByRole("button", { name: "手动设置时区和语言", exact: true }).click(); | |
| 22 | 新增: assert.equal(await page.getByRole("switch").nth(0).isChecked(), false); | |
| 23 | 新增: assert.equal(await page.getByRole("switch").nth(1).isChecked(), false); | |
| 24 | 新增: await page.getByLabel("系统时区", { exact: true }).fill("Asia/Tokyo"); | |
| 25 | 新增: await page.getByLabel("系统语言").selectOption("ja_JP.UTF-8"); | |
| 26 | 新增: await page.getByLabel("网页首选语言").selectOption("ja-JP"); | |
| 27 | 新增: await page.getByText("国家、城市限制仍须检测出口所在地。", { exact: false }).waitFor(); | |
| 28 | 新增: await page.screenshot({ path: fileURLToPath(new URL("manual-settings.png", output)) }); | |
| 29 | 新增: await page.getByRole("button", { name: "保存设置", exact: true }).click(); | |
| 30 | 新增: await page.getByRole("heading", { name: "时区与语言", exact: true }).waitFor({ state: "hidden" }); | |
| 31 | 新增: assert.equal(state.settings.auto_timezone, false); | |
| 32 | 新增: assert.equal(state.settings.auto_language, false); | |
| 33 | 新增: assert.equal(state.settings.timezone, "Asia/Tokyo"); | |
| 34 | 新增: assert.equal(state.settings.locale, "ja_JP.UTF-8"); | |
| 35 | 新增: assert.equal(state.settings.browser_language, "ja-JP"); | |
| 36 | 新增: assert.deepEqual(state.settings.exit_policy, policy); | |
| 37 | 新增: await page.reload(); | |
| 38 | 新增: await page.getByRole("button", { name: /^设置/ }).click(); | |
| 39 | 新增: await page.getByRole("button", { name: "时区与语言", exact: true }).click(); | |
| 40 | 新增: assert.equal(await page.getByLabel("系统时区", { exact: true }).inputValue(), "Asia/Tokyo"); | |
| 41 | 新增: assert.equal(await page.getByLabel("系统语言").inputValue(), "ja_JP.UTF-8"); | |
| 42 | 新增: assert.equal(await page.getByLabel("网页首选语言").inputValue(), "ja-JP"); | |
| 43 | 新增: assert.equal(await page.getByRole("switch").nth(0).isChecked(), false); | |
| 44 | 新增: assert.equal(await page.getByRole("switch").nth(1).isChecked(), false); | |
| 45 | 新增: assert.deepEqual(errors, []); | |
| 46 | 新增: console.log(JSON.stringify({ passed: true, checks: ["failed lookup recovery", "manual fields editable", "manual values saved and reloaded", "exit policy preserved"] })); | |
| 47 | 新增:} finally { | |
| 48 | 新增: await browser.close(); | |
| 49 | 新增:} | |
| @@ -6,7 +6,7 @@ const require = createRequire(import.meta.url); | ||
| 6 | 6 | const { chromium } = require( |
| 7 | 7 | process.env.CAGE_PLAYWRIGHT_MODULE || "playwright", |
| 8 | 8 | ); |
| 9 | 删除:const browser = await chromium.launch({ headless: true }); | |
| 9 | 新增:const browser = await chromium.launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH }); | |
| 10 | 10 | const page = await browser.newPage(); |
| 11 | 11 | const errors = []; |
| 12 | 12 | page.on("pageerror", (error) => errors.push(error.message)); |
| @@ -0,0 +1,279 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import fs from "node:fs/promises"; | |
| 3 | 新增:import { fileURLToPath } from "node:url"; | |
| 4 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 新增:import { | |
| 6 | 新增: themeDocument, | |
| 7 | 新增: parseThemeDocument, | |
| 8 | 新增: sameTheme, | |
| 9 | 新增:} from "../src/appearance-state.mjs"; | |
| 10 | 新增:const output = fileURLToPath( | |
| 11 | 新增: new URL("../../docs/test-reports/2026-11-02-themes/", import.meta.url), | |
| 12 | 新增:); | |
| 13 | 新增:await fs.mkdir(output, { recursive: true }); | |
| 14 | 新增:let imported = "", | |
| 15 | 新增: exported, | |
| 16 | 新增: cancelExport = false; | |
| 17 | 新增:const { browser, page, state, errors } = await createWorkbench({ | |
| 18 | 新增: nativeRequest: (body) => { | |
| 19 | 新增: if (body.action === "importTheme") return imported; | |
| 20 | 新增: if (body.action === "exportTheme") { | |
| 21 | 新增: exported = body; | |
| 22 | 新增: return !cancelExport; | |
| 23 | 新增: } | |
| 24 | 新增: return true; | |
| 25 | 新增: }, | |
| 26 | 新增:}); | |
| 27 | 新增:const checks = []; | |
| 28 | 新增:const open = async () => { | |
| 29 | 新增: await page.getByRole("button", { name: /^设置/ }).click(); | |
| 30 | 新增: await page.getByRole("button", { name: "外观", exact: true }).click(); | |
| 31 | 新增: await page.getByRole("heading", { name: "外观", exact: true }).waitFor(); | |
| 32 | 新增: await page.locator(".appearance-fields").evaluate((el) => { | |
| 33 | 新增: if (el.disabled) throw new Error("appearance still loading"); | |
| 34 | 新增: }); | |
| 35 | 新增:}; | |
| 36 | 新增:const saved = async () => { | |
| 37 | 新增: await page | |
| 38 | 新增: .locator(".appearance-save-state") | |
| 39 | 新增: .filter({ hasText: /更改自动保存|已同步 Codex 外观/ }) | |
| 40 | 新增: .waitFor(); | |
| 41 | 新增:}; | |
| 42 | 新增:const edit = async (label, value) => { | |
| 43 | 新增: const input = page.getByLabel(label, { exact: true }); | |
| 44 | 新增: await input.fill(value); | |
| 45 | 新增: await input.press("Enter"); | |
| 46 | 新增: await saved(); | |
| 47 | 新增:}; | |
| 48 | 新增:const light = () => page.getByRole("region", { name: "浅色主题", exact: true }); | |
| 49 | 新增:const color = (key) => | |
| 50 | 新增: page.evaluate( | |
| 51 | 新增: (key) => getComputedStyle(document.documentElement).getPropertyValue(key), | |
| 52 | 新增: key, | |
| 53 | 新增: ); | |
| 54 | 新增:const shot = async (name) => { | |
| 55 | 新增: await page.screenshot({ | |
| 56 | 新增: path: output + name + ".png", | |
| 57 | 新增: animations: "disabled", | |
| 58 | 新增: }); | |
| 59 | 新增:}; | |
| 60 | 新增:try { | |
| 61 | 新增: await page.emulateMedia({ colorScheme: "light" }); | |
| 62 | 新增: await open(); | |
| 63 | 新增: await shot("themes-light"); | |
| 64 | 新增: await edit("浅色主题背景", "#fdf6e3"); | |
| 65 | 新增: await light().getByRole("button", { name: "自定义", exact: true }).click(); | |
| 66 | 新增: await light().getByText("界面与层级", { exact: true }).click(); | |
| 67 | 新增: await edit("浅色主题面板背景", "#e8dec3"); | |
| 68 | 新增: assert.equal(await color("--chrome"), "#e8dec3"); | |
| 69 | 新增: await light().getByText("按钮与交互", { exact: true }).click(); | |
| 70 | 新增: await edit("浅色主题主按钮背景", "#426b52"); | |
| 71 | 新增: await edit("浅色主题主按钮文字", "#ffffff"); | |
| 72 | 新增: assert.equal(await color("--button"), "#426b52"); | |
| 73 | 新增: await light().getByText("终端", { exact: true }).click(); | |
| 74 | 新增: await edit("浅色主题终端背景", "#101820"); | |
| 75 | 新增: await light().getByText("终端 ANSI 配色", { exact: true }).click(); | |
| 76 | 新增: await edit("浅色主题终端红色", "#f08080"); | |
| 77 | 新增: await shot("themes-colors"); | |
| 78 | 新增: const originalChrome = state.appearance.lightTheme.colors.chrome; | |
| 79 | 新增: await page.getByLabel("浅色主题面板背景", { exact: true }).fill("#oops"); | |
| 80 | 新增: await page.getByLabel("浅色主题面板背景", { exact: true }).press("Tab"); | |
| 81 | 新增: assert.equal(state.appearance.lightTheme.colors.chrome, originalChrome); | |
| 82 | 新增: await page.getByLabel("浅色主题面板背景", { exact: true }).press("Escape"); | |
| 83 | 新增: checks.push("基础色和元素色即时生效、终端和 ANSI 独立覆盖、无效 HEX 不提交"); | |
| 84 | 新增: await page.getByLabel("主题名称", { exact: true }).fill("森林日光"); | |
| 85 | 新增: await page.getByRole("button", { name: "另存为主题", exact: true }).click(); | |
| 86 | 新增: await page.getByRole("status").filter({ hasText: "主题已保存" }).waitFor(); | |
| 87 | 新增: assert.equal(state.appearance.customThemes.length, 1); | |
| 88 | 新增: const savedTheme = structuredClone(state.appearance.customThemes[0]); | |
| 89 | 新增: await edit("浅色主题背景", "#eeeeee"); | |
| 90 | 新增: await page | |
| 91 | 新增: .getByRole("button", { name: "恢复已保存配色", exact: true }) | |
| 92 | 新增: .click(); | |
| 93 | 新增: await saved(); | |
| 94 | 新增: assert.equal(state.appearance.lightTheme.surface, "#fdf6e3"); | |
| 95 | 新增: await page.getByRole("button", { name: "导出主题", exact: true }).click(); | |
| 96 | 新增: await page.getByRole("status").filter({ hasText: "主题已导出" }).waitFor(); | |
| 97 | 新增: assert.ok(sameTheme(parseThemeDocument(exported.text), savedTheme)); | |
| 98 | 新增: assert.equal(exported.filename, "森林日光.cage-theme.json"); | |
| 99 | 新增: cancelExport = true; | |
| 100 | 新增: await page.getByRole("button", { name: "导出主题", exact: true }).click(); | |
| 101 | 新增: await page.waitForFunction( | |
| 102 | 新增: () => | |
| 103 | 新增: !Array.from(document.querySelectorAll("button")).find( | |
| 104 | 新增: (button) => button.textContent === "导出主题", | |
| 105 | 新增: )?.disabled, | |
| 106 | 新增: ); | |
| 107 | 新增: assert.equal( | |
| 108 | 新增: await page.getByRole("status").filter({ hasText: "主题已导出" }).count(), | |
| 109 | 新增: 0, | |
| 110 | 新增: ); | |
| 111 | 新增: cancelExport = false; | |
| 112 | 新增: const original = JSON.stringify(state.appearance); | |
| 113 | 新增: imported = ""; | |
| 114 | 新增: await page.getByRole("button", { name: "导入主题", exact: true }).click(); | |
| 115 | 新增: assert.equal(JSON.stringify(state.appearance), original); | |
| 116 | 新增: imported = '{"format":"cage-theme","version":2}'; | |
| 117 | 新增: await page.getByRole("button", { name: "导入主题", exact: true }).click(); | |
| 118 | 新增: await page | |
| 119 | 新增: .getByRole("alert") | |
| 120 | 新增: .filter({ hasText: "不支持的主题格式或版本" }) | |
| 121 | 新增: .waitFor(); | |
| 122 | 新增: assert.equal(JSON.stringify(state.appearance), original); | |
| 123 | 新增: imported = exported.text; | |
| 124 | 新增: await page.getByRole("button", { name: "导入主题", exact: true }).click(); | |
| 125 | 新增: await page | |
| 126 | 新增: .getByRole("status") | |
| 127 | 新增: .filter({ hasText: "主题已导入并应用" }) | |
| 128 | 新增: .waitFor(); | |
| 129 | 新增: assert.equal(state.appearance.customThemes.length, 2); | |
| 130 | 新增: assert.ok(sameTheme(state.appearance, savedTheme)); | |
| 131 | 新增: checks.push( | |
| 132 | 新增: "命名保存、切换还原、原生导出内容、同名导入不覆盖、取消和无效文件保留设置", | |
| 133 | 新增: ); | |
| 134 | 新增: const second = state.appearance.customThemes[1]; | |
| 135 | 新增: await edit("浅色主题背景", "#f5efdd"); | |
| 136 | 新增: await page.getByLabel("主题名称", { exact: true }).fill("森林日光 II"); | |
| 137 | 新增: await page.getByRole("button", { name: "更新此主题", exact: true }).click(); | |
| 138 | 新增: await page.getByRole("status").filter({ hasText: "主题已保存" }).waitFor(); | |
| 139 | 新增: assert.equal(state.appearance.customThemes[1].id, second.id); | |
| 140 | 新增: assert.equal(state.appearance.customThemes[1].name, "森林日光 II"); | |
| 141 | 新增: assert.equal(state.appearance.customThemes[0].name, "森林日光"); | |
| 142 | 新增: state.failAppearance = true; | |
| 143 | 新增: await page.getByLabel("浅色主题背景", { exact: true }).fill("#fafafa"); | |
| 144 | 新增: await page.getByLabel("浅色主题背景", { exact: true }).press("Enter"); | |
| 145 | 新增: await page | |
| 146 | 新增: .getByRole("alert") | |
| 147 | 新增: .filter({ hasText: "外观设置未能保存" }) | |
| 148 | 新增: .waitFor(); | |
| 149 | 新增: assert.equal(await color("--paper"), "#fafafa"); | |
| 150 | 新增: assert.equal(state.appearance.lightTheme.surface, "#f5efdd"); | |
| 151 | 新增: state.failAppearance = false; | |
| 152 | 新增: await page.getByRole("button", { name: "重试保存", exact: true }).click(); | |
| 153 | 新增: await saved(); | |
| 154 | 新增: await page.reload(); | |
| 155 | 新增: await open(); | |
| 156 | 新增: assert.equal(state.appearance.customThemes.length, 2); | |
| 157 | 新增: assert.equal( | |
| 158 | 新增: await page.getByLabel("浅色主题背景", { exact: true }).inputValue(), | |
| 159 | 新增: "#fafafa", | |
| 160 | 新增: ); | |
| 161 | 新增: await page | |
| 162 | 新增: .getByLabel("已保存的主题", { exact: true }) | |
| 163 | 新增: .selectOption(second.id); | |
| 164 | 新增: await saved(); | |
| 165 | 新增: assert.equal( | |
| 166 | 新增: await page.getByLabel("浅色主题背景", { exact: true }).inputValue(), | |
| 167 | 新增: "#f5efdd", | |
| 168 | 新增: ); | |
| 169 | 新增: // Codex sync must preserve the user's library. | |
| 170 | 新增: await page | |
| 171 | 新增: .getByRole("button", { name: "从本机 Codex 同步", exact: true }) | |
| 172 | 新增: .click(); | |
| 173 | 新增: await saved(); | |
| 174 | 新增: assert.equal(state.appearance.customThemes.length, 2); | |
| 175 | 新增: await page | |
| 176 | 新增: .getByLabel("已保存的主题", { exact: true }) | |
| 177 | 新增: .selectOption(second.id); | |
| 178 | 新增: await saved(); | |
| 179 | 新增: page.once("dialog", (dialog) => dialog.dismiss()); | |
| 180 | 新增: await page.getByRole("button", { name: "删除", exact: true }).click(); | |
| 181 | 新增: assert.equal(state.appearance.customThemes.length, 2); | |
| 182 | 新增: page.once("dialog", (dialog) => dialog.accept()); | |
| 183 | 新增: await page.getByRole("button", { name: "删除", exact: true }).click(); | |
| 184 | 新增: await saved(); | |
| 185 | 新增: assert.equal(state.appearance.customThemes.length, 1); | |
| 186 | 新增: assert.equal(state.appearance.lightTheme.surface, "#f5efdd"); | |
| 187 | 新增: checks.push( | |
| 188 | 新增: "更新主题、失败保留预览并重试、刷新读回、Codex 同步保留主题库、删除确认和保留当前配色", | |
| 189 | 新增: ); | |
| 190 | 新增: // Exercise the actual browser file input and download fallback as well. | |
| 191 | 新增: await page.evaluate(() => { | |
| 192 | 新增: delete window.webkit; | |
| 193 | 新增: }); | |
| 194 | 新增: const downloadEvent = page.waitForEvent("download"); | |
| 195 | 新增: await page.getByRole("button", { name: "导出主题", exact: true }).click(); | |
| 196 | 新增: const download = await downloadEvent; | |
| 197 | 新增: const path = output + "browser-export.cage-theme.json"; | |
| 198 | 新增: await download.saveAs(path); | |
| 199 | 新增: const data = parseThemeDocument(await fs.readFile(path, "utf8")); | |
| 200 | 新增: assert.ok(sameTheme(data, state.appearance)); | |
| 201 | 新增: await page.getByLabel("选择主题文件", { exact: true }).setInputFiles(path); | |
| 202 | 新增: await page | |
| 203 | 新增: .getByRole("status") | |
| 204 | 新增: .filter({ hasText: "主题已导入并应用" }) | |
| 205 | 新增: .waitFor(); | |
| 206 | 新增: assert.equal(state.appearance.customThemes.length, 2); | |
| 207 | 新增: await page.getByRole("button", { name: "深色", exact: true }).click(); | |
| 208 | 新增: await saved(); | |
| 209 | 新增: await page.locator(".settings-content").evaluate((el) => el.scrollTo(0, 0)); | |
| 210 | 新增: await shot("themes-dark"); | |
| 211 | 新增: await page.setViewportSize({ width: 820, height: 558 }); | |
| 212 | 新增: await shot("themes-minimum"); | |
| 213 | 新增: assert.equal( | |
| 214 | 新增: await page.evaluate( | |
| 215 | 新增: () => document.documentElement.scrollWidth > innerWidth, | |
| 216 | 新增: ), | |
| 217 | 新增: false, | |
| 218 | 新增: ); | |
| 219 | 新增: await light().getByRole("button", { name: "自定义", exact: true }).click(); | |
| 220 | 新增: await light().getByText("界面与层级", { exact: true }).click(); | |
| 221 | 新增: const row = page.getByLabel("浅色主题面板背景", { exact: true }); | |
| 222 | 新增: await row.scrollIntoViewIfNeeded(); | |
| 223 | 新增: await shot("themes-minimum-colors"); | |
| 224 | 新增: const bounds = await row.boundingBox(); | |
| 225 | 新增: assert.ok(bounds.x + bounds.width <= 820); | |
| 226 | 新增: await page.getByRole("button", { name: "浅色", exact: true }).click(); | |
| 227 | 新增: await saved(); | |
| 228 | 新增: await page.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 229 | 新增: await page | |
| 230 | 新增: .getByRole("button", { name: "启动 Cage 环境", exact: true }) | |
| 231 | 新增: .click(); | |
| 232 | 新增: await page | |
| 233 | 新增: .getByRole("button", { name: "新建终端", exact: true }) | |
| 234 | 新增: .first() | |
| 235 | 新增: .click(); | |
| 236 | 新增: await page.getByRole("tab", { name: "终端 1", exact: true }).waitFor(); | |
| 237 | 新增: await page.waitForFunction(() => | |
| 238 | 新增: [...document.querySelectorAll(".xterm-scrollable-element")].some( | |
| 239 | 新增: (el) => getComputedStyle(el).backgroundColor === "rgb(16, 24, 32)", | |
| 240 | 新增: ), | |
| 241 | 新增: ); | |
| 242 | 新增: await shot("themes-terminal"); | |
| 243 | 新增: const connections = state.terminalConnections; | |
| 244 | 新增: await open(); | |
| 245 | 新增: await light().getByRole("button", { name: "自定义", exact: true }).click(); | |
| 246 | 新增: await light().getByText("终端", { exact: true }).click(); | |
| 247 | 新增: await edit("浅色主题终端背景", "#202830"); | |
| 248 | 新增: await page.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 249 | 新增: await page.waitForFunction(() => | |
| 250 | 新增: [...document.querySelectorAll(".xterm-scrollable-element")].some( | |
| 251 | 新增: (el) => getComputedStyle(el).backgroundColor === "rgb(32, 40, 48)", | |
| 252 | 新增: ), | |
| 253 | 新增: ); | |
| 254 | 新增: assert.equal(state.terminalConnections, connections); | |
| 255 | 新增: checks.push( | |
| 256 | 新增: "浏览器文件上传与下载往返、浅深色与 820px 无溢出、已有终端实时改色且不重连", | |
| 257 | 新增: ); | |
| 258 | 新增: assert.deepEqual(errors, []); | |
| 259 | 新增: assert.ok( | |
| 260 | 新增: !state.requests.some( | |
| 261 | 新增: (request) => request.path === "/settings" && request.method === "POST", | |
| 262 | 新增: ), | |
| 263 | 新增: ); | |
| 264 | 新增: await fs.writeFile( | |
| 265 | 新增: output + "result.json", | |
| 266 | 新增: JSON.stringify( | |
| 267 | 新增: { | |
| 268 | 新增: passed: true, | |
| 269 | 新增: checks, | |
| 270 | 新增: scope: "真实前端与 xterm,隔离控制接口;Go 写盘与原生编译另验", | |
| 271 | 新增: }, | |
| 272 | 新增: null, | |
| 273 | 新增: 2, | |
| 274 | 新增: ), | |
| 275 | 新增: ); | |
| 276 | 新增: console.log(JSON.stringify({ passed: true, checks })); | |
| 277 | 新增:} finally { | |
| 278 | 新增: await browser.close(); | |
| 279 | 新增:} | |
| @@ -11,10 +11,10 @@ export async function createWorkbench({ | ||
| 11 | 11 | nativeRequest, |
| 12 | 12 | startupFailure = false, |
| 13 | 13 | } = {}) { |
| 14 | 删除: const { chromium } = require( | |
| 14 | 新增: const engines = require( | |
| 15 | 15 | process.env.CAGE_PLAYWRIGHT_MODULE || "playwright", |
| 16 | 16 | ); |
| 17 | 删除: const browser = await chromium.launch({ headless: true }); | |
| 17 | 新增: const browser = await engines[process.env.CAGE_TEST_BROWSER || "chromium"].launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH }); | |
| 18 | 18 | const context = await browser.newContext({ viewport, recordVideo }); |
| 19 | 19 | const page = await context.newPage(); |
| 20 | 20 | const errors = []; |
| @@ -50,6 +50,9 @@ export async function createWorkbench({ | ||
| 50 | 50 | saves: [], |
| 51 | 51 | requests: [], |
| 52 | 52 | terminalConnections: 0, |
| 53 | 新增: account: { exists: true, unlocked: true, username: "林间工作室", avatar: "" }, | |
| 54 | 新增: accountPassword: "fixture-password", | |
| 55 | 新增: failAccountSave: false, | |
| 53 | 56 | settings: { |
| 54 | 57 | workspace: "/Users/shihao/.claude-cage-workspace", |
| 55 | 58 | browser_home_url: "https://www.bing.com/", |
| @@ -107,7 +110,41 @@ export async function createWorkbench({ | ||
| 107 | 110 | const request = route.request(); |
| 108 | 111 | const path = new URL(request.url()).pathname.replace("/api", ""); |
| 109 | 112 | const body = request.postDataJSON(); |
| 110 | 删除: state.requests.push({ path, method: request.method(), body }); | |
| 113 | 新增: state.requests.push({ path, method: request.method(), body: path.startsWith("/account") ? undefined : body }); | |
| 114 | 新增: const accountView = () => ({ ...state.account, background_running: state.status.vm_running }); | |
| 115 | 新增: if (path === "/account") return route.fulfill({ json: accountView() }); | |
| 116 | 新增: if (path.startsWith("/account/")) { | |
| 117 | 新增: const action = path.split("/").at(-1); | |
| 118 | 新增: if (!["create", "unlock"].includes(action) && !state.account.unlocked) return route.fulfill({ status: 423, body: "请先解锁 Cage" }); | |
| 119 | 新增: if (action === "create") { | |
| 120 | 新增: if (state.account.exists || !body.username?.trim() || body.password?.length < 8 || body.password !== body.confirm_password) return route.fulfill({ status: 400, body: "账户信息无效" }); | |
| 121 | 新增: Object.assign(state.account, { exists: true, unlocked: true, username: body.username.trim(), avatar: body.avatar || "" }); | |
| 122 | 新增: state.accountPassword = body.password; | |
| 123 | 新增: } else if (action === "unlock") { | |
| 124 | 新增: if (body.password !== state.accountPassword) return route.fulfill({ status: 400, body: "密码不正确" }); | |
| 125 | 新增: state.account.unlocked = true; | |
| 126 | 新增: state.account.require_authentication = false; | |
| 127 | 新增: } else if (action === "profile") { | |
| 128 | 新增: if (state.failAccountSave) return route.fulfill({ status: 400, body: "资料未能保存,请重试" }); | |
| 129 | 新增: Object.assign(state.account, { username: body.username.trim(), avatar: body.avatar }); | |
| 130 | 新增: } else if (action === "password") { | |
| 131 | 新增: if (body.old_password !== state.accountPassword) return route.fulfill({ status: 400, body: "密码不正确" }); | |
| 132 | 新增: if (body.password?.length < 8 || body.password !== body.confirm_password) return route.fulfill({ status: 400, body: "新密码无效" }); | |
| 133 | 新增: state.accountPassword = body.password; | |
| 134 | 新增: } else if (action === "lock") { state.account.unlocked = false; state.account.require_authentication = true; } | |
| 135 | 新增: else if (action === "suspend") state.account.unlocked = false; | |
| 136 | 新增: else if (action === "logout") { | |
| 137 | 新增: Object.assign(state.status, { ready: false, vm_running: false }); | |
| 138 | 新增: state.account.unlocked = false; | |
| 139 | 新增: state.account.devices = {}; | |
| 140 | 新增: state.account.require_authentication = true; | |
| 141 | 新增: state.terminals = []; | |
| 142 | 新增: state.status.job = { id: "account-logout", kind: "stop", running: false }; | |
| 143 | 新增: return route.fulfill({ json: state.status.job }); | |
| 144 | 新增: } | |
| 145 | 新增: return route.fulfill({ json: accountView() }); | |
| 146 | 新增: } | |
| 147 | 新增: if (!state.account.unlocked && !["/session", "/launch", "/appearance"].includes(path)) return route.fulfill({ status: 423, body: "Cage 已锁定,请先登录" }); | |
| 111 | 148 | if (startupFailure && path === "/status") return route.fulfill({ status: 503, body: "测试:控制服务暂不可用" }); |
| 112 | 149 | let result = {}; |
| 113 | 150 | if (path === "/favorites") { |
| @@ -0,0 +1,324 @@ | ||
| 1 | 新增:.account-gate { | |
| 2 | 新增: height: 100dvh; | |
| 3 | 新增: display: flex; | |
| 4 | 新增: flex-direction: column; | |
| 5 | 新增: align-items: center; | |
| 6 | 新增: background: var(--paper); | |
| 7 | 新增: color: var(--ink); | |
| 8 | 新增: padding: 24px; | |
| 9 | 新增: overflow: auto; | |
| 10 | 新增:} | |
| 11 | 新增:.account-brand { | |
| 12 | 新增: align-self: flex-start; | |
| 13 | 新增: display: flex; | |
| 14 | 新增: align-items: center; | |
| 15 | 新增: gap: 10px; | |
| 16 | 新增: font-size: 18px; | |
| 17 | 新增: font-weight: 650; | |
| 18 | 新增:} | |
| 19 | 新增:.account-brand img { | |
| 20 | 新增: width: 28px; | |
| 21 | 新增: height: 28px; | |
| 22 | 新增:} | |
| 23 | 新增:.account-entry { | |
| 24 | 新增: width: min(100%, 380px); | |
| 25 | 新增: margin: auto; | |
| 26 | 新增: padding: 44px 0; | |
| 27 | 新增: text-align: center; | |
| 28 | 新增:} | |
| 29 | 新增:.account-entry h1 { | |
| 30 | 新增: font-size: 25px; | |
| 31 | 新增: font-weight: 600; | |
| 32 | 新增: line-height: 1.4; | |
| 33 | 新增: margin: 20px 0 10px; | |
| 34 | 新增: overflow-wrap: anywhere; | |
| 35 | 新增:} | |
| 36 | 新增:.account-entry-intro { | |
| 37 | 新增: color: var(--muted); | |
| 38 | 新增: line-height: 1.6; | |
| 39 | 新增: margin: 0 0 24px; | |
| 40 | 新增: font-size: 14px; | |
| 41 | 新增:} | |
| 42 | 新增:.account-welcome-logo { | |
| 43 | 新增: width: 58px; | |
| 44 | 新增: height: 58px; | |
| 45 | 新增:} | |
| 46 | 新增:.account-entry fieldset, | |
| 47 | 新增:.account-settings fieldset { | |
| 48 | 新增: border: 0; | |
| 49 | 新增: margin: 0; | |
| 50 | 新增: padding: 0; | |
| 51 | 新增: min-width: 0; | |
| 52 | 新增: display: flex; | |
| 53 | 新增: flex-direction: column; | |
| 54 | 新增: gap: 18px; | |
| 55 | 新增:} | |
| 56 | 新增:.account-field { | |
| 57 | 新增: display: flex; | |
| 58 | 新增: flex-direction: column; | |
| 59 | 新增: align-items: stretch; | |
| 60 | 新增: gap: 8px; | |
| 61 | 新增: font-size: 13px; | |
| 62 | 新增: text-align: left; | |
| 63 | 新增:} | |
| 64 | 新增:.account-field input { | |
| 65 | 新增: width: 100%; | |
| 66 | 新增: min-width: 0; | |
| 67 | 新增: font: inherit; | |
| 68 | 新增: font-size: 14px; | |
| 69 | 新增: padding: 11px 12px; | |
| 70 | 新增: border: 1px solid var(--line); | |
| 71 | 新增: border-radius: 9px; | |
| 72 | 新增: color: var(--ink); | |
| 73 | 新增: background: var(--paper); | |
| 74 | 新增:} | |
| 75 | 新增:.account-field input:focus { | |
| 76 | 新增: outline: 2px solid var(--accent); | |
| 77 | 新增: outline-offset: 2px; | |
| 78 | 新增:} | |
| 79 | 新增:.password-input { | |
| 80 | 新增: display: flex; | |
| 81 | 新增: position: relative; | |
| 82 | 新增: width: 100%; | |
| 83 | 新增:} | |
| 84 | 新增:.password-input input { | |
| 85 | 新增: padding-right: 42px; | |
| 86 | 新增:} | |
| 87 | 新增:.password-input > button { | |
| 88 | 新增: position: absolute; | |
| 89 | 新增: right: 5px; | |
| 90 | 新增: top: 50%; | |
| 91 | 新增: transform: translateY(-50%); | |
| 92 | 新增:} | |
| 93 | 新增:.account-submit { | |
| 94 | 新增: width: 100%; | |
| 95 | 新增: justify-content: center; | |
| 96 | 新增: min-height: 43px; | |
| 97 | 新增: margin-top: 4px; | |
| 98 | 新增:} | |
| 99 | 新增:.account-local-note { | |
| 100 | 新增: display: flex; | |
| 101 | 新增: align-items: center; | |
| 102 | 新增: justify-content: center; | |
| 103 | 新增: gap: 6px; | |
| 104 | 新增: color: var(--muted); | |
| 105 | 新增: font-size: 12px; | |
| 106 | 新增: margin: 24px 0 8px; | |
| 107 | 新增:} | |
| 108 | 新增:.account-recovery-note { | |
| 109 | 新增: font-size: 12px; | |
| 110 | 新增: line-height: 1.6; | |
| 111 | 新增: color: var(--muted); | |
| 112 | 新增: margin: 0; | |
| 113 | 新增:} | |
| 114 | 新增:.account-error { | |
| 115 | 新增: color: var(--danger, #b33d36); | |
| 116 | 新增: font-size: 13px; | |
| 117 | 新增: line-height: 1.6; | |
| 118 | 新增: margin: 0; | |
| 119 | 新增:} | |
| 120 | 新增:.account-background { | |
| 121 | 新增: display: flex; | |
| 122 | 新增: align-items: center; | |
| 123 | 新增: justify-content: center; | |
| 124 | 新增: gap: 8px; | |
| 125 | 新增: margin: 0 0 24px; | |
| 126 | 新增: font-size: 12px; | |
| 127 | 新增: color: var(--muted); | |
| 128 | 新增:} | |
| 129 | 新增:.account-background i { | |
| 130 | 新增: height: 6px; | |
| 131 | 新增: width: 6px; | |
| 132 | 新增: border-radius: 50%; | |
| 133 | 新增: background: #4e8762; | |
| 134 | 新增:} | |
| 135 | 新增:.account-exit-app { | |
| 136 | 新增: margin-top: 12px; | |
| 137 | 新增: flex-shrink: 0; | |
| 138 | 新增:} | |
| 139 | 新增:.account-avatar { | |
| 140 | 新增: width: 32px; | |
| 141 | 新增: height: 32px; | |
| 142 | 新增: flex-shrink: 0; | |
| 143 | 新增: display: inline-flex; | |
| 144 | 新增: align-items: center; | |
| 145 | 新增: justify-content: center; | |
| 146 | 新增: overflow: hidden; | |
| 147 | 新增: border-radius: 50%; | |
| 148 | 新增: background: linear-gradient(140deg, #e5ba9c, #c98360); | |
| 149 | 新增: color: #39281f; | |
| 150 | 新增: font-size: 14px; | |
| 151 | 新增: font-weight: 650; | |
| 152 | 新增: box-shadow: inset 0 0 0 1px #00000008; | |
| 153 | 新增:} | |
| 154 | 新增:.account-avatar.large { | |
| 155 | 新增: width: 64px; | |
| 156 | 新增: height: 64px; | |
| 157 | 新增: font-size: 26px; | |
| 158 | 新增:} | |
| 159 | 新增:.account-avatar img { | |
| 160 | 新增: width: 100%; | |
| 161 | 新增: height: 100%; | |
| 162 | 新增: object-fit: cover; | |
| 163 | 新增:} | |
| 164 | 新增:.account-menu-root { | |
| 165 | 新增: position: relative; | |
| 166 | 新增: flex: 1; | |
| 167 | 新增: min-width: 0; | |
| 168 | 新增:} | |
| 169 | 新增:.account-trigger { | |
| 170 | 新增: border: 0; | |
| 171 | 新增: background: transparent; | |
| 172 | 新增: width: 100%; | |
| 173 | 新增: display: flex; | |
| 174 | 新增: align-items: center; | |
| 175 | 新增: gap: 10px; | |
| 176 | 新增: padding: 8px; | |
| 177 | 新增: border-radius: 9px; | |
| 178 | 新增: color: var(--ink); | |
| 179 | 新增: text-align: left; | |
| 180 | 新增:} | |
| 181 | 新增:.account-trigger:hover, | |
| 182 | 新增:.account-trigger[aria-expanded="true"] { | |
| 183 | 新增: background: var(--selected); | |
| 184 | 新增:} | |
| 185 | 新增:.account-trigger-name { | |
| 186 | 新增: display: flex; | |
| 187 | 新增: flex: 1; | |
| 188 | 新增: min-width: 0; | |
| 189 | 新增: flex-direction: column; | |
| 190 | 新增: gap: 3px; | |
| 191 | 新增:} | |
| 192 | 新增:.account-trigger-name strong { | |
| 193 | 新增: font-size: 13px; | |
| 194 | 新增: font-weight: 550; | |
| 195 | 新增: overflow: hidden; | |
| 196 | 新增: white-space: nowrap; | |
| 197 | 新增: text-overflow: ellipsis; | |
| 198 | 新增:} | |
| 199 | 新增:.account-trigger-name small { | |
| 200 | 新增: font-size: 11px; | |
| 201 | 新增: color: var(--muted); | |
| 202 | 新增:} | |
| 203 | 新增:.account-menu { | |
| 204 | 新增: position: absolute; | |
| 205 | 新增: bottom: calc(100% + 8px); | |
| 206 | 新增: left: 0; | |
| 207 | 新增: width: 224px; | |
| 208 | 新增: max-width: calc(100vw - 32px); | |
| 209 | 新增: padding: 6px; | |
| 210 | 新增: border: 1px solid var(--line); | |
| 211 | 新增: border-radius: 12px; | |
| 212 | 新增: background: var(--paper); | |
| 213 | 新增: box-shadow: 0 8px 24px #00000012; | |
| 214 | 新增: z-index: 60; | |
| 215 | 新增:} | |
| 216 | 新增:.account-menu-label { | |
| 217 | 新增: padding: 8px 10px; | |
| 218 | 新增: font-size: 11px; | |
| 219 | 新增: color: var(--muted); | |
| 220 | 新增:} | |
| 221 | 新增:.account-menu > button { | |
| 222 | 新增: width: 100%; | |
| 223 | 新增: padding: 10px; | |
| 224 | 新增: border: 0; | |
| 225 | 新增: border-radius: 6px; | |
| 226 | 新增: display: flex; | |
| 227 | 新增: align-items: center; | |
| 228 | 新增: gap: 10px; | |
| 229 | 新增: text-align: left; | |
| 230 | 新增: background: transparent; | |
| 231 | 新增: color: var(--ink); | |
| 232 | 新增: font-size: 13px; | |
| 233 | 新增:} | |
| 234 | 新增:.account-menu > button:hover { | |
| 235 | 新增: background: var(--selected); | |
| 236 | 新增:} | |
| 237 | 新增:.account-menu small { | |
| 238 | 新增: margin-left: auto; | |
| 239 | 新增: color: var(--muted); | |
| 240 | 新增: font-size: 11px; | |
| 241 | 新增:} | |
| 242 | 新增:.account-menu-divider { | |
| 243 | 新增: border-top: 1px solid var(--line); | |
| 244 | 新增: margin: 5px 4px; | |
| 245 | 新增:} | |
| 246 | 新增:.account-settings { | |
| 247 | 新增: max-width: 560px; | |
| 248 | 新增:} | |
| 249 | 新增:.account-profile-heading { | |
| 250 | 新增: display: flex; | |
| 251 | 新增: align-items: center; | |
| 252 | 新增: gap: 20px; | |
| 253 | 新增: margin: 10px 0 4px; | |
| 254 | 新增:} | |
| 255 | 新增:.account-profile-heading .field-help { | |
| 256 | 新增: margin: 8px 0 0; | |
| 257 | 新增:} | |
| 258 | 新增:.account-settings form button.primary, | |
| 259 | 新增:.account-settings form button.quiet-button { | |
| 260 | 新增: align-self: flex-start; | |
| 261 | 新增:} | |
| 262 | 新增:.account-section-divider { | |
| 263 | 新增: margin: 32px 0; | |
| 264 | 新增: border-top: 1px solid var(--line); | |
| 265 | 新增:} | |
| 266 | 新增:.account-settings h4 { | |
| 267 | 新增: margin: 0; | |
| 268 | 新增: font-size: 15px; | |
| 269 | 新增: font-weight: 600; | |
| 270 | 新增:} | |
| 271 | 新增:.account-settings .field-help { | |
| 272 | 新增: line-height: 1.6; | |
| 273 | 新增:} | |
| 274 | 新增:.account-saved { | |
| 275 | 新增: display: flex; | |
| 276 | 新增: align-items: center; | |
| 277 | 新增: gap: 7px; | |
| 278 | 新增: font-size: 13px; | |
| 279 | 新增: color: var(--ink); | |
| 280 | 新增:} | |
| 281 | 新增:.account-settings > .account-error { | |
| 282 | 新增: margin-top: 18px; | |
| 283 | 新增:} | |
| 284 | 新增:.account-settings-note { | |
| 285 | 新增: display: flex; | |
| 286 | 新增: gap: 8px; | |
| 287 | 新增: align-items: flex-start; | |
| 288 | 新增: margin: 30px 0 0; | |
| 289 | 新增: color: var(--muted); | |
| 290 | 新增: font-size: 12px; | |
| 291 | 新增: line-height: 1.6; | |
| 292 | 新增:} | |
| 293 | 新增:@media (max-height: 650px) { | |
| 294 | 新增: .account-entry { | |
| 295 | 新增: padding: 20px 0; | |
| 296 | 新增: } | |
| 297 | 新增: .account-entry h1 { | |
| 298 | 新增: margin-top: 12px; | |
| 299 | 新增: font-size: 22px; | |
| 300 | 新增: } | |
| 301 | 新增: .account-entry fieldset { | |
| 302 | 新增: gap: 12px; | |
| 303 | 新增: } | |
| 304 | 新增: .account-local-note { | |
| 305 | 新增: margin-top: 18px; | |
| 306 | 新增: } | |
| 307 | 新增:} | |
| 308 | 新增: | |
| 309 | 新增:.account-device-settings { | |
| 310 | 新增: border-top: 1px solid var(--line); | |
| 311 | 新增: margin-top: 32px; | |
| 312 | 新增: padding-top: 24px; | |
| 313 | 新增:} | |
| 314 | 新增:.account-device-option { | |
| 315 | 新增: display: flex; | |
| 316 | 新增: align-items: flex-start; | |
| 317 | 新增: gap: 12px; | |
| 318 | 新增: margin: 20px 0; | |
| 319 | 新增: cursor: var(--control-cursor); | |
| 320 | 新增:} | |
| 321 | 新增:.account-device-option input { margin: 4px 0 0; accent-color: var(--accent); } | |
| 322 | 新增:.account-device-option span { display: flex; flex-direction: column; gap: 6px; } | |
| 323 | 新增:.account-device-option strong { font-size: 14px; font-weight: 550; } | |
| 324 | 新增:.account-device-option small { color: var(--muted); font-size: 12px; line-height: 1.6; } | |
| @@ -0,0 +1,675 @@ | ||
| 1 | 新增:import React, { | |
| 2 | 新增: createContext, | |
| 3 | 新增: useContext, | |
| 4 | 新增: useEffect, | |
| 5 | 新增: useId, | |
| 6 | 新增: useRef, | |
| 7 | 新增: useState, | |
| 8 | 新增:} from "react"; | |
| 9 | 新增:import { | |
| 10 | 新增: Camera, | |
| 11 | 新增: Check, | |
| 12 | 新增: ChevronUp, | |
| 13 | 新增: Eye, | |
| 14 | 新增: EyeOff, | |
| 15 | 新增: Fingerprint, | |
| 16 | 新增: LockKeyhole, | |
| 17 | 新增: LogOut, | |
| 18 | 新增: Settings2, | |
| 19 | 新增: UserRound, | |
| 20 | 新增:} from "lucide-react"; | |
| 21 | 新增:import { api, native, nativeAvailable } from "./api"; | |
| 22 | 新增:import logo from "./logo.png"; | |
| 23 | 新增:import "./account.css"; | |
| 24 | 新增: | |
| 25 | 新增:const AccountContext = createContext(null); | |
| 26 | 新增:export const useAccount = () => useContext(AccountContext); | |
| 27 | 新增: | |
| 28 | 新增:export function AccountProvider({ children }) { | |
| 29 | 新增: const [account, setAccount] = useState(null); | |
| 30 | 新增: const [error, setError] = useState(""); | |
| 31 | 新增: const [deviceSupport, setDeviceSupport] = useState(null); | |
| 32 | 新增: const [deviceNotice, setDeviceNotice] = useState(""); | |
| 33 | 新增: const sequence = useRef(0); | |
| 34 | 新增: const refresh = async () => { | |
| 35 | 新增: const current = ++sequence.current; | |
| 36 | 新增: try { | |
| 37 | 新增: const value = await api("/account"); | |
| 38 | 新增: if (sequence.current === current) { | |
| 39 | 新增: setAccount(value); | |
| 40 | 新增: setError(""); | |
| 41 | 新增: } | |
| 42 | 新增: return value; | |
| 43 | 新增: } catch (e) { | |
| 44 | 新增: if (sequence.current === current) setError(e.message); | |
| 45 | 新增: throw e; | |
| 46 | 新增: } | |
| 47 | 新增: }; | |
| 48 | 新增: const act = async (action, input = {}) => { | |
| 49 | 新增: const current = ++sequence.current; | |
| 50 | 新增: const value = await api(`/account/${action}`, input); | |
| 51 | 新增: if (action !== "logout" && sequence.current === current) setAccount(value); | |
| 52 | 新增: return value; | |
| 53 | 新增: }; | |
| 54 | 新增: useEffect(() => { | |
| 55 | 新增: if (!account || deviceSupport !== null) return; | |
| 56 | 新增: if (!nativeAvailable()) { setDeviceSupport({ supported: false }); return; } | |
| 57 | 新增: let live = true; | |
| 58 | 新增: native("accountDevice", { operation: "status" }) | |
| 59 | 新增: .then((value) => { if (live) setDeviceSupport(value || { supported: false }); }) | |
| 60 | 新增: .catch(() => { if (live) setDeviceSupport({ supported: false }); }); | |
| 61 | 新增: return () => { live = false; }; | |
| 62 | 新增: }, [Boolean(account), deviceSupport]); | |
| 63 | 新增: const deviceAction = async (operation, kind) => { | |
| 64 | 新增: await native("accountDevice", { operation, kind }); | |
| 65 | 新增: return refresh(); | |
| 66 | 新增: }; | |
| 67 | 新增: useEffect(() => { | |
| 68 | 新增: let live = true, | |
| 69 | 新增: timer; | |
| 70 | 新增: const poll = async () => { | |
| 71 | 新增: try { | |
| 72 | 新增: await refresh(); | |
| 73 | 新增: } catch { | |
| 74 | 新增: /* Keep the last state while disconnected. */ | |
| 75 | 新增: } | |
| 76 | 新增: if (live) timer = setTimeout(poll, document.hidden ? 10000 : 2500); | |
| 77 | 新增: }; | |
| 78 | 新增: const start = async () => { | |
| 79 | 新增: try { | |
| 80 | 新增: if (location.hash) { | |
| 81 | 新增: await api("/session", { token: location.hash.slice(1) }); | |
| 82 | 新增: history.replaceState(null, "", location.pathname); | |
| 83 | 新增: } | |
| 84 | 新增: window.dispatchEvent(new Event("cage-session-ready")); | |
| 85 | 新增: if (live) await poll(); | |
| 86 | 新增: } catch (e) { | |
| 87 | 新增: if (live) setError(e.message); | |
| 88 | 新增: } | |
| 89 | 新增: }; | |
| 90 | 新增: const locked = () => { | |
| 91 | 新增: setAccount((previous) => | |
| 92 | 新增: previous ? { ...previous, unlocked: false } : previous, | |
| 93 | 新增: ); | |
| 94 | 新增: refresh().catch(() => {}); | |
| 95 | 新增: }; | |
| 96 | 新增: start(); | |
| 97 | 新增: window.addEventListener("cage-account-locked", locked); | |
| 98 | 新增: return () => { | |
| 99 | 新增: live = false; | |
| 100 | 新增: sequence.current++; | |
| 101 | 新增: clearTimeout(timer); | |
| 102 | 新增: window.removeEventListener("cage-account-locked", locked); | |
| 103 | 新增: }; | |
| 104 | 新增: }, []); | |
| 105 | 新增: return ( | |
| 106 | 新增: <AccountContext.Provider value={{ account, error, refresh, act, deviceSupport, deviceAction, deviceNotice, setDeviceNotice }}> | |
| 107 | 新增: {children} | |
| 108 | 新增: </AccountContext.Provider> | |
| 109 | 新增: ); | |
| 110 | 新增:} | |
| 111 | 新增: | |
| 112 | 新增:export function AccountAvatar({ account, large = false }) { | |
| 113 | 新增: const initial = Array.from( | |
| 114 | 新增: account?.username?.trim() || "C", | |
| 115 | 新增: )[0].toLocaleUpperCase(); | |
| 116 | 新增: return ( | |
| 117 | 新增: <span | |
| 118 | 新增: className={`account-avatar ${large ? "large" : ""}`} | |
| 119 | 新增: aria-hidden="true" | |
| 120 | 新增: > | |
| 121 | 新增: {account?.avatar ? <img src={account.avatar} alt="" /> : initial} | |
| 122 | 新增: </span> | |
| 123 | 新增: ); | |
| 124 | 新增:} | |
| 125 | 新增: | |
| 126 | 新增:function PasswordField({ | |
| 127 | 新增: label, | |
| 128 | 新增: value, | |
| 129 | 新增: onChange, | |
| 130 | 新增: autoComplete = "current-password", | |
| 131 | 新增:}) { | |
| 132 | 新增: const [visible, setVisible] = useState(false); | |
| 133 | 新增: const id = useId(); | |
| 134 | 新增: return ( | |
| 135 | 新增: <div className="account-field"> | |
| 136 | 新增: <label htmlFor={id}>{label}</label> | |
| 137 | 新增: <span className="password-input"> | |
| 138 | 新增: <input | |
| 139 | 新增: id={id} | |
| 140 | 新增: type={visible ? "text" : "password"} | |
| 141 | 新增: value={value} | |
| 142 | 新增: onChange={(e) => onChange(e.target.value)} | |
| 143 | 新增: autoComplete={autoComplete} | |
| 144 | 新增: required | |
| 145 | 新增: maxLength={1024} | |
| 146 | 新增: /> | |
| 147 | 新增: <button | |
| 148 | 新增: type="button" | |
| 149 | 新增: className="icon-button" | |
| 150 | 新增: aria-label={`${visible ? "隐藏" : "显示"}${label}`} | |
| 151 | 新增: onClick={() => setVisible(!visible)} | |
| 152 | 新增: > | |
| 153 | 新增: {visible ? <EyeOff size={16} /> : <Eye size={16} />} | |
| 154 | 新增: </button> | |
| 155 | 新增: </span> | |
| 156 | 新增: </div> | |
| 157 | 新增: ); | |
| 158 | 新增:} | |
| 159 | 新增: | |
| 160 | 新增:export function AccountGate({ children }) { | |
| 161 | 新增: const { account, error: connectionError, refresh, act, deviceSupport, deviceAction, setDeviceNotice } = useAccount(); | |
| 162 | 新增: const [username, setUsername] = useState(""); | |
| 163 | 新增: const [password, setPassword] = useState(""); | |
| 164 | 新增: const [confirmation, setConfirmation] = useState(""); | |
| 165 | 新增: const [rememberLogin, setRememberLogin] = useState(true); | |
| 166 | 新增: const [busy, setBusy] = useState(false); | |
| 167 | 新增: const [error, setError] = useState(""); | |
| 168 | 新增: const automaticAttempt = useRef(""); | |
| 169 | 新增: const gateAcknowledged = useRef(false); | |
| 170 | 新增: useEffect(() => { | |
| 171 | 新增: if (!account || account.unlocked || connectionError || gateAcknowledged.current || !nativeAvailable()) return; | |
| 172 | 新增: // A working lock/setup screen is a valid upgraded UI. Waiting for the | |
| 173 | 新增: // user's password would incorrectly leave the native update unconfirmed. | |
| 174 | 新增: native("workbenchReady").then((accepted) => { | |
| 175 | 新增: if (accepted === true) gateAcknowledged.current = true; | |
| 176 | 新增: }).catch(() => {}); | |
| 177 | 新增: }, [Boolean(account), account?.unlocked, connectionError]); | |
| 178 | 新增: useEffect(() => { | |
| 179 | 新增: const id = account?.devices?.automatic; | |
| 180 | 新增: if (!id || account.unlocked || account.require_authentication || !deviceSupport?.supported || automaticAttempt.current === id) return; | |
| 181 | 新增: automaticAttempt.current = id; | |
| 182 | 新增: setBusy(true); | |
| 183 | 新增: deviceAction("unlock", "automatic").catch((e) => setError(e.message)).finally(() => setBusy(false)); | |
| 184 | 新增: }, [account?.unlocked, account?.devices?.automatic, account?.require_authentication, deviceSupport]); | |
| 185 | 新增: useEffect(() => { | |
| 186 | 新增: if (account?.unlocked) return; | |
| 187 | 新增: window.cageNativeAction = async (action) => { | |
| 188 | 新增: if (action === "quit") await native("quitNow"); | |
| 189 | 新增: }; | |
| 190 | 新增: return () => { | |
| 191 | 新增: delete window.cageNativeAction; | |
| 192 | 新增: }; | |
| 193 | 新增: }, [account?.unlocked]); | |
| 194 | 新增: if (account?.unlocked) return children; | |
| 195 | 新增: const creating = account && !account.exists; | |
| 196 | 新增: const submit = async (event) => { | |
| 197 | 新增: event.preventDefault(); | |
| 198 | 新增: if (busy) return; | |
| 199 | 新增: if (creating && password !== confirmation) { | |
| 200 | 新增: setError("两次密码不一致"); | |
| 201 | 新增: return; | |
| 202 | 新增: } | |
| 203 | 新增: setBusy(true); | |
| 204 | 新增: setError(""); | |
| 205 | 新增: try { | |
| 206 | 新增: await act( | |
| 207 | 新增: creating ? "create" : "unlock", | |
| 208 | 新增: creating | |
| 209 | 新增: ? { username, password, confirm_password: confirmation } | |
| 210 | 新增: : { password }, | |
| 211 | 新增: ); | |
| 212 | 新增: setPassword(""); | |
| 213 | 新增: setConfirmation(""); | |
| 214 | 新增: if (creating && rememberLogin && deviceSupport?.supported) { | |
| 215 | 新增: try { await deviceAction("enable", "automatic"); } | |
| 216 | 新增: catch (e) { setDeviceNotice(`账户已创建,记住登录未能开启:${e.message}。可在账户设置重试。`); } | |
| 217 | 新增: } | |
| 218 | 新增: } catch (e) { | |
| 219 | 新增: setError(e.message); | |
| 220 | 新增: } finally { | |
| 221 | 新增: setBusy(false); | |
| 222 | 新增: } | |
| 223 | 新增: }; | |
| 224 | 新增: return ( | |
| 225 | 新增: <main className="account-gate"> | |
| 226 | 新增: <div className="account-brand"> | |
| 227 | 新增: <img src={logo} alt="" /> | |
| 228 | 新增: Cage | |
| 229 | 新增: </div> | |
| 230 | 新增: <section | |
| 231 | 新增: className="account-entry" | |
| 232 | 新增: aria-label={creating ? "创建本地账户" : "解锁 Cage"} | |
| 233 | 新增: > | |
| 234 | 新增: {creating ? ( | |
| 235 | 新增: <img className="account-welcome-logo" src={logo} alt="" /> | |
| 236 | 新增: ) : ( | |
| 237 | 新增: account && <AccountAvatar account={account} large /> | |
| 238 | 新增: )} | |
| 239 | 新增: <h1> | |
| 240 | 新增: {creating | |
| 241 | 新增: ? "让 Cage 成为你的工作空间" | |
| 242 | 新增: : account | |
| 243 | 新增: ? `欢迎回来,${account.username}` | |
| 244 | 新增: : "正在连接 Cage"} | |
| 245 | 新增: </h1> | |
| 246 | 新增: <p className="account-entry-intro"> | |
| 247 | 新增: {creating | |
| 248 | 新增: ? "创建一个本地账户,收好你的工作与登录状态。" | |
| 249 | 新增: : account | |
| 250 | 新增: ? "输入密码,继续你的工作。" | |
| 251 | 新增: : "正在读取本机账户…"} | |
| 252 | 新增: </p> | |
| 253 | 新增: {account?.background_running && ( | |
| 254 | 新增: <div className="account-background"> | |
| 255 | 新增: <i /> | |
| 256 | 新增: 后台环境仍在运行,任务没有停止 | |
| 257 | 新增: </div> | |
| 258 | 新增: )} | |
| 259 | 新增: {account && ( | |
| 260 | 新增: <form onSubmit={submit}> | |
| 261 | 新增: <fieldset disabled={busy}> | |
| 262 | 新增: {creating && ( | |
| 263 | 新增: <label className="account-field"> | |
| 264 | 新增: 用户名 | |
| 265 | 新增: <input | |
| 266 | 新增: autoFocus | |
| 267 | 新增: autoComplete="username" | |
| 268 | 新增: maxLength={40} | |
| 269 | 新增: required | |
| 270 | 新增: value={username} | |
| 271 | 新增: onChange={(e) => setUsername(e.target.value)} | |
| 272 | 新增: placeholder="你希望怎样被称呼" | |
| 273 | 新增: /> | |
| 274 | 新增: </label> | |
| 275 | 新增: )} | |
| 276 | 新增: <PasswordField | |
| 277 | 新增: label={creating ? "设置密码" : "账户密码"} | |
| 278 | 新增: value={password} | |
| 279 | 新增: onChange={setPassword} | |
| 280 | 新增: autoComplete={creating ? "new-password" : "current-password"} | |
| 281 | 新增: /> | |
| 282 | 新增: {creating && ( | |
| 283 | 新增: <PasswordField | |
| 284 | 新增: label="确认密码" | |
| 285 | 新增: value={confirmation} | |
| 286 | 新增: onChange={setConfirmation} | |
| 287 | 新增: autoComplete="new-password" | |
| 288 | 新增: /> | |
| 289 | 新增: )} | |
| 290 | 新增: {(error || connectionError) && ( | |
| 291 | 新增: <p className="account-error" role="alert"> | |
| 292 | 新增: {error || connectionError} | |
| 293 | 新增: </p> | |
| 294 | 新增: )} | |
| 295 | 新增: {creating && deviceSupport?.supported && ( | |
| 296 | 新增: <label className="account-device-option check-line"> | |
| 297 | 新增: <input type="checkbox" checked={rememberLogin} onChange={(e) => setRememberLogin(e.target.checked)} /> | |
| 298 | 新增: <span><strong>记住登录</strong><small>下次打开直接进入。手动锁定后仍需验证。</small></span> | |
| 299 | 新增: </label> | |
| 300 | 新增: )} | |
| 301 | 新增: {!creating && deviceSupport?.supported && account.devices?.biometric && ( | |
| 302 | 新增: <button type="button" className="quiet-button account-submit" disabled={busy} | |
| 303 | 新增: onClick={async () => { | |
| 304 | 新增: setBusy(true); setError(""); | |
| 305 | 新增: try { await deviceAction("unlock", "biometric"); } | |
| 306 | 新增: catch (e) { setError(e.message); } | |
| 307 | 新增: finally { setBusy(false); } | |
| 308 | 新增: }}> | |
| 309 | 新增: <Fingerprint size={18} />使用 Touch ID 解锁 | |
| 310 | 新增: </button> | |
| 311 | 新增: )} | |
| 312 | 新增: <button | |
| 313 | 新增: className="primary account-submit" | |
| 314 | 新增: disabled={busy || !password || (creating && (!username.trim() || (nativeAvailable() && deviceSupport === null)))} | |
| 315 | 新增: > | |
| 316 | 新增: {busy ? "正在解锁…" : creating ? "创建本地账户" : "解锁 Cage"} | |
| 317 | 新增: </button> | |
| 318 | 新增: </fieldset> | |
| 319 | 新增: </form> | |
| 320 | 新增: )} | |
| 321 | 新增: {!account && connectionError && ( | |
| 322 | 新增: <> | |
| 323 | 新增: <p role="alert" className="account-error"> | |
| 324 | 新增: {connectionError} | |
| 325 | 新增: </p> | |
| 326 | 新增: <button onClick={() => refresh().catch(() => {})}>重新连接</button> | |
| 327 | 新增: </> | |
| 328 | 新增: )} | |
| 329 | 新增: <p className="account-local-note"> | |
| 330 | 新增: <LockKeyhole size={14} /> | |
| 331 | 新增: 账户资料仅保存在这台设备上 | |
| 332 | 新增: </p> | |
| 333 | 新增: <p className="account-recovery-note"> | |
| 334 | 新增: {creating | |
| 335 | 新增: ? "密码至少 8 个字符,用于保护应用登录凭据。请妥善保存,当前不支持在线找回。" | |
| 336 | 新增: : "请输入本地账户密码;当前不支持在线找回。"} | |
| 337 | 新增: </p> | |
| 338 | 新增: </section> | |
| 339 | 新增: {nativeAvailable() && ( | |
| 340 | 新增: <button | |
| 341 | 新增: className="text-button account-exit-app" | |
| 342 | 新增: onClick={() => native("quitNow").catch((e) => setError(e.message))} | |
| 343 | 新增: > | |
| 344 | 新增: {account?.background_running ? "退出应用,后台继续运行" : "退出 Cage"} | |
| 345 | 新增: </button> | |
| 346 | 新增: )} | |
| 347 | 新增: </main> | |
| 348 | 新增: ); | |
| 349 | 新增:} | |
| 350 | 新增: | |
| 351 | 新增:export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) { | |
| 352 | 新增: const { account, act, deviceNotice, setDeviceNotice } = useAccount(); | |
| 353 | 新增: useEffect(() => { | |
| 354 | 新增: if (deviceNotice) { onStatus(deviceNotice); setDeviceNotice(""); } | |
| 355 | 新增: }, [deviceNotice]); | |
| 356 | 新增: const [open, setOpen] = useState(false); | |
| 357 | 新增: const root = useRef(); | |
| 358 | 新增: useEffect(() => { | |
| 359 | 新增: if (!open) return; | |
| 360 | 新增: const dismiss = (event) => { | |
| 361 | 新增: if ( | |
| 362 | 新增: event.key === "Escape" || | |
| 363 | 新增: (event.type === "pointerdown" && !root.current?.contains(event.target)) | |
| 364 | 新增: ) | |
| 365 | 新增: setOpen(false); | |
| 366 | 新增: }; | |
| 367 | 新增: window.addEventListener("pointerdown", dismiss); | |
| 368 | 新增: window.addEventListener("keydown", dismiss); | |
| 369 | 新增: return () => { | |
| 370 | 新增: window.removeEventListener("pointerdown", dismiss); | |
| 371 | 新增: window.removeEventListener("keydown", dismiss); | |
| 372 | 新增: }; | |
| 373 | 新增: }, [open]); | |
| 374 | 新增: const perform = async (action) => { | |
| 375 | 新增: setOpen(false); | |
| 376 | 新增: if ( | |
| 377 | 新增: action === "logout" && | |
| 378 | 新增: !(await onConfirm({ | |
| 379 | 新增: title: "退出本地账户?", | |
| 380 | 新增: body: "这会停止 Cage 环境与后台任务,并锁定登录凭据。请先保存文件。", | |
| 381 | 新增: confirm: "停止环境并退出账户", | |
| 382 | 新增: })) | |
| 383 | 新增: ) | |
| 384 | 新增: return; | |
| 385 | 新增: try { | |
| 386 | 新增: await act(action); | |
| 387 | 新增: } catch (e) { | |
| 388 | 新增: onStatus(e.message); | |
| 389 | 新增: } | |
| 390 | 新增: }; | |
| 391 | 新增: return ( | |
| 392 | 新增: <div className="account-menu-root" ref={root}> | |
| 393 | 新增: <button | |
| 394 | 新增: className="account-trigger" | |
| 395 | 新增: aria-label={`账户菜单,${account.username}`} | |
| 396 | 新增: aria-expanded={open} | |
| 397 | 新增: aria-haspopup="menu" | |
| 398 | 新增: onClick={() => setOpen(!open)} | |
| 399 | 新增: > | |
| 400 | 新增: <AccountAvatar account={account} /> | |
| 401 | 新增: <span className="account-trigger-name"> | |
| 402 | 新增: <strong>{account.username}</strong> | |
| 403 | 新增: <small>本地账户</small> | |
| 404 | 新增: </span> | |
| 405 | 新增: <ChevronUp size={15} /> | |
| 406 | 新增: </button> | |
| 407 | 新增: {open && ( | |
| 408 | 新增: <div className="account-menu" role="menu" aria-label="本地账户菜单"> | |
| 409 | 新增: <div className="account-menu-label">你的 Cage</div> | |
| 410 | 新增: <button | |
| 411 | 新增: role="menuitem" | |
| 412 | 新增: onClick={() => { | |
| 413 | 新增: setOpen(false); | |
| 414 | 新增: onSettings("account"); | |
| 415 | 新增: }} | |
| 416 | 新增: > | |
| 417 | 新增: <UserRound size={16} /> | |
| 418 | 新增: 账户设置 | |
| 419 | 新增: </button> | |
| 420 | 新增: <button | |
| 421 | 新增: role="menuitem" | |
| 422 | 新增: onClick={() => { | |
| 423 | 新增: setOpen(false); | |
| 424 | 新增: onSettings("keyboard"); | |
| 425 | 新增: }} | |
| 426 | 新增: > | |
| 427 | 新增: <Settings2 size={16} /> | |
| 428 | 新增: 应用设置 | |
| 429 | 新增: </button> | |
| 430 | 新增: <div className="account-menu-divider" /> | |
| 431 | 新增: <button role="menuitem" onClick={() => perform("lock")}> | |
| 432 | 新增: <LockKeyhole size={16} /> | |
| 433 | 新增: 锁定 Cage<small>任务继续运行</small> | |
| 434 | 新增: </button> | |
| 435 | 新增: <button | |
| 436 | 新增: role="menuitem" | |
| 437 | 新增: disabled={busy} | |
| 438 | 新增: onClick={() => perform("logout")} | |
| 439 | 新增: > | |
| 440 | 新增: <LogOut size={16} /> | |
| 441 | 新增: 退出账户 | |
| 442 | 新增: </button> | |
| 443 | 新增: </div> | |
| 444 | 新增: )} | |
| 445 | 新增: </div> | |
| 446 | 新增: ); | |
| 447 | 新增:} | |
| 448 | 新增: | |
| 449 | 新增:export function AccountSettings({ busy: environmentBusy, onDirty }) { | |
| 450 | 新增: const { account, act } = useAccount(); | |
| 451 | 新增: const [name, setName] = useState(account.username), | |
| 452 | 新增: [avatar, setAvatar] = useState(account.avatar || ""); | |
| 453 | 新增: const [oldPassword, setOldPassword] = useState(""), | |
| 454 | 新增: [password, setPassword] = useState(""), | |
| 455 | 新增: [confirmation, setConfirmation] = useState(""); | |
| 456 | 新增: const [busy, setBusy] = useState(false), | |
| 457 | 新增: [error, setError] = useState(""), | |
| 458 | 新增: [message, setMessage] = useState(""); | |
| 459 | 新增: const [feedbackTarget, setFeedbackTarget] = useState("profile"); | |
| 460 | 新增: const file = useRef(); | |
| 461 | 新增: const changed = | |
| 462 | 新增: name !== account.username || avatar !== (account.avatar || ""); | |
| 463 | 新增: useEffect(() => { | |
| 464 | 新增: onDirty?.(changed || Boolean(oldPassword || password || confirmation)); | |
| 465 | 新增: }, [changed, oldPassword, password, confirmation]); | |
| 466 | 新增: useEffect(() => () => onDirty?.(false), []); | |
| 467 | 新增: const upload = async (event) => { | |
| 468 | 新增: setFeedbackTarget("profile"); | |
| 469 | 新增: const selected = event.target.files?.[0]; | |
| 470 | 新增: event.target.value = ""; | |
| 471 | 新增: if (!selected) return; | |
| 472 | 新增: if ( | |
| 473 | 新增: selected.size > 2 * 1024 * 1024 || | |
| 474 | 新增: !["image/png", "image/jpeg"].includes(selected.type) | |
| 475 | 新增: ) { | |
| 476 | 新增: setError("请选择不超过 2 MB 的 PNG 或 JPEG 图片"); | |
| 477 | 新增: return; | |
| 478 | 新增: } | |
| 479 | 新增: const reader = new FileReader(); | |
| 480 | 新增: reader.onload = () => { | |
| 481 | 新增: setAvatar(reader.result); | |
| 482 | 新增: setError(""); | |
| 483 | 新增: setMessage(""); | |
| 484 | 新增: }; | |
| 485 | 新增: reader.readAsDataURL(selected); | |
| 486 | 新增: }; | |
| 487 | 新增: const save = async (event, changingPassword = false) => { | |
| 488 | 新增: event.preventDefault(); | |
| 489 | 新增: if (busy) return; | |
| 490 | 新增: setFeedbackTarget(changingPassword ? "password" : "profile"); | |
| 491 | 新增: if (changingPassword && password !== confirmation) { | |
| 492 | 新增: setError("两次密码不一致"); | |
| 493 | 新增: return; | |
| 494 | 新增: } | |
| 495 | 新增: setBusy(true); | |
| 496 | 新增: setError(""); | |
| 497 | 新增: setMessage(""); | |
| 498 | 新增: try { | |
| 499 | 新增: const value = await act( | |
| 500 | 新增: changingPassword ? "password" : "profile", | |
| 501 | 新增: changingPassword | |
| 502 | 新增: ? { | |
| 503 | 新增: old_password: oldPassword, | |
| 504 | 新增: password, | |
| 505 | 新增: confirm_password: confirmation, | |
| 506 | 新增: } | |
| 507 | 新增: : { username: name, avatar }, | |
| 508 | 新增: ); | |
| 509 | 新增: if (changingPassword) { | |
| 510 | 新增: setOldPassword(""); | |
| 511 | 新增: setPassword(""); | |
| 512 | 新增: setConfirmation(""); | |
| 513 | 新增: setMessage("密码已修改,应用登录状态保持不变"); | |
| 514 | 新增: } else { | |
| 515 | 新增: setName(value.username); | |
| 516 | 新增: setAvatar(value.avatar || ""); | |
| 517 | 新增: setMessage("账户资料已保存"); | |
| 518 | 新增: } | |
| 519 | 新增: } catch (e) { | |
| 520 | 新增: setError(e.message); | |
| 521 | 新增: } finally { | |
| 522 | 新增: setBusy(false); | |
| 523 | 新增: } | |
| 524 | 新增: }; | |
| 525 | 新增: const feedback = ( | |
| 526 | 新增: <> | |
| 527 | 新增: {error && ( | |
| 528 | 新增: <p className="account-error" role="alert"> | |
| 529 | 新增: {error} | |
| 530 | 新增: </p> | |
| 531 | 新增: )} | |
| 532 | 新增: {message && ( | |
| 533 | 新增: <p className="account-saved" role="status"> | |
| 534 | 新增: <Check size={15} /> | |
| 535 | 新增: {message} | |
| 536 | 新增: </p> | |
| 537 | 新增: )} | |
| 538 | 新增: </> | |
| 539 | 新增: ); | |
| 540 | 新增: return ( | |
| 541 | 新增: <div className="account-settings"> | |
| 542 | 新增: <div className="section-title"> | |
| 543 | 新增: <h3>账户</h3> | |
| 544 | 新增: <p>给工作空间一点你的样子。</p> | |
| 545 | 新增: </div> | |
| 546 | 新增: <form onSubmit={(event) => save(event)}> | |
| 547 | 新增: <fieldset disabled={busy || environmentBusy}> | |
| 548 | 新增: <div className="account-profile-heading"> | |
| 549 | 新增: <AccountAvatar account={{ username: name, avatar }} large /> | |
| 550 | 新增: <div> | |
| 551 | 新增: <button | |
| 552 | 新增: type="button" | |
| 553 | 新增: className="quiet-button" | |
| 554 | 新增: onClick={() => file.current.click()} | |
| 555 | 新增: > | |
| 556 | 新增: <Camera size={16} /> | |
| 557 | 新增: 更换头像 | |
| 558 | 新增: </button> | |
| 559 | 新增: {avatar && ( | |
| 560 | 新增: <button | |
| 561 | 新增: type="button" | |
| 562 | 新增: className="text-button" | |
| 563 | 新增: onClick={() => setAvatar("")} | |
| 564 | 新增: > | |
| 565 | 新增: 恢复默认 | |
| 566 | 新增: </button> | |
| 567 | 新增: )} | |
| 568 | 新增: <p className="field-help"> | |
| 569 | 新增: PNG 或 JPEG,最多 2 MB,自动居中裁切。 | |
| 570 | 新增: </p> | |
| 571 | 新增: </div> | |
| 572 | 新增: </div> | |
| 573 | 新增: <input | |
| 574 | 新增: ref={file} | |
| 575 | 新增: type="file" | |
| 576 | 新增: accept="image/png,image/jpeg" | |
| 577 | 新增: hidden | |
| 578 | 新增: onChange={upload} | |
| 579 | 新增: aria-label="选择头像图片" | |
| 580 | 新增: /> | |
| 581 | 新增: <label className="account-field"> | |
| 582 | 新增: 用户名 | |
| 583 | 新增: <input | |
| 584 | 新增: value={name} | |
| 585 | 新增: maxLength={40} | |
| 586 | 新增: autoComplete="username" | |
| 587 | 新增: onChange={(e) => setName(e.target.value)} | |
| 588 | 新增: required | |
| 589 | 新增: /> | |
| 590 | 新增: </label> | |
| 591 | 新增: <button | |
| 592 | 新增: className="primary" | |
| 593 | 新增: disabled={!changed || !name.trim() || busy} | |
| 594 | 新增: > | |
| 595 | 新增: <Check size={16} /> | |
| 596 | 新增: 保存资料 | |
| 597 | 新增: </button> | |
| 598 | 新增: </fieldset> | |
| 599 | 新增: </form> | |
| 600 | 新增: {feedbackTarget === "profile" && feedback} | |
| 601 | 新增: <div className="account-section-divider" /> | |
| 602 | 新增: <form onSubmit={(event) => save(event, true)}> | |
| 603 | 新增: <fieldset disabled={busy || environmentBusy}> | |
| 604 | 新增: <h4>账户密码</h4> | |
| 605 | 新增: <p className="field-help"> | |
| 606 | 新增: 修改密码不会清除 Claude | |
| 607 | 新增: 的登录状态。密码仅用于本机解锁,没有在线找回。 | |
| 608 | 新增: </p> | |
| 609 | 新增: <PasswordField | |
| 610 | 新增: label="当前密码" | |
| 611 | 新增: value={oldPassword} | |
| 612 | 新增: onChange={setOldPassword} | |
| 613 | 新增: /> | |
| 614 | 新增: <PasswordField | |
| 615 | 新增: label="新密码" | |
| 616 | 新增: value={password} | |
| 617 | 新增: onChange={setPassword} | |
| 618 | 新增: autoComplete="new-password" | |
| 619 | 新增: /> | |
| 620 | 新增: <PasswordField | |
| 621 | 新增: label="确认新密码" | |
| 622 | 新增: value={confirmation} | |
| 623 | 新增: onChange={setConfirmation} | |
| 624 | 新增: autoComplete="new-password" | |
| 625 | 新增: /> | |
| 626 | 新增: <button | |
| 627 | 新增: className="quiet-button" | |
| 628 | 新增: disabled={busy || !oldPassword || !password || !confirmation} | |
| 629 | 新增: > | |
| 630 | 新增: 修改密码 | |
| 631 | 新增: </button> | |
| 632 | 新增: </fieldset> | |
| 633 | 新增: </form> | |
| 634 | 新增: | |
| 635 | 新增: {feedbackTarget === "password" && feedback} | |
| 636 | 新增: <AccountDeviceSettings /> | |
| 637 | 新增: <p className="account-settings-note"> | |
| 638 | 新增: <LockKeyhole size={15} /> | |
| 639 | 新增: 一个本地账户,一个持久工作环境。资料与凭据不上传到 Cage 服务器。 | |
| 640 | 新增: </p> | |
| 641 | 新增: </div> | |
| 642 | 新增: ); | |
| 643 | 新增:} | |
| 644 | 新增: | |
| 645 | 新增:function AccountDeviceSettings() { | |
| 646 | 新增: const { account, deviceSupport, deviceAction } = useAccount(); | |
| 647 | 新增: const [busy, setBusy] = useState(false); | |
| 648 | 新增: const [error, setError] = useState(""); | |
| 649 | 新增: const [message, setMessage] = useState(""); | |
| 650 | 新增: if (!deviceSupport?.supported) return null; | |
| 651 | 新增: const change = async (kind, enabled) => { | |
| 652 | 新增: setBusy(true); setError(""); setMessage(""); | |
| 653 | 新增: try { | |
| 654 | 新增: await deviceAction(enabled ? "enable" : "disable", kind); | |
| 655 | 新增: setMessage(enabled ? "已开启,解锁凭据保存在这台 Mac 的系统钥匙串中" : "已关闭快捷登录授权"); | |
| 656 | 新增: } catch (e) { setError(e.message); } | |
| 657 | 新增: finally { setBusy(false); } | |
| 658 | 新增: }; | |
| 659 | 新增: return <section className="account-device-settings" aria-label="登录与解锁"> | |
| 660 | 新增: <h4>登录与解锁</h4> | |
| 661 | 新增: <label className="account-device-option check-line"> | |
| 662 | 新增: <input type="checkbox" checked={Boolean(account.devices?.automatic)} disabled={busy} | |
| 663 | 新增: onChange={(event) => change("automatic", event.target.checked)} /> | |
| 664 | 新增: <span><strong>记住登录</strong><small>重新打开直接进入。手动锁定后仍需指纹或密码。</small></span> | |
| 665 | 新增: </label> | |
| 666 | 新增: <label className="account-device-option check-line"> | |
| 667 | 新增: <input type="checkbox" checked={Boolean(account.devices?.biometric)} disabled={busy || (!deviceSupport.biometric_available && !account.devices?.biometric)} | |
| 668 | 新增: onChange={(event) => change("biometric", event.target.checked)} /> | |
| 669 | 新增: <span><strong>使用 Touch ID 解锁</strong><small>{deviceSupport.biometric_available ? "手动锁定后,通过系统指纹验证进入。" : "请先在 macOS 系统设置中设置 Touch ID。"}</small></span> | |
| 670 | 新增: </label> | |
| 671 | 新增: <p className="field-help">退出账户会撤销本机快捷登录授权。密码始终可以用于解锁。</p> | |
| 672 | 新增: {error && <p className="account-error" role="alert">{error}</p>} | |
| 673 | 新增: {message && <p className="account-saved" role="status">{message}</p>} | |
| 674 | 新增: </section>; | |
| 675 | 新增:} | |
| @@ -40,12 +40,48 @@ export async function api(path, body, method) { | ||
| 40 | 40 | await renewSession(); |
| 41 | 41 | response = await fetch("/api" + path, options); |
| 42 | 42 | } |
| 43 | 新增: if (response.status === 423) window.dispatchEvent(new Event("cage-account-locked")); | |
| 43 | 44 | if (!response.ok) throw await responseError(response); |
| 44 | 45 | return response.json(); |
| 45 | 46 | } |
| 47 | 新增:export async function uploadFile(path, file, { signal, onProgress } = {}) { | |
| 48 | 新增: const send = () => new Promise((resolve, reject) => { | |
| 49 | 新增: if (signal?.aborted) { reject(new DOMException("上传已取消", "AbortError")); return; } | |
| 50 | 新增: const request = new XMLHttpRequest(); | |
| 51 | 新增: const abort = () => request.abort(); | |
| 52 | 新增: const cleanup = () => signal?.removeEventListener("abort", abort); | |
| 53 | 新增: request.open("POST", "/api" + path); | |
| 54 | 新增: request.setRequestHeader("Content-Type", "application/octet-stream"); | |
| 55 | 新增: request.upload.onprogress = event => onProgress?.(event.loaded, event.total || file.size); | |
| 56 | 新增: request.onerror = () => { cleanup(); reject(new Error("文件传递中断,请重试")); }; | |
| 57 | 新增: request.onabort = () => { cleanup(); reject(new DOMException("上传已取消", "AbortError")); }; | |
| 58 | 新增: request.onload = () => { | |
| 59 | 新增: cleanup(); | |
| 60 | 新增: if (request.status === 423) window.dispatchEvent(new Event("cage-account-locked")); | |
| 61 | 新增: if (request.status !== 200) { | |
| 62 | 新增: const error = new Error(request.responseText.trim() || "文件传递未完成"); | |
| 63 | 新增: error.status = request.status; reject(error); return; | |
| 64 | 新增: } | |
| 65 | 新增: try { resolve(JSON.parse(request.responseText)); } | |
| 66 | 新增: catch { reject(new Error("文件传递响应无效")); } | |
| 67 | 新增: }; | |
| 68 | 新增: signal?.addEventListener("abort", abort, { once: true }); | |
| 69 | 新增: request.send(file); | |
| 70 | 新增: }); | |
| 71 | 新增: try { return await send(); } | |
| 72 | 新增: catch (error) { | |
| 73 | 新增: if (error.status !== 401 || !nativeAvailable() || signal?.aborted) throw error; | |
| 74 | 新增: await renewSession(); | |
| 75 | 新增: return send(); | |
| 76 | 新增: } | |
| 77 | 新增:} | |
| 46 | 78 | export const nativeAvailable = () => |
| 47 | 79 | Boolean(window.webkit?.messageHandlers?.cage); |
| 48 | 80 | export async function native(action, extra = {}) { |
| 81 | 新增: if (action === "quitNow") { | |
| 82 | 新增: try { await api("/account/suspend", {}); } | |
| 83 | 新增: catch (error) { if (error.status !== 423) throw error; } | |
| 84 | 新增: } | |
| 49 | 85 | return window.webkit.messageHandlers.cage.postMessage({ action, ...extra }); |
| 50 | 86 | } |
| 51 | 87 | export const readClipboard = () => |
| @@ -57,6 +57,7 @@ export function AppUpdateButton({ updates }) { | ||
| 57 | 57 | ? Math.min(100, Math.floor((state.receivedBytes || 0) / state.totalBytes * 100)) |
| 58 | 58 | : null; |
| 59 | 59 | const label = state.phase === "available" ? "下载更新" |
| 60 | 新增: : state.phase === "manual" ? "查看更新方式" | |
| 60 | 61 | : state.phase === "ready" ? "安装更新并重启" |
| 61 | 62 | : state.phase === "downloading" ? `正在下载更新${percent === null ? "" : ` ${percent}%`}` |
| 62 | 63 | : state.phase === "verifying" || state.phase === "downloaded" ? "正在校验更新" |
| @@ -97,7 +98,7 @@ export function AppUpdateButton({ updates }) { | ||
| 97 | 98 | {state.phase === "ready" && <p>更新已下载。保存工作后可继续安装,项目与登录状态会保留。</p>} |
| 98 | 99 | <div className="modal-actions"> |
| 99 | 100 | {state.phase === "downloading" && <button onClick={() => run("cancel")}>取消下载</button>} |
| 100 | 删除: {!busy && ( | |
| 101 | 新增: {!busy && state.phase !== "manual" && ( | |
| 101 | 102 | <button onClick={() => run("check")}>重新检查</button> |
| 102 | 103 | )} |
| 103 | 104 | {!busy && (downloadable || (state.phase === "failed" && state.latestVersion)) && ( |
| @@ -0,0 +1,694 @@ | ||
| 1 | 新增:// Cage adaptations of these palettes; no third-party theme files are loaded at runtime. | |
| 2 | 新增:// VS Code: https://github.com/microsoft/vscode/tree/main/extensions/theme-defaults/themes | |
| 3 | 新增:// Typora: https://github.com/typora/typora-default-themes | |
| 4 | 新增:// Nord: https://www.nordtheme.com/docs/colors-and-palettes/ | |
| 5 | 新增:// Dracula: https://draculatheme.com/contribute | |
| 6 | 新增:// Color Universal Design: https://jfly.uni-koeln.de/color/ | |
| 7 | 新增:const light = (accent, surface, ink, colors = {}, terminal = {}) => ({ | |
| 8 | 新增: accent, | |
| 9 | 新增: surface, | |
| 10 | 新增: ink, | |
| 11 | 新增: contrast: 45, | |
| 12 | 新增: colors, | |
| 13 | 新增: terminal, | |
| 14 | 新增:}); | |
| 15 | 新增:const dark = (accent, surface, ink, colors = {}, terminal = {}) => ({ | |
| 16 | 新增: accent, | |
| 17 | 新增: surface, | |
| 18 | 新增: ink, | |
| 19 | 新增: contrast: 60, | |
| 20 | 新增: colors, | |
| 21 | 新增: terminal, | |
| 22 | 新增:}); | |
| 23 | 新增: | |
| 24 | 新增:export const themeCatalog = [ | |
| 25 | 新增: { | |
| 26 | 新增: id: "codex", | |
| 27 | 新增: name: "Codex", | |
| 28 | 新增: group: "经典", | |
| 29 | 新增: description: "中性背景与蓝色强调,保持 Cage 的默认外观。", | |
| 30 | 新增: light: light("#339cff", "#ffffff", "#1a1c1f"), | |
| 31 | 新增: dark: dark("#339cff", "#181818", "#ffffff"), | |
| 32 | 新增: }, | |
| 33 | 新增: { | |
| 34 | 新增: id: "solarized", | |
| 35 | 新增: name: "Solarized", | |
| 36 | 新增: group: "经典", | |
| 37 | 新增: description: "暖米白与深青底色,使用低饱和度的阅读配色。", | |
| 38 | 新增: light: light("#b58900", "#fdf6e3", "#657b83"), | |
| 39 | 新增: dark: dark("#b58900", "#002b36", "#93a1a1"), | |
| 40 | 新增: }, | |
| 41 | 新增: { | |
| 42 | 新增: id: "ayu", | |
| 43 | 新增: name: "Ayu", | |
| 44 | 新增: group: "经典", | |
| 45 | 新增: description: "深蓝灰背景,搭配温暖的金色强调。", | |
| 46 | 新增: dark: dark("#e6b450", "#10141c", "#bfbdb6"), | |
| 47 | 新增: }, | |
| 48 | 新增: { | |
| 49 | 新增: id: "vscode-modern", | |
| 50 | 新增: name: "VS Code Modern", | |
| 51 | 新增: group: "编辑器", | |
| 52 | 新增: description: "参考 VS Code Modern,区分工作区、侧栏和输入框的层级。", | |
| 53 | 新增: light: light( | |
| 54 | 新增: "#005fb8", | |
| 55 | 新增: "#ffffff", | |
| 56 | 新增: "#3b3b3b", | |
| 57 | 新增: { | |
| 58 | 新增: chrome: "#f8f8f8", | |
| 59 | 新增: sidebar: "#f8f8f8", | |
| 60 | 新增: toolbar: "#f8f8f8", | |
| 61 | 新增: line: "#cecece", | |
| 62 | 新增: strong: "#1f1f1f", | |
| 63 | 新增: muted: "#616161", | |
| 64 | 新增: hover: "#f2f2f2", | |
| 65 | 新增: selected: "#e8e8e8", | |
| 66 | 新增: selection: "#add6ff", | |
| 67 | 新增: button: "#005fb8", | |
| 68 | 新增: buttonInk: "#ffffff", | |
| 69 | 新增: }, | |
| 70 | 新增: { | |
| 71 | 新增: red: "#a31515", | |
| 72 | 新增: green: "#176b23", | |
| 73 | 新增: yellow: "#795e26", | |
| 74 | 新增: blue: "#005fb8", | |
| 75 | 新增: magenta: "#813f9c", | |
| 76 | 新增: cyan: "#006b70", | |
| 77 | 新增: brightBlack: "#616161", | |
| 78 | 新增: }, | |
| 79 | 新增: ), | |
| 80 | 新增: dark: dark( | |
| 81 | 新增: "#0078d4", | |
| 82 | 新增: "#1f1f1f", | |
| 83 | 新增: "#cccccc", | |
| 84 | 新增: { | |
| 85 | 新增: chrome: "#181818", | |
| 86 | 新增: sidebar: "#181818", | |
| 87 | 新增: toolbar: "#181818", | |
| 88 | 新增: input: "#313131", | |
| 89 | 新增: line: "#3c3c3c", | |
| 90 | 新增: strong: "#ffffff", | |
| 91 | 新增: muted: "#9d9d9d", | |
| 92 | 新增: hover: "#2b2b2b", | |
| 93 | 新增: selected: "#353535", | |
| 94 | 新增: selection: "#264f78", | |
| 95 | 新增: button: "#0078d4", | |
| 96 | 新增: buttonInk: "#ffffff", | |
| 97 | 新增: link: "#4daafc", | |
| 98 | 新增: }, | |
| 99 | 新增: { | |
| 100 | 新增: red: "#f48771", | |
| 101 | 新增: green: "#89d185", | |
| 102 | 新增: yellow: "#dcdcaa", | |
| 103 | 新增: blue: "#4daafc", | |
| 104 | 新增: magenta: "#c586c0", | |
| 105 | 新增: cyan: "#4ec9b0", | |
| 106 | 新增: white: "#cccccc", | |
| 107 | 新增: brightBlack: "#9d9d9d", | |
| 108 | 新增: }, | |
| 109 | 新增: ), | |
| 110 | 新增: }, | |
| 111 | 新增: { | |
| 112 | 新增: id: "vscode-classic", | |
| 113 | 新增: name: "VS Code Classic", | |
| 114 | 新增: group: "编辑器", | |
| 115 | 新增: description: "参考经典 Light+ / Dark+,蓝色强调与清楚的面板分区。", | |
| 116 | 新增: light: light( | |
| 117 | 新增: "#0066b8", | |
| 118 | 新增: "#ffffff", | |
| 119 | 新增: "#202020", | |
| 120 | 新增: { | |
| 121 | 新增: chrome: "#f3f3f3", | |
| 122 | 新增: sidebar: "#f3f3f3", | |
| 123 | 新增: toolbar: "#f3f3f3", | |
| 124 | 新增: line: "#b8b8b8", | |
| 125 | 新增: muted: "#5a5a5a", | |
| 126 | 新增: selected: "#d6ebff", | |
| 127 | 新增: selection: "#add6ff", | |
| 128 | 新增: button: "#0066b8", | |
| 129 | 新增: buttonInk: "#ffffff", | |
| 130 | 新增: }, | |
| 131 | 新增: { | |
| 132 | 新增: red: "#a31515", | |
| 133 | 新增: green: "#176b23", | |
| 134 | 新增: yellow: "#795e26", | |
| 135 | 新增: blue: "#0451a5", | |
| 136 | 新增: magenta: "#813f9c", | |
| 137 | 新增: cyan: "#006b70", | |
| 138 | 新增: }, | |
| 139 | 新增: ), | |
| 140 | 新增: dark: dark( | |
| 141 | 新增: "#569cd6", | |
| 142 | 新增: "#1e1e1e", | |
| 143 | 新增: "#d4d4d4", | |
| 144 | 新增: { | |
| 145 | 新增: chrome: "#252526", | |
| 146 | 新增: sidebar: "#252526", | |
| 147 | 新增: toolbar: "#252526", | |
| 148 | 新增: line: "#555555", | |
| 149 | 新增: muted: "#a0a0a0", | |
| 150 | 新增: selected: "#37373d", | |
| 151 | 新增: selection: "#264f78", | |
| 152 | 新增: button: "#0e639c", | |
| 153 | 新增: buttonInk: "#ffffff", | |
| 154 | 新增: }, | |
| 155 | 新增: { | |
| 156 | 新增: red: "#f48771", | |
| 157 | 新增: green: "#b5cea8", | |
| 158 | 新增: yellow: "#dcdcaa", | |
| 159 | 新增: blue: "#569cd6", | |
| 160 | 新增: magenta: "#c586c0", | |
| 161 | 新增: cyan: "#4ec9b0", | |
| 162 | 新增: white: "#d4d4d4", | |
| 163 | 新增: }, | |
| 164 | 新增: ), | |
| 165 | 新增: }, | |
| 166 | 新增: { | |
| 167 | 新增: id: "github", | |
| 168 | 新增: name: "GitHub", | |
| 169 | 新增: group: "编辑器", | |
| 170 | 新增: description: "清爽的蓝灰配色,提供白底与深色两套搭配。", | |
| 171 | 新增: light: light( | |
| 172 | 新增: "#0969da", | |
| 173 | 新增: "#ffffff", | |
| 174 | 新增: "#24292f", | |
| 175 | 新增: { | |
| 176 | 新增: chrome: "#f6f8fa", | |
| 177 | 新增: sidebar: "#f6f8fa", | |
| 178 | 新增: toolbar: "#f6f8fa", | |
| 179 | 新增: line: "#d0d7de", | |
| 180 | 新增: muted: "#57606a", | |
| 181 | 新增: selected: "#ddf4ff", | |
| 182 | 新增: button: "#1a7f37", | |
| 183 | 新增: buttonInk: "#ffffff", | |
| 184 | 新增: success: "#1a7f37", | |
| 185 | 新增: danger: "#cf222e", | |
| 186 | 新增: warning: "#9a6700", | |
| 187 | 新增: }, | |
| 188 | 新增: { | |
| 189 | 新增: red: "#cf222e", | |
| 190 | 新增: green: "#1a7f37", | |
| 191 | 新增: yellow: "#9a6700", | |
| 192 | 新增: blue: "#0969da", | |
| 193 | 新增: magenta: "#8250df", | |
| 194 | 新增: cyan: "#1b7c83", | |
| 195 | 新增: white: "#57606a", | |
| 196 | 新增: }, | |
| 197 | 新增: ), | |
| 198 | 新增: dark: dark( | |
| 199 | 新增: "#58a6ff", | |
| 200 | 新增: "#0d1117", | |
| 201 | 新增: "#e6edf3", | |
| 202 | 新增: { | |
| 203 | 新增: chrome: "#161b22", | |
| 204 | 新增: sidebar: "#161b22", | |
| 205 | 新增: toolbar: "#161b22", | |
| 206 | 新增: line: "#484f58", | |
| 207 | 新增: muted: "#9da7b3", | |
| 208 | 新增: selected: "#253a52", | |
| 209 | 新增: button: "#238636", | |
| 210 | 新增: buttonInk: "#ffffff", | |
| 211 | 新增: success: "#7ee787", | |
| 212 | 新增: danger: "#ff7b72", | |
| 213 | 新增: warning: "#e3b341", | |
| 214 | 新增: }, | |
| 215 | 新增: { | |
| 216 | 新增: red: "#ff7b72", | |
| 217 | 新增: green: "#7ee787", | |
| 218 | 新增: yellow: "#e3b341", | |
| 219 | 新增: blue: "#79c0ff", | |
| 220 | 新增: magenta: "#d2a8ff", | |
| 221 | 新增: cyan: "#a5d6ff", | |
| 222 | 新增: white: "#e6edf3", | |
| 223 | 新增: brightBlack: "#9da7b3", | |
| 224 | 新增: }, | |
| 225 | 新增: ), | |
| 226 | 新增: }, | |
| 227 | 新增: { | |
| 228 | 新增: id: "nord", | |
| 229 | 新增: name: "Nord", | |
| 230 | 新增: group: "编辑器", | |
| 231 | 新增: description: "冷调蓝灰与冰蓝强调,参考 Nord 的极地色板。", | |
| 232 | 新增: light: light( | |
| 233 | 新增: "#375f88", | |
| 234 | 新增: "#eceff4", | |
| 235 | 新增: "#2e3440", | |
| 236 | 新增: { | |
| 237 | 新增: chrome: "#e5e9f0", | |
| 238 | 新增: sidebar: "#e5e9f0", | |
| 239 | 新增: toolbar: "#e5e9f0", | |
| 240 | 新增: line: "#9aa7b8", | |
| 241 | 新增: muted: "#4c566a", | |
| 242 | 新增: selected: "#cbd9e8", | |
| 243 | 新增: button: "#375f88", | |
| 244 | 新增: buttonInk: "#ffffff", | |
| 245 | 新增: }, | |
| 246 | 新增: { | |
| 247 | 新增: red: "#963f4c", | |
| 248 | 新增: green: "#466637", | |
| 249 | 新增: yellow: "#795d22", | |
| 250 | 新增: blue: "#375f88", | |
| 251 | 新增: magenta: "#80567b", | |
| 252 | 新增: cyan: "#346b70", | |
| 253 | 新增: }, | |
| 254 | 新增: ), | |
| 255 | 新增: dark: dark( | |
| 256 | 新增: "#88c0d0", | |
| 257 | 新增: "#2e3440", | |
| 258 | 新增: "#eceff4", | |
| 259 | 新增: { | |
| 260 | 新增: chrome: "#3b4252", | |
| 261 | 新增: sidebar: "#3b4252", | |
| 262 | 新增: toolbar: "#3b4252", | |
| 263 | 新增: line: "#69778f", | |
| 264 | 新增: muted: "#bac5d6", | |
| 265 | 新增: selected: "#4c566a", | |
| 266 | 新增: button: "#88c0d0", | |
| 267 | 新增: buttonInk: "#2e3440", | |
| 268 | 新增: success: "#a3be8c", | |
| 269 | 新增: danger: "#e39aa3", | |
| 270 | 新增: warning: "#ebcb8b", | |
| 271 | 新增: }, | |
| 272 | 新增: { | |
| 273 | 新增: black: "#4c566a", | |
| 274 | 新增: red: "#e39aa3", | |
| 275 | 新增: green: "#a3be8c", | |
| 276 | 新增: yellow: "#ebcb8b", | |
| 277 | 新增: blue: "#81a1c1", | |
| 278 | 新增: magenta: "#b48ead", | |
| 279 | 新增: cyan: "#8fbcbb", | |
| 280 | 新增: white: "#e5e9f0", | |
| 281 | 新增: brightBlack: "#9aa7b8", | |
| 282 | 新增: brightWhite: "#eceff4", | |
| 283 | 新增: }, | |
| 284 | 新增: ), | |
| 285 | 新增: }, | |
| 286 | 新增: { | |
| 287 | 新增: id: "dracula", | |
| 288 | 新增: name: "Dracula", | |
| 289 | 新增: group: "编辑器", | |
| 290 | 新增: description: "紫灰底色,搭配粉、紫与青绿的鲜明终端色板。", | |
| 291 | 新增: dark: dark( | |
| 292 | 新增: "#bd93f9", | |
| 293 | 新增: "#282a36", | |
| 294 | 新增: "#f8f8f2", | |
| 295 | 新增: { | |
| 296 | 新增: chrome: "#21222c", | |
| 297 | 新增: sidebar: "#21222c", | |
| 298 | 新增: toolbar: "#21222c", | |
| 299 | 新增: line: "#6272a4", | |
| 300 | 新增: muted: "#b5bfdc", | |
| 301 | 新增: selected: "#44475a", | |
| 302 | 新增: button: "#bd93f9", | |
| 303 | 新增: buttonInk: "#282a36", | |
| 304 | 新增: success: "#50fa7b", | |
| 305 | 新增: danger: "#ff8080", | |
| 306 | 新增: warning: "#f1fa8c", | |
| 307 | 新增: }, | |
| 308 | 新增: { | |
| 309 | 新增: black: "#44475a", | |
| 310 | 新增: red: "#ff8080", | |
| 311 | 新增: green: "#50fa7b", | |
| 312 | 新增: yellow: "#f1fa8c", | |
| 313 | 新增: blue: "#bd93f9", | |
| 314 | 新增: magenta: "#ff79c6", | |
| 315 | 新增: cyan: "#8be9fd", | |
| 316 | 新增: white: "#f8f8f2", | |
| 317 | 新增: brightBlack: "#b5bfdc", | |
| 318 | 新增: brightRed: "#ff9f9f", | |
| 319 | 新增: brightGreen: "#8affaa", | |
| 320 | 新增: brightYellow: "#ffffa5", | |
| 321 | 新增: brightBlue: "#d6b7ff", | |
| 322 | 新增: brightMagenta: "#ffa4da", | |
| 323 | 新增: brightCyan: "#b2f2ff", | |
| 324 | 新增: brightWhite: "#ffffff", | |
| 325 | 新增: }, | |
| 326 | 新增: ), | |
| 327 | 新增: }, | |
| 328 | 新增: { | |
| 329 | 新增: id: "monokai", | |
| 330 | 新增: name: "Monokai", | |
| 331 | 新增: group: "编辑器", | |
| 332 | 新增: description: "参考 VS Code Monokai,橄榄黑背景与鲜明的暖色强调。", | |
| 333 | 新增: dark: dark( | |
| 334 | 新增: "#f8c555", | |
| 335 | 新增: "#272822", | |
| 336 | 新增: "#f8f8f2", | |
| 337 | 新增: { | |
| 338 | 新增: chrome: "#1e1f1c", | |
| 339 | 新增: sidebar: "#1e1f1c", | |
| 340 | 新增: toolbar: "#1e1f1c", | |
| 341 | 新增: line: "#75715e", | |
| 342 | 新增: muted: "#c0bea8", | |
| 343 | 新增: selected: "#414339", | |
| 344 | 新增: button: "#f8c555", | |
| 345 | 新增: buttonInk: "#272822", | |
| 346 | 新增: success: "#a6e22e", | |
| 347 | 新增: danger: "#ff719c", | |
| 348 | 新增: warning: "#e6db74", | |
| 349 | 新增: }, | |
| 350 | 新增: { | |
| 351 | 新增: red: "#ff719c", | |
| 352 | 新增: green: "#a6e22e", | |
| 353 | 新增: yellow: "#e6db74", | |
| 354 | 新增: blue: "#66d9ef", | |
| 355 | 新增: magenta: "#ae81ff", | |
| 356 | 新增: cyan: "#a1efe4", | |
| 357 | 新增: white: "#f8f8f2", | |
| 358 | 新增: brightBlack: "#c0bea8", | |
| 359 | 新增: }, | |
| 360 | 新增: ), | |
| 361 | 新增: }, | |
| 362 | 新增: { | |
| 363 | 新增: id: "paper", | |
| 364 | 新增: name: "纸白 · Typora 风格", | |
| 365 | 新增: group: "阅读", | |
| 366 | 新增: description: | |
| 367 | 新增: "参考 Typora 的 GitHub 阅读主题,白纸、深灰文字和克制的蓝色链接。", | |
| 368 | 新增: light: light( | |
| 369 | 新增: "#336da0", | |
| 370 | 新增: "#ffffff", | |
| 371 | 新增: "#333333", | |
| 372 | 新增: { | |
| 373 | 新增: chrome: "#f7f7f7", | |
| 374 | 新增: sidebar: "#f7f7f7", | |
| 375 | 新增: toolbar: "#fafafa", | |
| 376 | 新增: line: "#c8c8c8", | |
| 377 | 新增: muted: "#666666", | |
| 378 | 新增: strong: "#202020", | |
| 379 | 新增: button: "#333333", | |
| 380 | 新增: buttonInk: "#ffffff", | |
| 381 | 新增: }, | |
| 382 | 新增: { | |
| 383 | 新增: red: "#a33a3a", | |
| 384 | 新增: green: "#426e37", | |
| 385 | 新增: yellow: "#775b25", | |
| 386 | 新增: blue: "#336da0", | |
| 387 | 新增: magenta: "#865b8e", | |
| 388 | 新增: cyan: "#226b70", | |
| 389 | 新增: white: "#666666", | |
| 390 | 新增: }, | |
| 391 | 新增: ), | |
| 392 | 新增: }, | |
| 393 | 新增: { | |
| 394 | 新增: id: "sepia", | |
| 395 | 新增: name: "暖纸 · Sepia", | |
| 396 | 新增: group: "阅读", | |
| 397 | 新增: description: "参考 Typora 的暖纸阅读风格,米色背景、棕色强调与柔和分区。", | |
| 398 | 新增: light: light( | |
| 399 | 新增: "#80552f", | |
| 400 | 新增: "#f8f0e3", | |
| 401 | 新增: "#514437", | |
| 402 | 新增: { | |
| 403 | 新增: chrome: "#eee3d1", | |
| 404 | 新增: sidebar: "#eee3d1", | |
| 405 | 新增: toolbar: "#f3e9da", | |
| 406 | 新增: line: "#b1a18b", | |
| 407 | 新增: muted: "#6d5a48", | |
| 408 | 新增: selected: "#e1d2bb", | |
| 409 | 新增: button: "#80552f", | |
| 410 | 新增: buttonInk: "#fffaf1", | |
| 411 | 新增: link: "#76502e", | |
| 412 | 新增: }, | |
| 413 | 新增: { | |
| 414 | 新增: red: "#993c2c", | |
| 415 | 新增: green: "#4f652c", | |
| 416 | 新增: yellow: "#775314", | |
| 417 | 新增: blue: "#355e85", | |
| 418 | 新增: magenta: "#79517e", | |
| 419 | 新增: cyan: "#28665f", | |
| 420 | 新增: white: "#6d5a48", | |
| 421 | 新增: }, | |
| 422 | 新增: ), | |
| 423 | 新增: }, | |
| 424 | 新增: { | |
| 425 | 新增: id: "night", | |
| 426 | 新增: name: "夜间 · Typora 风格", | |
| 427 | 新增: group: "阅读", | |
| 428 | 新增: description: "参考 Typora Night,使用柔和蓝灰底色与较低饱和度的强调色。", | |
| 429 | 新增: dark: dark( | |
| 430 | 新增: "#a6c9ea", | |
| 431 | 新增: "#363b40", | |
| 432 | 新增: "#e0e4e8", | |
| 433 | 新增: { | |
| 434 | 新增: chrome: "#2b3035", | |
| 435 | 新增: sidebar: "#2b3035", | |
| 436 | 新增: toolbar: "#2b3035", | |
| 437 | 新增: line: "#75818b", | |
| 438 | 新增: muted: "#b8bfc6", | |
| 439 | 新增: selected: "#505b65", | |
| 440 | 新增: button: "#a6c9ea", | |
| 441 | 新增: buttonInk: "#263440", | |
| 442 | 新增: success: "#b1d0a7", | |
| 443 | 新增: danger: "#f0a5a5", | |
| 444 | 新增: warning: "#e7c78c", | |
| 445 | 新增: }, | |
| 446 | 新增: { | |
| 447 | 新增: red: "#f0a5a5", | |
| 448 | 新增: green: "#b1d0a7", | |
| 449 | 新增: yellow: "#e7c78c", | |
| 450 | 新增: blue: "#a6c9ea", | |
| 451 | 新增: magenta: "#cfb0db", | |
| 452 | 新增: cyan: "#a1d4cf", | |
| 453 | 新增: white: "#e0e4e8", | |
| 454 | 新增: brightBlack: "#b8bfc6", | |
| 455 | 新增: }, | |
| 456 | 新增: ), | |
| 457 | 新增: }, | |
| 458 | 新增: { | |
| 459 | 新增: id: "color-vision", | |
| 460 | 新增: name: "色觉友好 · 蓝橙", | |
| 461 | 新增: group: "无障碍", | |
| 462 | 新增: description: | |
| 463 | 新增: "用蓝色和橙色区分成功与错误,减少红绿依赖;状态仍有图标和文字。", | |
| 464 | 新增: light: { | |
| 465 | 新增: ...light( | |
| 466 | 新增: "#005a9c", | |
| 467 | 新增: "#ffffff", | |
| 468 | 新增: "#17212b", | |
| 469 | 新增: { | |
| 470 | 新增: chrome: "#f2f5f8", | |
| 471 | 新增: sidebar: "#f2f5f8", | |
| 472 | 新增: toolbar: "#f2f5f8", | |
| 473 | 新增: chromeDark: "#e8edf2", | |
| 474 | 新增: strong: "#0c1722", | |
| 475 | 新增: muted: "#46596b", | |
| 476 | 新增: line: "#6b7785", | |
| 477 | 新增: input: "#ffffff", | |
| 478 | 新增: hover: "#e5edf5", | |
| 479 | 新增: selected: "#c9dff2", | |
| 480 | 新增: selection: "#c9dff2", | |
| 481 | 新增: button: "#005a9c", | |
| 482 | 新增: buttonInk: "#ffffff", | |
| 483 | 新增: accentInk: "#ffffff", | |
| 484 | 新增: link: "#005a9c", | |
| 485 | 新增: focus: "#005a9c", | |
| 486 | 新增: success: "#005a9c", | |
| 487 | 新增: danger: "#a63b00", | |
| 488 | 新增: warning: "#735700", | |
| 489 | 新增: inactive: "#546477", | |
| 490 | 新增: }, | |
| 491 | 新增: { | |
| 492 | 新增: black: "#17212b", | |
| 493 | 新增: red: "#a63b00", | |
| 494 | 新增: green: "#005a9c", | |
| 495 | 新增: yellow: "#735700", | |
| 496 | 新增: blue: "#5a3cbd", | |
| 497 | 新增: magenta: "#a13d75", | |
| 498 | 新增: cyan: "#006b63", | |
| 499 | 新增: white: "#5c6673", | |
| 500 | 新增: brightBlack: "#46596b", | |
| 501 | 新增: brightRed: "#9c3500", | |
| 502 | 新增: brightGreen: "#004c86", | |
| 503 | 新增: brightYellow: "#654b00", | |
| 504 | 新增: brightBlue: "#4d329f", | |
| 505 | 新增: brightMagenta: "#8c3265", | |
| 506 | 新增: brightCyan: "#005c55", | |
| 507 | 新增: brightWhite: "#384552", | |
| 508 | 新增: }, | |
| 509 | 新增: ), | |
| 510 | 新增: opaqueWindows: true, | |
| 511 | 新增: }, | |
| 512 | 新增: dark: { | |
| 513 | 新增: ...dark( | |
| 514 | 新增: "#56b4e9", | |
| 515 | 新增: "#121b24", | |
| 516 | 新增: "#f1f5f9", | |
| 517 | 新增: { | |
| 518 | 新增: chrome: "#1b2835", | |
| 519 | 新增: sidebar: "#1b2835", | |
| 520 | 新增: toolbar: "#1b2835", | |
| 521 | 新增: chromeDark: "#233447", | |
| 522 | 新增: strong: "#ffffff", | |
| 523 | 新增: muted: "#b3c4d6", | |
| 524 | 新增: line: "#8197ab", | |
| 525 | 新增: input: "#121b24", | |
| 526 | 新增: hover: "#2b4056", | |
| 527 | 新增: selected: "#334c66", | |
| 528 | 新增: selection: "#334c66", | |
| 529 | 新增: button: "#56b4e9", | |
| 530 | 新增: buttonInk: "#0a1822", | |
| 531 | 新增: accentInk: "#0a1822", | |
| 532 | 新增: link: "#87cefa", | |
| 533 | 新增: focus: "#ffcc80", | |
| 534 | 新增: success: "#56b4e9", | |
| 535 | 新增: danger: "#ffad66", | |
| 536 | 新增: warning: "#e6d55a", | |
| 537 | 新增: inactive: "#a6b3c3", | |
| 538 | 新增: }, | |
| 539 | 新增: { | |
| 540 | 新增: black: "#a7b6c2", | |
| 541 | 新增: red: "#ffad66", | |
| 542 | 新增: green: "#56b4e9", | |
| 543 | 新增: yellow: "#e6d55a", | |
| 544 | 新增: blue: "#a89dff", | |
| 545 | 新增: magenta: "#f19ccb", | |
| 546 | 新增: cyan: "#74d6c5", | |
| 547 | 新增: white: "#eceff4", | |
| 548 | 新增: brightBlack: "#cad5df", | |
| 549 | 新增: brightRed: "#ffc18f", | |
| 550 | 新增: brightGreen: "#87cefa", | |
| 551 | 新增: brightYellow: "#f2e68b", | |
| 552 | 新增: brightBlue: "#c6beff", | |
| 553 | 新增: brightMagenta: "#f7bfdf", | |
| 554 | 新增: brightCyan: "#a1e9dc", | |
| 555 | 新增: brightWhite: "#ffffff", | |
| 556 | 新增: }, | |
| 557 | 新增: ), | |
| 558 | 新增: opaqueWindows: true, | |
| 559 | 新增: }, | |
| 560 | 新增: }, | |
| 561 | 新增: { | |
| 562 | 新增: id: "high-contrast", | |
| 563 | 新增: name: "高对比", | |
| 564 | 新增: group: "无障碍", | |
| 565 | 新增: description: | |
| 566 | 新增: "提高文字、边框和焦点的对比度,关闭半透明侧栏;浅色为白底,深色为黑底。", | |
| 567 | 新增: light: { | |
| 568 | 新增: ...light( | |
| 569 | 新增: "#002b66", | |
| 570 | 新增: "#ffffff", | |
| 571 | 新增: "#000000", | |
| 572 | 新增: { | |
| 573 | 新增: chrome: "#ffffff", | |
| 574 | 新增: sidebar: "#ffffff", | |
| 575 | 新增: toolbar: "#ffffff", | |
| 576 | 新增: chromeDark: "#f0f0f0", | |
| 577 | 新增: strong: "#000000", | |
| 578 | 新增: muted: "#333333", | |
| 579 | 新增: line: "#595959", | |
| 580 | 新增: input: "#ffffff", | |
| 581 | 新增: hover: "#ededed", | |
| 582 | 新增: selected: "#e0e0e0", | |
| 583 | 新增: selection: "#d4d4d4", | |
| 584 | 新增: button: "#000000", | |
| 585 | 新增: buttonInk: "#ffffff", | |
| 586 | 新增: accentInk: "#ffffff", | |
| 587 | 新增: link: "#002b66", | |
| 588 | 新增: focus: "#000000", | |
| 589 | 新增: success: "#003b73", | |
| 590 | 新增: danger: "#8a2800", | |
| 591 | 新增: warning: "#554000", | |
| 592 | 新增: inactive: "#3f3f3f", | |
| 593 | 新增: }, | |
| 594 | 新增: { | |
| 595 | 新增: black: "#000000", | |
| 596 | 新增: red: "#8a2800", | |
| 597 | 新增: green: "#003b73", | |
| 598 | 新增: yellow: "#554000", | |
| 599 | 新增: blue: "#003587", | |
| 600 | 新增: magenta: "#651153", | |
| 601 | 新增: cyan: "#005248", | |
| 602 | 新增: white: "#3f3f3f", | |
| 603 | 新增: brightBlack: "#333333", | |
| 604 | 新增: brightRed: "#792200", | |
| 605 | 新增: brightGreen: "#00315f", | |
| 606 | 新增: brightYellow: "#483600", | |
| 607 | 新增: brightBlue: "#002d72", | |
| 608 | 新增: brightMagenta: "#580d47", | |
| 609 | 新增: brightCyan: "#00453c", | |
| 610 | 新增: brightWhite: "#202020", | |
| 611 | 新增: }, | |
| 612 | 新增: ), | |
| 613 | 新增: opaqueWindows: true, | |
| 614 | 新增: }, | |
| 615 | 新增: dark: { | |
| 616 | 新增: ...dark( | |
| 617 | 新增: "#00e5ff", | |
| 618 | 新增: "#000000", | |
| 619 | 新增: "#ffffff", | |
| 620 | 新增: { | |
| 621 | 新增: chrome: "#000000", | |
| 622 | 新增: sidebar: "#000000", | |
| 623 | 新增: toolbar: "#000000", | |
| 624 | 新增: chromeDark: "#151515", | |
| 625 | 新增: strong: "#ffffff", | |
| 626 | 新增: muted: "#dedede", | |
| 627 | 新增: line: "#a6a6a6", | |
| 628 | 新增: input: "#000000", | |
| 629 | 新增: hover: "#1c1c1c", | |
| 630 | 新增: selected: "#252525", | |
| 631 | 新增: selection: "#424242", | |
| 632 | 新增: button: "#ffffff", | |
| 633 | 新增: buttonInk: "#000000", | |
| 634 | 新增: accentInk: "#000000", | |
| 635 | 新增: link: "#64d8ff", | |
| 636 | 新增: focus: "#ffff00", | |
| 637 | 新增: success: "#75d8ff", | |
| 638 | 新增: danger: "#ffb86b", | |
| 639 | 新增: warning: "#ffea00", | |
| 640 | 新增: inactive: "#d0d0d0", | |
| 641 | 新增: }, | |
| 642 | 新增: { | |
| 643 | 新增: black: "#bdbdbd", | |
| 644 | 新增: red: "#ffb86b", | |
| 645 | 新增: green: "#75d8ff", | |
| 646 | 新增: yellow: "#ffea00", | |
| 647 | 新增: blue: "#8fbfff", | |
| 648 | 新增: magenta: "#f4aaff", | |
| 649 | 新增: cyan: "#79f4dc", | |
| 650 | 新增: white: "#eeeeee", | |
| 651 | 新增: brightBlack: "#dedede", | |
| 652 | 新增: brightRed: "#ffd2a6", | |
| 653 | 新增: brightGreen: "#b7edff", | |
| 654 | 新增: brightYellow: "#fff59d", | |
| 655 | 新增: brightBlue: "#c4dcff", | |
| 656 | 新增: brightMagenta: "#f9d3ff", | |
| 657 | 新增: brightCyan: "#b9ffef", | |
| 658 | 新增: brightWhite: "#ffffff", | |
| 659 | 新增: }, | |
| 660 | 新增: ), | |
| 661 | 新增: opaqueWindows: true, | |
| 662 | 新增: }, | |
| 663 | 新增: }, | |
| 664 | 新增:]; | |
| 665 | 新增: | |
| 666 | 新增:export const presets = Object.fromEntries( | |
| 667 | 新增: ["light", "dark"].map((variant) => [ | |
| 668 | 新增: variant, | |
| 669 | 新增: Object.fromEntries( | |
| 670 | 新增: themeCatalog | |
| 671 | 新增: .filter((item) => item[variant]) | |
| 672 | 新增: .map((item) => [item.id, item[variant]]), | |
| 673 | 新增: ), | |
| 674 | 新增: ]), | |
| 675 | 新增:); | |
| 676 | 新增:export const presetNames = Object.fromEntries( | |
| 677 | 新增: themeCatalog.map((item) => [item.id, item.name]), | |
| 678 | 新增:); | |
| 679 | 新增:export const presetGroups = ["经典", "编辑器", "阅读", "无障碍"]; | |
| 680 | 新增:export const presetInfo = Object.fromEntries( | |
| 681 | 新增: themeCatalog.map((item) => [item.id, item]), | |
| 682 | 新增:); | |
| 683 | 新增: | |
| 684 | 新增:export function applyThemePreset(current, variant, id) { | |
| 685 | 新增: const preset = presets[variant]?.[id]; | |
| 686 | 新增: if (!preset) throw new Error("所选主题不支持当前明暗模式"); | |
| 687 | 新增: return { | |
| 688 | 新增: ...current, | |
| 689 | 新增: ...structuredClone(preset), | |
| 690 | 新增: preset: id, | |
| 691 | 新增: colors: structuredClone(preset.colors), | |
| 692 | 新增: terminal: structuredClone(preset.terminal), | |
| 693 | 新增: }; | |
| 694 | 新增:} | |
| @@ -1,4 +1,4 @@ | ||
| 1 | 删除:import React, { useEffect, useState } from "react"; | |
| 1 | 新增:import React, { useEffect, useRef, useState } from "react"; | |
| 2 | 2 | import { |
| 3 | 3 | Check, |
| 4 | 4 | ChevronDown, |
| @@ -7,13 +7,31 @@ import { | ||
| 7 | 7 | Monitor, |
| 8 | 8 | Moon, |
| 9 | 9 | Sun, |
| 10 | 新增: Upload, | |
| 11 | 新增: RotateCcw, | |
| 12 | 新增: CircleCheck, | |
| 13 | 新增: TriangleAlert, | |
| 14 | 新增: CircleX, | |
| 10 | 15 | } from "lucide-react"; |
| 11 | 删除:import { api } from "./api"; | |
| 16 | 新增:import { api, native, nativeAvailable } from "./api"; | |
| 12 | 17 | import { useAppearance } from "./appearance"; |
| 13 | 18 | import { |
| 14 | 删除: mix, | |
| 19 | 新增: colorGroups, | |
| 20 | 新增: colorTokens, | |
| 21 | 新增: terminalColorGroups, | |
| 22 | 新增: terminalTheme, | |
| 23 | 新增: customThemeLimit, | |
| 24 | 新增: themeFileLimit, | |
| 25 | 新增: parseThemeDocument, | |
| 26 | 新增: themeDocument, | |
| 27 | 新增: validateThemeName, | |
| 28 | 新增: sameTheme, | |
| 15 | 29 | presets, |
| 16 | 30 | presetNames, |
| 31 | 新增: presetInfo, | |
| 32 | 新增: presetGroups, | |
| 33 | 新增: themeCatalog, | |
| 34 | 新增: applyThemePreset, | |
| 17 | 35 | systemUIFont, |
| 18 | 36 | systemCodeFont, |
| 19 | 37 | themeVariables, |
| @@ -53,12 +71,73 @@ function FontSizeInput({ label, value, min, onChange }) { | ||
| 53 | 71 | </div> |
| 54 | 72 | ); |
| 55 | 73 | } |
| 74 | 新增:function ColorField({ label, value, onChange, onReset }) { | |
| 75 | 新增: const [text, setText] = useState(value); | |
| 76 | 新增: useEffect(() => setText(value), [value]); | |
| 77 | 新增: const invalid = !/^#[0-9a-fA-F]{6}$/.test(text); | |
| 78 | 新增: const commit = () => { | |
| 79 | 新增: if (!invalid && text !== value) onChange(text.toLowerCase()); | |
| 80 | 新增: }; | |
| 81 | 新增: return ( | |
| 82 | 新增: <div className="theme-color-field"> | |
| 83 | 新增: <span>{label.replace(/^(浅色|深色)主题(终端)?/, "")}</span> | |
| 84 | 新增: <div className="theme-color-value"> | |
| 85 | 新增: <input | |
| 86 | 新增: type="color" | |
| 87 | 新增: aria-label={label + "取色"} | |
| 88 | 新增: value={value} | |
| 89 | 新增: onChange={(e) => onChange(e.target.value)} | |
| 90 | 新增: /> | |
| 91 | 新增: <input | |
| 92 | 新增: type="text" | |
| 93 | 新增: aria-label={label} | |
| 94 | 新增: aria-invalid={invalid} | |
| 95 | 新增: value={text} | |
| 96 | 新增: maxLength={7} | |
| 97 | 新增: spellCheck={false} | |
| 98 | 新增: onChange={(e) => setText(e.target.value)} | |
| 99 | 新增: onBlur={commit} | |
| 100 | 新增: onKeyDown={(e) => { | |
| 101 | 新增: if (e.key === "Enter") { | |
| 102 | 新增: e.preventDefault(); | |
| 103 | 新增: commit(); | |
| 104 | 新增: } | |
| 105 | 新增: if (e.key === "Escape") { | |
| 106 | 新增: e.stopPropagation(); | |
| 107 | 新增: setText(value); | |
| 108 | 新增: } | |
| 109 | 新增: }} | |
| 110 | 新增: /> | |
| 111 | 新增: {onReset && ( | |
| 112 | 新增: <button | |
| 113 | 新增: className="icon-button" | |
| 114 | 新增: aria-label={label + "恢复自动"} | |
| 115 | 新增: title="恢复自动颜色" | |
| 116 | 新增: onClick={onReset} | |
| 117 | 新增: > | |
| 118 | 新增: <RotateCcw size={13} /> | |
| 119 | 新增: </button> | |
| 120 | 新增: )} | |
| 121 | 新增: </div> | |
| 122 | 新增: {invalid && ( | |
| 123 | 新增: <small className="theme-color-error">请输入 # 加六位十六进制颜色</small> | |
| 124 | 新增: )} | |
| 125 | 新增: </div> | |
| 126 | 新增: ); | |
| 127 | 新增:} | |
| 56 | 128 | function ThemeCard({ variant, value, active, onChange }) { |
| 57 | 129 | const [advanced, setAdvanced] = useState(false); |
| 58 | 130 | const label = variant === "light" ? "浅色主题" : "深色主题"; |
| 59 | 131 | const options = presets[variant]; |
| 60 | 删除: const patch = (delta) => onChange({ ...value, ...delta }); | |
| 132 | 新增: const patch = (delta) => onChange({ ...value, preset: "custom", ...delta }); | |
| 61 | 133 | const vars = themeVariables(value, variant); |
| 134 | 新增: const terminal = terminalTheme(value, variant); | |
| 135 | 新增: const setColor = (field, key, color) => { | |
| 136 | 新增: const next = { ...value[field] }; | |
| 137 | 新增: if (color === undefined) delete next[key]; | |
| 138 | 新增: else next[key] = color; | |
| 139 | 新增: patch({ [field]: next }); | |
| 140 | 新增: }; | |
| 62 | 141 | return ( |
| 63 | 142 | <section |
| 64 | 143 | className={`appearance-theme-card ${active ? "current" : ""}`} |
| @@ -71,16 +150,22 @@ function ThemeCard({ variant, value, active, onChange }) { | ||
| 71 | 150 | aria-label={label + "预设"} |
| 72 | 151 | value={value.preset} |
| 73 | 152 | onChange={(e) => |
| 74 | 删除: patch({ ...options[e.target.value], preset: e.target.value }) | |
| 153 | 新增: onChange(applyThemePreset(value, variant, e.target.value)) | |
| 75 | 154 | } |
| 76 | 155 | > |
| 77 | 删除: {Object.keys(options).map((key) => ( | |
| 78 | 删除: <option key={key} value={key}> | |
| 79 | 删除: {presetNames[key]} | |
| 80 | 删除: </option> | |
| 156 | 新增: {presetGroups.map((group) => ( | |
| 157 | 新增: <optgroup key={group} label={group}> | |
| 158 | 新增: {themeCatalog | |
| 159 | 新增: .filter((item) => item.group === group && options[item.id]) | |
| 160 | 新增: .map((item) => ( | |
| 161 | 新增: <option key={item.id} value={item.id}> | |
| 162 | 新增: {item.name} | |
| 163 | 新增: </option> | |
| 164 | 新增: ))} | |
| 165 | 新增: </optgroup> | |
| 81 | 166 | ))} |
| 82 | 167 | {!options[value.preset] && ( |
| 83 | 删除: <option value={value.preset}> | |
| 168 | 新增: <option value={value.preset} disabled> | |
| 84 | 169 | {presetNames[value.preset] || "自定义"} |
| 85 | 170 | </option> |
| 86 | 171 | )} |
| @@ -91,38 +176,58 @@ function ThemeCard({ variant, value, active, onChange }) { | ||
| 91 | 176 | aria-hidden="true" |
| 92 | 177 | style={{ ...vars, background: value.surface, color: value.ink }} |
| 93 | 178 | > |
| 94 | 删除: <div | |
| 95 | 删除: className="mini-sidebar" | |
| 96 | 删除: style={{ background: mix(value.surface, value.ink, 0.055) }} | |
| 97 | 删除: > | |
| 179 | 新增: <div className="mini-sidebar" style={{ background: vars["--sidebar"] }}> | |
| 98 | 180 | <i /> |
| 99 | 181 | <i /> |
| 100 | 182 | <i /> |
| 101 | 183 | </div> |
| 102 | 184 | <div className="mini-content"> |
| 103 | 删除: <span style={{ background: value.ink }} /> | |
| 185 | 新增: <span style={{ background: vars["--strong"] }} /> | |
| 104 | 186 | <span /> |
| 105 | 删除: <div style={{ borderColor: vars["--line"] }}> | |
| 187 | 新增: <div | |
| 188 | 新增: style={{ borderColor: vars["--line"], background: vars["--input"] }} | |
| 189 | 新增: > | |
| 106 | 190 | <i /> |
| 107 | 191 | <b style={{ background: value.accent }} /> |
| 108 | 192 | </div> |
| 109 | 193 | </div> |
| 110 | 194 | </div> |
| 111 | 删除: <div className="theme-colors"> | |
| 195 | 新增: <div className="theme-preset-summary"> | |
| 196 | 新增: <p> | |
| 197 | 新增: {presetInfo[value.preset]?.description || | |
| 198 | 新增: "自定义配色,可另存为主题以便下次使用。"} | |
| 199 | 新增: </p> | |
| 200 | 新增: <div | |
| 201 | 新增: className="theme-status-preview" | |
| 202 | 新增: aria-label={label + "状态配色预览"} | |
| 203 | 新增: style={{ background: value.surface }} | |
| 204 | 新增: > | |
| 205 | 新增: <span style={{ color: vars["--success"] }}> | |
| 206 | 新增: <CircleCheck size={13} /> | |
| 207 | 新增: 成功 | |
| 208 | 新增: </span> | |
| 209 | 新增: <span style={{ color: vars["--warning"] }}> | |
| 210 | 新增: <TriangleAlert size={13} /> | |
| 211 | 新增: 警告 | |
| 212 | 新增: </span> | |
| 213 | 新增: <span style={{ color: vars["--danger"] }}> | |
| 214 | 新增: <CircleX size={13} /> | |
| 215 | 新增: 错误 | |
| 216 | 新增: </span> | |
| 217 | 新增: </div> | |
| 218 | 新增: </div> | |
| 219 | 新增: <div className="theme-base-colors"> | |
| 112 | 220 | {[ |
| 113 | 221 | ["accent", "强调色"], |
| 114 | 222 | ["surface", "背景"], |
| 115 | 223 | ["ink", "文字"], |
| 116 | 224 | ].map(([key, name]) => ( |
| 117 | 删除: <label key={key}> | |
| 118 | 删除: <input | |
| 119 | 删除: type="color" | |
| 120 | 删除: aria-label={label + name} | |
| 121 | 删除: value={value[key]} | |
| 122 | 删除: onChange={(e) => patch({ [key]: e.target.value })} | |
| 123 | 删除: /> | |
| 124 | 删除: <span>{name}</span> | |
| 125 | 删除: </label> | |
| 225 | 新增: <ColorField | |
| 226 | 新增: key={key} | |
| 227 | 新增: label={label + name} | |
| 228 | 新增: value={value[key]} | |
| 229 | 新增: onChange={(color) => patch({ [key]: color })} | |
| 230 | 新增: /> | |
| 126 | 231 | ))} |
| 127 | 232 | </div> |
| 128 | 233 | <button |
| @@ -135,6 +240,68 @@ function ThemeCard({ variant, value, active, onChange }) { | ||
| 135 | 240 | </button> |
| 136 | 241 | {advanced && ( |
| 137 | 242 | <div className="theme-options"> |
| 243 | 新增: <p className="theme-options-hint"> | |
| 244 | 新增: 未单独设置的颜色随基础配色自动调整。 | |
| 245 | 新增: </p> | |
| 246 | 新增: {colorGroups.map((group) => ( | |
| 247 | 新增: <details className="theme-color-group" key={group.label}> | |
| 248 | 新增: <summary>{group.label}</summary> | |
| 249 | 新增: {group.entries.map(([key, name]) => ( | |
| 250 | 新增: <ColorField | |
| 251 | 新增: key={key} | |
| 252 | 新增: label={label + name} | |
| 253 | 新增: value={vars[colorTokens[key]]} | |
| 254 | 新增: onChange={(color) => setColor("colors", key, color)} | |
| 255 | 新增: onReset={ | |
| 256 | 新增: value.colors?.[key] | |
| 257 | 新增: ? () => setColor("colors", key) | |
| 258 | 新增: : undefined | |
| 259 | 新增: } | |
| 260 | 新增: /> | |
| 261 | 新增: ))} | |
| 262 | 新增: </details> | |
| 263 | 新增: ))} | |
| 264 | 新增: {terminalColorGroups.map((group) => ( | |
| 265 | 新增: <details className="theme-color-group" key={group.label}> | |
| 266 | 新增: <summary>{group.label}</summary> | |
| 267 | 新增: {group.entries.map(([key, name]) => ( | |
| 268 | 新增: <ColorField | |
| 269 | 新增: key={key} | |
| 270 | 新增: label={label + "终端" + name} | |
| 271 | 新增: value={terminal[key]} | |
| 272 | 新增: onChange={(color) => setColor("terminal", key, color)} | |
| 273 | 新增: onReset={ | |
| 274 | 新增: value.terminal?.[key] | |
| 275 | 新增: ? () => setColor("terminal", key) | |
| 276 | 新增: : undefined | |
| 277 | 新增: } | |
| 278 | 新增: /> | |
| 279 | 新增: ))} | |
| 280 | 新增: </details> | |
| 281 | 新增: ))} | |
| 282 | 新增: <div | |
| 283 | 新增: className="theme-terminal-preview" | |
| 284 | 新增: style={{ | |
| 285 | 新增: background: terminal.background, | |
| 286 | 新增: color: terminal.foreground, | |
| 287 | 新增: }} | |
| 288 | 新增: aria-label={label + "终端预览"} | |
| 289 | 新增: > | |
| 290 | 新增: <span style={{ color: terminal.green }}>~/cage</span> ${" "} | |
| 291 | 新增: <span style={{ color: terminal.blue }}>echo</span> hello | |
| 292 | 新增: <i style={{ background: terminal.cursor }} /> | |
| 293 | 新增: </div> | |
| 294 | 新增: <button | |
| 295 | 新增: className="theme-reset-colors" | |
| 296 | 新增: disabled={ | |
| 297 | 新增: !Object.keys(value.colors || {}).length && | |
| 298 | 新增: !Object.keys(value.terminal || {}).length | |
| 299 | 新增: } | |
| 300 | 新增: onClick={() => patch({ colors: {}, terminal: {} })} | |
| 301 | 新增: > | |
| 302 | 新增: <RotateCcw size={13} /> | |
| 303 | 新增: 恢复全部自动颜色 | |
| 304 | 新增: </button> | |
| 138 | 305 | <label> |
| 139 | 306 | 对比度 <output>{value.contrast}</output> |
| 140 | 307 | <input |
| @@ -185,12 +352,252 @@ function ThemeCard({ variant, value, active, onChange }) { | ||
| 185 | 352 | </section> |
| 186 | 353 | ); |
| 187 | 354 | } |
| 355 | 新增:function ThemeLibrary({ appearance, update, saving, onError }) { | |
| 356 | 新增: const themes = appearance.customThemes; | |
| 357 | 新增: const matching = themes.find((item) => sameTheme(item, appearance)); | |
| 358 | 新增: const [selectedId, setSelectedId] = useState(matching?.id || ""); | |
| 359 | 新增: const [name, setName] = useState(matching?.name || ""); | |
| 360 | 新增: const [busy, setBusy] = useState(false); | |
| 361 | 新增: const [notice, setNotice] = useState(""); | |
| 362 | 新增: const input = useRef(null); | |
| 363 | 新增: const selected = themes.find((item) => item.id === selectedId); | |
| 364 | 新增: const current = selected || matching; | |
| 365 | 新增: const dirty = current && !sameTheme(current, appearance); | |
| 366 | 新增: const run = async (task) => { | |
| 367 | 新增: setBusy(true); | |
| 368 | 新增: setNotice(""); | |
| 369 | 新增: onError(""); | |
| 370 | 新增: try { | |
| 371 | 新增: await task(); | |
| 372 | 新增: } catch (e) { | |
| 373 | 新增: onError(e.message); | |
| 374 | 新增: } finally { | |
| 375 | 新增: setBusy(false); | |
| 376 | 新增: } | |
| 377 | 新增: }; | |
| 378 | 新增: const apply = (item) => { | |
| 379 | 新增: setSelectedId(item.id); | |
| 380 | 新增: setName(item.name); | |
| 381 | 新增: setNotice(""); | |
| 382 | 新增: onError(""); | |
| 383 | 新增: void update((previous) => ({ | |
| 384 | 新增: ...previous, | |
| 385 | 新增: lightTheme: structuredClone(item.lightTheme), | |
| 386 | 新增: darkTheme: structuredClone(item.darkTheme), | |
| 387 | 新增: })); | |
| 388 | 新增: }; | |
| 389 | 新增: const save = (replace) => | |
| 390 | 新增: run(async () => { | |
| 391 | 新增: const title = validateThemeName(name); | |
| 392 | 新增: if (!replace && themes.length >= customThemeLimit) | |
| 393 | 新增: throw new Error("最多保存 50 个自定义主题,请先删除不需要的主题"); | |
| 394 | 新增: const document = themeDocument(title, appearance); | |
| 395 | 新增: const item = { | |
| 396 | 新增: id: replace ? current.id : crypto.randomUUID(), | |
| 397 | 新增: name: title, | |
| 398 | 新增: lightTheme: document.lightTheme, | |
| 399 | 新增: darkTheme: document.darkTheme, | |
| 400 | 新增: }; | |
| 401 | 新增: if ( | |
| 402 | 新增: await update((previous) => ({ | |
| 403 | 新增: ...previous, | |
| 404 | 新增: customThemes: replace | |
| 405 | 新增: ? previous.customThemes.map((old) => | |
| 406 | 新增: old.id === item.id ? item : old, | |
| 407 | 新增: ) | |
| 408 | 新增: : [...previous.customThemes, item], | |
| 409 | 新增: })) | |
| 410 | 新增: ) { | |
| 411 | 新增: setSelectedId(item.id); | |
| 412 | 新增: setName(title); | |
| 413 | 新增: setNotice("主题已保存"); | |
| 414 | 新增: } | |
| 415 | 新增: }); | |
| 416 | 新增: const importText = async (text) => { | |
| 417 | 新增: const document = parseThemeDocument(text); | |
| 418 | 新增: if (themes.length >= customThemeLimit) | |
| 419 | 新增: throw new Error("最多保存 50 个自定义主题,请先删除不需要的主题"); | |
| 420 | 新增: const item = { | |
| 421 | 新增: id: crypto.randomUUID(), | |
| 422 | 新增: name: document.name, | |
| 423 | 新增: lightTheme: document.lightTheme, | |
| 424 | 新增: darkTheme: document.darkTheme, | |
| 425 | 新增: }; | |
| 426 | 新增: if ( | |
| 427 | 新增: await update((previous) => ({ | |
| 428 | 新增: ...previous, | |
| 429 | 新增: lightTheme: item.lightTheme, | |
| 430 | 新增: darkTheme: item.darkTheme, | |
| 431 | 新增: customThemes: [...previous.customThemes, item], | |
| 432 | 新增: })) | |
| 433 | 新增: ) { | |
| 434 | 新增: setSelectedId(item.id); | |
| 435 | 新增: setName(item.name); | |
| 436 | 新增: setNotice("主题已导入并应用"); | |
| 437 | 新增: } | |
| 438 | 新增: }; | |
| 439 | 新增: const importFile = () => { | |
| 440 | 新增: if (!nativeAvailable()) { | |
| 441 | 新增: input.current.click(); | |
| 442 | 新增: return; | |
| 443 | 新增: } | |
| 444 | 新增: void run(async () => { | |
| 445 | 新增: const text = await native("importTheme"); | |
| 446 | 新增: if (text) await importText(text); | |
| 447 | 新增: }); | |
| 448 | 新增: }; | |
| 449 | 新增: const exportFile = () => | |
| 450 | 新增: run(async () => { | |
| 451 | 新增: const title = name.trim() || matching?.name || "我的主题"; | |
| 452 | 新增: const text = | |
| 453 | 新增: JSON.stringify(themeDocument(title, appearance), null, 2) + "\n"; | |
| 454 | 新增: const filename = | |
| 455 | 新增: title | |
| 456 | 新增: .replace(/[<>:"/\\|?*\x00-\x1f]/g, "_") | |
| 457 | 新增: .replace(/[. ]+$/, "") | |
| 458 | 新增: .slice(0, 80) + ".cage-theme.json"; | |
| 459 | 新增: if (nativeAvailable()) { | |
| 460 | 新增: if (await native("exportTheme", { text, filename })) | |
| 461 | 新增: setNotice("主题已导出"); | |
| 462 | 新增: } else { | |
| 463 | 新增: const url = URL.createObjectURL( | |
| 464 | 新增: new Blob([text], { type: "application/json" }), | |
| 465 | 新增: ); | |
| 466 | 新增: const link = document.createElement("a"); | |
| 467 | 新增: link.href = url; | |
| 468 | 新增: link.download = filename; | |
| 469 | 新增: document.body.append(link); | |
| 470 | 新增: link.click(); | |
| 471 | 新增: link.remove(); | |
| 472 | 新增: setTimeout(() => URL.revokeObjectURL(url), 1000); | |
| 473 | 新增: setNotice("已开始下载主题文件"); | |
| 474 | 新增: } | |
| 475 | 新增: }); | |
| 476 | 新增: return ( | |
| 477 | 新增: <section className="theme-library" aria-label="我的主题"> | |
| 478 | 新增: <div className="theme-library-heading"> | |
| 479 | 新增: <div> | |
| 480 | 新增: <h4>我的主题</h4> | |
| 481 | 新增: <p>保存浅色、深色两套配色与字体,随时切换或分享。</p> | |
| 482 | 新增: </div> | |
| 483 | 新增: <div className="theme-file-actions"> | |
| 484 | 新增: <button disabled={busy || saving} onClick={importFile}> | |
| 485 | 新增: <Upload size={14} /> | |
| 486 | 新增: 导入主题 | |
| 487 | 新增: </button> | |
| 488 | 新增: <button disabled={busy} onClick={exportFile}> | |
| 489 | 新增: <Download size={14} /> | |
| 490 | 新增: 导出主题 | |
| 491 | 新增: </button> | |
| 492 | 新增: </div> | |
| 493 | 新增: </div> | |
| 494 | 新增: <input | |
| 495 | 新增: ref={input} | |
| 496 | 新增: type="file" | |
| 497 | 新增: accept=".json,application/json" | |
| 498 | 新增: hidden | |
| 499 | 新增: aria-label="选择主题文件" | |
| 500 | 新增: onChange={(e) => { | |
| 501 | 新增: const file = e.target.files?.[0]; | |
| 502 | 新增: e.target.value = ""; | |
| 503 | 新增: if (file) | |
| 504 | 新增: void run(async () => { | |
| 505 | 新增: if (file.size > themeFileLimit) | |
| 506 | 新增: throw new Error("主题文件不能超过 256 KB"); | |
| 507 | 新增: await importText(await file.text()); | |
| 508 | 新增: }); | |
| 509 | 新增: }} | |
| 510 | 新增: /> | |
| 511 | 新增: <div className="theme-library-fields"> | |
| 512 | 新增: <select | |
| 513 | 新增: aria-label="已保存的主题" | |
| 514 | 新增: value={current?.id || ""} | |
| 515 | 新增: disabled={busy || saving} | |
| 516 | 新增: onChange={(e) => { | |
| 517 | 新增: const item = themes.find((theme) => theme.id === e.target.value); | |
| 518 | 新增: if (item) apply(item); | |
| 519 | 新增: }} | |
| 520 | 新增: > | |
| 521 | 新增: <option value="" disabled> | |
| 522 | 新增: {themes.length ? "选择已保存的主题" : "尚无自定义主题"} | |
| 523 | 新增: </option> | |
| 524 | 新增: {themes.map((item) => ( | |
| 525 | 新增: <option key={item.id} value={item.id}> | |
| 526 | 新增: {item.name} | |
| 527 | 新增: {item.id === current?.id && dirty ? " · 已修改" : ""} | |
| 528 | 新增: </option> | |
| 529 | 新增: ))} | |
| 530 | 新增: </select> | |
| 531 | 新增: <input | |
| 532 | 新增: aria-label="主题名称" | |
| 533 | 新增: placeholder="为当前配色命名" | |
| 534 | 新增: value={name} | |
| 535 | 新增: maxLength={80} | |
| 536 | 新增: onChange={(e) => setName(e.target.value)} | |
| 537 | 新增: /> | |
| 538 | 新增: <button | |
| 539 | 新增: disabled={busy || saving || !name.trim()} | |
| 540 | 新增: onClick={() => save(false)} | |
| 541 | 新增: > | |
| 542 | 新增: 另存为主题 | |
| 543 | 新增: </button> | |
| 544 | 新增: </div> | |
| 545 | 新增: {current && ( | |
| 546 | 新增: <div className="theme-library-manage"> | |
| 547 | 新增: <span> | |
| 548 | 新增: {dirty ? "当前配色有未存入主题的修改" : "当前配色与已保存主题一致"} | |
| 549 | 新增: </span> | |
| 550 | 新增: {dirty && ( | |
| 551 | 新增: <button disabled={busy || saving} onClick={() => apply(current)}> | |
| 552 | 新增: 恢复已保存配色 | |
| 553 | 新增: </button> | |
| 554 | 新增: )} | |
| 555 | 新增: <button | |
| 556 | 新增: disabled={busy || saving || !name.trim()} | |
| 557 | 新增: onClick={() => save(true)} | |
| 558 | 新增: > | |
| 559 | 新增: 更新此主题 | |
| 560 | 新增: </button> | |
| 561 | 新增: <button | |
| 562 | 新增: disabled={busy || saving} | |
| 563 | 新增: onClick={() => | |
| 564 | 新增: run(async () => { | |
| 565 | 新增: if (!confirm(`删除主题“${current.name}”?当前配色会保留。`)) | |
| 566 | 新增: return; | |
| 567 | 新增: if ( | |
| 568 | 新增: await update((previous) => ({ | |
| 569 | 新增: ...previous, | |
| 570 | 新增: customThemes: previous.customThemes.filter( | |
| 571 | 新增: (item) => item.id !== current.id, | |
| 572 | 新增: ), | |
| 573 | 新增: })) | |
| 574 | 新增: ) { | |
| 575 | 新增: setSelectedId(""); | |
| 576 | 新增: setName(""); | |
| 577 | 新增: setNotice("主题已删除,当前配色已保留"); | |
| 578 | 新增: } | |
| 579 | 新增: }) | |
| 580 | 新增: } | |
| 581 | 新增: > | |
| 582 | 新增: 删除 | |
| 583 | 新增: </button> | |
| 584 | 新增: </div> | |
| 585 | 新增: )} | |
| 586 | 新增: {notice && ( | |
| 587 | 新增: <p className="theme-library-notice" role="status"> | |
| 588 | 新增: {notice} | |
| 589 | 新增: </p> | |
| 590 | 新增: )} | |
| 591 | 新增: </section> | |
| 592 | 新增: ); | |
| 593 | 新增:} | |
| 188 | 594 | export function AppearanceSettings() { |
| 189 | 595 | const { appearance, theme, variant, loading, saving, error, update, retry } = |
| 190 | 596 | useAppearance(); |
| 191 | 597 | const [syncing, setSyncing] = useState(false), |
| 192 | 598 | [syncError, setSyncError] = useState(""), |
| 193 | 删除: [synced, setSynced] = useState(false); | |
| 599 | 新增: [synced, setSynced] = useState(false), | |
| 600 | 新增: [themeError, setThemeError] = useState(""); | |
| 194 | 601 | const patch = (delta) => update((previous) => ({ ...previous, ...delta })); |
| 195 | 602 | const sync = async () => { |
| 196 | 603 | setSyncing(true); |
| @@ -198,8 +605,13 @@ export function AppearanceSettings() { | ||
| 198 | 605 | setSynced(false); |
| 199 | 606 | try { |
| 200 | 607 | const value = await api("/appearance/codex"); |
| 201 | 删除: await update(value); | |
| 202 | 删除: setSynced(true); | |
| 608 | 新增: if ( | |
| 609 | 新增: await update((previous) => ({ | |
| 610 | 新增: ...value, | |
| 611 | 新增: customThemes: previous.customThemes, | |
| 612 | 新增: })) | |
| 613 | 新增: ) | |
| 614 | 新增: setSynced(true); | |
| 203 | 615 | } catch (e) { |
| 204 | 616 | setSyncError(e.message); |
| 205 | 617 | } finally { |
| @@ -234,6 +646,18 @@ export function AppearanceSettings() { | ||
| 234 | 646 | ))} |
| 235 | 647 | </div> |
| 236 | 648 | </SettingRow> |
| 649 | 新增: <ThemeLibrary | |
| 650 | 新增: key={String(loading)} | |
| 651 | 新增: appearance={appearance} | |
| 652 | 新增: update={update} | |
| 653 | 新增: saving={saving} | |
| 654 | 新增: onError={setThemeError} | |
| 655 | 新增: /> | |
| 656 | 新增: {themeError && ( | |
| 657 | 新增: <div className="error-message" role="alert"> | |
| 658 | 新增: {themeError} | |
| 659 | 新增: </div> | |
| 660 | 新增: )} | |
| 237 | 661 | <div className="theme-card-grid"> |
| 238 | 662 | {["light", "dark"].map((key) => ( |
| 239 | 663 | <ThemeCard |
| @@ -1,48 +1,17 @@ | ||
| 1 | 1 | export const systemUIFont = |
| 2 | 2 | '-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", sans-serif'; |
| 3 | 3 | export const systemCodeFont = '"SF Mono", Menlo, Consolas, monospace'; |
| 4 | 删除:export const presets = { | |
| 5 | 删除: light: { | |
| 6 | 删除: codex: { | |
| 7 | 删除: accent: "#339cff", | |
| 8 | 删除: surface: "#ffffff", | |
| 9 | 删除: ink: "#1a1c1f", | |
| 10 | 删除: contrast: 45, | |
| 11 | 删除: }, | |
| 12 | 删除: solarized: { | |
| 13 | 删除: accent: "#b58900", | |
| 14 | 删除: surface: "#fdf6e3", | |
| 15 | 删除: ink: "#657b83", | |
| 16 | 删除: contrast: 45, | |
| 17 | 删除: }, | |
| 18 | 删除: }, | |
| 19 | 删除: dark: { | |
| 20 | 删除: codex: { | |
| 21 | 删除: accent: "#339cff", | |
| 22 | 删除: surface: "#181818", | |
| 23 | 删除: ink: "#ffffff", | |
| 24 | 删除: contrast: 60, | |
| 25 | 删除: }, | |
| 26 | 删除: ayu: { | |
| 27 | 删除: accent: "#e6b450", | |
| 28 | 删除: surface: "#10141c", | |
| 29 | 删除: ink: "#bfbdb6", | |
| 30 | 删除: contrast: 60, | |
| 31 | 删除: }, | |
| 32 | 删除: solarized: { | |
| 33 | 删除: accent: "#b58900", | |
| 34 | 删除: surface: "#002b36", | |
| 35 | 删除: ink: "#93a1a1", | |
| 36 | 删除: contrast: 60, | |
| 37 | 删除: }, | |
| 38 | 删除: }, | |
| 39 | 删除:}; | |
| 40 | 删除:export const presetNames = { | |
| 41 | 删除: codex: "Codex", | |
| 42 | 删除: solarized: "Solarized", | |
| 43 | 删除: ayu: "Ayu", | |
| 44 | 删除:}; | |
| 4 | 新增:import { presets } from "./appearance-presets.mjs"; | |
| 5 | 新增:export { | |
| 6 | 新增: presets, | |
| 7 | 新增: presetNames, | |
| 8 | 新增: presetGroups, | |
| 9 | 新增: presetInfo, | |
| 10 | 新增: themeCatalog, | |
| 11 | 新增: applyThemePreset, | |
| 12 | 新增:} from "./appearance-presets.mjs"; | |
| 45 | 13 | export const defaultAppearance = { |
| 14 | 新增: customThemes: [], | |
| 46 | 15 | mode: "system", |
| 47 | 16 | lightTheme: { |
| 48 | 17 | ...presets.light.codex, |
| @@ -63,12 +32,16 @@ export const defaultAppearance = { | ||
| 63 | 32 | reducedMotion: "system", |
| 64 | 33 | }; |
| 65 | 34 | export function normalizeAppearance(value = {}) { |
| 35 | 新增: value = value && typeof value === "object" ? value : {}; | |
| 66 | 36 | return { |
| 67 | 37 | ...defaultAppearance, |
| 68 | 38 | ...value, |
| 39 | 新增: customThemes: Array.isArray(value.customThemes) ? value.customThemes : [], | |
| 69 | 40 | lightTheme: { |
| 70 | 41 | ...defaultAppearance.lightTheme, |
| 71 | 42 | ...value.lightTheme, |
| 43 | 新增: colors: { ...value.lightTheme?.colors }, | |
| 44 | 新增: terminal: { ...value.lightTheme?.terminal }, | |
| 72 | 45 | fonts: { |
| 73 | 46 | ...defaultAppearance.lightTheme.fonts, |
| 74 | 47 | ...value.lightTheme?.fonts, |
| @@ -77,6 +50,8 @@ export function normalizeAppearance(value = {}) { | ||
| 77 | 50 | darkTheme: { |
| 78 | 51 | ...defaultAppearance.darkTheme, |
| 79 | 52 | ...value.darkTheme, |
| 53 | 新增: colors: { ...value.darkTheme?.colors }, | |
| 54 | 新增: terminal: { ...value.darkTheme?.terminal }, | |
| 80 | 55 | fonts: { |
| 81 | 56 | ...defaultAppearance.darkTheme.fonts, |
| 82 | 57 | ...value.darkTheme?.fonts, |
| @@ -110,7 +85,7 @@ export function themeVariables(theme, variant) { | ||
| 110 | 85 | const { surface, ink, accent, contrast } = theme; |
| 111 | 86 | const chrome = mix(surface, ink, 0.025 + contrast * 0.00055); |
| 112 | 87 | const line = mix(surface, ink, 0.09 + contrast * 0.0013); |
| 113 | 删除: return { | |
| 88 | 新增: const variables = { | |
| 114 | 89 | "--paper": surface, |
| 115 | 90 | "--chrome": chrome, |
| 116 | 91 | "--chrome-dark": mix(surface, ink, 0.1), |
| @@ -129,17 +104,32 @@ export function themeVariables(theme, variant) { | ||
| 129 | 104 | "--link": accent, |
| 130 | 105 | "--success": variant === "dark" ? "#70bf56" : "#357c3c", |
| 131 | 106 | "--danger": variant === "dark" ? "#f26d78" : "#bb3535", |
| 107 | 新增: "--warning": variant === "dark" ? "#e6b450" : "#af7a22", | |
| 108 | 新增: "--inactive": "#a3a3a3", | |
| 132 | 109 | "--ui-font-family": theme.fonts.ui || systemUIFont, |
| 133 | 110 | "--code-font-family": theme.fonts.code || systemCodeFont, |
| 134 | 111 | "--accent-ink": luminance(accent) > 0.4 ? "#111111" : "#ffffff", |
| 135 | 112 | }; |
| 113 | 新增: for (const [key, value] of Object.entries(theme.colors || {})) { | |
| 114 | 新增: if (colorTokens[key]) variables[colorTokens[key]] = value; | |
| 115 | 新增: } | |
| 116 | 新增: variables["--sidebar"] = theme.colors?.sidebar || variables["--chrome"]; | |
| 117 | 新增: variables["--sidebar-ink"] = theme.colors?.sidebarInk || ink; | |
| 118 | 新增: variables["--toolbar"] = theme.colors?.toolbar || surface; | |
| 119 | 新增: variables["--toolbar-ink"] = theme.colors?.toolbarInk || ink; | |
| 120 | 新增: // Shared components also use these aliases. | |
| 121 | 新增: variables["--border"] = variables["--line"]; | |
| 122 | 新增: variables["--surface"] = variables["--paper"]; | |
| 123 | 新增: return variables; | |
| 136 | 124 | } |
| 137 | 125 | export function terminalTheme(theme, variant) { |
| 126 | 新增: const vars = themeVariables(theme, variant); | |
| 138 | 127 | return { |
| 139 | 128 | background: theme.surface, |
| 140 | 129 | foreground: theme.ink, |
| 141 | 130 | cursor: theme.ink, |
| 142 | 删除: selectionBackground: mix(theme.surface, theme.accent, 0.32), | |
| 131 | 新增: cursorAccent: theme.surface, | |
| 132 | 新增: selectionBackground: vars["--selection"], | |
| 143 | 133 | black: variant === "dark" ? "#202020" : "#242424", |
| 144 | 134 | red: variant === "dark" ? "#f26d78" : "#c43d3d", |
| 145 | 135 | green: variant === "dark" ? "#aad94c" : "#4b7b23", |
| @@ -156,5 +146,210 @@ export function terminalTheme(theme, variant) { | ||
| 156 | 146 | brightMagenta: "#d4bfff", |
| 157 | 147 | brightCyan: "#95e6cb", |
| 158 | 148 | brightWhite: "#ffffff", |
| 149 | 新增: ...theme.terminal, | |
| 150 | 新增: }; | |
| 151 | 新增:} | |
| 152 | 新增: | |
| 153 | 新增:// Optional overrides keep unedited colors linked to the three base colors. | |
| 154 | 新增:export const colorGroups = [ | |
| 155 | 新增: { | |
| 156 | 新增: label: "界面与层级", | |
| 157 | 新增: entries: [ | |
| 158 | 新增: ["chrome", "面板背景"], | |
| 159 | 新增: ["sidebar", "侧栏背景"], | |
| 160 | 新增: ["sidebarInk", "侧栏文字"], | |
| 161 | 新增: ["toolbar", "工具栏背景"], | |
| 162 | 新增: ["toolbarInk", "工具栏文字"], | |
| 163 | 新增: ["chromeDark", "次级背景"], | |
| 164 | 新增: ["strong", "标题文字"], | |
| 165 | 新增: ["muted", "辅助文字"], | |
| 166 | 新增: ["line", "边框与分隔线"], | |
| 167 | 新增: ["input", "输入框背景"], | |
| 168 | 新增: ], | |
| 169 | 新增: }, | |
| 170 | 新增: { | |
| 171 | 新增: label: "按钮与交互", | |
| 172 | 新增: entries: [ | |
| 173 | 新增: ["button", "主按钮背景"], | |
| 174 | 新增: ["buttonInk", "主按钮文字"], | |
| 175 | 新增: ["accentInk", "强调色上的文字"], | |
| 176 | 新增: ["link", "链接"], | |
| 177 | 新增: ["focus", "焦点边框"], | |
| 178 | 新增: ["hover", "悬停背景"], | |
| 179 | 新增: ["selected", "选中背景"], | |
| 180 | 新增: ["selection", "文本选区"], | |
| 181 | 新增: ], | |
| 182 | 新增: }, | |
| 183 | 新增: { | |
| 184 | 新增: label: "状态提示", | |
| 185 | 新增: entries: [ | |
| 186 | 新增: ["success", "成功状态"], | |
| 187 | 新增: ["warning", "警告状态"], | |
| 188 | 新增: ["danger", "错误状态"], | |
| 189 | 新增: ["inactive", "未启动状态"], | |
| 190 | 新增: ], | |
| 191 | 新增: }, | |
| 192 | 新增:]; | |
| 193 | 新增:export const colorTokens = Object.fromEntries( | |
| 194 | 新增: colorGroups.flatMap((group) => | |
| 195 | 新增: group.entries.map(([key]) => [ | |
| 196 | 新增: key, | |
| 197 | 新增: "--" + key.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()), | |
| 198 | 新增: ]), | |
| 199 | 新增: ), | |
| 200 | 新增:); | |
| 201 | 新增:export const terminalColorGroups = [ | |
| 202 | 新增: { | |
| 203 | 新增: label: "终端", | |
| 204 | 新增: entries: [ | |
| 205 | 新增: ["background", "背景"], | |
| 206 | 新增: ["foreground", "文字"], | |
| 207 | 新增: ["cursor", "光标"], | |
| 208 | 新增: ["cursorAccent", "光标内文字"], | |
| 209 | 新增: ["selectionBackground", "选区背景"], | |
| 210 | 新增: ], | |
| 211 | 新增: }, | |
| 212 | 新增: { | |
| 213 | 新增: label: "终端 ANSI 配色", | |
| 214 | 新增: entries: [ | |
| 215 | 新增: ["black", "黑色"], | |
| 216 | 新增: ["red", "红色"], | |
| 217 | 新增: ["green", "绿色"], | |
| 218 | 新增: ["yellow", "黄色"], | |
| 219 | 新增: ["blue", "蓝色"], | |
| 220 | 新增: ["magenta", "品红"], | |
| 221 | 新增: ["cyan", "青色"], | |
| 222 | 新增: ["white", "白色"], | |
| 223 | 新增: ["brightBlack", "亮黑"], | |
| 224 | 新增: ["brightRed", "亮红"], | |
| 225 | 新增: ["brightGreen", "亮绿"], | |
| 226 | 新增: ["brightYellow", "亮黄"], | |
| 227 | 新增: ["brightBlue", "亮蓝"], | |
| 228 | 新增: ["brightMagenta", "亮品红"], | |
| 229 | 新增: ["brightCyan", "亮青"], | |
| 230 | 新增: ["brightWhite", "亮白"], | |
| 231 | 新增: ], | |
| 232 | 新增: }, | |
| 233 | 新增:]; | |
| 234 | 新增:export const themeFileLimit = 256 * 1024; | |
| 235 | 新增:export const customThemeLimit = 50; | |
| 236 | 新增:const hexColor = /^#[0-9a-fA-F]{6}$/; | |
| 237 | 新增:const object = (value) => | |
| 238 | 新增: value !== null && typeof value === "object" && !Array.isArray(value); | |
| 239 | 新增:export function validateTheme(theme) { | |
| 240 | 新增: if (!object(theme)) throw new Error("主题缺少浅色或深色配置"); | |
| 241 | 新增: const allowed = [ | |
| 242 | 新增: "preset", | |
| 243 | 新增: "accent", | |
| 244 | 新增: "surface", | |
| 245 | 新增: "ink", | |
| 246 | 新增: "contrast", | |
| 247 | 新增: "opaqueWindows", | |
| 248 | 新增: "fonts", | |
| 249 | 新增: "colors", | |
| 250 | 新增: "terminal", | |
| 251 | 新增: ]; | |
| 252 | 新增: if (Object.keys(theme).some((key) => !allowed.includes(key))) | |
| 253 | 新增: throw new Error("主题包含不支持的设置"); | |
| 254 | 新增: if ( | |
| 255 | 新增: ![theme.accent, theme.surface, theme.ink].every( | |
| 256 | 新增: (value) => typeof value === "string" && hexColor.test(value), | |
| 257 | 新增: ) | |
| 258 | 新增: ) | |
| 259 | 新增: throw new Error("颜色须为六位十六进制值,例如 #fdf6e3"); | |
| 260 | 新增: if ( | |
| 261 | 新增: typeof theme.preset !== "string" || | |
| 262 | 新增: theme.preset.length > 80 || | |
| 263 | 新增: !Number.isInteger(theme.contrast) || | |
| 264 | 新增: theme.contrast < 0 || | |
| 265 | 新增: theme.contrast > 100 || | |
| 266 | 新增: typeof theme.opaqueWindows !== "boolean" | |
| 267 | 新增: ) | |
| 268 | 新增: throw new Error("主题配置无效"); | |
| 269 | 新增: if ( | |
| 270 | 新增: !object(theme.fonts) || | |
| 271 | 新增: Object.keys(theme.fonts).some((key) => !["ui", "code"].includes(key)) || | |
| 272 | 新增: [theme.fonts.ui, theme.fonts.code].some( | |
| 273 | 新增: (font) => | |
| 274 | 新增: typeof font !== "string" || | |
| 275 | 新增: font.length > 200 || | |
| 276 | 新增: /[;{}<>\r\n]/.test(font), | |
| 277 | 新增: ) | |
| 278 | 新增: ) | |
| 279 | 新增: throw new Error("字体名称无效"); | |
| 280 | 新增: for (const [field, keys] of [ | |
| 281 | 新增: ["colors", Object.keys(colorTokens)], | |
| 282 | 新增: [ | |
| 283 | 新增: "terminal", | |
| 284 | 新增: terminalColorGroups.flatMap((group) => group.entries.map(([key]) => key)), | |
| 285 | 新增: ], | |
| 286 | 新增: ]) { | |
| 287 | 新增: if (theme[field] === undefined) continue; | |
| 288 | 新增: if ( | |
| 289 | 新增: !object(theme[field]) || | |
| 290 | 新增: Object.entries(theme[field]).some( | |
| 291 | 新增: ([key, value]) => | |
| 292 | 新增: !keys.includes(key) || | |
| 293 | 新增: typeof value !== "string" || | |
| 294 | 新增: !hexColor.test(value), | |
| 295 | 新增: ) | |
| 296 | 新增: ) | |
| 297 | 新增: throw new Error("元素颜色无效或包含不支持的颜色项目"); | |
| 298 | 新增: } | |
| 299 | 新增: return structuredClone(theme); | |
| 300 | 新增:} | |
| 301 | 新增:export function validateThemeName(name) { | |
| 302 | 新增: if (typeof name !== "string" || !name.trim() || name.trim().length > 80) | |
| 303 | 新增: throw new Error("请输入 1–80 个字符的主题名称"); | |
| 304 | 新增: return name.trim(); | |
| 305 | 新增:} | |
| 306 | 新增:export function themeDocument(name, appearance) { | |
| 307 | 新增: return { | |
| 308 | 新增: format: "cage-theme", | |
| 309 | 新增: version: 1, | |
| 310 | 新增: name: validateThemeName(name), | |
| 311 | 新增: lightTheme: validateTheme(appearance.lightTheme), | |
| 312 | 新增: darkTheme: validateTheme(appearance.darkTheme), | |
| 313 | 新增: }; | |
| 314 | 新增:} | |
| 315 | 新增:export function parseThemeDocument(text) { | |
| 316 | 新增: if (new TextEncoder().encode(text).length > themeFileLimit) | |
| 317 | 新增: throw new Error("主题文件不能超过 256 KB"); | |
| 318 | 新增: let data; | |
| 319 | 新增: try { | |
| 320 | 新增: data = JSON.parse(text); | |
| 321 | 新增: } catch { | |
| 322 | 新增: throw new Error("无法读取主题,请选择有效的 JSON 文件"); | |
| 323 | 新增: } | |
| 324 | 新增: if (!object(data) || data.format !== "cage-theme" || data.version !== 1) | |
| 325 | 新增: throw new Error("不支持的主题格式或版本,请使用 Cage 导出的主题文件"); | |
| 326 | 新增: if ( | |
| 327 | 新增: Object.keys(data).some( | |
| 328 | 新增: (key) => | |
| 329 | 新增: !["format", "version", "name", "lightTheme", "darkTheme"].includes(key), | |
| 330 | 新增: ) | |
| 331 | 新增: ) | |
| 332 | 新增: throw new Error("主题文件包含不支持的设置"); | |
| 333 | 新增: return themeDocument(data.name, data); | |
| 334 | 新增:} | |
| 335 | 新增:export function sameTheme(left, right) { | |
| 336 | 新增: const canonical = (theme) => { | |
| 337 | 新增: const valid = validateTheme(theme); | |
| 338 | 新增: return JSON.stringify([ | |
| 339 | 新增: valid.preset, | |
| 340 | 新增: valid.accent, | |
| 341 | 新增: valid.surface, | |
| 342 | 新增: valid.ink, | |
| 343 | 新增: valid.contrast, | |
| 344 | 新增: valid.opaqueWindows, | |
| 345 | 新增: valid.fonts.ui, | |
| 346 | 新增: valid.fonts.code, | |
| 347 | 新增: Object.entries(valid.colors || {}).sort(), | |
| 348 | 新增: Object.entries(valid.terminal || {}).sort(), | |
| 349 | 新增: ]); | |
| 159 | 350 | }; |
| 351 | 新增: return ( | |
| 352 | 新增: canonical(left.lightTheme) === canonical(right.lightTheme) && | |
| 353 | 新增: canonical(left.darkTheme) === canonical(right.darkTheme) | |
| 354 | 新增: ); | |
| 160 | 355 | } |
| @@ -0,0 +1,255 @@ | ||
| 1 | 新增:import test from "node:test"; | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增:import { | |
| 4 | 新增: defaultAppearance, | |
| 5 | 新增: normalizeAppearance, | |
| 6 | 新增: themeVariables, | |
| 7 | 新增: terminalTheme, | |
| 8 | 新增: themeDocument, | |
| 9 | 新增: parseThemeDocument, | |
| 10 | 新增: sameTheme, | |
| 11 | 新增: colorGroups, | |
| 12 | 新增: terminalColorGroups, | |
| 13 | 新增:} from "./appearance-state.mjs"; | |
| 14 | 新增: | |
| 15 | 新增:test("element overrides stay independent, reset returns to derived colors, and terminal follows live values", () => { | |
| 16 | 新增: const appearance = normalizeAppearance(structuredClone(defaultAppearance)); | |
| 17 | 新增: const theme = appearance.lightTheme; | |
| 18 | 新增: const before = themeVariables(theme, "light"); | |
| 19 | 新增: theme.colors = { | |
| 20 | 新增: chrome: "#123456", | |
| 21 | 新增: button: "#654321", | |
| 22 | 新增: buttonInk: "#abcdef", | |
| 23 | 新增: selection: "#aabbcc", | |
| 24 | 新增: }; | |
| 25 | 新增: theme.terminal = { background: "#112233", red: "#fedcba", cursor: "#445566" }; | |
| 26 | 新增: theme.surface = "#fafafa"; | |
| 27 | 新增: const vars = themeVariables(theme, "light"); | |
| 28 | 新增: assert.equal(vars["--chrome"], "#123456"); | |
| 29 | 新增: assert.equal(vars["--button-ink"], "#abcdef"); | |
| 30 | 新增: assert.equal(vars["--surface"], "#fafafa"); | |
| 31 | 新增: assert.equal(vars["--border"], vars["--line"]); | |
| 32 | 新增: assert.notEqual(vars["--line"], before["--line"]); | |
| 33 | 新增: const terminal = terminalTheme(theme, "light"); | |
| 34 | 新增: assert.equal(terminal.background, "#112233"); | |
| 35 | 新增: assert.equal(terminal.red, "#fedcba"); | |
| 36 | 新增: assert.equal(terminal.selectionBackground, "#aabbcc"); | |
| 37 | 新增: delete theme.colors.chrome; | |
| 38 | 新增: assert.notEqual(themeVariables(theme, "light")["--chrome"], "#123456"); | |
| 39 | 新增:}); | |
| 40 | 新增: | |
| 41 | 新增:test("theme document round trips both variants and all editable colors, without device preferences or library", () => { | |
| 42 | 新增: const appearance = normalizeAppearance(structuredClone(defaultAppearance)); | |
| 43 | 新增: appearance.lightTheme.colors = Object.fromEntries( | |
| 44 | 新增: colorGroups.flatMap((group) => | |
| 45 | 新增: group.entries.map(([key]) => [key, "#123456"]), | |
| 46 | 新增: ), | |
| 47 | 新增: ); | |
| 48 | 新增: appearance.darkTheme.terminal = Object.fromEntries( | |
| 49 | 新增: terminalColorGroups.flatMap((group) => | |
| 50 | 新增: group.entries.map(([key]) => [key, "#abcdef"]), | |
| 51 | 新增: ), | |
| 52 | 新增: ); | |
| 53 | 新增: appearance.darkTheme.fonts.code = "Menlo"; | |
| 54 | 新增: const document = themeDocument(" 自定义主题 ", appearance); | |
| 55 | 新增: const imported = parseThemeDocument(JSON.stringify(document)); | |
| 56 | 新增: assert.equal(imported.name, "自定义主题"); | |
| 57 | 新增: assert.ok(sameTheme(appearance, imported)); | |
| 58 | 新增: assert.deepEqual(Object.keys(imported).sort(), [ | |
| 59 | 新增: "darkTheme", | |
| 60 | 新增: "format", | |
| 61 | 新增: "lightTheme", | |
| 62 | 新增: "name", | |
| 63 | 新增: "version", | |
| 64 | 新增: ]); | |
| 65 | 新增: const copy = structuredClone(imported); | |
| 66 | 新增: copy.lightTheme.colors = Object.fromEntries( | |
| 67 | 新增: Object.entries(copy.lightTheme.colors).reverse(), | |
| 68 | 新增: ); | |
| 69 | 新增: assert.ok(sameTheme(copy, imported)); | |
| 70 | 新增: copy.darkTheme.terminal.red = "#000000"; | |
| 71 | 新增: assert.equal(sameTheme(copy, imported), false); | |
| 72 | 新增:}); | |
| 73 | 新增: | |
| 74 | 新增:test("invalid theme files are rejected before any mutation", () => { | |
| 75 | 新增: const valid = themeDocument("主题", defaultAppearance); | |
| 76 | 新增: const reject = (mutate) => { | |
| 77 | 新增: const data = structuredClone(valid); | |
| 78 | 新增: mutate(data); | |
| 79 | 新增: assert.throws(() => parseThemeDocument(JSON.stringify(data))); | |
| 80 | 新增: }; | |
| 81 | 新增: for (const input of [ | |
| 82 | 新增: "not json", | |
| 83 | 新增: "null", | |
| 84 | 新增: "[]", | |
| 85 | 新增: "{}", | |
| 86 | 新增: " ".repeat(256 * 1024 + 1), | |
| 87 | 新增: ]) | |
| 88 | 新增: assert.throws(() => parseThemeDocument(input)); | |
| 89 | 新增: reject((data) => { | |
| 90 | 新增: data.version = 2; | |
| 91 | 新增: }); | |
| 92 | 新增: reject((data) => { | |
| 93 | 新增: data.name = " "; | |
| 94 | 新增: }); | |
| 95 | 新增: reject((data) => { | |
| 96 | 新增: delete data.darkTheme; | |
| 97 | 新增: }); | |
| 98 | 新增: reject((data) => { | |
| 99 | 新增: data.lightTheme.accent = "#abc"; | |
| 100 | 新增: }); | |
| 101 | 新增: reject((data) => { | |
| 102 | 新增: data.lightTheme.colors = { chrome: "red" }; | |
| 103 | 新增: }); | |
| 104 | 新增: reject((data) => { | |
| 105 | 新增: data.lightTheme.colors = { unknown: "#abcdef" }; | |
| 106 | 新增: }); | |
| 107 | 新增: reject((data) => { | |
| 108 | 新增: data.lightTheme.terminal = { foreground: "url(https://example.com)" }; | |
| 109 | 新增: }); | |
| 110 | 新增: reject((data) => { | |
| 111 | 新增: data.lightTheme.fonts.code = "Menlo; color:red"; | |
| 112 | 新增: }); | |
| 113 | 新增: reject((data) => { | |
| 114 | 新增: data.lightTheme.contrast = 10.5; | |
| 115 | 新增: }); | |
| 116 | 新增: reject((data) => { | |
| 117 | 新增: data.mode = "dark"; | |
| 118 | 新增: }); | |
| 119 | 新增: assert.equal(defaultAppearance.lightTheme.accent, "#339cff"); | |
| 120 | 新增:}); | |
| 121 | 新增: | |
| 122 | 新增:test("all built-in palettes produce valid, independently editable theme documents", async () => { | |
| 123 | 新增: const { themeCatalog, presets, presetNames, presetGroups, applyThemePreset } = | |
| 124 | 新增: await import("./appearance-presets.mjs"); | |
| 125 | 新增: assert.equal( | |
| 126 | 新增: new Set(themeCatalog.map((item) => item.id)).size, | |
| 127 | 新增: themeCatalog.length, | |
| 128 | 新增: ); | |
| 129 | 新增: assert.ok(Object.keys(presets.light).length >= 10); | |
| 130 | 新增: assert.ok(Object.keys(presets.dark).length >= 12); | |
| 131 | 新增: for (const item of themeCatalog) { | |
| 132 | 新增: assert.ok(presetGroups.includes(item.group)); | |
| 133 | 新增: assert.equal(presetNames[item.id], item.name); | |
| 134 | 新增: for (const variant of ["light", "dark"]) { | |
| 135 | 新增: if (!item[variant]) continue; | |
| 136 | 新增: const current = structuredClone(defaultAppearance[variant + "Theme"]); | |
| 137 | 新增: current.colors = { danger: "#123456", toolbar: "#123456" }; | |
| 138 | 新增: current.terminal = { foreground: "#123456", brightRed: "#123456" }; | |
| 139 | 新增: current.fonts.code = "Menlo"; | |
| 140 | 新增: const applied = applyThemePreset(current, variant, item.id); | |
| 141 | 新增: const appearance = normalizeAppearance({ [variant + "Theme"]: applied }); | |
| 142 | 新增: const imported = parseThemeDocument( | |
| 143 | 新增: JSON.stringify(themeDocument(item.name, appearance)), | |
| 144 | 新增: ); | |
| 145 | 新增: assert.ok(sameTheme(appearance, imported), item.id); | |
| 146 | 新增: assert.equal(applied.fonts.code, "Menlo"); | |
| 147 | 新增: assert.notEqual(applied.colors.danger, "#123456"); | |
| 148 | 新增: assert.notEqual(applied.terminal.foreground, "#123456"); | |
| 149 | 新增: assert.ok( | |
| 150 | 新增: Object.values(themeVariables(applied, variant)).every( | |
| 151 | 新增: (value) => !String(value).includes("NaN"), | |
| 152 | 新增: ), | |
| 153 | 新增: ); | |
| 154 | 新增: applied.colors.line = "#123456"; | |
| 155 | 新增: applied.terminal.red = "#123456"; | |
| 156 | 新增: assert.notEqual(presets[variant][item.id].colors.line, "#123456"); | |
| 157 | 新增: assert.notEqual(presets[variant][item.id].terminal.red, "#123456"); | |
| 158 | 新增: } | |
| 159 | 新增: } | |
| 160 | 新增:}); | |
| 161 | 新增: | |
| 162 | 新增:function contrastRatio(left, right) { | |
| 163 | 新增: const luminance = (color) => { | |
| 164 | 新增: const [r, g, b] = [1, 3, 5] | |
| 165 | 新增: .map((index) => parseInt(color.slice(index, index + 2), 16) / 255) | |
| 166 | 新增: .map((value) => | |
| 167 | 新增: value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4, | |
| 168 | 新增: ); | |
| 169 | 新增: return 0.2126 * r + 0.7152 * g + 0.0722 * b; | |
| 170 | 新增: }; | |
| 171 | 新增: const a = luminance(left), | |
| 172 | 新增: b = luminance(right); | |
| 173 | 新增: return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); | |
| 174 | 新增:} | |
| 175 | 新增: | |
| 176 | 新增:test("accessible presets keep text, state colors, focus, borders and all ANSI text legible", async () => { | |
| 177 | 新增: const { applyThemePreset } = await import("./appearance-presets.mjs"); | |
| 178 | 新增: for (const id of ["color-vision", "high-contrast"]) | |
| 179 | 新增: for (const variant of ["light", "dark"]) { | |
| 180 | 新增: const theme = applyThemePreset( | |
| 181 | 新增: defaultAppearance[variant + "Theme"], | |
| 182 | 新增: variant, | |
| 183 | 新增: id, | |
| 184 | 新增: ); | |
| 185 | 新增: const vars = themeVariables(theme, variant), | |
| 186 | 新增: terminal = terminalTheme(theme, variant); | |
| 187 | 新增: const threshold = id === "high-contrast" ? 7 : 4.5; | |
| 188 | 新增: const check = (foreground, background, minimum, name) => | |
| 189 | 新增: assert.ok( | |
| 190 | 新增: contrastRatio(foreground, background) >= minimum, | |
| 191 | 新增: `${id}/${variant}/${name}: ${contrastRatio(foreground, background).toFixed(3)} < ${minimum}`, | |
| 192 | 新增: ); | |
| 193 | 新增: for (const key of [ | |
| 194 | 新增: "--ink", | |
| 195 | 新增: "--strong", | |
| 196 | 新增: "--muted", | |
| 197 | 新增: "--link", | |
| 198 | 新增: "--success", | |
| 199 | 新增: "--danger", | |
| 200 | 新增: "--warning", | |
| 201 | 新增: "--inactive", | |
| 202 | 新增: ]) { | |
| 203 | 新增: for (const background of [ | |
| 204 | 新增: "--paper", | |
| 205 | 新增: "--chrome", | |
| 206 | 新增: "--chrome-dark", | |
| 207 | 新增: "--hover", | |
| 208 | 新增: "--selected", | |
| 209 | 新增: "--input", | |
| 210 | 新增: ]) { | |
| 211 | 新增: // State messages and links are shown on paper/panel surfaces, not selection rows. | |
| 212 | 新增: if ( | |
| 213 | 新增: ["--hover", "--selected"].includes(background) && | |
| 214 | 新增: !["--ink", "--strong"].includes(key) | |
| 215 | 新增: ) | |
| 216 | 新增: continue; | |
| 217 | 新增: check( | |
| 218 | 新增: vars[key], | |
| 219 | 新增: vars[background], | |
| 220 | 新增: threshold, | |
| 221 | 新增: `${key} on ${background}`, | |
| 222 | 新增: ); | |
| 223 | 新增: } | |
| 224 | 新增: } | |
| 225 | 新增: check(vars["--sidebar-ink"], vars["--sidebar"], threshold, "sidebar"); | |
| 226 | 新增: check(vars["--toolbar-ink"], vars["--toolbar"], threshold, "toolbar"); | |
| 227 | 新增: check(vars["--button-ink"], vars["--button"], threshold, "button"); | |
| 228 | 新增: for (const background of ["--paper", "--chrome", "--input"]) { | |
| 229 | 新增: check(vars["--line"], vars[background], 3, "border"); | |
| 230 | 新增: check(vars["--focus"], vars[background], 3, "focus"); | |
| 231 | 新增: } | |
| 232 | 新增: for (const group of terminalColorGroups) | |
| 233 | 新增: for (const [key] of group.entries) { | |
| 234 | 新增: if ( | |
| 235 | 新增: ["background", "selectionBackground", "cursorAccent"].includes(key) | |
| 236 | 新增: ) | |
| 237 | 新增: continue; | |
| 238 | 新增: check( | |
| 239 | 新增: terminal[key], | |
| 240 | 新增: terminal.background, | |
| 241 | 新增: threshold, | |
| 242 | 新增: `terminal ${key}`, | |
| 243 | 新增: ); | |
| 244 | 新增: } | |
| 245 | 新增: assert.equal(theme.opaqueWindows, true); | |
| 246 | 新增: assert.notEqual(vars["--success"], vars["--danger"]); | |
| 247 | 新增: check( | |
| 248 | 新增: terminal.foreground, | |
| 249 | 新增: terminal.selectionBackground, | |
| 250 | 新增: threshold, | |
| 251 | 新增: "terminal selection", | |
| 252 | 新增: ); | |
| 253 | 新增: check(terminal.cursorAccent, terminal.cursor, threshold, "cursor text"); | |
| 254 | 新增: } | |
| 255 | 新增:}); | |
| @@ -16,15 +16,15 @@ | ||
| 16 | 16 | } |
| 17 | 17 | :root[data-translucent="true"] .workspace-sidebar, |
| 18 | 18 | :root[data-translucent="true"] .settings-sidebar { |
| 19 | 删除: background: color-mix(in srgb, var(--chrome) 84%, transparent); | |
| 19 | 新增: background: color-mix(in srgb, var(--sidebar) 84%, transparent); | |
| 20 | 20 | backdrop-filter: blur(24px); |
| 21 | 21 | } |
| 22 | 22 | :root[data-translucent="true"] .settings-page { |
| 23 | 23 | background: transparent; |
| 24 | 24 | } |
| 25 | 25 | button.primary:hover:not(:disabled) { |
| 26 | 删除: background: var(--strong); | |
| 27 | 删除: border-color: var(--strong); | |
| 26 | 新增: background: color-mix(in srgb, var(--button) 90%, var(--button-ink)); | |
| 27 | 新增: border-color: var(--button); | |
| 28 | 28 | } |
| 29 | 29 | .appearance-fields { |
| 30 | 30 | margin: 0; |
| @@ -181,39 +181,6 @@ button.primary:hover:not(:disabled) { | ||
| 181 | 181 | height: 15px; |
| 182 | 182 | border-radius: 4px; |
| 183 | 183 | } |
| 184 | 删除:.theme-colors { | |
| 185 | 删除: display: flex; | |
| 186 | 删除: justify-content: space-between; | |
| 187 | 删除: gap: 8px; | |
| 188 | 删除: padding: 16px; | |
| 189 | 删除:} | |
| 190 | 删除:.settings-content | |
| 191 | 删除: .theme-colors | |
| 192 | 删除: label:not(.check-line):not(.choice):not(.toggle-row) { | |
| 193 | 删除: flex-direction: row; | |
| 194 | 删除: align-items: center; | |
| 195 | 删除: gap: 6px; | |
| 196 | 删除: margin: 0; | |
| 197 | 删除: font-size: 0.786rem; | |
| 198 | 删除: font-weight: 400; | |
| 199 | 删除:} | |
| 200 | 删除:.settings-content .theme-colors input[type="color"] { | |
| 201 | 删除: width: 22px; | |
| 202 | 删除: height: 22px; | |
| 203 | 删除: min-width: 22px; | |
| 204 | 删除: padding: 0; | |
| 205 | 删除: border: 1px solid var(--line); | |
| 206 | 删除: border-radius: 50%; | |
| 207 | 删除: cursor: var(--control-cursor); | |
| 208 | 删除: overflow: hidden; | |
| 209 | 删除:} | |
| 210 | 删除:.theme-colors input::-webkit-color-swatch-wrapper { | |
| 211 | 删除: padding: 0; | |
| 212 | 删除:} | |
| 213 | 删除:.theme-colors input::-webkit-color-swatch { | |
| 214 | 删除: border: 0; | |
| 215 | 删除: border-radius: 50%; | |
| 216 | 删除:} | |
| 217 | 184 | .theme-customize { |
| 218 | 185 | width: 100%; |
| 219 | 186 | border: 0; |
| @@ -358,10 +325,6 @@ button.primary:hover:not(:disabled) { | ||
| 358 | 325 | .theme-card-grid { |
| 359 | 326 | gap: 12px; |
| 360 | 327 | } |
| 361 | 删除: .theme-colors { | |
| 362 | 删除: padding: 12px; | |
| 363 | 删除: gap: 4px; | |
| 364 | 删除: } | |
| 365 | 328 | .appearance-import { |
| 366 | 329 | flex-wrap: wrap; |
| 367 | 330 | gap: 12px; |
| @@ -378,3 +341,213 @@ button.primary:hover:not(:disabled) { | ||
| 378 | 341 | padding: 7px; |
| 379 | 342 | } |
| 380 | 343 | } |
| 344 | 新增:/* Theme editing stays compact until a group is expanded. */ | |
| 345 | 新增:.theme-library { | |
| 346 | 新增: margin-top: 24px; | |
| 347 | 新增: padding: 18px; | |
| 348 | 新增: border: 1px solid var(--line); | |
| 349 | 新增: border-radius: 12px; | |
| 350 | 新增:} | |
| 351 | 新增:.theme-library-heading { | |
| 352 | 新增: display: flex; | |
| 353 | 新增: justify-content: space-between; | |
| 354 | 新增: align-items: start; | |
| 355 | 新增: gap: 16px; | |
| 356 | 新增: flex-wrap: wrap; | |
| 357 | 新增:} | |
| 358 | 新增:.theme-library-heading h4 { | |
| 359 | 新增: margin: 0; | |
| 360 | 新增:} | |
| 361 | 新增:.theme-library-heading p, | |
| 362 | 新增:.theme-options-hint { | |
| 363 | 新增: color: var(--muted); | |
| 364 | 新增: font-size: 0.857rem; | |
| 365 | 新增: line-height: 1.6; | |
| 366 | 新增: margin: 6px 0 14px; | |
| 367 | 新增:} | |
| 368 | 新增:.theme-file-actions { | |
| 369 | 新增: display: flex; | |
| 370 | 新增: gap: 8px; | |
| 371 | 新增:} | |
| 372 | 新增:.theme-library button { | |
| 373 | 新增: font-size: 0.857rem; | |
| 374 | 新增: white-space: nowrap; | |
| 375 | 新增:} | |
| 376 | 新增:.theme-library-fields { | |
| 377 | 新增: display: grid; | |
| 378 | 新增: grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; | |
| 379 | 新增: gap: 8px; | |
| 380 | 新增:} | |
| 381 | 新增:.theme-library-fields select, | |
| 382 | 新增:.theme-library-fields input { | |
| 383 | 新增: min-width: 0; | |
| 384 | 新增:} | |
| 385 | 新增:.theme-library-manage { | |
| 386 | 新增: display: flex; | |
| 387 | 新增: align-items: center; | |
| 388 | 新增: gap: 10px; | |
| 389 | 新增: margin-top: 12px; | |
| 390 | 新增: flex-wrap: wrap; | |
| 391 | 新增:} | |
| 392 | 新增:.theme-library-manage span { | |
| 393 | 新增: flex: 1; | |
| 394 | 新增: min-width: 140px; | |
| 395 | 新增: color: var(--muted); | |
| 396 | 新增: font-size: 0.786rem; | |
| 397 | 新增:} | |
| 398 | 新增:.theme-library-notice { | |
| 399 | 新增: color: var(--success); | |
| 400 | 新增: font-size: 0.857rem; | |
| 401 | 新增: margin: 12px 0 0; | |
| 402 | 新增:} | |
| 403 | 新增:.theme-base-colors { | |
| 404 | 新增: padding: 12px 16px; | |
| 405 | 新增:} | |
| 406 | 新增:.theme-color-field { | |
| 407 | 新增: display: flex; | |
| 408 | 新增: justify-content: space-between; | |
| 409 | 新增: align-items: center; | |
| 410 | 新增: gap: 8px; | |
| 411 | 新增: padding: 7px 0; | |
| 412 | 新增: flex-wrap: wrap; | |
| 413 | 新增:} | |
| 414 | 新增:.theme-color-field > span { | |
| 415 | 新增: font-size: 0.786rem; | |
| 416 | 新增: flex: 1; | |
| 417 | 新增: min-width: 78px; | |
| 418 | 新增:} | |
| 419 | 新增:.theme-color-value { | |
| 420 | 新增: display: flex; | |
| 421 | 新增: align-items: center; | |
| 422 | 新增: gap: 6px; | |
| 423 | 新增:} | |
| 424 | 新增:.settings-content .theme-color-value input[type="text"] { | |
| 425 | 新增: width: 80px; | |
| 426 | 新增: height: 30px; | |
| 427 | 新增: padding: 4px 6px; | |
| 428 | 新增: font: 0.786rem var(--code-font-family); | |
| 429 | 新增:} | |
| 430 | 新增:.settings-content .theme-color-value input[type="color"] { | |
| 431 | 新增: width: 24px; | |
| 432 | 新增: height: 24px; | |
| 433 | 新增: min-width: 24px; | |
| 434 | 新增: padding: 2px; | |
| 435 | 新增: border: 1px solid var(--line); | |
| 436 | 新增: border-radius: 6px; | |
| 437 | 新增: cursor: var(--control-cursor); | |
| 438 | 新增:} | |
| 439 | 新增:.theme-color-value input[type="color"]::-webkit-color-swatch-wrapper { | |
| 440 | 新增: padding: 0; | |
| 441 | 新增:} | |
| 442 | 新增:.theme-color-value input[type="color"]::-webkit-color-swatch { | |
| 443 | 新增: border: 0; | |
| 444 | 新增: border-radius: 3px; | |
| 445 | 新增:} | |
| 446 | 新增:.theme-color-value .icon-button { | |
| 447 | 新增: width: 24px; | |
| 448 | 新增: min-height: 24px; | |
| 449 | 新增: padding: 4px; | |
| 450 | 新增:} | |
| 451 | 新增:.theme-color-error { | |
| 452 | 新增: flex-basis: 100%; | |
| 453 | 新增: color: var(--danger); | |
| 454 | 新增: font-size: 0.786rem; | |
| 455 | 新增:} | |
| 456 | 新增:.theme-color-group { | |
| 457 | 新增: border-top: 1px solid var(--line); | |
| 458 | 新增:} | |
| 459 | 新增:.theme-color-group summary { | |
| 460 | 新增: padding: 12px 0; | |
| 461 | 新增: font-size: 0.857rem; | |
| 462 | 新增: font-weight: 500; | |
| 463 | 新增: cursor: var(--control-cursor); | |
| 464 | 新增:} | |
| 465 | 新增:.theme-color-group summary:hover { | |
| 466 | 新增: color: var(--link); | |
| 467 | 新增:} | |
| 468 | 新增:.theme-terminal-preview { | |
| 469 | 新增: padding: 12px; | |
| 470 | 新增: border: 1px solid var(--line); | |
| 471 | 新增: border-radius: 6px; | |
| 472 | 新增: font: 0.786rem var(--code-font-family); | |
| 473 | 新增: overflow-wrap: anywhere; | |
| 474 | 新增: margin-top: 8px; | |
| 475 | 新增:} | |
| 476 | 新增:.theme-terminal-preview i { | |
| 477 | 新增: display: inline-block; | |
| 478 | 新增: width: 6px; | |
| 479 | 新增: height: 12px; | |
| 480 | 新增: vertical-align: middle; | |
| 481 | 新增: margin-left: 4px; | |
| 482 | 新增:} | |
| 483 | 新增:.theme-reset-colors { | |
| 484 | 新增: width: 100%; | |
| 485 | 新增: margin: 12px 0 20px; | |
| 486 | 新增: font-size: 0.786rem; | |
| 487 | 新增:} | |
| 488 | 新增:.theme-customize svg { | |
| 489 | 新增: transition: transform 120ms; | |
| 490 | 新增:} | |
| 491 | 新增:@media (max-width: 1050px) { | |
| 492 | 新增: .theme-library-fields { | |
| 493 | 新增: grid-template-columns: minmax(0, 1fr); | |
| 494 | 新增: } | |
| 495 | 新增:} | |
| 496 | 新增: | |
| 497 | 新增:.workspace-sidebar, | |
| 498 | 新增:.settings-sidebar { | |
| 499 | 新增: background: var(--sidebar); | |
| 500 | 新增: color: var(--sidebar-ink); | |
| 501 | 新增:} | |
| 502 | 新增:.sidebar-link, | |
| 503 | 新增:.project-disclosure, | |
| 504 | 新增:.settings-sidebar nav button { | |
| 505 | 新增: color: var(--sidebar-ink); | |
| 506 | 新增:} | |
| 507 | 新增:.content-heading, | |
| 508 | 新增:.navigation-row, | |
| 509 | 新增:.status-bar { | |
| 510 | 新增: background: var(--toolbar); | |
| 511 | 新增: color: var(--toolbar-ink); | |
| 512 | 新增:} | |
| 513 | 新增:.content-breadcrumb > button, | |
| 514 | 新增:.navigation-row .icon-button, | |
| 515 | 新增:.heading-actions .icon-button, | |
| 516 | 新增:.status-bar button { | |
| 517 | 新增: color: var(--toolbar-ink); | |
| 518 | 新增:} | |
| 519 | 新增:.appearance-sample { | |
| 520 | 新增: background: var(--chrome-dark); | |
| 521 | 新增:} | |
| 522 | 新增:.appearance-switch input:checked:after { | |
| 523 | 新增: background: var(--accent-ink); | |
| 524 | 新增:} | |
| 525 | 新增:.theme-preset-summary { | |
| 526 | 新增: padding: 12px 16px 0; | |
| 527 | 新增:} | |
| 528 | 新增:.theme-preset-summary p { | |
| 529 | 新增: margin: 0 0 10px; | |
| 530 | 新增: min-height: 3.2em; | |
| 531 | 新增: color: var(--muted); | |
| 532 | 新增: font-size: 0.786rem; | |
| 533 | 新增: line-height: 1.6; | |
| 534 | 新增:} | |
| 535 | 新增:.theme-status-preview { | |
| 536 | 新增: display: flex; | |
| 537 | 新增: flex-wrap: wrap; | |
| 538 | 新增: align-items: center; | |
| 539 | 新增: justify-content: space-between; | |
| 540 | 新增: gap: 8px; | |
| 541 | 新增: padding: 9px 10px; | |
| 542 | 新增: border: 1px solid var(--line); | |
| 543 | 新增: border-radius: 6px; | |
| 544 | 新增:} | |
| 545 | 新增:.theme-status-preview span { | |
| 546 | 新增: display: inline-flex; | |
| 547 | 新增: align-items: center; | |
| 548 | 新增: gap: 5px; | |
| 549 | 新增: font-size: 0.786rem; | |
| 550 | 新增:} | |
| 551 | 新增:.theme-status-preview svg { | |
| 552 | 新增: flex: none; | |
| 553 | 新增:} | |
| @@ -100,7 +100,7 @@ export function AppearanceProvider({ children }) { | ||
| 100 | 100 | native("appearance", { |
| 101 | 101 | mode: appearance.mode, |
| 102 | 102 | variant, |
| 103 | 删除: background: variables["--chrome"], | |
| 103 | 新增: background: variables["--sidebar"], | |
| 104 | 104 | translucent: !theme.opaqueWindows, |
| 105 | 105 | }).catch(() => |
| 106 | 106 | setError("外观已应用到工作台,原生窗口未能同步,请重新打开 Cage。"), |
| @@ -123,11 +123,13 @@ export function AppearanceProvider({ children }) { | ||
| 123 | 123 | await api("/appearance", next); |
| 124 | 124 | localStorage.setItem("cage-appearance", JSON.stringify(next)); |
| 125 | 125 | if (id === revision.current) setSaving(false); |
| 126 | 新增: return true; | |
| 126 | 127 | } catch (e) { |
| 127 | 128 | if (id === revision.current) { |
| 128 | 129 | setError(e.message); |
| 129 | 130 | setSaving(false); |
| 130 | 131 | } |
| 132 | 新增: return false; | |
| 131 | 133 | } |
| 132 | 134 | }); |
| 133 | 135 | return queue.current; |
| @@ -0,0 +1,115 @@ | ||
| 1 | 新增:import { api } from "./api"; | |
| 2 | 新增:import workletURL from "./audio-worklet.js?url&no-inline"; | |
| 3 | 新增: | |
| 4 | 新增:export class AudioOutput { | |
| 5 | 新增: constructor(onState) { | |
| 6 | 新增: this.onState = onState; | |
| 7 | 新增: this.active = false; | |
| 8 | 新增: this.volume = 1; | |
| 9 | 新增: this.generation = 0; | |
| 10 | 新增: } | |
| 11 | 新增: setActive(active) { | |
| 12 | 新增: if (this.active === active) return; | |
| 13 | 新增: this.active = active; | |
| 14 | 新增: if (active) this.activate(); | |
| 15 | 新增: else { | |
| 16 | 新增: this.disconnect(); | |
| 17 | 新增: this.context?.suspend().catch(() => {}); | |
| 18 | 新增: this.onState("idle"); | |
| 19 | 新增: } | |
| 20 | 新增: } | |
| 21 | 新增: setVolume(value) { | |
| 22 | 新增: this.volume = value; | |
| 23 | 新增: if (this.gain) this.gain.gain.value = value; | |
| 24 | 新增: } | |
| 25 | 新增: activate() { | |
| 26 | 新增: if (this.disposed || !this.active) return; | |
| 27 | 新增: try { | |
| 28 | 新增: if (!this.context) { | |
| 29 | 新增: this.context = new AudioContext({ latencyHint: "interactive" }); | |
| 30 | 新增: this.context.onstatechange = () => { | |
| 31 | 新增: if (this.disposed || !this.active) return; | |
| 32 | 新增: if (this.context.state === "running") this.connect(); | |
| 33 | 新增: else { this.disconnect(); this.onState("blocked"); } | |
| 34 | 新增: }; | |
| 35 | 新增: } | |
| 36 | 新增: // Call resume directly from the pointer/key handler, before awaiting any | |
| 37 | 新增: // API request, so all three platform WebViews retain the user gesture. | |
| 38 | 新增: const resume = this.context.resume(); | |
| 39 | 新增: if (this.context.state !== "running") this.onState("blocked"); | |
| 40 | 新增: void resume.then(() => { | |
| 41 | 新增: if (this.context.state === "running") this.connect(); | |
| 42 | 新增: }).catch(() => this.onState("blocked")); | |
| 43 | 新增: } catch { this.onState("unsupported"); } | |
| 44 | 新增: } | |
| 45 | 新增: disconnect() { | |
| 46 | 新增: this.generation++; | |
| 47 | 新增: clearTimeout(this.retry); | |
| 48 | 新增: this.opening = false; | |
| 49 | 新增: const socket = this.socket; | |
| 50 | 新增: this.socket = null; | |
| 51 | 新增: if (socket) { socket.onclose = null; socket.close(); } | |
| 52 | 新增: this.node?.port.postMessage("reset"); | |
| 53 | 新增: } | |
| 54 | 新增: async prepare() { | |
| 55 | 新增: if (!this.preparing) { | |
| 56 | 新增: this.preparing = this.context.audioWorklet.addModule(workletURL).then(() => { | |
| 57 | 新增: if (this.disposed) return; | |
| 58 | 新增: this.node = new AudioWorkletNode(this.context, "cage-audio", { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2] }); | |
| 59 | 新增: this.gain = this.context.createGain(); | |
| 60 | 新增: this.gain.gain.value = this.volume; | |
| 61 | 新增: this.node.connect(this.gain).connect(this.context.destination); | |
| 62 | 新增: }).catch(error => { this.preparing = null; throw error; }); | |
| 63 | 新增: } | |
| 64 | 新增: return this.preparing; | |
| 65 | 新增: } | |
| 66 | 新增: async connect() { | |
| 67 | 新增: if (!this.active || this.disposed || this.context.state !== "running" || this.socket || this.opening) return; | |
| 68 | 新增: clearTimeout(this.retry); | |
| 69 | 新增: this.opening = true; | |
| 70 | 新增: const generation = this.generation; | |
| 71 | 新增: const live = () => this.active && !this.disposed && generation === this.generation; | |
| 72 | 新增: this.onState("connecting"); | |
| 73 | 新增: const reconnect = () => { | |
| 74 | 新增: if (!live()) return; | |
| 75 | 新增: this.opening = false; | |
| 76 | 新增: this.socket = null; | |
| 77 | 新增: this.node?.port.postMessage("reset"); | |
| 78 | 新增: this.onState("disconnected"); | |
| 79 | 新增: this.retry = setTimeout(() => this.connect(), 2500); | |
| 80 | 新增: }; | |
| 81 | 新增: try { | |
| 82 | 新增: await this.prepare(); | |
| 83 | 新增: const format = await api("/audio"); | |
| 84 | 新增: if (!live()) return; | |
| 85 | 新增: if (format.format !== "s16le" || format.sample_rate !== 48000 || format.channels !== 2) throw new Error("声音格式不兼容"); | |
| 86 | 新增: const socket = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/audio`); | |
| 87 | 新增: socket.binaryType = "arraybuffer"; | |
| 88 | 新增: this.socket = socket; | |
| 89 | 新增: let confirmed = false; | |
| 90 | 新增: socket.onmessage = ({ data }) => { | |
| 91 | 新增: if (!live()) return; | |
| 92 | 新增: if (typeof data === "string") { | |
| 93 | 新增: try { | |
| 94 | 新增: const header = JSON.parse(data); | |
| 95 | 新增: confirmed = header.format === "s16le" && header.sample_rate === 48000 && header.channels === 2; | |
| 96 | 新增: } catch { confirmed = false; } | |
| 97 | 新增: if (!confirmed) socket.close(); | |
| 98 | 新增: } else if (confirmed) { | |
| 99 | 新增: this.onState("playing"); | |
| 100 | 新增: this.node.port.postMessage(data, [data]); | |
| 101 | 新增: } | |
| 102 | 新增: }; | |
| 103 | 新增: socket.onclose = reconnect; | |
| 104 | 新增: socket.onerror = () => socket.close(); | |
| 105 | 新增: this.opening = false; | |
| 106 | 新增: } catch { reconnect(); } | |
| 107 | 新增: } | |
| 108 | 新增: close() { | |
| 109 | 新增: this.disposed = true; | |
| 110 | 新增: this.disconnect(); | |
| 111 | 新增: this.node?.disconnect(); | |
| 112 | 新增: this.gain?.disconnect(); | |
| 113 | 新增: this.context?.close().catch(() => {}); | |
| 114 | 新增: } | |
| 115 | 新增:} | |
| @@ -0,0 +1,71 @@ | ||
| 1 | 新增:// Standalone AudioWorklet module: Vite emits this file without dependencies. | |
| 2 | 新增:// Keep only a short live buffer; reconnecting or a stalled UI must never replay | |
| 3 | 新增:// seconds of old sound. Source PCM is always 48 kHz stereo signed little-endian. | |
| 4 | 新增:export class PCMQueue { | |
| 5 | 新增: constructor() { | |
| 6 | 新增: this.capacity = 12000; | |
| 7 | 新增: this.left = new Float32Array(this.capacity); | |
| 8 | 新增: this.right = new Float32Array(this.capacity); | |
| 9 | 新增: this.read = 0; | |
| 10 | 新增: this.count = 0; | |
| 11 | 新增: this.fraction = 0; | |
| 12 | 新增: this.playing = false; | |
| 13 | 新增: } | |
| 14 | 新增: push(data) { | |
| 15 | 新增: if (!(data instanceof ArrayBuffer) || data.byteLength % 4) return; | |
| 16 | 新增: const view = new DataView(data); | |
| 17 | 新增: const frames = view.byteLength / 4; | |
| 18 | 新增: if (this.count + frames > this.capacity) { | |
| 19 | 新增: // Drop the backlog together so repeated late packets cannot accumulate. | |
| 20 | 新增: this.read = this.count = this.fraction = 0; | |
| 21 | 新增: this.playing = false; | |
| 22 | 新增: } | |
| 23 | 新增: for (let i = Math.max(0, frames - this.capacity); i < frames; i++) { | |
| 24 | 新增: const at = (this.read + this.count) % this.capacity; | |
| 25 | 新增: this.left[at] = view.getInt16(i * 4, true) / 32768; | |
| 26 | 新增: this.right[at] = view.getInt16(i * 4 + 2, true) / 32768; | |
| 27 | 新增: this.count++; | |
| 28 | 新增: } | |
| 29 | 新增: } | |
| 30 | 新增: render(left, right, outputRate) { | |
| 31 | 新增: left.fill(0); | |
| 32 | 新增: right.fill(0); | |
| 33 | 新增: if (!this.playing && this.count >= 2880) this.playing = true; | |
| 34 | 新增: if (!this.playing) return; | |
| 35 | 新增: const step = 48000 / outputRate; | |
| 36 | 新增: for (let i = 0; i < left.length; i++) { | |
| 37 | 新增: if (this.count < Math.max(2, Math.ceil(this.fraction + step))) { | |
| 38 | 新增: this.playing = false; | |
| 39 | 新增: this.read = this.count = this.fraction = 0; | |
| 40 | 新增: return; | |
| 41 | 新增: } | |
| 42 | 新增: const next = (this.read + 1) % this.capacity; | |
| 43 | 新增: left[i] = this.left[this.read] + (this.left[next] - this.left[this.read]) * this.fraction; | |
| 44 | 新增: right[i] = this.right[this.read] + (this.right[next] - this.right[this.read]) * this.fraction; | |
| 45 | 新增: this.fraction += step; | |
| 46 | 新增: const consumed = Math.floor(this.fraction); | |
| 47 | 新增: this.fraction -= consumed; | |
| 48 | 新增: this.read = (this.read + consumed) % this.capacity; | |
| 49 | 新增: this.count -= consumed; | |
| 50 | 新增: } | |
| 51 | 新增: } | |
| 52 | 新增:} | |
| 53 | 新增: | |
| 54 | 新增:if (typeof globalThis.registerProcessor === "function") { | |
| 55 | 新增: class CageAudioProcessor extends globalThis.AudioWorkletProcessor { | |
| 56 | 新增: constructor() { | |
| 57 | 新增: super(); | |
| 58 | 新增: this.queue = new PCMQueue(); | |
| 59 | 新增: this.port.onmessage = ({ data }) => { | |
| 60 | 新增: if (data === "reset") this.queue = new PCMQueue(); | |
| 61 | 新增: else this.queue.push(data); | |
| 62 | 新增: }; | |
| 63 | 新增: } | |
| 64 | 新增: process(_inputs, outputs) { | |
| 65 | 新增: const [left, right] = outputs[0]; | |
| 66 | 新增: if (left && right) this.queue.render(left, right, globalThis.sampleRate); | |
| 67 | 新增: return true; | |
| 68 | 新增: } | |
| 69 | 新增: } | |
| 70 | 新增: globalThis.registerProcessor("cage-audio", CageAudioProcessor); | |
| 71 | 新增:} | |
| @@ -0,0 +1,46 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import test from "node:test"; | |
| 3 | 新增:import { PCMQueue } from "./audio-worklet.js"; | |
| 4 | 新增: | |
| 5 | 新增:function pcm(frames, value = i => [i, -i]) { | |
| 6 | 新增: const data = new ArrayBuffer(frames * 4), view = new DataView(data); | |
| 7 | 新增: for (let i = 0; i < frames; i++) { | |
| 8 | 新增: const [left, right] = value(i); | |
| 9 | 新增: view.setInt16(i * 4, left, true); | |
| 10 | 新增: view.setInt16(i * 4 + 2, right, true); | |
| 11 | 新增: } | |
| 12 | 新增: return data; | |
| 13 | 新增:} | |
| 14 | 新增:test("PCM preserves signed stereo samples and silence before buffering", () => { | |
| 15 | 新增: const q = new PCMQueue(), left = new Float32Array(128), right = new Float32Array(128); | |
| 16 | 新增: q.push(pcm(960)); q.render(left, right, 48000); | |
| 17 | 新增: assert.ok(left.every(v => v === 0)); | |
| 18 | 新增: q.push(pcm(1920, () => [-32768, 32767])); | |
| 19 | 新增: q.render(left, right, 48000); | |
| 20 | 新增: assert.equal(left[40], 40 / 32768); | |
| 21 | 新增: assert.equal(right[40], -40 / 32768); | |
| 22 | 新增: for (let i = 0; i < 8; i++) q.render(left, right, 48000); | |
| 23 | 新增: assert.equal(left[100], -1); | |
| 24 | 新增: assert.equal(right[100], 32767 / 32768); | |
| 25 | 新增:}); | |
| 26 | 新增:test("PCM resamples to the host rate and returns silence on underrun", () => { | |
| 27 | 新增: const q = new PCMQueue(), left = new Float32Array(441), right = new Float32Array(441); | |
| 28 | 新增: q.push(pcm(4800)); q.render(left, right, 44100); | |
| 29 | 新增: assert.ok(Math.abs(left[147] - 160 / 32768) < 1e-7); | |
| 30 | 新增: assert.ok(Math.abs(right[294] + 320 / 32768) < 1e-7); | |
| 31 | 新增: for (let i = 0; i < 12; i++) q.render(left, right, 44100); | |
| 32 | 新增: assert.ok(left.every(v => v === 0)); | |
| 33 | 新增: assert.ok(q.count < 2); | |
| 34 | 新增:}); | |
| 35 | 新增:test("late PCM is bounded and old audio is discarded", () => { | |
| 36 | 新增: const q = new PCMQueue(), left = new Float32Array(128), right = new Float32Array(128); | |
| 37 | 新增: q.push(pcm(11000, () => [100, 100])); | |
| 38 | 新增: q.push(pcm(3000, () => [500, -500])); | |
| 39 | 新增: assert.equal(q.count, 3000); | |
| 40 | 新增: q.render(left, right, 48000); | |
| 41 | 新增: assert.equal(left[0], 500 / 32768); | |
| 42 | 新增: q.push(pcm(24000)); | |
| 43 | 新增: assert.equal(q.count, q.capacity); | |
| 44 | 新增: q.push(new ArrayBuffer(3)); | |
| 45 | 新增: assert.equal(q.count, q.capacity); | |
| 46 | 新增:}); | |
| @@ -0,0 +1,59 @@ | ||
| 1 | 新增:import { useEffect, useRef, useState } from "react"; | |
| 2 | 新增:import { Volume2, VolumeX } from "lucide-react"; | |
| 3 | 新增:import { AudioOutput } from "./audio-output"; | |
| 4 | 新增: | |
| 5 | 新增:function savedAudio() { | |
| 6 | 新增: try { | |
| 7 | 新增: const value = JSON.parse(localStorage.getItem("cage.audio") || "{}"); | |
| 8 | 新增: return { muted: value.muted === true, volume: Number.isFinite(value.volume) ? Math.max(0, Math.min(1, value.volume)) : 1 }; | |
| 9 | 新增: } catch { return { muted: false, volume: 1 }; } | |
| 10 | 新增:} | |
| 11 | 新增: | |
| 12 | 新增:export function useAudioOutput(enabled) { | |
| 13 | 新增: const [preferences, setPreferences] = useState(savedAudio); | |
| 14 | 新增: const [state, setState] = useState("idle"); | |
| 15 | 新增: const player = useRef(); | |
| 16 | 新增: useEffect(() => { | |
| 17 | 新增: const output = new AudioOutput(setState); | |
| 18 | 新增: player.current = output; | |
| 19 | 新增: const activate = () => output.activate(); | |
| 20 | 新增: window.addEventListener("pointerdown", activate, true); | |
| 21 | 新增: window.addEventListener("keydown", activate, true); | |
| 22 | 新增: return () => { | |
| 23 | 新增: window.removeEventListener("pointerdown", activate, true); | |
| 24 | 新增: window.removeEventListener("keydown", activate, true); | |
| 25 | 新增: output.close(); | |
| 26 | 新增: player.current = null; | |
| 27 | 新增: }; | |
| 28 | 新增: }, []); | |
| 29 | 新增: useEffect(() => { | |
| 30 | 新增: player.current?.setVolume(preferences.volume); | |
| 31 | 新增: player.current?.setActive(enabled && !preferences.muted && preferences.volume > 0); | |
| 32 | 新增: try { localStorage.setItem("cage.audio", JSON.stringify(preferences)); } catch { /* Playback also works without storage. */ } | |
| 33 | 新增: }, [enabled, preferences]); | |
| 34 | 新增: const toggle = () => { | |
| 35 | 新增: if (state === "blocked" && !preferences.muted && preferences.volume > 0) { | |
| 36 | 新增: player.current?.activate(); | |
| 37 | 新增: return; | |
| 38 | 新增: } | |
| 39 | 新增: const muted = !preferences.muted && preferences.volume > 0; | |
| 40 | 新增: setPreferences({ ...preferences, muted, volume: preferences.volume || 1 }); | |
| 41 | 新增: player.current?.setActive(enabled && !muted); | |
| 42 | 新增: }; | |
| 43 | 新增: return { enabled, state, ...preferences, toggle, volumeChange: volume => { | |
| 44 | 新增: setPreferences({ muted: false, volume }); | |
| 45 | 新增: player.current?.setActive(enabled && volume > 0); | |
| 46 | 新增: } }; | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:export function AudioControls({ audio }) { | |
| 50 | 新增: const silent = audio.muted || audio.volume === 0; | |
| 51 | 新增: const label = !audio.enabled ? "环境声音:未启动" : silent ? "取消静音" : audio.state === "blocked" ? "启用声音" : audio.state === "unsupported" ? "当前窗口不支持声音播放" : audio.state === "disconnected" ? "声音连接中断,正在重连" : "静音"; | |
| 52 | 新增: return <div className="audio-controls"> | |
| 53 | 新增: <button onClick={audio.toggle} disabled={!audio.enabled} aria-label={label} title={label} aria-pressed={silent}> | |
| 54 | 新增: {silent ? <VolumeX size={15} /> : <Volume2 size={15} />} | |
| 55 | 新增: {audio.state === "blocked" && !silent && audio.enabled && <span>启用声音</span>} | |
| 56 | 新增: </button> | |
| 57 | 新增: <input type="range" aria-label="环境音量" title={`环境音量 ${Math.round(audio.volume * 100)}%`} min="0" max="100" step="1" value={Math.round(audio.volume * 100)} disabled={!audio.enabled} onChange={e => audio.volumeChange(Number(e.target.value) / 100)} /> | |
| 58 | 新增: </div>; | |
| 59 | 新增:} | |
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。