mirror of
https://github.com/majd/ipatool
synced 2026-11-28 10:17:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8619332e52 | ||
|
|
6db68b6bd2 | ||
|
|
3c90c45dab | ||
|
|
94fc3a6d47 | ||
|
|
0f517f43f6 |
No files matched your search
@@ -1 +0,0 @@
|
||||
github: majd
|
||||
@@ -1,25 +0,0 @@
|
||||
name: Bug Report
|
||||
description: File a bug report
|
||||
labels:
|
||||
- bug
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: What happened?
|
||||
description: Also share, what did you expect to happen?
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: What version of ipatool are you running?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Relevant log output
|
||||
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
|
||||
render: shell
|
||||
@@ -1,12 +0,0 @@
|
||||
name: Feature Request
|
||||
description: Submit a feature request
|
||||
labels:
|
||||
- feature request
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Description
|
||||
description: Please provide details about the desired feature.
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,76 +0,0 @@
|
||||
name: Dry Build
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build_windows:
|
||||
name: Build for Windows
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
build_linux:
|
||||
name: Build for Linux
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
- arch: amd64
|
||||
runner: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -o ipatool-linux-$GOARCH
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
build_macos:
|
||||
name: Build for macOS
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
CGO_ENABLED: 1
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
build_ios:
|
||||
name: Build for iOS
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: brew install ldid cmake
|
||||
- run: ./tools/build-ios.sh
|
||||
@@ -1,41 +0,0 @@
|
||||
name: Integration Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -o ipatool
|
||||
env:
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool
|
||||
path: ipatool
|
||||
if-no-files-found: error
|
||||
test:
|
||||
name: Test
|
||||
runs-on: macos-latest
|
||||
needs: [build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
command: [auth, download, purchase, search]
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool
|
||||
path: build
|
||||
- run: chmod +x ./build/ipatool
|
||||
- run: ./build/ipatool ${{ matrix.command }} --help
|
||||
@@ -1,21 +0,0 @@
|
||||
name: Lint
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go generate github.com/majd/ipatool/...
|
||||
- uses: golangci/golangci-lint-action@v8
|
||||
with:
|
||||
version: v2.9
|
||||
@@ -1,266 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
get_version:
|
||||
name: Get version
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: set_output
|
||||
run: echo ::set-output name=version::${GITHUB_REF#refs/tags/v}
|
||||
outputs:
|
||||
version: ${{ steps.set_output.outputs.version }}
|
||||
test:
|
||||
name: Run tests
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go generate github.com/majd/ipatool/...
|
||||
- run: go test -v github.com/majd/ipatool/...
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-latest
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-arm64.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: arm64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-amd64.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: amd64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-macos-arm64
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: arm64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_ENABLED: 1
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-macos-amd64
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: amd64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_ENABLED: 1
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
if-no-files-found: error
|
||||
build_linux:
|
||||
name: Build for Linux
|
||||
runs-on: ${{ matrix.runner }}
|
||||
needs: [get_version, test]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
- arch: amd64
|
||||
runner: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-linux-$GOARCH
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
if-no-files-found: error
|
||||
build_ios:
|
||||
name: Build for iOS
|
||||
runs-on: macos-latest
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: brew install ldid cmake
|
||||
- run: ./tools/build-ios.sh "ipatool-$VERSION-ios-arm64"
|
||||
env:
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
if-no-files-found: error
|
||||
release_ios:
|
||||
name: Release for iOS
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build_ios, release_windows]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
path: bin
|
||||
- run: chmod +x "bin/$FILE" && tar -czvf "$FILE.tar.gz" "bin/$FILE"
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
- run: ./tools/sha256sum.sh "$TARBALL" > "$TARBALL.sha256sum"
|
||||
env:
|
||||
TARBALL: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64.tar.gz
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64.*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
release_windows:
|
||||
name: Release for Windows
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.exe
|
||||
path: bin
|
||||
- run: tar -czvf $FILE.tar.gz bin/$FILE.exe
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}
|
||||
- run: ./tools/sha256sum.sh $TARBALL > $TARBALL.sha256sum
|
||||
env:
|
||||
TARBALL: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.tar.gz
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
release_linux:
|
||||
name: Release for Linux
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build_linux, release_windows]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
path: bin
|
||||
- run: chmod +x bin/$FILE && tar -czvf $FILE.tar.gz bin/$FILE
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
- run: ./tools/sha256sum.sh $TARBALL > $TARBALL.sha256sum
|
||||
env:
|
||||
TARBALL: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}.tar.gz
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}.*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
release_macos:
|
||||
name: Release for macOS
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build, build_linux, release_windows, release_linux]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
path: ./ipatool
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
path: bin
|
||||
- run: chmod +x bin/$BIN && tar -czvf $BIN.tar.gz bin/$BIN && rm -rf bin/
|
||||
env:
|
||||
BIN: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
path: bin
|
||||
- run: chmod +x bin/$FILE && tar -czvf $FILE.tar.gz bin/$FILE && rm -rf bin/
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
- id: sha256
|
||||
run: |
|
||||
SHA256_ARM64=$(./ipatool/tools/sha256sum.sh ipatool-${{ needs.get_version.outputs.version }}-macos-arm64.tar.gz)
|
||||
SHA256_AMD64=$(./ipatool/tools/sha256sum.sh ipatool-${{ needs.get_version.outputs.version }}-macos-amd64.tar.gz)
|
||||
echo $SHA256_ARM64 > ipatool-${{ needs.get_version.outputs.version }}-macos-arm64.tar.gz.sha256sum
|
||||
echo $SHA256_AMD64 > ipatool-${{ needs.get_version.outputs.version }}-macos-amd64.tar.gz.sha256sum
|
||||
echo ::set-output name=sha256_arm64::$SHA256_ARM64
|
||||
echo ::set-output name=sha256_amd64::$SHA256_AMD64
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-macos-*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: ${{ secrets.HOMEBREW_REPO }}
|
||||
ref: main
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
path: homebrew-repo
|
||||
- run: |
|
||||
cd homebrew-repo
|
||||
sed -i "3s/.*/ sha256 \"$SHA256_ARM64\"/" Casks/ipatool.rb
|
||||
sed -i "4s/.*/ url \"https:\/\/github.com\/majd\/ipatool\/releases\/download\/v${{ needs.get_version.outputs.version }}\/ipatool-${{ needs.get_version.outputs.version }}-macos-arm64.tar.gz\"/" Casks/ipatool.rb
|
||||
sed -i "5s/.*/ binary \"bin\/ipatool-${{ needs.get_version.outputs.version }}-macos-arm64\", target: \"ipatool\"/" Casks/ipatool.rb
|
||||
sed -i "7s/.*/ sha256 \"$SHA256_AMD64\"/" Casks/ipatool.rb
|
||||
sed -i "8s/.*/ url \"https:\/\/github.com\/majd\/ipatool\/releases\/download\/v${{ needs.get_version.outputs.version }}\/ipatool-${{ needs.get_version.outputs.version }}-macos-amd64.tar.gz\"/" Casks/ipatool.rb
|
||||
sed -i "9s/.*/ binary \"bin\/ipatool-${{ needs.get_version.outputs.version }}-macos-amd64\", target: \"ipatool\"/" Casks/ipatool.rb
|
||||
sed -i "12s/.*/ version \"${{ needs.get_version.outputs.version }}\"/" Casks/ipatool.rb
|
||||
git config --local user.name ${{ secrets.GH_NAME }}
|
||||
git config --local user.email ${{ secrets.GH_EMAIL }}
|
||||
git add Casks/ipatool.rb
|
||||
git commit -m "Update ipatool to v${{ needs.get_version.outputs.version }}"
|
||||
git push "https://${{ secrets.GH_TOKEN }}@github.com/${{ secrets.HOMEBREW_REPO }}.git" --set-upstream "main"
|
||||
env:
|
||||
SHA256_ARM64: ${{ steps.sha256.outputs.sha256_arm64 }}
|
||||
SHA256_AMD64: ${{ steps.sha256.outputs.sha256_amd64 }}
|
||||
@@ -1,23 +0,0 @@
|
||||
name: Unit Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
run_tests:
|
||||
name: Run tests
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
runner: [ubuntu-latest, windows-latest, windows-11-arm]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go generate github.com/majd/ipatool/...
|
||||
- run: go test -v github.com/majd/ipatool/...
|
||||
+127
-4
@@ -1,7 +1,130 @@
|
||||
### macOS ###
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
.vscode/
|
||||
.idea/
|
||||
**/*_mock.go
|
||||
exp/
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
### Swift ###
|
||||
# Xcode
|
||||
#
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
## User settings
|
||||
xcuserdata/
|
||||
|
||||
## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
|
||||
*.xcscmblueprint
|
||||
*.xccheckout
|
||||
|
||||
## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
|
||||
build/
|
||||
DerivedData/
|
||||
*.moved-aside
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
|
||||
## Obj-C/Swift specific
|
||||
*.hmap
|
||||
|
||||
## App packaging
|
||||
*.ipa
|
||||
*.dSYM.zip
|
||||
*.dSYM
|
||||
.build*
|
||||
|
||||
## Playgrounds
|
||||
timeline.xctimeline
|
||||
playground.xcworkspace
|
||||
|
||||
# Swift Package Manager
|
||||
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
|
||||
# Packages/
|
||||
# Package.pins
|
||||
# Package.resolved
|
||||
# *.xcodeproj
|
||||
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
|
||||
# hence it is not needed unless you have added a package configuration file to your project
|
||||
# .swiftpm
|
||||
|
||||
.build/
|
||||
|
||||
# CocoaPods
|
||||
# We recommend against adding the Pods directory to your .gitignore. However
|
||||
# you should judge for yourself, the pros and cons are mentioned at:
|
||||
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
|
||||
# Pods/
|
||||
# Add this line if you want to avoid checking in source code from the Xcode workspace
|
||||
# *.xcworkspace
|
||||
|
||||
# Carthage
|
||||
# Add this line if you want to avoid checking in source code from Carthage dependencies.
|
||||
# Carthage/Checkouts
|
||||
|
||||
Carthage/Build/
|
||||
|
||||
# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12)
|
||||
# Dependencies/
|
||||
# .accio/
|
||||
|
||||
# fastlane
|
||||
# It is recommended to not store the screenshots in the git repo.
|
||||
# Instead, use fastlane to re-generate the screenshots whenever they are needed.
|
||||
# For more information about the recommended setup visit:
|
||||
# https://docs.fastlane.tools/best-practices/source-control/#source-control
|
||||
|
||||
fastlane/report.xml
|
||||
fastlane/Preview.html
|
||||
fastlane/screenshots/**/*.png
|
||||
fastlane/test_output
|
||||
|
||||
# Code Injection
|
||||
# After new code Injection tools there's a generated folder /iOSInjectionProject
|
||||
# https://github.com/johnno1962/injectionforxcode
|
||||
|
||||
iOSInjectionProject/
|
||||
|
||||
### Xcode ###
|
||||
# Xcode
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
|
||||
|
||||
|
||||
## Gcc Patch
|
||||
/*.gcno
|
||||
|
||||
### Xcode Patch ###
|
||||
*.xcodeproj/*
|
||||
!*.xcodeproj/project.pbxproj
|
||||
!*.xcodeproj/xcshareddata/
|
||||
!*.xcworkspace/contents.xcworkspacedata
|
||||
**/xcshareddata/WorkspaceSettings.xcsettings
|
||||
@@ -1,38 +0,0 @@
|
||||
version: "2"
|
||||
linters:
|
||||
enable:
|
||||
- ginkgolinter
|
||||
- godot
|
||||
- godox
|
||||
- importas
|
||||
- nlreturn
|
||||
- nonamedreturns
|
||||
- prealloc
|
||||
- predeclared
|
||||
- unconvert
|
||||
- unparam
|
||||
- usestdlibvars
|
||||
- wastedassign
|
||||
- wrapcheck
|
||||
- wsl
|
||||
exclusions:
|
||||
generated: lax
|
||||
presets:
|
||||
- comments
|
||||
- common-false-positives
|
||||
- legacy
|
||||
- std-error-handling
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
- goimports
|
||||
exclusions:
|
||||
generated: lax
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
@@ -0,0 +1,17 @@
|
||||
prefix ?= /usr/local
|
||||
bindir = $(prefix)/bin
|
||||
|
||||
build:
|
||||
xcodebuild -scheme ipatool -configuration release -archivePath .build archive
|
||||
|
||||
install: build
|
||||
install -d "$(bindir)"
|
||||
install ".build.xcarchive/Products/$(bindir)/ipatool" "$(bindir)"
|
||||
|
||||
uninstall:
|
||||
rm -rf "$(bindir)/ipatool"
|
||||
|
||||
clean:
|
||||
rm -rf .build.xcarchive
|
||||
|
||||
.PHONY: build install uninstall clean
|
||||
@@ -1,87 +1,70 @@
|
||||
<p align="center">
|
||||
<a href="https://GitHub.com/majd/ipatool/releases/"><img src="https://img.shields.io/github/release/majd/ipatool.svg?label=Release" alt="Release"></a>
|
||||
<a href="https://github.com/majd/ipatool/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License"></a>
|
||||
<a href="https://github.com/sponsors/majd"><img src="https://img.shields.io/badge/Sponsor-%E2%9D%A4-pink.svg" alt="Sponsor"></a>
|
||||
</p>
|
||||
# IPATool
|
||||
[](https://GitHub.com/majd/ipatool/releases/)
|
||||

|
||||

|
||||
[](https://github.com/majd/ipatool/blob/main/LICENSE)
|
||||
|
||||
<p align="center">
|
||||
<code>ipatool</code> is a command line tool that allows you to search for iOS, iPadOS, tvOS, watchOS, visionOS, and macOS apps on the <a href="https://apps.apple.com">App Store</a>, and download <code>.ipa</code> or macOS <code>.pkg</code> app packages.
|
||||
</p>
|
||||
`ipatool` is a command line tool that allows you to search for iOS apps on the [App Store](https://apps.apple.com) and download a copy of the app package, known as an _ipa_ file.
|
||||
|
||||
<p align="center">
|
||||
<img src="./resources/demo.gif" alt="Demo">
|
||||
</p>
|
||||

|
||||
|
||||
## Requirements
|
||||
|
||||
- A supported operating system (macOS, Linux, Windows or iOS).
|
||||
- An Apple Account already configured to use the App Store.
|
||||
|
||||
## Installation
|
||||
|
||||
### Linux and Windows
|
||||
|
||||
You can grab the latest version of `ipatool` from [GitHub releases](https://github.com/majd/ipatool/releases).
|
||||
|
||||
### macOS
|
||||
|
||||
You can install `ipatool` using [Homebrew](https://brew.sh).
|
||||
|
||||
```shell
|
||||
$ brew install ipatool
|
||||
```
|
||||
* macOS 10.11 or later.
|
||||
* Apple ID set up to use the App Store.
|
||||
|
||||
## Usage
|
||||
|
||||
To get started, run the following command.
|
||||
To search for apps on the App Store, use the `search` command.
|
||||
|
||||
```text
|
||||
$ ipatool --help
|
||||
A cli tool for interacting with Apple's ipa files
|
||||
```
|
||||
OVERVIEW: Search for iOS apps available on the App Store.
|
||||
|
||||
Usage:
|
||||
ipatool [command]
|
||||
USAGE: ipatool search [--limit <limit>] <term> [--log-level <log-level>]
|
||||
|
||||
Available Commands:
|
||||
auth Authenticate with the App Store
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
download Download iOS, iPadOS, tvOS, watchOS, visionOS, and macOS app packages from the App Store
|
||||
get-version-metadata Retrieves the metadata for a specific version of an app
|
||||
help Help about any command
|
||||
list-purchases List apps owned by the authenticated App Store account
|
||||
list-versions List the available versions of an App Store app
|
||||
purchase Obtain a license for the app from the App Store
|
||||
search Search for iOS, iPadOS, tvOS, watchOS, visionOS, and macOS apps available on the App Store
|
||||
ARGUMENTS:
|
||||
<term> The term to search for.
|
||||
|
||||
Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
-h, --help help for ipatool
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
-v, --version version for ipatool
|
||||
|
||||
Use "ipatool [command] --help" for more information about a command.
|
||||
OPTIONS:
|
||||
--limit <limit> (default: 5)
|
||||
--log-level <log-level> (default: info)
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
```
|
||||
|
||||
**Note:** the tool runs in interactive mode by default. Use the `--non-interactive` flag
|
||||
if running in an automated environment.
|
||||
To download a copy of the ipa file, use the `download` command.
|
||||
|
||||
## Compiling
|
||||
```
|
||||
OVERVIEW: Download (encrypted) iOS app packages from the App Store.
|
||||
|
||||
The tool can be compiled using the Go toolchain.
|
||||
USAGE: ipatool download --bundle-identifier <bundle-identifier> [--email <email>] [--password <password>] [--log-level <log-level>]
|
||||
|
||||
```shell
|
||||
$ go build -o ipatool
|
||||
OPTIONS:
|
||||
-b, --bundle-identifier <bundle-identifier>
|
||||
The bundle identifier of the target iOS app.
|
||||
-e, --email <email> The email address for the Apple ID.
|
||||
-p, --password <password>
|
||||
The password for the Apple ID.
|
||||
--log-level <log-level> (default: info)
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
```
|
||||
|
||||
Unit tests can be executed with the following commands.
|
||||
**Note:** You can specify the Apple ID email address and username as arguments when using the tool or by setting them as environment variables (`IPATOOL_EMAIL` and `IPATOOL_PASSWORD`). If you do not specify this information using either of those methods, the tool will prompt for user input in an interactive session.
|
||||
|
||||
```shell
|
||||
$ go generate ./...
|
||||
$ go test -v ./...
|
||||
```
|
||||
## Common Knowledge
|
||||
|
||||
## License
|
||||
**Are my Apple ID credentials stored safely?**
|
||||
|
||||
ipatool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
|
||||
The tool does not store your credentials anywhere and it only communicates with Apple servers directly. Feel free to go through the source code.
|
||||
|
||||
**Will my Apple ID get flagged for using this tool?**
|
||||
|
||||
Maybe, but probably not. While this tool communicates with iTunes and the App Store directly, mimicking the behavior of iTunes running on macOS, I cannot guarrantee its safety. I recommend using a throwaway Apple ID. **Use this tool your own risk**.
|
||||
|
||||
**Can I use this tool to download paid apps without paying for them?**
|
||||
|
||||
**No**. This is is not a piracy tool; you can only download apps that you have previously install on your iOS device. This limitation applies to free apps as well. Essentially, your account must already have a license for the app you are trying to download.
|
||||
|
||||
**Can I use this tool to sideload unuspported iOS apps on Apple Silicon Macs?**
|
||||
|
||||
While it was previously possible to download ipa files using this tool and install them on Macs running on Apple Silicon, this is no longer the case as of recently. Apple stopped serving macOS compatible `sinf` data for the app package. You could, however, use this tool to get a copy of the iOS app and use a jailbroken iOS device to strip any codesigning requirements then codesign the app again using an adhoc signature to run on Apple Silicon.
|
||||
@@ -0,0 +1,193 @@
|
||||
//
|
||||
// Download.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
|
||||
struct Download: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Download (encrypted) iOS app packages from the App Store.")
|
||||
}
|
||||
|
||||
@Option(name: [.short, .long], help: "The bundle identifier of the target iOS app.")
|
||||
private var bundleIdentifier: String
|
||||
|
||||
@Option(name: [.short, .long], help: "The email address for the Apple ID.")
|
||||
private var email: String?
|
||||
|
||||
@Option(name: [.short, .long], help: "The password for the Apple ID.")
|
||||
private var password: String?
|
||||
|
||||
@Option
|
||||
private var logLevel: LogLevel = .info
|
||||
}
|
||||
|
||||
extension Download {
|
||||
func run() throws {
|
||||
let logger = ConsoleLogger(level: logLevel)
|
||||
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(urlSession: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
logger.log("Creating App Store client...", level: .debug)
|
||||
let storeClient = StoreClient(httpClient: httpClient)
|
||||
|
||||
logger.log("Creating download client...", level: .debug)
|
||||
let downloadClient = HTTPDownloadClient()
|
||||
|
||||
logger.log("Querying the iTunes store for '\(bundleIdentifier)'...", level: .info)
|
||||
let app: iTunesResponse.Result
|
||||
|
||||
do {
|
||||
app = try itunesClient.lookup(bundleIdentifier: bundleIdentifier)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case iTunesClient.Error.appNotFound:
|
||||
logger.log("Could not find app.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
logger.log("Found app: \(app.name) (\(app.version)).", level: .debug)
|
||||
|
||||
let email: String
|
||||
let password: String
|
||||
|
||||
if let cliEmail = self.email {
|
||||
email = cliEmail
|
||||
} else if let envEmail = ProcessInfo.processInfo.environment["IPATOOL_EMAIL"] {
|
||||
email = envEmail
|
||||
} else if let inputEmail = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID email: ", level: .warning)))) {
|
||||
email = inputEmail
|
||||
} else {
|
||||
logger.log("An Apple ID email address is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
if let cliPassword = self.password {
|
||||
password = cliPassword
|
||||
} else if let envPassword = ProcessInfo.processInfo.environment["IPATOOL_PASSWORD"] {
|
||||
password = envPassword
|
||||
} else if let inputPassword = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID password: ", level: .warning)))) {
|
||||
password = inputPassword
|
||||
} else {
|
||||
logger.log("An Apple ID password is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
let account: StoreResponse.Account
|
||||
|
||||
do {
|
||||
logger.log("Authenticating with the App Store...", level: .info)
|
||||
account = try storeClient.authenticate(email: email, password: password)
|
||||
} catch {
|
||||
switch error {
|
||||
case StoreResponse.Error.codeRequired:
|
||||
let code = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter 2FA code: ", level: .warning))))
|
||||
|
||||
do {
|
||||
account = try storeClient.authenticate(email: email, password: password, code: code)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.invalidResponse:
|
||||
logger.log("Received invalid response.", level: .error)
|
||||
case StoreResponse.Error.invalidAccount:
|
||||
logger.log("This Apple ID has not been set up to use the App Store.", level: .error)
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
logger.log("Invalid credentials.", level: .error)
|
||||
case StoreResponse.Error.lockedAccount:
|
||||
logger.log("This Apple ID has been disabled for security reasons.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
default:
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.invalidResponse:
|
||||
logger.log("Received invalid response.", level: .error)
|
||||
case StoreResponse.Error.invalidAccount:
|
||||
logger.log("This Apple ID has not been set up to use the App Store.", level: .error)
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
logger.log("Invalid credentials.", level: .error)
|
||||
case StoreResponse.Error.lockedAccount:
|
||||
logger.log("This Apple ID has been disabled for security reasons.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
logger.log("Authenticated as '\(account.firstName) \(account.lastName)'.", level: .info)
|
||||
|
||||
logger.log("Requesting a signed copy of '\(app.identifier)' from the App Store...", level: .info)
|
||||
let item: StoreResponse.Item
|
||||
|
||||
do {
|
||||
item = try storeClient.item(identifier: "\(app.identifier)", directoryServicesIdentifier: account.directoryServicesIdentifier)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.invalidResponse:
|
||||
logger.log("Received invalid response.", level: .error)
|
||||
case StoreResponse.Error.invalidItem:
|
||||
logger.log("Received invalid store item.", level: .error)
|
||||
case StoreResponse.Error.invalidLicense:
|
||||
logger.log("Your Apple ID does not have a license for this app. Download the app on an iOS device to obtain a license.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
logger.log("Received a response of the signed copy: \(item.md5).", level: .debug)
|
||||
|
||||
logger.log("Creating signature client...", level: .debug)
|
||||
let path = FileManager.default.currentDirectoryPath
|
||||
.appending("/\(bundleIdentifier)_\(app.identifier)_v\(app.version)_\(Int.random(in: 100...999))")
|
||||
.appending(".ipa")
|
||||
|
||||
logger.log("Output path: \(path).", level: .debug)
|
||||
let signatureClient = SignatureClient(fileManager: .default, filePath: path)
|
||||
|
||||
logger.log("Downloading app package...", level: .info)
|
||||
try downloadClient.download(from: item.url, to: URL(fileURLWithPath: path)) { progress in
|
||||
logger.log("Downloading app package... [\(Int((progress * 100).rounded()))%]",
|
||||
prefix: "\u{1B}[1A\u{1B}[K",
|
||||
level: .info)
|
||||
}
|
||||
logger.log("Saved app package to \(URL(fileURLWithPath: path).lastPathComponent).", level: .info)
|
||||
|
||||
logger.log("Applying patches...", level: .info)
|
||||
|
||||
do {
|
||||
try signatureClient.appendMetadata(item: item, email: email)
|
||||
try signatureClient.appendSignature(item: item)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
logger.log("Failed to apply patches. The ipa file will be left incomplete.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
logger.log("Done.", level: .info)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//
|
||||
// IPATool.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
|
||||
struct IPATool: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(commandName: "ipatool",
|
||||
abstract: "A cli tool for interacting with Apple's ipa files.",
|
||||
version: "1.0.2",
|
||||
subcommands: [Download.self, Search.self])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//
|
||||
// Search.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
|
||||
struct Search: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Search for iOS apps available on the App Store.")
|
||||
}
|
||||
|
||||
@Option
|
||||
private var limit: Int = 5
|
||||
|
||||
@Argument(help: "The term to search for.")
|
||||
var term: String
|
||||
|
||||
@Option
|
||||
private var logLevel: LogLevel = .info
|
||||
}
|
||||
|
||||
extension Search {
|
||||
func run() throws {
|
||||
let logger = ConsoleLogger(level: logLevel)
|
||||
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(urlSession: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Searching for '\(term)'...", level: .info)
|
||||
let results = try itunesClient.search(term: term, limit: limit)
|
||||
|
||||
guard !results.isEmpty else {
|
||||
logger.log("No results found.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
let output = results
|
||||
.enumerated()
|
||||
.map({ "\($0 + 1). \($1.name): \($1.bundleIdentifier) (\($1.version))." })
|
||||
.joined(separator: "\n")
|
||||
|
||||
logger.log("Found \(results.count) \(results.count == 1 ? "result" : "results"):\n\(output)", level: .info)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//
|
||||
// ConsoleLogger.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
final class ConsoleLogger: Logging {
|
||||
private let level: LogLevel
|
||||
|
||||
init(level: LogLevel) {
|
||||
self.level = level
|
||||
}
|
||||
|
||||
func log(_ message: String, level: LogLevel) {
|
||||
guard level <= self.level else { return }
|
||||
print(compile(message, level: level))
|
||||
}
|
||||
|
||||
func log(_ message: String, prefix: String, level: LogLevel) {
|
||||
guard level <= self.level else { return }
|
||||
print("\(prefix)\(compile(message, level: level))")
|
||||
}
|
||||
|
||||
func compile(_ message: String, level: LogLevel) -> String {
|
||||
return "==> \(level.prefix)\(message)".trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//
|
||||
// LogLevel.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ArgumentParser
|
||||
|
||||
enum LogLevel: String, ExpressibleByArgument {
|
||||
case error
|
||||
case warning
|
||||
case info
|
||||
case debug
|
||||
}
|
||||
|
||||
extension LogLevel {
|
||||
var prefix: String {
|
||||
switch self {
|
||||
case .error:
|
||||
return "❌\t[Error] "
|
||||
case .warning:
|
||||
return "⚠️\t[Warning] "
|
||||
case .info:
|
||||
return "ℹ️\t[Info] "
|
||||
case .debug:
|
||||
return "🛠\t[Debug] "
|
||||
}
|
||||
}
|
||||
|
||||
var priority: Int {
|
||||
switch self {
|
||||
case .error:
|
||||
return 0
|
||||
case .warning:
|
||||
return 1
|
||||
case .info:
|
||||
return 2
|
||||
case .debug:
|
||||
return 3
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension LogLevel: Comparable {
|
||||
static func < (lhs: LogLevel, rhs: LogLevel) -> Bool {
|
||||
return lhs.priority < rhs.priority
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//
|
||||
// Logging.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol Logging {
|
||||
func compile(_ message: String, level: LogLevel) -> String
|
||||
func log(_ message: String, prefix: String, level: LogLevel)
|
||||
func log(_ message: String, level: LogLevel)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//
|
||||
// HTTPClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPClientInterface {
|
||||
func send(_ request: HTTPRequest, completion: @escaping (Result<HTTPResponse, Error>) -> Void)
|
||||
}
|
||||
|
||||
extension HTTPClientInterface {
|
||||
func send(_ request: HTTPRequest) throws -> HTTPResponse {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<HTTPResponse, Error>?
|
||||
|
||||
send(request) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw HTTPClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(response):
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class HTTPClient: HTTPClientInterface {
|
||||
private let urlSession: URLSessionInterface
|
||||
|
||||
init(urlSession: URLSessionInterface) {
|
||||
self.urlSession = urlSession
|
||||
}
|
||||
|
||||
func send(_ request: HTTPRequest, completion: @escaping (Result<HTTPResponse, Swift.Error>) -> Void) {
|
||||
do {
|
||||
let urlRequest = try makeURLRequest(from: request)
|
||||
|
||||
urlSession.dataTask(with: urlRequest) { (data, response, error) in
|
||||
if let error = error {
|
||||
return completion(.failure(error))
|
||||
}
|
||||
|
||||
guard let response = response as? HTTPURLResponse else {
|
||||
return completion(.failure(Error.invalidResponse(response)))
|
||||
}
|
||||
|
||||
completion(.success(.init(statusCode: response.statusCode, data: data)))
|
||||
}.resume()
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
private func makeURLRequest(from request: HTTPRequest) throws -> URLRequest {
|
||||
var urlRequest = URLRequest(url: request.endpoint.url)
|
||||
urlRequest.httpMethod = request.method.rawValue
|
||||
|
||||
switch request.payload {
|
||||
case .none:
|
||||
urlRequest.httpBody = nil
|
||||
case let .urlEncoding(propertyList):
|
||||
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
||||
|
||||
var urlComponents = URLComponents(string: request.endpoint.url.absoluteString)
|
||||
urlComponents?.queryItems = !propertyList.isEmpty ? propertyList.map { URLQueryItem(name: $0.0, value: $0.1.description) } : nil
|
||||
|
||||
switch request.method {
|
||||
case .get:
|
||||
urlRequest.url = urlComponents?.url
|
||||
case .post:
|
||||
urlRequest.httpBody = urlComponents?.percentEncodedQuery?.data(using: .utf8, allowLossyConversion: false)
|
||||
}
|
||||
case let .xml(value):
|
||||
urlRequest.setValue("application/xml", forHTTPHeaderField: "Content-Type")
|
||||
urlRequest.httpBody = try PropertyListSerialization.data(fromPropertyList: value, format: .xml, options: 0)
|
||||
}
|
||||
|
||||
request.headers.forEach { urlRequest.setValue($0.value, forHTTPHeaderField: $0.key) }
|
||||
|
||||
return urlRequest
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPClient {
|
||||
enum Error: Swift.Error {
|
||||
case invalidResponse(URLResponse?)
|
||||
case timeout
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//
|
||||
// HTTPDownloadClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPDownloadClientInterface {
|
||||
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void, completion: @escaping (Result<Void, Error>) -> Void)
|
||||
}
|
||||
|
||||
extension HTTPDownloadClientInterface {
|
||||
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void) throws {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<Void, Error>?
|
||||
|
||||
download(from: source, to: target, progress: progress) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw HTTPClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class HTTPDownloadClient: NSObject, HTTPDownloadClientInterface {
|
||||
private var urlSession: URLSession!
|
||||
private var progressHandler: ((Float) -> Void)?
|
||||
private var completionHandler: ((Result<Void, Swift.Error>) -> Void)?
|
||||
private var targetURL: URL?
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
self.urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
|
||||
}
|
||||
|
||||
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void, completion: @escaping (Result<Void, Swift.Error>) -> Void) {
|
||||
assert(progressHandler == nil)
|
||||
assert(completionHandler == nil)
|
||||
assert(targetURL == nil)
|
||||
|
||||
progressHandler = progress
|
||||
completionHandler = completion
|
||||
targetURL = target
|
||||
urlSession.downloadTask(with: source).resume()
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPDownloadClient: URLSessionDownloadDelegate {
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
||||
progressHandler?(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
|
||||
defer {
|
||||
progressHandler = nil
|
||||
completionHandler = nil
|
||||
targetURL = nil
|
||||
}
|
||||
|
||||
guard let target = targetURL else {
|
||||
return completionHandler?(.failure(Error.invalidTarget)) ?? ()
|
||||
}
|
||||
|
||||
do {
|
||||
try FileManager.default.moveItem(at: location, to: target)
|
||||
completionHandler?(.success(()))
|
||||
} catch {
|
||||
completionHandler?(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPDownloadClient {
|
||||
enum Error: Swift.Error {
|
||||
case invalidTarget
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//
|
||||
// HTTPEndpoint.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPEndpoint {
|
||||
var url: URL { get }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//
|
||||
// HTTPMethod.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum HTTPMethod: String {
|
||||
case get = "GET"
|
||||
case post = "POST"
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//
|
||||
// HTTPPayload.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum HTTPPayload {
|
||||
case xml([String: String])
|
||||
case urlEncoding([String: String])
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// HTTPRequest.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPRequest {
|
||||
var method: HTTPMethod { get }
|
||||
var endpoint: HTTPEndpoint { get }
|
||||
var headers: [String: String] { get }
|
||||
var payload: HTTPPayload? { get }
|
||||
}
|
||||
|
||||
extension HTTPRequest {
|
||||
var headers: [String: String] { [:] }
|
||||
var payload: HTTPPayload? { nil }
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//
|
||||
// HTTPResponse.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct HTTPResponse {
|
||||
let statusCode: Int
|
||||
let data: Data?
|
||||
}
|
||||
|
||||
extension HTTPResponse {
|
||||
func decode<T: Decodable>(_ type: T.Type, as decoder: Decoder) throws -> T {
|
||||
guard let data = data else {
|
||||
throw Error.noData
|
||||
}
|
||||
|
||||
switch decoder {
|
||||
case .json:
|
||||
let decoder = JSONDecoder()
|
||||
decoder.userInfo = [.init(rawValue: "data")!: data]
|
||||
return try decoder.decode(type, from: data)
|
||||
case .xml:
|
||||
let decoder = PropertyListDecoder()
|
||||
decoder.userInfo = [.init(rawValue: "data")!: data]
|
||||
return try decoder.decode(type, from: data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPResponse {
|
||||
enum Decoder {
|
||||
case json
|
||||
case xml
|
||||
}
|
||||
|
||||
enum Error: Swift.Error {
|
||||
case noData
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//
|
||||
// URLSession.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol URLSessionInterface {
|
||||
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
|
||||
}
|
||||
|
||||
extension URLSession: URLSessionInterface {}
|
||||
@@ -0,0 +1,109 @@
|
||||
//
|
||||
// SignatureClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ZIPFoundation
|
||||
|
||||
protocol SignatureClientInterface {
|
||||
func appendMetadata(item: StoreResponse.Item, email: String) throws
|
||||
func appendSignature(item: StoreResponse.Item) throws
|
||||
}
|
||||
|
||||
final class SignatureClient: SignatureClientInterface {
|
||||
private let fileManager: FileManager
|
||||
private let filePath: String
|
||||
|
||||
init(fileManager: FileManager, filePath: String) {
|
||||
self.fileManager = fileManager
|
||||
self.filePath = filePath
|
||||
}
|
||||
|
||||
func appendMetadata(item: StoreResponse.Item, email: String) throws {
|
||||
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
|
||||
throw Error.invalidArchive
|
||||
}
|
||||
|
||||
var metadata = item.metadata
|
||||
metadata["apple-id"] = email
|
||||
metadata["userName"] = email
|
||||
|
||||
let metadataUrl = URL(fileURLWithPath: NSTemporaryDirectory().appending("\(UUID().uuidString)/iTunesMetadata.plist"))
|
||||
|
||||
try fileManager.createDirectory(at: metadataUrl.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try PropertyListSerialization.data(fromPropertyList: metadata, format: .xml, options: .zero).write(to: metadataUrl)
|
||||
try archive.addEntry(with: metadataUrl.lastPathComponent, relativeTo: metadataUrl.deletingLastPathComponent())
|
||||
try fileManager.removeItem(at: metadataUrl)
|
||||
}
|
||||
|
||||
func appendSignature(item: StoreResponse.Item) throws {
|
||||
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
|
||||
throw Error.invalidArchive
|
||||
}
|
||||
|
||||
let manifest = try readPlist(archive: archive, matchingSuffix: ".app/SC_Info/Manifest.plist", type: Manifest.self)
|
||||
|
||||
guard let infoEntry = archive.first(where: { $0.path.hasSuffix(".app/Info.plist") }) else {
|
||||
throw Error.invalidAppBundle
|
||||
}
|
||||
|
||||
let appBundleName = URL(fileURLWithPath: infoEntry.path)
|
||||
.deletingLastPathComponent()
|
||||
.deletingPathExtension()
|
||||
.lastPathComponent
|
||||
|
||||
guard let signatureItem = item.signatures.first(where: { $0.id == 0 }), let signatureTargetPath = manifest.paths.first else {
|
||||
throw Error.invalidSignature
|
||||
}
|
||||
|
||||
let signatureBaseUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
|
||||
let signatureUrl = signatureBaseUrl
|
||||
.appendingPathComponent("Payload")
|
||||
.appendingPathComponent(appBundleName)
|
||||
.appendingPathExtension("app")
|
||||
.appendingPathComponent(signatureTargetPath)
|
||||
|
||||
let signatureRelativePath = signatureUrl.path.replacingOccurrences(of: "\(signatureBaseUrl.path)/", with: "")
|
||||
|
||||
try fileManager.createDirectory(at: signatureUrl.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try signatureItem.sinf.write(to: signatureUrl)
|
||||
try archive.addEntry(with: signatureRelativePath, relativeTo: signatureBaseUrl)
|
||||
try fileManager.removeItem(at: signatureBaseUrl)
|
||||
}
|
||||
|
||||
private func readPlist<T: Decodable>(archive: Archive, matchingSuffix: String, type: T.Type) throws -> T {
|
||||
guard let entry = archive.first(where: { $0.path.hasSuffix(matchingSuffix) }) else {
|
||||
throw Error.fileNotFound(matchingSuffix)
|
||||
}
|
||||
|
||||
let url = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent(UUID().uuidString).appendingPathExtension("plist")
|
||||
_ = try archive.extract(entry, to: url)
|
||||
|
||||
let data = try Data(contentsOf: url)
|
||||
let plist = try PropertyListDecoder().decode(type, from: data)
|
||||
|
||||
try FileManager.default.removeItem(at: url)
|
||||
|
||||
return plist
|
||||
}
|
||||
}
|
||||
|
||||
extension SignatureClient {
|
||||
struct Manifest: Codable {
|
||||
let paths: [String]
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case paths = "SinfPaths"
|
||||
}
|
||||
}
|
||||
|
||||
enum Error: Swift.Error {
|
||||
case invalidArchive
|
||||
case invalidAppBundle
|
||||
case invalidSignature
|
||||
case fileNotFound(String)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
//
|
||||
// StoreClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol StoreClientInterface {
|
||||
func authenticate(email: String, password: String, code: String?, completion: @escaping (Result<StoreResponse.Account, Error>) -> Void)
|
||||
func item(identifier: String, directoryServicesIdentifier: String, completion: @escaping (Result<StoreResponse.Item, Error>) -> Void)
|
||||
}
|
||||
|
||||
extension StoreClientInterface {
|
||||
func authenticate(email: String,
|
||||
password: String,
|
||||
code: String? = nil,
|
||||
completion: @escaping (Result<StoreResponse.Account, Swift.Error>) -> Void) {
|
||||
authenticate(email: email, password: password, code: code, completion: completion)
|
||||
}
|
||||
|
||||
func authenticate(email: String, password: String, code: String? = nil) throws -> StoreResponse.Account {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<StoreResponse.Account, Error>?
|
||||
|
||||
authenticate(email: email, password: password, code: code) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw StoreClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
func item(identifier: String, directoryServicesIdentifier: String) throws -> StoreResponse.Item {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<StoreResponse.Item, Error>?
|
||||
|
||||
item(identifier: identifier, directoryServicesIdentifier: directoryServicesIdentifier) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw StoreClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class StoreClient: StoreClientInterface {
|
||||
private let httpClient: HTTPClient
|
||||
|
||||
init(httpClient: HTTPClient) {
|
||||
self.httpClient = httpClient
|
||||
}
|
||||
|
||||
func authenticate(email: String, password: String, code: String?, completion: @escaping (Result<StoreResponse.Account, Swift.Error>) -> Void) {
|
||||
authenticate(email: email,
|
||||
password: password,
|
||||
code: code,
|
||||
isFirstAttempt: true,
|
||||
completion: completion)
|
||||
}
|
||||
|
||||
private func authenticate(email: String,
|
||||
password: String,
|
||||
code: String?,
|
||||
isFirstAttempt: Bool,
|
||||
completion: @escaping (Result<StoreResponse.Account, Swift.Error>) -> Void) {
|
||||
let request = StoreRequest.authenticate(email: email, password: password, code: code)
|
||||
|
||||
httpClient.send(request) { [weak self] result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch decoded {
|
||||
case let .account(account):
|
||||
completion(.success(account))
|
||||
case .item:
|
||||
completion(.failure(Error.invalidResponse))
|
||||
case let .failure(error):
|
||||
switch error {
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
if isFirstAttempt {
|
||||
return self?.authenticate(email: email,
|
||||
password: password,
|
||||
code: code,
|
||||
isFirstAttempt: false,
|
||||
completion: completion) ?? ()
|
||||
}
|
||||
|
||||
completion(.failure(error))
|
||||
default:
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func item(identifier: String, directoryServicesIdentifier: String, completion: @escaping (Result<StoreResponse.Item, Swift.Error>) -> Void) {
|
||||
let request = StoreRequest.download(appIdentifier: identifier, directoryServicesIdentifier: directoryServicesIdentifier)
|
||||
|
||||
httpClient.send(request) { result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch decoded {
|
||||
case let .item(item):
|
||||
completion(.success(item))
|
||||
case .account:
|
||||
completion(.failure(Error.invalidResponse))
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreClient {
|
||||
enum Error: Swift.Error {
|
||||
case timeout
|
||||
case invalidResponse
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// StoreEndpoint.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum StoreEndpoint {
|
||||
case authenticate(prefix: String, guid: String)
|
||||
case download(guid: String)
|
||||
}
|
||||
|
||||
extension StoreEndpoint: HTTPEndpoint {
|
||||
var url: URL {
|
||||
var components = URLComponents(string: path)!
|
||||
components.scheme = "https"
|
||||
components.host = host
|
||||
return components.url!
|
||||
}
|
||||
|
||||
private var host: String {
|
||||
switch self {
|
||||
case let .authenticate(prefix, _):
|
||||
return "\(prefix)-buy.itunes.apple.com"
|
||||
case .download:
|
||||
return "p25-buy.itunes.apple.com"
|
||||
}
|
||||
}
|
||||
|
||||
private var path: String {
|
||||
switch self {
|
||||
case let .authenticate(_, guid):
|
||||
return "/WebObjects/MZFinance.woa/wa/authenticate?guid=\(guid)"
|
||||
case let .download(guid):
|
||||
return "/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct?guid=\(guid)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//
|
||||
// StoreRequest.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum StoreRequest {
|
||||
case authenticate(email: String, password: String, code: String? = nil)
|
||||
case download(appIdentifier: String, directoryServicesIdentifier: String)
|
||||
}
|
||||
|
||||
extension StoreRequest: HTTPRequest {
|
||||
var endpoint: HTTPEndpoint {
|
||||
switch self {
|
||||
case let .authenticate(_, _, code):
|
||||
return StoreEndpoint.authenticate(prefix: (code == nil) ? "p25" : "p71", guid: guid)
|
||||
case .download:
|
||||
return StoreEndpoint.download(guid: guid)
|
||||
}
|
||||
}
|
||||
|
||||
var method: HTTPMethod {
|
||||
return .post
|
||||
}
|
||||
|
||||
var headers: [String: String] {
|
||||
var headers: [String: String] = [
|
||||
"User-Agent": "Configurator/2.0 (Macintosh; OS X 10.12.6; 16G29) AppleWebKit/2603.3.8",
|
||||
"Content-Type": "application/x-www-form-urlencoded"
|
||||
]
|
||||
|
||||
switch self {
|
||||
case .authenticate:
|
||||
break
|
||||
case let .download(_, directoryServicesIdentifier):
|
||||
headers["X-Dsid"] = directoryServicesIdentifier
|
||||
headers["iCloud-DSID"] = directoryServicesIdentifier
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
var payload: HTTPPayload? {
|
||||
switch self {
|
||||
case let .authenticate(email, password, code):
|
||||
return .xml([
|
||||
"appleId": email,
|
||||
"attempt": "\(code == nil ? "4" : "2")",
|
||||
"createSession": "true",
|
||||
"guid": guid,
|
||||
"password": "\(password)\(code ?? "")",
|
||||
"rmp": "0",
|
||||
"why": "signIn"
|
||||
])
|
||||
case let .download(appIdentifier, _):
|
||||
return .xml([
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": "\(appIdentifier)"
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreRequest {
|
||||
// This identifier is calculated by reading the MAC address of the device and stripping the nonalphabetic characters from the string.
|
||||
// https://stackoverflow.com/a/31838376
|
||||
private var guid: String {
|
||||
let MAC_ADDRESS_LENGTH = 6
|
||||
let bsds: [String] = ["en0", "en1"]
|
||||
var bsd: String = bsds[0]
|
||||
|
||||
var length : size_t = 0
|
||||
var buffer : [CChar]
|
||||
|
||||
var bsdIndex = Int32(if_nametoindex(bsd))
|
||||
if bsdIndex == 0 {
|
||||
bsd = bsds[1]
|
||||
bsdIndex = Int32(if_nametoindex(bsd))
|
||||
guard bsdIndex != 0 else { fatalError("Could not read MAC address") }
|
||||
}
|
||||
|
||||
let bsdData = Data(bsd.utf8)
|
||||
var managementInfoBase = [CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, bsdIndex]
|
||||
|
||||
guard sysctl(&managementInfoBase, 6, nil, &length, nil, 0) >= 0 else { fatalError("Could not read MAC address") }
|
||||
|
||||
buffer = [CChar](unsafeUninitializedCapacity: length, initializingWith: {buffer, initializedCount in
|
||||
for x in 0..<length { buffer[x] = 0 }
|
||||
initializedCount = length
|
||||
})
|
||||
|
||||
guard sysctl(&managementInfoBase, 6, &buffer, &length, nil, 0) >= 0 else { fatalError("Could not read MAC address") }
|
||||
|
||||
let infoData = Data(bytes: buffer, count: length)
|
||||
let indexAfterMsghdr = MemoryLayout<if_msghdr>.stride + 1
|
||||
let rangeOfToken = infoData[indexAfterMsghdr...].range(of: bsdData)!
|
||||
let lower = rangeOfToken.upperBound
|
||||
let upper = lower + MAC_ADDRESS_LENGTH
|
||||
let macAddressData = infoData[lower..<upper]
|
||||
let addressBytes = macAddressData.map{ String(format:"%02x", $0) }
|
||||
return addressBytes.joined().uppercased()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//
|
||||
// StoreResponse.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum StoreResponse {
|
||||
case failure(error: Swift.Error)
|
||||
case account(Account)
|
||||
case item(Item)
|
||||
}
|
||||
|
||||
extension StoreResponse {
|
||||
struct Account {
|
||||
let firstName: String
|
||||
let lastName: String
|
||||
let directoryServicesIdentifier: String
|
||||
}
|
||||
|
||||
struct Item {
|
||||
let url: URL
|
||||
let md5: String
|
||||
let signatures: [Signature]
|
||||
let metadata: [String: Any]
|
||||
}
|
||||
|
||||
enum Error: Int, Swift.Error {
|
||||
case unknownError = 0
|
||||
case genericError = 5002
|
||||
case codeRequired = 1
|
||||
case invalidLicense = 9610
|
||||
case invalidCredentials = -5000
|
||||
case invalidAccount = 5001
|
||||
case invalidItem = -10000
|
||||
case lockedAccount = -10001
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreResponse: Decodable {
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
|
||||
let error = try container.decodeIfPresent(String.self, forKey: .error)
|
||||
let message = try container.decodeIfPresent(String.self, forKey: .message)
|
||||
|
||||
if container.contains(.account) {
|
||||
let directoryServicesIdentifier = try container.decode(String.self, forKey: .directoryServicesIdentifier)
|
||||
let accountContainer = try container.nestedContainer(keyedBy: AccountInfoCodingKeys.self, forKey: .account)
|
||||
let addressContainer = try accountContainer.nestedContainer(keyedBy: AddressCodingKeys.self, forKey: .address)
|
||||
let firstName = try addressContainer.decode(String.self, forKey: .firstName)
|
||||
let lastName = try addressContainer.decode(String.self, forKey: .lastName)
|
||||
|
||||
self = .account(.init(firstName: firstName, lastName: lastName, directoryServicesIdentifier: directoryServicesIdentifier))
|
||||
} else if let items = try container.decodeIfPresent([Item].self, forKey: .items), let item = items.first {
|
||||
self = .item(item)
|
||||
} else if let error = error, !error.isEmpty {
|
||||
self = .failure(error: Error(rawValue: Int(error) ?? 0) ?? .unknownError)
|
||||
} else {
|
||||
switch message {
|
||||
case "Your account information was entered incorrectly.":
|
||||
self = .failure(error: Error.invalidCredentials)
|
||||
case "An Apple ID verification code is required to sign in. Type your password followed by the verification code shown on your other devices.":
|
||||
self = .failure(error: Error.codeRequired)
|
||||
case "This Apple ID has been locked for security reasons. Visit iForgot to reset your account (https://iforgot.apple.com).":
|
||||
self = .failure(error: Error.lockedAccount)
|
||||
default:
|
||||
self = .failure(error: Error.unknownError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case directoryServicesIdentifier = "dsPersonId"
|
||||
case message = "customerMessage"
|
||||
case items = "songList"
|
||||
case error = "failureType"
|
||||
case account = "accountInfo"
|
||||
}
|
||||
|
||||
private enum AccountInfoCodingKeys: String, CodingKey {
|
||||
case address
|
||||
}
|
||||
|
||||
private enum AddressCodingKeys: String, CodingKey {
|
||||
case firstName
|
||||
case lastName
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreResponse.Item: Decodable {
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let md5 = try container.decode(String.self, forKey: .md5)
|
||||
|
||||
guard let key = CodingUserInfoKey(rawValue: "data"),
|
||||
let data = decoder.userInfo[key] as? Data,
|
||||
let json = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any],
|
||||
let items = json["songList"] as? [[String: Any]],
|
||||
let item = items.first(where: { $0["md5"] as? String == md5 }),
|
||||
let metadata = item["metadata"] as? [String: Any]
|
||||
else { throw StoreResponse.Error.invalidItem }
|
||||
|
||||
let absoluteUrl = try container.decode(String.self, forKey: .url)
|
||||
|
||||
self.md5 = md5
|
||||
self.metadata = metadata
|
||||
self.signatures = try container.decode([Signature].self, forKey: .signatures)
|
||||
|
||||
if let url = URL(string: absoluteUrl) {
|
||||
self.url = url
|
||||
} else {
|
||||
let context = DecodingError.Context(codingPath: [CodingKeys.url], debugDescription: "URL contains illegal characters: \(absoluteUrl).")
|
||||
throw DecodingError.keyNotFound(CodingKeys.url, context)
|
||||
}
|
||||
}
|
||||
|
||||
struct Signature: Decodable {
|
||||
let id: Int
|
||||
let sinf: Data
|
||||
}
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case url = "URL"
|
||||
case metadata
|
||||
case md5
|
||||
case signatures = "sinfs"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//
|
||||
// iTunesClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol iTunesClientInterface {
|
||||
func lookup(bundleIdentifier: String, completion: @escaping (Result<iTunesResponse.Result, Error>) -> Void)
|
||||
func search(term: String, limit: Int, completion: @escaping (Result<[iTunesResponse.Result], Error>) -> Void)
|
||||
}
|
||||
|
||||
extension iTunesClientInterface {
|
||||
func lookup(bundleIdentifier: String) throws -> iTunesResponse.Result {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<iTunesResponse.Result, Error>?
|
||||
|
||||
lookup(bundleIdentifier: bundleIdentifier) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw iTunesClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
func search(term: String, limit: Int) throws -> [iTunesResponse.Result] {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<[iTunesResponse.Result], Error>?
|
||||
|
||||
search(term: term, limit: limit) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw iTunesClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class iTunesClient: iTunesClientInterface {
|
||||
private let httpClient: HTTPClient
|
||||
|
||||
init(httpClient: HTTPClient) {
|
||||
self.httpClient = httpClient
|
||||
}
|
||||
|
||||
func lookup(bundleIdentifier: String, completion: @escaping (Result<iTunesResponse.Result, Swift.Error>) -> Void) {
|
||||
let request = iTunesRequest.lookup(bundleIdentifier: bundleIdentifier)
|
||||
|
||||
httpClient.send(request) { result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(iTunesResponse.self, as: .json)
|
||||
guard let result = decoded.results.first else { return completion(.failure(Error.appNotFound)) }
|
||||
completion(.success(result))
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func search(term: String, limit: Int, completion: @escaping (Result<[iTunesResponse.Result], Swift.Error>) -> Void) {
|
||||
let request = iTunesRequest.search(term: term, limit: limit)
|
||||
|
||||
httpClient.send(request) { result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(iTunesResponse.self, as: .json)
|
||||
completion(.success(decoded.results))
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension iTunesClient {
|
||||
enum Error: Swift.Error {
|
||||
case timeout
|
||||
case appNotFound
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//
|
||||
// iTunesEndpoint.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum iTunesEndpoint {
|
||||
case search
|
||||
case lookup
|
||||
}
|
||||
|
||||
extension iTunesEndpoint: HTTPEndpoint {
|
||||
var url: URL {
|
||||
var components = URLComponents(string: path)!
|
||||
components.scheme = "https"
|
||||
components.host = "itunes.apple.com"
|
||||
return components.url!
|
||||
}
|
||||
|
||||
private var path: String {
|
||||
switch self {
|
||||
case .search:
|
||||
return "/search"
|
||||
case .lookup:
|
||||
return "/lookup"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//
|
||||
// iTunesRequest.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum iTunesRequest {
|
||||
case search(term: String, limit: Int)
|
||||
case lookup(bundleIdentifier: String)
|
||||
}
|
||||
|
||||
extension iTunesRequest: HTTPRequest {
|
||||
var method: HTTPMethod {
|
||||
return .get
|
||||
}
|
||||
|
||||
var endpoint: HTTPEndpoint {
|
||||
switch self {
|
||||
case .lookup:
|
||||
return iTunesEndpoint.lookup
|
||||
case .search:
|
||||
return iTunesEndpoint.search
|
||||
}
|
||||
}
|
||||
|
||||
var payload: HTTPPayload? {
|
||||
switch self {
|
||||
case let .lookup(bundleIdentifier):
|
||||
return .urlEncoding(["media": "software", "bundleId": bundleIdentifier, "limit": "1"])
|
||||
case let .search(term, limit):
|
||||
return .urlEncoding(["media": "software", "term": term, "limit": "\(limit)"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//
|
||||
// iTunesResponse.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct iTunesResponse {
|
||||
let results: [Result]
|
||||
let count: Int
|
||||
}
|
||||
|
||||
extension iTunesResponse {
|
||||
struct Result {
|
||||
let bundleIdentifier: String
|
||||
let version: String
|
||||
let identifier: Int
|
||||
let name: String
|
||||
}
|
||||
}
|
||||
|
||||
extension iTunesResponse: Codable {
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case count = "resultCount"
|
||||
case results
|
||||
}
|
||||
}
|
||||
|
||||
extension iTunesResponse.Result: Codable {
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case identifier = "trackId"
|
||||
case name = "trackName"
|
||||
case bundleIdentifier = "bundleId"
|
||||
case version
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//
|
||||
// main.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
IPATool.main()
|
||||
-159
@@ -1,159 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func authCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "auth",
|
||||
Short: "Authenticate with the App Store",
|
||||
}
|
||||
|
||||
cmd.AddCommand(loginCmd())
|
||||
cmd.AddCommand(infoCmd())
|
||||
cmd.AddCommand(revokeCmd())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func loginCmd() *cobra.Command {
|
||||
var email, password, authCode string
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "login",
|
||||
Short: "Login to the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
interactive := cmd.Context().Value(interactiveKey).(bool)
|
||||
|
||||
if email == "" && !interactive {
|
||||
return errors.New("an Apple ID is required when not running in interactive mode; use the \"--email\" flag")
|
||||
}
|
||||
|
||||
if email == "" && interactive {
|
||||
value, err := readPrompt("enter Apple ID (email address or phone number): ", false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read Apple ID: %w", err)
|
||||
}
|
||||
email = value
|
||||
}
|
||||
|
||||
if password == "" && !interactive {
|
||||
return errors.New("password is required when not running in interactive mode; use the \"--password\" flag")
|
||||
}
|
||||
|
||||
if password == "" && interactive {
|
||||
value, err := readPrompt("enter password: ", true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read password: %w", err)
|
||||
}
|
||||
password = value
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().Msg("preparing authentication; the first login may take a few minutes")
|
||||
|
||||
var lastErr error
|
||||
|
||||
// nolint:wrapcheck
|
||||
return retry.Do(func() error {
|
||||
if errors.Is(lastErr, appstore.ErrAuthCodeRequired) && interactive {
|
||||
var err error
|
||||
authCode, err = readPrompt("enter 2FA code: ", false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read auth code: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies.Logger.Verbose().
|
||||
Str("email", email).
|
||||
Bool("authCodeProvided", authCode != "").
|
||||
Msg("logging in")
|
||||
|
||||
output, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: email,
|
||||
Password: password,
|
||||
AuthCode: authCode,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, appstore.ErrAuthCodeRequired) && !interactive {
|
||||
dependencies.Logger.Log().Msg("2FA code is required; run the command again and supply a code using the `--auth-code` flag")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("name", output.Account.Name).
|
||||
Str("email", output.Account.Email).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrAuthCodeRequired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&email, "email", "e", "", "Apple ID email address or phone number (required)")
|
||||
cmd.Flags().StringVarP(&password, "password", "p", "", "password for the Apple ID (required)")
|
||||
cmd.Flags().StringVar(&authCode, "auth-code", "", "2FA code for the Apple ID")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
// nolint:wrapcheck
|
||||
func infoCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "info",
|
||||
Short: "Show current account info",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
output, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("name", output.Account.Name).
|
||||
Str("email", output.Account.Email).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// nolint:wrapcheck
|
||||
func revokeCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "revoke",
|
||||
Short: "Revoke your App Store credentials",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
err := dependencies.AppStore.Revoke()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().Bool("success", true).Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Login command", func() {
|
||||
var store *fakeLoginAppStore
|
||||
|
||||
BeforeEach(func() {
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
store = &fakeLoginAppStore{}
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
})
|
||||
|
||||
DescribeTable("requires credentials in non-interactive mode", func(args []string, message string) {
|
||||
cmd := loginCmd()
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
cmd.SetArgs(args)
|
||||
|
||||
Expect(cmd.Execute()).To(MatchError(message))
|
||||
Expect(store.loginCalls).To(BeZero())
|
||||
},
|
||||
Entry("missing Apple ID", []string{"--password", "secret"}, "an Apple ID is required when not running in interactive mode; use the \"--email\" flag"),
|
||||
Entry("missing password", []string{"--email", "user@example.com"}, "password is required when not running in interactive mode; use the \"--password\" flag"),
|
||||
)
|
||||
|
||||
DescribeTable("uses supplied credentials", func(interactive bool, appleID string) {
|
||||
cmd := loginCmd()
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, interactive))
|
||||
cmd.SetArgs([]string{"--email", appleID, "--password", "secret"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.loginCalls).To(Equal(1))
|
||||
Expect(store.input).To(Equal(appstore.LoginInput{Email: appleID, Password: "secret"}))
|
||||
},
|
||||
Entry("interactive email", true, "user@example.com"),
|
||||
Entry("non-interactive email", false, "user@example.com"),
|
||||
Entry("interactive Chinese phone number", true, "+8613912345678"),
|
||||
Entry("non-interactive Chinese phone number", false, "+8613912345678"),
|
||||
Entry("interactive Indian phone number", true, "9123456789"),
|
||||
Entry("non-interactive Indian phone number", false, "9123456789"),
|
||||
)
|
||||
|
||||
DescribeTable("prompts for an Apple ID", func(input, appleID, message string) {
|
||||
dir := GinkgoT().TempDir()
|
||||
inputPath := filepath.Join(dir, "stdin")
|
||||
Expect(os.WriteFile(inputPath, []byte(input), 0o600)).To(Succeed())
|
||||
stdin, err := os.Open(inputPath)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(stdin.Close)
|
||||
stderr, err := os.Create(filepath.Join(dir, "stderr"))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(stderr.Close)
|
||||
|
||||
previousStdin, previousStderr := os.Stdin, os.Stderr
|
||||
os.Stdin, os.Stderr = stdin, stderr
|
||||
DeferCleanup(func() { os.Stdin, os.Stderr = previousStdin, previousStderr })
|
||||
|
||||
cmd := loginCmd()
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, true))
|
||||
cmd.SetArgs([]string{"--password", "secret"})
|
||||
cmd.SilenceErrors = true
|
||||
cmd.SilenceUsage = true
|
||||
|
||||
err = cmd.Execute()
|
||||
if message == "" {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(store.loginCalls).To(Equal(1))
|
||||
Expect(store.input).To(Equal(appstore.LoginInput{Email: appleID, Password: "secret"}))
|
||||
} else {
|
||||
Expect(err).To(MatchError(message))
|
||||
Expect(store.loginCalls).To(BeZero())
|
||||
}
|
||||
|
||||
prompt, err := os.ReadFile(stderr.Name())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(prompt)).To(Equal("enter Apple ID (email address or phone number): "))
|
||||
},
|
||||
Entry("reads email without requiring a terminal", "user@example.com\n", "user@example.com", ""),
|
||||
Entry("reads a phone number without requiring a terminal", "+91 91234-56789\n", "+91 91234-56789", ""),
|
||||
Entry("reports input errors", "", "", "failed to read Apple ID: failed to read input: EOF"),
|
||||
)
|
||||
})
|
||||
|
||||
type fakeLoginAppStore struct {
|
||||
appstore.AppStore
|
||||
input appstore.LoginInput
|
||||
loginCalls int
|
||||
}
|
||||
|
||||
func (f *fakeLoginAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
f.input = input
|
||||
f.loginCalls++
|
||||
|
||||
return appstore.LoginOutput{}, nil
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestCmd(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Command Suite")
|
||||
}
|
||||
-119
@@ -1,119 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
cookiejar "github.com/juju/persistent-cookiejar"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
"github.com/majd/ipatool/v2/pkg/util"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var dependencies = Dependencies{}
|
||||
var keychainPassphrase string
|
||||
|
||||
type Dependencies struct {
|
||||
Logger log.Logger
|
||||
OS operatingsystem.OperatingSystem
|
||||
Machine machine.Machine
|
||||
CookieJar http.CookieJar
|
||||
Keychain keychain.Keychain
|
||||
AppStore appstore.AppStore
|
||||
}
|
||||
|
||||
// newLogger returns a new logger instance.
|
||||
func newLogger(format OutputFormat, verbose bool) log.Logger {
|
||||
var writer io.Writer
|
||||
|
||||
switch format {
|
||||
case OutputFormatJSON:
|
||||
writer = zerolog.SyncWriter(os.Stdout)
|
||||
case OutputFormatText:
|
||||
writer = log.NewWriter()
|
||||
}
|
||||
|
||||
return log.NewLogger(log.Args{
|
||||
Verbose: verbose,
|
||||
Writer: writer,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// newCookieJar returns a new cookie jar instance.
|
||||
func newCookieJar(stateDirectory string) http.CookieJar {
|
||||
return util.Must(cookiejar.New(&cookiejar.Options{
|
||||
Filename: filepath.Join(stateDirectory, CookieJarFileName),
|
||||
}))
|
||||
}
|
||||
|
||||
// newKeychain returns a new keychain instance.
|
||||
func newKeychain(stateDirectory string, interactive bool) keychain.Keychain {
|
||||
ring := util.Must(openKeyring(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{
|
||||
keyring.KeychainBackend,
|
||||
keyring.SecretServiceBackend,
|
||||
keyring.FileBackend,
|
||||
},
|
||||
ServiceName: KeychainServiceName,
|
||||
KeychainTrustApplication: true,
|
||||
FileDir: stateDirectory,
|
||||
FilePasswordFunc: func(s string) (string, error) {
|
||||
if keychainPassphrase == "" && !interactive {
|
||||
return "", errors.New("keychain passphrase is required when not running in interactive mode; use the \"--keychain-passphrase\" flag")
|
||||
}
|
||||
|
||||
if keychainPassphrase != "" {
|
||||
return keychainPassphrase, nil
|
||||
}
|
||||
|
||||
path := strings.Split(s, " unlock ")[1]
|
||||
password, err := readPrompt(fmt.Sprintf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path), true)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read password: %w", err)
|
||||
}
|
||||
|
||||
return password, nil
|
||||
},
|
||||
}))
|
||||
|
||||
return keychain.New(keychain.Args{
|
||||
Keyring: ring,
|
||||
Label: KeychainServiceName,
|
||||
})
|
||||
}
|
||||
|
||||
// initWithCommand initializes the dependencies of the command.
|
||||
func initWithCommand(cmd *cobra.Command) {
|
||||
verbose := cmd.Flag("verbose").Value.String() == "true"
|
||||
interactive, _ := cmd.Context().Value(interactiveKey).(bool)
|
||||
format := util.Must(OutputFormatFromString(cmd.Flag("format").Value.String()))
|
||||
|
||||
dependencies.Logger = newLogger(format, verbose)
|
||||
if cmd.Name() == "mcp" {
|
||||
dependencies.Logger = log.NewLogger(log.Args{Verbose: verbose, Writer: zerolog.SyncWriter(os.Stderr)})
|
||||
}
|
||||
|
||||
dependencies.OS = operatingsystem.New()
|
||||
dependencies.Machine = machine.New(machine.Args{OS: dependencies.OS})
|
||||
stateDirectory := util.Must(prepareStateDirectory(dependencies.OS, dependencies.Machine.HomeDirectory()))
|
||||
dependencies.CookieJar = newCookieJar(stateDirectory)
|
||||
dependencies.Keychain = newKeychain(stateDirectory, interactive)
|
||||
dependencies.AppStore = appstore.NewAppStore(appstore.Args{
|
||||
CookieJar: dependencies.CookieJar,
|
||||
OperatingSystem: dependencies.OS,
|
||||
Keychain: dependencies.Keychain,
|
||||
Machine: dependencies.Machine,
|
||||
})
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package cmd
|
||||
|
||||
const (
|
||||
ConfigDirectoryName = ".ipatool"
|
||||
CookieJarFileName = "cookies"
|
||||
KeychainServiceName = "ipatool-auth.service"
|
||||
)
|
||||
-191
@@ -1,191 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func downloadCmd() *cobra.Command {
|
||||
return downloadCmdWithAppStore(func() appstore.AppStore { return dependencies.AppStore })
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func downloadCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
|
||||
var (
|
||||
acquireLicense bool
|
||||
outputPath string
|
||||
appID int64
|
||||
bundleID string
|
||||
externalVersionID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "download",
|
||||
Short: "Download iOS, iPadOS, tvOS, watchOS, visionOS, and macOS app packages from the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
store := appStore()
|
||||
infoResult, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc := infoResult.Account
|
||||
var lastErr error
|
||||
purchaseRequired := false
|
||||
purchased := false
|
||||
|
||||
return retry.Do(func() error {
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := store.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID, BundleID: bundleID}
|
||||
|
||||
if bundleID != "" {
|
||||
lookupResult, err := store.Lookup(appstore.LookupInput{
|
||||
Account: acc,
|
||||
BundleID: bundleID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil && (appID == 0 || !errors.Is(err, appstore.ErrAppNotFound)) {
|
||||
return err
|
||||
}
|
||||
|
||||
// Delisted apps may still be downloadable by their numeric ID.
|
||||
if err == nil {
|
||||
app = lookupResult.App
|
||||
}
|
||||
}
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrLicenseRequired) {
|
||||
purchaseRequired = true
|
||||
}
|
||||
|
||||
if purchaseRequired {
|
||||
err := store.Purchase(appstore.PurchaseInput{
|
||||
Account: acc,
|
||||
App: app,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return err
|
||||
}
|
||||
purchaseRequired = false
|
||||
purchased = true
|
||||
dependencies.Logger.Verbose().
|
||||
Bool("success", true).
|
||||
Msg("purchase")
|
||||
}
|
||||
|
||||
interactive, _ := cmd.Context().Value(interactiveKey).(bool)
|
||||
var progress *progressbar.ProgressBar
|
||||
if interactive {
|
||||
progress = progressbar.NewOptions64(1,
|
||||
progressbar.OptionSetDescription("downloading"),
|
||||
progressbar.OptionSetWriter(os.Stdout),
|
||||
progressbar.OptionShowBytes(true),
|
||||
progressbar.OptionSetWidth(20),
|
||||
progressbar.OptionFullWidth(),
|
||||
progressbar.OptionThrottle(65*time.Millisecond),
|
||||
progressbar.OptionShowCount(),
|
||||
progressbar.OptionClearOnFinish(),
|
||||
progressbar.OptionSpinnerType(14),
|
||||
progressbar.OptionSetRenderBlankState(true),
|
||||
progressbar.OptionSetElapsedTime(false),
|
||||
progressbar.OptionSetPredictTime(false),
|
||||
)
|
||||
}
|
||||
|
||||
out, err := store.Download(appstore.DownloadInput{
|
||||
Context: cmd.Context(),
|
||||
Account: acc,
|
||||
App: app,
|
||||
OutputPath: outputPath,
|
||||
Progress: progress,
|
||||
ExternalVersionID: externalVersionID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := replicateDownloadSinf(store, platform, out); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("output", out.DestinationPath).
|
||||
Bool("purchased", purchased).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(3),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
if errors.Is(err, appstore.ErrPasswordTokenExpired) {
|
||||
return true
|
||||
}
|
||||
|
||||
if errors.Is(err, appstore.ErrLicenseRequired) && acquireLicense {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID when found)")
|
||||
cmd.Flags().StringVarP(&outputPath, "output", "o", "", "The destination path of the downloaded app package")
|
||||
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target app (defaults to latest version when not specified)")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
cmd.Flags().BoolVar(&acquireLicense, "purchase", false, "Obtain a license for the app if needed")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
type sinfReplicator interface {
|
||||
ReplicateSinf(input appstore.ReplicateSinfInput) error
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func replicateDownloadSinf(store sinfReplicator, platform appstore.Platform, out appstore.DownloadOutput) error {
|
||||
if platform == appstore.PlatformMacOS && len(out.Sinfs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return store.ReplicateSinf(appstore.ReplicateSinfInput{Sinfs: out.Sinfs, PackagePath: out.DestinationPath})
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Download command", func() {
|
||||
Describe("app resolution", func() {
|
||||
var store *fakeDownloadAppStore
|
||||
|
||||
BeforeEach(func() {
|
||||
store = &fakeDownloadAppStore{account: appstore.Account{StoreFront: "143441"}}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
})
|
||||
|
||||
execute := func(args ...string) error {
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs(args)
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
return cmd.Execute()
|
||||
}
|
||||
|
||||
It("uses the app ID when the bundle is absent from the catalog", func() {
|
||||
store.lookupError = fmt.Errorf("lookup: %w", appstore.ErrAppNotFound)
|
||||
Expect(execute("-i", "42", "-b", "com.example.delisted", "--platform", "appletv")).To(Succeed())
|
||||
Expect(store.lookupInputs).To(Equal([]appstore.LookupInput{{
|
||||
Account: appstore.Account{StoreFront: "143441"},
|
||||
BundleID: "com.example.delisted",
|
||||
Platform: appstore.PlatformAppleTV,
|
||||
}}))
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.delisted"}))
|
||||
Expect(store.downloadInputs[0].Platform).To(Equal(appstore.PlatformAppleTV))
|
||||
})
|
||||
|
||||
It("preserves bundle identifier precedence when lookup succeeds", func() {
|
||||
store.lookupOutput.App = appstore.App{ID: 43, BundleID: "com.example.listed"}
|
||||
Expect(execute("-i", "42", "-b", "com.example.listed")).To(Succeed())
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(store.lookupOutput.App))
|
||||
})
|
||||
|
||||
It("resolves a bundle identifier without an app ID", func() {
|
||||
store.lookupOutput.App = appstore.App{ID: 43, BundleID: "com.example.listed"}
|
||||
Expect(execute("-b", "com.example.listed")).To(Succeed())
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(store.lookupOutput.App))
|
||||
})
|
||||
|
||||
It("does not look up the bundle for an explicit app ID and version", func() {
|
||||
Expect(execute("-i", "42", "--platform", "appletv", "--external-version-id", "123456")).To(Succeed())
|
||||
Expect(store.lookupInputs).To(BeEmpty())
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(appstore.App{ID: 42}))
|
||||
Expect(store.downloadInputs[0].ExternalVersionID).To(Equal("123456"))
|
||||
})
|
||||
|
||||
DescribeTable("preserves lookup errors", func(args []string, lookupError error) {
|
||||
store.lookupError = lookupError
|
||||
Expect(execute(args...)).To(MatchError(lookupError))
|
||||
Expect(store.downloadInputs).To(BeEmpty())
|
||||
},
|
||||
Entry("missing bundle without an app ID", []string{"-b", "com.example.delisted"}, appstore.ErrAppNotFound),
|
||||
Entry("request failure with an app ID", []string{"-i", "42", "-b", "com.example.app"}, errors.New("request failed")),
|
||||
)
|
||||
})
|
||||
|
||||
It("exposes macOS in platform help", func() {
|
||||
cmd := downloadCmd()
|
||||
Expect(cmd.Flag("platform").Usage).To(ContainSubstring("macos"))
|
||||
})
|
||||
|
||||
It("skips sinf replication for macOS packages", func() {
|
||||
replicator := &fakeSinfReplicator{}
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformMacOS, appstore.DownloadOutput{
|
||||
DestinationPath: "app.pkg",
|
||||
})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(replicator.called).To(BeFalse())
|
||||
})
|
||||
|
||||
It("replicates sinf for mobile packages downloaded for macOS", func() {
|
||||
replicator := &fakeSinfReplicator{}
|
||||
out := appstore.DownloadOutput{
|
||||
DestinationPath: "app.ipa",
|
||||
Sinfs: []appstore.Sinf{{Data: []byte("sinf")}},
|
||||
}
|
||||
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformMacOS, out)
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(replicator.called).To(BeTrue())
|
||||
Expect(replicator.input).To(Equal(appstore.ReplicateSinfInput{
|
||||
PackagePath: out.DestinationPath,
|
||||
Sinfs: out.Sinfs,
|
||||
}))
|
||||
})
|
||||
|
||||
It("replicates sinf for non-macOS packages", func() {
|
||||
replicator := &fakeSinfReplicator{}
|
||||
out := appstore.DownloadOutput{
|
||||
DestinationPath: "app.ipa",
|
||||
Sinfs: []appstore.Sinf{{Data: []byte("sinf")}},
|
||||
}
|
||||
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformIPhone, out)
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(replicator.called).To(BeTrue())
|
||||
Expect(replicator.input).To(Equal(appstore.ReplicateSinfInput{
|
||||
PackagePath: out.DestinationPath,
|
||||
Sinfs: out.Sinfs,
|
||||
}))
|
||||
})
|
||||
|
||||
It("returns sinf replication errors for non-macOS packages", func() {
|
||||
replicator := &fakeSinfReplicator{err: errors.New("replication failed")}
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformIPhone, appstore.DownloadOutput{})
|
||||
Expect(err).To(MatchError("replication failed"))
|
||||
})
|
||||
|
||||
DescribeTable("preserves the platform when automatic purchase retries the download", func(platform appstore.Platform) {
|
||||
store := &fakeDownloadAppStore{downloadErrors: []error{appstore.ErrLicenseRequired, nil}}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--app-id", "42", "--platform", string(platform), "--purchase"})
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.purchaseInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs[0].Platform).To(Equal(platform))
|
||||
Expect(store.purchaseInputs[0].App).To(Equal(appstore.App{ID: 42}))
|
||||
Expect(store.downloadInputs).To(HaveLen(2))
|
||||
Expect(store.downloadInputs[0].Platform).To(Equal(platform))
|
||||
Expect(store.downloadInputs[1].Platform).To(Equal(platform))
|
||||
},
|
||||
Entry("macOS", appstore.PlatformMacOS),
|
||||
Entry("watchOS", appstore.PlatformWatchOS),
|
||||
)
|
||||
|
||||
It("retains the pending automatic purchase after refreshing authentication", func() {
|
||||
store := &fakeDownloadAppStore{
|
||||
downloadErrors: []error{appstore.ErrLicenseRequired, nil},
|
||||
purchaseErrors: []error{appstore.ErrPasswordTokenExpired, nil},
|
||||
}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--app-id", "42", "--platform", "macos", "--purchase"})
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.loginInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs).To(HaveLen(2))
|
||||
Expect(store.purchaseInputs[0].Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.purchaseInputs[1].Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.downloadInputs).To(HaveLen(2))
|
||||
})
|
||||
|
||||
DescribeTable("reuses the account throughout download retries", func(downloadErrors []error, purchaseCount int) {
|
||||
account := appstore.Account{
|
||||
Email: "user@example.com",
|
||||
Password: "password",
|
||||
PasswordToken: "expired-token",
|
||||
StoreFront: "143441",
|
||||
}
|
||||
refreshedAccount := account
|
||||
refreshedAccount.PasswordToken = "refreshed-token"
|
||||
store := &fakeDownloadAppStore{
|
||||
account: account,
|
||||
loginAccount: refreshedAccount,
|
||||
downloadErrors: downloadErrors,
|
||||
}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--bundle-identifier", "com.example.app", "--purchase"})
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.loginInputs).To(Equal([]appstore.LoginInput{{Email: account.Email, Password: account.Password}}))
|
||||
Expect(store.lookupInputs).To(HaveLen(len(downloadErrors)))
|
||||
Expect(store.lookupInputs[0].Account).To(Equal(account))
|
||||
Expect(store.downloadInputs).To(HaveLen(len(downloadErrors)))
|
||||
Expect(store.downloadInputs[0].Account).To(Equal(account))
|
||||
|
||||
for _, input := range store.lookupInputs[1:] {
|
||||
Expect(input.Account).To(Equal(refreshedAccount))
|
||||
}
|
||||
|
||||
for _, input := range store.downloadInputs[1:] {
|
||||
Expect(input.Account).To(Equal(refreshedAccount))
|
||||
}
|
||||
|
||||
Expect(store.purchaseInputs).To(HaveLen(purchaseCount))
|
||||
|
||||
for _, input := range store.purchaseInputs {
|
||||
Expect(input.Account).To(Equal(refreshedAccount))
|
||||
}
|
||||
},
|
||||
Entry("refreshes an expired token", []error{appstore.ErrPasswordTokenExpired, nil}, 0),
|
||||
Entry("retains the refreshed token for a subsequent purchase", []error{appstore.ErrPasswordTokenExpired, appstore.ErrLicenseRequired, nil}, 1),
|
||||
)
|
||||
|
||||
It("returns an account read error before attempting a download", func() {
|
||||
store := &fakeDownloadAppStore{accountInfoError: errors.New("account unavailable")}
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--app-id", "42"})
|
||||
|
||||
Expect(cmd.Execute()).To(MatchError(store.accountInfoError))
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.loginInputs).To(BeEmpty())
|
||||
Expect(store.lookupInputs).To(BeEmpty())
|
||||
Expect(store.purchaseInputs).To(BeEmpty())
|
||||
Expect(store.downloadInputs).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
||||
type fakeSinfReplicator struct {
|
||||
called bool
|
||||
input appstore.ReplicateSinfInput
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeSinfReplicator) ReplicateSinf(input appstore.ReplicateSinfInput) error {
|
||||
f.called = true
|
||||
f.input = input
|
||||
|
||||
return f.err
|
||||
}
|
||||
|
||||
type fakeDownloadAppStore struct {
|
||||
account appstore.Account
|
||||
accountInfoCalls int
|
||||
accountInfoError error
|
||||
downloadErrors []error
|
||||
downloadInputs []appstore.DownloadInput
|
||||
loginAccount appstore.Account
|
||||
loginInputs []appstore.LoginInput
|
||||
lookupInputs []appstore.LookupInput
|
||||
lookupOutput appstore.LookupOutput
|
||||
lookupError error
|
||||
purchaseErrors []error
|
||||
purchaseInputs []appstore.PurchaseInput
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
f.loginInputs = append(f.loginInputs, input)
|
||||
|
||||
return appstore.LoginOutput{Account: f.loginAccount}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
f.accountInfoCalls++
|
||||
|
||||
return appstore.AccountInfoOutput{Account: f.account}, f.accountInfoError
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) Revoke() error { return nil }
|
||||
|
||||
func (f *fakeDownloadAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
f.lookupInputs = append(f.lookupInputs, input)
|
||||
|
||||
return f.lookupOutput, f.lookupError
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Purchase(input appstore.PurchaseInput) error {
|
||||
f.purchaseInputs = append(f.purchaseInputs, input)
|
||||
index := len(f.purchaseInputs) - 1
|
||||
|
||||
if index < len(f.purchaseErrors) && f.purchaseErrors[index] != nil {
|
||||
return f.purchaseErrors[index]
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
f.downloadInputs = append(f.downloadInputs, input)
|
||||
index := len(f.downloadInputs) - 1
|
||||
|
||||
if index < len(f.downloadErrors) && f.downloadErrors[index] != nil {
|
||||
return appstore.DownloadOutput{}, f.downloadErrors[index]
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "app.pkg"}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error { return nil }
|
||||
|
||||
func (*fakeDownloadAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) Bag(input appstore.BagInput) (appstore.BagOutput, error) {
|
||||
return appstore.BagOutput{}, nil
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func getVersionMetadataCmd() *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
externalVersionID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get-version-metadata",
|
||||
Short: "Retrieves the metadata for a specific version of an app",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID, Platform: platform})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.GetVersionMetadata(appstore.GetVersionMetadataInput{
|
||||
Context: cmd.Context(),
|
||||
Account: acc,
|
||||
App: app,
|
||||
VersionID: externalVersionID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("externalVersionID", externalVersionID).
|
||||
Str("displayVersion", out.DisplayVersion).
|
||||
Time("releaseDate", out.ReleaseDate).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
|
||||
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target app (required)")
|
||||
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to retrieve metadata for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
|
||||
_ = cmd.MarkFlagRequired("external-version-id")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Get Version Metadata command", func() {
|
||||
DescribeTable("passes the platform and exact version to metadata lookup", func(args []string, platform appstore.Platform, lookup bool) {
|
||||
store := &fakeVersionMetadataAppStore{}
|
||||
previous := dependencies
|
||||
DeferCleanup(func() { dependencies = previous })
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
cmd := getVersionMetadataCmd()
|
||||
cmd.SetArgs(append(args, "--external-version-id", "876660716"))
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.input.Platform).To(Equal(platform))
|
||||
Expect(store.input.VersionID).To(Equal("876660716"))
|
||||
Expect(store.input.App.ID).To(Equal(int64(42)))
|
||||
Expect(store.lookupCalled).To(Equal(lookup))
|
||||
if lookup {
|
||||
Expect(store.lookupInput.Platform).To(Equal(platform))
|
||||
}
|
||||
},
|
||||
Entry("Mac bundle", []string{"-b", "com.example.mac", "--platform", "macos"}, appstore.PlatformMacOS, true),
|
||||
Entry("Mac ID alias", []string{"-i", "42", "--platform", "mac"}, appstore.PlatformMacOS, false),
|
||||
Entry("default", []string{"-i", "42"}, appstore.Platform(""), false),
|
||||
)
|
||||
It("rejects unknown as a filter", func() {
|
||||
cmd := getVersionMetadataCmd()
|
||||
cmd.SetArgs([]string{"-i", "42", "--external-version-id", "123", "--platform", "unknown"})
|
||||
Expect(cmd.Execute()).To(MatchError(`invalid platform "unknown"`))
|
||||
})
|
||||
})
|
||||
|
||||
type fakeVersionMetadataAppStore struct {
|
||||
fakeListVersionsAppStore
|
||||
input appstore.GetVersionMetadataInput
|
||||
}
|
||||
|
||||
func (s *fakeVersionMetadataAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
s.input = input
|
||||
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
//go:build !ios
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
)
|
||||
|
||||
func openKeyring(config keyring.Config) (keychain.Keyring, error) {
|
||||
return keyring.Open(config) //nolint:wrapcheck
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
gokeychain "github.com/byteness/go-keychain"
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
)
|
||||
|
||||
// iosKeyring fixes the update query in keyring v1.9.0, which includes attributes
|
||||
// that SecItemUpdate rejects on iOS (kSecMatchLimit and kSecReturnAttributes).
|
||||
type iosKeyring struct {
|
||||
keyring.Keyring
|
||||
service string
|
||||
}
|
||||
|
||||
func openKeyring(config keyring.Config) (keychain.Keyring, error) {
|
||||
ring, err := keyring.Open(config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open iOS keyring: %w", err)
|
||||
}
|
||||
|
||||
return &iosKeyring{Keyring: ring, service: config.ServiceName}, nil
|
||||
}
|
||||
|
||||
func (k *iosKeyring) Set(item keyring.Item) error {
|
||||
query := gokeychain.NewItem()
|
||||
query.SetSecClass(gokeychain.SecClassGenericPassword)
|
||||
query.SetService(k.service)
|
||||
query.SetAccount(item.Key)
|
||||
|
||||
attributes := gokeychain.NewItem()
|
||||
attributes.SetData(item.Data)
|
||||
attributes.SetLabel(item.Label)
|
||||
attributes.SetDescription(item.Description)
|
||||
|
||||
err := gokeychain.UpdateItem(query, attributes)
|
||||
if err == gokeychain.ErrorItemNotFound {
|
||||
return k.Keyring.Set(item) //nolint:wrapcheck
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("update iOS keyring item: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("iOS keyring", func() {
|
||||
It("persists and updates credentials without invalid SecItemUpdate parameters", func() {
|
||||
ring, err := openKeyring(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{keyring.KeychainBackend},
|
||||
ServiceName: fmt.Sprintf("ipatool-test-%d", time.Now().UnixNano()),
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(func() { Expect(ring.Remove("account")).To(Succeed()) })
|
||||
Expect(ring.Set(keyring.Item{Key: "account", Data: []byte("first"), Label: "ipatool"})).To(Succeed())
|
||||
Expect(ring.Set(keyring.Item{Key: "account", Data: []byte("updated"), Label: "ipatool"})).To(Succeed())
|
||||
item, err := ring.Get("account")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(item.Data).To(Equal([]byte("updated")))
|
||||
Expect(item.Label).To(Equal("ipatool"))
|
||||
})
|
||||
})
|
||||
@@ -1,98 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func ListVersionsCmd() *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "list-versions",
|
||||
Short: "List the available versions of an App Store app",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID, Platform: platform})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Context: cmd.Context(), Account: acc, App: app, Platform: platform})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Interface("externalVersionIdentifiers", out.ExternalVersionIdentifiers).
|
||||
Str("bundleID", app.BundleID).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
|
||||
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to list versions for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("List Versions command", func() {
|
||||
DescribeTable("passes the selected platform to lookup and version listing", func(args []string, expected appstore.Platform, lookup bool) {
|
||||
store := &fakeListVersionsAppStore{}
|
||||
previous := dependencies
|
||||
DeferCleanup(func() { dependencies = previous })
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
cmd := ListVersionsCmd()
|
||||
cmd.SetArgs(args)
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.input.Platform).To(Equal(expected))
|
||||
Expect(store.input.App.ID).To(Equal(int64(42)))
|
||||
Expect(store.lookupCalled).To(Equal(lookup))
|
||||
if lookup {
|
||||
Expect(store.lookupInput.Platform).To(Equal(expected))
|
||||
}
|
||||
},
|
||||
Entry("Mac bundle ID", []string{"-b", "com.example.mac", "--platform", "macos"}, appstore.PlatformMacOS, true),
|
||||
Entry("Mac app ID alias", []string{"-i", "42", "--platform", "mac"}, appstore.PlatformMacOS, false),
|
||||
Entry("default platform", []string{"-i", "42"}, appstore.Platform(""), false),
|
||||
Entry("iOS alias", []string{"-i", "42", "--platform", "ios"}, appstore.PlatformIPhone, false),
|
||||
)
|
||||
|
||||
It("rejects unknown as a platform before accessing the account", func() {
|
||||
cmd := ListVersionsCmd()
|
||||
cmd.SetArgs([]string{"-i", "42", "--platform", "unknown"})
|
||||
Expect(cmd.Execute()).To(MatchError(`invalid platform "unknown"`))
|
||||
})
|
||||
})
|
||||
|
||||
type fakeListVersionsAppStore struct {
|
||||
appstore.AppStore
|
||||
input appstore.ListVersionsInput
|
||||
lookupInput appstore.LookupInput
|
||||
lookupCalled bool
|
||||
}
|
||||
|
||||
func (*fakeListVersionsAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, nil
|
||||
}
|
||||
func (s *fakeListVersionsAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
s.lookupCalled = true
|
||||
s.lookupInput = input
|
||||
|
||||
return appstore.LookupOutput{App: appstore.App{ID: 42, BundleID: input.BundleID}}, nil
|
||||
}
|
||||
func (s *fakeListVersionsAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
s.input = input
|
||||
|
||||
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"123"}}, nil
|
||||
}
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func mcpCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "mcp",
|
||||
Short: "Serve App Store tools over MCP using stdio",
|
||||
Long: "Serve App Store tools over the Model Context Protocol using stdio.\n" +
|
||||
"Authenticate with 'ipatool auth login' before using the tools.\n" +
|
||||
"Runs non-interactively; authentication tools are not exposed.",
|
||||
Args: cobra.NoArgs,
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
cmd.SetContext(context.WithValue(cmd.Context(), interactiveKey, false))
|
||||
initWithCommand(cmd)
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt)
|
||||
defer stop()
|
||||
|
||||
server := newMCPServer(dependencies.AppStore)
|
||||
if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil {
|
||||
return fmt.Errorf("MCP server failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type mcpTools struct {
|
||||
store appstore.AppStore
|
||||
gate chan struct{}
|
||||
}
|
||||
|
||||
func newMCPServer(store appstore.AppStore) *mcp.Server {
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "ipatool", Version: version}, &mcp.ServerOptions{
|
||||
Instructions: "Use the existing ipatool account. If authentication is required, ask the user to run ipatool auth login outside MCP. Purchases support free apps only.",
|
||||
})
|
||||
tools := &mcpTools{store: store, gate: make(chan struct{}, 1)}
|
||||
addMCPTool(server, tools, "search_apps", "Search for apps on the App Store.", true, tools.search)
|
||||
addMCPTool(server, tools, "download_app", "Download an app package to the local filesystem. Optionally acquire a free license if purchase is true.", false, tools.download)
|
||||
addMCPTool(server, tools, "list_app_versions", "List available external version identifiers for an app.", true, tools.listVersions)
|
||||
addMCPTool(server, tools, "get_version_metadata", "Retrieve the display version and release date for a specific external version identifier of an app.", true, tools.getVersionMetadata)
|
||||
addMCPTool(server, tools, "list_purchases", "List apps owned by the authenticated account, with pagination.", true, tools.listPurchases)
|
||||
addMCPTool(server, tools, "purchase_app", "Obtain a license for a free app. Paid apps are not supported.", false, tools.purchase)
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
func addMCPTool[In, Out any](server *mcp.Server, tools *mcpTools, name, description string, readOnly bool, handler func(context.Context, In) (Out, error)) {
|
||||
mcp.AddTool(server, &mcp.Tool{
|
||||
Name: name,
|
||||
Description: description,
|
||||
Annotations: &mcp.ToolAnnotations{ReadOnlyHint: readOnly},
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, input In) (*mcp.CallToolResult, Out, error) {
|
||||
var zero Out
|
||||
|
||||
// The App Store client shares account state and caches across calls.
|
||||
select {
|
||||
case tools.gate <- struct{}{}:
|
||||
defer func() { <-tools.gate }()
|
||||
case <-ctx.Done():
|
||||
return nil, zero, fmt.Errorf("tool call canceled: %w", ctx.Err())
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, zero, fmt.Errorf("tool call canceled: %w", err)
|
||||
}
|
||||
|
||||
output, err := handler(ctx, input)
|
||||
if err != nil {
|
||||
return nil, zero, fmt.Errorf("%s failed: %w", name, err)
|
||||
}
|
||||
|
||||
return nil, output, nil
|
||||
})
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
)
|
||||
|
||||
// mcpApp keeps every metadata field in the MCP response, including zero values.
|
||||
// The App Store's JSON representation is also used by other callers, so its
|
||||
// omission rules are left unchanged.
|
||||
type mcpApp struct {
|
||||
ID int64 `json:"trackId"`
|
||||
BundleID string `json:"bundleId"`
|
||||
Name string `json:"trackName"`
|
||||
Version string `json:"version"`
|
||||
Price float64 `json:"price"`
|
||||
PurchaseDate *time.Time `json:"purchaseDate"`
|
||||
Platforms []appstore.Platform `json:"platforms"`
|
||||
}
|
||||
|
||||
func newMCPApp(app appstore.App) mcpApp {
|
||||
output := mcpApp{
|
||||
ID: app.ID, BundleID: app.BundleID, Name: app.Name, Version: app.Version, Price: app.Price,
|
||||
Platforms: append([]appstore.Platform{}, app.Platforms...),
|
||||
}
|
||||
if !app.PurchaseDate.IsZero() {
|
||||
output.PurchaseDate = &app.PurchaseDate
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
// completeApp supplements sparse metadata without making catalog availability a
|
||||
// prerequisite for operating on owned or delisted apps.
|
||||
func (t *mcpTools) completeApp(acc appstore.Account, app appstore.App, platform appstore.Platform) appstore.App {
|
||||
knownPlatforms := len(app.Platforms) > 0 && app.Platforms[0] != appstore.PlatformUnknown
|
||||
if app.ID <= 0 || (app.BundleID != "" && app.Name != "" && app.Version != "" && knownPlatforms) {
|
||||
return app
|
||||
}
|
||||
|
||||
// Purchase history can contain several platforms when no filter was supplied.
|
||||
// Use an app's known platform for its catalog lookup in that case.
|
||||
if platform == "" && len(app.Platforms) > 0 && app.Platforms[0] != appstore.PlatformUnknown {
|
||||
platform = app.Platforms[0]
|
||||
}
|
||||
|
||||
out, err := t.store.Lookup(appstore.LookupInput{Account: acc, AppID: app.ID, Platform: platform})
|
||||
if err != nil || out.App.ID != app.ID {
|
||||
return app
|
||||
}
|
||||
|
||||
if app.BundleID == "" {
|
||||
app.BundleID = out.App.BundleID
|
||||
}
|
||||
|
||||
if app.Name == "" {
|
||||
app.Name = out.App.Name
|
||||
}
|
||||
|
||||
if app.Version == "" {
|
||||
app.Version = out.App.Version
|
||||
}
|
||||
|
||||
if len(out.App.Platforms) > 0 && (len(app.Platforms) == 0 || (len(app.Platforms) == 1 && app.Platforms[0] == appstore.PlatformUnknown)) {
|
||||
app.Platforms = out.App.Platforms
|
||||
}
|
||||
|
||||
if app.Price == 0 {
|
||||
app.Price = out.App.Price
|
||||
}
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
func (t *mcpTools) appResults(acc appstore.Account, apps []appstore.App, platform appstore.Platform) []mcpApp {
|
||||
results := make([]mcpApp, 0, len(apps))
|
||||
for _, app := range apps {
|
||||
results = append(results, newMCPApp(t.completeApp(acc, app, platform)))
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
type mcpAppParameters struct {
|
||||
AppID int64 `json:"app_id"`
|
||||
BundleIdentifier string `json:"bundle_identifier"`
|
||||
Platform appstore.Platform `json:"platform"`
|
||||
}
|
||||
|
||||
func appParameters(app appstore.App, platform appstore.Platform) mcpAppParameters {
|
||||
return mcpAppParameters{AppID: app.ID, BundleIdentifier: app.BundleID, Platform: platform}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("MCP app metadata", func() {
|
||||
DescribeTable("preserves source data when catalog metadata cannot be used", func(catalog appstore.App, lookupErr error) {
|
||||
original := appstore.App{ID: 123, Name: "Original name", Price: 2.99, Platforms: []appstore.Platform{appstore.PlatformUnknown}}
|
||||
store := &fakeMCPAppStore{lookup: func(appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return appstore.LookupOutput{App: catalog}, lookupErr
|
||||
}}
|
||||
tools := &mcpTools{store: store}
|
||||
|
||||
Expect(tools.completeApp(appstore.Account{}, original, "")).To(Equal(original))
|
||||
},
|
||||
Entry("delisted app", appstore.App{}, appstore.ErrAppNotFound),
|
||||
Entry("network failure", appstore.App{}, errors.New("network failure")),
|
||||
Entry("wrong app ID", appstore.App{ID: 999, BundleID: "wrong.bundle"}, nil),
|
||||
Entry("missing catalog values", appstore.App{ID: 123}, nil),
|
||||
)
|
||||
|
||||
It("avoids catalog lookups when app metadata is already complete", func() {
|
||||
tools := &mcpTools{store: &fakeMCPAppStore{}}
|
||||
app := appstore.App{ID: 123, BundleID: "com.example.app", Name: "Example", Version: "1.0", Platforms: []appstore.Platform{appstore.PlatformIPhone}}
|
||||
Expect(tools.completeApp(appstore.Account{}, app, "")).To(Equal(app))
|
||||
})
|
||||
})
|
||||
-603
@@ -1,603 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("MCP server", func() {
|
||||
var (
|
||||
ctx context.Context
|
||||
store *fakeMCPAppStore
|
||||
session *mcp.ClientSession
|
||||
account appstore.Account
|
||||
app appstore.App
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
var cancel context.CancelFunc
|
||||
|
||||
ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
|
||||
DeferCleanup(cancel)
|
||||
account = appstore.Account{Email: "private-email", Password: "private-password", PasswordToken: "private-token"}
|
||||
app = appstore.App{ID: 123, BundleID: "com.example.app", Name: "Example"}
|
||||
store = &fakeMCPAppStore{}
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{Account: account}, nil
|
||||
}
|
||||
store.lookup = func(appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return appstore.LookupOutput{}, appstore.ErrAppNotFound
|
||||
}
|
||||
clientTransport, serverTransport := mcp.NewInMemoryTransports()
|
||||
serverSession, err := newMCPServer(store).Connect(ctx, serverTransport, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(func() { Expect(serverSession.Close()).To(Succeed()) })
|
||||
session, err = mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil).Connect(ctx, clientTransport, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(func() { Expect(session.Close()).To(Succeed()) })
|
||||
})
|
||||
|
||||
call := func(name string, args map[string]any) *mcp.CallToolResult {
|
||||
result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
It("registers the mcp subcommand", func() {
|
||||
command, _, err := rootCmd().Find([]string{"mcp"})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(command.Name()).To(Equal("mcp"))
|
||||
Expect(command.Args(command, []string{"unexpected"})).NotTo(Succeed())
|
||||
})
|
||||
|
||||
It("advertises exactly six tools and their schemas without auth functions", func() {
|
||||
result, err := session.ListTools(ctx, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
names := make([]string, 0, len(result.Tools))
|
||||
for _, tool := range result.Tools {
|
||||
names = append(names, tool.Name)
|
||||
Expect(tool.InputSchema).NotTo(BeNil())
|
||||
Expect(tool.OutputSchema).NotTo(BeNil())
|
||||
Expect(tool.Annotations.ReadOnlyHint).To(Equal(tool.Name != "download_app" && tool.Name != "purchase_app"))
|
||||
}
|
||||
Expect(names).To(ConsistOf("search_apps", "download_app", "list_app_versions", "get_version_metadata", "list_purchases", "purchase_app"))
|
||||
})
|
||||
|
||||
It("searches with CLI defaults and returns structured app data without credentials", func() {
|
||||
var input appstore.SearchInput
|
||||
|
||||
store.search = func(in appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.SearchOutput{Count: 1, Results: []appstore.App{app}}, nil
|
||||
}
|
||||
result := call("search_apps", map[string]any{"term": "example"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input).To(Equal(appstore.SearchInput{Account: account, Term: "example", Limit: 5}))
|
||||
data, err := json.Marshal(result.StructuredContent)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).To(ContainSubstring("com.example.app"))
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
Expect(result.Content).To(HaveLen(1))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("term", "example"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("limit", float64(5)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", ""))
|
||||
})
|
||||
|
||||
DescribeTable("passes search platform aliases and limits to the App Store", func(value string, platform appstore.Platform) {
|
||||
var input appstore.SearchInput
|
||||
|
||||
store.search = func(in appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.SearchOutput{}, nil
|
||||
}
|
||||
Expect(call("search_apps", map[string]any{"term": "example", "platform": value, "limit": 7}).IsError).To(BeFalse())
|
||||
Expect(input.Platform).To(Equal(platform))
|
||||
Expect(input.Limit).To(Equal(int64(7)))
|
||||
},
|
||||
Entry("tvOS", "tvos", appstore.PlatformAppleTV),
|
||||
Entry("watchOS", "watch", appstore.PlatformWatchOS),
|
||||
)
|
||||
|
||||
DescribeTable("rejects invalid inputs before accessing the account", func(name string, args map[string]any) {
|
||||
accountCalls := 0
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
accountCalls++
|
||||
|
||||
return appstore.AccountInfoOutput{}, errors.New("unexpected account access")
|
||||
}
|
||||
result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
|
||||
Expect(err != nil || (result != nil && result.IsError)).To(BeTrue())
|
||||
Expect(accountCalls).To(BeZero())
|
||||
},
|
||||
Entry("missing search term", "search_apps", map[string]any{}),
|
||||
Entry("blank search term", "search_apps", map[string]any{"term": " "}),
|
||||
Entry("invalid search limit", "search_apps", map[string]any{"term": "app", "limit": 0}),
|
||||
Entry("wrong argument type", "search_apps", map[string]any{"term": 123}),
|
||||
Entry("credentials are not arguments", "search_apps", map[string]any{"term": "app", "password": "secret"}),
|
||||
Entry("invalid platform", "search_apps", map[string]any{"term": "app", "platform": "unknown"}),
|
||||
Entry("missing download app", "download_app", map[string]any{}),
|
||||
Entry("negative app ID", "purchase_app", map[string]any{"app_id": -1}),
|
||||
Entry("missing versions app", "list_app_versions", map[string]any{}),
|
||||
Entry("missing metadata app", "get_version_metadata", map[string]any{"external_version_id": "200"}),
|
||||
Entry("missing metadata version", "get_version_metadata", map[string]any{"app_id": 123}),
|
||||
Entry("empty metadata version", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": ""}),
|
||||
Entry("blank metadata version", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": " "}),
|
||||
Entry("invalid metadata version type", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": 200}),
|
||||
Entry("invalid metadata platform", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200", "platform": "unknown"}),
|
||||
Entry("invalid page", "list_purchases", map[string]any{"page": 0}),
|
||||
Entry("invalid page size", "list_purchases", map[string]any{"max_results": 101}),
|
||||
)
|
||||
|
||||
It("returns actionable account errors and keeps serving requests", func() {
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, errors.New("account not found")
|
||||
}
|
||||
result := call("list_purchases", map[string]any{})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("ipatool auth login"))
|
||||
_, err := session.ListTools(ctx, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
})
|
||||
|
||||
DescribeTable("lists purchases with pagination", func(args map[string]any, page, limit int, platform appstore.Platform) {
|
||||
var input appstore.OwnedAppsInput
|
||||
|
||||
store.ownedApps = func(in appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 11, Page: in.Page, Results: []appstore.App{app}}, nil
|
||||
}
|
||||
result := call("list_purchases", args)
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input).To(Equal(appstore.OwnedAppsInput{Account: account, Page: page, Limit: limit, Platform: platform}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("totalCount", float64(11)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("page", float64(page)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("max_results", float64(limit)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", string(platform)))
|
||||
},
|
||||
Entry("defaults", map[string]any{}, 1, 10, appstore.Platform("")),
|
||||
Entry("explicit values", map[string]any{"page": 2, "max_results": 5, "platform": "macos"}, 2, 5, appstore.PlatformMacOS),
|
||||
)
|
||||
|
||||
It("resolves bundle identifiers and lists versions", func() {
|
||||
var lookup appstore.LookupInput
|
||||
var input appstore.ListVersionsInput
|
||||
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: app}, nil
|
||||
}
|
||||
store.listVersions = func(in appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"100", "200"}, LatestExternalVersionID: "200"}, nil
|
||||
}
|
||||
result := call("list_app_versions", map[string]any{"app_id": 999, "bundle_identifier": app.BundleID, "platform": "ipados"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, BundleID: app.BundleID, Platform: appstore.PlatformIPad}))
|
||||
Expect(input.App).To(Equal(app))
|
||||
Expect(input.Context).NotTo(BeNil())
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("externalVersionIdentifiers", []any{"100", "200"}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(app.ID)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", "ipad"))
|
||||
})
|
||||
|
||||
It("resolves a bundle identifier and returns metadata for the requested version", func() {
|
||||
var lookup appstore.LookupInput
|
||||
var input appstore.GetVersionMetadataInput
|
||||
|
||||
app.Version = "2.0"
|
||||
releasedAt := time.Date(2025, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: app}, nil
|
||||
}
|
||||
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3", ReleaseDate: releasedAt}, nil
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 999, "bundle_identifier": app.BundleID, "external_version_id": "200", "platform": "ipados"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, BundleID: app.BundleID, Platform: appstore.PlatformIPad}))
|
||||
Expect(input.Context).NotTo(BeNil())
|
||||
Expect(input.Account).To(Equal(account))
|
||||
Expect(input.App).To(Equal(app))
|
||||
Expect(input.VersionID).To(Equal("200"))
|
||||
Expect(input.Platform).To(Equal(appstore.PlatformIPad))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(app.ID)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", "ipad"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("external_version_id", "200"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("displayVersion", "1.2.3"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("releaseDate", releasedAt.Format(time.RFC3339)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("success", true))
|
||||
Expect(result.StructuredContent.(map[string]any)["app"]).To(HaveKeyWithValue("version", "2.0"))
|
||||
data, err := json.Marshal(result.StructuredContent)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(MatchJSON(string(data)))
|
||||
})
|
||||
|
||||
DescribeTable("retrieves version metadata by app ID when catalog metadata is unavailable", func(platform string, expected appstore.Platform) {
|
||||
var input appstore.GetVersionMetadataInput
|
||||
|
||||
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3"}, nil
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200", "platform": platform})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input.App).To(Equal(appstore.App{ID: 123}))
|
||||
Expect(input.VersionID).To(Equal("200"))
|
||||
Expect(input.Platform).To(Equal(expected))
|
||||
},
|
||||
Entry("CLI default", "", appstore.Platform("")),
|
||||
Entry("iOS alias", "ios", appstore.PlatformIPhone),
|
||||
Entry("macOS", "macos", appstore.PlatformMacOS),
|
||||
)
|
||||
|
||||
It("returns bundle lookup failures as metadata tool errors", func() {
|
||||
result := call("get_version_metadata", map[string]any{"bundle_identifier": app.BundleID, "external_version_id": "200"})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(appstore.ErrAppNotFound.Error()))
|
||||
})
|
||||
|
||||
DescribeTable("returns metadata failures as tool errors without acquiring a license", func(metadataErr error) {
|
||||
store.getVersionMetadata = func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, appstore.NewErrorWithMetadata(metadataErr, account)
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(metadataErr.Error()))
|
||||
data, err := json.Marshal(result)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
},
|
||||
Entry("missing license", appstore.ErrLicenseRequired),
|
||||
Entry("metadata unavailable", errors.New("metadata unavailable")),
|
||||
)
|
||||
|
||||
It("refreshes an expired session when retrieving version metadata", func() {
|
||||
var login appstore.LoginInput
|
||||
var accounts []appstore.Account
|
||||
|
||||
refreshed := appstore.Account{PasswordToken: "refreshed-private-token"}
|
||||
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
accounts = append(accounts, in.Account)
|
||||
if len(accounts) == 1 {
|
||||
return appstore.GetVersionMetadataOutput{}, appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3"}, nil
|
||||
}
|
||||
store.login = func(in appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
login = in
|
||||
|
||||
return appstore.LoginOutput{Account: refreshed}, nil
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(login).To(Equal(appstore.LoginInput{Email: account.Email, Password: account.Password}))
|
||||
Expect(accounts).To(Equal([]appstore.Account{account, refreshed}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("displayVersion", "1.2.3"))
|
||||
})
|
||||
|
||||
DescribeTable("purchases a free license", func(purchaseErr error, alreadyOwned bool) {
|
||||
var input appstore.PurchaseInput
|
||||
|
||||
store.purchase = func(in appstore.PurchaseInput) error {
|
||||
input = in
|
||||
|
||||
return purchaseErr
|
||||
}
|
||||
result := call("purchase_app", map[string]any{"app_id": 123, "platform": "visionos"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input).To(Equal(appstore.PurchaseInput{Account: account, App: appstore.App{ID: 123}, Platform: appstore.PlatformVisionOS}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("alreadyOwned", alreadyOwned))
|
||||
},
|
||||
Entry("new license", nil, false),
|
||||
Entry("existing license", appstore.ErrLicenseAlreadyExists, true),
|
||||
)
|
||||
|
||||
It("downloads a selected version and finalizes the package without a progress bar", func() {
|
||||
var input appstore.DownloadInput
|
||||
var sinfInput appstore.ReplicateSinfInput
|
||||
|
||||
store.download = func(in appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(in appstore.ReplicateSinfInput) error {
|
||||
sinfInput = in
|
||||
|
||||
return nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "output": "/tmp/example.ipa", "external_version_id": "200", "platform": "ios"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input.App.ID).To(Equal(int64(123)))
|
||||
Expect(input.OutputPath).To(Equal("/tmp/example.ipa"))
|
||||
Expect(input.ExternalVersionID).To(Equal("200"))
|
||||
Expect(input.Platform).To(Equal(appstore.PlatformIPhone))
|
||||
Expect(input.Context).NotTo(BeNil())
|
||||
Expect(input.Progress).To(BeNil())
|
||||
Expect(sinfInput.PackagePath).To(Equal(input.OutputPath))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("output", input.OutputPath))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("external_version_id", "200"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("purchase", false))
|
||||
})
|
||||
|
||||
It("downloads delisted macOS apps by ID without attempting IPA finalization", func() {
|
||||
var input appstore.DownloadInput
|
||||
|
||||
store.lookup = func(appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return appstore.LookupOutput{}, appstore.ErrAppNotFound
|
||||
}
|
||||
store.download = func(in appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "bundle_identifier": app.BundleID, "platform": "macos"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input.App.ID).To(Equal(int64(123)))
|
||||
})
|
||||
|
||||
DescribeTable("only acquires a license during download when requested", func(purchase bool) {
|
||||
downloads, purchases := 0, 0
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
downloads++
|
||||
if downloads == 1 {
|
||||
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error {
|
||||
purchases++
|
||||
|
||||
return nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": purchase})
|
||||
Expect(result.IsError).To(Equal(!purchase))
|
||||
if purchase {
|
||||
Expect(purchases).To(Equal(1))
|
||||
Expect(downloads).To(Equal(2))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("purchased", true))
|
||||
} else {
|
||||
Expect(purchases).To(BeZero())
|
||||
Expect(downloads).To(Equal(1))
|
||||
}
|
||||
}, Entry("explicit opt in", true), Entry("no opt in", false))
|
||||
|
||||
It("refreshes an expired session using saved credentials", func() {
|
||||
var login appstore.LoginInput
|
||||
var accounts []appstore.Account
|
||||
|
||||
refreshed := appstore.Account{PasswordToken: "refreshed-private-token"}
|
||||
store.purchase = func(in appstore.PurchaseInput) error {
|
||||
accounts = append(accounts, in.Account)
|
||||
if len(accounts) == 1 {
|
||||
return appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
store.login = func(in appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
login = in
|
||||
|
||||
return appstore.LoginOutput{Account: refreshed}, nil
|
||||
}
|
||||
Expect(call("purchase_app", map[string]any{"app_id": 123}).IsError).To(BeFalse())
|
||||
Expect(login).To(Equal(appstore.LoginInput{Email: account.Email, Password: account.Password}))
|
||||
Expect(accounts).To(Equal([]appstore.Account{account, refreshed}))
|
||||
})
|
||||
|
||||
It("reports two-factor requirements as tool errors without requesting credentials", func() {
|
||||
store.purchase = func(appstore.PurchaseInput) error {
|
||||
return appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
store.login = func(appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
return appstore.LoginOutput{}, appstore.ErrAuthCodeRequired
|
||||
}
|
||||
result := call("purchase_app", map[string]any{"app_id": 123})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("ipatool auth login"))
|
||||
})
|
||||
|
||||
It("does not expose App Store error metadata", func() {
|
||||
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{}, appstore.NewErrorWithMetadata(errors.New("request failed"), account)
|
||||
}
|
||||
result := call("search_apps", map[string]any{"term": "example"})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
data, err := json.Marshal(result)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).To(ContainSubstring("request failed"))
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
})
|
||||
|
||||
It("reports package finalization failures as tool errors", func() {
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(appstore.ReplicateSinfInput) error {
|
||||
return errors.New("finalization failed")
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("finalization failed"))
|
||||
})
|
||||
|
||||
DescribeTable("returns every parameter and app field even when metadata is unavailable", func(name string, args map[string]any, expectedKeys []string) {
|
||||
partial := appstore.App{ID: 123}
|
||||
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{Count: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
store.ownedApps = func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 1, Page: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
store.listVersions = func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"200"}}, nil
|
||||
}
|
||||
store.getVersionMetadata = func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error { return nil }
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(appstore.ReplicateSinfInput) error { return nil }
|
||||
result := call(name, args)
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
output := result.StructuredContent.(map[string]any)
|
||||
for _, key := range expectedKeys {
|
||||
Expect(output).To(HaveKey(key))
|
||||
}
|
||||
|
||||
metadata := output["app"]
|
||||
if metadata == nil {
|
||||
metadata = output["apps"].([]any)[0]
|
||||
}
|
||||
Expect(metadata).To(Equal(map[string]any{
|
||||
"trackId": float64(123), "bundleId": "", "trackName": "", "version": "",
|
||||
"price": float64(0), "purchaseDate": nil, "platforms": []any{},
|
||||
}))
|
||||
textJSON, err := json.Marshal(result.StructuredContent)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(MatchJSON(string(textJSON)))
|
||||
},
|
||||
Entry("search", "search_apps", map[string]any{"term": "example"}, []string{"term", "limit", "platform", "count", "apps"}),
|
||||
Entry("purchases", "list_purchases", map[string]any{}, []string{"page", "max_results", "platform", "count", "totalCount", "apps"}),
|
||||
Entry("versions", "list_app_versions", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "bundleID", "app", "externalVersionIdentifiers", "latestExternalVersionID", "success"}),
|
||||
Entry("version metadata", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"}, []string{"app_id", "bundle_identifier", "platform", "app", "external_version_id", "displayVersion", "releaseDate", "success"}),
|
||||
Entry("purchase", "purchase_app", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "app", "alreadyOwned", "success"}),
|
||||
Entry("download", "download_app", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "app", "output", "external_version_id", "purchase", "purchased", "success"}),
|
||||
)
|
||||
|
||||
DescribeTable("fills missing bundle identifiers in app lists without losing purchase metadata", func(name string, args map[string]any) {
|
||||
purchasedAt := time.Date(2025, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
partial := appstore.App{ID: 123, Name: "Original name", PurchaseDate: purchasedAt, Platforms: []appstore.Platform{appstore.PlatformMacOS}}
|
||||
var lookup appstore.LookupInput
|
||||
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: appstore.App{ID: 123, BundleID: app.BundleID, Name: "Catalog name", Version: "2.0", Price: 4.99}}, nil
|
||||
}
|
||||
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{Count: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
store.ownedApps = func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 1, Page: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
result := call(name, args)
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, AppID: 123, Platform: appstore.PlatformMacOS}))
|
||||
metadata := result.StructuredContent.(map[string]any)["apps"].([]any)[0]
|
||||
Expect(metadata).To(Equal(map[string]any{
|
||||
"trackId": float64(123), "bundleId": app.BundleID, "trackName": "Original name", "version": "2.0",
|
||||
"price": 4.99, "purchaseDate": purchasedAt.Format(time.RFC3339), "platforms": []any{"macos"},
|
||||
}))
|
||||
},
|
||||
Entry("search", "search_apps", map[string]any{"term": "example"}),
|
||||
Entry("purchases", "list_purchases", map[string]any{}),
|
||||
)
|
||||
|
||||
DescribeTable("resolves bundle identifiers for numeric app IDs", func(name string) {
|
||||
var lookup appstore.LookupInput
|
||||
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: app}, nil
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error { return nil }
|
||||
store.listVersions = func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{}, nil
|
||||
}
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(appstore.ReplicateSinfInput) error { return nil }
|
||||
result := call(name, map[string]any{"app_id": 123})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup.AppID).To(Equal(int64(123)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(123)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
|
||||
Expect(result.StructuredContent.(map[string]any)["app"]).To(HaveKeyWithValue("bundleId", app.BundleID))
|
||||
if name == "list_app_versions" {
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundleID", app.BundleID))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("externalVersionIdentifiers", []any{}))
|
||||
}
|
||||
}, Entry("purchase", "purchase_app"), Entry("download", "download_app"), Entry("versions", "list_app_versions"))
|
||||
})
|
||||
|
||||
type fakeMCPAppStore struct {
|
||||
appstore.AppStore
|
||||
accountInfo func() (appstore.AccountInfoOutput, error)
|
||||
search func(appstore.SearchInput) (appstore.SearchOutput, error)
|
||||
lookup func(appstore.LookupInput) (appstore.LookupOutput, error)
|
||||
ownedApps func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error)
|
||||
listVersions func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error)
|
||||
getVersionMetadata func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error)
|
||||
purchase func(appstore.PurchaseInput) error
|
||||
download func(appstore.DownloadInput) (appstore.DownloadOutput, error)
|
||||
replicateSinf func(appstore.ReplicateSinfInput) error
|
||||
login func(appstore.LoginInput) (appstore.LoginOutput, error)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return s.accountInfo()
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return s.search(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return s.lookup(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return s.ownedApps(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return s.listVersions(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return s.getVersionMetadata(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Purchase(input appstore.PurchaseInput) error {
|
||||
return s.purchase(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return s.download(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error {
|
||||
return s.replicateSinf(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
return s.login(input)
|
||||
}
|
||||
@@ -1,358 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
)
|
||||
|
||||
type mcpSearchInput struct {
|
||||
Term string `json:"term" jsonschema:"Search term"`
|
||||
Limit *int64 `json:"limit,omitempty" jsonschema:"Maximum results; defaults to 5. visionOS supports up to 12."`
|
||||
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), watchos, visionos, or macos; defaults to iOS and iPadOS"`
|
||||
}
|
||||
|
||||
type mcpSearchOutput struct {
|
||||
Term string `json:"term"`
|
||||
Limit int64 `json:"limit"`
|
||||
Platform appstore.Platform `json:"platform"`
|
||||
Count int `json:"count"`
|
||||
Apps []mcpApp `json:"apps"`
|
||||
}
|
||||
|
||||
type mcpAppInput struct {
|
||||
AppID int64 `json:"app_id,omitempty" jsonschema:"Numeric app ID; required unless bundle_identifier is provided"`
|
||||
BundleID string `json:"bundle_identifier,omitempty" jsonschema:"Bundle identifier; overrides app_id when found"`
|
||||
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), watchos, visionos, or macos; uses the CLI default when omitted"`
|
||||
}
|
||||
|
||||
type mcpDownloadInput struct {
|
||||
mcpAppInput
|
||||
Output string `json:"output,omitempty" jsonschema:"Destination file or directory; defaults to the server's working directory"`
|
||||
ExternalVersionID string `json:"external_version_id,omitempty" jsonschema:"External version identifier; defaults to the latest version"`
|
||||
Purchase bool `json:"purchase,omitempty" jsonschema:"Acquire a free license if needed; defaults to false"`
|
||||
}
|
||||
|
||||
type mcpDownloadOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
Output string `json:"output"`
|
||||
ExternalVersionID string `json:"external_version_id"`
|
||||
Purchase bool `json:"purchase"`
|
||||
Purchased bool `json:"purchased"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type mcpVersionsOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
ExternalVersionIdentifiers []string `json:"externalVersionIdentifiers"`
|
||||
LatestExternalVersionID string `json:"latestExternalVersionID"`
|
||||
BundleID string `json:"bundleID"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type mcpVersionMetadataInput struct {
|
||||
mcpAppInput
|
||||
ExternalVersionID string `json:"external_version_id" jsonschema:"External version identifier of the target app (required)"`
|
||||
}
|
||||
|
||||
type mcpVersionMetadataOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
ExternalVersionID string `json:"external_version_id"`
|
||||
DisplayVersion string `json:"displayVersion" jsonschema:"Display version of the requested external version identifier"`
|
||||
ReleaseDate time.Time `json:"releaseDate"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type mcpPurchasesInput struct {
|
||||
Page *int `json:"page,omitempty" jsonschema:"Page number starting at 1; defaults to 1"`
|
||||
MaxResults *int `json:"max_results,omitempty" jsonschema:"Apps per page from 1 to 100; defaults to 10"`
|
||||
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), visionos, or macos; defaults to all platforms"`
|
||||
}
|
||||
|
||||
type mcpPurchasesOutput struct {
|
||||
Count int `json:"count"`
|
||||
TotalCount int `json:"totalCount"`
|
||||
Page int `json:"page"`
|
||||
MaxResults int `json:"max_results"`
|
||||
Platform appstore.Platform `json:"platform"`
|
||||
Apps []mcpApp `json:"apps"`
|
||||
}
|
||||
|
||||
type mcpPurchaseOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
AlreadyOwned bool `json:"alreadyOwned"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// withMCPAccount refreshes expired tokens using the saved credentials, as the CLI does.
|
||||
// Authentication and account details are never included in tool results.
|
||||
func withMCPAccount[Out any](ctx context.Context, store appstore.AppStore, operation func(appstore.Account) (Out, error)) (Out, error) {
|
||||
var zero Out
|
||||
|
||||
info, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("account unavailable; run 'ipatool auth login' before using MCP: %w", err)
|
||||
}
|
||||
|
||||
output, err := operation(info.Account)
|
||||
if !errors.Is(err, appstore.ErrPasswordTokenExpired) {
|
||||
return output, err
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return zero, fmt.Errorf("tool call canceled: %w", err)
|
||||
}
|
||||
|
||||
login, err := store.Login(appstore.LoginInput{Email: info.Account.Email, Password: info.Account.Password})
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("session refresh failed; run 'ipatool auth login' outside MCP: %w", err)
|
||||
}
|
||||
|
||||
output, err = operation(login.Account)
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("operation failed after session refresh: %w", err)
|
||||
}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) search(ctx context.Context, input mcpSearchInput) (mcpSearchOutput, error) {
|
||||
if strings.TrimSpace(input.Term) == "" {
|
||||
return mcpSearchOutput{}, errors.New("search term must not be empty")
|
||||
}
|
||||
|
||||
limit := int64(5)
|
||||
if input.Limit != nil {
|
||||
limit = *input.Limit
|
||||
}
|
||||
|
||||
if limit < 1 {
|
||||
return mcpSearchOutput{}, errors.New("limit must be greater than 0")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(input.Platform)
|
||||
if err != nil {
|
||||
return mcpSearchOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpSearchOutput, error) {
|
||||
out, err := t.store.Search(appstore.SearchInput{Account: acc, Term: input.Term, Limit: limit, Platform: platform})
|
||||
if err != nil {
|
||||
return mcpSearchOutput{}, err
|
||||
}
|
||||
|
||||
return mcpSearchOutput{
|
||||
Term: input.Term, Limit: limit, Platform: platform,
|
||||
Count: out.Count, Apps: t.appResults(acc, out.Results, platform),
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (input mcpAppInput) validate() (appstore.Platform, error) {
|
||||
if input.AppID < 0 || (input.AppID == 0 && strings.TrimSpace(input.BundleID) == "") {
|
||||
return "", errors.New("a positive app ID or a bundle identifier must be specified")
|
||||
}
|
||||
|
||||
return appstore.ParsePlatform(input.Platform)
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) resolveApp(acc appstore.Account, input mcpAppInput, platform appstore.Platform, allowDelisted bool) (appstore.App, error) {
|
||||
app := appstore.App{ID: input.AppID, BundleID: input.BundleID}
|
||||
if input.BundleID == "" {
|
||||
return t.completeApp(acc, app, platform), nil
|
||||
}
|
||||
|
||||
out, err := t.store.Lookup(appstore.LookupInput{Account: acc, BundleID: input.BundleID, Platform: platform})
|
||||
if allowDelisted && input.AppID > 0 && errors.Is(err, appstore.ErrAppNotFound) {
|
||||
return app, nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return appstore.App{}, err
|
||||
}
|
||||
|
||||
// Preserve a known bundle identifier even if the catalog omits it.
|
||||
if out.App.BundleID == "" {
|
||||
out.App.BundleID = input.BundleID
|
||||
}
|
||||
|
||||
return out.App, nil
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) download(ctx context.Context, input mcpDownloadInput) (mcpDownloadOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
purchased := false
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpDownloadOutput, error) {
|
||||
app, err := t.resolveApp(acc, input.mcpAppInput, platform, true)
|
||||
if err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
downloadInput := appstore.DownloadInput{
|
||||
Context: ctx, Account: acc, App: app, OutputPath: input.Output,
|
||||
ExternalVersionID: input.ExternalVersionID, Platform: platform,
|
||||
}
|
||||
|
||||
out, err := t.store.Download(downloadInput)
|
||||
if errors.Is(err, appstore.ErrLicenseRequired) && input.Purchase && !purchased {
|
||||
err = t.store.Purchase(appstore.PurchaseInput{Account: acc, App: app, Platform: platform})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
purchased = true
|
||||
out, err = t.store.Download(downloadInput)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
if err := replicateDownloadSinf(t.store, platform, out); err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
return mcpDownloadOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
Output: out.DestinationPath, ExternalVersionID: input.ExternalVersionID,
|
||||
Purchase: input.Purchase, Purchased: purchased, Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) listVersions(ctx context.Context, input mcpAppInput) (mcpVersionsOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpVersionsOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpVersionsOutput, error) {
|
||||
app, err := t.resolveApp(acc, input, platform, false)
|
||||
if err != nil {
|
||||
return mcpVersionsOutput{}, err
|
||||
}
|
||||
|
||||
out, err := t.store.ListVersions(appstore.ListVersionsInput{Context: ctx, Account: acc, App: app, Platform: platform})
|
||||
if err != nil {
|
||||
return mcpVersionsOutput{}, err
|
||||
}
|
||||
|
||||
return mcpVersionsOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
ExternalVersionIdentifiers: append([]string{}, out.ExternalVersionIdentifiers...),
|
||||
LatestExternalVersionID: out.LatestExternalVersionID, BundleID: app.BundleID, Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) getVersionMetadata(ctx context.Context, input mcpVersionMetadataInput) (mcpVersionMetadataOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
if strings.TrimSpace(input.ExternalVersionID) == "" {
|
||||
return mcpVersionMetadataOutput{}, errors.New("external version identifier must not be empty")
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpVersionMetadataOutput, error) {
|
||||
app, err := t.resolveApp(acc, input.mcpAppInput, platform, false)
|
||||
if err != nil {
|
||||
return mcpVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
out, err := t.store.GetVersionMetadata(appstore.GetVersionMetadataInput{
|
||||
Context: ctx, Account: acc, App: app, VersionID: input.ExternalVersionID, Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return mcpVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
return mcpVersionMetadataOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
ExternalVersionID: input.ExternalVersionID, DisplayVersion: out.DisplayVersion,
|
||||
ReleaseDate: out.ReleaseDate, Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) listPurchases(ctx context.Context, input mcpPurchasesInput) (mcpPurchasesOutput, error) {
|
||||
page, limit := 1, appstore.DefaultOwnedAppsLimit
|
||||
if input.Page != nil {
|
||||
page = *input.Page
|
||||
}
|
||||
|
||||
if input.MaxResults != nil {
|
||||
limit = *input.MaxResults
|
||||
}
|
||||
|
||||
if page < 1 {
|
||||
return mcpPurchasesOutput{}, errors.New("page must be greater than 0")
|
||||
}
|
||||
|
||||
if limit < 1 || limit > appstore.MaxOwnedAppsLimit {
|
||||
return mcpPurchasesOutput{}, fmt.Errorf("max results must be between 1 and %d", appstore.MaxOwnedAppsLimit)
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(input.Platform)
|
||||
if err != nil {
|
||||
return mcpPurchasesOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpPurchasesOutput, error) {
|
||||
out, err := t.store.OwnedApps(appstore.OwnedAppsInput{Account: acc, Page: page, Limit: limit, Platform: platform})
|
||||
if err != nil {
|
||||
return mcpPurchasesOutput{}, err
|
||||
}
|
||||
|
||||
return mcpPurchasesOutput{
|
||||
Count: out.Count, TotalCount: out.TotalCount, Page: out.Page, MaxResults: limit, Platform: platform,
|
||||
Apps: t.appResults(acc, out.Results, platform),
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) purchase(ctx context.Context, input mcpAppInput) (mcpPurchaseOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpPurchaseOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpPurchaseOutput, error) {
|
||||
app, err := t.resolveApp(acc, input, platform, false)
|
||||
if err != nil {
|
||||
return mcpPurchaseOutput{}, err
|
||||
}
|
||||
|
||||
err = t.store.Purchase(appstore.PurchaseInput{Account: acc, App: app, Platform: platform})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return mcpPurchaseOutput{}, err
|
||||
}
|
||||
|
||||
return mcpPurchaseOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
AlreadyOwned: errors.Is(err, appstore.ErrLicenseAlreadyExists), Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/thediveo/enumflag/v2"
|
||||
)
|
||||
|
||||
type OutputFormat enumflag.Flag
|
||||
|
||||
const (
|
||||
OutputFormatText OutputFormat = iota
|
||||
OutputFormatJSON
|
||||
)
|
||||
|
||||
func OutputFormatFromString(value string) (OutputFormat, error) {
|
||||
switch value {
|
||||
case "json":
|
||||
return OutputFormatJSON, nil
|
||||
case "text":
|
||||
return OutputFormatText, nil
|
||||
default:
|
||||
return OutputFormatJSON, fmt.Errorf("invalid output format '%s'", value)
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func readPrompt(prompt string, masked bool) (string, error) {
|
||||
if masked {
|
||||
state, err := term.MakeRaw(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to configure terminal: %w", err)
|
||||
}
|
||||
defer term.Restore(int(os.Stdin.Fd()), state) //nolint:errcheck
|
||||
}
|
||||
|
||||
// Prompts belong on stderr so structured output on stdout stays valid.
|
||||
if _, err := io.WriteString(os.Stderr, prompt); err != nil {
|
||||
return "", fmt.Errorf("failed to write prompt: %w", err)
|
||||
}
|
||||
|
||||
if masked {
|
||||
defer fmt.Fprint(os.Stderr, "\r\n")
|
||||
|
||||
return readMaskedInput(os.Stdin, os.Stderr)
|
||||
}
|
||||
|
||||
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read input: %w", err)
|
||||
}
|
||||
|
||||
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
|
||||
}
|
||||
|
||||
func readMaskedInput(input io.Reader, output io.Writer) (string, error) {
|
||||
reader := bufio.NewReader(input)
|
||||
|
||||
var (
|
||||
password []rune
|
||||
escape int
|
||||
)
|
||||
|
||||
for {
|
||||
key, _, err := reader.ReadRune()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read input: %w", err)
|
||||
}
|
||||
|
||||
// Ignore terminal escape sequences (for example, arrow keys).
|
||||
if escape != 0 {
|
||||
if escape == 1 && (key == '[' || key == 'O') {
|
||||
escape = 2
|
||||
} else if escape == 1 || (key >= 0x40 && key <= 0x7e) {
|
||||
escape = 0
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var echo string
|
||||
|
||||
switch key {
|
||||
case '\r', '\n':
|
||||
return string(password), nil
|
||||
case 3:
|
||||
return "", errors.New("input interrupted")
|
||||
case 4:
|
||||
return "", io.EOF
|
||||
case 27:
|
||||
escape = 1
|
||||
case '\b', 127:
|
||||
if len(password) > 0 {
|
||||
password = password[:len(password)-1]
|
||||
echo = "\b \b"
|
||||
}
|
||||
case 21:
|
||||
echo = strings.Repeat("\b \b", len(password))
|
||||
password = password[:0]
|
||||
default:
|
||||
if unicode.IsPrint(key) {
|
||||
password = append(password, key)
|
||||
echo = "*"
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := io.WriteString(output, echo); err != nil {
|
||||
return "", fmt.Errorf("failed to echo input: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Masked input", func() {
|
||||
DescribeTable("echoes masks while preserving the entered password", func(input, password, echo string) {
|
||||
var output bytes.Buffer
|
||||
value, err := readMaskedInput(strings.NewReader(input), &output)
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(value).To(Equal(password))
|
||||
Expect(output.String()).To(Equal(echo))
|
||||
},
|
||||
Entry("enter", "secret\r", "secret", "******"),
|
||||
Entry("newline", "secret\n", "secret", "******"),
|
||||
Entry("unicode", "pä密🔑\r", "pä密🔑", "****"),
|
||||
Entry("delete", "ab\x7fc\r", "ac", "**\b \b*"),
|
||||
Entry("unicode backspace", "a密\bc\r", "ac", "**\b \b*"),
|
||||
Entry("backspace on empty input", "\b\x7fa\r", "a", "*"),
|
||||
Entry("clear line", "ab\x15c\r", "c", "**\b \b\b \b*"),
|
||||
Entry("arrow keys", "ab\x1b[D\x1bOCc\r", "abc", "***"),
|
||||
Entry("empty input", "\r", "", ""),
|
||||
)
|
||||
|
||||
It("cancels without returning the password on Ctrl-C", func() {
|
||||
value, err := readMaskedInput(strings.NewReader("secret\x03"), io.Discard)
|
||||
|
||||
Expect(err).To(MatchError("input interrupted"))
|
||||
Expect(value).To(BeEmpty())
|
||||
})
|
||||
|
||||
DescribeTable("discards incomplete input", func(input string) {
|
||||
value, err := readMaskedInput(strings.NewReader(input), io.Discard)
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("EOF")))
|
||||
Expect(value).To(BeEmpty())
|
||||
},
|
||||
Entry("end of stream", "secret"),
|
||||
Entry("Ctrl-D", "secret\x04"),
|
||||
)
|
||||
})
|
||||
-110
@@ -1,110 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func purchaseCmd() *cobra.Command {
|
||||
return purchaseCmdWithAppStore(func() appstore.AppStore { return dependencies.AppStore })
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func purchaseCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "purchase",
|
||||
Short: "Obtain a license for the app from the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
return retry.Do(func() error {
|
||||
store := appStore()
|
||||
infoResult, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := store.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := store.Lookup(appstore.LookupInput{
|
||||
Account: acc,
|
||||
BundleID: bundleID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
err = store.Purchase(appstore.PurchaseInput{
|
||||
Account: acc,
|
||||
App: app,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Bool("alreadyOwned", errors.Is(err, appstore.ErrLicenseAlreadyExists)).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to purchase for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Purchase command", func() {
|
||||
It("accepts a platform flag with macOS help", func() {
|
||||
cmd := purchaseCmd()
|
||||
platform, err := cmd.Flags().GetString("platform")
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(platform).To(BeEmpty())
|
||||
Expect(cmd.Flag("platform").Usage).To(ContainSubstring("macos"))
|
||||
})
|
||||
|
||||
DescribeTable("purchasing by app ID", func(flag string) {
|
||||
store := &fakePurchaseAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{flag, "123456789", "--platform", "macos"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.lookupCalls).To(BeZero())
|
||||
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 123456789}))
|
||||
Expect(store.purchaseInput.Platform).To(Equal(appstore.PlatformMacOS))
|
||||
},
|
||||
Entry("accepts the long flag", "--app-id"),
|
||||
Entry("accepts the short flag", "-i"),
|
||||
)
|
||||
|
||||
It("requires an app ID or bundle identifier before accessing the account", func() {
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore {
|
||||
Fail("must not access the app store without a target")
|
||||
|
||||
return nil
|
||||
})
|
||||
cmd.SetArgs([]string{})
|
||||
|
||||
Expect(cmd.Execute()).To(MatchError("either the app ID or the bundle identifier must be specified"))
|
||||
})
|
||||
|
||||
It("lets the bundle identifier override the app ID", func() {
|
||||
store := &fakePurchaseAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"-i", "123456789", "-b", "com.example.app"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.lookupCalls).To(Equal(1))
|
||||
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.app"}))
|
||||
})
|
||||
|
||||
It("propagates macOS to lookup and purchase", func() {
|
||||
store := &fakePurchaseAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--bundle-identifier", "com.example.mac", "--platform", "macos"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.lookupInput.BundleID).To(Equal("com.example.mac"))
|
||||
Expect(store.lookupInput.Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.purchaseInput.Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.mac"}))
|
||||
})
|
||||
})
|
||||
|
||||
type fakePurchaseAppStore struct {
|
||||
lookupCalls int
|
||||
lookupInput appstore.LookupInput
|
||||
purchaseInput appstore.PurchaseInput
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
return appstore.LoginOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{Account: appstore.Account{StoreFront: "143441"}}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Revoke() error { return nil }
|
||||
|
||||
func (f *fakePurchaseAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
f.lookupCalls++
|
||||
f.lookupInput = input
|
||||
|
||||
return appstore.LookupOutput{App: appstore.App{ID: 42, BundleID: input.BundleID}}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{}, nil
|
||||
}
|
||||
|
||||
func (f *fakePurchaseAppStore) Purchase(input appstore.PurchaseInput) error {
|
||||
f.purchaseInput = input
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error { return nil }
|
||||
|
||||
func (*fakePurchaseAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Bag(input appstore.BagInput) (appstore.BagOutput, error) {
|
||||
return appstore.BagOutput{}, nil
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func listPurchasesCmd() *cobra.Command {
|
||||
var page, maxResults int
|
||||
|
||||
var platformValue string
|
||||
|
||||
var platform appstore.Platform
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "list-purchases",
|
||||
Short: "List apps owned by the authenticated App Store account",
|
||||
Args: cobra.NoArgs,
|
||||
PreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
if page < 1 {
|
||||
return errors.New("page must be greater than 0")
|
||||
}
|
||||
if maxResults < 1 {
|
||||
return errors.New("max results must be greater than 0")
|
||||
}
|
||||
if maxResults > appstore.MaxOwnedAppsLimit {
|
||||
return fmt.Errorf("max results must not exceed %d", appstore.MaxOwnedAppsLimit)
|
||||
}
|
||||
|
||||
var err error
|
||||
platform, err = appstore.ParsePlatform(platformValue)
|
||||
|
||||
return err
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
var lastErr error
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc := infoResult.Account
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
output, err := dependencies.AppStore.OwnedApps(appstore.OwnedAppsInput{
|
||||
Account: acc,
|
||||
Page: page,
|
||||
Limit: maxResults,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Int("count", output.Count).
|
||||
Int("totalCount", output.TotalCount).
|
||||
Int("page", output.Page).
|
||||
Array("apps", appstore.Apps(output.Results)).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().IntVarP(&maxResults, "max-results", "l", appstore.DefaultOwnedAppsLimit, "maximum number of apps to return per page")
|
||||
cmd.Flags().IntVarP(&page, "page", "p", 1, "page of owned apps to return")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Filter by platform: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("List Purchases command", func() {
|
||||
DescribeTable("passes the platform filter to owned apps",
|
||||
func(value string, expected appstore.Platform) {
|
||||
store := &fakePurchasesAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
cmd := listPurchasesCmd()
|
||||
cmd.SetArgs([]string{"--platform", value})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.input.Platform).To(Equal(expected))
|
||||
},
|
||||
Entry("all platforms by default", "", appstore.Platform("")),
|
||||
Entry("iOS alias", "ios", appstore.PlatformIPhone),
|
||||
Entry("iPadOS alias", "ipados", appstore.PlatformIPad),
|
||||
Entry("tvOS alias", "tvos", appstore.PlatformAppleTV),
|
||||
Entry("visionOS", "visionos", appstore.PlatformVisionOS),
|
||||
Entry("macOS", "macos", appstore.PlatformMacOS),
|
||||
)
|
||||
|
||||
DescribeTable("rejects an invalid platform before accessing the account", func(value string) {
|
||||
cmd := listPurchasesCmd()
|
||||
Expect(cmd.Flags().Set("platform", value)).To(Succeed())
|
||||
Expect(cmd.PreRunE(cmd, nil)).To(MatchError(ContainSubstring("invalid platform")))
|
||||
},
|
||||
Entry("invalid value", "invalid"),
|
||||
Entry("unknown is output only", "unknown"),
|
||||
Entry("uppercase unknown", "UNKNOWN"),
|
||||
)
|
||||
|
||||
It("uses the pagination defaults", func() {
|
||||
cmd := listPurchasesCmd()
|
||||
|
||||
page, err := cmd.Flags().GetInt("page")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(page).To(Equal(1))
|
||||
|
||||
maxResults, err := cmd.Flags().GetInt("max-results")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(maxResults).To(Equal(appstore.DefaultOwnedAppsLimit))
|
||||
})
|
||||
|
||||
DescribeTable("rejects invalid pagination",
|
||||
func(flag, value, errorText string) {
|
||||
cmd := listPurchasesCmd()
|
||||
Expect(cmd.Flags().Set(flag, value)).To(Succeed())
|
||||
|
||||
err := cmd.PreRunE(cmd, nil)
|
||||
Expect(err).To(MatchError(ContainSubstring(errorText)))
|
||||
},
|
||||
Entry("page below one", "page", "0", "page"),
|
||||
Entry("max results below one", "max-results", "0", "max results"),
|
||||
Entry("max results over limit", "max-results", "101", "100"),
|
||||
)
|
||||
|
||||
It("is registered on the root command", func() {
|
||||
cmd, _, err := rootCmd().Find([]string{"list-purchases"})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(cmd.Name()).To(Equal("list-purchases"))
|
||||
})
|
||||
})
|
||||
|
||||
type fakePurchasesAppStore struct {
|
||||
appstore.AppStore
|
||||
input appstore.OwnedAppsInput
|
||||
}
|
||||
|
||||
func (*fakePurchasesAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, nil
|
||||
}
|
||||
|
||||
func (s *fakePurchasesAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
s.input = input
|
||||
|
||||
return appstore.OwnedAppsOutput{}, nil
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/thediveo/enumflag/v2"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
type contextKey string
|
||||
|
||||
const interactiveKey contextKey = "interactive"
|
||||
|
||||
func rootCmd() *cobra.Command {
|
||||
var (
|
||||
verbose bool
|
||||
nonInteractive bool
|
||||
format OutputFormat
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "ipatool",
|
||||
Short: "A cli tool for interacting with Apple's ipa files",
|
||||
SilenceErrors: true,
|
||||
SilenceUsage: true,
|
||||
Version: version,
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
ctx := context.WithValue(context.Background(), interactiveKey, !nonInteractive)
|
||||
cmd.SetContext(ctx)
|
||||
initWithCommand(cmd)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.PersistentFlags().VarP(
|
||||
enumflag.New(&format, "format", map[OutputFormat][]string{
|
||||
OutputFormatText: {"text"},
|
||||
OutputFormatJSON: {"json"},
|
||||
}, enumflag.EnumCaseSensitive), "format", "", "sets output format for command; can be 'text', 'json'")
|
||||
cmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "enables verbose logs")
|
||||
cmd.PersistentFlags().BoolVarP(&nonInteractive, "non-interactive", "", false, "run in non-interactive session")
|
||||
cmd.PersistentFlags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
|
||||
cmd.AddCommand(authCmd())
|
||||
cmd.AddCommand(downloadCmd())
|
||||
cmd.AddCommand(listPurchasesCmd())
|
||||
cmd.AddCommand(purchaseCmd())
|
||||
cmd.AddCommand(searchCmd())
|
||||
cmd.AddCommand(ListVersionsCmd())
|
||||
cmd.AddCommand(getVersionMetadataCmd())
|
||||
cmd.AddCommand(mcpCmd())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
// Execute runs the program and returns the appropriate exit status code.
|
||||
func Execute() int {
|
||||
cmd := rootCmd()
|
||||
err := cmd.Execute()
|
||||
|
||||
if err != nil {
|
||||
if reflect.ValueOf(dependencies).IsZero() {
|
||||
initWithCommand(cmd)
|
||||
}
|
||||
|
||||
var appstoreErr *appstore.Error
|
||||
if errors.As(err, &appstoreErr) {
|
||||
dependencies.Logger.Verbose().Stack().
|
||||
Err(err).
|
||||
Interface("metadata", appstoreErr.Metadata).
|
||||
Send()
|
||||
} else {
|
||||
dependencies.Logger.Verbose().Stack().Err(err).Send()
|
||||
}
|
||||
|
||||
dependencies.Logger.Error().
|
||||
Err(err).
|
||||
Bool("success", false).
|
||||
Send()
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func searchCmd() *cobra.Command {
|
||||
var (
|
||||
limit int64
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "search <term>",
|
||||
Short: "Search for iOS, iPadOS, tvOS, watchOS, visionOS, and macOS apps available on the App Store",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
output, err := dependencies.AppStore.Search(appstore.SearchInput{
|
||||
Account: infoResult.Account,
|
||||
Term: args[0],
|
||||
Limit: limit,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Int("count", output.Count).
|
||||
Array("apps", appstore.Apps(output.Results)).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&limit, "limit", "l", 5, "maximum amount of search results to retrieve; visionOS supports up to 12")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
)
|
||||
|
||||
// prepareStateDirectory resolves and migrates session storage before it is opened.
|
||||
func prepareStateDirectory(os operatingsystem.OperatingSystem, homeDirectory string) (string, error) {
|
||||
legacyDirectory := filepath.Join(homeDirectory, ConfigDirectoryName)
|
||||
stateDirectory := legacyDirectory
|
||||
|
||||
for _, variable := range []string{"XDG_STATE_HOME", "XDG_DATA_HOME"} {
|
||||
if base := os.Getenv(variable); filepath.IsAbs(base) {
|
||||
stateDirectory = filepath.Join(base, "ipatool")
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
info, err := os.Stat(legacyDirectory)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return "", fmt.Errorf("could not read legacy state directory metadata: %w", err)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
if !info.IsDir() {
|
||||
return "", fmt.Errorf("legacy state path is not a directory: %s", legacyDirectory)
|
||||
}
|
||||
// Never merge sessions or move a directory into itself. Keeping the legacy
|
||||
// directory also preserves authentication when migration is unavailable.
|
||||
relative, err := filepath.Rel(legacyDirectory, stateDirectory)
|
||||
if err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
|
||||
if _, err := os.Stat(stateDirectory); err == nil || !os.IsNotExist(err) {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(stateDirectory), 0700); err != nil {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
// Rename keeps cookies and encrypted credentials together, with their
|
||||
// existing permissions. Cross-filesystem moves fall back to legacy storage.
|
||||
if err := os.Rename(legacyDirectory, stateDirectory); err != nil {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
|
||||
return stateDirectory, nil
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(stateDirectory, 0700); err != nil {
|
||||
return "", fmt.Errorf("failed to create state directory: %w", err)
|
||||
}
|
||||
|
||||
return stateDirectory, nil
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("State directory", func() {
|
||||
var home, legacy, target string
|
||||
|
||||
BeforeEach(func() {
|
||||
home = GinkgoT().TempDir()
|
||||
legacy = filepath.Join(home, ConfigDirectoryName)
|
||||
target = filepath.Join(home, "state", "ipatool")
|
||||
GinkgoT().Setenv("XDG_STATE_HOME", filepath.Dir(target))
|
||||
GinkgoT().Setenv("XDG_DATA_HOME", "")
|
||||
})
|
||||
|
||||
DescribeTable("selects the session directory", func(state, data, want string) {
|
||||
for variable, value := range map[string]string{"XDG_STATE_HOME": state, "XDG_DATA_HOME": data} {
|
||||
if value != "" && value != "relative" {
|
||||
value = filepath.Join(home, value)
|
||||
}
|
||||
|
||||
GinkgoT().Setenv(variable, value)
|
||||
}
|
||||
|
||||
got, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(filepath.Join(home, want)))
|
||||
Expect(got).To(BeADirectory())
|
||||
|
||||
if got != legacy {
|
||||
Expect(legacy).ToNot(BeAnExistingFile())
|
||||
}
|
||||
},
|
||||
Entry("defaults to legacy storage", "", "", ConfigDirectoryName),
|
||||
Entry("prefers state storage", "state", "data", "state/ipatool"),
|
||||
Entry("falls back to data storage", "", "data", "data/ipatool"),
|
||||
Entry("ignores a relative state path", "relative", "data", "data/ipatool"),
|
||||
Entry("ignores relative paths", "relative", "relative", ConfigDirectoryName),
|
||||
)
|
||||
|
||||
It("preserves authentication after migration and subsequent startup", func() {
|
||||
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
|
||||
|
||||
openKeyring := func(directory string) keyring.Keyring {
|
||||
ring, err := keyring.Open(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{keyring.FileBackend},
|
||||
ServiceName: KeychainServiceName,
|
||||
FileDir: directory,
|
||||
FilePasswordFunc: keyring.FixedStringPrompt("test-passphrase"),
|
||||
})
|
||||
ExpectWithOffset(1, err).ToNot(HaveOccurred())
|
||||
|
||||
return ring
|
||||
}
|
||||
item := keyring.Item{Key: "account", Data: []byte("existing-session"), Label: KeychainServiceName}
|
||||
Expect(openKeyring(legacy).Set(item)).To(Succeed())
|
||||
|
||||
cookieURL, err := url.Parse("https://apps.apple.com/")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
jar := newCookieJar(legacy)
|
||||
jar.SetCookies(cookieURL, []*http.Cookie{{Name: "session", Value: "existing-cookie", Path: "/", Expires: time.Now().Add(time.Hour)}})
|
||||
Expect(jar.Save()).To(Succeed())
|
||||
|
||||
before, err := os.ReadFile(filepath.Join(legacy, item.Key))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
directory, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(directory).To(Equal(target))
|
||||
|
||||
got, err := openKeyring(directory).Get(item.Key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got.Data).To(Equal(item.Data))
|
||||
|
||||
after, err := os.ReadFile(filepath.Join(directory, item.Key))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(after).To(Equal(before), "encrypted credentials must remain unchanged")
|
||||
|
||||
cookies := newCookieJar(directory).Cookies(cookieURL)
|
||||
Expect(cookies).To(HaveLen(1))
|
||||
Expect(cookies[0].Name).To(Equal("session"))
|
||||
Expect(cookies[0].Value).To(Equal("existing-cookie"))
|
||||
}
|
||||
|
||||
Expect(legacy).ToNot(BeAnExistingFile())
|
||||
})
|
||||
|
||||
DescribeTable("preserves legacy storage when migration fails", func(mkdirErr, renameErr error) {
|
||||
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(legacy, CookieJarFileName), []byte("session"), 0600)).To(Succeed())
|
||||
|
||||
got, err := prepareStateDirectory(migrationFailureOS{operatingsystem.New(), mkdirErr, renameErr}, home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(legacy))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(got, CookieJarFileName))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(string(data)).To(Equal("session"))
|
||||
},
|
||||
Entry("parent creation denied", os.ErrPermission, nil),
|
||||
Entry("rename denied", nil, os.ErrPermission),
|
||||
Entry("cross filesystem", nil, errors.New("cross-device link")),
|
||||
)
|
||||
|
||||
It("preserves conflicting sessions and uses legacy storage", func() {
|
||||
for _, directory := range []string{legacy, target} {
|
||||
Expect(os.MkdirAll(directory, 0700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(directory, "account"), []byte(directory), 0600)).To(Succeed())
|
||||
}
|
||||
|
||||
got, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(legacy))
|
||||
|
||||
for _, directory := range []string{legacy, target} {
|
||||
data, err := os.ReadFile(filepath.Join(directory, "account"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(string(data)).To(Equal(directory))
|
||||
}
|
||||
})
|
||||
|
||||
DescribeTable("rejects files at directory paths", func(useLegacy bool) {
|
||||
path := target
|
||||
if useLegacy {
|
||||
path = legacy
|
||||
}
|
||||
|
||||
Expect(os.MkdirAll(filepath.Dir(path), 0700)).To(Succeed())
|
||||
Expect(os.WriteFile(path, []byte("existing file"), 0600)).To(Succeed())
|
||||
|
||||
_, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).To(HaveOccurred())
|
||||
},
|
||||
Entry("legacy", true),
|
||||
Entry("destination", false),
|
||||
)
|
||||
|
||||
It("preserves legacy storage for a nested destination", func() {
|
||||
GinkgoT().Setenv("XDG_STATE_HOME", filepath.Join(legacy, "state"))
|
||||
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
|
||||
|
||||
got, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(legacy))
|
||||
|
||||
entries, err := os.ReadDir(legacy)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(entries).To(BeEmpty(), "migration must not create directories inside legacy storage")
|
||||
})
|
||||
})
|
||||
|
||||
type migrationFailureOS struct {
|
||||
operatingsystem.OperatingSystem
|
||||
mkdirErr, renameErr error
|
||||
}
|
||||
|
||||
// nolint:wrapcheck
|
||||
func (o migrationFailureOS) MkdirAll(path string, mode os.FileMode) error {
|
||||
if o.mkdirErr != nil {
|
||||
return o.mkdirErr
|
||||
}
|
||||
|
||||
return o.OperatingSystem.MkdirAll(path, mode)
|
||||
}
|
||||
|
||||
func (o migrationFailureOS) Rename(from, to string) error {
|
||||
return o.renameErr
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
module github.com/majd/ipatool/v2
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/avast/retry-go v3.0.0+incompatible
|
||||
github.com/blacktop/go-macho v1.1.282
|
||||
github.com/bodgit/sevenzip v1.6.3
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4
|
||||
github.com/byteness/keyring v1.9.0
|
||||
github.com/ebitengine/purego v0.10.2
|
||||
github.com/juju/persistent-cookiejar v1.0.0
|
||||
github.com/klauspost/compress v1.18.6
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0
|
||||
github.com/onsi/ginkgo/v2 v2.5.0
|
||||
github.com/onsi/gomega v1.24.0
|
||||
github.com/rs/zerolog v1.28.0
|
||||
github.com/schollz/progressbar/v3 v3.13.1
|
||||
github.com/spf13/cobra v1.6.1
|
||||
github.com/thediveo/enumflag/v2 v2.0.1
|
||||
go.uber.org/mock v0.4.0
|
||||
golang.org/x/sys v0.45.0
|
||||
golang.org/x/term v0.43.0
|
||||
howett.net/plist v1.0.0
|
||||
howett.net/ranger v0.0.0-20171016084633-e2e137620847
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b // indirect
|
||||
github.com/1password/onepassword-sdk-go v0.4.1-beta.1 // indirect
|
||||
github.com/andybalholm/brotli v1.2.1 // indirect
|
||||
github.com/blacktop/go-dwarf v1.0.14 // indirect
|
||||
github.com/bodgit/plumbing v1.3.0 // indirect
|
||||
github.com/bodgit/windows v1.0.1 // indirect
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 // indirect
|
||||
github.com/byteness/percent v0.2.2 // indirect
|
||||
github.com/danieljoos/wincred v1.2.3 // indirect
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0 // indirect
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 // indirect
|
||||
github.com/extism/go-sdk v1.7.1 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/gobwas/glob v0.2.3 // indirect
|
||||
github.com/godbus/dbus/v5 v5.2.2 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/jsonschema-go v0.4.3 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.1 // indirect
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.17 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.14 // indirect
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
|
||||
github.com/noamcohen97/touchid-go v0.3.0 // indirect
|
||||
github.com/opentracing/opentracing-go v1.2.0 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.26 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/segmentio/asm v1.1.3 // indirect
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/stangelandcl/ppmd v0.1.0 // indirect
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect
|
||||
github.com/tetratelabs/wazero v1.11.0 // indirect
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible // indirect
|
||||
github.com/ulikunitz/xz v0.5.15 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f // indirect
|
||||
golang.org/x/crypto v0.52.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
|
||||
golang.org/x/mod v0.35.0 // indirect
|
||||
golang.org/x/net v0.55.0 // indirect
|
||||
golang.org/x/oauth2 v0.35.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/tools v0.44.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/errgo.v1 v1.0.1 // indirect
|
||||
gopkg.in/retry.v1 v1.0.3 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -1,214 +0,0 @@
|
||||
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b h1:sVddTkAGVmDXJbZKgp+W1zC7hN4lLz9Nus1XmjbY7eo=
|
||||
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b/go.mod h1:5rSymY4oIYtS4G3t0oMkGAXBeoYiukV3vkqlnEjIDJs=
|
||||
github.com/1password/onepassword-sdk-go v0.4.1-beta.1 h1:b/tt+bAXFXR5f3/irmPAaytfmsN6+5Nj6pbsx5nmKZA=
|
||||
github.com/1password/onepassword-sdk-go v0.4.1-beta.1/go.mod h1:j/CbzhucTywjlYrd6SE6k0LcQaFZ2l8OLBsAsOYtvD0=
|
||||
github.com/HdrHistogram/hdrhistogram-go v1.1.2 h1:5IcZpTvzydCQeHzK4Ef/D5rrSqwxob0t8PQPMybUNFM=
|
||||
github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo=
|
||||
github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro=
|
||||
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0=
|
||||
github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY=
|
||||
github.com/blacktop/go-dwarf v1.0.14 h1:OjmzfSgg/qAKckn2tWFebcgKgJ7HOqCj7bS+CiE1lrY=
|
||||
github.com/blacktop/go-dwarf v1.0.14/go.mod h1:4W2FKgSFYcZLDwnR7k+apv5i3nrau4NGl9N6VQ9DSTo=
|
||||
github.com/blacktop/go-macho v1.1.282 h1:DW3HYz5zVCT6+Jlp1+hxauYvEgxqZsGMvu8/1j4+Ibg=
|
||||
github.com/blacktop/go-macho v1.1.282/go.mod h1:Hc5E2Lvt/U1VT+jOxr1O5l/LNFJeMYK4eAmDfazTiGc=
|
||||
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
|
||||
github.com/bodgit/plumbing v1.3.0/go.mod h1:JOTb4XiRu5xfnmdnDJo6GmSbSbtSyufrsyZFByMtKEs=
|
||||
github.com/bodgit/sevenzip v1.6.3 h1:t7K1jcgPnXdZyRHr68vq5L9vO/WmjDJEiGUwTR6i6gk=
|
||||
github.com/bodgit/sevenzip v1.6.3/go.mod h1:a29jn+ZL8UfQr/L+8jJT1wmhCMulGOfaT5d1HWxwD5g=
|
||||
github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4=
|
||||
github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM=
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:HFl8GFmwK19hYuXB8OQ0rTO9WOCgZY9JUy964zaYawY=
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:9HlL8SWBRtCZE7sCNq+c3//H/oHywgSwtocmPTdOij8=
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 h1:j59wGsxaBk6aFBuuYofk2oznMGZYyzFovjDqavlJHM8=
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0/go.mod h1:3FrDGTXj08zj6qtqlIvt0vS8eWNrrYpnXOEbcQgFmvM=
|
||||
github.com/byteness/keyring v1.9.0 h1:9m+7pru+JkMJ8wxma5id5m6pSt2Zx/xPj77kyM+yAVE=
|
||||
github.com/byteness/keyring v1.9.0/go.mod h1:a6CV8t/qfEUERPTP+dqeVfKgib2wz3PIYbMWRfmvmes=
|
||||
github.com/byteness/percent v0.2.2 h1:vnIFh8WBR1xoC+U2etz0EMB1cgp+vsK6vynqTCeDziU=
|
||||
github.com/byteness/percent v0.2.2/go.mod h1:nwavge92FhIyfnldz4YWZD8uxPVvdh8NlzLRd1VYRDs=
|
||||
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
|
||||
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0 h1:LqkkVKAlHFfH9LOEl5fe4p/zL02OhWE7pCufMBG2jLA=
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 h1:idfl8M8rPW93NehFw5H1qqH8yG158t5POr+LX9avbJY=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
|
||||
github.com/ebitengine/purego v0.10.2 h1:W809HbnvzAxgdm+aOvlSekrM16wGCdT/e76+9tS7gzE=
|
||||
github.com/ebitengine/purego v0.10.2/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
|
||||
github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA=
|
||||
github.com/frankban/quicktest v1.2.2 h1:xfmOhhoH5fGPgbEAlhLpJH9p0z/0Qizio9osmvn9IUY=
|
||||
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
|
||||
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
|
||||
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
|
||||
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f h1:Fnl4pzx8SR7k7JuzyW8lEtSFH6EQ8xgcypgIn8pcGIE=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
|
||||
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
|
||||
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a h1:45JtCyuNYE+QN9aPuR1ID9++BQU+NMTMudHSuaK0Las=
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a/go.mod h1:RVHtZuvrpETIepiNUrNlih2OynoFf1eM6DGC6dloXzk=
|
||||
github.com/juju/persistent-cookiejar v1.0.0 h1:Ag7+QLzqC2m+OYXy2QQnRjb3gTkEBSZagZ6QozwT3EQ=
|
||||
github.com/juju/persistent-cookiejar v1.0.0/go.mod h1:zrbmo4nBKaiP/Ez3F67ewkMbzGYfXyMvRtbOfuAwG0w=
|
||||
github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
|
||||
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
|
||||
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/noamcohen97/touchid-go v0.3.0 h1:fcXxVCizysD7KHRR6hrURt3nyNIs5JBGSbOIidD/3wo=
|
||||
github.com/noamcohen97/touchid-go v0.3.0/go.mod h1:X9MRNIBGEmPqwpDm1G3fQOAQX7fwBlhzUbnkDTxuta0=
|
||||
github.com/onsi/ginkgo/v2 v2.5.0 h1:TRtrvv2vdQqzkwrQ1ke6vtXf7IK34RBUJafIy1wMwls=
|
||||
github.com/onsi/ginkgo/v2 v2.5.0/go.mod h1:Luc4sArBICYCS8THh8v3i3i5CuSZO+RaQRaJoeNwomw=
|
||||
github.com/onsi/gomega v1.24.0 h1:+0glovB9Jd6z3VR+ScSwQqXVTIfJcGA9UBM8yzQxhqg=
|
||||
github.com/onsi/gomega v1.24.0/go.mod h1:Z/NWtiqwBrwUt4/2loMmHL63EDLnYHmVbuBpDr2vQAg=
|
||||
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
|
||||
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
|
||||
github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=
|
||||
github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a h1:3QH7VyOaaiUHNrA9Se4YQIRkDTCw1EJls9xTUCaCeRM=
|
||||
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a/go.mod h1:4r5QyqhjIWCcK8DO4KMclc5Iknq5qVBAlbYYzAbUScQ=
|
||||
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY=
|
||||
github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/schollz/progressbar/v3 v3.13.1 h1:o8rySDYiQ59Mwzy2FELeHY5ZARXZTVJC7iHD6PEFUiE=
|
||||
github.com/schollz/progressbar/v3 v3.13.1/go.mod h1:xvrbki8kfT1fzWzBT/UZd9L6GA+jdL7HAgq2RFnO6fQ=
|
||||
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
|
||||
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
|
||||
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
|
||||
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
||||
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
|
||||
github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
|
||||
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/stangelandcl/ppmd v0.1.0 h1:0gOKtSdWyXxpRW55H/dZ3AgaJqjrtlIrAvsokFwp7ug=
|
||||
github.com/stangelandcl/ppmd v0.1.0/go.mod h1:Rrv7M+/2P5jYr/GMLhBl7Ug3uJ1bUiVzr5LbbaV6xgY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk=
|
||||
github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
|
||||
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
|
||||
github.com/thediveo/enumflag/v2 v2.0.1 h1:2bmWZPD2uSARDsOjXIdLRlNcYBFNF9xX0RNUNF2vKic=
|
||||
github.com/thediveo/enumflag/v2 v2.0.1/go.mod h1:SyxyCNvv0QeRtZ7fjuaUz4FRLC3cWuDiD7QdORU0MGg=
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o=
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVKhn2Um6rjCsSsg=
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
|
||||
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
|
||||
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
|
||||
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f h1:ziUVAjmTPwQMBmYR1tbdRFJPtTcQUI12fH9QQjfb0Sw=
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f/go.mod h1:ZRJnO5ZI4zAwMFp+dS1+V6J6MSyAowhRqAE+DPa1Xp0=
|
||||
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=
|
||||
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
|
||||
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
|
||||
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
|
||||
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U=
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/errgo.v1 v1.0.1 h1:oQFRXzZ7CkBGdm1XZm/EbQYaYNNEElNBOd09M6cqNso=
|
||||
gopkg.in/errgo.v1 v1.0.1/go.mod h1:3NjfXwocQRYAPTq4/fzX+CwUhPRcR/azYRhj8G+LqMo=
|
||||
gopkg.in/retry.v1 v1.0.3 h1:a9CArYczAVv6Qs6VGoLMio99GEs7kY9UzSF9+LD+iGs=
|
||||
gopkg.in/retry.v1 v1.0.3/go.mod h1:FJkXmWiMaAo7xB+xhvDF59zhfjDWyzmyAxiT4dB688g=
|
||||
gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM=
|
||||
howett.net/plist v1.0.0/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
|
||||
howett.net/ranger v0.0.0-20171016084633-e2e137620847 h1:jHX+2Sv8rQNb1nG2G9pcQLdVoWXBLW5fcd2gnfHluCU=
|
||||
howett.net/ranger v0.0.0-20171016084633-e2e137620847/go.mod h1:ZWGIG4mR6Ck+CdmFqK2/jox5vO2OAS8Qpb33HB8z0og=
|
||||
@@ -1,386 +0,0 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/bzip2"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/blacktop/go-macho/pkg/xar"
|
||||
"howett.net/ranger"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/cpio"
|
||||
)
|
||||
|
||||
const (
|
||||
updateURL = "https://swcdn.apple.com/content/downloads/27/34/041-98128-A_SYPWICN3KH/5dqkl4rqgbsr18yzy61yeie9g3cmjc5hiv/OSXUpd10.9.pkg"
|
||||
payloadName = "Payload"
|
||||
payloadBZOffset = int64(0x352F40D5)
|
||||
payloadCPIO = int64(0x3A4)
|
||||
)
|
||||
|
||||
type Bundle struct {
|
||||
CommerceKit []byte
|
||||
CommerceCore []byte
|
||||
CoreFP []byte
|
||||
CoreFPICXS []byte
|
||||
}
|
||||
|
||||
type fileSpec struct {
|
||||
name string
|
||||
path string
|
||||
size int
|
||||
digest [32]byte
|
||||
}
|
||||
|
||||
var requiredFiles = []fileSpec{
|
||||
{
|
||||
name: "CommerceKit",
|
||||
path: "./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/CommerceKit",
|
||||
size: 3271840,
|
||||
digest: mustDigest("b84ff12c21987856c0a17b78f1ad82b73195a6dec5f3b208a17d245555a2c8a2"),
|
||||
},
|
||||
{
|
||||
name: "CommerceCore",
|
||||
path: "./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Frameworks/CommerceCore.framework/Versions/A/CommerceCore",
|
||||
size: 207744,
|
||||
digest: mustDigest("c5401e57402230f3c876409d295319ddf1e61287bc882683c5d61277be7bc1f2"),
|
||||
},
|
||||
{
|
||||
name: "CoreFP",
|
||||
path: "./System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/CoreFP",
|
||||
size: 29014912,
|
||||
digest: mustDigest("f19141336be4198d0f8991bb00017c915efc7aeaece36c345f7faa1237ea6074"),
|
||||
},
|
||||
{
|
||||
name: "CoreFP.icxs",
|
||||
path: "./System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/CoreFP.icxs",
|
||||
size: 5288352,
|
||||
digest: mustDigest("473e78af86979f5bd4f6269561caf770b3d16c098d918846eeac8cdd2fe6566a"),
|
||||
},
|
||||
}
|
||||
|
||||
func Load(ctx context.Context) (Bundle, error) {
|
||||
directory, err := cacheDirectory()
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if bundle, err := readCache(directory); err == nil {
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
bundle, err := download(ctx)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if err := writeCache(directory, bundle); err != nil {
|
||||
return Bundle{}, fmt.Errorf("cache Apple SAP assets: %w", err)
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func download(ctx context.Context) (Bundle, error) {
|
||||
found, err := downloadFiles(ctx, requiredFiles, "download Apple SAP assets")
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
bundle := bundleFrom(found)
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func downloadFiles(ctx context.Context, specs []fileSpec, operation string) (map[string][]byte, error) {
|
||||
parsed, err := url.Parse(updateURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse Apple software update URL: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: 2 * time.Minute,
|
||||
Transport: contextTransport{ctx: ctx, next: http.DefaultTransport},
|
||||
}
|
||||
|
||||
remote, err := ranger.NewReader(&ranger.HTTPRanger{Client: client, URL: parsed})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open Apple software update: %w", err)
|
||||
}
|
||||
|
||||
length, err := remote.Length()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("measure Apple software update: %w", err)
|
||||
}
|
||||
|
||||
container, err := xar.NewReader(remote, length)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read Apple software update: %w", err)
|
||||
}
|
||||
|
||||
var payload *xar.File
|
||||
|
||||
for _, candidate := range container.Files {
|
||||
if candidate.Name == payloadName {
|
||||
payload = candidate
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if payload == nil {
|
||||
return nil, &fs.PathError{Op: "open", Path: payloadName, Err: fs.ErrNotExist}
|
||||
}
|
||||
|
||||
raw := payload.OpenRaw()
|
||||
if _, err := raw.Seek(payloadBZOffset, io.SeekStart); err != nil {
|
||||
return nil, fmt.Errorf("seek Apple update payload: %w", err)
|
||||
}
|
||||
|
||||
compressed := io.MultiReader(bytes.NewReader([]byte{'B', 'Z', 'h', '9'}), raw)
|
||||
|
||||
archive := bzip2.NewReader(compressed)
|
||||
if _, err := io.CopyN(io.Discard, archive, payloadCPIO); err != nil {
|
||||
return nil, fmt.Errorf("seek Apple payload archive: %w", err)
|
||||
}
|
||||
|
||||
wanted := make(map[string]fileSpec, len(specs))
|
||||
for _, spec := range specs {
|
||||
wanted[spec.path] = spec
|
||||
}
|
||||
|
||||
found := make(map[string][]byte, len(specs))
|
||||
reader := cpio.NewReader(archive)
|
||||
|
||||
for len(found) != len(wanted) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", operation, err)
|
||||
}
|
||||
|
||||
path, body, err := reader.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read Apple payload archive: %w", err)
|
||||
}
|
||||
|
||||
spec, ok := wanted[path]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(body, int64(spec.size)+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", spec.name, err)
|
||||
}
|
||||
|
||||
found[spec.name] = data
|
||||
}
|
||||
|
||||
return found, nil
|
||||
}
|
||||
|
||||
func cacheDirectory() (string, error) {
|
||||
root, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("find user cache directory: %w", err)
|
||||
}
|
||||
|
||||
return filepath.Join(root, "ipatool", "sap", "apple-assets-v2"), nil
|
||||
}
|
||||
|
||||
func readCache(directory string) (Bundle, error) {
|
||||
files := make(map[string][]byte, len(requiredFiles))
|
||||
|
||||
for _, spec := range requiredFiles {
|
||||
data, err := readCacheFile(filepath.Join(directory, spec.name), spec.size)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read cached Apple SAP asset %s: %w", spec.name, err)
|
||||
}
|
||||
|
||||
files[spec.name] = data
|
||||
}
|
||||
|
||||
bundle := bundleFrom(files)
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func readCacheFile(path string, expectedSize int) ([]byte, error) {
|
||||
if expectedSize < 0 {
|
||||
return nil, errors.New("invalid expected size")
|
||||
}
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open cached asset: %w", err)
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("inspect cached asset: %w", err)
|
||||
}
|
||||
|
||||
if info.Size() != int64(expectedSize) {
|
||||
return nil, fmt.Errorf("has size %d, expected %d", info.Size(), expectedSize)
|
||||
}
|
||||
|
||||
data := make([]byte, expectedSize)
|
||||
if _, err := io.ReadFull(file, data); err != nil {
|
||||
return nil, fmt.Errorf("read cached asset: %w", err)
|
||||
}
|
||||
|
||||
var extra [1]byte
|
||||
if count, err := io.ReadFull(file, extra[:]); err == nil || count != 0 {
|
||||
return nil, fmt.Errorf("grew beyond expected size %d while being read", expectedSize)
|
||||
} else if !errors.Is(err, io.EOF) {
|
||||
return nil, fmt.Errorf("verify cached asset length: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func writeCache(directory string, bundle Bundle) error {
|
||||
if err := validate(bundle); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
return fmt.Errorf("create SAP asset cache: %w", err)
|
||||
}
|
||||
|
||||
files := bundleFiles(bundle)
|
||||
for _, spec := range requiredFiles {
|
||||
if err := replaceFile(filepath.Join(directory, spec.name), files[spec.name]); err != nil {
|
||||
return fmt.Errorf("write cached SAP asset %s: %w", spec.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func replaceFile(path string, data []byte) error {
|
||||
temporary, err := os.CreateTemp(filepath.Dir(path), ".download-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temporary cache file: %w", err)
|
||||
}
|
||||
|
||||
temporaryPath := temporary.Name()
|
||||
defer os.Remove(temporaryPath)
|
||||
|
||||
if err := temporary.Chmod(0o600); err != nil {
|
||||
_ = temporary.Close()
|
||||
|
||||
return fmt.Errorf("set cache file permissions: %w", err)
|
||||
}
|
||||
|
||||
if _, err := temporary.Write(data); err != nil {
|
||||
_ = temporary.Close()
|
||||
|
||||
return fmt.Errorf("write temporary cache file: %w", err)
|
||||
}
|
||||
|
||||
if err := temporary.Close(); err != nil {
|
||||
return fmt.Errorf("close temporary cache file: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(temporaryPath, path); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("remove existing cache file: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(temporaryPath, path); err != nil {
|
||||
return fmt.Errorf("install cache file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validate(bundle Bundle) error {
|
||||
files := bundleFiles(bundle)
|
||||
for _, spec := range requiredFiles {
|
||||
data := files[spec.name]
|
||||
if len(data) != spec.size {
|
||||
return fmt.Errorf("apple SAP asset %s has size %d, expected %d", spec.name, len(data), spec.size)
|
||||
}
|
||||
|
||||
if sha256.Sum256(data) != spec.digest {
|
||||
return fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func bundleFrom(files map[string][]byte) Bundle {
|
||||
return Bundle{
|
||||
CommerceKit: files["CommerceKit"],
|
||||
CommerceCore: files["CommerceCore"],
|
||||
CoreFP: files["CoreFP"],
|
||||
CoreFPICXS: files["CoreFP.icxs"],
|
||||
}
|
||||
}
|
||||
|
||||
func bundleFiles(bundle Bundle) map[string][]byte {
|
||||
return map[string][]byte{
|
||||
"CommerceKit": bundle.CommerceKit,
|
||||
"CommerceCore": bundle.CommerceCore,
|
||||
"CoreFP": bundle.CoreFP,
|
||||
"CoreFP.icxs": bundle.CoreFPICXS,
|
||||
}
|
||||
}
|
||||
|
||||
func mustDigest(value string) [32]byte {
|
||||
var digest [32]byte
|
||||
|
||||
decoded, err := hex.DecodeString(value)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if len(decoded) != len(digest) {
|
||||
panic("invalid SHA-256 length")
|
||||
}
|
||||
|
||||
copy(digest[:], decoded)
|
||||
|
||||
return digest
|
||||
}
|
||||
|
||||
type contextTransport struct {
|
||||
ctx context.Context
|
||||
next http.RoundTripper
|
||||
}
|
||||
|
||||
func (t contextTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
response, err := t.next.RoundTrip(request.Clone(t.ctx))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetch Apple software update: %w", err)
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestAssetsGinkgo(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "SAP Assets Suite")
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadCacheFile(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
data []byte
|
||||
expectedSize int
|
||||
wantErr string
|
||||
}{
|
||||
{name: "exact size", data: []byte("12345678"), expectedSize: 8},
|
||||
{name: "too short", data: []byte("1234"), expectedSize: 8, wantErr: "has size 4, expected 8"},
|
||||
{name: "too large", data: bytes.Repeat([]byte{1}, 64), expectedSize: 8, wantErr: "has size 64, expected 8"},
|
||||
{name: "invalid expected size", expectedSize: -1, wantErr: "invalid expected size"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "asset")
|
||||
if err := os.WriteFile(path, test.data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := readCacheFile(path, test.expectedSize)
|
||||
if test.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("readCacheFile() error = %v", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(got, test.data) {
|
||||
t.Fatalf("readCacheFile() = %q, want %q", got, test.data)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||||
t.Fatalf("readCacheFile() error = %v, want error containing %q", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const storeAgentCacheDirectory = "apple-storeagent-v1"
|
||||
|
||||
var storeAgentSpec = fileSpec{
|
||||
name: "storeagent",
|
||||
path: "./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Resources/storeagent",
|
||||
size: 2580176,
|
||||
digest: mustDigest("70ce036f9dbcbc04db9511ebd08de0dd3cbc35ccc9d44b089c90170cb5453c59"),
|
||||
}
|
||||
|
||||
// LoadStoreAgent loads the pinned StoreAgent image from its separate cache or Apple payload.
|
||||
func LoadStoreAgent(ctx context.Context) ([]byte, error) {
|
||||
directory, err := storeAgentDirectory()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
path := filepath.Join(directory, storeAgentSpec.name)
|
||||
if data, err := readStoreAgent(path); err == nil {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
files, err := downloadFiles(ctx, []fileSpec{storeAgentSpec}, "download Apple StoreAgent asset")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data := files[storeAgentSpec.name]
|
||||
if err := VerifyStoreAgent(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
return nil, fmt.Errorf("create StoreAgent asset cache: %w", err)
|
||||
}
|
||||
|
||||
if err := replaceFile(path, data); err != nil {
|
||||
return nil, fmt.Errorf("cache Apple StoreAgent asset: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func storeAgentDirectory() (string, error) {
|
||||
root, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("find user cache directory: %w", err)
|
||||
}
|
||||
|
||||
return filepath.Join(root, "ipatool", "sap", storeAgentCacheDirectory), nil
|
||||
}
|
||||
|
||||
func readStoreAgent(path string) ([]byte, error) {
|
||||
data, err := readCacheFile(path, storeAgentSpec.size)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read cached Apple StoreAgent asset: %w", err)
|
||||
}
|
||||
|
||||
if err := VerifyStoreAgent(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// VerifyStoreAgent verifies the image profile required by the StoreAgent runtime.
|
||||
func VerifyStoreAgent(data []byte) error {
|
||||
if len(data) != storeAgentSpec.size {
|
||||
return fmt.Errorf("apple StoreAgent asset has size %d, expected %d", len(data), storeAgentSpec.size)
|
||||
}
|
||||
|
||||
if sha256.Sum256(data) != storeAgentSpec.digest {
|
||||
return fmt.Errorf("apple StoreAgent asset failed integrity verification")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("StoreAgent asset profile", func() {
|
||||
It("pins the verified Apple payload asset", func() {
|
||||
Expect(storeAgentSpec.name).To(Equal("storeagent"))
|
||||
Expect(storeAgentSpec.path).To(Equal("./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Resources/storeagent"))
|
||||
Expect(storeAgentSpec.size).To(Equal(2580176))
|
||||
Expect(storeAgentSpec.digest).To(Equal(mustDigest("70ce036f9dbcbc04db9511ebd08de0dd3cbc35ccc9d44b089c90170cb5453c59")))
|
||||
})
|
||||
|
||||
It("rejects an asset with the wrong size", func() {
|
||||
Expect(VerifyStoreAgent(nil)).To(MatchError(ContainSubstring("has size 0, expected 2580176")))
|
||||
})
|
||||
|
||||
It("rejects an asset with the wrong digest", func() {
|
||||
data := bytes.Repeat([]byte{0xa5}, storeAgentSpec.size)
|
||||
Expect(sha256.Sum256(data)).NotTo(Equal(storeAgentSpec.digest))
|
||||
Expect(VerifyStoreAgent(data)).To(MatchError("apple StoreAgent asset failed integrity verification"))
|
||||
})
|
||||
|
||||
It("uses a cache namespace separate from ordinary SAP assets", func() {
|
||||
Expect(storeAgentCacheDirectory).NotTo(Equal("apple-assets-v2"))
|
||||
})
|
||||
})
|
||||
@@ -1,86 +0,0 @@
|
||||
// Package cpio reads the old portable ASCII CPIO format used by Apple's
|
||||
// software-update payload. It streams entry bodies so unrelated files are not
|
||||
// retained while locating the small set needed by the SAP emulator.
|
||||
package cpio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
const (
|
||||
headerSize = 76
|
||||
nameSizeOffset = 59
|
||||
fileSizeOffset = 65
|
||||
)
|
||||
|
||||
var (
|
||||
headerMagic = []byte("070707")
|
||||
trailerName = []byte("TRAILER!!!")
|
||||
)
|
||||
|
||||
type Reader struct {
|
||||
source io.Reader
|
||||
current *io.LimitedReader
|
||||
}
|
||||
|
||||
func NewReader(source io.Reader) *Reader {
|
||||
return &Reader{source: source}
|
||||
}
|
||||
|
||||
func (r *Reader) Next() (string, io.Reader, error) {
|
||||
if r.current != nil {
|
||||
if _, err := io.Copy(io.Discard, r.current); err != nil {
|
||||
return "", nil, fmt.Errorf("skip CPIO entry: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
header := make([]byte, headerSize)
|
||||
if _, err := io.ReadFull(r.source, header); err != nil {
|
||||
return "", nil, fmt.Errorf("read CPIO header: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(header[:len(headerMagic)], headerMagic) {
|
||||
return "", nil, fmt.Errorf("invalid CPIO magic %q", header[:len(headerMagic)])
|
||||
}
|
||||
|
||||
nameSize, err := parseOctal(header[nameSizeOffset:fileSizeOffset])
|
||||
if err != nil || nameSize < 1 {
|
||||
return "", nil, fmt.Errorf("invalid CPIO name size %q", header[nameSizeOffset:fileSizeOffset])
|
||||
}
|
||||
|
||||
fileSize, err := parseOctal(header[fileSizeOffset:headerSize])
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("invalid CPIO file size %q", header[fileSizeOffset:headerSize])
|
||||
}
|
||||
|
||||
name := make([]byte, nameSize)
|
||||
if _, err := io.ReadFull(r.source, name); err != nil {
|
||||
return "", nil, fmt.Errorf("read CPIO name: %w", err)
|
||||
}
|
||||
|
||||
if name[len(name)-1] != 0 {
|
||||
return "", nil, errors.New("CPIO name is not NUL-terminated")
|
||||
}
|
||||
|
||||
name = name[:len(name)-1]
|
||||
if bytes.Equal(name, trailerName) {
|
||||
return "", nil, io.EOF
|
||||
}
|
||||
|
||||
r.current = &io.LimitedReader{R: r.source, N: int64(fileSize)}
|
||||
|
||||
return string(name), r.current, nil
|
||||
}
|
||||
|
||||
func parseOctal(value []byte) (uint64, error) {
|
||||
parsed, err := strconv.ParseUint(string(value), 8, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("parse CPIO octal value: %w", err)
|
||||
}
|
||||
|
||||
return parsed, nil
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package cpio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReaderStreamsEntries(t *testing.T) {
|
||||
archive := append(cpioEntry("first", []byte("ignored")), cpioEntry("second", []byte("wanted"))...)
|
||||
archive = append(archive, cpioEntry("TRAILER!!!", nil)...)
|
||||
reader := NewReader(bytes.NewReader(archive))
|
||||
|
||||
name, _, err := reader.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if name != "first" {
|
||||
t.Fatalf("name = %q, want first", name)
|
||||
}
|
||||
|
||||
name, body, err := reader.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if name != "second" || string(data) != "wanted" {
|
||||
t.Fatalf("entry = %q %q, want second wanted", name, data)
|
||||
}
|
||||
|
||||
if _, _, err := reader.Next(); err != io.EOF {
|
||||
t.Fatalf("trailer error = %v, want EOF", err)
|
||||
}
|
||||
}
|
||||
|
||||
func cpioEntry(name string, body []byte) []byte {
|
||||
nameBytes := append([]byte(name), 0)
|
||||
header := fmt.Sprintf(
|
||||
"070707%06o%06o%06o%06o%06o%06o%06o%011o%06o%011o",
|
||||
0, 0, 0, 0, 0, 1, 0, 0, len(nameBytes), len(body),
|
||||
)
|
||||
entry := append([]byte(header), nameBytes...)
|
||||
|
||||
return append(entry, body...)
|
||||
}
|
||||
@@ -1,339 +0,0 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
const (
|
||||
pageSize = uint64(0x1000)
|
||||
maxImageSpan = uint64(1 << 30)
|
||||
pointerSize = uint64(8)
|
||||
)
|
||||
|
||||
type Memory interface {
|
||||
MemMap(address, size uint64) error
|
||||
MemWrite(address uint64, data []byte) error
|
||||
}
|
||||
|
||||
type segment struct {
|
||||
name string
|
||||
address uint64
|
||||
size uint64
|
||||
fileOff uint64
|
||||
fileSize uint64
|
||||
}
|
||||
|
||||
type Image struct {
|
||||
name string
|
||||
data []byte
|
||||
file *macho.File
|
||||
base uint64
|
||||
segments []segment
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
relocated bool
|
||||
loadedBase uint64
|
||||
}
|
||||
|
||||
func Open(name string, input []byte) (*Image, error) {
|
||||
data, err := amd64Slice(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s: %w", name, err)
|
||||
}
|
||||
|
||||
file, err := macho.NewFile(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s Mach-O: %w", name, err)
|
||||
}
|
||||
|
||||
if file.CPU != types.CPUAmd64 {
|
||||
return nil, fmt.Errorf("open %s: expected x86-64 Mach-O, found %s", name, file.CPU)
|
||||
}
|
||||
|
||||
image := &Image{
|
||||
name: name,
|
||||
data: data,
|
||||
file: file,
|
||||
base: file.GetBaseAddress(),
|
||||
}
|
||||
for _, item := range file.Segments() {
|
||||
image.segments = append(image.segments, segment{
|
||||
name: item.Name,
|
||||
address: item.Addr,
|
||||
size: item.Memsz,
|
||||
fileOff: item.Offset,
|
||||
fileSize: item.Filesz,
|
||||
})
|
||||
}
|
||||
|
||||
if err := image.validateSegments(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
image.binds, err = file.GetBindInfo()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s bindings: %w", name, err)
|
||||
}
|
||||
|
||||
image.rebases, err = file.GetRebaseInfo()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s rebases: %w", name, err)
|
||||
}
|
||||
|
||||
return image, nil
|
||||
}
|
||||
|
||||
func amd64Slice(input []byte) ([]byte, error) {
|
||||
fat, err := macho.NewFatFile(bytes.NewReader(input))
|
||||
if err != nil {
|
||||
return bytes.Clone(input), nil
|
||||
}
|
||||
|
||||
for _, architecture := range fat.Arches {
|
||||
if architecture.CPU != types.CPUAmd64 {
|
||||
continue
|
||||
}
|
||||
|
||||
end, overflow := add(uint64(architecture.Offset), uint64(architecture.Size))
|
||||
if overflow || end > uint64(len(input)) {
|
||||
return nil, errors.New("x86-64 slice exceeds input size")
|
||||
}
|
||||
|
||||
return bytes.Clone(input[architecture.Offset:end]), nil
|
||||
}
|
||||
|
||||
return nil, errors.New("universal binary has no x86-64 slice")
|
||||
}
|
||||
|
||||
func (i *Image) Export(name string, loadBase uint64) (uint64, error) {
|
||||
address, err := i.file.FindSymbolAddress(name)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("find %s in %s: %w", name, i.name, err)
|
||||
}
|
||||
|
||||
if address < i.base {
|
||||
return 0, fmt.Errorf("symbol %s in %s precedes image base", name, i.name)
|
||||
}
|
||||
|
||||
result, overflow := add(loadBase, address-i.base)
|
||||
if overflow {
|
||||
return 0, fmt.Errorf("symbol %s address overflows in %s", name, i.name)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (i *Image) Relocate(loadBase uint64, resolve func(string) (uint64, error)) error {
|
||||
if i.relocated {
|
||||
return fmt.Errorf("%s is already relocated", i.name)
|
||||
}
|
||||
|
||||
for _, relocation := range i.rebases {
|
||||
if relocation.Type != types.REBASE_TYPE_POINTER {
|
||||
return fmt.Errorf("%s uses unsupported rebase type %d", i.name, relocation.Type)
|
||||
}
|
||||
|
||||
if relocation.Value < i.base {
|
||||
return fmt.Errorf("%s contains a rebase below its image base", i.name)
|
||||
}
|
||||
|
||||
offset, err := i.segmentFileOffset(relocation.Segment, relocation.Offset, pointerSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
address, overflow := add(loadBase, relocation.Value-i.base)
|
||||
if overflow {
|
||||
return fmt.Errorf("rebase address overflows in %s", i.name)
|
||||
}
|
||||
|
||||
if err := i.putPointer(offset, address); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, binding := range i.binds {
|
||||
// Lazy bind streams may omit SET_TYPE; dyld's default is a pointer bind.
|
||||
if binding.Type != 0 && binding.Type != types.BIND_TYPE_POINTER {
|
||||
return fmt.Errorf("%s uses unsupported bind type %d for %s", i.name, binding.Type, binding.Name)
|
||||
}
|
||||
|
||||
offset, err := i.segmentFileOffset(binding.Segment, binding.SegOffset, pointerSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
address, err := resolve(binding.Name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve %s for %s: %w", binding.Name, i.name, err)
|
||||
}
|
||||
|
||||
address, err = addSigned(address, binding.Addend)
|
||||
if err != nil {
|
||||
return fmt.Errorf("apply addend for %s in %s: %w", binding.Name, i.name, err)
|
||||
}
|
||||
|
||||
if err := i.putPointer(offset, address); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
i.relocated = true
|
||||
i.loadedBase = loadBase
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Image) Load(memory Memory) error {
|
||||
if !i.relocated {
|
||||
return fmt.Errorf("%s must be relocated before loading", i.name)
|
||||
}
|
||||
|
||||
var span uint64
|
||||
|
||||
for _, item := range i.segments {
|
||||
if item.name == "__PAGEZERO" || item.size == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if item.address < i.base {
|
||||
return fmt.Errorf("segment %s in %s precedes image base", item.name, i.name)
|
||||
}
|
||||
|
||||
end, overflow := add(item.address-i.base, item.size)
|
||||
if overflow || end > maxImageSpan {
|
||||
return fmt.Errorf("segment %s makes %s too large", item.name, i.name)
|
||||
}
|
||||
|
||||
span = max(span, end)
|
||||
}
|
||||
|
||||
span = align(span, pageSize)
|
||||
if span == 0 {
|
||||
return fmt.Errorf("%s has no loadable segments", i.name)
|
||||
}
|
||||
|
||||
if _, overflow := add(i.loadedBase, span); overflow {
|
||||
return fmt.Errorf("load range for %s overflows", i.name)
|
||||
}
|
||||
|
||||
if err := memory.MemMap(i.loadedBase, span); err != nil {
|
||||
return fmt.Errorf("map %s: %w", i.name, err)
|
||||
}
|
||||
|
||||
for _, item := range i.segments {
|
||||
if item.name == "__PAGEZERO" || item.fileSize == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
end, overflow := add(item.fileOff, item.fileSize)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("segment %s data exceeds %s", item.name, i.name)
|
||||
}
|
||||
|
||||
address, overflow := add(i.loadedBase, item.address-i.base)
|
||||
if overflow {
|
||||
return fmt.Errorf("segment %s address overflows in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
if err := memory.MemWrite(address, i.data[item.fileOff:end]); err != nil {
|
||||
return fmt.Errorf("write segment %s from %s: %w", item.name, i.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Image) validateSegments() error {
|
||||
for _, item := range i.segments {
|
||||
if item.fileSize > item.size {
|
||||
return fmt.Errorf("segment %s file data exceeds its memory size in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
if _, overflow := add(item.address, item.size); overflow {
|
||||
return fmt.Errorf("segment %s address range overflows in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
end, overflow := add(item.fileOff, item.fileSize)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("segment %s data exceeds %s", item.name, i.name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Image) segmentFileOffset(name string, offset, size uint64) (uint64, error) {
|
||||
for _, item := range i.segments {
|
||||
if item.name != name {
|
||||
continue
|
||||
}
|
||||
|
||||
segmentEnd, overflow := add(offset, size)
|
||||
if overflow || segmentEnd > item.size {
|
||||
return 0, fmt.Errorf("fixup at %#x exceeds segment %s in %s", offset, name, i.name)
|
||||
}
|
||||
|
||||
if segmentEnd > item.fileSize {
|
||||
return 0, fmt.Errorf("fixup at %#x exceeds file data for segment %s in %s", offset, name, i.name)
|
||||
}
|
||||
|
||||
result, overflow := add(item.fileOff, offset)
|
||||
if overflow {
|
||||
return 0, fmt.Errorf("fixup offset overflows in %s", i.name)
|
||||
}
|
||||
|
||||
end, overflow := add(result, size)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return 0, fmt.Errorf("fixup at %#x exceeds %s", result, i.name)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("fixup references unknown segment %s in %s", name, i.name)
|
||||
}
|
||||
|
||||
func (i *Image) putPointer(offset, value uint64) error {
|
||||
end, overflow := add(offset, 8)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("fixup at %#x exceeds %s", offset, i.name)
|
||||
}
|
||||
|
||||
binary.LittleEndian.PutUint64(i.data[offset:end], value)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func addSigned(value uint64, delta int64) (uint64, error) {
|
||||
if delta >= 0 {
|
||||
result, overflow := add(value, uint64(delta))
|
||||
if overflow {
|
||||
return 0, errors.New("address overflow")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
magnitude := uint64(-(delta + 1)) + 1
|
||||
if magnitude > value {
|
||||
return 0, errors.New("address underflow")
|
||||
}
|
||||
|
||||
return value - magnitude, nil
|
||||
}
|
||||
|
||||
func add(left, right uint64) (uint64, bool) {
|
||||
return left + right, right > math.MaxUint64-left
|
||||
}
|
||||
|
||||
func align(value, alignment uint64) uint64 {
|
||||
return (value + alignment - 1) &^ (alignment - 1)
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
func TestValidateSegments(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dataLen int
|
||||
segment segment
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "valid",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: 8, fileSize: 16},
|
||||
},
|
||||
{
|
||||
name: "file data exceeds memory",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 8, fileOff: 8, fileSize: 16},
|
||||
wantErr: "file data exceeds its memory size",
|
||||
},
|
||||
{
|
||||
name: "file data exceeds image",
|
||||
dataLen: 16,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: 8, fileSize: 16},
|
||||
wantErr: "data exceeds",
|
||||
},
|
||||
{
|
||||
name: "file range overflows",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: math.MaxUint64 - 7, fileSize: 16},
|
||||
wantErr: "data exceeds",
|
||||
},
|
||||
{
|
||||
name: "address range overflows",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: math.MaxUint64 - 7, size: 16},
|
||||
wantErr: "address range overflows",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
image := Image{name: "test", data: make([]byte, test.dataLen), segments: []segment{test.segment}}
|
||||
|
||||
err := image.validateSegments()
|
||||
if test.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("validateSegments() error = %v", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||||
t.Fatalf("validateSegments() error = %v, want error containing %q", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSegmentFileOffsetBounds(t *testing.T) {
|
||||
image := Image{
|
||||
name: "test",
|
||||
data: make([]byte, 64),
|
||||
segments: []segment{
|
||||
{name: "__DATA", address: 0x1000, size: 24, fileOff: 16, fileSize: 16},
|
||||
{name: "__SHORT", address: 0x2000, size: 16, fileOff: 56, fileSize: 16},
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
segment string
|
||||
offset uint64
|
||||
want uint64
|
||||
wantErr string
|
||||
}{
|
||||
{name: "valid at end", segment: "__DATA", offset: 8, want: 24},
|
||||
{name: "past file data", segment: "__DATA", offset: 9, wantErr: "exceeds file data"},
|
||||
{name: "past memory", segment: "__DATA", offset: 17, wantErr: "exceeds segment"},
|
||||
{name: "past image", segment: "__SHORT", offset: 8, wantErr: "exceeds test"},
|
||||
{name: "offset overflow", segment: "__DATA", offset: math.MaxUint64 - 3, wantErr: "exceeds segment"},
|
||||
{name: "unknown segment", segment: "__MISSING", wantErr: "unknown segment"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := image.segmentFileOffset(test.segment, test.offset, pointerSize)
|
||||
if test.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("segmentFileOffset() error = %v", err)
|
||||
}
|
||||
|
||||
if got != test.want {
|
||||
t.Fatalf("segmentFileOffset() = %#x, want %#x", got, test.want)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||||
t.Fatalf("segmentFileOffset() error = %v, want error containing %q", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelocateRejectsFixupsOutsideTheirSegments(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
}{
|
||||
{
|
||||
name: "bind",
|
||||
binds: []types.Bind{{Name: "symbol", Segment: "__DATA", SegOffset: 9}},
|
||||
},
|
||||
{
|
||||
name: "rebase",
|
||||
rebases: []types.Rebase{{Type: types.REBASE_TYPE_POINTER, Segment: "__DATA", Offset: 9, Value: 0x1000}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
image := Image{
|
||||
name: "test",
|
||||
data: make([]byte, 64),
|
||||
base: 0x1000,
|
||||
segments: []segment{{name: "__DATA", address: 0x1000, size: 32, fileOff: 16, fileSize: 16}},
|
||||
binds: test.binds,
|
||||
rebases: test.rebases,
|
||||
}
|
||||
|
||||
err := image.Relocate(0x2000, func(string) (uint64, error) { return 0x3000, nil })
|
||||
if err == nil || !strings.Contains(err.Error(), "exceeds file data") {
|
||||
t.Fatalf("Relocate() error = %v, want file-data bounds error", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
)
|
||||
|
||||
// GenerateKBSync creates the account and hardware bound FairPlay data required
|
||||
// by the bag's ent/download endpoint, without opening a decryption session.
|
||||
func GenerateKBSync(ctx context.Context, bundle assets.Bundle, hardwareID []byte, dsid uint64) ([]byte, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("StoreAgent context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("generate kbsync: %w", err)
|
||||
}
|
||||
|
||||
if dsid == 0 {
|
||||
return nil, errors.New("kbsync requires a nonzero account DSID")
|
||||
}
|
||||
|
||||
image, err := assets.LoadStoreAgent(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load Apple StoreAgent asset: %w", err)
|
||||
}
|
||||
|
||||
agent, globalContext, err := openStoreAgentGlobal(ctx, bundle, image, hardwareID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer agent.Close()
|
||||
|
||||
return agent.guest.generateKBSync(storeAgentKBSyncEntry, globalContext, dsid)
|
||||
}
|
||||
|
||||
func (m *Machine) generateKBSync(entry uint64, globalContext uint32, dsid uint64) ([]byte, error) {
|
||||
m.beginCall()
|
||||
defer m.clearScratch()
|
||||
|
||||
pointerField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// StoreAgent writes a uint32 length. Zero the upper half so consumeOutput
|
||||
// can share the SAP buffer bounds checking and storage disposal.
|
||||
lengthField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
status, err := m.invoke(entry, uint64(globalContext), dsid, 0, 1, pointerField, lengthField)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate StoreAgent kbsync: %w", err)
|
||||
}
|
||||
|
||||
output, outputErr := m.consumeOutput(pointerField, lengthField)
|
||||
if int32(status) != 0 {
|
||||
return nil, errors.Join(fmt.Errorf("StoreAgent kbsync returned %d", int32(status)), outputErr)
|
||||
}
|
||||
|
||||
if outputErr != nil {
|
||||
return nil, outputErr
|
||||
}
|
||||
|
||||
if len(output) == 0 {
|
||||
return nil, errors.New("StoreAgent kbsync returned an empty buffer")
|
||||
}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("StoreAgent kbsync", func() {
|
||||
It("pins the kbsync entry in the verified StoreAgent image", func() {
|
||||
Expect(storeAgentKBSyncEntry).To(Equal(storeAgentBase + 0x0c93c0))
|
||||
})
|
||||
|
||||
It("rejects a canceled context before loading assets", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := GenerateKBSync(ctx, assets.Bundle{}, []byte{1}, 123)
|
||||
Expect(err).To(MatchError(ContainSubstring(context.Canceled.Error())))
|
||||
})
|
||||
|
||||
It("rejects missing context or account identity before loading assets", func() {
|
||||
var missingContext context.Context
|
||||
_, err := GenerateKBSync(missingContext, assets.Bundle{}, nil, 123)
|
||||
Expect(err).To(MatchError("StoreAgent context is nil"))
|
||||
_, err = GenerateKBSync(context.Background(), assets.Bundle{}, nil, 0)
|
||||
Expect(err).To(MatchError("kbsync requires a nonzero account DSID"))
|
||||
})
|
||||
|
||||
DescribeTable("copies and disposes guest output with the StoreAgent ABI",
|
||||
func(pointer, length uint64, status uint32, wantError string) {
|
||||
guest := newGinkgoServiceMachine(shimOptions{})
|
||||
data := []byte{0, 4, 0, 1, 42}
|
||||
Expect(guest.engine.MemWrite(heapBase, data)).To(Succeed())
|
||||
var disposed []uint64
|
||||
|
||||
dispose, err := guest.services.addFunction("test.kbsync.dispose", func() error {
|
||||
address, err := guest.services.argument(0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
disposed = append(disposed, address)
|
||||
|
||||
return guest.services.setResult(0)
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
guest.entry.dispose = dispose
|
||||
|
||||
entry, err := guest.services.addFunction("test.kbsync.generate", func() error {
|
||||
for index, expected := range []uint64{0x1234, 0x123456789abcdef0, 0, 1} {
|
||||
argument, err := guest.services.argument(index)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(argument).To(Equal(expected))
|
||||
}
|
||||
|
||||
pointerField, err := guest.services.argument(4)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(guest.writeUint64(pointerField, pointer)).To(Succeed())
|
||||
lengthField, err := guest.services.argument(5)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
// Only the low 32 bits are written by the real entry point.
|
||||
Expect(guest.engine.MemWrite(lengthField, binary.LittleEndian.AppendUint32(nil, uint32(length)))).To(Succeed())
|
||||
|
||||
return guest.services.setResult(uint64(status))
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
output, err := guest.generateKBSync(entry, 0x1234, 0x123456789abcdef0)
|
||||
if wantError == "" {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(output).To(Equal(data))
|
||||
} else {
|
||||
Expect(err).To(MatchError(ContainSubstring(wantError)))
|
||||
Expect(output).To(BeNil())
|
||||
}
|
||||
|
||||
if pointer != 0 {
|
||||
Expect(disposed).To(Equal([]uint64{pointer}))
|
||||
} else {
|
||||
Expect(disposed).To(BeEmpty())
|
||||
}
|
||||
Expect(guest.scratchCursor).To(BeZero())
|
||||
Expect(guest.engine.MemRead(scratchBase, 32)).To(Equal(make([]byte, 32)))
|
||||
},
|
||||
Entry("valid blob", heapBase, uint64(5), uint32(0), ""),
|
||||
Entry("guest error still releases storage", heapBase, uint64(5), ^uint32(41), "kbsync returned -42"),
|
||||
Entry("oversized blob", heapBase, maxOutputSize+1, uint32(0), "maximum is"),
|
||||
Entry("null pointer", uint64(0), uint64(5), uint32(0), "null output pointer"),
|
||||
Entry("empty blob", heapBase, uint64(0), uint32(0), "empty buffer"),
|
||||
)
|
||||
})
|
||||
@@ -1,623 +0,0 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/sap/machimage"
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
)
|
||||
|
||||
const sapGuestTimeout = time.Minute
|
||||
|
||||
const (
|
||||
returnAddress = uint64(0x0000000100000000)
|
||||
coreFPBase = uint64(0x0000100000000000)
|
||||
commerceBase = uint64(0x0000100040000000)
|
||||
kitBase = uint64(0x0000100080000000)
|
||||
scratchBase = uint64(0x0000300000000000)
|
||||
scratchSize = uint64(32 << 20)
|
||||
heapBase = uint64(0x0000400000000000)
|
||||
heapSize = uint64(64 << 20)
|
||||
stackBase = uint64(0x0000500000000000)
|
||||
stackSize = uint64(8 << 20)
|
||||
stackEnd = stackBase + stackSize
|
||||
pageSize = uint64(0x1000)
|
||||
maxOutputSize = uint64(16 << 20)
|
||||
)
|
||||
|
||||
var coreExportNames = []string{
|
||||
"_WIn9UJ86JKdV4dM",
|
||||
"_X46O5IeS",
|
||||
"_YlCJ3lg",
|
||||
"_dku592fbFAj",
|
||||
"_fdjkDSAFjklaf2s",
|
||||
"_lxpgvVMLd0S7uRl",
|
||||
}
|
||||
|
||||
type entryPoints struct {
|
||||
initialize uint64
|
||||
exchange uint64
|
||||
sign uint64
|
||||
teardown uint64
|
||||
dispose uint64
|
||||
}
|
||||
|
||||
type Machine struct {
|
||||
engine *unicorn.Engine
|
||||
services *shims
|
||||
entry entryPoints
|
||||
scratchCursor uint64
|
||||
closed bool
|
||||
}
|
||||
|
||||
type imageSpec struct {
|
||||
name string
|
||||
data []byte
|
||||
base uint64
|
||||
}
|
||||
|
||||
type runtimeOptions struct {
|
||||
extraImages []imageSpec
|
||||
shims shimOptions
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, bundle assets.Bundle) (*Machine, error) {
|
||||
machine, exports, err := openRuntime(ctx, bundle, runtimeOptions{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
machine.entry = entryPoints{
|
||||
initialize: exports["_cp2g1b9ro"],
|
||||
exchange: exports["_Mib5yocT"],
|
||||
sign: exports["_Fc3vhtJDvr"],
|
||||
teardown: exports["_IPaI1oem5iL"],
|
||||
dispose: exports["_jEHf8Xzsv8K"],
|
||||
}
|
||||
|
||||
return machine, nil
|
||||
}
|
||||
|
||||
func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptions) (*Machine, map[string]uint64, error) {
|
||||
if ctx == nil {
|
||||
return nil, nil, errors.New("SAP runtime context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
}
|
||||
|
||||
imageSpecs := make([]imageSpec, 0, 3+len(options.extraImages))
|
||||
imageSpecs = append(imageSpecs,
|
||||
imageSpec{name: "CoreFP", data: bundle.CoreFP, base: coreFPBase},
|
||||
imageSpec{name: "CommerceCore", data: bundle.CommerceCore, base: commerceBase},
|
||||
imageSpec{name: "CommerceKit", data: bundle.CommerceKit, base: kitBase},
|
||||
)
|
||||
imageSpecs = append(imageSpecs, options.extraImages...)
|
||||
|
||||
images := make(map[string]*machimage.Image, len(imageSpecs))
|
||||
|
||||
for _, spec := range imageSpecs {
|
||||
image, err := machimage.Open(spec.name, spec.data)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("open %s image: %w", spec.name, err)
|
||||
}
|
||||
|
||||
images[spec.name] = image
|
||||
}
|
||||
|
||||
exports := make(map[string]uint64)
|
||||
coreExports := make(map[string]uint64, len(coreExportNames))
|
||||
coreFP := images["CoreFP"]
|
||||
|
||||
for _, name := range coreExportNames {
|
||||
address, err := coreFP.Export(name, coreFPBase)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("resolve CoreFP export %s: %w", name, err)
|
||||
}
|
||||
|
||||
exports[name] = address
|
||||
coreExports[name] = address
|
||||
}
|
||||
|
||||
commerceCore := images["CommerceCore"]
|
||||
macAddress, err := commerceCore.Export("_get_mac_address", commerceBase)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("resolve CommerceCore MAC address export: %w", err)
|
||||
}
|
||||
|
||||
exports["_get_mac_address"] = macAddress
|
||||
|
||||
commerceKit := images["CommerceKit"]
|
||||
for _, name := range []string{
|
||||
"_cp2g1b9ro",
|
||||
"_Mib5yocT",
|
||||
"_Fc3vhtJDvr",
|
||||
"_IPaI1oem5iL",
|
||||
"_jEHf8Xzsv8K",
|
||||
} {
|
||||
address, err := commerceKit.Export(name, kitBase)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("resolve CommerceKit export %s: %w", name, err)
|
||||
}
|
||||
|
||||
exports[name] = address
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
}
|
||||
|
||||
engine, err := unicorn.New(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create Unicorn engine: %w", err)
|
||||
}
|
||||
|
||||
machine := &Machine{engine: engine}
|
||||
ready := false
|
||||
|
||||
defer func() {
|
||||
if !ready {
|
||||
_ = machine.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
for _, region := range []struct {
|
||||
address uint64
|
||||
size uint64
|
||||
}{
|
||||
{returnAddress, pageSize},
|
||||
{scratchBase, scratchSize},
|
||||
{heapBase, heapSize},
|
||||
{stackBase, stackSize},
|
||||
} {
|
||||
if err := engine.MemMap(region.address, region.size); err != nil {
|
||||
return nil, nil, fmt.Errorf("map SAP guest memory at %#x: %w", region.address, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := engine.MemWrite(returnAddress, []byte{0xF4}); err != nil {
|
||||
return nil, nil, fmt.Errorf("write SAP guest return instruction: %w", err)
|
||||
}
|
||||
|
||||
machine.services, err = newShimsWithOptions(engine, coreExports, bundle.CoreFPICXS, options.shims)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
resolver := func(name string) (uint64, error) {
|
||||
if address, ok := exports[name]; ok {
|
||||
return address, nil
|
||||
}
|
||||
|
||||
return machine.services.resolve(name)
|
||||
}
|
||||
|
||||
for _, spec := range imageSpecs {
|
||||
image := images[spec.name]
|
||||
if err := image.Relocate(spec.base, resolver); err != nil {
|
||||
return nil, nil, fmt.Errorf("relocate SAP guest image: %w", err)
|
||||
}
|
||||
|
||||
if err := image.Load(engine); err != nil {
|
||||
return nil, nil, fmt.Errorf("load SAP guest image: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
ready = true
|
||||
|
||||
return machine, exports, nil
|
||||
}
|
||||
|
||||
func (m *Machine) Initialize(hardwareID []byte) (uint64, error) {
|
||||
hardware, err := hardwareBlock(hardwareID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
m.beginCall()
|
||||
|
||||
defer m.clearScratch()
|
||||
|
||||
contextField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
hardwareAddress, err := m.scratch(hardware, uint64(len(hardware)))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
status, err := m.invoke(m.entry.initialize, contextField, hardwareAddress)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return 0, fmt.Errorf("SAP initialization returned %d", int32(status))
|
||||
}
|
||||
|
||||
contextValue, err := m.readUint64(contextField)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if contextValue == 0 {
|
||||
return 0, errors.New("SAP initialization returned a null context")
|
||||
}
|
||||
|
||||
return contextValue, nil
|
||||
}
|
||||
|
||||
func (m *Machine) Exchange(version uint32, hardwareID []byte, contextValue uint64, input []byte) ([]byte, int32, error) {
|
||||
if uint64(len(input)) > math.MaxUint32 {
|
||||
return nil, 0, errors.New("SAP exchange input is too large")
|
||||
}
|
||||
|
||||
hardware, err := hardwareBlock(hardwareID)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
m.beginCall()
|
||||
|
||||
defer m.clearScratch()
|
||||
|
||||
hardwareAddress, err := m.scratch(hardware, uint64(len(hardware)))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
inputAddress, err := m.scratch(input, uint64(len(input)))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
outputField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
lengthField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
resultField, err := m.scratch(nil, 4)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
status, err := m.invoke(
|
||||
m.entry.exchange,
|
||||
uint64(version),
|
||||
hardwareAddress,
|
||||
contextValue,
|
||||
inputAddress,
|
||||
uint64(len(input)),
|
||||
outputField,
|
||||
lengthField,
|
||||
resultField,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return nil, 0, fmt.Errorf("SAP exchange returned %d", int32(status))
|
||||
}
|
||||
|
||||
output, err := m.consumeOutput(outputField, lengthField)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
result, err := m.readUint32(resultField)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return output, int32(result), nil
|
||||
}
|
||||
|
||||
func (m *Machine) Sign(contextValue uint64, input []byte) ([]byte, error) {
|
||||
if uint64(len(input)) > math.MaxUint32 {
|
||||
return nil, errors.New("SAP signing input is too large")
|
||||
}
|
||||
|
||||
m.beginCall()
|
||||
|
||||
defer m.clearScratch()
|
||||
|
||||
inputAddress, err := m.scratch(input, uint64(len(input)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lengthField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
status, err := m.invoke(
|
||||
m.entry.sign,
|
||||
contextValue,
|
||||
inputAddress,
|
||||
uint64(len(input)),
|
||||
outputField,
|
||||
lengthField,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return nil, fmt.Errorf("SAP signing returned %d", int32(status))
|
||||
}
|
||||
|
||||
output, err := m.consumeOutput(outputField, lengthField)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func (m *Machine) Teardown(contextValue uint64) error {
|
||||
status, err := m.invoke(m.entry.teardown, contextValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return fmt.Errorf("SAP teardown returned %d", int32(status))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Machine) dispose(output uint64) error {
|
||||
status, err := m.invoke(m.entry.dispose, output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return fmt.Errorf("SAP storage disposal returned %d", int32(status))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Machine) invoke(function uint64, arguments ...uint64) (uint64, error) {
|
||||
if m.closed {
|
||||
return 0, errors.New("SAP guest machine is closed")
|
||||
}
|
||||
|
||||
if function == 0 {
|
||||
return 0, errors.New("SAP guest entry point is unavailable")
|
||||
}
|
||||
|
||||
registers := [...]int{
|
||||
unicorn.RegRDI,
|
||||
unicorn.RegRSI,
|
||||
unicorn.RegRDX,
|
||||
unicorn.RegRCX,
|
||||
unicorn.RegR8,
|
||||
unicorn.RegR9,
|
||||
}
|
||||
for index, register := range registers {
|
||||
var value uint64
|
||||
if index < len(arguments) {
|
||||
value = arguments[index]
|
||||
}
|
||||
|
||||
if err := m.engine.RegWrite(register, value); err != nil {
|
||||
return 0, fmt.Errorf("write SAP guest argument register: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
extra := max(len(arguments)-len(registers), 0)
|
||||
|
||||
stackPointer := stackEnd - uint64(extra+1)*8
|
||||
if stackPointer%16 != 8 {
|
||||
stackPointer -= 8
|
||||
}
|
||||
|
||||
if err := m.writeUint64(stackPointer, returnAddress); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for index := range extra {
|
||||
if err := m.writeUint64(stackPointer+8+uint64(index)*8, arguments[len(registers)+index]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := m.engine.RegWrite(unicorn.RegRSP, stackPointer); err != nil {
|
||||
return 0, fmt.Errorf("write SAP guest stack register: %w", err)
|
||||
}
|
||||
|
||||
m.services.resetFault()
|
||||
|
||||
// SAP's cryptographic routines have input- and host-dependent instruction
|
||||
// counts. Bound execution by wall time without rejecting legitimate work on
|
||||
// slower machines for crossing a fixed instruction limit.
|
||||
if err := m.engine.StartBounded(function, returnAddress, sapGuestTimeout, 0); err != nil {
|
||||
if m.services.fault != nil {
|
||||
return 0, m.services.fault
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("execute SAP guest function: %w", err)
|
||||
}
|
||||
|
||||
if m.services.fault != nil {
|
||||
return 0, m.services.fault
|
||||
}
|
||||
|
||||
instruction, err := m.engine.RegRead(unicorn.RegRIP)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read SAP guest instruction register: %w", err)
|
||||
}
|
||||
|
||||
if instruction != returnAddress {
|
||||
return 0, fmt.Errorf("SAP guest stopped unexpectedly at %#x", instruction)
|
||||
}
|
||||
|
||||
result, err := m.engine.RegRead(unicorn.RegRAX)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read SAP guest result register: %w", err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *Machine) beginCall() {
|
||||
m.scratchCursor = 0
|
||||
}
|
||||
|
||||
func (m *Machine) scratch(data []byte, size uint64) (uint64, error) {
|
||||
reserved := align(max(size, 1), 16)
|
||||
if m.scratchCursor > scratchSize || reserved > scratchSize-m.scratchCursor {
|
||||
return 0, errors.New("SAP guest scratch space exhausted")
|
||||
}
|
||||
|
||||
address := scratchBase + m.scratchCursor
|
||||
m.scratchCursor += reserved
|
||||
|
||||
if len(data) != 0 {
|
||||
if uint64(len(data)) > size {
|
||||
return 0, errors.New("scratch data exceeds reservation")
|
||||
}
|
||||
|
||||
if err := m.engine.MemWrite(address, data); err != nil {
|
||||
return 0, fmt.Errorf("write SAP guest scratch data: %w", err)
|
||||
}
|
||||
} else if size != 0 {
|
||||
if err := m.engine.MemWrite(address, make([]byte, size)); err != nil {
|
||||
return 0, fmt.Errorf("clear SAP guest scratch data: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func (m *Machine) clearScratch() {
|
||||
if m.scratchCursor != 0 && m.engine != nil && !m.closed {
|
||||
_ = m.engine.MemWrite(scratchBase, make([]byte, m.scratchCursor))
|
||||
}
|
||||
|
||||
m.scratchCursor = 0
|
||||
}
|
||||
|
||||
func (m *Machine) consumeOutput(pointerField, lengthField uint64) ([]byte, error) {
|
||||
pointer, err := m.readUint64(pointerField)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
length, err := m.readUint64(lengthField)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var output []byte
|
||||
|
||||
var outputErr error
|
||||
|
||||
switch {
|
||||
case length > maxOutputSize:
|
||||
outputErr = fmt.Errorf("SAP output is %d bytes, maximum is %d", length, maxOutputSize)
|
||||
case length == 0:
|
||||
case pointer == 0:
|
||||
outputErr = errors.New("SAP returned a null output pointer")
|
||||
default:
|
||||
output, outputErr = m.engine.MemRead(pointer, length)
|
||||
}
|
||||
|
||||
var disposeErr error
|
||||
if pointer != 0 {
|
||||
disposeErr = m.dispose(pointer)
|
||||
}
|
||||
|
||||
return output, errors.Join(outputErr, disposeErr)
|
||||
}
|
||||
|
||||
func (m *Machine) readUint32(address uint64) (uint32, error) {
|
||||
data, err := m.engine.MemRead(address, 4)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read SAP guest uint32: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint32(data), nil
|
||||
}
|
||||
|
||||
func (m *Machine) readUint64(address uint64) (uint64, error) {
|
||||
data, err := m.engine.MemRead(address, 8)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read SAP guest uint64: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint64(data), nil
|
||||
}
|
||||
|
||||
func (m *Machine) writeUint64(address, value uint64) error {
|
||||
var data [8]byte
|
||||
|
||||
binary.LittleEndian.PutUint64(data[:], value)
|
||||
|
||||
if err := m.engine.MemWrite(address, data[:]); err != nil {
|
||||
return fmt.Errorf("write SAP guest uint64: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Machine) Close() error {
|
||||
if m == nil || m.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
var errs []error
|
||||
|
||||
if m.services != nil {
|
||||
errs = append(errs, m.services.close())
|
||||
}
|
||||
|
||||
if m.engine != nil {
|
||||
errs = append(errs, m.engine.Close())
|
||||
}
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func hardwareBlock(hardwareID []byte) ([]byte, error) {
|
||||
if len(hardwareID) == 0 || len(hardwareID) > 20 {
|
||||
return nil, errors.New("hardware ID must contain between 1 and 20 bytes")
|
||||
}
|
||||
|
||||
result := make([]byte, 24)
|
||||
binary.LittleEndian.PutUint32(result[0:4], uint32(len(hardwareID)))
|
||||
copy(result[4:], hardwareID)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func align(value, alignment uint64) uint64 {
|
||||
return (value + alignment - 1) &^ (alignment - 1)
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestMachineGinkgo(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "SAP Machine Suite")
|
||||
}
|
||||
@@ -1,319 +0,0 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
)
|
||||
|
||||
func TestOpenHonorsCanceledContext(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
if _, err := Open(ctx, assets.Bundle{}); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Open error = %v, want %v", err, context.Canceled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHardwareBlock(t *testing.T) {
|
||||
identifier := []byte{1, 2, 3, 4, 5, 6}
|
||||
|
||||
block, err := hardwareBlock(identifier)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(block) != 24 || binary.LittleEndian.Uint32(block[:4]) != uint32(len(identifier)) {
|
||||
t.Fatalf("unexpected hardware block header: %x", block)
|
||||
}
|
||||
|
||||
if string(block[4:10]) != string(identifier) {
|
||||
t.Fatalf("hardware ID = %x", block[4:10])
|
||||
}
|
||||
|
||||
if _, err := hardwareBlock(make([]byte, 21)); err == nil {
|
||||
t.Fatal("oversized hardware ID was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuestServiceDispatchAndStackArguments(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
|
||||
address, err := machine.services.addFunction("test.stackArguments", func() error {
|
||||
seventh, err := machine.services.argument(6)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
eighth, err := machine.services.argument(7)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return machine.services.setResult(seventh + eighth)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := machine.invoke(address, 1, 2, 3, 4, 5, 6, 7, 8)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != 15 {
|
||||
t.Fatalf("result = %d, want 15", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownGuestServiceFailsClosed(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
|
||||
address, err := machine.services.resolve("test.unsupported")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := machine.invoke(address); err == nil || !strings.Contains(err.Error(), "unsupported import") {
|
||||
t.Fatalf("invoke error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuestAllocatorReusesAndClearsFreedMemory(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
|
||||
address, err := machine.services.allocate(64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := machine.engine.MemWrite(address, bytes.Repeat([]byte{0xa5}, 64)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := machine.services.release(address); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reused, err := machine.services.allocate(32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if reused != address {
|
||||
t.Fatalf("reused address = %#x, want %#x", reused, address)
|
||||
}
|
||||
|
||||
data, err := machine.engine.MemRead(reused, 32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(data, make([]byte, 32)) {
|
||||
t.Fatalf("reused allocation was not cleared: %x", data)
|
||||
}
|
||||
|
||||
if err := machine.services.release(reused); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if machine.services.heapCursor != 0 || len(machine.services.freeBlocks) != 0 {
|
||||
t.Fatalf("released heap was not reclaimed: cursor=%d free=%v", machine.services.heapCursor, machine.services.freeBlocks)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMallocSizeReturnsUsableSize(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
|
||||
address, err := machine.services.allocate(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := machine.invoke(machine.services.symbols["_malloc_size"], address)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != 16 {
|
||||
t.Fatalf("malloc_size = %d, want 16", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrncmpStopsAtMappedPageBoundary(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
left := returnAddress + pageSize - 2
|
||||
right := stackBase + pageSize - 2
|
||||
|
||||
for _, address := range []uint64{left, right} {
|
||||
if err := machine.engine.MemWrite(address, []byte{'a', 0}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
result, err := machine.invoke(machine.services.symbols["_strncmp"], left, right, 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != 0 {
|
||||
t.Fatalf("strncmp = %d, want 0", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformServicesInitializeOutputs(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
buffer := stackBase + pageSize
|
||||
|
||||
if err := machine.engine.MemWrite(buffer, bytes.Repeat([]byte{0xa5}, 16)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := machine.invoke(machine.services.symbols["_CFStringGetCString"], fakeHandle, buffer, 16, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != 1 {
|
||||
t.Fatalf("CFStringGetCString = %d, want 1", result)
|
||||
}
|
||||
|
||||
data, err := machine.engine.MemRead(buffer, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if data[0] != 0 {
|
||||
t.Fatalf("CFStringGetCString output = %#x, want NUL", data[0])
|
||||
}
|
||||
|
||||
for _, name := range []string{"_IORegistryEntryGetParentEntry", "_IOServiceGetMatchingServices"} {
|
||||
if err := machine.engine.MemWrite(buffer, bytes.Repeat([]byte{0xa5}, 4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := machine.invoke(machine.services.symbols[name], 0, 0, buffer)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != 0 {
|
||||
t.Fatalf("%s = %d, want 0", name, result)
|
||||
}
|
||||
|
||||
data, err := machine.engine.MemRead(buffer, 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if binary.LittleEndian.Uint32(data) != math.MaxUint32 {
|
||||
t.Fatalf("%s output = %x, want uint32 max", name, data)
|
||||
}
|
||||
}
|
||||
|
||||
result, err = machine.invoke(machine.services.symbols["_statfs"], 0, buffer)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != math.MaxUint64 {
|
||||
t.Fatalf("statfs = %#x, want -1", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsumeOutputDisposesAllocation(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
|
||||
output, err := machine.services.allocate(4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := machine.engine.MemWrite(output, []byte("test")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
pointerField := scratchBase
|
||||
lengthField := scratchBase + 8
|
||||
|
||||
if err := machine.writeUint64(pointerField, output); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := machine.writeUint64(lengthField, 4); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
machine.entry.dispose, err = machine.services.addFunction("test.dispose", machine.services.free)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, err := machine.consumeOutput(pointerField, lengthField)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if string(data) != "test" {
|
||||
t.Fatalf("output = %q, want test", data)
|
||||
}
|
||||
|
||||
if _, ok := machine.services.allocations[output]; ok {
|
||||
t.Fatal("output allocation was not released")
|
||||
}
|
||||
}
|
||||
|
||||
func newServiceTestMachine(t *testing.T) *Machine {
|
||||
t.Helper()
|
||||
|
||||
engine, err := unicorn.New(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("create Unicorn engine: %v", err)
|
||||
}
|
||||
|
||||
for _, region := range []struct {
|
||||
address uint64
|
||||
size uint64
|
||||
}{
|
||||
{returnAddress, pageSize},
|
||||
{scratchBase, scratchSize},
|
||||
{heapBase, heapSize},
|
||||
{stackBase, stackSize},
|
||||
} {
|
||||
if err := engine.MemMap(region.address, region.size); err != nil {
|
||||
_ = engine.Close()
|
||||
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := engine.MemWrite(returnAddress, []byte{0xF4}); err != nil {
|
||||
_ = engine.Close()
|
||||
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
services, err := newShims(engine, map[string]uint64{}, nil)
|
||||
if err != nil {
|
||||
_ = engine.Close()
|
||||
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
machine := &Machine{engine: engine, services: services}
|
||||
|
||||
t.Cleanup(func() {
|
||||
if err := machine.Close(); err != nil {
|
||||
t.Errorf("close machine: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
return machine
|
||||
}
|
||||
@@ -1,516 +0,0 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
)
|
||||
|
||||
const maxGuestTransfer = uint64(64 << 20)
|
||||
|
||||
func (s *shims) registerMemoryServices() error {
|
||||
services := []struct {
|
||||
names []string
|
||||
handler shimHandler
|
||||
}{
|
||||
{[]string{"_malloc"}, s.malloc},
|
||||
{[]string{"_malloc_good_size"}, s.mallocGoodSize},
|
||||
{[]string{"_malloc_size"}, s.mallocSize},
|
||||
{[]string{"_calloc"}, s.calloc},
|
||||
{[]string{"_realloc", "_reallocf"}, s.realloc},
|
||||
{[]string{"_free"}, s.free},
|
||||
{[]string{"_memcpy", "_memmove"}, s.memmove},
|
||||
{[]string{"_memset"}, s.memset},
|
||||
{[]string{"___bzero"}, s.bzero},
|
||||
{[]string{"___memcpy_chk"}, s.checkedMemcpy},
|
||||
{[]string{"___memset_chk"}, s.checkedMemset},
|
||||
{[]string{"_memcmp"}, s.memcmp},
|
||||
{[]string{"_strcmp"}, s.strcmp},
|
||||
{[]string{"_strncmp"}, s.strncmp},
|
||||
{[]string{"_strlen"}, s.strlen},
|
||||
}
|
||||
for _, service := range services {
|
||||
if err := s.addAliases(service.names, service.handler); err != nil {
|
||||
return fmt.Errorf("clear allocated guest memory: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) malloc() error {
|
||||
size, err := s.argument(0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write reallocated guest memory: %w", err)
|
||||
}
|
||||
|
||||
address, err := s.allocate(size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(address)
|
||||
}
|
||||
|
||||
func (s *shims) mallocGoodSize() error {
|
||||
size, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(align(max(size, 1), 16))
|
||||
}
|
||||
|
||||
func (s *shims) mallocSize() error {
|
||||
address, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
allocation, ok := s.allocations[address]
|
||||
if !ok {
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
return s.setResult(allocation.reserved)
|
||||
}
|
||||
|
||||
func (s *shims) calloc() error {
|
||||
count, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
size, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if count != 0 && size > math.MaxUint64/count {
|
||||
return errors.New("allocation size overflows")
|
||||
}
|
||||
|
||||
total := count * size
|
||||
|
||||
address, err := s.allocate(total)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if total != 0 {
|
||||
if err := s.engine.MemWrite(address, make([]byte, total)); err != nil {
|
||||
_ = s.release(address)
|
||||
|
||||
return fmt.Errorf("clear allocated guest memory: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return s.setResult(address)
|
||||
}
|
||||
|
||||
func (s *shims) realloc() error {
|
||||
oldAddress, err := s.argument(0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write reallocated guest memory: %w", err)
|
||||
}
|
||||
|
||||
newSize, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if oldAddress == 0 {
|
||||
address, err := s.allocate(newSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(address)
|
||||
}
|
||||
|
||||
oldAllocation, ok := s.allocations[oldAddress]
|
||||
if !ok {
|
||||
return fmt.Errorf("reallocate unknown pointer %#x", oldAddress)
|
||||
}
|
||||
|
||||
if newSize <= oldAllocation.reserved {
|
||||
oldAllocation.size = newSize
|
||||
s.allocations[oldAddress] = oldAllocation
|
||||
|
||||
return s.setResult(oldAddress)
|
||||
}
|
||||
|
||||
newAddress, err := s.allocate(newSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
data, err := s.engine.MemRead(oldAddress, oldAllocation.size)
|
||||
if err != nil {
|
||||
_ = s.release(newAddress)
|
||||
|
||||
return fmt.Errorf("read reallocated guest memory: %w", err)
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(newAddress, data); err != nil {
|
||||
_ = s.release(newAddress)
|
||||
|
||||
return fmt.Errorf("write reallocated guest memory: %w", err)
|
||||
}
|
||||
|
||||
if err := s.release(oldAddress); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(newAddress)
|
||||
}
|
||||
|
||||
func (s *shims) free() error {
|
||||
address, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if address != 0 {
|
||||
if err := s.release(address); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) allocate(size uint64) (uint64, error) {
|
||||
if size > maxGuestTransfer {
|
||||
return 0, fmt.Errorf("allocation size %d exceeds limit", size)
|
||||
}
|
||||
|
||||
reserved := align(max(size, 1), 16)
|
||||
for index, block := range s.freeBlocks {
|
||||
if block.size < reserved {
|
||||
continue
|
||||
}
|
||||
|
||||
address := block.address
|
||||
|
||||
if block.size == reserved {
|
||||
s.freeBlocks = append(s.freeBlocks[:index], s.freeBlocks[index+1:]...)
|
||||
} else {
|
||||
s.freeBlocks[index].address += reserved
|
||||
s.freeBlocks[index].size -= reserved
|
||||
}
|
||||
|
||||
s.allocations[address] = guestAllocation{size: size, reserved: reserved}
|
||||
|
||||
return address, nil
|
||||
}
|
||||
|
||||
if s.heapCursor > heapSize || reserved > heapSize-s.heapCursor {
|
||||
return 0, errors.New("guest heap exhausted")
|
||||
}
|
||||
|
||||
address := heapBase + s.heapCursor
|
||||
s.heapCursor += reserved
|
||||
s.allocations[address] = guestAllocation{size: size, reserved: reserved}
|
||||
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func (s *shims) release(address uint64) error {
|
||||
allocation, ok := s.allocations[address]
|
||||
if !ok {
|
||||
return fmt.Errorf("free unknown pointer %#x", address)
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(address, make([]byte, allocation.reserved)); err != nil {
|
||||
return fmt.Errorf("clear released guest memory: %w", err)
|
||||
}
|
||||
|
||||
delete(s.allocations, address)
|
||||
s.freeBlocks = append(s.freeBlocks, freeBlock{address: address, size: allocation.reserved})
|
||||
s.coalesceFreeBlocks()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) coalesceFreeBlocks() {
|
||||
sort.Slice(s.freeBlocks, func(left, right int) bool {
|
||||
return s.freeBlocks[left].address < s.freeBlocks[right].address
|
||||
})
|
||||
|
||||
merged := s.freeBlocks[:0]
|
||||
for _, block := range s.freeBlocks {
|
||||
last := len(merged) - 1
|
||||
if last >= 0 && merged[last].address+merged[last].size == block.address {
|
||||
merged[last].size += block.size
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
merged = append(merged, block)
|
||||
}
|
||||
|
||||
s.freeBlocks = merged
|
||||
for len(s.freeBlocks) != 0 {
|
||||
last := len(s.freeBlocks) - 1
|
||||
|
||||
block := s.freeBlocks[last]
|
||||
if block.address+block.size != heapBase+s.heapCursor {
|
||||
break
|
||||
}
|
||||
|
||||
s.heapCursor -= block.size
|
||||
s.freeBlocks = s.freeBlocks[:last]
|
||||
}
|
||||
}
|
||||
|
||||
func (s *shims) memmove() error {
|
||||
destination, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
source, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := checkedSize(length); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
data, err := s.engine.MemRead(source, length)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read memmove source: %w", err)
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(destination, data); err != nil {
|
||||
return fmt.Errorf("write memmove destination: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(destination)
|
||||
}
|
||||
|
||||
func (s *shims) memset() error {
|
||||
destination, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
value, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
size, err := checkedSize(length)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(destination, bytes.Repeat([]byte{byte(value)}, size)); err != nil {
|
||||
return fmt.Errorf("write guest memory fill: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(destination)
|
||||
}
|
||||
|
||||
func (s *shims) bzero() error {
|
||||
destination, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
size, err := checkedSize(length)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(destination, make([]byte, size)); err != nil {
|
||||
return fmt.Errorf("clear guest memory: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(destination)
|
||||
}
|
||||
|
||||
func (s *shims) checkedMemcpy() error {
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
capacity, err := s.argument(3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if length > capacity {
|
||||
return errors.New("checked copy exceeds destination")
|
||||
}
|
||||
|
||||
return s.memmove()
|
||||
}
|
||||
|
||||
func (s *shims) checkedMemset() error {
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
capacity, err := s.argument(3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if length > capacity {
|
||||
return errors.New("checked fill exceeds destination")
|
||||
}
|
||||
|
||||
return s.memset()
|
||||
}
|
||||
|
||||
func (s *shims) memcmp() error {
|
||||
left, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
right, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := checkedSize(length); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
a, err := s.engine.MemRead(left, length)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read left memory operand: %w", err)
|
||||
}
|
||||
|
||||
b, err := s.engine.MemRead(right, length)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read right memory operand: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(uint64(int64(bytes.Compare(a, b))))
|
||||
}
|
||||
|
||||
func (s *shims) strcmp() error {
|
||||
left, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
right, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
a, err := s.readCString(left)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b, err := s.readCString(right)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(uint64(int64(bytes.Compare([]byte(a), []byte(b)))))
|
||||
}
|
||||
|
||||
func (s *shims) strncmp() error {
|
||||
left, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
right, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := checkedSize(length); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for offset := uint64(0); offset < length; {
|
||||
if left > math.MaxUint64-offset || right > math.MaxUint64-offset {
|
||||
return errors.New("string comparison address overflows")
|
||||
}
|
||||
|
||||
leftAddress := left + offset
|
||||
rightAddress := right + offset
|
||||
chunk := min(
|
||||
length-offset,
|
||||
pageSize-leftAddress%pageSize,
|
||||
pageSize-rightAddress%pageSize,
|
||||
)
|
||||
|
||||
a, err := s.engine.MemRead(leftAddress, chunk)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read left memory page: %w", err)
|
||||
}
|
||||
|
||||
b, err := s.engine.MemRead(rightAddress, chunk)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read right memory page: %w", err)
|
||||
}
|
||||
|
||||
for index := range a {
|
||||
if a[index] != b[index] {
|
||||
return s.setResult(uint64(int64(int(a[index]) - int(b[index]))))
|
||||
}
|
||||
|
||||
if a[index] == 0 {
|
||||
return s.setResult(0)
|
||||
}
|
||||
}
|
||||
|
||||
offset += chunk
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) strlen() error {
|
||||
address, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
value, err := s.readCString(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(uint64(len(value)))
|
||||
}
|
||||
@@ -1,433 +0,0 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
)
|
||||
|
||||
const (
|
||||
fakeHandle = uint64(math.MaxUint64)
|
||||
coreFPFile = uint64(3)
|
||||
coreFPPath = "/System/Library/PrivateFrameworks/CoreFP.framework/CoreFP"
|
||||
icxsPath = "./../CoreFP.icxs"
|
||||
keySerial = "IOPlatformSerialNumber"
|
||||
keyUUID = "IOPlatformUUID"
|
||||
keyBoard = "board-id"
|
||||
keyedMessage = "objectForKey:"
|
||||
)
|
||||
|
||||
func (s *shims) registerPlatformServices() error {
|
||||
services := []struct {
|
||||
names []string
|
||||
handler shimHandler
|
||||
}{
|
||||
{[]string{"_CFBundleGetMainBundle", "_CFDataGetBytePtr", "_CFDataGetLength", "_CFStringGetLength", "_CFStringGetMaximumSizeForEncoding", "_CFUUIDCreateString", "_IORegistryEntryFromPath", "_IORegistryEntrySearchCFProperty", "_IOServiceMatching", "_getenv", "_pthread_self"}, s.returnZero},
|
||||
{[]string{"_CFDictionaryGetValue", "_DADiskCopyDescription", "_DADiskCreateFromBSDName", "_DASessionCreate", "_IORegistryEntryCreateCFProperty"}, s.returnFakeHandle},
|
||||
{[]string{"_CFRelease", "_IOObjectRelease", "_close", "_close$UNIX2003", "_pthread_mutex_lock", "_pthread_mutex_unlock", "_pthread_rwlock_init", "_pthread_rwlock_init$UNIX2003", "_pthread_rwlock_unlock", "_pthread_rwlock_unlock$UNIX2003", "_pthread_rwlock_wrlock", "_pthread_rwlock_wrlock$UNIX2003"}, s.returnZero},
|
||||
{[]string{"_CFStringCreateWithCString"}, s.cfStringCreate},
|
||||
{[]string{"_CFStringCreateWithCStringNoCopy"}, s.returnZero},
|
||||
{[]string{"_CFStringGetCString"}, s.cfStringGetCString},
|
||||
{[]string{"_IOIteratorNext"}, s.ioIteratorNext},
|
||||
{[]string{"_IORegistryEntryGetParentEntry"}, s.ioRegistryEntryGetParentEntry},
|
||||
{[]string{"_IOServiceGetMatchingServices"}, s.ioServiceGetMatchingServices},
|
||||
{[]string{"_IOServiceGetMatchingService"}, s.returnUint32Max},
|
||||
{[]string{"_OSAtomicCompareAndSwap32Barrier"}, s.compareAndSwap32},
|
||||
{[]string{"___error"}, s.errorPointer},
|
||||
{[]string{"_abort", "___stack_chk_fail", "dyld_stub_binder"}, s.abort},
|
||||
{[]string{"_arc4random"}, s.arc4random},
|
||||
{[]string{"_dlopen"}, s.dlopen},
|
||||
{[]string{"_dlsym"}, s.dlsym},
|
||||
{[]string{"_fcntl", "_fcntl$UNIX2003", "_lstat$INODE64", "_statfs", "_statfs$INODE64"}, s.returnMinusOne},
|
||||
{[]string{"_gettimeofday"}, s.gettimeofday},
|
||||
{[]string{"_objc_msgSend"}, s.objcMsgSend},
|
||||
{[]string{"_open", "_open$UNIX2003"}, s.open},
|
||||
{[]string{"_pthread_once"}, s.pthreadOnce},
|
||||
{[]string{"_read", "_read$UNIX2003"}, s.read},
|
||||
{[]string{"_sysctl"}, s.returnMinusOne},
|
||||
{[]string{"_sysctlbyname"}, s.sysctlbyname},
|
||||
}
|
||||
for _, service := range services {
|
||||
if err := s.addAliases(service.names, service.handler); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
s.errno, err = s.addData("guest.errno", make([]byte, 8))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := s.addData("___stack_chk_guard", []byte{0xA5, 0x71, 0x3C, 0xD9, 0x86, 0x42, 0xEF, 0x10}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, name := range []string{
|
||||
"_kCFAllocatorDefault",
|
||||
"_kCFAllocatorNull",
|
||||
"_kDADiskDescriptionVolumeUUIDKey",
|
||||
"_kIOMasterPortDefault",
|
||||
} {
|
||||
if _, err := s.addData(name, make([]byte, 8)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) returnZero() error {
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) returnFakeHandle() error {
|
||||
return s.setResult(fakeHandle)
|
||||
}
|
||||
|
||||
func (s *shims) returnUint32Max() error {
|
||||
return s.setResult(math.MaxUint32)
|
||||
}
|
||||
|
||||
func (s *shims) returnMinusOne() error {
|
||||
return s.setResult(math.MaxUint64)
|
||||
}
|
||||
|
||||
func (s *shims) cfStringCreate() error {
|
||||
address, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
value, err := s.readCString(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch value {
|
||||
case keySerial, keyUUID, keyBoard:
|
||||
return s.setResult(fakeHandle)
|
||||
default:
|
||||
return s.setResult(0)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *shims) cfStringGetCString() error {
|
||||
buffer, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
capacity, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if buffer == 0 || capacity == 0 {
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(buffer, []byte{0}); err != nil {
|
||||
return fmt.Errorf("terminate guest string buffer: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(1)
|
||||
}
|
||||
|
||||
func (s *shims) ioIteratorNext() error {
|
||||
s.iterator++
|
||||
|
||||
return s.setResult(uint64(s.iterator % 2))
|
||||
}
|
||||
|
||||
func (s *shims) ioRegistryEntryGetParentEntry() error {
|
||||
parent, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if parent == 0 {
|
||||
return errors.New("parent registry entry output is null")
|
||||
}
|
||||
|
||||
if err := s.writeUint32(parent, math.MaxUint32); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) ioServiceGetMatchingServices() error {
|
||||
iterator, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if iterator == 0 {
|
||||
return errors.New("matching services iterator output is null")
|
||||
}
|
||||
|
||||
s.iterator = 0
|
||||
if err := s.writeUint32(iterator, math.MaxUint32); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) compareAndSwap32() error {
|
||||
oldValue, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
newValue, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
address, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
current, err := s.readUint32(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if current != uint32(oldValue) {
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
if err := s.writeUint32(address, uint32(newValue)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(1)
|
||||
}
|
||||
|
||||
func (s *shims) errorPointer() error {
|
||||
return s.setResult(s.errno)
|
||||
}
|
||||
|
||||
func (s *shims) abort() error {
|
||||
return errors.New("guest aborted")
|
||||
}
|
||||
|
||||
func (s *shims) arc4random() error {
|
||||
var value [4]byte
|
||||
if _, err := rand.Read(value[:]); err != nil {
|
||||
return fmt.Errorf("generate guest random value: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(uint64(binary.LittleEndian.Uint32(value[:])))
|
||||
}
|
||||
|
||||
func (s *shims) dlopen() error {
|
||||
pathAddress, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
path, err := s.readCString(pathAddress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if path == coreFPPath {
|
||||
return s.setResult(fakeHandle)
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) dlsym() error {
|
||||
nameAddress, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
name, err := s.readCString(nameAddress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
address := s.coreExports["_"+name]
|
||||
|
||||
return s.setResult(address)
|
||||
}
|
||||
|
||||
func (s *shims) gettimeofday() error {
|
||||
timeAddress, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
zoneAddress, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
|
||||
if timeAddress != 0 {
|
||||
var value [16]byte
|
||||
|
||||
binary.LittleEndian.PutUint64(value[0:8], uint64(now.Unix()))
|
||||
binary.LittleEndian.PutUint32(value[8:12], uint32(now.Nanosecond()/1000))
|
||||
|
||||
if err := s.engine.MemWrite(timeAddress, value[:]); err != nil {
|
||||
return fmt.Errorf("write guest time value: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if zoneAddress != 0 {
|
||||
if err := s.engine.MemWrite(zoneAddress, make([]byte, 8)); err != nil {
|
||||
return fmt.Errorf("clear guest time zone: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) objcMsgSend() error {
|
||||
selectorAddress, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
selector, err := s.readCString(selectorAddress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if selector == keyedMessage {
|
||||
return s.setResult(fakeHandle)
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) open() error {
|
||||
pathAddress, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
path, err := s.readCString(pathAddress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if path == icxsPath {
|
||||
s.icxsOffset = 0
|
||||
|
||||
return s.setResult(coreFPFile)
|
||||
}
|
||||
|
||||
return s.returnMinusOne()
|
||||
}
|
||||
|
||||
func (s *shims) pthreadOnce() error {
|
||||
control, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
initializer, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
value, err := s.readUint64(control)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if value == 0 {
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
if err := s.writeUint64(control, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stack, err := s.engine.RegRead(unicorn.RegRSP)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read guest stack register: %w", err)
|
||||
}
|
||||
|
||||
stack -= 8
|
||||
if err := s.writeUint64(stack, initializer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.engine.RegWrite(unicorn.RegRSP, stack); err != nil {
|
||||
return fmt.Errorf("write guest stack register: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) read() error {
|
||||
descriptor, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
buffer, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
requested, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if descriptor != coreFPFile {
|
||||
return s.returnMinusOne()
|
||||
}
|
||||
|
||||
size, err := checkedSize(requested)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
remaining := len(s.icxs) - s.icxsOffset
|
||||
if size > remaining {
|
||||
size = remaining
|
||||
}
|
||||
|
||||
if size != 0 {
|
||||
if err := s.engine.MemWrite(buffer, s.icxs[s.icxsOffset:s.icxsOffset+size]); err != nil {
|
||||
return fmt.Errorf("write guest ICXS data: %w", err)
|
||||
}
|
||||
|
||||
s.icxsOffset += size
|
||||
}
|
||||
|
||||
return s.setResult(uint64(size))
|
||||
}
|
||||
|
||||
func (s *shims) sysctlbyname() error {
|
||||
lengthAddress, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if lengthAddress != 0 {
|
||||
if err := s.writeUint64(lengthAddress, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
@@ -1,316 +0,0 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
)
|
||||
|
||||
const (
|
||||
shimBase = uint64(0x0000200000000000)
|
||||
shimCodeSize = uint64(0x0000000000080000)
|
||||
shimSize = uint64(0x0000000000100000)
|
||||
shimSlotSize = uint64(16)
|
||||
)
|
||||
|
||||
type shimHandler func() error
|
||||
|
||||
type shimEntry struct {
|
||||
name string
|
||||
handler shimHandler
|
||||
}
|
||||
|
||||
type guestAllocation struct {
|
||||
size uint64
|
||||
reserved uint64
|
||||
}
|
||||
|
||||
type freeBlock struct {
|
||||
address uint64
|
||||
size uint64
|
||||
}
|
||||
|
||||
type shimOptions struct {
|
||||
zeroReturnAliases []string
|
||||
}
|
||||
|
||||
type shims struct {
|
||||
engine *unicorn.Engine
|
||||
hook *unicorn.Hook
|
||||
entries map[uint64]shimEntry
|
||||
symbols map[string]uint64
|
||||
codeCursor uint64
|
||||
dataCursor uint64
|
||||
fault error
|
||||
coreExports map[string]uint64
|
||||
icxs []byte
|
||||
icxsOffset int
|
||||
errno uint64
|
||||
heapCursor uint64
|
||||
allocations map[uint64]guestAllocation
|
||||
freeBlocks []freeBlock
|
||||
iterator uint32
|
||||
}
|
||||
|
||||
func newShims(engine *unicorn.Engine, coreExports map[string]uint64, icxs []byte) (*shims, error) {
|
||||
return newShimsWithOptions(engine, coreExports, icxs, shimOptions{})
|
||||
}
|
||||
|
||||
func newShimsWithOptions(engine *unicorn.Engine, coreExports map[string]uint64, icxs []byte, options shimOptions) (*shims, error) {
|
||||
if err := engine.MemMap(shimBase, shimSize); err != nil {
|
||||
return nil, fmt.Errorf("map guest service area: %w", err)
|
||||
}
|
||||
|
||||
s := &shims{
|
||||
engine: engine,
|
||||
entries: make(map[uint64]shimEntry),
|
||||
symbols: make(map[string]uint64),
|
||||
codeCursor: shimBase,
|
||||
dataCursor: shimBase + shimCodeSize,
|
||||
coreExports: coreExports,
|
||||
icxs: icxs,
|
||||
allocations: make(map[uint64]guestAllocation),
|
||||
}
|
||||
if err := s.registerMemoryServices(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.registerPlatformServices(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.addAliases(options.zeroReturnAliases, s.returnZero); err != nil {
|
||||
return nil, fmt.Errorf("register profile guest services: %w", err)
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
s.hook, err = engine.AddCodeHook(shimBase, shimBase+shimCodeSize-1, s.dispatch)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("register guest service dispatcher: %w", err)
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *shims) close() error {
|
||||
if s.hook == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := s.hook.Close()
|
||||
s.hook = nil
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("close guest service hook: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) resolve(name string) (uint64, error) {
|
||||
if address, ok := s.symbols[name]; ok {
|
||||
return address, nil
|
||||
}
|
||||
|
||||
return s.addFunction(name, func() error {
|
||||
return fmt.Errorf("guest called unsupported import %s", name)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *shims) addAliases(names []string, handler shimHandler) error {
|
||||
for _, name := range names {
|
||||
if _, err := s.addFunction(name, handler); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) addFunction(name string, handler shimHandler) (uint64, error) {
|
||||
if address, exists := s.symbols[name]; exists {
|
||||
return address, nil
|
||||
}
|
||||
|
||||
if s.codeCursor+shimSlotSize > shimBase+shimCodeSize {
|
||||
return 0, errors.New("guest service code area is full")
|
||||
}
|
||||
|
||||
address := s.codeCursor
|
||||
s.codeCursor += shimSlotSize
|
||||
|
||||
if err := s.engine.MemWrite(address, []byte{0xC3}); err != nil {
|
||||
return 0, fmt.Errorf("write guest service stub: %w", err)
|
||||
}
|
||||
|
||||
s.entries[address] = shimEntry{name: name, handler: handler}
|
||||
s.symbols[name] = address
|
||||
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func (s *shims) addData(name string, data []byte) (uint64, error) {
|
||||
if address, exists := s.symbols[name]; exists {
|
||||
return address, nil
|
||||
}
|
||||
|
||||
s.dataCursor = align(s.dataCursor, 8)
|
||||
if s.dataCursor+uint64(len(data)) > shimBase+shimSize {
|
||||
return 0, errors.New("guest service data area is full")
|
||||
}
|
||||
|
||||
address := s.dataCursor
|
||||
s.dataCursor += uint64(max(len(data), 8))
|
||||
|
||||
if err := s.engine.MemWrite(address, data); err != nil {
|
||||
return 0, fmt.Errorf("write guest service data: %w", err)
|
||||
}
|
||||
|
||||
s.symbols[name] = address
|
||||
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func (s *shims) dispatch(address uint64, _ uint32) {
|
||||
entry, ok := s.entries[address]
|
||||
if !ok {
|
||||
s.fail(fmt.Errorf("guest entered unknown service address %#x", address))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := entry.handler(); err != nil {
|
||||
s.fail(fmt.Errorf("%s: %w", entry.name, err))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *shims) fail(err error) {
|
||||
if s.fault == nil {
|
||||
s.fault = err
|
||||
}
|
||||
|
||||
if stopErr := s.engine.Stop(); stopErr != nil && s.fault == nil {
|
||||
s.fault = stopErr
|
||||
}
|
||||
}
|
||||
|
||||
func (s *shims) resetFault() {
|
||||
s.fault = nil
|
||||
}
|
||||
|
||||
func (s *shims) argument(index int) (uint64, error) {
|
||||
registers := [...]int{
|
||||
unicorn.RegRDI,
|
||||
unicorn.RegRSI,
|
||||
unicorn.RegRDX,
|
||||
unicorn.RegRCX,
|
||||
unicorn.RegR8,
|
||||
unicorn.RegR9,
|
||||
}
|
||||
if index >= 0 && index < len(registers) {
|
||||
value, err := s.engine.RegRead(registers[index])
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read guest argument register: %w", err)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
if index < 0 {
|
||||
return 0, errors.New("negative guest argument index")
|
||||
}
|
||||
|
||||
stack, err := s.engine.RegRead(unicorn.RegRSP)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read guest stack register: %w", err)
|
||||
}
|
||||
|
||||
data, err := s.engine.MemRead(stack+8+uint64(index-len(registers))*8, 8)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read guest stack argument: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint64(data), nil
|
||||
}
|
||||
|
||||
func (s *shims) setResult(value uint64) error {
|
||||
if err := s.engine.RegWrite(unicorn.RegRAX, value); err != nil {
|
||||
return fmt.Errorf("write guest result register: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) readUint32(address uint64) (uint32, error) {
|
||||
data, err := s.engine.MemRead(address, 4)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read guest uint32: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint32(data), nil
|
||||
}
|
||||
|
||||
func (s *shims) writeUint32(address uint64, value uint32) error {
|
||||
var data [4]byte
|
||||
|
||||
binary.LittleEndian.PutUint32(data[:], value)
|
||||
|
||||
if err := s.engine.MemWrite(address, data[:]); err != nil {
|
||||
return fmt.Errorf("write guest uint32: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) readUint64(address uint64) (uint64, error) {
|
||||
data, err := s.engine.MemRead(address, 8)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read guest uint64: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint64(data), nil
|
||||
}
|
||||
|
||||
func (s *shims) writeUint64(address, value uint64) error {
|
||||
var data [8]byte
|
||||
|
||||
binary.LittleEndian.PutUint64(data[:], value)
|
||||
|
||||
if err := s.engine.MemWrite(address, data[:]); err != nil {
|
||||
return fmt.Errorf("write guest uint64: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) readCString(address uint64) (string, error) {
|
||||
const maximum = 4096
|
||||
|
||||
value := make([]byte, 0, 64)
|
||||
for len(value) < maximum {
|
||||
item, err := s.engine.MemRead(address+uint64(len(value)), 1)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read guest string: %w", err)
|
||||
}
|
||||
|
||||
if item[0] == 0 {
|
||||
return string(value), nil
|
||||
}
|
||||
|
||||
value = append(value, item[0])
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("guest string exceeds %d bytes", maximum)
|
||||
}
|
||||
|
||||
func checkedSize(value uint64) (int, error) {
|
||||
if value > uint64(math.MaxInt) || value > maxGuestTransfer {
|
||||
return 0, fmt.Errorf("guest transfer size %d exceeds limit", value)
|
||||
}
|
||||
|
||||
return int(value), nil
|
||||
}
|
||||
@@ -1,340 +0,0 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
)
|
||||
|
||||
const (
|
||||
storeAgentBase = uint64(0x00001000c0000000)
|
||||
storeAgentGlobalInit = storeAgentBase + 0x0c5fc0
|
||||
storeAgentKBSyncEntry = storeAgentBase + 0x0c93c0
|
||||
storeAgentSessionInit = storeAgentBase + 0x0debd0
|
||||
storeAgentDecryptEntry = storeAgentBase + 0x0ee700
|
||||
storeAgentSessionClose = storeAgentBase + 0x1212d0
|
||||
storeAgentChunkSize = 0x8000
|
||||
storeAgentSCInfoPath = "/Users/Shared/SC Info"
|
||||
)
|
||||
|
||||
var storeAgentZeroReturnAliases = []string{
|
||||
"_pthread_rwlock_rdlock",
|
||||
"_pthread_rwlock_rdlock$UNIX2003",
|
||||
"_pthread_mutex_init",
|
||||
"_pthread_mutex_destroy",
|
||||
"_pthread_rwlock_destroy",
|
||||
}
|
||||
|
||||
type StoreAgent struct {
|
||||
mu sync.Mutex
|
||||
guest *Machine
|
||||
session uint64
|
||||
decryptEntry uint64
|
||||
closeEntry uint64
|
||||
closed bool
|
||||
}
|
||||
|
||||
func OpenStoreAgent(ctx context.Context, bundle assets.Bundle, hardwareID, dpInfo []byte) (*StoreAgent, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("StoreAgent context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("open StoreAgent runtime: %w", err)
|
||||
}
|
||||
|
||||
image, err := assets.LoadStoreAgent(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load Apple StoreAgent asset: %w", err)
|
||||
}
|
||||
|
||||
return openStoreAgent(ctx, bundle, image, hardwareID, dpInfo)
|
||||
}
|
||||
|
||||
func openStoreAgent(ctx context.Context, bundle assets.Bundle, image, hardwareID, dpInfo []byte) (*StoreAgent, error) {
|
||||
if len(dpInfo) == 0 {
|
||||
return nil, errors.New("StoreAgent dpInfo is empty")
|
||||
}
|
||||
|
||||
agent, globalContext, err := openStoreAgentGlobal(ctx, bundle, image, hardwareID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
agent.session, err = agent.initializeSession(globalContext, dpInfo)
|
||||
if err != nil {
|
||||
_ = agent.Close()
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
func openStoreAgentGlobal(ctx context.Context, bundle assets.Bundle, image, hardwareID []byte) (*StoreAgent, uint32, error) {
|
||||
if ctx == nil {
|
||||
return nil, 0, errors.New("StoreAgent context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, 0, fmt.Errorf("open StoreAgent runtime: %w", err)
|
||||
}
|
||||
|
||||
if err := assets.VerifyStoreAgent(image); err != nil {
|
||||
return nil, 0, fmt.Errorf("verify Apple StoreAgent profile: %w", err)
|
||||
}
|
||||
|
||||
hardware, err := hardwareBlock(hardwareID)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
guest, exports, err := openRuntime(ctx, bundle, runtimeOptions{
|
||||
extraImages: []imageSpec{{name: "storeagent", data: image, base: storeAgentBase}},
|
||||
shims: shimOptions{
|
||||
zeroReturnAliases: storeAgentZeroReturnAliases,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("start StoreAgent runtime: %w", err)
|
||||
}
|
||||
|
||||
guest.entry.dispose = exports["_jEHf8Xzsv8K"]
|
||||
|
||||
agent := &StoreAgent{
|
||||
guest: guest,
|
||||
decryptEntry: storeAgentDecryptEntry,
|
||||
closeEntry: storeAgentSessionClose,
|
||||
}
|
||||
|
||||
globalContext, err := agent.initializeGlobal(hardware)
|
||||
if err != nil {
|
||||
_ = agent.Close()
|
||||
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return agent, globalContext, nil
|
||||
}
|
||||
|
||||
func (s *StoreAgent) initializeGlobal(hardware []byte) (uint32, error) {
|
||||
s.guest.beginCall()
|
||||
defer s.guest.clearScratch()
|
||||
|
||||
hardwareAddress, err := s.guest.scratch(hardware, uint64(len(hardware)))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
path := append([]byte(storeAgentSCInfoPath), 0)
|
||||
pathAddress, err := s.guest.scratch(path, uint64(len(path)))
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
contextField, err := s.guest.scratch(nil, 4)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
status, err := s.guest.invoke(storeAgentGlobalInit, 0, hardwareAddress, pathAddress, contextField)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("initialize StoreAgent global context: %w", err)
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return 0, fmt.Errorf("StoreAgent global initialization returned %d", int32(status))
|
||||
}
|
||||
|
||||
value, err := s.guest.readUint32(contextField)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if value == 0 {
|
||||
return 0, errors.New("StoreAgent global initialization returned a null context")
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (s *StoreAgent) initializeSession(globalContext uint32, dpInfo []byte) (uint64, error) {
|
||||
s.guest.beginCall()
|
||||
defer s.guest.clearScratch()
|
||||
|
||||
dpInfoAddress, err := s.guest.scratch(dpInfo, uint64(len(dpInfo)))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
sessionField, err := s.guest.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
status, err := s.guest.invoke(
|
||||
storeAgentSessionInit,
|
||||
uint64(globalContext),
|
||||
dpInfoAddress,
|
||||
uint64(len(dpInfo)),
|
||||
sessionField,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("initialize StoreAgent session: %w", err)
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return 0, fmt.Errorf("StoreAgent session initialization returned %d", int32(status))
|
||||
}
|
||||
|
||||
session, err := s.guest.readUint64(sessionField)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if session == 0 {
|
||||
return 0, errors.New("StoreAgent session initialization returned a null session")
|
||||
}
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *StoreAgent) Decrypt(ctx context.Context, dst io.Writer, src io.Reader) (int64, error) {
|
||||
if s == nil {
|
||||
return 0, errors.New("StoreAgent is nil")
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.closed {
|
||||
return 0, errors.New("StoreAgent is closed")
|
||||
}
|
||||
|
||||
if ctx == nil {
|
||||
return 0, errors.New("StoreAgent decryption context is nil")
|
||||
}
|
||||
|
||||
if dst == nil {
|
||||
return 0, errors.New("StoreAgent decryption destination is nil")
|
||||
}
|
||||
|
||||
if src == nil {
|
||||
return 0, errors.New("StoreAgent decryption source is nil")
|
||||
}
|
||||
|
||||
return decryptStream(ctx, dst, src, s.decryptChunk)
|
||||
}
|
||||
|
||||
func (s *StoreAgent) decryptChunk(data []byte) error {
|
||||
s.guest.beginCall()
|
||||
defer s.guest.clearScratch()
|
||||
|
||||
address, err := s.guest.scratch(data, uint64(len(data)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
status, err := s.guest.invoke(
|
||||
s.decryptEntry,
|
||||
s.session,
|
||||
address,
|
||||
uint64(len(data)),
|
||||
address,
|
||||
0,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decrypt StoreAgent chunk: %w", err)
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return fmt.Errorf("StoreAgent decryption returned %d", int32(status))
|
||||
}
|
||||
|
||||
if err := s.guest.engine.MemReadInto(data, address); err != nil {
|
||||
return fmt.Errorf("read decrypted StoreAgent chunk: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func decryptStream(ctx context.Context, dst io.Writer, src io.Reader, decrypt func([]byte) error) (int64, error) {
|
||||
buffer := make([]byte, storeAgentChunkSize)
|
||||
|
||||
var written int64
|
||||
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return written, fmt.Errorf("decrypt StoreAgent stream: %w", err)
|
||||
}
|
||||
|
||||
count, readErr := io.ReadFull(src, buffer)
|
||||
if count != 0 {
|
||||
chunk := buffer[:count]
|
||||
if err := decrypt(chunk); err != nil {
|
||||
return written, err
|
||||
}
|
||||
|
||||
n, err := dst.Write(chunk)
|
||||
written += int64(n)
|
||||
|
||||
if err != nil {
|
||||
return written, fmt.Errorf("write decrypted StoreAgent stream: %w", err)
|
||||
}
|
||||
|
||||
if n != len(chunk) {
|
||||
return written, fmt.Errorf("write decrypted StoreAgent stream: %w", io.ErrShortWrite)
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case readErr == nil:
|
||||
continue
|
||||
case errors.Is(readErr, io.EOF), errors.Is(readErr, io.ErrUnexpectedEOF):
|
||||
return written, nil
|
||||
default:
|
||||
return written, fmt.Errorf("read encrypted StoreAgent stream: %w", readErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StoreAgent) Close() error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.closed = true
|
||||
|
||||
var errs []error
|
||||
|
||||
if s.guest != nil && s.session != 0 {
|
||||
session := s.session
|
||||
s.session = 0
|
||||
|
||||
status, err := s.guest.invoke(s.closeEntry, session)
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Errorf("close StoreAgent session: %w", err))
|
||||
} else if int32(status) != 0 {
|
||||
errs = append(errs, fmt.Errorf("StoreAgent session close returned %d", int32(status)))
|
||||
}
|
||||
}
|
||||
|
||||
if s.guest != nil {
|
||||
errs = append(errs, s.guest.Close())
|
||||
s.guest = nil
|
||||
}
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
@@ -1,204 +0,0 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("StoreAgent", func() {
|
||||
Describe("profile", func() {
|
||||
It("pins the verified image base and entry offsets", func() {
|
||||
Expect(storeAgentBase).To(Equal(uint64(0x00001000c0000000)))
|
||||
Expect(storeAgentGlobalInit).To(Equal(storeAgentBase + 0x0c5fc0))
|
||||
Expect(storeAgentSessionInit).To(Equal(storeAgentBase + 0x0debd0))
|
||||
Expect(storeAgentDecryptEntry).To(Equal(storeAgentBase + 0x0ee700))
|
||||
Expect(storeAgentSessionClose).To(Equal(storeAgentBase + 0x1212d0))
|
||||
})
|
||||
|
||||
It("re-verifies the pinned image before opening the runtime", func() {
|
||||
_, err := openStoreAgent(context.Background(), assets.Bundle{}, []byte("wrong image"), []byte{1}, []byte{1})
|
||||
Expect(err).To(MatchError(ContainSubstring("verify Apple StoreAgent profile")))
|
||||
Expect(err).To(MatchError(ContainSubstring("has size")))
|
||||
})
|
||||
|
||||
It("adds only the StoreAgent synchronization aliases", func() {
|
||||
machine := newGinkgoServiceMachine(shimOptions{zeroReturnAliases: storeAgentZeroReturnAliases})
|
||||
|
||||
for _, name := range storeAgentZeroReturnAliases {
|
||||
address, ok := machine.services.symbols[name]
|
||||
Expect(ok).To(BeTrue(), name)
|
||||
Expect(machine.invoke(address)).To(Equal(uint64(0)))
|
||||
}
|
||||
})
|
||||
|
||||
It("does not add StoreAgent aliases to the default SAP profile", func() {
|
||||
machine := newGinkgoServiceMachine(shimOptions{})
|
||||
address, err := machine.services.resolve("_pthread_mutex_init")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
_, err = machine.invoke(address)
|
||||
Expect(err).To(MatchError(ContainSubstring("unsupported import _pthread_mutex_init")))
|
||||
})
|
||||
})
|
||||
|
||||
Describe("streaming decryption", func() {
|
||||
It("uses full 0x8000 chunks and a final partial chunk", func() {
|
||||
input := bytes.Repeat([]byte{0x3c}, 2*storeAgentChunkSize+17)
|
||||
var output bytes.Buffer
|
||||
var sizes []int
|
||||
|
||||
written, err := decryptStream(context.Background(), &output, bytes.NewReader(input), func(chunk []byte) error {
|
||||
sizes = append(sizes, len(chunk))
|
||||
for index := range chunk {
|
||||
chunk[index] ^= 0xff
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(written).To(Equal(int64(len(input))))
|
||||
Expect(sizes).To(Equal([]int{storeAgentChunkSize, storeAgentChunkSize, 17}))
|
||||
Expect(output.Bytes()).To(Equal(bytes.Repeat([]byte{0xc3}, len(input))))
|
||||
})
|
||||
|
||||
It("does not invoke the decryptor for an empty stream", func() {
|
||||
called := false
|
||||
written, err := decryptStream(context.Background(), io.Discard, bytes.NewReader(nil), func([]byte) error {
|
||||
called = true
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(written).To(BeZero())
|
||||
Expect(called).To(BeFalse())
|
||||
})
|
||||
|
||||
It("writes a partial read before returning its source error", func() {
|
||||
sourceErr := errors.New("source failed")
|
||||
source := io.MultiReader(bytes.NewReader([]byte("partial")), errorReader{err: sourceErr})
|
||||
var output bytes.Buffer
|
||||
|
||||
written, err := decryptStream(context.Background(), &output, source, func(chunk []byte) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
Expect(written).To(Equal(int64(len("partial"))))
|
||||
Expect(output.String()).To(Equal("partial"))
|
||||
Expect(err).To(MatchError(ContainSubstring(sourceErr.Error())))
|
||||
})
|
||||
|
||||
It("stops before the next chunk when the context is canceled", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
input := bytes.Repeat([]byte{1}, 2*storeAgentChunkSize)
|
||||
calls := 0
|
||||
|
||||
written, err := decryptStream(ctx, io.Discard, bytes.NewReader(input), func([]byte) error {
|
||||
calls++
|
||||
cancel()
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
Expect(calls).To(Equal(1))
|
||||
Expect(written).To(Equal(int64(storeAgentChunkSize)))
|
||||
Expect(err).To(MatchError(ContainSubstring(context.Canceled.Error())))
|
||||
})
|
||||
|
||||
It("returns decryptor errors without writing the failed chunk", func() {
|
||||
decryptErr := errors.New("decrypt failed")
|
||||
var output bytes.Buffer
|
||||
|
||||
written, err := decryptStream(context.Background(), &output, bytes.NewReader([]byte("encrypted")), func([]byte) error {
|
||||
return decryptErr
|
||||
})
|
||||
|
||||
Expect(written).To(BeZero())
|
||||
Expect(output.Len()).To(BeZero())
|
||||
Expect(err).To(MatchError(decryptErr))
|
||||
})
|
||||
|
||||
It("reports short writes", func() {
|
||||
written, err := decryptStream(context.Background(), shortWriter{}, bytes.NewReader([]byte("encrypted")), func([]byte) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
Expect(written).To(Equal(int64(1)))
|
||||
Expect(err).To(MatchError(ContainSubstring(io.ErrShortWrite.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
It("closes the session and machine idempotently", func() {
|
||||
machine := newGinkgoServiceMachine(shimOptions{})
|
||||
var closedSession uint64
|
||||
closeEntry, err := machine.services.addFunction("test.storeagent.close", func() error {
|
||||
value, argumentErr := machine.services.argument(0)
|
||||
if argumentErr != nil {
|
||||
return argumentErr
|
||||
}
|
||||
|
||||
closedSession = value
|
||||
|
||||
return machine.services.setResult(0)
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
agent := &StoreAgent{guest: machine, session: 0x1234, closeEntry: closeEntry}
|
||||
Expect(agent.Close()).To(Succeed())
|
||||
Expect(closedSession).To(Equal(uint64(0x1234)))
|
||||
Expect(agent.session).To(BeZero())
|
||||
Expect(agent.guest).To(BeNil())
|
||||
Expect(agent.Close()).To(Succeed())
|
||||
})
|
||||
})
|
||||
|
||||
type errorReader struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (r errorReader) Read([]byte) (int, error) {
|
||||
return 0, r.err
|
||||
}
|
||||
|
||||
type shortWriter struct{}
|
||||
|
||||
func (shortWriter) Write([]byte) (int, error) {
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
func newGinkgoServiceMachine(options shimOptions) *Machine {
|
||||
engine, err := unicorn.New(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
for _, region := range []struct {
|
||||
address uint64
|
||||
size uint64
|
||||
}{
|
||||
{returnAddress, pageSize},
|
||||
{scratchBase, scratchSize},
|
||||
{heapBase, heapSize},
|
||||
{stackBase, stackSize},
|
||||
} {
|
||||
Expect(engine.MemMap(region.address, region.size)).To(Succeed())
|
||||
}
|
||||
|
||||
Expect(engine.MemWrite(returnAddress, []byte{0xF4})).To(Succeed())
|
||||
|
||||
services, err := newShimsWithOptions(engine, map[string]uint64{}, nil, options)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
machine := &Machine{engine: engine, services: services}
|
||||
|
||||
DeferCleanup(func() {
|
||||
Expect(machine.Close()).To(Succeed())
|
||||
})
|
||||
|
||||
return machine
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"howett.net/plist"
|
||||
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
const (
|
||||
setupCertificateKey = "sign-sap-setup-cert"
|
||||
setupBufferKey = "sign-sap-setup-buffer"
|
||||
maxSetupBody = int64(1 << 20)
|
||||
)
|
||||
|
||||
type setupProtocol struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func (p setupProtocol) certificate(ctx context.Context, endpoint string) ([]byte, error) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create SAP certificate request: %w", err)
|
||||
}
|
||||
|
||||
request.Header.Set("User-Agent", apphttp.DefaultUserAgent)
|
||||
|
||||
body, err := p.send(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetch SAP certificate: %w", err)
|
||||
}
|
||||
|
||||
return plistBytes(body, setupCertificateKey)
|
||||
}
|
||||
|
||||
func (p setupProtocol) exchange(ctx context.Context, endpoint string, input []byte) ([]byte, error) {
|
||||
envelope, err := plist.Marshal(map[string]any{setupBufferKey: input}, plist.XMLFormat)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encode SAP setup message: %w", err)
|
||||
}
|
||||
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(envelope))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create SAP setup request: %w", err)
|
||||
}
|
||||
|
||||
request.Header.Set("Content-Type", "application/x-plist")
|
||||
request.Header.Set("User-Agent", apphttp.DefaultUserAgent)
|
||||
|
||||
body, err := p.send(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("exchange SAP setup message: %w", err)
|
||||
}
|
||||
|
||||
return plistBytes(body, setupBufferKey)
|
||||
}
|
||||
|
||||
func (p setupProtocol) send(request *http.Request) ([]byte, error) {
|
||||
response, err := p.client.Do(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("send SAP request: %w", err)
|
||||
}
|
||||
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, maxSetupBody))
|
||||
|
||||
return nil, fmt.Errorf("apple returned %s", response.Status)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, maxSetupBody+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read SAP response: %w", err)
|
||||
}
|
||||
|
||||
if int64(len(body)) > maxSetupBody {
|
||||
return nil, fmt.Errorf("apple response exceeds %d bytes", maxSetupBody)
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func plistBytes(document []byte, key string) ([]byte, error) {
|
||||
var values map[string]any
|
||||
if _, err := plist.Unmarshal(document, &values); err != nil {
|
||||
return nil, fmt.Errorf("decode Apple plist: %w", err)
|
||||
}
|
||||
|
||||
value, ok := values[key].([]byte)
|
||||
if !ok || len(value) == 0 {
|
||||
return nil, errors.New("Apple plist is missing " + key)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
return function(request)
|
||||
}
|
||||
|
||||
func TestSetupProtocol(t *testing.T) {
|
||||
protocol := setupProtocol{client: &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
if request.Header.Get("User-Agent") == "" {
|
||||
t.Error("User-Agent is empty")
|
||||
}
|
||||
key := setupCertificateKey
|
||||
value := []byte("certificate")
|
||||
if request.Method == http.MethodPost {
|
||||
if request.Header.Get("Content-Type") != "application/x-plist" {
|
||||
t.Errorf("Content-Type = %q", request.Header.Get("Content-Type"))
|
||||
}
|
||||
requestBody, err := io.ReadAll(request.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, err := plistBytes(requestBody, setupBufferKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(decoded, []byte("request")) {
|
||||
t.Errorf("request data = %q", decoded)
|
||||
}
|
||||
key = setupBufferKey
|
||||
value = []byte("reply")
|
||||
}
|
||||
body, err := plist.Marshal(map[string]any{key: value}, plist.XMLFormat)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Status: "200 OK",
|
||||
Body: io.NopCloser(bytes.NewReader(body)),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
})}}
|
||||
|
||||
certificate, err := protocol.certificate(context.Background(), "https://example.com/certificate")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if string(certificate) != "certificate" {
|
||||
t.Fatalf("certificate = %q", certificate)
|
||||
}
|
||||
|
||||
reply, err := protocol.exchange(context.Background(), "https://example.com/setup", []byte("request"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if string(reply) != "reply" {
|
||||
t.Fatalf("reply = %q", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupProtocolRejectsOversizedResponse(t *testing.T) {
|
||||
protocol := setupProtocol{client: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Status: "200 OK",
|
||||
Body: io.NopCloser(strings.NewReader(strings.Repeat("x", int(maxSetupBody)+1))),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
})}}
|
||||
if _, err := protocol.certificate(context.Background(), "https://example.com/certificate"); err == nil {
|
||||
t.Fatal("oversized response was accepted")
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const supportedVersion = uint32(200)
|
||||
|
||||
var errSignerClosed = errors.New("SAP signer is closed")
|
||||
|
||||
type Config struct {
|
||||
SetupURL string
|
||||
CertificateURL string
|
||||
Version uint32
|
||||
HardwareID []byte
|
||||
}
|
||||
|
||||
type ActionSigner interface {
|
||||
Sign(input []byte) ([]byte, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
func validateConfig(config Config) error {
|
||||
if config.Version != supportedVersion {
|
||||
return fmt.Errorf("unsupported SAP version %d", config.Version)
|
||||
}
|
||||
|
||||
if len(config.HardwareID) == 0 || len(config.HardwareID) > 20 {
|
||||
return errors.New("SAP hardware ID must contain between 1 and 20 bytes")
|
||||
}
|
||||
|
||||
if err := validateEndpoint("setup", config.SetupURL); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := validateEndpoint("certificate", config.CertificateURL); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateEndpoint(label, value string) error {
|
||||
endpoint, err := url.Parse(value)
|
||||
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || endpoint.User != nil {
|
||||
return fmt.Errorf("SAP %s URL must be an absolute HTTPS URL", label)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSignerIntegration(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
signer, err := NewSigner(ctx, Config{
|
||||
SetupURL: "https://fpinit.itunes.apple.com/v1/signSapSetup/legacy",
|
||||
CertificateURL: "https://s.mzstatic.com/sap/setupCert.plist",
|
||||
Version: 200,
|
||||
HardwareID: []byte{0x02, 0, 0, 0, 0, 1},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
if err := signer.Close(); err != nil {
|
||||
t.Errorf("close signer: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
signature, err := signer.Sign([]byte("ipatool SAP smoke test"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(signature) == 0 {
|
||||
t.Fatal("signature is empty")
|
||||
}
|
||||
|
||||
second, err := signer.Sign([]byte("ipatool second SAP smoke test"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(second) == 0 || bytes.Equal(signature, second) {
|
||||
t.Fatal("second signature is empty or unexpectedly reused")
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/sap/machine"
|
||||
)
|
||||
|
||||
type Signer struct {
|
||||
mu sync.Mutex
|
||||
machine *machine.Machine
|
||||
context uint64
|
||||
hardware []byte
|
||||
closed bool
|
||||
}
|
||||
|
||||
func NewSigner(ctx context.Context, config Config) (ActionSigner, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("SAP signer context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("create SAP signer: %w", err)
|
||||
}
|
||||
|
||||
if err := validateConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
bundle, err := assets.Load(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load Apple SAP assets: %w", err)
|
||||
}
|
||||
|
||||
guest, err := machine.Open(ctx, bundle)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("start Apple SAP runtime: %w", err)
|
||||
}
|
||||
|
||||
signer := &Signer{
|
||||
machine: guest,
|
||||
hardware: append([]byte(nil), config.HardwareID...),
|
||||
}
|
||||
complete := false
|
||||
|
||||
defer func() {
|
||||
if !complete {
|
||||
_ = signer.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
signer.context, err = guest.Initialize(signer.hardware)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initialize Apple SAP session: %w", err)
|
||||
}
|
||||
|
||||
protocol := setupProtocol{client: &http.Client{Timeout: 30 * time.Second}}
|
||||
|
||||
certificate, err := protocol.certificate(ctx, config.CertificateURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
request, state, err := guest.Exchange(config.Version, signer.hardware, signer.context, certificate)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create SAP setup message: %w", err)
|
||||
}
|
||||
|
||||
if state != 1 {
|
||||
return nil, fmt.Errorf("SAP setup entered unexpected state %d", state)
|
||||
}
|
||||
|
||||
if len(request) == 0 {
|
||||
return nil, errors.New("SAP setup message is empty")
|
||||
}
|
||||
|
||||
reply, err := protocol.exchange(ctx, config.SetupURL, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, state, err = guest.Exchange(config.Version, signer.hardware, signer.context, reply)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("complete SAP setup: %w", err)
|
||||
}
|
||||
|
||||
if state != 0 {
|
||||
return nil, fmt.Errorf("SAP setup completed in unexpected state %d", state)
|
||||
}
|
||||
|
||||
complete = true
|
||||
|
||||
return signer, nil
|
||||
}
|
||||
|
||||
func (s *Signer) Sign(input []byte) ([]byte, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.closed {
|
||||
return nil, errSignerClosed
|
||||
}
|
||||
|
||||
signature, err := s.machine.Sign(s.context, input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sign Apple request: %w", err)
|
||||
}
|
||||
|
||||
if len(signature) == 0 {
|
||||
return nil, errors.New("sign Apple request: signature is empty")
|
||||
}
|
||||
|
||||
return signature, nil
|
||||
}
|
||||
|
||||
func (s *Signer) Close() error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.closed = true
|
||||
|
||||
var closeErrors []error
|
||||
if s.machine != nil && s.context != 0 {
|
||||
closeErrors = append(closeErrors, s.machine.Teardown(s.context))
|
||||
s.context = 0
|
||||
}
|
||||
|
||||
if s.machine != nil {
|
||||
closeErrors = append(closeErrors, s.machine.Close())
|
||||
s.machine = nil
|
||||
}
|
||||
|
||||
for index := range s.hardware {
|
||||
s.hardware[index] = 0
|
||||
}
|
||||
|
||||
return errors.Join(closeErrors...)
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClosedSigner(t *testing.T) {
|
||||
signer := &Signer{closed: true}
|
||||
if _, err := signer.Sign([]byte("message")); !errors.Is(err, errSignerClosed) {
|
||||
t.Fatalf("Sign error = %v, want %v", err, errSignerClosed)
|
||||
}
|
||||
|
||||
if err := signer.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewSignerRejectsInvalidContext(t *testing.T) {
|
||||
config := Config{
|
||||
SetupURL: "https://example.apple.com/setup",
|
||||
CertificateURL: "https://example.apple.com/certificate",
|
||||
Version: 200,
|
||||
HardwareID: []byte{1, 2, 3, 4, 5, 6},
|
||||
}
|
||||
//nolint:staticcheck // This test verifies that a nil context is rejected.
|
||||
if _, err := NewSigner(nil, config); err == nil {
|
||||
t.Fatal("NewSigner accepted a nil context")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
if _, err := NewSigner(ctx, config); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("NewSigner error = %v, want %v", err, context.Canceled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateConfig(t *testing.T) {
|
||||
valid := Config{
|
||||
SetupURL: "https://example.apple.com/setup",
|
||||
CertificateURL: "https://example.apple.com/certificate",
|
||||
Version: 200,
|
||||
HardwareID: []byte{1, 2, 3, 4, 5, 6},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*Config)
|
||||
}{
|
||||
{"version", func(config *Config) { config.Version = 210 }},
|
||||
{"empty hardware ID", func(config *Config) { config.HardwareID = nil }},
|
||||
{"long hardware ID", func(config *Config) { config.HardwareID = make([]byte, 21) }},
|
||||
{"relative setup URL", func(config *Config) { config.SetupURL = "/setup" }},
|
||||
{"HTTP certificate URL", func(config *Config) { config.CertificateURL = "http://example.apple.com/cert" }},
|
||||
{"credentialed URL", func(config *Config) { config.SetupURL = "https://user@example.apple.com/setup" }},
|
||||
}
|
||||
|
||||
if err := validateConfig(valid); err != nil {
|
||||
t.Fatalf("valid config: %v", err)
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
config := valid
|
||||
test.mutate(&config)
|
||||
|
||||
if err := validateConfig(config); err == nil {
|
||||
t.Fatal("validateConfig accepted invalid config")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package unicorn
|
||||
|
||||
import "io"
|
||||
|
||||
type archiveFormat uint8
|
||||
|
||||
const (
|
||||
archiveZIP archiveFormat = iota
|
||||
archiveSevenZip
|
||||
archiveTarZstd
|
||||
)
|
||||
|
||||
type archiveEntry struct {
|
||||
reader io.Reader
|
||||
size uint64
|
||||
close func() error
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/bodgit/sevenzip"
|
||||
)
|
||||
|
||||
func openArchiveEntry(path, name string, format archiveFormat) (archiveEntry, error) {
|
||||
switch format {
|
||||
case archiveZIP:
|
||||
return openZIPEntry(path, name)
|
||||
case archiveSevenZip:
|
||||
return openSevenZipEntry(path, name)
|
||||
case archiveTarZstd:
|
||||
return openTarZstdEntry(path, name)
|
||||
default:
|
||||
return archiveEntry{}, fmt.Errorf("unsupported Unicorn archive format %d", format)
|
||||
}
|
||||
}
|
||||
|
||||
func openSevenZipEntry(path, name string) (archiveEntry, error) {
|
||||
archive, err := sevenzip.OpenReader(path)
|
||||
if err != nil {
|
||||
return archiveEntry{}, fmt.Errorf("open Unicorn archive: %w", err)
|
||||
}
|
||||
|
||||
for _, candidate := range archive.File {
|
||||
if candidate.Name != name {
|
||||
continue
|
||||
}
|
||||
if candidate.FileInfo().IsDir() {
|
||||
_ = archive.Close()
|
||||
return archiveEntry{}, fmt.Errorf("invalid Unicorn library entry %q", name)
|
||||
}
|
||||
|
||||
reader, err := candidate.Open()
|
||||
if err != nil {
|
||||
_ = archive.Close()
|
||||
return archiveEntry{}, fmt.Errorf("open Unicorn library entry: %w", err)
|
||||
}
|
||||
return archiveEntry{
|
||||
reader: reader,
|
||||
size: candidate.UncompressedSize,
|
||||
close: func() error {
|
||||
return errors.Join(reader.Close(), archive.Close())
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
_ = archive.Close()
|
||||
return archiveEntry{}, fmt.Errorf("Unicorn archive does not contain %q", name)
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
)
|
||||
|
||||
func openTarZstdEntry(path, name string) (archiveEntry, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return archiveEntry{}, fmt.Errorf("open Unicorn archive: %w", err)
|
||||
}
|
||||
|
||||
decoder, err := zstd.NewReader(file)
|
||||
if err != nil {
|
||||
_ = file.Close()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("open Unicorn archive: %w", err)
|
||||
}
|
||||
|
||||
closeArchive := func() error {
|
||||
decoder.Close()
|
||||
|
||||
return file.Close()
|
||||
}
|
||||
|
||||
reader := tar.NewReader(decoder)
|
||||
|
||||
for {
|
||||
header, err := reader.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
_ = closeArchive()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("unicorn archive does not contain %q", name)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
_ = closeArchive()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("read Unicorn archive: %w", err)
|
||||
}
|
||||
|
||||
if header.Name != name {
|
||||
continue
|
||||
}
|
||||
|
||||
if header.Typeflag != tar.TypeReg || header.Size < 0 {
|
||||
_ = closeArchive()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("invalid Unicorn library entry %q", name)
|
||||
}
|
||||
|
||||
return archiveEntry{
|
||||
reader: io.LimitReader(reader, header.Size),
|
||||
size: uint64(header.Size),
|
||||
close: closeArchive,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
)
|
||||
|
||||
func TestOpenTarZstdEntry(t *testing.T) {
|
||||
const name = "clangarm64/bin/libunicorn.dll"
|
||||
|
||||
payload := []byte("test Unicorn library")
|
||||
|
||||
var compressed bytes.Buffer
|
||||
|
||||
encoder, err := zstd.NewWriter(&compressed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
archive := tar.NewWriter(encoder)
|
||||
if err := archive.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(payload))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := archive.Write(payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := archive.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := encoder.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
path := filepath.Join(t.TempDir(), "runtime.pkg.tar.zst")
|
||||
if err := os.WriteFile(path, compressed.Bytes(), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
entry, err := openTarZstdEntry(path, name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
if err := entry.close(); err != nil {
|
||||
t.Errorf("close archive entry: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
actual, err := io.ReadAll(entry.reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(actual, payload) {
|
||||
t.Fatalf("contents = %q, want %q", actual, payload)
|
||||
}
|
||||
|
||||
if entry.size != uint64(len(payload)) {
|
||||
t.Fatalf("size = %d, want %d", entry.size, len(payload))
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package unicorn
|
||||
|
||||
import "fmt"
|
||||
|
||||
func openArchiveEntry(path, name string, format archiveFormat) (archiveEntry, error) {
|
||||
if format != archiveZIP {
|
||||
return archiveEntry{}, fmt.Errorf("unsupported Unicorn archive format %d", format)
|
||||
}
|
||||
|
||||
return openZIPEntry(path, name)
|
||||
}
|
||||
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user