mirror of
https://github.com/majd/ipatool
synced 2026-11-28 18:27:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b02b4c555 | ||
|
|
d69faf83c8 | ||
|
|
5a6dfe0582 | ||
|
|
b352566155 | ||
|
|
6194bf4ecd | ||
|
|
20290220cd | ||
|
|
3e84853e2e | ||
|
|
2cfd33fa45 | ||
|
|
e4b0aaee61 | ||
|
|
9df35a6d84 | ||
|
|
8771e57445 | ||
|
|
e0e2908dc8 | ||
|
|
f137223276 | ||
|
|
536d7bacc1 | ||
|
|
856323251a | ||
|
|
0d99fc2d96 | ||
|
|
72c47d538b | ||
|
|
001d889896 | ||
|
|
d9c0247dae | ||
|
|
5dc4c8058d | ||
|
|
1b9ff28eb4 | ||
|
|
7578671482 | ||
|
|
b0fe32d8a1 | ||
|
|
0259df3c09 | ||
|
|
5b7a812a77 | ||
|
|
9d343753c4 | ||
|
|
987900b417 | ||
|
|
4484b55d36 | ||
|
|
e3932cec31 | ||
|
|
cde7d00355 | ||
|
|
93b527a839 | ||
|
|
ed45c02852 | ||
|
|
f11d9abafe | ||
|
|
f9aa6536cd | ||
|
|
3411d57f45 | ||
|
|
0cc226a3d7 | ||
|
|
e258fed14a | ||
|
|
1ec8b3e5dc | ||
|
|
387d1a4f47 | ||
|
|
294488012f | ||
|
|
5deb9b521b | ||
|
|
acd9e7a972 | ||
|
|
50312a928b | ||
|
|
735b689ac3 | ||
|
|
e5211d6fd9 | ||
|
|
747d66fc0a | ||
|
|
1ed3bf94dd | ||
|
|
fb1ca3521b | ||
|
|
ad88910ad6 | ||
|
|
c66d6537f4 | ||
|
|
7b4913a71c | ||
|
|
c4323e4c55 | ||
|
|
2aaf18b832 | ||
|
|
e3dea14461 | ||
|
|
dd28a3a9d8 | ||
|
|
5a47056bc3 | ||
|
|
ba85241c88 | ||
|
|
394cd643de | ||
|
|
62f1c8b435 | ||
|
|
5c522b685d | ||
|
|
ba180d741d | ||
|
|
d1845ba678 | ||
|
|
a814a71a9f | ||
|
|
843f5c6c29 | ||
|
|
b8bac296b8 | ||
|
|
24f93d332f | ||
|
|
e6acb9c3c2 | ||
|
|
abdb5902cb | ||
|
|
91d4294085 | ||
|
|
73fabcc283 | ||
|
|
30b2909231 | ||
|
|
a9bd16c9a2 | ||
|
|
cee3674258 | ||
|
|
8f9748fa51 | ||
|
|
d5d0b56faf | ||
|
|
30d19a6859 | ||
|
|
27e8902d7e | ||
|
|
acaf6c566e | ||
|
|
652b9d0083 | ||
|
|
a53550f9c4 | ||
|
|
161888d240 | ||
|
|
abd86cb01a | ||
|
|
5f776fe2f5 | ||
|
|
ab79e429d5 | ||
|
|
9032d4c192 | ||
|
|
779a2e66cb | ||
|
|
fd630343bc | ||
|
|
dcddce4650 | ||
|
|
a3fa2f09b3 | ||
|
|
85ae82d9c4 | ||
|
|
1bee8bc568 | ||
|
|
abaeccefec | ||
|
|
8c4e037aa3 | ||
|
|
4142ab48ad | ||
|
|
1858ad7a72 | ||
|
|
2140a26bdf | ||
|
|
e914156036 | ||
|
|
19ffd1bf6b | ||
|
|
7ffd4bf050 | ||
|
|
496595a039 | ||
|
|
7765fd5445 | ||
|
|
6f63cd4776 | ||
|
|
65242569b3 | ||
|
|
14883b4631 | ||
|
|
91ae69cc58 | ||
|
|
80dbbef6c8 | ||
|
|
e3e604925f | ||
|
|
cffa279e31 | ||
|
|
034a0978ab | ||
|
|
9657750fc1 | ||
|
|
9969c18cef | ||
|
|
f09439ecde | ||
|
|
55ef41fc20 | ||
|
|
b4bd8d6580 | ||
|
|
79250ae2a3 | ||
|
|
a3212e0fd2 | ||
|
|
805678138e | ||
|
|
3a537e7571 | ||
|
|
e686248270 | ||
|
|
ac081fa19d | ||
|
|
7136f81fd1 | ||
|
|
34866f5833 | ||
|
|
46f3369de0 | ||
|
|
0bb134e9d7 | ||
|
|
bbf3717456 | ||
|
|
e1eda9f776 | ||
|
|
c406c36819 | ||
|
|
e5291ba16b | ||
|
|
37af8f8468 | ||
|
|
21cbd596bc | ||
|
|
f3c9076ff0 | ||
|
|
d147788501 | ||
|
|
8a23d6fadd | ||
|
|
63ee6fc6a4 | ||
|
|
5b547457f1 | ||
|
|
169af4b2ea | ||
|
|
f68a119963 | ||
|
|
58e9a18778 | ||
|
|
c8624b26d5 | ||
|
|
3199afc494 | ||
|
|
6597f5ac77 | ||
|
|
6ccb4a7f0b | ||
|
|
64c5cc9843 | ||
|
|
19e7261713 | ||
|
|
b031cd20d1 | ||
|
|
9db93c83c0 | ||
|
|
90253c336f | ||
|
|
e1141bd6d2 | ||
|
|
6a7adabbfa | ||
|
|
cfc4a075ae | ||
|
|
74e7588c6d | ||
|
|
67e557e9a7 | ||
|
|
bf33e0d1c4 | ||
|
|
95c3aa6629 | ||
|
|
cf926d7911 | ||
|
|
9a361cf7a0 | ||
|
|
574d5b5148 | ||
|
|
5abc5d1777 | ||
|
|
8762eaf192 | ||
|
|
4f3115d60f | ||
|
|
0e38e43d8b | ||
|
|
73e9bd90d1 | ||
|
|
e76dbf044e | ||
|
|
d82e819d4e | ||
|
|
19ac47d098 | ||
|
|
fece9ea79c | ||
|
|
1b31ee6556 | ||
|
|
fbd9d74729 | ||
|
|
8d2467491e | ||
|
|
4eba914bff | ||
|
|
56cc64fcef | ||
|
|
7813e78e3c | ||
|
|
50a1e546ef | ||
|
|
094ff93693 | ||
|
|
5d014266e3 | ||
|
|
8dd1a8508d | ||
|
|
dff5a5ad0b | ||
|
|
6356b522df | ||
|
|
a2cb7c653e | ||
|
|
2f154ad4f9 | ||
|
|
a3b322c8da | ||
|
|
5386d36275 | ||
|
|
7e21c8571a | ||
|
|
ff582bb97b | ||
|
|
98bd6f0e45 | ||
|
|
40d1f700b5 | ||
|
|
a2ce1c4213 | ||
|
|
d42ba7ef4b | ||
|
|
721e23fd8a | ||
|
|
15dbfe423a | ||
|
|
f77b0d94d9 | ||
|
|
99c1bf1013 | ||
|
|
1a71cf89b4 | ||
|
|
3088cde9ba | ||
|
|
5d6e83c2e9 | ||
|
|
001ee4ca12 | ||
|
|
0e57952e06 | ||
|
|
12db867c54 | ||
|
|
d5c4f88533 | ||
|
|
65439346eb | ||
|
|
eb42a63845 | ||
|
|
4633cf17b6 | ||
|
|
b73de7cd88 | ||
|
|
169a17f7ac | ||
|
|
d913b16c55 | ||
|
|
915c70dcfa | ||
|
|
b2711aa8b4 | ||
|
|
9c00557474 | ||
|
|
5e06154ccb | ||
|
|
102f510ddb | ||
|
|
bd8d4e7e3f | ||
|
|
19196d70ce | ||
|
|
bdee2b94c2 |
No files matched your search
@@ -0,0 +1 @@
|
||||
github: majd
|
||||
@@ -1,147 +0,0 @@
|
||||
name: Distribute
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
get_version:
|
||||
name: Get version
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- name: Set output
|
||||
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-12
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Cache SwiftPM packages
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: .build/checkouts
|
||||
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
${{ runner.os }}-spm-
|
||||
- name: Inject version
|
||||
run: ./Scripts/version
|
||||
- name: Run tests
|
||||
run: swift test
|
||||
build_macos:
|
||||
name: Build (macOS)
|
||||
runs-on: macos-12
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Cache SwiftPM packages
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: .build/checkouts
|
||||
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
${{ runner.os }}-spm-
|
||||
- name: Inject version
|
||||
run: ./Scripts/version
|
||||
- name: Build
|
||||
run: make build-macos
|
||||
- name: Upload binary
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-macos-v${{ needs.get_version.outputs.version }}
|
||||
path: .build/ipatool
|
||||
if-no-files-found: error
|
||||
build_ios:
|
||||
name: Build (iOS)
|
||||
runs-on: macos-12
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Cache SwiftPM packages
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: .build/checkouts
|
||||
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
${{ runner.os }}-spm-
|
||||
- name: Inject version
|
||||
run: ./Scripts/version
|
||||
- name: Install dependencies
|
||||
run: brew install xcodegen ldid
|
||||
- name: Build
|
||||
run: make build-ios
|
||||
- name: Upload binary
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-ios-v${{ needs.get_version.outputs.version }}
|
||||
path: .build/ipatool
|
||||
if-no-files-found: error
|
||||
distribute:
|
||||
name: Distribute
|
||||
runs-on: ubuntu-20.04
|
||||
needs: [get_version, build_ios, build_macos]
|
||||
steps:
|
||||
- name: Download binary (macOS)
|
||||
uses: actions/download-artifact@v2
|
||||
with:
|
||||
name: ipatool-macos-v${{ needs.get_version.outputs.version }}
|
||||
path: ipatool-macos-v${{ needs.get_version.outputs.version }}
|
||||
- name: Archive binary (macOS)
|
||||
run: |
|
||||
mv ipatool-macos-v${{ needs.get_version.outputs.version }}/ipatool ipatool
|
||||
zip ipatool-macos-v${{ needs.get_version.outputs.version }}.zip ipatool
|
||||
rm ipatool
|
||||
- name: Upload release (macOS)
|
||||
uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-macos-v${{ needs.get_version.outputs.version }}.zip
|
||||
asset_name: ipatool-macos-v${{ needs.get_version.outputs.version }}.zip
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
- name: Download binary (iOS)
|
||||
uses: actions/download-artifact@v2
|
||||
with:
|
||||
name: ipatool-ios-v${{ needs.get_version.outputs.version }}
|
||||
path: ipatool-ios-v${{ needs.get_version.outputs.version }}
|
||||
- name: Archive binary (iOS)
|
||||
run: |
|
||||
mv ipatool-ios-v${{ needs.get_version.outputs.version }}/ipatool ipatool
|
||||
zip ipatool-ios-v${{ needs.get_version.outputs.version }}.zip ipatool
|
||||
rm ipatool
|
||||
- name: Upload release (iOS)
|
||||
uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-ios-v${{ needs.get_version.outputs.version }}.zip
|
||||
asset_name: ipatool-ios-v${{ needs.get_version.outputs.version }}.zip
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
- name: Checkout homebrew repo
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
repository: ${{ secrets.HOMEBREW_REPO }}
|
||||
path: repo
|
||||
ref: main
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
- name: Update homebrew repo
|
||||
run: |
|
||||
SHA256=$(sha256sum ipatool-macos-v${{ needs.get_version.outputs.version }}.zip | awk '{print $1}')
|
||||
cd repo
|
||||
sed -i "3s/.*/ sha256 \"$SHA256\"/" Casks/ipatool.rb
|
||||
sed -i "2s/.*/ version \"${{ needs.get_version.outputs.version }}\"/" Casks/ipatool.rb
|
||||
sed -i "5s/.*/ url \"https:\/\/github.com\/majd\/ipatool\/releases\/download\/v${{ needs.get_version.outputs.version }}\/ipatool-macos-v${{ needs.get_version.outputs.version }}.zip\"/" 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"
|
||||
@@ -0,0 +1,76 @@
|
||||
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.26.5"
|
||||
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.26.5"
|
||||
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.26.5"
|
||||
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.26.5"
|
||||
cache: true
|
||||
- run: brew install ldid cmake
|
||||
- run: ./tools/build-ios.sh
|
||||
@@ -1,50 +0,0 @@
|
||||
name: Dry Builds
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build_ios:
|
||||
name: Dry build (iOS)
|
||||
runs-on: macos-12
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Cache SwiftPM packages
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: .build/checkouts
|
||||
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
${{ runner.os }}-spm-
|
||||
- name: Install dependencies
|
||||
run: brew install xcodegen ldid
|
||||
- name: Inject version
|
||||
run: ./Scripts/version
|
||||
- name: Build
|
||||
run: |
|
||||
make build-ios
|
||||
file .build/ipatool
|
||||
build_macos:
|
||||
name: Dry build (macOS)
|
||||
runs-on: macos-12
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Cache SwiftPM packages
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: .build/checkouts
|
||||
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
${{ runner.os }}-spm-
|
||||
- name: Inject version
|
||||
run: ./Scripts/version
|
||||
- name: Build
|
||||
run: |
|
||||
make build-macos
|
||||
file .build/ipatool
|
||||
@@ -1,9 +1,6 @@
|
||||
name: Integration Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
@@ -11,44 +8,34 @@ on:
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-12
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Cache SwiftPM packages
|
||||
uses: actions/cache@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
path: .build/checkouts
|
||||
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
${{ runner.os }}-spm-
|
||||
- name: Inject version
|
||||
run: ./Scripts/version
|
||||
- name: Build
|
||||
run: make build-macos
|
||||
- name: Upload binary
|
||||
uses: actions/upload-artifact@v2
|
||||
go-version: "1.26.5"
|
||||
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: .build/ipatool
|
||||
path: ipatool
|
||||
if-no-files-found: error
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ${{ matrix.macos }}
|
||||
runs-on: macos-latest
|
||||
needs: [build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
macos: [macos-10.15, macos-11, macos-12]
|
||||
command: [auth, download, purchase, search]
|
||||
steps:
|
||||
- name: Download binary
|
||||
uses: actions/download-artifact@v2
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool
|
||||
path: ipatool-current
|
||||
- name: Update permissions
|
||||
run: chmod +x ./ipatool-current/ipatool
|
||||
- name: Run tests
|
||||
run: ./ipatool-current/ipatool ${{ matrix.command }} --help
|
||||
path: build
|
||||
- run: chmod +x ./build/ipatool
|
||||
- run: ./build/ipatool ${{ matrix.command }} --help
|
||||
@@ -0,0 +1,21 @@
|
||||
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.26.5"
|
||||
cache: true
|
||||
- run: go generate ./...
|
||||
- uses: golangci/golangci-lint-action@v8
|
||||
with:
|
||||
version: v2.9
|
||||
@@ -0,0 +1,266 @@
|
||||
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.26.5"
|
||||
cache: true
|
||||
- run: go generate ./...
|
||||
- run: go test -v -timeout 20m ./...
|
||||
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.26.5"
|
||||
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.26.5"
|
||||
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.26.5"
|
||||
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,31 +1,62 @@
|
||||
name: Unit Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
test-networking:
|
||||
name: Test Networking
|
||||
runs-on: macos-12
|
||||
cross_build_library:
|
||||
name: Cross-build Windows library consumer
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Cache SwiftPM packages
|
||||
uses: actions/cache@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
path: .build/checkouts
|
||||
key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
|
||||
${{ runner.os }}-spm-
|
||||
- name: Inject version
|
||||
run: ./Scripts/version
|
||||
- name: Build
|
||||
run: swift build
|
||||
- name: Run tests
|
||||
run: swift test --filter NetworkingTests
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- name: Build from an independent module without dependency replacements
|
||||
shell: bash
|
||||
env:
|
||||
GOWORK: "off"
|
||||
CGO_ENABLED: "0"
|
||||
run: |
|
||||
consumer_dir=$(mktemp -d)
|
||||
cd "$consumer_dir"
|
||||
go mod init example.com/ipatool-consumer
|
||||
go mod edit -require=github.com/majd/ipatool/v2@v2.0.0
|
||||
go mod edit -replace="github.com/majd/ipatool/v2=$GITHUB_WORKSPACE"
|
||||
cat > main.go <<'EOF'
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
)
|
||||
|
||||
func main() {
|
||||
_ = appstore.NewAppStore(appstore.Args{})
|
||||
if err := appstore.Prepare(context.Background()); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
EOF
|
||||
go mod tidy
|
||||
GOOS=windows GOARCH=amd64 go build -o consumer-amd64.exe .
|
||||
GOOS=windows GOARCH=arm64 go build -o consumer-arm64.exe .
|
||||
|
||||
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.26.5"
|
||||
cache: true
|
||||
- run: go generate ./...
|
||||
- run: go test -v -timeout 20m ./...
|
||||
+3
-70
@@ -1,74 +1,7 @@
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
.vscode/
|
||||
|
||||
# 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
|
||||
|
||||
## 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
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.build/
|
||||
Sources/CLI/Package.swift
|
||||
|
||||
### Xcode Patch ###
|
||||
*.xcodeproj/*
|
||||
!*.xcodeproj/project.pbxproj
|
||||
!*.xcodeproj/xcshareddata/
|
||||
!*.xcworkspace/contents.xcworkspacedata
|
||||
**/xcshareddata/WorkspaceSettings.xcsettings
|
||||
.idea/
|
||||
**/*_mock.go
|
||||
exp/
|
||||
@@ -0,0 +1,38 @@
|
||||
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$
|
||||
@@ -1,46 +0,0 @@
|
||||
disabled_rules:
|
||||
- cyclomatic_complexity
|
||||
- type_body_length
|
||||
- identifier_name
|
||||
- function_body_length
|
||||
|
||||
opt_in_rules:
|
||||
- multiline_function_chains
|
||||
- anyobject_protocol
|
||||
- overridden_super_call
|
||||
- prohibited_super_call
|
||||
- last_where
|
||||
- contains_over_first_not_nil
|
||||
- vertical_parameter_alignment_on_call
|
||||
- multiline_arguments
|
||||
- multiline_literal_brackets
|
||||
- closure_end_indentation
|
||||
- collection_alignment
|
||||
- reduce_into
|
||||
- explicit_init
|
||||
- static_operator
|
||||
- sorted_first_last
|
||||
- no_space_in_method_call
|
||||
- contains_over_filter_count
|
||||
- contains_over_filter_is_empty
|
||||
- empty_collection_literal
|
||||
- empty_count
|
||||
|
||||
type_name:
|
||||
validates_start_with_lowercase: false
|
||||
|
||||
nesting:
|
||||
type_level:
|
||||
warning: 3
|
||||
|
||||
line_length:
|
||||
warning: 120
|
||||
error: 120
|
||||
ignore_comments: true
|
||||
ignore_urls: true
|
||||
|
||||
file_length:
|
||||
warning: 1000
|
||||
error: 1000
|
||||
|
||||
reporter: "xcode"
|
||||
@@ -1,170 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1320"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "Networking"
|
||||
BuildableName = "Networking"
|
||||
BlueprintName = "Networking"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "StoreAPI"
|
||||
BuildableName = "StoreAPI"
|
||||
BlueprintName = "StoreAPI"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "ipatool"
|
||||
BuildableName = "ipatool"
|
||||
BlueprintName = "ipatool"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "NetworkingTests"
|
||||
BuildableName = "NetworkingTests"
|
||||
BlueprintName = "NetworkingTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CLI"
|
||||
BuildableName = "CLI"
|
||||
BlueprintName = "CLI"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "Persistence"
|
||||
BuildableName = "Persistence"
|
||||
BlueprintName = "Persistence"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "SwiftLint"
|
||||
BuildableName = "SwiftLint"
|
||||
BlueprintName = "SwiftLint"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "NetworkingTests"
|
||||
BuildableName = "NetworkingTests"
|
||||
BlueprintName = "NetworkingTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "ipatool"
|
||||
BuildableName = "ipatool"
|
||||
BlueprintName = "ipatool"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "ipatool"
|
||||
BuildableName = "ipatool"
|
||||
BlueprintName = "ipatool"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,77 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1320"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "Networking"
|
||||
BuildableName = "Networking"
|
||||
BlueprintName = "Networking"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "NetworkingTests"
|
||||
BuildableName = "NetworkingTests"
|
||||
BlueprintName = "NetworkingTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "Networking"
|
||||
BuildableName = "Networking"
|
||||
BlueprintName = "Networking"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,67 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1320"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "StoreAPI"
|
||||
BuildableName = "StoreAPI"
|
||||
BlueprintName = "StoreAPI"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "StoreAPI"
|
||||
BuildableName = "StoreAPI"
|
||||
BlueprintName = "StoreAPI"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,102 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1320"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "ipatool"
|
||||
BuildableName = "ipatool"
|
||||
BlueprintName = "ipatool"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "NetworkingTests"
|
||||
BuildableName = "NetworkingTests"
|
||||
BlueprintName = "NetworkingTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "NetworkingTests"
|
||||
BuildableName = "NetworkingTests"
|
||||
BlueprintName = "NetworkingTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "ipatool"
|
||||
BuildableName = "ipatool"
|
||||
BlueprintName = "ipatool"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "ipatool"
|
||||
BuildableName = "ipatool"
|
||||
BlueprintName = "ipatool"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,57 +0,0 @@
|
||||
prefix ?= /usr/local
|
||||
bindir = $(prefix)/bin
|
||||
|
||||
define ios_entitlements
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>ipatool</string>
|
||||
</array>
|
||||
<key>application-identifier</key>
|
||||
<string>ipatool</string>
|
||||
<key>platform-application</key>
|
||||
<true />
|
||||
<key>com.apple.private.security.container-required</key>
|
||||
<false />
|
||||
</dict>
|
||||
</plist>
|
||||
endef
|
||||
|
||||
lint:
|
||||
swiftlint lint --config .swiftlint.yml --path Sources/ Tests/m Plugins/
|
||||
|
||||
build-macos: lint
|
||||
swift build -c release --arch arm64
|
||||
swift build -c release --arch x86_64
|
||||
lipo -create -output .build/ipatool .build/arm64-apple-macosx/release/ipatool .build/x86_64-apple-macosx/release/ipatool
|
||||
|
||||
build-ios: lint
|
||||
xcodegen -s ios-project.yml
|
||||
xcodebuild archive -scheme CLI \
|
||||
-sdk iphoneos \
|
||||
-configuration Release \
|
||||
-derivedDataPath .build \
|
||||
-archivePath .build/ipatool.xcarchive \
|
||||
CODE_SIGN_IDENTITY='' \
|
||||
CODE_SIGNING_REQUIRED=NO \
|
||||
CODE_SIGN_ENTITLEMENTS='' \
|
||||
CODE_SIGNING_ALLOWED=NO
|
||||
cp .build/ipatool.xcarchive/Products/Applications/CLI.app/CLI .build/ipatool
|
||||
echo "$$ios_entitlements" > "${PWD}/.build/entitlements.xml"
|
||||
ldid -S.build/entitlements.xml ./.build/ipatool
|
||||
|
||||
install-macos: build
|
||||
install -d "$(bindir)"
|
||||
install ".build/ipatool" "$(bindir)"
|
||||
|
||||
uninstall-macos:
|
||||
rm -rf "$(bindir)/ipatool"
|
||||
|
||||
clean:
|
||||
rm -rf .build
|
||||
|
||||
.PHONY: build-macos install-macos uninstall-macos clean
|
||||
|
||||
export ios_entitlements
|
||||
@@ -1,32 +0,0 @@
|
||||
{
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "keychainaccess",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/kishikawakatsumi/KeychainAccess",
|
||||
"state" : {
|
||||
"branch" : "v4.2.2",
|
||||
"revision" : "84e546727d66f1adc5439debad16270d0fdd04e7"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-argument-parser",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-argument-parser",
|
||||
"state" : {
|
||||
"branch" : "1.1.2",
|
||||
"revision" : "f3c9084a71ef4376f2fabbdf1d3d90a49f1fabdb"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "zipfoundation",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/weichsel/ZIPFoundation",
|
||||
"state" : {
|
||||
"branch" : "0.9.14",
|
||||
"revision" : "7254c74b49cec2cb81520523ba993c671f71b066"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
// swift-tools-version:5.6
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "IPATool",
|
||||
platforms: [.macOS(.v10_11)],
|
||||
products: [
|
||||
.executable(name: "ipatool", targets: ["CLI"]),
|
||||
.library(name: "StoreAPI", targets: ["StoreAPI"]),
|
||||
.library(name: "Networking", targets: ["Networking"]),
|
||||
.library(name: "Persistence", targets: ["Persistence"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-argument-parser", revision: "1.1.2"),
|
||||
.package(url: "https://github.com/weichsel/ZIPFoundation", revision: "0.9.14"),
|
||||
.package(url: "https://github.com/kishikawakatsumi/KeychainAccess", revision: "v4.2.2")
|
||||
],
|
||||
targets: [
|
||||
// IPATool CLI
|
||||
.executableTarget(
|
||||
name: "CLI",
|
||||
dependencies: [
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
.byName(name: "Networking"),
|
||||
.byName(name: "StoreAPI"),
|
||||
.byName(name: "Persistence")
|
||||
],
|
||||
plugins: ["SwiftLint"]
|
||||
),
|
||||
|
||||
// StoreAPI
|
||||
.target(
|
||||
name: "StoreAPI",
|
||||
dependencies: [
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
.product(name: "ZIPFoundation", package: "ZIPFoundation"),
|
||||
.byName(name: "Networking"),
|
||||
],
|
||||
plugins: ["SwiftLint"]
|
||||
),
|
||||
|
||||
// Networking
|
||||
.target(
|
||||
name: "Networking",
|
||||
plugins: ["SwiftLint"]
|
||||
),
|
||||
.testTarget(
|
||||
name: "NetworkingTests",
|
||||
dependencies: ["Networking"],
|
||||
plugins: ["SwiftLint"]
|
||||
),
|
||||
|
||||
// Persistence
|
||||
.target(
|
||||
name: "Persistence",
|
||||
dependencies: [
|
||||
.byName(name: "KeychainAccess")
|
||||
],
|
||||
plugins: ["SwiftLint"]
|
||||
),
|
||||
|
||||
// SwiftLint
|
||||
.plugin(name: "SwiftLint", capability: .buildTool())
|
||||
]
|
||||
)
|
||||
@@ -1,51 +0,0 @@
|
||||
//
|
||||
// main.swift
|
||||
// SwiftLint
|
||||
//
|
||||
// Created by Majd Alfhaily on 15.06.22.
|
||||
//
|
||||
|
||||
import PackagePlugin
|
||||
import Foundation
|
||||
|
||||
@main
|
||||
struct SwiftLint: BuildToolPlugin {
|
||||
func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {
|
||||
let toolPath = try determinePath(forTool: "swiftlint")
|
||||
let configPath = context.package.directory.appending(".swiftlint.yml")
|
||||
|
||||
return [
|
||||
.buildCommand(
|
||||
displayName: "Run SwiftLint",
|
||||
executable: toolPath,
|
||||
arguments: [
|
||||
"lint",
|
||||
"--in-process-sourcekit",
|
||||
"--config",
|
||||
configPath.string,
|
||||
"--path",
|
||||
target.directory.string
|
||||
]
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
private func determinePath(forTool toolName: String) throws -> Path {
|
||||
let prefixes: [String] = [
|
||||
"/opt/homebrew/bin",
|
||||
"/usr/local/bin",
|
||||
"/usr/bin",
|
||||
"/bin"
|
||||
]
|
||||
|
||||
for path in prefixes where FileManager.default.fileExists(atPath: "\(path)/\(toolName)") {
|
||||
return Path("\(path)/\(toolName)")
|
||||
}
|
||||
|
||||
throw NSError(
|
||||
domain: Bundle.main.bundleIdentifier ?? String(describing: type(of: self)),
|
||||
code: 0,
|
||||
userInfo: [NSLocalizedDescriptionKey: "Could not find tool: \(toolName)."]
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,131 +1,103 @@
|
||||
# IPATool
|
||||
<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>
|
||||
|
||||
[](https://GitHub.com/majd/ipatool/releases/)
|
||||
[](https://github.com/majd/ipatool/blob/main/LICENSE)
|
||||
[](https://github.com/majd/ipatool/actions/workflows/unit-tests.yml)
|
||||
[](https://github.com/majd/ipatool/actions/workflows/integration-tests.yml)
|
||||

|
||||

|
||||
<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.
|
||||
|
||||

|
||||
|
||||
- [Requirements](#requirements)
|
||||
- [Installation](#installation)
|
||||
- [Manual](#manual)
|
||||
- [Homebrew](#homebrew)
|
||||
- [Usage](#usage)
|
||||
- [FAQ](https://github.com/majd/ipatool/wiki/FAQ)
|
||||
- [License](#license)
|
||||
<p align="center">
|
||||
<img src="./resources/demo.gif" alt="Demo">
|
||||
</p>
|
||||
|
||||
## Requirements
|
||||
|
||||
- macOS 10.11 or later.
|
||||
- Apple ID set up to use the App Store.
|
||||
- A supported operating system (macOS, Linux, Windows or iOS).
|
||||
- An Apple Account already configured to use the App Store.
|
||||
|
||||
## Installation
|
||||
|
||||
### Manual
|
||||
### Linux and Windows
|
||||
|
||||
You can grab the latest version of `ipatool` from [GitHub releases](https://github.com/majd/ipatool/releases).
|
||||
|
||||
### Homebrew
|
||||
### macOS
|
||||
|
||||
You can install `ipatool` using [Homebrew](https://brew.sh).
|
||||
|
||||
```
|
||||
$ brew tap majd/repo
|
||||
```shell
|
||||
$ brew install ipatool
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
To authenticate with the App Store, use the `auth` command.
|
||||
To get started, run the following command.
|
||||
|
||||
```
|
||||
OVERVIEW: Authenticate with the App Store.
|
||||
```text
|
||||
$ ipatool --help
|
||||
A cli tool for interacting with Apple's ipa files
|
||||
|
||||
USAGE: ipatool auth <subcommand>
|
||||
Usage:
|
||||
ipatool [command]
|
||||
|
||||
OPTIONS:
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
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
|
||||
mcp Serve App Store tools over MCP using stdio
|
||||
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
|
||||
|
||||
SUBCOMMANDS:
|
||||
login Login to the App Store.
|
||||
revoke Revoke your App Store credentials.
|
||||
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
|
||||
|
||||
See 'ipatool help auth <subcommand>' for detailed help.
|
||||
Use "ipatool [command] --help" for more information about a command.
|
||||
```
|
||||
|
||||
To search for apps on the App Store, use the `search` command.
|
||||
**Note:** the tool runs in interactive mode by default. Use the `--non-interactive` flag
|
||||
if running in an automated environment.
|
||||
|
||||
```
|
||||
OVERVIEW: Search for iOS apps available on the App Store.
|
||||
### MCP tools
|
||||
|
||||
USAGE: ipatool search <term> [--limit <limit>] [--country <country>] [--device-family <device-family>] [--log-level <log-level>]
|
||||
Run `ipatool auth login` in a terminal, then configure your MCP client to launch the stdio server:
|
||||
|
||||
ARGUMENTS:
|
||||
<term> The term to search for.
|
||||
|
||||
OPTIONS:
|
||||
-l, --limit <limit> The maximum amount of search results to retrieve.
|
||||
(default: 5)
|
||||
-c, --country <country> The two-letter (ISO 3166-1 alpha-2) country code for
|
||||
the iTunes Store. (default: US)
|
||||
-d, --device-family <device-family>
|
||||
The device family to limit the search query to.
|
||||
(default: iPhone)
|
||||
--log-level <log-level> The log level. (default: info)
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"ipatool": {
|
||||
"command": "ipatool",
|
||||
"args": ["mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
To obtain a license for an app, use the `purchase` command.
|
||||
## Compiling
|
||||
|
||||
```
|
||||
OVERVIEW: Obtain a license for the app from the App Store.
|
||||
The tool can be compiled using the Go toolchain.
|
||||
|
||||
USAGE: ipatool purchase --bundle-identifier <bundle-identifier> [--country <country>] [--device-family <device-family>] [--log-level <log-level>]
|
||||
|
||||
OPTIONS:
|
||||
-b, --bundle-identifier <bundle-identifier>
|
||||
The bundle identifier of the target iOS app.
|
||||
-c, --country <country> The two-letter (ISO 3166-1 alpha-2) country code for
|
||||
the iTunes Store. (default: US)
|
||||
-d, --device-family <device-family>
|
||||
The device family to limit the search query to.
|
||||
(default: iPhone)
|
||||
--log-level <log-level> The log level. (default: info)
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
```shell
|
||||
$ go build -o ipatool
|
||||
```
|
||||
|
||||
To download a copy of the ipa file, use the `download` command.
|
||||
Unit tests can be executed with the following commands.
|
||||
|
||||
```shell
|
||||
$ go generate ./...
|
||||
$ go test -v ./...
|
||||
```
|
||||
OVERVIEW: Download (encrypted) iOS app packages from the App Store.
|
||||
|
||||
USAGE: ipatool download --bundle-identifier <bundle-identifier> [--country <country>] [--device-family <device-family>] [--output <output>] [--log-level <log-level>] [--purchase]
|
||||
|
||||
OPTIONS:
|
||||
-b, --bundle-identifier <bundle-identifier>
|
||||
The bundle identifier of the target iOS app.
|
||||
-c, --country <country> The two-letter (ISO 3166-1 alpha-2) country code for
|
||||
the iTunes Store. (default: US)
|
||||
-d, --device-family <device-family>
|
||||
The device family to limit the search query to.
|
||||
(default: iPhone)
|
||||
-o, --output <output> The destination path of the downloaded app package.
|
||||
--log-level <log-level> The log level. (default: info)
|
||||
--purchase Obtain a license for the app if needed.
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
```
|
||||
|
||||
**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. Similarly, you can supply the 2FA code interactively or using the environment variable `IPATOOL_2FA_CODE`.
|
||||
|
||||
## License
|
||||
|
||||
IPATool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
|
||||
ipatool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
|
||||
@@ -1,13 +0,0 @@
|
||||
#!/bin/bash -e
|
||||
|
||||
VERSION=$(git describe --abbrev=0 --tags | cut -c 2-)
|
||||
|
||||
cat <<EOF >"$PWD/Sources/CLI/Package.swift"
|
||||
// Automatically generated
|
||||
|
||||
enum Package {
|
||||
static let version = "${VERSION}"
|
||||
}
|
||||
EOF
|
||||
|
||||
echo "Version ${VERSION}"
|
||||
@@ -1,207 +0,0 @@
|
||||
//
|
||||
// Auth.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 21.03.22.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import Networking
|
||||
import StoreAPI
|
||||
import Persistence
|
||||
|
||||
struct Auth: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(
|
||||
commandName: "auth",
|
||||
abstract: "Authenticate with the App Store.",
|
||||
subcommands: [Login.self, Revoke.self],
|
||||
defaultSubcommand: nil
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension Auth {
|
||||
struct Login: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Login to the App Store.")
|
||||
}
|
||||
|
||||
@Option(name: [.short, .customLong("email")], help: "The email address for the Apple ID.")
|
||||
private var emailArgument: String?
|
||||
|
||||
@Option(name: [.short, .customLong("password")], help: "The password for the Apple ID.")
|
||||
private var passwordArgument: String?
|
||||
|
||||
@Option(name: [.customLong("auth-code")], help: "The 2FA code for the Apple ID.")
|
||||
private var authCodeArgument: String?
|
||||
|
||||
@Option(name: [.long], help: "The log level.")
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
lazy var logger = ConsoleLogger(level: logLevel)
|
||||
}
|
||||
|
||||
struct Revoke: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Revoke your App Store credentials.")
|
||||
}
|
||||
|
||||
@Option(name: [.long], help: "The log level.")
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
lazy var logger = ConsoleLogger(level: logLevel)
|
||||
}
|
||||
}
|
||||
|
||||
extension Auth.Login {
|
||||
private mutating func email() -> String {
|
||||
if let email = emailArgument {
|
||||
return email
|
||||
} else if let email = ProcessInfo.processInfo.environment["IPATOOL_EMAIL"] {
|
||||
return email
|
||||
} else if let email = String(
|
||||
validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID email: ", level: .warning)))
|
||||
) {
|
||||
return email
|
||||
} else {
|
||||
logger.log("An Apple ID email address is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func password() -> String {
|
||||
if let password = passwordArgument {
|
||||
return password
|
||||
} else if let password = ProcessInfo.processInfo.environment["IPATOOL_PASSWORD"] {
|
||||
return password
|
||||
} else if let password = String(
|
||||
validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID password: ", level: .warning)))
|
||||
) {
|
||||
return password
|
||||
} else {
|
||||
logger.log("An Apple ID password is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func authCode() -> String {
|
||||
if let authCode = authCodeArgument {
|
||||
return authCode
|
||||
} else if let authCode = ProcessInfo.processInfo.environment["IPATOOL_2FA_CODE"] {
|
||||
return authCode
|
||||
} else if let authCode = String(
|
||||
validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter 2FA code: ", level: .warning)))
|
||||
) {
|
||||
return authCode
|
||||
} else {
|
||||
logger.log("A 2FA auth-code is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func authenticate(email: String, password: String) -> Account {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating App Store client...", level: .debug)
|
||||
let storeClient = StoreClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Authenticating with the App Store...", level: .info)
|
||||
let account = try storeClient.authenticate(email: email, password: password, code: nil)
|
||||
return Account(
|
||||
name: "\(account.firstName) \(account.lastName)",
|
||||
email: email,
|
||||
passwordToken: account.passwordToken,
|
||||
directoryServicesIdentifier: account.directoryServicesIdentifier
|
||||
)
|
||||
} catch {
|
||||
switch error {
|
||||
case StoreResponse.Error.codeRequired:
|
||||
do {
|
||||
let account = try storeClient.authenticate(email: email, password: password, code: authCode())
|
||||
return Account(
|
||||
name: "\(account.firstName) \(account.lastName)",
|
||||
email: email,
|
||||
passwordToken: account.passwordToken,
|
||||
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.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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mutating func run() throws {
|
||||
// Get Apple ID email
|
||||
let email: String = email()
|
||||
|
||||
// Get Apple ID password
|
||||
let password: String = password()
|
||||
|
||||
// Authenticate with the App Store
|
||||
let account: Account = authenticate(email: email, password: password)
|
||||
|
||||
// Store data in keychain
|
||||
do {
|
||||
let keychainStore = KeychainStore(service: "ipatool.service")
|
||||
try keychainStore.setValue(account, forKey: "account")
|
||||
|
||||
logger.log("Authenticated as '\(account.name)'.", level: .info)
|
||||
} catch {
|
||||
logger.log("Failed to save account data in keychain.", level: .error)
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Auth.Revoke {
|
||||
mutating func run() throws {
|
||||
let keychainStore = KeychainStore(service: "ipatool.service")
|
||||
|
||||
guard let account: Account = try keychainStore.value(forKey: "account") else {
|
||||
logger.log("No credentials available to revoke.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
try keychainStore.remove("account")
|
||||
logger.log("Revoked credentials for '\(account.name)'.", level: .info)
|
||||
}
|
||||
}
|
||||
@@ -1,290 +0,0 @@
|
||||
//
|
||||
// Download.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import Networking
|
||||
import StoreAPI
|
||||
import Persistence
|
||||
|
||||
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: [.customShort("c"), .customLong("country")],
|
||||
help: "The two-letter (ISO 3166-1 alpha-2) country code for the iTunes Store."
|
||||
)
|
||||
private var countryCode: String = "US"
|
||||
|
||||
@Option(name: [.short, .long], help: "The device family to limit the search query to.")
|
||||
private var deviceFamily: DeviceFamily = .phone
|
||||
|
||||
@Option(name: [.short, .long], help: "The destination path of the downloaded app package.")
|
||||
private var output: String?
|
||||
|
||||
@Option(name: [.long], help: "The log level.")
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
@Flag(name: .long, help: "Obtain a license for the app if needed.")
|
||||
private var purchase: Bool = false
|
||||
|
||||
lazy var logger = ConsoleLogger(level: logLevel)
|
||||
}
|
||||
|
||||
extension Download {
|
||||
private mutating func app(with bundleIdentifier: String, countryCode: String) -> iTunesResponse.Result {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log(
|
||||
"Querying the iTunes Store for '\(bundleIdentifier)' in country '\(countryCode)'...",
|
||||
level: .info
|
||||
)
|
||||
return try itunesClient.lookup(
|
||||
bundleIdentifier: bundleIdentifier,
|
||||
countryCode: countryCode,
|
||||
deviceFamily: deviceFamily
|
||||
)
|
||||
} 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)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func purchase(app: iTunesResponse.Result, account: Account) {
|
||||
guard app.price == 0 else {
|
||||
logger.log([
|
||||
"It is only possible to obtain a license for free apps.",
|
||||
"Purchase the app manually and run the \"download\" command again."
|
||||
].joined(separator: " "), level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating App Store client...", level: .debug)
|
||||
let storeClient = StoreClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Obtaining a license for '\(app.identifier)' from the App Store...", level: .info)
|
||||
try storeClient.purchase(
|
||||
identifier: "\(app.identifier)",
|
||||
directoryServicesIdentifier: account.directoryServicesIdentifier,
|
||||
passwordToken: account.passwordToken,
|
||||
countryCode: countryCode
|
||||
)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.purchaseFailed:
|
||||
logger.log("Purchase failed.", level: .error)
|
||||
case StoreClient.Error.duplicateLicense:
|
||||
logger.log("A license already exists for this item.", level: .error)
|
||||
case StoreResponse.Error.priceMismatch:
|
||||
logger.log("Price mismatch. It is only possible to obtain a license for free apps.", level: .error)
|
||||
case StoreResponse.Error.invalidCountry:
|
||||
logger.log([
|
||||
"The country provided does not match with the account you are using.",
|
||||
"Supply a valid country using the \"--country\" flag."
|
||||
].joined(separator: " "), level: .error)
|
||||
case StoreResponse.Error.passwordTokenExpired, StoreResponse.Error.passwordChanged:
|
||||
logger.log("Token expired. Login again using the \"auth\" command.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func item(
|
||||
from app: iTunesResponse.Result,
|
||||
account: Account,
|
||||
purchaseAttempted: Bool = false
|
||||
) -> StoreResponse.Item {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating App Store client...", level: .debug)
|
||||
let storeClient = StoreClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Requesting a signed copy of '\(app.identifier)' from the App Store...", level: .info)
|
||||
return 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:
|
||||
if !purchaseAttempted, purchase {
|
||||
logger.log("License is missing.", level: .info)
|
||||
|
||||
purchase(app: app, account: account)
|
||||
logger.log("Obtained a license for '\(app.identifier)'.", level: .debug)
|
||||
|
||||
return item(from: app, account: account, purchaseAttempted: true)
|
||||
} else {
|
||||
logger.log([
|
||||
"Your Apple ID does not have a license for this app.",
|
||||
"Use the \"purchase\" command or the \"--purchase\" to obtain a license."
|
||||
].joined(separator: " "), level: .error)
|
||||
}
|
||||
case StoreResponse.Error.invalidCountry:
|
||||
logger.log([
|
||||
"The country provided does not match with the account you are using.",
|
||||
"Supply a valid country using the \"--country\" flag."
|
||||
].joined(separator: " "), level: .error)
|
||||
case StoreResponse.Error.passwordTokenExpired, StoreResponse.Error.passwordChanged:
|
||||
logger.log("Token expired. Login again using the \"auth\" command.", level: .error)
|
||||
default:
|
||||
logger.log([
|
||||
"An unknown error has occurred.",
|
||||
"The token may have already expired - try loggin in again using the \"auth\" command."
|
||||
].joined(separator: " "), level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func download(item: StoreResponse.Item, to targetURL: URL) {
|
||||
logger.log("Creating download client...", level: .debug)
|
||||
let downloadClient = HTTPDownloadClient()
|
||||
|
||||
do {
|
||||
logger.log("Downloading app package...", level: .info)
|
||||
try downloadClient.download(from: item.url, to: targetURL) { [logger] progress in
|
||||
logger.log("Downloading app package... [\(Int((progress * 100).rounded()))%]",
|
||||
prefix: "\u{1B}[1A\u{1B}[K",
|
||||
level: .info)
|
||||
}
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
logger.log("An error has occurred while downloading the app package.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func applyPatches(item: StoreResponse.Item, email: String, path: String) {
|
||||
logger.log("Creating signature client...", level: .debug)
|
||||
let signatureClient = SignatureClient(fileManager: .default, filePath: path)
|
||||
|
||||
do {
|
||||
logger.log("Applying patches...", level: .info)
|
||||
try signatureClient.appendMetadata(item: item, email: email)
|
||||
try signatureClient.appendSignature(item: item)
|
||||
} catch {
|
||||
switch error {
|
||||
case SignatureClient.Error.fileNotFound:
|
||||
logger.log(
|
||||
"App uses old code signature version, falling back to alternative patching mechanism.",
|
||||
level: .debug
|
||||
)
|
||||
logger.log("The produced app package may not be compatible with modern iOS releases.", level: .info)
|
||||
applyOldPatches(item: item, email: email, path: path)
|
||||
default:
|
||||
logger.log("\(error)", level: .debug)
|
||||
logger.log("Failed to apply patches. The ipa file will be left incomplete.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func applyOldPatches(item: StoreResponse.Item, email: String, path: String) {
|
||||
logger.log("Creating signature client...", level: .debug)
|
||||
let signatureClient = SignatureClient(fileManager: .default, filePath: path)
|
||||
|
||||
do {
|
||||
logger.log("Applying fallback patches...", level: .info)
|
||||
try signatureClient.appendOldSignature(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)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func makeOutputPath(app: iTunesResponse.Result) -> String {
|
||||
let fileName: String = "/\(bundleIdentifier)_\(app.identifier)_v\(app.version)_\(Int.random(in: 100...999)).ipa"
|
||||
|
||||
guard let output = output else {
|
||||
return FileManager.default.currentDirectoryPath.appending(fileName)
|
||||
}
|
||||
|
||||
var isDirectory: ObjCBool = false
|
||||
FileManager.default.fileExists(atPath: output, isDirectory: &isDirectory)
|
||||
|
||||
return isDirectory.boolValue ? output.appending(fileName) : output
|
||||
}
|
||||
|
||||
mutating func validate() throws {
|
||||
guard let output = output else { return }
|
||||
|
||||
var isDirectory: ObjCBool = false
|
||||
guard !FileManager.default.fileExists(atPath: output, isDirectory: &isDirectory) || isDirectory.boolValue else {
|
||||
logger.log("A file already exists at \(output).", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func run() throws {
|
||||
// Authenticate with the App Store
|
||||
let keychainStore = KeychainStore(service: "ipatool.service")
|
||||
|
||||
guard let account: Account = try keychainStore.value(forKey: "account") else {
|
||||
logger.log("Authentication required. Run \"ipatool auth --help\" for help.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
logger.log("Authenticated as '\(account.name)'.", level: .info)
|
||||
|
||||
// Query for app
|
||||
let app: iTunesResponse.Result = app(with: bundleIdentifier, countryCode: countryCode)
|
||||
logger.log("Found app: \(app.name) (\(app.version)).", level: .debug)
|
||||
|
||||
// Query for store item
|
||||
let item: StoreResponse.Item = item(from: app, account: account)
|
||||
logger.log("Received a response of the signed copy: \(item.md5).", level: .debug)
|
||||
|
||||
// Generate file name
|
||||
let path = makeOutputPath(app: app)
|
||||
logger.log("Output path: \(path).", level: .debug)
|
||||
|
||||
// Download app package
|
||||
download(item: item, to: URL(fileURLWithPath: path))
|
||||
logger.log("Saved app package to \(URL(fileURLWithPath: path).lastPathComponent).", level: .info)
|
||||
|
||||
// Apply patches
|
||||
applyPatches(item: item, email: account.email, path: path)
|
||||
logger.log("Done.", level: .info)
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
//
|
||||
// IPATool.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
|
||||
struct IPATool: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return CommandConfiguration(
|
||||
commandName: "ipatool",
|
||||
abstract: "A cli tool for interacting with Apple's ipa files.",
|
||||
version: Package.version,
|
||||
subcommands: [Auth.self, Download.self, Purchase.self, Search.self]
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
//
|
||||
// Purchase.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.03.22.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import Networking
|
||||
import StoreAPI
|
||||
import Persistence
|
||||
|
||||
struct Purchase: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Obtain a license for the app from the App Store.")
|
||||
}
|
||||
|
||||
@Option(name: [.short, .long], help: "The bundle identifier of the target iOS app.")
|
||||
private var bundleIdentifier: String
|
||||
|
||||
@Option(
|
||||
name: [.customShort("c"), .customLong("country")],
|
||||
help: "The two-letter (ISO 3166-1 alpha-2) country code for the iTunes Store."
|
||||
)
|
||||
private var countryCode: String = "US"
|
||||
|
||||
@Option(name: [.short, .long], help: "The device family to limit the search query to.")
|
||||
private var deviceFamily: DeviceFamily = .phone
|
||||
|
||||
@Option(name: [.long], help: "The log level.")
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
lazy var logger = ConsoleLogger(level: logLevel)
|
||||
}
|
||||
|
||||
extension Purchase {
|
||||
private mutating func app(with bundleIdentifier: String) -> iTunesResponse.Result {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log(
|
||||
"Querying the iTunes Store for '\(bundleIdentifier)' in country '\(countryCode)'...",
|
||||
level: .info
|
||||
)
|
||||
let app = try itunesClient.lookup(
|
||||
bundleIdentifier: bundleIdentifier,
|
||||
countryCode: countryCode,
|
||||
deviceFamily: deviceFamily
|
||||
)
|
||||
|
||||
guard app.price == 0 else {
|
||||
logger.log("Only free apps are supported.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
return app
|
||||
} 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)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func purchase(app: iTunesResponse.Result, account: Account) {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating App Store client...", level: .debug)
|
||||
let storeClient = StoreClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Obtaining a license for '\(app.identifier)' from the App Store...", level: .info)
|
||||
try storeClient.purchase(
|
||||
identifier: "\(app.identifier)",
|
||||
directoryServicesIdentifier: account.directoryServicesIdentifier,
|
||||
passwordToken: account.passwordToken,
|
||||
countryCode: countryCode
|
||||
)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.purchaseFailed:
|
||||
logger.log("Purchase failed.", level: .error)
|
||||
case StoreClient.Error.duplicateLicense:
|
||||
logger.log("A license already exists for this item.", level: .error)
|
||||
case StoreResponse.Error.priceMismatch:
|
||||
logger.log("Price mismatch. It is only possible to obtain a license for free apps.", level: .error)
|
||||
case StoreResponse.Error.invalidCountry:
|
||||
logger.log([
|
||||
"The country provided does not match with the account you are using.",
|
||||
"Supply a valid country using the \"--country\" flag."
|
||||
].joined(separator: " "), level: .error)
|
||||
case StoreResponse.Error.passwordTokenExpired, StoreResponse.Error.passwordChanged:
|
||||
logger.log("Token expired. Login again using the \"auth\" command.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func run() throws {
|
||||
// Authenticate with the App Store
|
||||
let keychainStore = KeychainStore(service: "ipatool.service")
|
||||
|
||||
guard let account: Account = try keychainStore.value(forKey: "account") else {
|
||||
logger.log("Authentication required. Run \"ipatool auth --help\" for help.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
logger.log("Authenticated as '\(account.name)'.", level: .info)
|
||||
|
||||
// Query for app
|
||||
let app: iTunesResponse.Result = app(with: bundleIdentifier)
|
||||
logger.log("Found app: \(app.name) (\(app.version)).", level: .debug)
|
||||
|
||||
// Obtain a license
|
||||
purchase(app: app, account: account)
|
||||
logger.log("Obtained a license for '\(app.identifier)'.", level: .debug)
|
||||
logger.log("Done.", level: .info)
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
//
|
||||
// Search.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import Networking
|
||||
import StoreAPI
|
||||
|
||||
struct Search: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Search for iOS apps available on the App Store.")
|
||||
}
|
||||
|
||||
@Argument(help: "The term to search for.")
|
||||
private var term: String
|
||||
|
||||
@Option(name: [.short, .long], help: "The maximum amount of search results to retrieve.")
|
||||
private var limit: Int = 5
|
||||
|
||||
@Option(
|
||||
name: [.customShort("c"), .customLong("country")],
|
||||
help: "The two-letter (ISO 3166-1 alpha-2) country code for the iTunes Store."
|
||||
)
|
||||
private var countryCode: String = "US"
|
||||
|
||||
@Option(name: [.short, .long], help: "The device family to limit the search query to.")
|
||||
private var deviceFamily: DeviceFamily = .phone
|
||||
|
||||
@Option(name: [.long], help: "The log level.")
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
lazy var logger = ConsoleLogger(level: logLevel)
|
||||
}
|
||||
|
||||
extension Search {
|
||||
mutating func results(with term: String) -> [iTunesResponse.Result] {
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(session: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
logger.log("Searching for '\(term)' using the '\(countryCode)' store front...", level: .info)
|
||||
|
||||
do {
|
||||
let results = try itunesClient.search(
|
||||
term: term,
|
||||
limit: limit,
|
||||
countryCode: countryCode,
|
||||
deviceFamily: deviceFamily
|
||||
)
|
||||
|
||||
guard !results.isEmpty else {
|
||||
logger.log("No results found.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
return results
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func run() throws {
|
||||
// Search the iTunes store
|
||||
let results = results(with: term)
|
||||
|
||||
// Compile output
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
//
|
||||
// ConsoleLogger.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
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 }
|
||||
|
||||
switch level {
|
||||
case .error:
|
||||
fputs("\(compile(message, level: level))\n", stderr)
|
||||
default:
|
||||
print(compile(message, level: level))
|
||||
}
|
||||
}
|
||||
|
||||
func log(_ message: String, prefix: String, level: LogLevel) {
|
||||
guard level <= self.level else { return }
|
||||
switch level {
|
||||
case .error:
|
||||
fputs("\(prefix)\(compile(message, level: level))\n", stderr)
|
||||
default:
|
||||
print("\(prefix)\(compile(message, level: level))")
|
||||
}
|
||||
}
|
||||
|
||||
func compile(_ message: String, level: LogLevel) -> String {
|
||||
return "==> \(level.prefix)\(message)".trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
//
|
||||
// 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
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
//
|
||||
// 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)
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
//
|
||||
// Account.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 21.03.22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct Account: Codable {
|
||||
let name: String
|
||||
let email: String
|
||||
let passwordToken: String
|
||||
let directoryServicesIdentifier: String
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
//
|
||||
// main.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 15.06.22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
func disablePrintBuffering() {
|
||||
setbuf(stderr, nil)
|
||||
setbuf(stdout, nil)
|
||||
}
|
||||
|
||||
disablePrintBuffering()
|
||||
IPATool.main()
|
||||
@@ -1,86 +0,0 @@
|
||||
//
|
||||
// HTTPClient.swift
|
||||
// Networking
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public protocol HTTPClientInterface {
|
||||
func send(_ request: HTTPRequest) throws -> HTTPResponse
|
||||
}
|
||||
|
||||
public final class HTTPClient: HTTPClientInterface {
|
||||
private let session: URLSessionInterface
|
||||
|
||||
public init(session: URLSessionInterface) {
|
||||
self.session = session
|
||||
}
|
||||
|
||||
public func send(_ request: HTTPRequest) throws -> HTTPResponse {
|
||||
let request = try makeURLRequest(from: request)
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: (data: Data?, response: URLResponse?, error: Swift.Error?)
|
||||
|
||||
session
|
||||
.dataTask(with: request) { (data, response, error) in
|
||||
result = (data, response, error)
|
||||
semaphore.signal()
|
||||
}
|
||||
.resume()
|
||||
|
||||
semaphore.wait()
|
||||
|
||||
if let error = result.error {
|
||||
throw error
|
||||
}
|
||||
|
||||
guard let response = result.response as? HTTPURLResponse else {
|
||||
throw Error.invalidResponse(result.response)
|
||||
}
|
||||
|
||||
return HTTPResponse(statusCode: response.statusCode, data: result.data)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
//
|
||||
// HTTPDownloadClient.swift
|
||||
// Networking
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public protocol HTTPDownloadClientInterface {
|
||||
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void) throws
|
||||
}
|
||||
|
||||
public final class HTTPDownloadClient: NSObject, HTTPDownloadClientInterface {
|
||||
private var session: URLSession!
|
||||
private var progressHandler: ((Float) -> Void)?
|
||||
private var semaphore: DispatchSemaphore?
|
||||
private var targetURL: URL?
|
||||
private var result: Result<Void, Swift.Error>?
|
||||
|
||||
public override init() {
|
||||
super.init()
|
||||
self.session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
|
||||
}
|
||||
|
||||
public func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void) throws {
|
||||
assert(progressHandler == nil)
|
||||
assert(semaphore == nil)
|
||||
assert(targetURL == nil)
|
||||
|
||||
progressHandler = progress
|
||||
targetURL = target
|
||||
|
||||
semaphore = DispatchSemaphore(value: 0)
|
||||
session.downloadTask(with: source).resume()
|
||||
semaphore?.wait()
|
||||
|
||||
switch result {
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case .success:
|
||||
break
|
||||
case .none:
|
||||
preconditionFailure()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPDownloadClient: URLSessionDownloadDelegate {
|
||||
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Swift.Error?) {
|
||||
guard let error = error else {
|
||||
return
|
||||
}
|
||||
|
||||
defer {
|
||||
semaphore?.signal()
|
||||
progressHandler = nil
|
||||
semaphore = nil
|
||||
targetURL = nil
|
||||
}
|
||||
|
||||
result = .failure(error)
|
||||
}
|
||||
|
||||
public func urlSession(
|
||||
_ session: URLSession,
|
||||
downloadTask: URLSessionDownloadTask,
|
||||
didWriteData bytesWritten: Int64,
|
||||
totalBytesWritten: Int64,
|
||||
totalBytesExpectedToWrite: Int64
|
||||
) {
|
||||
progressHandler?(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
|
||||
}
|
||||
|
||||
public func urlSession(
|
||||
_ session: URLSession,
|
||||
downloadTask: URLSessionDownloadTask,
|
||||
didFinishDownloadingTo location: URL
|
||||
) {
|
||||
defer {
|
||||
semaphore?.signal()
|
||||
progressHandler = nil
|
||||
semaphore = nil
|
||||
targetURL = nil
|
||||
}
|
||||
|
||||
guard let target = targetURL else {
|
||||
result = .failure(Error.invalidTarget)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
try FileManager.default.moveItem(at: location, to: target)
|
||||
result = .success(())
|
||||
} catch {
|
||||
result = .failure(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPDownloadClient {
|
||||
enum Error: Swift.Error {
|
||||
case invalidTarget
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
//
|
||||
// HTTPEndpoint.swift
|
||||
// Networking
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public protocol HTTPEndpoint {
|
||||
var url: URL { get }
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
//
|
||||
// HTTPMethod.swift
|
||||
// Networking
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public enum HTTPMethod: String {
|
||||
case get = "GET"
|
||||
case post = "POST"
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
//
|
||||
// HTTPPayload.swift
|
||||
// Networking
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public enum HTTPPayload {
|
||||
case xml([String: String])
|
||||
case urlEncoding([String: String])
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
//
|
||||
// HTTPRequest.swift
|
||||
// Networking
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public protocol HTTPRequest {
|
||||
var method: HTTPMethod { get }
|
||||
var endpoint: HTTPEndpoint { get }
|
||||
var headers: [String: String] { get }
|
||||
var payload: HTTPPayload? { get }
|
||||
}
|
||||
|
||||
extension HTTPRequest {
|
||||
public var headers: [String: String] { [:] }
|
||||
public var payload: HTTPPayload? { nil }
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
//
|
||||
// HTTPResponse.swift
|
||||
// Networking
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public struct HTTPResponse {
|
||||
public let statusCode: Int
|
||||
public let data: Data?
|
||||
}
|
||||
|
||||
extension HTTPResponse {
|
||||
public 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 {
|
||||
public enum Decoder {
|
||||
case json
|
||||
case xml
|
||||
}
|
||||
|
||||
public enum Error: Swift.Error {
|
||||
case noData
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
//
|
||||
// URLSession.swift
|
||||
// Networking
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public protocol URLSessionDataTaskInterface {
|
||||
func resume()
|
||||
}
|
||||
|
||||
public protocol URLSessionInterface {
|
||||
func dataTask(
|
||||
with request: URLRequest,
|
||||
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
|
||||
) -> URLSessionDataTaskInterface
|
||||
}
|
||||
|
||||
extension URLSessionDataTask: URLSessionDataTaskInterface {}
|
||||
|
||||
extension URLSession: URLSessionInterface {
|
||||
public func dataTask(
|
||||
with request: URLRequest,
|
||||
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
|
||||
) -> URLSessionDataTaskInterface {
|
||||
let task: URLSessionDataTask = dataTask(with: request, completionHandler: completionHandler)
|
||||
return task
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
//
|
||||
// KeychainStore.swift
|
||||
// Persistence
|
||||
//
|
||||
// Created by Majd Alfhaily on 21.03.22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import KeychainAccess
|
||||
|
||||
public protocol KeychainStoreInterface {
|
||||
func value<T: Codable>(forKey itemKey: String) throws -> T?
|
||||
func setValue<T: Codable>(_ item: T, forKey itemKey: String) throws
|
||||
func remove(_ key: String) throws
|
||||
}
|
||||
|
||||
public class KeychainStore: KeychainStoreInterface {
|
||||
private let keychain: Keychain
|
||||
|
||||
public init(service: String) {
|
||||
self.keychain = Keychain(service: service)
|
||||
}
|
||||
|
||||
public func value<T: Codable>(forKey itemKey: String) throws -> T? {
|
||||
guard let data = try keychain.getData(itemKey) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return try JSONDecoder().decode(T.self, from: data)
|
||||
}
|
||||
|
||||
public func setValue<T: Codable>(_ item: T, forKey itemKey: String) throws {
|
||||
let data = try JSONEncoder().encode(item)
|
||||
try keychain.set(data, key: itemKey)
|
||||
}
|
||||
|
||||
public func remove(_ key: String) throws {
|
||||
try keychain.remove(key)
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
//
|
||||
// DeviceFamily.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Majd Alfhaily on 17.01.22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ArgumentParser
|
||||
|
||||
public enum DeviceFamily: String, ExpressibleByArgument {
|
||||
case phone = "iPhone"
|
||||
case pad = "iPad"
|
||||
|
||||
public var defaultValueDescription: String {
|
||||
return rawValue
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
//
|
||||
// Storefront.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Benjamin Altpeter on 20.03.22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
// https://web.archive.org/web/20191206001952/
|
||||
// https://affiliate.itunes.apple.com/resources/documentation/linking-to-the-itunes-music-store
|
||||
public enum Storefront: String, CaseIterable {
|
||||
case AE = "143481"
|
||||
case AG = "143540"
|
||||
case AI = "143538"
|
||||
case AM = "143524"
|
||||
case AO = "143564"
|
||||
case AR = "143505"
|
||||
case AT = "143445"
|
||||
case AU = "143460"
|
||||
case AZ = "143568"
|
||||
case BB = "143541"
|
||||
case BD = "143490"
|
||||
case BE = "143446"
|
||||
case BG = "143526"
|
||||
case BH = "143559"
|
||||
case BM = "143542"
|
||||
case BN = "143560"
|
||||
case BO = "143556"
|
||||
case BR = "143503"
|
||||
case BS = "143539"
|
||||
case BW = "143525"
|
||||
case BY = "143565"
|
||||
case BZ = "143555"
|
||||
case CA = "143455"
|
||||
case CH = "143459"
|
||||
case CI = "143527"
|
||||
case CL = "143483"
|
||||
case CN = "143465"
|
||||
case CO = "143501"
|
||||
case CR = "143495"
|
||||
case CY = "143557"
|
||||
case CZ = "143489"
|
||||
case DE = "143443"
|
||||
case DK = "143458"
|
||||
case DM = "143545"
|
||||
case DO = "143508"
|
||||
case DZ = "143563"
|
||||
case EC = "143509"
|
||||
case EE = "143518"
|
||||
case EG = "143516"
|
||||
case ES = "143454"
|
||||
case FI = "143447"
|
||||
case FR = "143442"
|
||||
case GB = "143444"
|
||||
case GD = "143546"
|
||||
case GH = "143573"
|
||||
case GR = "143448"
|
||||
case GT = "143504"
|
||||
case GY = "143553"
|
||||
case HK = "143463"
|
||||
case HN = "143510"
|
||||
case HR = "143494"
|
||||
case HU = "143482"
|
||||
case ID = "143476"
|
||||
case IE = "143449"
|
||||
case IL = "143491"
|
||||
case IN = "143467"
|
||||
case IS = "143558"
|
||||
case IT = "143450"
|
||||
case JM = "143511"
|
||||
case JO = "143528"
|
||||
case JP = "143462"
|
||||
case KE = "143529"
|
||||
case KN = "143548"
|
||||
case KR = "143466"
|
||||
case KW = "143493"
|
||||
case KY = "143544"
|
||||
case KZ = "143517"
|
||||
case LB = "143497"
|
||||
case LC = "143549"
|
||||
case LI = "143522"
|
||||
case LK = "143486"
|
||||
case LT = "143520"
|
||||
case LU = "143451"
|
||||
case LV = "143519"
|
||||
case MD = "143523"
|
||||
case MG = "143531"
|
||||
case MK = "143530"
|
||||
case ML = "143532"
|
||||
case MO = "143515"
|
||||
case MS = "143547"
|
||||
case MT = "143521"
|
||||
case MU = "143533"
|
||||
case MV = "143488"
|
||||
case MX = "143468"
|
||||
case MY = "143473"
|
||||
case NE = "143534"
|
||||
case NG = "143561"
|
||||
case NI = "143512"
|
||||
case NL = "143452"
|
||||
case NO = "143457"
|
||||
case NP = "143484"
|
||||
case NZ = "143461"
|
||||
case OM = "143562"
|
||||
case PA = "143485"
|
||||
case PE = "143507"
|
||||
case PH = "143474"
|
||||
case PK = "143477"
|
||||
case PL = "143478"
|
||||
case PT = "143453"
|
||||
case PY = "143513"
|
||||
case QA = "143498"
|
||||
case RO = "143487"
|
||||
case RS = "143500"
|
||||
case RU = "143469"
|
||||
case SA = "143479"
|
||||
case SE = "143456"
|
||||
case SG = "143464"
|
||||
case SI = "143499"
|
||||
case SK = "143496"
|
||||
case SN = "143535"
|
||||
case SR = "143554"
|
||||
case SV = "143506"
|
||||
case TC = "143552"
|
||||
case TH = "143475"
|
||||
case TN = "143536"
|
||||
case TR = "143480"
|
||||
case TT = "143551"
|
||||
case TW = "143470"
|
||||
case TZ = "143572"
|
||||
case UA = "143492"
|
||||
case UG = "143537"
|
||||
case US = "143441"
|
||||
case UY = "143514"
|
||||
case UZ = "143566"
|
||||
case VC = "143550"
|
||||
case VE = "143502"
|
||||
case VG = "143543"
|
||||
case VN = "143471"
|
||||
case YE = "143571"
|
||||
case ZA = "143472"
|
||||
|
||||
init?(countryCode: String) {
|
||||
guard let value = Storefront.allCases.first(where: { "\($0)" == countryCode }) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
self = value
|
||||
}
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
//
|
||||
// SignatureClient.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ZIPFoundation
|
||||
|
||||
public protocol SignatureClientInterface {
|
||||
func appendMetadata(item: StoreResponse.Item, email: String) throws
|
||||
func appendSignature(item: StoreResponse.Item) throws
|
||||
}
|
||||
|
||||
public final class SignatureClient: SignatureClientInterface {
|
||||
private let fileManager: FileManager
|
||||
private let filePath: String
|
||||
|
||||
public init(fileManager: FileManager, filePath: String) {
|
||||
self.fileManager = fileManager
|
||||
self.filePath = filePath
|
||||
}
|
||||
|
||||
public 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 metadataPath = NSTemporaryDirectory().appending("\(UUID().uuidString)/iTunesMetadata.plist")
|
||||
let metadataUrl = URL(fileURLWithPath: metadataPath)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
public func appendSignature(item: StoreResponse.Item) throws {
|
||||
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
|
||||
throw Error.invalidArchive
|
||||
}
|
||||
|
||||
try appendSignatureFromManfiest(forItem: item, inArchive: archive)
|
||||
}
|
||||
|
||||
public func appendOldSignature(item: StoreResponse.Item) throws {
|
||||
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
|
||||
throw Error.invalidArchive
|
||||
}
|
||||
|
||||
try appendOldSignature(forItem: item, inArchive: archive)
|
||||
}
|
||||
|
||||
private func appendSignatureFromManfiest(forItem item: StoreResponse.Item, inArchive archive: Archive) throws {
|
||||
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: {
|
||||
return $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 appendOldSignature(forItem item: StoreResponse.Item, inArchive archive: Archive) throws {
|
||||
guard let infoEntry = archive.first(where: { $0.path.hasSuffix(".app/Info.plist") }) else {
|
||||
throw Error.invalidAppBundle
|
||||
}
|
||||
|
||||
let temporaryInfoURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
|
||||
_ = try archive.extract(infoEntry, to: temporaryInfoURL, skipCRC32: true)
|
||||
let infoData = try Data(contentsOf: temporaryInfoURL)
|
||||
|
||||
guard let infoPlist = try PropertyListSerialization.propertyList(
|
||||
from: infoData,
|
||||
format: nil
|
||||
) as? [String: Any] else {
|
||||
throw Error.invalidAppBundle
|
||||
}
|
||||
|
||||
guard let executableName = infoPlist["CFBundleExecutable"] as? String else {
|
||||
throw Error.invalidAppBundle
|
||||
}
|
||||
|
||||
let appBundleName = URL(fileURLWithPath: infoEntry.path)
|
||||
.deletingLastPathComponent()
|
||||
.deletingPathExtension()
|
||||
.lastPathComponent
|
||||
|
||||
guard let signatureItem = item.signatures.first(where: { $0.id == 0 }) else {
|
||||
throw Error.invalidSignature
|
||||
}
|
||||
|
||||
let signatureBaseUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
|
||||
let signatureUrl = signatureBaseUrl
|
||||
.appendingPathComponent("Payload")
|
||||
.appendingPathComponent(appBundleName)
|
||||
.appendingPathExtension("app")
|
||||
.appendingPathComponent("SC_Info")
|
||||
.appendingPathComponent(executableName)
|
||||
.appendingPathExtension("sinf")
|
||||
|
||||
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"
|
||||
}
|
||||
}
|
||||
|
||||
public enum Error: Swift.Error {
|
||||
case invalidArchive
|
||||
case invalidAppBundle
|
||||
case invalidSignature
|
||||
case fileNotFound(String)
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
//
|
||||
// StoreClient.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Networking
|
||||
|
||||
public protocol StoreClientInterface {
|
||||
func authenticate(email: String, password: String, code: String?) throws -> StoreResponse.Account
|
||||
func item(identifier: String, directoryServicesIdentifier: String) throws -> StoreResponse.Item
|
||||
func purchase(
|
||||
identifier: String,
|
||||
directoryServicesIdentifier: String,
|
||||
passwordToken: String,
|
||||
countryCode: String
|
||||
) throws
|
||||
}
|
||||
|
||||
public final class StoreClient: StoreClientInterface {
|
||||
private let httpClient: HTTPClient
|
||||
|
||||
public init(httpClient: HTTPClient) {
|
||||
self.httpClient = httpClient
|
||||
}
|
||||
|
||||
public func authenticate(email: String, password: String, code: String?) throws -> StoreResponse.Account {
|
||||
try authenticate(email: email, password: password, code: code, isFirstAttempt: true)
|
||||
}
|
||||
|
||||
public func item(identifier: String, directoryServicesIdentifier: String) throws -> StoreResponse.Item {
|
||||
let request = StoreRequest.download(
|
||||
appIdentifier: identifier,
|
||||
directoryServicesIdentifier: directoryServicesIdentifier
|
||||
)
|
||||
let response = try httpClient.send(request)
|
||||
let storeResponse = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch storeResponse {
|
||||
case let .item(item):
|
||||
return item
|
||||
case let .failure(error):
|
||||
throw error
|
||||
default:
|
||||
throw Error.invalidResponse
|
||||
}
|
||||
}
|
||||
|
||||
public func purchase(
|
||||
identifier: String,
|
||||
directoryServicesIdentifier: String,
|
||||
passwordToken: String,
|
||||
countryCode: String
|
||||
) throws {
|
||||
let request = StoreRequest.purchase(
|
||||
appIdentifier: identifier,
|
||||
directoryServicesIdentifier: directoryServicesIdentifier,
|
||||
passwordToken: passwordToken,
|
||||
countryCode: countryCode
|
||||
)
|
||||
|
||||
let response = try httpClient.send(request)
|
||||
|
||||
// Returns status code 500 if the Apple ID already contains a license
|
||||
switch response.statusCode {
|
||||
case 500:
|
||||
throw Error.duplicateLicense
|
||||
default:
|
||||
let response = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch response {
|
||||
case let .purchase(receipt):
|
||||
guard receipt.statusCode == 0, receipt.status == .success else {
|
||||
throw Error.purchaseFailed
|
||||
}
|
||||
case let .failure(error):
|
||||
throw error
|
||||
default:
|
||||
throw Error.invalidResponse
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func authenticate(email: String,
|
||||
password: String,
|
||||
code: String?,
|
||||
isFirstAttempt: Bool) throws -> StoreResponse.Account {
|
||||
let request = StoreRequest.authenticate(email: email, password: password, code: code)
|
||||
let response = try httpClient.send(request)
|
||||
let decoded = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch decoded {
|
||||
case let .account(account):
|
||||
return account
|
||||
case let .failure(error):
|
||||
switch error {
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
if isFirstAttempt {
|
||||
return try authenticate(email: email, password: password, code: code, isFirstAttempt: false)
|
||||
}
|
||||
|
||||
throw error
|
||||
default:
|
||||
throw error
|
||||
}
|
||||
default:
|
||||
throw Error.invalidResponse
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreClient {
|
||||
public enum Error: Swift.Error {
|
||||
case timeout
|
||||
case invalidResponse
|
||||
case purchaseFailed
|
||||
case duplicateLicense
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
//
|
||||
// StoreEndpoint.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Networking
|
||||
|
||||
enum StoreEndpoint {
|
||||
case authenticate(prefix: String, guid: String)
|
||||
case download(guid: String)
|
||||
case purchase
|
||||
}
|
||||
|
||||
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"
|
||||
case .purchase:
|
||||
return "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)"
|
||||
case .purchase:
|
||||
return "/WebObjects/MZBuy.woa/wa/buyProduct"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
//
|
||||
// StoreRequest.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Networking
|
||||
|
||||
enum StoreRequest {
|
||||
case authenticate(email: String, password: String, code: String? = nil)
|
||||
case download(appIdentifier: String, directoryServicesIdentifier: String)
|
||||
case purchase(
|
||||
appIdentifier: String,
|
||||
directoryServicesIdentifier: String,
|
||||
passwordToken: String,
|
||||
countryCode: 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)
|
||||
case .purchase:
|
||||
return StoreEndpoint.purchase
|
||||
}
|
||||
}
|
||||
|
||||
var method: HTTPMethod {
|
||||
return .post
|
||||
}
|
||||
|
||||
var headers: [String: String] {
|
||||
var headers: [String: String] = [
|
||||
"User-Agent": "Configurator/2.15 (Macintosh; OS X 11.0.0; 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
|
||||
case let .purchase(_, directoryServicesIdentifier, passwordToken, countryCode):
|
||||
headers["X-Dsid"] = directoryServicesIdentifier
|
||||
headers["iCloud-DSID"] = directoryServicesIdentifier
|
||||
headers["Content-Type"] = "application/x-apple-plist"
|
||||
headers["X-Apple-Store-Front"] = Storefront(countryCode: countryCode)?.rawValue
|
||||
headers["X-Token"] = passwordToken
|
||||
}
|
||||
|
||||
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)"
|
||||
])
|
||||
case let .purchase(appIdentifier, _, _, _):
|
||||
return .xml([
|
||||
"appExtVrsId": "0",
|
||||
"hasAskedToFulfillPreorder": "true",
|
||||
"buyWithoutAuthorization": "true",
|
||||
"hasDoneAgeCheck": "true",
|
||||
"guid": guid,
|
||||
"needDiv": "0",
|
||||
"origPage": "Software-" + appIdentifier,
|
||||
"origPageLocation": "Buy",
|
||||
"price": "0",
|
||||
"pricingParameters": "STDQ",
|
||||
"productType": "C",
|
||||
"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()
|
||||
}
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
//
|
||||
// StoreResponse.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public enum StoreResponse {
|
||||
case failure(error: Swift.Error)
|
||||
case account(Account)
|
||||
case item(Item)
|
||||
case purchase(Receipt)
|
||||
|
||||
public enum Error: Int, Swift.Error {
|
||||
case unknownError = 0
|
||||
case passwordChanged = 2002
|
||||
case genericError = 5002
|
||||
case codeRequired = 1
|
||||
case invalidLicense = 9610
|
||||
case invalidCredentials = -5000
|
||||
case invalidAccount = 5001
|
||||
case invalidItem = -10000
|
||||
case lockedAccount = -10001
|
||||
case invalidCountry = -128
|
||||
case passwordTokenExpired = 2034
|
||||
case priceMismatch = 2019
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreResponse: Decodable {
|
||||
public 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 passwordToken = try container.decode(String.self, forKey: .passwordToken)
|
||||
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(
|
||||
Account(
|
||||
firstName: firstName,
|
||||
lastName: lastName,
|
||||
directoryServicesIdentifier: directoryServicesIdentifier,
|
||||
passwordToken: passwordToken
|
||||
)
|
||||
)
|
||||
} else if let items = try container.decodeIfPresent([Item].self, forKey: .items), let item = items.first {
|
||||
self = .item(item)
|
||||
} else if container.contains(.statusCode) {
|
||||
let statusCode = try container.decode(Int.self, forKey: .statusCode)
|
||||
let statusType = try container.decode(String.self, forKey: .statusType)
|
||||
|
||||
self = .purchase(Receipt(statusCode: statusCode, status: Receipt.Status(rawValue: statusType)))
|
||||
} 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."
|
||||
].joined(separator: " "):
|
||||
self = .failure(error: Error.codeRequired)
|
||||
case "MZFinance.BadLogin.Configurator_message":
|
||||
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)."
|
||||
].joined(separator: " "):
|
||||
self = .failure(error: Error.lockedAccount)
|
||||
default:
|
||||
self = .failure(error: Error.unknownError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case directoryServicesIdentifier = "dsPersonId"
|
||||
case passwordToken = "passwordToken"
|
||||
case message = "customerMessage"
|
||||
case items = "songList"
|
||||
case error = "failureType"
|
||||
case account = "accountInfo"
|
||||
case statusCode = "status"
|
||||
case statusType = "jingleDocType"
|
||||
}
|
||||
|
||||
private enum AccountInfoCodingKeys: String, CodingKey {
|
||||
case address
|
||||
}
|
||||
|
||||
private enum AddressCodingKeys: String, CodingKey {
|
||||
case firstName
|
||||
case lastName
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Account
|
||||
|
||||
extension StoreResponse {
|
||||
public struct Account {
|
||||
public let firstName: String
|
||||
public let lastName: String
|
||||
public let directoryServicesIdentifier: String
|
||||
public let passwordToken: String
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Item
|
||||
|
||||
extension StoreResponse {
|
||||
public struct Item: Decodable {
|
||||
public let url: URL
|
||||
public let md5: String
|
||||
public let signatures: [Signature]
|
||||
public let metadata: [String: Any]
|
||||
|
||||
public 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, 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)
|
||||
}
|
||||
}
|
||||
|
||||
public struct Signature: Decodable {
|
||||
public let id: Int
|
||||
public let sinf: Data
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case url = "URL"
|
||||
case metadata
|
||||
case md5
|
||||
case signatures = "sinfs"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Receipt
|
||||
|
||||
extension StoreResponse {
|
||||
public struct Receipt {
|
||||
public let statusCode: Int
|
||||
public let status: Status
|
||||
|
||||
public enum Status {
|
||||
case success
|
||||
case failure
|
||||
|
||||
init(rawValue: String) {
|
||||
self = rawValue == "purchaseSuccess" ? .success : .failure
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
//
|
||||
// iTunesClient.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Networking
|
||||
|
||||
public protocol iTunesClientInterface {
|
||||
func lookup(
|
||||
bundleIdentifier: String,
|
||||
countryCode: String,
|
||||
deviceFamily: DeviceFamily
|
||||
) throws -> iTunesResponse.Result
|
||||
|
||||
func search(
|
||||
term: String,
|
||||
limit: Int,
|
||||
countryCode: String,
|
||||
deviceFamily: DeviceFamily
|
||||
) throws -> [iTunesResponse.Result]
|
||||
}
|
||||
|
||||
public final class iTunesClient: iTunesClientInterface {
|
||||
private let httpClient: HTTPClient
|
||||
|
||||
public init(httpClient: HTTPClient) {
|
||||
self.httpClient = httpClient
|
||||
}
|
||||
|
||||
public func lookup(
|
||||
bundleIdentifier: String,
|
||||
countryCode: String,
|
||||
deviceFamily: DeviceFamily
|
||||
) throws -> iTunesResponse.Result {
|
||||
let request = iTunesRequest.lookup(
|
||||
bundleIdentifier: bundleIdentifier,
|
||||
countryCode: countryCode,
|
||||
deviceFamily: deviceFamily
|
||||
)
|
||||
let response = try httpClient.send(request)
|
||||
let decoded = try response.decode(iTunesResponse.self, as: .json)
|
||||
guard let result = decoded.results.first else { throw Error.appNotFound }
|
||||
return result
|
||||
}
|
||||
|
||||
public func search(
|
||||
term: String,
|
||||
limit: Int,
|
||||
countryCode: String,
|
||||
deviceFamily: DeviceFamily
|
||||
) throws -> [iTunesResponse.Result] {
|
||||
let request = iTunesRequest.search(
|
||||
term: term,
|
||||
limit: limit,
|
||||
countryCode: countryCode,
|
||||
deviceFamily: deviceFamily
|
||||
)
|
||||
let response = try httpClient.send(request)
|
||||
let decoded = try response.decode(iTunesResponse.self, as: .json)
|
||||
return decoded.results
|
||||
}
|
||||
}
|
||||
|
||||
extension iTunesClient {
|
||||
public enum Error: Swift.Error {
|
||||
case timeout
|
||||
case appNotFound
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
//
|
||||
// iTunesEndpoint.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Networking
|
||||
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
//
|
||||
// iTunesRequest.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Networking
|
||||
|
||||
enum iTunesRequest {
|
||||
case search(term: String, limit: Int, countryCode: String, deviceFamily: DeviceFamily = .phone)
|
||||
case lookup(bundleIdentifier: String, countryCode: String, deviceFamily: DeviceFamily = .phone)
|
||||
}
|
||||
|
||||
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, countryCode, deviceFamily):
|
||||
return .urlEncoding([
|
||||
"media": "software",
|
||||
"bundleId": bundleIdentifier,
|
||||
"limit": "1",
|
||||
"country": countryCode,
|
||||
"entity": deviceFamily.entity
|
||||
])
|
||||
case let .search(term, limit, countryCode, deviceFamily):
|
||||
return .urlEncoding([
|
||||
"media": "software",
|
||||
"term": term,
|
||||
"limit": "\(limit)",
|
||||
"country": countryCode,
|
||||
"entity": deviceFamily.entity
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension DeviceFamily {
|
||||
var entity: String {
|
||||
switch self {
|
||||
case .phone:
|
||||
return "software"
|
||||
case .pad:
|
||||
return "iPadSoftware"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
//
|
||||
// iTunesResponse.swift
|
||||
// StoreAPI
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public struct iTunesResponse {
|
||||
let results: [Result]
|
||||
let count: Int
|
||||
}
|
||||
|
||||
extension iTunesResponse {
|
||||
public struct Result {
|
||||
public let bundleIdentifier: String
|
||||
public let version: String
|
||||
public let identifier: Int
|
||||
public let name: String
|
||||
public let price: Float
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
case price
|
||||
}
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
//
|
||||
// HTTPClientTests.swift
|
||||
// NetworkingTests
|
||||
//
|
||||
// Created by Majd Alfhaily on 17.01.22.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import Networking
|
||||
|
||||
final class HTTPClientTests: XCTestCase {
|
||||
private var sut: HTTPClient!
|
||||
private var session: URLSessionMock!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
|
||||
session = URLSessionMock()
|
||||
sut = HTTPClient(session: session)
|
||||
}
|
||||
|
||||
func test_GET_success_returnsValidResposne() throws {
|
||||
session.onDataTask = { request in
|
||||
let url = try XCTUnwrap(request.url?.absoluteString)
|
||||
XCTAssertTrue(url.hasPrefix("https://api.example.com"))
|
||||
XCTAssertEqual(request.httpMethod, "GET")
|
||||
|
||||
let data = try XCTUnwrap("foo".data(using: .utf8))
|
||||
let response = HTTPURLResponse(
|
||||
url: URL(string: "https://example.com")!,
|
||||
mimeType: nil,
|
||||
expectedContentLength: 0,
|
||||
textEncodingName: nil
|
||||
)
|
||||
return (data, response)
|
||||
}
|
||||
|
||||
let response = try sut.send(TestRequest.get(nil))
|
||||
let data = try XCTUnwrap(response.data)
|
||||
XCTAssertEqual(String(data: data, encoding: .utf8), "foo")
|
||||
}
|
||||
|
||||
func test_GET_failure_returnsInvalidResposne() throws {
|
||||
session.onDataTask = { request in
|
||||
let url = try XCTUnwrap(request.url?.absoluteString)
|
||||
XCTAssertTrue(url.hasPrefix("https://api.example.com"))
|
||||
XCTAssertEqual(request.httpMethod, "GET")
|
||||
|
||||
let data = try XCTUnwrap("foo".data(using: .utf8))
|
||||
|
||||
let response = URLResponse(
|
||||
url: URL(string: "https://example.com")!,
|
||||
mimeType: nil,
|
||||
expectedContentLength: 0,
|
||||
textEncodingName: nil
|
||||
)
|
||||
return (data, response)
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try sut.send(TestRequest.get(nil))
|
||||
XCTFail("Call succeeded while expecting a failure.")
|
||||
} catch {
|
||||
XCTAssertNotNil(error)
|
||||
}
|
||||
}
|
||||
|
||||
func test_POST_xmlEncoding_returnsValidResponse() throws {
|
||||
session.onDataTask = { request in
|
||||
let url = try XCTUnwrap(request.url?.absoluteString)
|
||||
XCTAssertTrue(url.hasPrefix("https://api.example.com"))
|
||||
XCTAssertEqual(request.httpMethod, "POST")
|
||||
|
||||
let data = try XCTUnwrap(request.httpBody)
|
||||
let decoded = try XCTUnwrap(
|
||||
PropertyListSerialization.propertyList(
|
||||
from: data,
|
||||
options: [],
|
||||
format: nil
|
||||
) as? [String: String]
|
||||
)
|
||||
|
||||
XCTAssertEqual(decoded["foo"], "bar")
|
||||
|
||||
let response = HTTPURLResponse(
|
||||
url: URL(string: "https://example.com")!,
|
||||
mimeType: nil,
|
||||
expectedContentLength: 0,
|
||||
textEncodingName: nil
|
||||
)
|
||||
return (data, response)
|
||||
}
|
||||
|
||||
_ = try sut.send(TestRequest.post(.xml(["foo": "bar"])))
|
||||
}
|
||||
|
||||
func test_GET_urlEncoding_returnsValidResponse() throws {
|
||||
session.onDataTask = { request in
|
||||
let url = try XCTUnwrap(request.url?.absoluteString)
|
||||
XCTAssertTrue(url.hasPrefix("https://api.example.com"))
|
||||
XCTAssertTrue(url.hasSuffix("?foo=bar"))
|
||||
XCTAssertEqual(request.httpMethod, "GET")
|
||||
|
||||
let response = HTTPURLResponse(
|
||||
url: URL(string: "https://example.com")!,
|
||||
mimeType: nil,
|
||||
expectedContentLength: 0,
|
||||
textEncodingName: nil
|
||||
)
|
||||
return (Data(), response)
|
||||
}
|
||||
|
||||
_ = try sut.send(TestRequest.get(.urlEncoding(["foo": "bar"])))
|
||||
}
|
||||
|
||||
func test_POST_urlEncoding_returnsValidResponse() throws {
|
||||
session.onDataTask = { request in
|
||||
let url = try XCTUnwrap(request.url?.absoluteString)
|
||||
let data = try XCTUnwrap(request.httpBody)
|
||||
let decoded = String(data: data, encoding: .utf8)
|
||||
let headerValue = try XCTUnwrap(request.allHTTPHeaderFields?["X-Test"])
|
||||
|
||||
XCTAssertTrue(url.hasPrefix("https://api.example.com"))
|
||||
XCTAssertEqual(decoded, "foo=bar")
|
||||
XCTAssertEqual(request.httpMethod, "POST")
|
||||
XCTAssertEqual(headerValue, "true")
|
||||
|
||||
let response = HTTPURLResponse(
|
||||
url: URL(string: "https://example.com")!,
|
||||
mimeType: nil,
|
||||
expectedContentLength: 0,
|
||||
textEncodingName: nil
|
||||
)
|
||||
return (Data(), response)
|
||||
}
|
||||
|
||||
_ = try sut.send(TestRequest.post(.urlEncoding(["foo": "bar"])))
|
||||
}
|
||||
}
|
||||
|
||||
private enum TestRequest: HTTPRequest {
|
||||
case get(HTTPPayload?)
|
||||
case post(HTTPPayload)
|
||||
|
||||
var method: HTTPMethod {
|
||||
switch self {
|
||||
case .get:
|
||||
return .get
|
||||
case .post:
|
||||
return .post
|
||||
}
|
||||
}
|
||||
|
||||
var endpoint: HTTPEndpoint {
|
||||
switch self {
|
||||
case .get, .post:
|
||||
return TestEndpoint.generic
|
||||
}
|
||||
}
|
||||
|
||||
var payload: HTTPPayload? {
|
||||
switch self {
|
||||
case let .get(payload):
|
||||
return payload
|
||||
case let .post(payload):
|
||||
return payload
|
||||
}
|
||||
}
|
||||
|
||||
var headers: [String: String] {
|
||||
switch self {
|
||||
case .get, .post:
|
||||
return ["X-Test": "true"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum TestEndpoint: HTTPEndpoint {
|
||||
case generic
|
||||
|
||||
var url: URL {
|
||||
switch self {
|
||||
case .generic:
|
||||
return URL(string: "https://api.example.com/\(UUID().uuidString)")!
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
//
|
||||
// HTTPDownloadClient.swift
|
||||
// NetworkingTests
|
||||
//
|
||||
// Created by Majd Alfhaily on 17.01.22.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import Networking
|
||||
|
||||
final class HTTPDownloadClientTests: XCTestCase {
|
||||
private var sut: HTTPDownloadClient!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
|
||||
sut = HTTPDownloadClient()
|
||||
}
|
||||
|
||||
func test_download_success_returnsValidResponse() throws {
|
||||
let source = try XCTUnwrap(URL(string: "https://proof.ovh.net/files/1Mb.dat"))
|
||||
let target = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
|
||||
var lastValue: Float = 0
|
||||
|
||||
try sut.download(from: source, to: target) { value in
|
||||
XCTAssertGreaterThanOrEqual(value, lastValue)
|
||||
lastValue = value
|
||||
}
|
||||
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: target.path))
|
||||
}
|
||||
|
||||
func test_download_failure_throwsError() throws {
|
||||
let source = try XCTUnwrap(URL(string: "https://\(UUID().uuidString).test"))
|
||||
let target = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
|
||||
|
||||
do {
|
||||
try sut.download(from: source, to: target) { _ in }
|
||||
} catch {
|
||||
XCTAssertNotNil(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
//
|
||||
// HTTPResponseTests.swift
|
||||
// NetworkingTests
|
||||
//
|
||||
// Created by Majd Alfhaily on 17.01.22.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import Networking
|
||||
|
||||
final class HTTPResponseTests: XCTestCase {
|
||||
func test_decode_jsonData_returnsObject() throws {
|
||||
let data = try JSONEncoder().encode(["foo": "bar"])
|
||||
let response = HTTPResponse(statusCode: 200, data: data)
|
||||
|
||||
let object = try response.decode([String: String].self, as: .json)
|
||||
XCTAssertEqual(object["foo"], "bar")
|
||||
}
|
||||
|
||||
func test_decode_xmlData_returnsObject() throws {
|
||||
let data = try PropertyListEncoder().encode(["foo": "bar"])
|
||||
let response = HTTPResponse(statusCode: 200, data: data)
|
||||
|
||||
let object = try response.decode([String: String].self, as: .xml)
|
||||
XCTAssertEqual(object["foo"], "bar")
|
||||
}
|
||||
|
||||
func test_decode_noData_returnsObject() throws {
|
||||
let response = HTTPResponse(statusCode: 200, data: nil)
|
||||
XCTAssertThrowsError(try response.decode([String: String].self, as: .xml))
|
||||
}
|
||||
|
||||
func test_decode_invalidData_returnsObject() throws {
|
||||
let data = try PropertyListEncoder().encode(["foo": "bar"])
|
||||
let response = HTTPResponse(statusCode: 200, data: data)
|
||||
|
||||
XCTAssertThrowsError(try response.decode([String: String].self, as: .json))
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
//
|
||||
// URLSessionDataTaskMock.swift
|
||||
// NetworkingTests
|
||||
//
|
||||
// Created by Majd Alfhaily on 29.05.22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Networking
|
||||
|
||||
final class URLSessionDataTaskMock: URLSessionDataTaskInterface {
|
||||
var onResume: (() -> Void)?
|
||||
|
||||
func resume() {
|
||||
guard let onResume = onResume else {
|
||||
fatalError("Override implementation using `onResume`.")
|
||||
}
|
||||
|
||||
onResume()
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
//
|
||||
// URLSessionMock.swift
|
||||
// NetworkingTests
|
||||
//
|
||||
// Created by Majd Alfhaily on 17.01.22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Networking
|
||||
|
||||
final class URLSessionMock: URLSessionInterface {
|
||||
var onDataTask: ((URLRequest) throws -> (data: Data?, response: URLResponse?))?
|
||||
|
||||
func dataTask(
|
||||
with request: URLRequest,
|
||||
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
|
||||
) -> URLSessionDataTaskInterface {
|
||||
guard let onDataTask = onDataTask else {
|
||||
fatalError("Override implementation using `onDataTask`.")
|
||||
}
|
||||
|
||||
let dataTask = URLSessionDataTaskMock()
|
||||
|
||||
dataTask.onResume = {
|
||||
do {
|
||||
let result = try onDataTask(request)
|
||||
completionHandler(result.data, result.response, nil)
|
||||
} catch {
|
||||
completionHandler(nil, nil, error)
|
||||
}
|
||||
}
|
||||
|
||||
return dataTask
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
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
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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
@@ -0,0 +1,119 @@
|
||||
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,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package cmd
|
||||
|
||||
const (
|
||||
ConfigDirectoryName = ".ipatool"
|
||||
CookieJarFileName = "cookies"
|
||||
KeychainServiceName = "ipatool-auth.service"
|
||||
)
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
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
|
||||
}
|
||||
|
||||
// Purchasing may persist a server-corrected storefront.
|
||||
info, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = info.Account
|
||||
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})
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
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(2))
|
||||
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(2))
|
||||
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 + purchaseCount))
|
||||
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),
|
||||
)
|
||||
|
||||
DescribeTable("downloads using the storefront persisted during purchase", func(refresh bool) {
|
||||
original := appstore.Account{Email: "user@example.com", Password: "password", PasswordToken: "old-token", StoreFront: "143441-1,34"}
|
||||
corrected := original
|
||||
corrected.StoreFront = "143462-1,34"
|
||||
store := &fakeDownloadAppStore{
|
||||
account: original, downloadErrors: []error{appstore.ErrLicenseRequired, nil},
|
||||
purchaseStorefront: corrected.StoreFront,
|
||||
}
|
||||
if refresh {
|
||||
corrected.PasswordToken = "new-token"
|
||||
store.loginAccount = corrected
|
||||
store.purchaseErrors = []error{appstore.ErrPasswordTokenExpired, nil}
|
||||
}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
command := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
command.SetArgs([]string{"--app-id", "42", "--purchase"})
|
||||
command.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
Expect(command.Execute()).To(Succeed())
|
||||
Expect(store.downloadInputs).To(HaveLen(2))
|
||||
Expect(store.downloadInputs[0].Account).To(Equal(original))
|
||||
Expect(store.downloadInputs[1].Account).To(Equal(corrected))
|
||||
if refresh {
|
||||
Expect(store.loginInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs).To(HaveLen(2))
|
||||
Expect(store.purchaseInputs[1].Account).To(Equal(corrected))
|
||||
} else {
|
||||
Expect(store.loginInputs).To(BeEmpty())
|
||||
}
|
||||
}, Entry("immediate success", false), Entry("token refresh after correction", true))
|
||||
|
||||
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
|
||||
purchaseStorefront string
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
f.loginInputs = append(f.loginInputs, input)
|
||||
f.account = f.loginAccount
|
||||
|
||||
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)
|
||||
if f.purchaseStorefront != "" {
|
||||
f.account.StoreFront = f.purchaseStorefront
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//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
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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"))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
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
@@ -0,0 +1,87 @@
|
||||
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
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
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}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
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))
|
||||
})
|
||||
})
|
||||
+670
@@ -0,0 +1,670 @@
|
||||
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))
|
||||
|
||||
DescribeTable("uses a purchase-corrected storefront for MCP downloads", func(refresh bool) {
|
||||
account.DirectoryServicesID = "123456"
|
||||
account.StoreFront = "143441-1,34"
|
||||
var downloads []appstore.Account
|
||||
purchases := 0
|
||||
expectedPurchases := 1
|
||||
if refresh {
|
||||
expectedPurchases = 2
|
||||
}
|
||||
store.download = func(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
downloads = append(downloads, input.Account)
|
||||
if purchases < expectedPurchases {
|
||||
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
|
||||
}
|
||||
store.purchase = func(input appstore.PurchaseInput) error {
|
||||
purchases++
|
||||
account.StoreFront = "143462-1,34"
|
||||
if refresh && purchases == 1 {
|
||||
return appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
store.login = func(appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
account.PasswordToken = "new-token"
|
||||
|
||||
return appstore.LoginOutput{Account: account}, nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": true})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(purchases).To(Equal(expectedPurchases))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("purchased", true))
|
||||
Expect(downloads[0].StoreFront).To(Equal("143441-1,34"))
|
||||
Expect(downloads[len(downloads)-1].StoreFront).To(Equal("143462-1,34"))
|
||||
if refresh {
|
||||
Expect(downloads[len(downloads)-1].PasswordToken).To(Equal("new-token"))
|
||||
}
|
||||
}, Entry("immediate success", false), Entry("after token refresh", true))
|
||||
|
||||
DescribeTable("propagates errors after purchasing during an MCP download", func(accountReadFails bool) {
|
||||
failure := errors.New("fixture post-purchase failure")
|
||||
downloads := 0
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
downloads++
|
||||
if downloads == 1 {
|
||||
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{}, failure
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error {
|
||||
if accountReadFails {
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, failure
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": true})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(failure.Error()))
|
||||
}, Entry("reloading the saved account", true), Entry("retrying the download", 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)
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
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
|
||||
}
|
||||
|
||||
info, accountErr := t.store.AccountInfo()
|
||||
if accountErr != nil {
|
||||
return mcpDownloadOutput{}, accountErr
|
||||
}
|
||||
|
||||
downloadInput.Account = info.Account
|
||||
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
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
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
@@ -0,0 +1,110 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
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
@@ -0,0 +1,89 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
module github.com/majd/ipatool/v2
|
||||
|
||||
go 1.26.5
|
||||
|
||||
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/deploymenttheory/go-macos-pkg v0.3.0
|
||||
github.com/ebitengine/purego v0.10.2
|
||||
github.com/go-compressions/lzfse v0.3.0
|
||||
github.com/juju/persistent-cookiejar v1.0.0
|
||||
github.com/klauspost/compress v1.18.7
|
||||
github.com/majd/go-apfs v1.0.29
|
||||
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.19.1
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/thediveo/enumflag/v2 v2.0.1
|
||||
go.uber.org/mock v0.4.0
|
||||
golang.org/x/sys v0.48.0
|
||||
golang.org/x/term v0.46.0
|
||||
golang.org/x/text v0.42.0
|
||||
howett.net/plist v1.0.1
|
||||
)
|
||||
|
||||
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/VividCortex/ewma v1.2.0 // indirect
|
||||
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect
|
||||
github.com/andybalholm/brotli v1.2.1 // indirect
|
||||
github.com/apex/log v1.9.0 // indirect
|
||||
github.com/blacktop/go-dwarf v1.0.14 // indirect
|
||||
github.com/blacktop/go-plist v1.0.2 // 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/dustin/go-humanize v1.1.0 // 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/fatih/color v1.19.0 // indirect
|
||||
github.com/frankban/quicktest v1.14.6 // 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.1.0 // indirect
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.22 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // 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.29 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/segmentio/asm v1.1.3 // indirect
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // 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.17 // indirect
|
||||
github.com/vbauerster/mpb/v7 v7.5.3 // indirect
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // 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.57.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
|
||||
golang.org/x/mod v0.41.0 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/oauth2 v0.35.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/tools v0.49.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // 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
|
||||
)
|
||||
@@ -0,0 +1,306 @@
|
||||
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/VividCortex/ewma v1.2.0 h1:f58SaIzcDXrSy3kWaHNvuJgJ3Nmz59Zji6XoJR/q1ow=
|
||||
github.com/VividCortex/ewma v1.2.0/go.mod h1:nz4BbCtbLyFDeC9SUHbtcT5644juEuWfUAUnGx7j5l4=
|
||||
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8=
|
||||
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo=
|
||||
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/apex/log v1.9.0 h1:FHtw/xuaM8AgmvDDTI9fiwoAL25Sq2cxojnZICUU8l0=
|
||||
github.com/apex/log v1.9.0/go.mod h1:m82fZlWIuiWzWP04XCTXmnX0xRkYYbCdYn8jbJeLBEA=
|
||||
github.com/apex/logs v1.0.0/go.mod h1:XzxuLZ5myVHDy9SAmYpamKKRNApGj54PfYLcFrXqDwo=
|
||||
github.com/aphistic/golf v0.0.0-20180712155816-02c07f170c5a/go.mod h1:3NqKYiepwy8kCu4PNA+aP7WUV72eXWJeP9/r3/K9aLE=
|
||||
github.com/aphistic/sweet v0.2.0/go.mod h1:fWDlIh/isSE9n6EPsRmC0det+whmX6dJid3stzu0Xys=
|
||||
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/aws/aws-sdk-go v1.20.6/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
|
||||
github.com/aybabtme/rgbterm v0.0.0-20170906152045-cc83f3b3ce59/go.mod h1:q/89r3U2H7sSsE2t6Kca0lfwTK8JdoNGS/yzM/4iH5I=
|
||||
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/blacktop/go-plist v1.0.2 h1:DMX8uBiE308HWZkO9o37j7Z2b0neI3GSzN2caNa2zXk=
|
||||
github.com/blacktop/go-plist v1.0.2/go.mod h1:fqVhCVVXVJWsIGY9QPgdK0mDWZD82HrRMfU5PanvdTA=
|
||||
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/chengxilo/virtualterm v1.0.4 h1:Z6IpERbRVlfB8WkOmtbHiDbBANU7cimRIof7mk9/PwM=
|
||||
github.com/chengxilo/virtualterm v1.0.4/go.mod h1:DyxxBZz/x1iqJjFxTFcr6/x+jSpqN0iwWCOK1q10rlY=
|
||||
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.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
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/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/deploymenttheory/go-macos-pkg v0.3.0 h1:1pbCbFpib7lzAdu0FUnCW5frhYtjEmqO1iNg0kIKthI=
|
||||
github.com/deploymenttheory/go-macos-pkg v0.3.0/go.mod h1:aSMBLo4teBpMNx6bioyGfF22Kkdu1dodyWiyn0PLFjg=
|
||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
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/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
||||
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
|
||||
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
|
||||
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/go-compressions/lzfse v0.3.0 h1:slxIjY9HeG2llJSoXTwTnQ+u/iKMbr2WHUwaNAl/2yI=
|
||||
github.com/go-compressions/lzfse v0.3.0/go.mod h1:geg9IRFbMNHPgbm8xNwF3AnYTsldTX9YptJ0DOWzYv8=
|
||||
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
||||
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.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
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.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
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.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
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/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
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.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
|
||||
github.com/jpillora/backoff v0.0.0-20180909062703-3050d21c67d7/go.mod h1:2iMrUgbbvHEiQClaW2NsSzMyGHqN+rDFqY705q49KG0=
|
||||
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/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
|
||||
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/majd/go-apfs v1.0.29 h1:UogjWvwkvNIcDRjiEQvIpOxrK5PgFo48yRern2mnrVM=
|
||||
github.com/majd/go-apfs v1.0.29/go.mod h1:gA+fjwBmzHsm5ubsWtRJJUdRcu/8qhyuAJ4jFGGNYdk=
|
||||
github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
|
||||
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
|
||||
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
|
||||
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/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 v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
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.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
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.29 h1:CDQY6qZOLI4DW0Nx6R1vRrifrCeQHnNXkMb0hZWXFjg=
|
||||
github.com/pierrec/lz4/v4 v4.1.29/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
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/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
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/rogpeppe/fastuuid v1.1.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
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.19.1 h1:iv8BgwOvdML/S3p84uBpy/IMigv4U9594vPZYa2EdrU=
|
||||
github.com/schollz/progressbar/v3 v3.19.1/go.mod h1:LFL7jqimKxfhero4K1eCkUr/6R39AgQeiPCJtlTWIW8=
|
||||
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/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/smartystreets/assertions v1.0.0/go.mod h1:kHHU4qYBaI3q23Pp3VPrmWhuIUrLW/7eUrw0BU5VaoM=
|
||||
github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9/go.mod h1:SnhjPscd9TpLiy1LpzGSKh3bXCfxxXuqd9xmQJy3slM=
|
||||
github.com/smartystreets/gunit v1.0.0/go.mod h1:qwPWnhz6pn0NnRBP++URONOVyNkPyr4SauJk4cUOwJs=
|
||||
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.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/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.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
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/tj/assert v0.0.0-20171129193455-018094318fb0/go.mod h1:mZ9/Rh9oLWpLLDRpvE+3b7gP/C2YyLFYxNmcLnPTMe0=
|
||||
github.com/tj/assert v0.0.3 h1:Df/BlaZ20mq6kuai7f5z2TvPFiwC3xaWJSDQNiIS3Rk=
|
||||
github.com/tj/assert v0.0.3/go.mod h1:Ne6X72Q+TB1AteidzQncjw9PabbMp4PBMZ1k+vd1Pvk=
|
||||
github.com/tj/go-buffer v1.1.0/go.mod h1:iyiJpfFcR2B9sXu7KvjbT9fpM4mOelRSDTbntVj52Uc=
|
||||
github.com/tj/go-elastic v0.0.0-20171221160941-36157cbbebc2/go.mod h1:WjeM0Oo1eNAjXGDx2yma7uG2XoyRZTq1uv3M/o7imD0=
|
||||
github.com/tj/go-kinesis v0.0.0-20171128231115-08b17f58cb1b/go.mod h1:/yhzCV0xPfx6jb1bBgRFjl5lytqVqZXEaeqWP8lTEao=
|
||||
github.com/tj/go-spin v1.1.0/go.mod h1:Mg1mzmePZm4dva8Qz60H2lHwmJ2loum4VIrLgVnKwh4=
|
||||
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.17 h1:flR0y/x1hgM8EGV1AW3Xll6T413G0glV8UfBwR617V4=
|
||||
github.com/ulikunitz/xz v0.5.17/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw=
|
||||
github.com/vbauerster/mpb/v7 v7.5.3 h1:BkGfmb6nMrrBQDFECR/Q7RkKCw7ylMetCb4079CGs4w=
|
||||
github.com/vbauerster/mpb/v7 v7.5.3/go.mod h1:i+h4QY6lmLvBNK2ah1fSreiw3ajskRlBp9AhY/PnuOE=
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
|
||||
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=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
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.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
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.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
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.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
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-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220909162455-aba9fc2a8ff2/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
||||
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
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.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||
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-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
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/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
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/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/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.1 h1:37GdZ8tP09Q35o9ych3ehygcsL+HqKSwzctveSlarvM=
|
||||
howett.net/plist v1.0.1/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
|
||||
@@ -0,0 +1,641 @@
|
||||
//nolint:wsl // Binary format parsing is clearer when related bounds checks remain adjacent.
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/ecdh"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hkdf"
|
||||
"crypto/hmac"
|
||||
"crypto/hpke"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/go-compressions/lzfse"
|
||||
)
|
||||
|
||||
const (
|
||||
aeaMagic = "AEA1"
|
||||
aeaSymmetricProfile = 1
|
||||
aeaMainKeyInfo = "AEA_AMK"
|
||||
aeaRootKeyInfo = "AEA_RHEK"
|
||||
aeaClusterKeyInfo = "AEA_CK"
|
||||
aeaClusterHeaderKeyInfo = "AEA_CHEK"
|
||||
aeaSegmentKeyInfo = "AEA_SK"
|
||||
aeaLZFSECompression = 'e'
|
||||
aeaSHA256Checksum = 2
|
||||
aeaDecodedSegmentCacheCount = 64
|
||||
maxAEAAuthDataSize = 1 << 20
|
||||
maxFCSKeySize = 64 << 10
|
||||
)
|
||||
|
||||
type aeaHeader struct {
|
||||
Magic [4]byte
|
||||
ProfileAndScryptStrength uint32
|
||||
AuthDataLength uint32
|
||||
}
|
||||
|
||||
type aeaMAC [sha256.Size]byte
|
||||
|
||||
type encryptedAEARootHeader struct {
|
||||
MAC aeaMAC
|
||||
Data [48]byte
|
||||
ClusterMAC aeaMAC
|
||||
}
|
||||
|
||||
type aeaRootHeader struct {
|
||||
FileSize uint64
|
||||
EncryptedSize uint64
|
||||
SegmentSize uint32
|
||||
SegmentsPerCluster uint32
|
||||
Compression uint8
|
||||
Checksum uint8
|
||||
_ [22]byte
|
||||
}
|
||||
|
||||
type aeaHeaderKey struct {
|
||||
MAC aeaMAC
|
||||
Key [32]byte
|
||||
IV [aes.BlockSize]byte
|
||||
}
|
||||
|
||||
type aeaSegmentHeader struct {
|
||||
DecompressedSize uint32
|
||||
CompressedSize uint32
|
||||
Checksum [sha256.Size]byte
|
||||
}
|
||||
|
||||
type aeaSegment struct {
|
||||
inputOffset int64
|
||||
outputOffset int64
|
||||
compressedSize uint32
|
||||
decompressedSize uint32
|
||||
checksum [sha256.Size]byte
|
||||
mac aeaMAC
|
||||
cluster uint32
|
||||
index uint32
|
||||
}
|
||||
|
||||
type aeaReader struct {
|
||||
source io.ReaderAt
|
||||
size int64
|
||||
segmentSize uint32
|
||||
mainKey []byte
|
||||
segments []aeaSegment
|
||||
cache map[int][]byte
|
||||
cacheOrder []int
|
||||
cacheMu sync.Mutex
|
||||
}
|
||||
|
||||
type fcsResponse struct {
|
||||
EncRequest string `json:"enc-request"`
|
||||
WrappedKey string `json:"wrapped-key"`
|
||||
}
|
||||
|
||||
func newAEAReader(ctx context.Context, client *http.Client, source io.ReaderAt, sourceSize int64) (*aeaReader, error) {
|
||||
var header aeaHeader
|
||||
if err := readBinaryAt(source, 0, &header); err != nil {
|
||||
return nil, fmt.Errorf("read AEA header: %w", err)
|
||||
}
|
||||
|
||||
if string(header.Magic[:]) != aeaMagic {
|
||||
return nil, fmt.Errorf("invalid AEA magic %q", header.Magic)
|
||||
}
|
||||
|
||||
if header.ProfileAndScryptStrength&0xffffff != aeaSymmetricProfile {
|
||||
return nil, fmt.Errorf("unsupported AEA profile %d", header.ProfileAndScryptStrength&0xffffff)
|
||||
}
|
||||
|
||||
if header.AuthDataLength > maxAEAAuthDataSize {
|
||||
return nil, fmt.Errorf("AEA authentication data is too large: %d", header.AuthDataLength)
|
||||
}
|
||||
|
||||
headerSize := int64(binary.Size(header))
|
||||
authData := make([]byte, header.AuthDataLength)
|
||||
if _, err := source.ReadAt(authData, headerSize); err != nil {
|
||||
return nil, fmt.Errorf("read AEA authentication data: %w", err)
|
||||
}
|
||||
|
||||
metadata, err := parseAEAMetadata(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
symmetricKey, err := resolveAEASymmetricKey(ctx, client, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mainSaltOffset := headerSize + int64(len(authData))
|
||||
mainSalt := make([]byte, sha256.Size)
|
||||
if _, err := source.ReadAt(mainSalt, mainSaltOffset); err != nil {
|
||||
return nil, fmt.Errorf("read AEA main salt: %w", err)
|
||||
}
|
||||
|
||||
mainKey, err := deriveAEAKey(symmetricKey, mainSalt, binary.LittleEndian.AppendUint32([]byte(aeaMainKeyInfo), header.ProfileAndScryptStrength), len(symmetricKey))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive AEA main key: %w", err)
|
||||
}
|
||||
|
||||
rootOffset := mainSaltOffset + int64(len(mainSalt))
|
||||
|
||||
var encryptedRoot encryptedAEARootHeader
|
||||
if err := readBinaryAt(source, rootOffset, &encryptedRoot); err != nil {
|
||||
return nil, fmt.Errorf("read encrypted AEA root header: %w", err)
|
||||
}
|
||||
|
||||
rootKey, err := deriveAEAHeaderKey(mainKey, []byte(aeaRootKeyInfo))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive AEA root key: %w", err)
|
||||
}
|
||||
|
||||
rootSalt := make([]byte, 0, len(encryptedRoot.ClusterMAC)+len(authData))
|
||||
rootSalt = append(rootSalt, encryptedRoot.ClusterMAC[:]...)
|
||||
rootSalt = append(rootSalt, authData...)
|
||||
computedRootMAC := calculateAEAMAC(rootKey.MAC[:], encryptedRoot.Data[:], rootSalt)
|
||||
if !hmac.Equal(encryptedRoot.MAC[:], computedRootMAC[:]) {
|
||||
return nil, errors.New("AEA root header failed authentication")
|
||||
}
|
||||
|
||||
rootData, err := decryptAEACTR(encryptedRoot.Data[:], rootKey.Key[:], rootKey.IV[:])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt AEA root header: %w", err)
|
||||
}
|
||||
|
||||
var root aeaRootHeader
|
||||
if err := binary.Read(bytes.NewReader(rootData), binary.LittleEndian, &root); err != nil {
|
||||
return nil, fmt.Errorf("decode AEA root header: %w", err)
|
||||
}
|
||||
|
||||
if root.FileSize == 0 || root.FileSize > ^uint64(0)>>1 {
|
||||
return nil, fmt.Errorf("invalid AEA output size %d", root.FileSize)
|
||||
}
|
||||
|
||||
if root.EncryptedSize != uint64(sourceSize) {
|
||||
return nil, fmt.Errorf("AEA encrypted size is %d, expected %d", root.EncryptedSize, sourceSize)
|
||||
}
|
||||
|
||||
if root.SegmentSize == 0 || root.SegmentsPerCluster == 0 {
|
||||
return nil, errors.New("AEA has an invalid segment layout")
|
||||
}
|
||||
|
||||
if root.Compression != aeaLZFSECompression || root.Checksum != aeaSHA256Checksum {
|
||||
return nil, fmt.Errorf("unsupported AEA encoding: compression %q, checksum %d", root.Compression, root.Checksum)
|
||||
}
|
||||
|
||||
reader := &aeaReader{
|
||||
source: source,
|
||||
size: int64(root.FileSize),
|
||||
segmentSize: root.SegmentSize,
|
||||
mainKey: mainKey,
|
||||
segments: make([]aeaSegment, (root.FileSize+uint64(root.SegmentSize)-1)/uint64(root.SegmentSize)),
|
||||
cache: make(map[int][]byte, aeaDecodedSegmentCacheCount),
|
||||
}
|
||||
|
||||
clusterOffset := rootOffset + int64(binary.Size(encryptedRoot))
|
||||
if err := reader.indexClusters(clusterOffset, encryptedRoot.ClusterMAC, root, sourceSize); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return reader, nil
|
||||
}
|
||||
|
||||
func parseAEAMetadata(data []byte) (map[string][]byte, error) {
|
||||
metadata := make(map[string][]byte)
|
||||
reader := bytes.NewReader(data)
|
||||
|
||||
for reader.Len() != 0 {
|
||||
var length uint32
|
||||
if err := binary.Read(reader, binary.LittleEndian, &length); err != nil {
|
||||
return nil, fmt.Errorf("read AEA metadata length: %w", err)
|
||||
}
|
||||
|
||||
if length < 5 || uint64(length-4) > uint64(reader.Len()) {
|
||||
return nil, fmt.Errorf("invalid AEA metadata record length %d", length)
|
||||
}
|
||||
|
||||
record := make([]byte, length-4)
|
||||
if _, err := io.ReadFull(reader, record); err != nil {
|
||||
return nil, fmt.Errorf("read AEA metadata record: %w", err)
|
||||
}
|
||||
|
||||
key, value, ok := bytes.Cut(record, []byte{0})
|
||||
if !ok || len(key) == 0 {
|
||||
return nil, errors.New("invalid AEA metadata record")
|
||||
}
|
||||
|
||||
metadata[string(key)] = value
|
||||
}
|
||||
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
// resolveAEASymmetricKey downloads the Apple-published FCS P-256 private key
|
||||
// identified by the AEA metadata. That key is the HPKE recipient key for this
|
||||
// image's wrapped symmetric key; the unwrapped key is then used to derive the
|
||||
// AES and HMAC keys that decrypt and authenticate the AEA headers and segments.
|
||||
// It is restore-image key material, not a user credential.
|
||||
func resolveAEASymmetricKey(ctx context.Context, client *http.Client, metadata map[string][]byte) ([]byte, error) {
|
||||
keyURLData, ok := metadata["com.apple.wkms.fcs-key-url"]
|
||||
if !ok {
|
||||
return nil, errors.New("AEA metadata does not contain an FCS key URL")
|
||||
}
|
||||
|
||||
keyURL, err := url.Parse(string(keyURLData))
|
||||
if err != nil || keyURL.Scheme != "https" || keyURL.Hostname() != "wkms-public.apple.com" {
|
||||
return nil, fmt.Errorf("invalid Apple FCS key URL %q", keyURLData)
|
||||
}
|
||||
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, keyURL.String(), nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create Apple FCS key request: %w", err)
|
||||
}
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download Apple FCS key: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("download Apple FCS key: server returned %s", response.Status)
|
||||
}
|
||||
|
||||
pemData, err := io.ReadAll(io.LimitReader(response.Body, maxFCSKeySize+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read Apple FCS key: %w", err)
|
||||
}
|
||||
|
||||
if len(pemData) > maxFCSKeySize {
|
||||
return nil, errors.New("apple FCS key response is too large")
|
||||
}
|
||||
|
||||
block, _ := pem.Decode(pemData)
|
||||
if block == nil {
|
||||
return nil, errors.New("apple FCS key response is not PEM encoded")
|
||||
}
|
||||
|
||||
privateKeyValue, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse Apple FCS private key: %w", err)
|
||||
}
|
||||
|
||||
privateKey, ok := privateKeyValue.(*ecdsa.PrivateKey)
|
||||
if !ok || privateKey.Curve != elliptic.P256() {
|
||||
return nil, errors.New("apple FCS key is not a P-256 private key")
|
||||
}
|
||||
|
||||
responseData, ok := metadata["com.apple.wkms.fcs-response"]
|
||||
if !ok {
|
||||
return nil, errors.New("AEA metadata does not contain an FCS response")
|
||||
}
|
||||
|
||||
var wrapped fcsResponse
|
||||
if err := json.Unmarshal(responseData, &wrapped); err != nil {
|
||||
return nil, fmt.Errorf("parse AEA FCS response: %w", err)
|
||||
}
|
||||
|
||||
encapsulation, err := base64.StdEncoding.DecodeString(wrapped.EncRequest)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode AEA FCS encapsulation: %w", err)
|
||||
}
|
||||
|
||||
wrappedKey, err := base64.StdEncoding.DecodeString(wrapped.WrappedKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode AEA wrapped key: %w", err)
|
||||
}
|
||||
|
||||
kem := hpke.DHKEM(ecdh.P256())
|
||||
ecdhPrivateKey, err := privateKey.ECDH()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("convert AEA FCS private key: %w", err)
|
||||
}
|
||||
hpkePrivateKey, err := kem.NewPrivateKey(ecdhPrivateKey.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load AEA FCS private key: %w", err)
|
||||
}
|
||||
|
||||
recipient, err := hpke.NewRecipient(encapsulation, hpkePrivateKey, hpke.HKDFSHA256(), hpke.AES256GCM(), nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initialize AEA FCS recipient: %w", err)
|
||||
}
|
||||
|
||||
symmetricKey, err := recipient.Open(nil, wrappedKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unwrap AEA symmetric key: %w", err)
|
||||
}
|
||||
|
||||
return symmetricKey, nil
|
||||
}
|
||||
|
||||
func (r *aeaReader) indexClusters(offset int64, clusterMAC aeaMAC, root aeaRootHeader, sourceSize int64) error {
|
||||
const segmentHeaderSize = 8 + sha256.Size
|
||||
|
||||
headerSize := int64(segmentHeaderSize*root.SegmentsPerCluster + sha256.Size + sha256.Size*root.SegmentsPerCluster)
|
||||
outputSize := uint64(0)
|
||||
clusterIndex := uint32(0)
|
||||
|
||||
for outputSize < root.FileSize {
|
||||
if offset < 0 || headerSize > sourceSize-offset {
|
||||
return errors.New("AEA cluster header extends beyond the encrypted image")
|
||||
}
|
||||
|
||||
headerData := make([]byte, headerSize)
|
||||
if _, err := r.source.ReadAt(headerData, offset); err != nil {
|
||||
return fmt.Errorf("read AEA cluster %d header: %w", clusterIndex, err)
|
||||
}
|
||||
|
||||
clusterKey, err := deriveAEAKey(r.mainKey, nil, binary.LittleEndian.AppendUint32([]byte(aeaClusterKeyInfo), clusterIndex), len(r.mainKey))
|
||||
if err != nil {
|
||||
return fmt.Errorf("derive AEA cluster %d key: %w", clusterIndex, err)
|
||||
}
|
||||
|
||||
clusterHeaderKey, err := deriveAEAHeaderKey(clusterKey, []byte(aeaClusterHeaderKeyInfo))
|
||||
if err != nil {
|
||||
return fmt.Errorf("derive AEA cluster %d header key: %w", clusterIndex, err)
|
||||
}
|
||||
|
||||
encryptedHeadersSize := int(segmentHeaderSize * root.SegmentsPerCluster)
|
||||
encryptedHeaders := headerData[:encryptedHeadersSize]
|
||||
var nextClusterMAC aeaMAC
|
||||
copy(nextClusterMAC[:], headerData[encryptedHeadersSize:encryptedHeadersSize+sha256.Size])
|
||||
segmentMACData := headerData[encryptedHeadersSize+sha256.Size:]
|
||||
|
||||
hmacSalt := make([]byte, 0, len(nextClusterMAC)+len(segmentMACData))
|
||||
hmacSalt = append(hmacSalt, nextClusterMAC[:]...)
|
||||
hmacSalt = append(hmacSalt, segmentMACData...)
|
||||
computedMAC := calculateAEAMAC(clusterHeaderKey.MAC[:], encryptedHeaders, hmacSalt)
|
||||
if !hmac.Equal(clusterMAC[:], computedMAC[:]) {
|
||||
return fmt.Errorf("AEA cluster %d failed authentication", clusterIndex)
|
||||
}
|
||||
|
||||
decryptedHeaders, err := decryptAEACTR(encryptedHeaders, clusterHeaderKey.Key[:], clusterHeaderKey.IV[:])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decrypt AEA cluster %d headers: %w", clusterIndex, err)
|
||||
}
|
||||
|
||||
dataOffset := offset + headerSize
|
||||
for segmentIndex := range root.SegmentsPerCluster {
|
||||
start := int(segmentIndex) * segmentHeaderSize
|
||||
var segmentHeader aeaSegmentHeader
|
||||
if err := binary.Read(bytes.NewReader(decryptedHeaders[start:start+segmentHeaderSize]), binary.LittleEndian, &segmentHeader); err != nil {
|
||||
return fmt.Errorf("decode AEA cluster %d segment %d header: %w", clusterIndex, segmentIndex, err)
|
||||
}
|
||||
|
||||
if segmentHeader.DecompressedSize == 0 {
|
||||
if segmentHeader.CompressedSize != 0 {
|
||||
return fmt.Errorf("AEA cluster %d segment %d has compressed data without output", clusterIndex, segmentIndex)
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if segmentHeader.DecompressedSize > root.SegmentSize || segmentHeader.CompressedSize == 0 {
|
||||
return fmt.Errorf("AEA cluster %d segment %d has invalid sizes", clusterIndex, segmentIndex)
|
||||
}
|
||||
|
||||
if int64(segmentHeader.CompressedSize) > sourceSize-dataOffset {
|
||||
return fmt.Errorf("AEA cluster %d segment %d extends beyond the encrypted image", clusterIndex, segmentIndex)
|
||||
}
|
||||
|
||||
var segmentMAC aeaMAC
|
||||
copy(segmentMAC[:], segmentMACData[int(segmentIndex)*sha256.Size:(int(segmentIndex)+1)*sha256.Size])
|
||||
|
||||
globalIndex := uint64(clusterIndex)*uint64(root.SegmentsPerCluster) + uint64(segmentIndex)
|
||||
if globalIndex >= uint64(len(r.segments)) {
|
||||
return fmt.Errorf("AEA cluster %d segment %d is outside the declared output", clusterIndex, segmentIndex)
|
||||
}
|
||||
|
||||
outputOffset := int64(globalIndex * uint64(root.SegmentSize))
|
||||
if uint64(outputOffset)+uint64(segmentHeader.DecompressedSize) > root.FileSize {
|
||||
return fmt.Errorf("AEA cluster %d segment %d extends beyond the declared output", clusterIndex, segmentIndex)
|
||||
}
|
||||
|
||||
r.segments[globalIndex] = aeaSegment{
|
||||
inputOffset: dataOffset,
|
||||
outputOffset: outputOffset,
|
||||
compressedSize: segmentHeader.CompressedSize,
|
||||
decompressedSize: segmentHeader.DecompressedSize,
|
||||
checksum: segmentHeader.Checksum,
|
||||
mac: segmentMAC,
|
||||
cluster: clusterIndex,
|
||||
index: segmentIndex,
|
||||
}
|
||||
|
||||
dataOffset += int64(segmentHeader.CompressedSize)
|
||||
outputSize += uint64(segmentHeader.DecompressedSize)
|
||||
if outputSize > root.FileSize {
|
||||
return errors.New("AEA segment data exceeds the declared output size")
|
||||
}
|
||||
}
|
||||
|
||||
offset = dataOffset
|
||||
clusterMAC = nextClusterMAC
|
||||
clusterIndex++
|
||||
}
|
||||
|
||||
if outputSize != root.FileSize {
|
||||
return fmt.Errorf("AEA segment data has size %d, expected %d", outputSize, root.FileSize)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *aeaReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||
if len(data) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if offset < 0 {
|
||||
return 0, errors.New("negative AEA output offset")
|
||||
}
|
||||
|
||||
if offset >= r.size {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
wanted := len(data)
|
||||
if remaining := r.size - offset; int64(wanted) > remaining {
|
||||
wanted = int(remaining)
|
||||
}
|
||||
|
||||
written := 0
|
||||
for written < wanted {
|
||||
segmentIndex := int((offset + int64(written)) / int64(r.segmentSize))
|
||||
if segmentIndex >= len(r.segments) {
|
||||
return written, errors.New("AEA segment index is incomplete")
|
||||
}
|
||||
|
||||
segment := r.segments[segmentIndex]
|
||||
if segment.decompressedSize == 0 {
|
||||
return written, fmt.Errorf("AEA segment %d is missing", segmentIndex)
|
||||
}
|
||||
decoded, err := r.decodeSegment(segmentIndex, segment)
|
||||
if err != nil {
|
||||
return written, err
|
||||
}
|
||||
|
||||
inside := int(offset + int64(written) - segment.outputOffset)
|
||||
if inside < 0 || inside >= len(decoded) {
|
||||
return written, errors.New("AEA segment has an invalid output offset")
|
||||
}
|
||||
|
||||
count := min(wanted-written, len(decoded)-inside)
|
||||
copy(data[written:written+count], decoded[inside:inside+count])
|
||||
written += count
|
||||
}
|
||||
|
||||
if wanted != len(data) {
|
||||
return written, io.EOF
|
||||
}
|
||||
|
||||
return written, nil
|
||||
}
|
||||
|
||||
func (r *aeaReader) decodeSegment(cacheIndex int, segment aeaSegment) ([]byte, error) {
|
||||
r.cacheMu.Lock()
|
||||
defer r.cacheMu.Unlock()
|
||||
|
||||
if data, ok := r.cache[cacheIndex]; ok {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
encrypted := make([]byte, segment.compressedSize)
|
||||
if _, err := r.source.ReadAt(encrypted, segment.inputOffset); err != nil {
|
||||
return nil, fmt.Errorf("read AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
|
||||
}
|
||||
|
||||
clusterKey, err := deriveAEAKey(r.mainKey, nil, binary.LittleEndian.AppendUint32([]byte(aeaClusterKeyInfo), segment.cluster), len(r.mainKey))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive AEA cluster %d key: %w", segment.cluster, err)
|
||||
}
|
||||
|
||||
segmentKey, err := deriveAEAHeaderKey(clusterKey, binary.LittleEndian.AppendUint32([]byte(aeaSegmentKeyInfo), segment.index))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive AEA cluster %d segment %d key: %w", segment.cluster, segment.index, err)
|
||||
}
|
||||
|
||||
computedMAC := calculateAEAMAC(segmentKey.MAC[:], encrypted, nil)
|
||||
if !hmac.Equal(segment.mac[:], computedMAC[:]) {
|
||||
return nil, fmt.Errorf("AEA cluster %d segment %d failed authentication", segment.cluster, segment.index)
|
||||
}
|
||||
|
||||
compressed, err := decryptAEACTR(encrypted, segmentKey.Key[:], segmentKey.IV[:])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
|
||||
}
|
||||
|
||||
var decoded []byte
|
||||
if segment.compressedSize == segment.decompressedSize {
|
||||
decoded = compressed
|
||||
} else {
|
||||
decoded, err = lzfse.Decompress(compressed)
|
||||
if err != nil && strings.Contains(err.Error(), "fse: stream too short") {
|
||||
padded, e := padLZFSEStreams(compressed)
|
||||
if e == nil {
|
||||
decoded, err = lzfse.Decompress(padded)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decompress AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
|
||||
}
|
||||
if len(decoded) != int(segment.decompressedSize) {
|
||||
return nil, fmt.Errorf("decompress AEA cluster %d segment %d: produced %d bytes, expected %d", segment.cluster, segment.index, len(decoded), segment.decompressedSize)
|
||||
}
|
||||
}
|
||||
|
||||
if sha256.Sum256(decoded) != segment.checksum {
|
||||
return nil, fmt.Errorf("AEA cluster %d segment %d failed checksum verification", segment.cluster, segment.index)
|
||||
}
|
||||
|
||||
if len(r.cacheOrder) == aeaDecodedSegmentCacheCount {
|
||||
delete(r.cache, r.cacheOrder[0])
|
||||
copy(r.cacheOrder, r.cacheOrder[1:])
|
||||
r.cacheOrder = r.cacheOrder[:len(r.cacheOrder)-1]
|
||||
}
|
||||
|
||||
r.cache[cacheIndex] = decoded
|
||||
r.cacheOrder = append(r.cacheOrder, cacheIndex)
|
||||
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
func deriveAEAKey(key, salt, info []byte, size int) ([]byte, error) {
|
||||
derived, err := hkdf.Key(sha256.New, key, salt, string(info), size)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("expand AEA key: %w", err)
|
||||
}
|
||||
|
||||
return derived, nil
|
||||
}
|
||||
|
||||
func deriveAEAHeaderKey(key, info []byte) (aeaHeaderKey, error) {
|
||||
var headerKey aeaHeaderKey
|
||||
derived, err := deriveAEAKey(key, nil, info, binary.Size(headerKey))
|
||||
if err != nil {
|
||||
return aeaHeaderKey{}, fmt.Errorf("derive AEA header key: %w", err)
|
||||
}
|
||||
|
||||
if err := binary.Read(bytes.NewReader(derived), binary.LittleEndian, &headerKey); err != nil {
|
||||
return aeaHeaderKey{}, fmt.Errorf("decode AEA header key: %w", err)
|
||||
}
|
||||
|
||||
return headerKey, nil
|
||||
}
|
||||
|
||||
func calculateAEAMAC(key, data, salt []byte) aeaMAC {
|
||||
mac := hmac.New(sha256.New, key)
|
||||
_, _ = mac.Write(salt)
|
||||
_, _ = mac.Write(data)
|
||||
|
||||
var length [8]byte
|
||||
binary.LittleEndian.PutUint64(length[:], uint64(len(salt)))
|
||||
_, _ = mac.Write(length[:])
|
||||
|
||||
return aeaMAC(mac.Sum(nil))
|
||||
}
|
||||
|
||||
func decryptAEACTR(data, key, iv []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initialize AEA cipher: %w", err)
|
||||
}
|
||||
|
||||
decrypted := make([]byte, len(data))
|
||||
cipher.NewCTR(block, iv).XORKeyStream(decrypted, data)
|
||||
|
||||
return decrypted, nil
|
||||
}
|
||||
|
||||
func readBinaryAt(source io.ReaderAt, offset int64, value any) error {
|
||||
size := binary.Size(value)
|
||||
if size < 0 {
|
||||
return errors.New("invalid binary value")
|
||||
}
|
||||
|
||||
data := make([]byte, size)
|
||||
if _, err := source.ReadAt(data, offset); err != nil {
|
||||
return fmt.Errorf("read binary value: %w", err)
|
||||
}
|
||||
|
||||
if err := binary.Read(bytes.NewReader(data), binary.LittleEndian, value); err != nil {
|
||||
return fmt.Errorf("decode binary value: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,872 @@
|
||||
//nolint:wsl // Binary tree traversal is clearer when related bounds checks remain adjacent.
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/deploymenttheory/go-macos-pkg/pkg/lzbitmap"
|
||||
"github.com/go-compressions/lzfse"
|
||||
"github.com/majd/go-apfs"
|
||||
"github.com/majd/go-apfs/pkg/disk"
|
||||
"github.com/majd/go-apfs/pkg/disk/dmg"
|
||||
"github.com/majd/go-apfs/types"
|
||||
"github.com/majd/ipatool/v2/internal/sap/machimage"
|
||||
)
|
||||
|
||||
const (
|
||||
apfsObjectHeaderSize = 32
|
||||
apfsObjectTypeBTree = 2
|
||||
apfsObjectTypeNode = 3
|
||||
apfsObjectTypeFSTree = 14
|
||||
apfsObjectNoHeader = 0x20000000
|
||||
apfsNodeRoot = 0x0001
|
||||
apfsNodeNoHeader = 0x0010
|
||||
apfsBlockSize = 4096
|
||||
apfsMaximumTreeDepth = 32
|
||||
decmpfsLZVN = 8
|
||||
decmpfsLZFSE = 12
|
||||
decmpfsLZBitmap = 14
|
||||
decmpfsBlockSize = 64 << 10
|
||||
)
|
||||
|
||||
type apfsExtractor struct {
|
||||
device disk.Device
|
||||
filesystem *apfs.APFS
|
||||
volumeOMap types.BTreeNodePhys
|
||||
rootTreeBase uint64
|
||||
transactionID types.XidT
|
||||
}
|
||||
|
||||
type apfsExtent struct {
|
||||
logical uint64
|
||||
physical uint64
|
||||
length uint64
|
||||
}
|
||||
|
||||
type apfsFile struct {
|
||||
io.ReaderAt
|
||||
size int64
|
||||
}
|
||||
|
||||
func extractAPFSFiles(ctx context.Context, source io.ReaderAt, size int64, paths []string, destination string) error {
|
||||
extractor, closeExtractor, err := newAPFSExtractor(source, size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = closeExtractor() }()
|
||||
|
||||
if err := os.MkdirAll(destination, 0o700); err != nil {
|
||||
return fmt.Errorf("create Apple filesystem extraction directory: %w", err)
|
||||
}
|
||||
|
||||
for _, path := range paths {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return fmt.Errorf("extract Apple filesystem files: %w", err)
|
||||
}
|
||||
if err := extractor.extractImageFile(ctx, path, destination, filepath.Ext(path) != ".icxs"); err != nil {
|
||||
return fmt.Errorf("extract %s from Apple filesystem: %w", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func newAPFSExtractor(source io.ReaderAt, size int64) (*apfsExtractor, func() error, error) {
|
||||
device, closeDevice, err := openAPFSDevice(source, size)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
filesystem, err := apfs.NewAPFS(device)
|
||||
if err != nil {
|
||||
_ = closeDevice()
|
||||
|
||||
return nil, nil, fmt.Errorf("open Apple filesystem: %w", err)
|
||||
}
|
||||
fail := func(err error) (*apfsExtractor, func() error, error) {
|
||||
filesystem.Close()
|
||||
_ = closeDevice()
|
||||
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
volumeOMap, ok := filesystem.Volume.OMap.Body.(types.OMap)
|
||||
if !ok {
|
||||
return fail(fmt.Errorf("apple filesystem volume has an invalid object map"))
|
||||
}
|
||||
if volumeOMap.Tree == nil {
|
||||
return fail(fmt.Errorf("apple filesystem volume has no object-map tree"))
|
||||
}
|
||||
volumeOMapRoot, ok := volumeOMap.Tree.Body.(types.BTreeNodePhys)
|
||||
if !ok {
|
||||
return fail(fmt.Errorf("apple filesystem volume has an invalid object-map tree"))
|
||||
}
|
||||
|
||||
extractor := &apfsExtractor{
|
||||
device: device,
|
||||
filesystem: filesystem,
|
||||
volumeOMap: volumeOMapRoot,
|
||||
rootTreeBase: uint64(filesystem.Volume.RootTreeOid),
|
||||
transactionID: filesystem.Volume.OMap.Hdr.Xid,
|
||||
}
|
||||
closeExtractor := func() error {
|
||||
filesystem.Close()
|
||||
|
||||
return closeDevice()
|
||||
}
|
||||
|
||||
return extractor, closeExtractor, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) extractImageFile(ctx context.Context, path, destination string, thin bool) (err error) {
|
||||
file, err := e.openFile(ctx, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
outputPath := filepath.Join(destination, filepath.Base(path))
|
||||
output, err := os.OpenFile(outputPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create output: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := output.Close(); err == nil && closeErr != nil {
|
||||
err = fmt.Errorf("close output: %w", closeErr)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
_ = os.Remove(outputPath)
|
||||
}
|
||||
}()
|
||||
|
||||
offset, size := int64(0), file.size
|
||||
if thin {
|
||||
offset, size, err = machimage.ARM64Range(file, file.size)
|
||||
if err != nil {
|
||||
return fmt.Errorf("select runtime image architecture: %w", err)
|
||||
}
|
||||
}
|
||||
reader := &contextReader{ctx: ctx, reader: io.NewSectionReader(file, offset, size)}
|
||||
if _, err := io.CopyN(output, reader, size); err != nil {
|
||||
return fmt.Errorf("copy file data: %w", err)
|
||||
}
|
||||
|
||||
if err := output.Sync(); err != nil {
|
||||
return fmt.Errorf("sync output: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) openFile(ctx context.Context, path string) (*apfsFile, error) {
|
||||
records, err := e.resolvePath(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var inode *types.JInodeVal
|
||||
var compression *types.DecmpfsDiskHeader
|
||||
var resource *types.JXattrDstreamT
|
||||
var extents []apfsExtent
|
||||
for _, record := range records {
|
||||
switch record.Hdr.GetType() {
|
||||
case types.APFS_TYPE_INODE:
|
||||
value, ok := record.Val.(types.JInodeVal)
|
||||
if ok {
|
||||
inode = &value
|
||||
}
|
||||
case types.APFS_TYPE_FILE_EXTENT:
|
||||
key, keyOK := record.Key.(types.JFileExtentKeyT)
|
||||
value, valueOK := record.Val.(types.JFileExtentValT)
|
||||
if keyOK && valueOK {
|
||||
extents = append(extents, apfsExtent{
|
||||
logical: key.LogicalAddr,
|
||||
physical: value.PhysBlockNum,
|
||||
length: value.Length(),
|
||||
})
|
||||
}
|
||||
case types.APFS_TYPE_XATTR:
|
||||
key, keyOK := record.Key.(types.JXattrKeyT)
|
||||
value, valueOK := record.Val.(types.JXattrValT)
|
||||
if !keyOK || !valueOK {
|
||||
continue
|
||||
}
|
||||
|
||||
switch key.Name {
|
||||
case types.DECMPFS_XATTR_NAME:
|
||||
compression, err = types.GetDecmpfsHeader(record)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read compression metadata: %w", err)
|
||||
}
|
||||
case "com.apple.ResourceFork":
|
||||
stream, ok := value.Data.(types.JXattrDstreamT)
|
||||
if ok {
|
||||
resource = &stream
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if inode == nil {
|
||||
return nil, fmt.Errorf("file has no inode record")
|
||||
}
|
||||
|
||||
if compression != nil {
|
||||
method := uint32(compression.CompressionType)
|
||||
if method != decmpfsLZVN && method != decmpfsLZFSE && method != decmpfsLZBitmap {
|
||||
return nil, fmt.Errorf("unsupported compression type %d", compression.CompressionType)
|
||||
}
|
||||
if resource == nil {
|
||||
return nil, fmt.Errorf("compressed file has no resource fork")
|
||||
}
|
||||
|
||||
extents, err = e.dataExtents(resource.XattrObjID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read resource-fork extents: %w", err)
|
||||
}
|
||||
resourceReader, err := newAPFSExtentReader(e.device, extents, resource.DStream.Size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reader, err := newDecmpfsReader(ctx, resourceReader, resource.DStream.Size, compression.UncompressedSize, method)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &apfsFile{ReaderAt: reader, size: int64(compression.UncompressedSize)}, nil
|
||||
}
|
||||
|
||||
size := inode.UncompressedSize
|
||||
for _, field := range inode.Xfields {
|
||||
if stream, ok := field.Field.(types.JDstreamT); ok {
|
||||
size = stream.Size
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(extents) == 0 && size != 0 {
|
||||
extents, err = e.dataExtents(inode.PrivateID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read file extents: %w", err)
|
||||
}
|
||||
}
|
||||
reader, err := newAPFSExtentReader(e.device, extents, size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &apfsFile{ReaderAt: reader, size: int64(size)}, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) resolvePath(path string) ([]types.NodeEntry, error) {
|
||||
objectID := uint64(types.FSROOT_OID)
|
||||
for _, name := range strings.Split(strings.Trim(path, "/"), "/") {
|
||||
records, err := e.recordsForObject(objectID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, record := range records {
|
||||
if record.Hdr.GetType() != types.APFS_TYPE_DIR_REC {
|
||||
continue
|
||||
}
|
||||
key, keyOK := record.Key.(types.JDrecHashedKeyT)
|
||||
value, valueOK := record.Val.(types.JDrecVal)
|
||||
if keyOK && valueOK && key.Name == name {
|
||||
objectID = value.FileID
|
||||
found = true
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, fmt.Errorf("path component %q was not found", name)
|
||||
}
|
||||
}
|
||||
|
||||
return e.recordsForObject(objectID)
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) recordsForObject(objectID uint64) ([]types.NodeEntry, error) {
|
||||
visited := make(map[uint64]struct{})
|
||||
|
||||
return e.collectRecords(e.filesystem.FSRootBtree, objectID, visited, 0)
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) collectRecords(node types.BTreeNodePhys, objectID uint64, visited map[uint64]struct{}, depth int) ([]types.NodeEntry, error) {
|
||||
if depth > apfsMaximumTreeDepth {
|
||||
return nil, fmt.Errorf("filesystem tree exceeds maximum depth")
|
||||
}
|
||||
if node.IsLeaf() {
|
||||
var records []types.NodeEntry
|
||||
for _, raw := range node.Entries {
|
||||
record, ok := raw.(types.NodeEntry)
|
||||
if ok && record.Hdr.GetID() == objectID {
|
||||
records = append(records, record)
|
||||
}
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
var records []types.NodeEntry
|
||||
for index, raw := range node.Entries {
|
||||
entry, ok := raw.(types.NodeEntry)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("filesystem tree contains an invalid index entry")
|
||||
}
|
||||
lower := entry.Hdr.GetID()
|
||||
upper := ^uint64(0)
|
||||
if index+1 < len(node.Entries) {
|
||||
next, ok := node.Entries[index+1].(types.NodeEntry)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("filesystem tree contains an invalid index entry")
|
||||
}
|
||||
upper = next.Hdr.GetID()
|
||||
}
|
||||
if objectID < lower || objectID > upper {
|
||||
continue
|
||||
}
|
||||
|
||||
child, address, err := e.filesystemChild(entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, seen := visited[address]; seen {
|
||||
continue
|
||||
}
|
||||
visited[address] = struct{}{}
|
||||
childRecords, err := e.collectRecords(child, objectID, visited, depth+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
records = append(records, childRecords...)
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) filesystemChild(entry types.NodeEntry) (types.BTreeNodePhys, uint64, error) {
|
||||
var objectID types.OidT
|
||||
var expectedHash *[sha256.Size]byte
|
||||
switch value := entry.Val.(type) {
|
||||
case types.BTreeNodeIndexNodeValT:
|
||||
objectID = types.OidT(e.rootTreeBase + uint64(value.ChildOid))
|
||||
expectedHash = &value.ChildHash
|
||||
case uint64:
|
||||
objectID = types.OidT(value)
|
||||
default:
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("sealed filesystem tree contains an invalid child reference")
|
||||
}
|
||||
|
||||
mapping, err := e.volumeOMap.GetOMapEntry(e.device, objectID, e.transactionID)
|
||||
if err != nil {
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("resolve filesystem child %#x: %w", objectID, err)
|
||||
}
|
||||
|
||||
if expectedHash != nil {
|
||||
raw := make([]byte, apfsBlockSize)
|
||||
if _, err := readAPFSBlock(e.device, raw, mapping.Val.Paddr); err != nil {
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("read filesystem child %#x: %w", objectID, err)
|
||||
}
|
||||
if digest := sha256.Sum256(raw); digest != *expectedHash {
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("filesystem child %#x failed SHA-256 verification", objectID)
|
||||
}
|
||||
}
|
||||
|
||||
object, err := types.ReadObj(e.device, mapping.Val.Paddr)
|
||||
if err != nil {
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("decode filesystem child %#x: %w", objectID, err)
|
||||
}
|
||||
child, ok := object.Body.(types.BTreeNodePhys)
|
||||
if !ok {
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("filesystem child %#x is not a tree node", objectID)
|
||||
}
|
||||
|
||||
return child, mapping.Val.Paddr, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) physicalExtents(objectID uint64) ([]apfsExtent, error) {
|
||||
object, err := types.ReadObj(e.device, uint64(e.filesystem.Volume.FextTreeOid))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read physical extent tree: %w", err)
|
||||
}
|
||||
root, ok := object.Body.(types.BTreeNodePhys)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("physical extent tree root is not a tree node")
|
||||
}
|
||||
|
||||
extents, err := e.collectPhysicalExtents(root, objectID, make(map[uint64]struct{}), 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.Slice(extents, func(i, j int) bool { return extents[i].logical < extents[j].logical })
|
||||
|
||||
return extents, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) dataExtents(objectID uint64) ([]apfsExtent, error) {
|
||||
if e.filesystem.Volume.FextTreeOid != 0 {
|
||||
return e.physicalExtents(objectID)
|
||||
}
|
||||
|
||||
records, err := e.recordsForObject(objectID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var extents []apfsExtent
|
||||
for _, record := range records {
|
||||
if record.Hdr.GetType() != types.APFS_TYPE_FILE_EXTENT {
|
||||
continue
|
||||
}
|
||||
key, keyOK := record.Key.(types.JFileExtentKeyT)
|
||||
value, valueOK := record.Val.(types.JFileExtentValT)
|
||||
if keyOK && valueOK {
|
||||
extents = append(extents, apfsExtent{
|
||||
logical: key.LogicalAddr,
|
||||
physical: value.PhysBlockNum,
|
||||
length: value.Length(),
|
||||
})
|
||||
}
|
||||
}
|
||||
sort.Slice(extents, func(i, j int) bool { return extents[i].logical < extents[j].logical })
|
||||
|
||||
return extents, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) collectPhysicalExtents(node types.BTreeNodePhys, objectID uint64, visited map[uint64]struct{}, depth int) ([]apfsExtent, error) {
|
||||
if depth > apfsMaximumTreeDepth {
|
||||
return nil, fmt.Errorf("physical extent tree exceeds maximum depth")
|
||||
}
|
||||
if node.IsLeaf() {
|
||||
var extents []apfsExtent
|
||||
for _, raw := range node.Entries {
|
||||
entry, ok := raw.(types.FextNodeEntry)
|
||||
if ok && entry.Key.PrivateID == objectID {
|
||||
extents = append(extents, apfsExtent{
|
||||
logical: entry.Key.LogicalAddr,
|
||||
physical: entry.Val.PhysBlockNum,
|
||||
length: entry.Val.Length(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return extents, nil
|
||||
}
|
||||
|
||||
var extents []apfsExtent
|
||||
for index, raw := range node.Entries {
|
||||
entry, ok := raw.(types.OMapNodeEntry)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("physical extent tree contains an invalid index entry")
|
||||
}
|
||||
lower := uint64(entry.Key.Oid)
|
||||
upper := ^uint64(0)
|
||||
if index+1 < len(node.Entries) {
|
||||
next, ok := node.Entries[index+1].(types.OMapNodeEntry)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("physical extent tree contains an invalid index entry")
|
||||
}
|
||||
upper = uint64(next.Key.Oid)
|
||||
}
|
||||
if objectID < lower || objectID > upper {
|
||||
continue
|
||||
}
|
||||
if _, seen := visited[entry.PAddr]; seen {
|
||||
continue
|
||||
}
|
||||
visited[entry.PAddr] = struct{}{}
|
||||
|
||||
object, err := types.ReadObj(e.device, entry.PAddr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read physical extent child %#x: %w", entry.PAddr, err)
|
||||
}
|
||||
child, ok := object.Body.(types.BTreeNodePhys)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("physical extent child %#x is not a tree node", entry.PAddr)
|
||||
}
|
||||
childExtents, err := e.collectPhysicalExtents(child, objectID, visited, depth+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
extents = append(extents, childExtents...)
|
||||
}
|
||||
|
||||
return extents, nil
|
||||
}
|
||||
|
||||
func readAPFSBlock(device disk.Device, data []byte, physicalAddress uint64) (int, error) {
|
||||
var count int
|
||||
var err error
|
||||
if raw, ok := device.(*readerDevice); ok {
|
||||
count, err = raw.source.ReadAt(data, int64(physicalAddress*apfsBlockSize))
|
||||
} else {
|
||||
count, err = device.ReadAt(data, int64(physicalAddress*apfsBlockSize))
|
||||
}
|
||||
if err != nil {
|
||||
return count, fmt.Errorf("read Apple filesystem block: %w", err)
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
type apfsExtentReader struct {
|
||||
device disk.Device
|
||||
extents []apfsExtent
|
||||
size uint64
|
||||
}
|
||||
|
||||
func newAPFSExtentReader(device disk.Device, extents []apfsExtent, size uint64) (*apfsExtentReader, error) {
|
||||
if size > math.MaxInt64 {
|
||||
return nil, fmt.Errorf("file size %d exceeds the supported maximum", size)
|
||||
}
|
||||
|
||||
sort.Slice(extents, func(i, j int) bool { return extents[i].logical < extents[j].logical })
|
||||
position := uint64(0)
|
||||
for _, extent := range extents {
|
||||
if extent.length == 0 || extent.logical != position || extent.physical > ^uint64(0)/apfsBlockSize {
|
||||
return nil, fmt.Errorf("file has invalid or sparse physical extents")
|
||||
}
|
||||
physicalOffset := extent.physical * apfsBlockSize
|
||||
if physicalOffset > device.GetSize() || extent.length > device.GetSize()-physicalOffset {
|
||||
return nil, fmt.Errorf("file extent exceeds the Apple filesystem image")
|
||||
}
|
||||
position += extent.length
|
||||
if position < extent.logical {
|
||||
return nil, fmt.Errorf("file extent length overflows")
|
||||
}
|
||||
}
|
||||
if position < size {
|
||||
return nil, fmt.Errorf("file extents cover %d bytes, expected %d", position, size)
|
||||
}
|
||||
|
||||
return &apfsExtentReader{device: device, extents: extents, size: size}, nil
|
||||
}
|
||||
|
||||
func (r *apfsExtentReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||
if offset < 0 {
|
||||
return 0, fmt.Errorf("negative file offset")
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
position := uint64(offset)
|
||||
if position >= r.size {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
written := 0
|
||||
for written < len(data) && position < r.size {
|
||||
index := sort.Search(len(r.extents), func(index int) bool {
|
||||
extent := r.extents[index]
|
||||
|
||||
return extent.logical+extent.length > position
|
||||
})
|
||||
if index == len(r.extents) || position < r.extents[index].logical {
|
||||
return written, io.ErrUnexpectedEOF
|
||||
}
|
||||
extent := r.extents[index]
|
||||
available := min(extent.logical+extent.length-position, r.size-position)
|
||||
count := min(uint64(len(data)-written), available)
|
||||
physicalOffset := extent.physical*apfsBlockSize + position - extent.logical
|
||||
n, err := r.device.ReadAt(data[written:written+int(count)], int64(physicalOffset))
|
||||
written += n
|
||||
position += uint64(n)
|
||||
if err != nil {
|
||||
return written, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
if n != int(count) {
|
||||
return written, io.ErrUnexpectedEOF
|
||||
}
|
||||
}
|
||||
if written != len(data) {
|
||||
return written, io.EOF
|
||||
}
|
||||
|
||||
return written, nil
|
||||
}
|
||||
|
||||
type decmpfsReader struct {
|
||||
ctx context.Context
|
||||
source io.ReaderAt
|
||||
outputSize uint64
|
||||
method uint32
|
||||
offsets []uint32
|
||||
mu sync.Mutex
|
||||
cache map[uint64][]byte
|
||||
cacheOrder []uint64
|
||||
}
|
||||
|
||||
func newDecmpfsReader(ctx context.Context, source io.ReaderAt, sourceSize, outputSize uint64, method uint32) (*decmpfsReader, error) {
|
||||
if outputSize > math.MaxInt64 {
|
||||
return nil, fmt.Errorf("compressed file size %d exceeds the supported maximum", outputSize)
|
||||
}
|
||||
if sourceSize < 8 {
|
||||
return nil, fmt.Errorf("compressed resource fork is too small")
|
||||
}
|
||||
|
||||
var first [4]byte
|
||||
if _, err := source.ReadAt(first[:], 0); err != nil {
|
||||
return nil, fmt.Errorf("read compression index: %w", err)
|
||||
}
|
||||
tableSize := uint64(binary.LittleEndian.Uint32(first[:]))
|
||||
blockCount := (outputSize + decmpfsBlockSize - 1) / decmpfsBlockSize
|
||||
expectedTableSize := (blockCount + 1) * 4
|
||||
if tableSize != expectedTableSize || tableSize > sourceSize {
|
||||
return nil, fmt.Errorf("compression index has size %d, expected %d", tableSize, expectedTableSize)
|
||||
}
|
||||
|
||||
table := make([]byte, tableSize)
|
||||
if _, err := source.ReadAt(table, 0); err != nil {
|
||||
return nil, fmt.Errorf("read compression index: %w", err)
|
||||
}
|
||||
offsets := make([]uint32, blockCount+1)
|
||||
for index := range offsets {
|
||||
offsets[index] = binary.LittleEndian.Uint32(table[index*4:])
|
||||
}
|
||||
for index := uint64(0); index < blockCount; index++ {
|
||||
start, end := uint64(offsets[index]), uint64(offsets[index+1])
|
||||
if start < tableSize || end <= start || end > sourceSize || end-start > decmpfsBlockSize+1 {
|
||||
return nil, fmt.Errorf("compressed block %d has invalid range %d..%d", index, start, end)
|
||||
}
|
||||
}
|
||||
if uint64(offsets[len(offsets)-1]) != sourceSize {
|
||||
return nil, fmt.Errorf("compressed blocks end at %d, expected %d", offsets[len(offsets)-1], sourceSize)
|
||||
}
|
||||
|
||||
return &decmpfsReader{
|
||||
ctx: ctx,
|
||||
source: source,
|
||||
outputSize: outputSize,
|
||||
method: method,
|
||||
offsets: offsets,
|
||||
cache: make(map[uint64][]byte),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *decmpfsReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||
if offset < 0 {
|
||||
return 0, fmt.Errorf("negative compressed file offset")
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err //nolint:wrapcheck // ReaderAt must preserve context cancellation.
|
||||
}
|
||||
position := uint64(offset)
|
||||
if position >= r.outputSize {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
wanted := len(data)
|
||||
if remaining := r.outputSize - position; uint64(wanted) > remaining {
|
||||
wanted = int(remaining)
|
||||
}
|
||||
written := 0
|
||||
for written < wanted {
|
||||
blockIndex := position / decmpfsBlockSize
|
||||
block, err := r.block(blockIndex)
|
||||
if err != nil {
|
||||
return written, err
|
||||
}
|
||||
blockOffset := position % decmpfsBlockSize
|
||||
count := min(wanted-written, len(block)-int(blockOffset))
|
||||
copy(data[written:written+count], block[blockOffset:uint64(count)+blockOffset])
|
||||
written += count
|
||||
position += uint64(count)
|
||||
}
|
||||
if written != len(data) {
|
||||
return written, io.EOF
|
||||
}
|
||||
|
||||
return written, nil
|
||||
}
|
||||
|
||||
func (r *decmpfsReader) block(index uint64) ([]byte, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
if block, ok := r.cache[index]; ok {
|
||||
return block, nil
|
||||
}
|
||||
if index+1 >= uint64(len(r.offsets)) {
|
||||
return nil, io.EOF
|
||||
}
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("read compressed file: %w", err)
|
||||
}
|
||||
|
||||
start, end := uint64(r.offsets[index]), uint64(r.offsets[index+1])
|
||||
compressed := make([]byte, end-start)
|
||||
if _, err := r.source.ReadAt(compressed, int64(start)); err != nil {
|
||||
return nil, fmt.Errorf("read compressed block %d: %w", index, err)
|
||||
}
|
||||
expected := min(uint64(decmpfsBlockSize), r.outputSize-index*decmpfsBlockSize)
|
||||
plain, err := decompressBlock(compressed, r.method, int(expected))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode compressed block %d: %w", index, err)
|
||||
}
|
||||
if uint64(len(plain)) != expected {
|
||||
return nil, fmt.Errorf("decompressed block %d has size %d, expected %d", index, len(plain), expected)
|
||||
}
|
||||
|
||||
const maximumCachedBlocks = 128
|
||||
if len(r.cacheOrder) == maximumCachedBlocks {
|
||||
delete(r.cache, r.cacheOrder[0])
|
||||
r.cacheOrder = r.cacheOrder[1:]
|
||||
}
|
||||
r.cache[index] = plain
|
||||
r.cacheOrder = append(r.cacheOrder, index)
|
||||
|
||||
return plain, nil
|
||||
}
|
||||
|
||||
func decompressBlock(compressed []byte, method uint32, maximumSize int) ([]byte, error) {
|
||||
switch method {
|
||||
case decmpfsLZVN:
|
||||
if compressed[0] == 0x06 {
|
||||
return compressed[1:], nil
|
||||
}
|
||||
|
||||
decoded, err := lzfse.DecompressLZVN(compressed, maximumSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decompress LZVN block: %w", err)
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
case decmpfsLZFSE:
|
||||
if compressed[0] != 'b' {
|
||||
return compressed[1:], nil
|
||||
}
|
||||
|
||||
decoded, err := lzfse.Decompress(compressed)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decompress LZFSE block: %w", err)
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
case decmpfsLZBitmap:
|
||||
if compressed[0] == 0xff {
|
||||
return compressed[1:], nil
|
||||
}
|
||||
|
||||
decoded, err := lzbitmap.Decompress(compressed)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decompress LZBITMAP block: %w", err)
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported compression type %d", method)
|
||||
}
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
ctx context.Context
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func (r *contextReader) Read(data []byte) (int, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err //nolint:wrapcheck // Preserve context cancellation for io.CopyN.
|
||||
}
|
||||
|
||||
return r.reader.Read(data) //nolint:wrapcheck // Reader adapters must preserve io.EOF.
|
||||
}
|
||||
|
||||
func openAPFSDevice(source io.ReaderAt, size int64) (disk.Device, func() error, error) {
|
||||
if size < 36 {
|
||||
return nil, nil, fmt.Errorf("apple filesystem image is too small: %d", size)
|
||||
}
|
||||
|
||||
header := make([]byte, 36)
|
||||
if _, err := source.ReadAt(header, 0); err != nil {
|
||||
return nil, nil, fmt.Errorf("read Apple filesystem header: %w", err)
|
||||
}
|
||||
|
||||
if bytes.Equal(header[32:36], []byte("NXSB")) {
|
||||
device := &readerDevice{source: source, size: uint64(size)}
|
||||
|
||||
return device, device.Close, nil
|
||||
}
|
||||
|
||||
image, err := dmg.NewDMG(io.NewSectionReader(source, 0, size))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("open Apple disk image: %w", err)
|
||||
}
|
||||
|
||||
return image, image.Close, nil
|
||||
}
|
||||
|
||||
type readerDevice struct {
|
||||
source io.ReaderAt
|
||||
size uint64
|
||||
}
|
||||
|
||||
func (d *readerDevice) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *readerDevice) ReadFile(writer *bufio.Writer, offset, length int64) error {
|
||||
if offset < 0 || length < 0 || uint64(offset) > d.size || uint64(length) > d.size-uint64(offset) {
|
||||
return fmt.Errorf("invalid Apple filesystem range %d+%d", offset, length)
|
||||
}
|
||||
|
||||
if _, err := io.CopyN(writer, io.NewSectionReader(d.source, offset, length), length); err != nil {
|
||||
return fmt.Errorf("copy Apple filesystem range: %w", err)
|
||||
}
|
||||
|
||||
if err := writer.Flush(); err != nil {
|
||||
return fmt.Errorf("flush Apple filesystem range: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *readerDevice) GetSize() uint64 {
|
||||
return d.size
|
||||
}
|
||||
|
||||
func (d *readerDevice) ReadAt(data []byte, offset int64) (int, error) {
|
||||
count, err := d.source.ReadAt(data, offset)
|
||||
if count != len(data) || len(data) != int(types.BLOCK_SIZE) || offset%int64(types.BLOCK_SIZE) != 0 {
|
||||
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
|
||||
if !bytes.Equal(data[:apfsObjectHeaderSize], make([]byte, apfsObjectHeaderSize)) {
|
||||
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
|
||||
flags := binary.LittleEndian.Uint16(data[apfsObjectHeaderSize:])
|
||||
if flags&apfsNodeNoHeader == 0 {
|
||||
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
|
||||
objectType := uint32(apfsObjectTypeNode)
|
||||
if flags&apfsNodeRoot != 0 {
|
||||
objectType = apfsObjectTypeBTree
|
||||
}
|
||||
|
||||
// Sealed APFS tree nodes omit the normal object header. Add a synthetic
|
||||
// header after their hash has been verified so go-apfs can decode them.
|
||||
binary.LittleEndian.PutUint64(data[8:16], uint64(offset/int64(types.BLOCK_SIZE)))
|
||||
binary.LittleEndian.PutUint32(data[24:28], apfsObjectNoHeader|objectType)
|
||||
binary.LittleEndian.PutUint32(data[28:32], apfsObjectTypeFSTree)
|
||||
binary.LittleEndian.PutUint64(data[:8], types.CreateChecksum(data))
|
||||
|
||||
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/machimage"
|
||||
)
|
||||
|
||||
const (
|
||||
macOSVersion = "27.0.1"
|
||||
macOSBuild = "26A434"
|
||||
macOSRestoreURL = "https://updates.cdn-apple.com/2026FallFCS/59241290-5d51-4ca8-9df4-31624b9a4eac/UniversalMac_27.0.1_26A434_Restore.ipsw"
|
||||
assetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v5"
|
||||
legacyAssetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v4"
|
||||
)
|
||||
|
||||
type Bundle struct {
|
||||
AppleMediaServices []byte
|
||||
Commerce []byte
|
||||
ADID []byte
|
||||
CoreFP []byte
|
||||
CoreFPICXS []byte
|
||||
FairPlayD []byte
|
||||
FairPlayKext []byte
|
||||
}
|
||||
|
||||
type fileSpec struct {
|
||||
name string
|
||||
size int
|
||||
digest [32]byte
|
||||
}
|
||||
|
||||
var requiredFiles = []fileSpec{
|
||||
{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
|
||||
{name: "commerce", size: 2735088, digest: mustDigest("c4b2088dd39aeb353f59cb57597902e8317aec66ae7da0414b03c5f932771343")},
|
||||
{name: "adid", size: 3047808, digest: mustDigest("43419a206c28bc93ecb8884256088d18306a0a462350f83adbced8e60a94e390")},
|
||||
{name: "CoreFP", size: 30764976, digest: mustDigest("afbc123e688a822d980d5816cc2b52f69fde669d1dca92cf85627e1cbee587f6")},
|
||||
{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
|
||||
{name: "fairplayd", size: 17389744, digest: mustDigest("1e58d37e9602dd0ca5e24b14762063b6c310248b4d3a94272771d815e4ea1784")},
|
||||
{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
|
||||
}
|
||||
|
||||
var legacyFiles = []fileSpec{
|
||||
{
|
||||
name: "AppleMediaServices",
|
||||
size: 14813888,
|
||||
digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4"),
|
||||
},
|
||||
{
|
||||
name: "commerce",
|
||||
size: 8092640,
|
||||
digest: mustDigest("76de40a4a32f691947cb926ce3b128d2fc446f7cac9755f831c406cf5a316ac9"),
|
||||
},
|
||||
{
|
||||
name: "adid",
|
||||
size: 9797952,
|
||||
digest: mustDigest("1fec225b6917206e3d9b00fe636c04878f82bfd06a87a4b6941711de60efab5b"),
|
||||
},
|
||||
{
|
||||
name: "CoreFP",
|
||||
size: 94842464,
|
||||
digest: mustDigest("2c30fa2b5f695fd66c0360dce72f54757d03ddb7107549715c12cb359a003b46"),
|
||||
},
|
||||
{
|
||||
name: "CoreFP.icxs",
|
||||
size: 7365344,
|
||||
digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b"),
|
||||
},
|
||||
{
|
||||
name: "fairplayd",
|
||||
size: 37689264,
|
||||
digest: mustDigest("28b4c7b2a5a0409c5020da55fc3984713a8e2b0eec8557076c8717f7166d003e"),
|
||||
},
|
||||
{
|
||||
name: "FairPlayIOKit",
|
||||
size: 2132320,
|
||||
digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025"),
|
||||
},
|
||||
}
|
||||
|
||||
type bundleLoader struct {
|
||||
gate chan struct{}
|
||||
installed *Bundle
|
||||
resolve func(context.Context) (Bundle, error)
|
||||
}
|
||||
|
||||
var defaultLoader = bundleLoader{gate: make(chan struct{}, 1), resolve: loadBundle}
|
||||
|
||||
// Load resolves and verifies the pinned macOS framework profile once per process.
|
||||
// The returned slices are shared and must not be modified by callers.
|
||||
func Load(ctx context.Context) (Bundle, error) {
|
||||
return defaultLoader.load(ctx)
|
||||
}
|
||||
|
||||
func (l *bundleLoader) load(ctx context.Context) (Bundle, error) {
|
||||
if ctx == nil {
|
||||
return Bundle{}, errors.New("apple asset context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case l.gate <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", ctx.Err())
|
||||
}
|
||||
|
||||
defer func() { <-l.gate }()
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
|
||||
}
|
||||
|
||||
if l.installed != nil {
|
||||
return *l.installed, nil
|
||||
}
|
||||
|
||||
bundle, err := l.resolve(ctx)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
|
||||
}
|
||||
|
||||
l.installed = &bundle
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func loadBundle(ctx context.Context) (Bundle, error) {
|
||||
directory, err := cacheDirectory()
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if bundle, found := loadCachedBundle(directory); found {
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
bundle, err := resolveRemoteImage(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
|
||||
}
|
||||
|
||||
// Keep only the architecture used by the emulator after verifying and caching
|
||||
// the original files. Cloning releases the unused slices of universal binaries.
|
||||
func compactBundle(bundle Bundle) (Bundle, error) {
|
||||
for _, image := range []struct {
|
||||
name string
|
||||
data *[]byte
|
||||
}{
|
||||
{"AppleMediaServices", &bundle.AppleMediaServices},
|
||||
{"commerce", &bundle.Commerce},
|
||||
{"adid", &bundle.ADID},
|
||||
{"CoreFP", &bundle.CoreFP},
|
||||
{"fairplayd", &bundle.FairPlayD},
|
||||
{"FairPlayIOKit", &bundle.FairPlayKext},
|
||||
} {
|
||||
data, err := compactImage(image.name, *image.data)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
*image.data = data
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func compactImage(name string, input []byte) ([]byte, error) {
|
||||
data, err := machimage.ARM64Slice(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select %s architecture: %w", name, err)
|
||||
}
|
||||
|
||||
if len(data) != len(input) {
|
||||
return bytes.Clone(data), nil
|
||||
}
|
||||
|
||||
return data, 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", assetCacheDirectory), nil
|
||||
}
|
||||
|
||||
func loadCachedBundle(directory string) (Bundle, bool) {
|
||||
if bundle, err := readCache(directory); err == nil {
|
||||
return bundle, true
|
||||
}
|
||||
|
||||
legacyDirectory := filepath.Join(filepath.Dir(directory), legacyAssetCacheDirectory)
|
||||
|
||||
bundle, err := readCacheSpecs(legacyDirectory, legacyFiles)
|
||||
if err != nil {
|
||||
return Bundle{}, false
|
||||
}
|
||||
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, false
|
||||
}
|
||||
|
||||
// A verified legacy cache remains usable on read-only mounts. Persist the
|
||||
// smaller representation when possible without requiring a new download.
|
||||
_ = writeCache(directory, bundle)
|
||||
|
||||
return bundle, true
|
||||
}
|
||||
|
||||
func readCache(directory string) (Bundle, error) {
|
||||
return readCacheSpecs(directory, requiredFiles)
|
||||
}
|
||||
|
||||
func readCacheSpecs(directory string, specs []fileSpec) (Bundle, error) {
|
||||
files := make(map[string][]byte, len(specs))
|
||||
|
||||
for _, spec := range specs {
|
||||
data, err := readCacheData(filepath.Join(directory, spec.name), spec.size, &spec)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read cached Apple SAP asset %s: %w", spec.name, err)
|
||||
}
|
||||
|
||||
files[spec.name] = data
|
||||
}
|
||||
|
||||
return bundleFrom(files), nil
|
||||
}
|
||||
|
||||
func readCacheFile(path string, expectedSize int) ([]byte, error) {
|
||||
return readCacheData(path, expectedSize, nil)
|
||||
}
|
||||
|
||||
func readCacheData(path string, expectedSize int, spec *fileSpec) ([]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)
|
||||
}
|
||||
|
||||
var reader io.Reader = file
|
||||
|
||||
var digest hash.Hash
|
||||
if spec != nil {
|
||||
digest = sha256.New()
|
||||
reader = io.TeeReader(file, digest)
|
||||
}
|
||||
|
||||
var data []byte
|
||||
if spec != nil && spec.name != "CoreFP.icxs" {
|
||||
data, err = machimage.ReadARM64(reader, expectedSize)
|
||||
} else {
|
||||
data = make([]byte, expectedSize)
|
||||
_, err = io.ReadFull(reader, data)
|
||||
}
|
||||
|
||||
if 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)
|
||||
}
|
||||
|
||||
if spec != nil && !bytes.Equal(digest.Sum(nil), spec.digest[:]) {
|
||||
return nil, fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
|
||||
}
|
||||
|
||||
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 {
|
||||
if err := validateFile(spec, files[spec.name]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateFile(spec fileSpec, data []byte) error {
|
||||
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{
|
||||
AppleMediaServices: files["AppleMediaServices"],
|
||||
Commerce: files["commerce"],
|
||||
ADID: files["adid"],
|
||||
CoreFP: files["CoreFP"],
|
||||
CoreFPICXS: files["CoreFP.icxs"],
|
||||
FairPlayD: files["fairplayd"],
|
||||
FairPlayKext: files["FairPlayIOKit"],
|
||||
}
|
||||
}
|
||||
|
||||
func bundleFiles(bundle Bundle) map[string][]byte {
|
||||
return map[string][]byte{
|
||||
"AppleMediaServices": bundle.AppleMediaServices,
|
||||
"commerce": bundle.Commerce,
|
||||
"adid": bundle.ADID,
|
||||
"CoreFP": bundle.CoreFP,
|
||||
"CoreFP.icxs": bundle.CoreFPICXS,
|
||||
"fairplayd": bundle.FairPlayD,
|
||||
"FairPlayIOKit": bundle.FairPlayKext,
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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")
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Verified bundle cache", func() {
|
||||
It("shares one successful load across concurrent callers", func() {
|
||||
var calls atomic.Int32
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
data := []byte("verified bundle")
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls.Add(1)
|
||||
close(entered)
|
||||
<-release
|
||||
|
||||
return Bundle{CoreFP: data}, nil
|
||||
}}
|
||||
var workers sync.WaitGroup
|
||||
results := make(chan Bundle, 8)
|
||||
failures := make(chan error, 8)
|
||||
for range 8 {
|
||||
workers.Go(func() {
|
||||
bundle, err := loader.load(context.Background())
|
||||
results <- bundle
|
||||
failures <- err
|
||||
})
|
||||
}
|
||||
Eventually(entered).Should(BeClosed())
|
||||
close(release)
|
||||
workers.Wait()
|
||||
Expect(calls.Load()).To(Equal(int32(1)))
|
||||
for range 8 {
|
||||
Expect(<-failures).NotTo(HaveOccurred())
|
||||
Expect(&(<-results).CoreFP[0]).To(BeIdenticalTo(&data[0]))
|
||||
}
|
||||
})
|
||||
|
||||
It("lets a waiting caller cancel without interrupting the load", func() {
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
close(entered)
|
||||
<-release
|
||||
|
||||
return Bundle{CoreFP: []byte("ready")}, nil
|
||||
}}
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := loader.load(context.Background()); done <- err }()
|
||||
Eventually(entered).Should(BeClosed())
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err := loader.load(ctx)
|
||||
Expect(errors.Is(err, context.DeadlineExceeded)).To(BeTrue())
|
||||
close(release)
|
||||
Eventually(done).Should(Receive(BeNil()))
|
||||
bundle, err := loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(bundle.CoreFP)).To(Equal("ready"))
|
||||
})
|
||||
|
||||
It("retries failed loads", func() {
|
||||
calls := 0
|
||||
failed := errors.New("temporary failure")
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return Bundle{}, failed
|
||||
}
|
||||
|
||||
return Bundle{CoreFP: []byte("ready")}, nil
|
||||
}}
|
||||
_, err := loader.load(context.Background())
|
||||
Expect(err).To(MatchError(failed))
|
||||
bundle, err := loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(bundle.CoreFP)).To(Equal("ready"))
|
||||
Expect(calls).To(Equal(2))
|
||||
})
|
||||
|
||||
It("does not publish a load canceled before completion", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
calls := 0
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls++
|
||||
cancel()
|
||||
|
||||
return Bundle{CoreFP: []byte("ready")}, nil
|
||||
}}
|
||||
_, err := loader.load(ctx)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(loader.installed).To(BeNil())
|
||||
_, err = loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(calls).To(Equal(2))
|
||||
})
|
||||
|
||||
It("rejects nil and canceled contexts even after a successful load", func() {
|
||||
calls := 0
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls++
|
||||
|
||||
return Bundle{}, nil
|
||||
}}
|
||||
_, err := loader.load(nil) //nolint:staticcheck // Verify invalid caller input.
|
||||
Expect(err).To(MatchError(ContainSubstring("context is nil")))
|
||||
_, err = loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err = loader.load(ctx)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(calls).To(Equal(1))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Runtime bundle compaction", func() {
|
||||
It("retains independent arm64e images and preserves thin images and ICXS", func() {
|
||||
fat := make([]byte, 32)
|
||||
for i, value := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
|
||||
binary.BigEndian.PutUint32(fat[i*4:], value)
|
||||
}
|
||||
copy(fat[28:], "arm!")
|
||||
thin, icxs := []byte("thin"), []byte("ICXS")
|
||||
bundle := Bundle{CoreFP: fat, Commerce: fat, ADID: fat, FairPlayD: fat, AppleMediaServices: thin, FairPlayKext: thin, CoreFPICXS: icxs}
|
||||
original := bytes.Clone(fat)
|
||||
compact, err := compactBundle(bundle)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
for _, data := range [][]byte{compact.CoreFP, compact.Commerce, compact.ADID, compact.FairPlayD} {
|
||||
Expect(string(data)).To(Equal("arm!"))
|
||||
Expect(&data[0]).NotTo(BeIdenticalTo(&fat[28]))
|
||||
Expect(cap(data)).To(BeNumerically("<", len(fat)))
|
||||
}
|
||||
Expect(&compact.AppleMediaServices[0]).To(BeIdenticalTo(&thin[0]))
|
||||
Expect(&compact.FairPlayKext[0]).To(BeIdenticalTo(&thin[0]))
|
||||
Expect(&compact.CoreFPICXS[0]).To(BeIdenticalTo(&icxs[0]))
|
||||
Expect(fat).To(Equal(original))
|
||||
Expect(bundle.CoreFP).To(HaveLen(32))
|
||||
})
|
||||
It("verifies the entire cached file before discarding unused architectures", func() {
|
||||
fat := make([]byte, 40)
|
||||
for i, value := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
|
||||
binary.BigEndian.PutUint32(fat[i*4:], value)
|
||||
}
|
||||
copy(fat[28:], "arm!unused!!")
|
||||
originalSpecs := requiredFiles
|
||||
DeferCleanup(func() { requiredFiles = originalSpecs })
|
||||
requiredFiles = []fileSpec{{name: "CoreFP", size: len(fat), digest: sha256.Sum256(fat)}}
|
||||
directory := GinkgoT().TempDir()
|
||||
path := filepath.Join(directory, "CoreFP")
|
||||
Expect(os.WriteFile(path, fat, 0o600)).To(Succeed())
|
||||
bundle, err := readCache(directory)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(bundle.CoreFP)).To(Equal("arm!"))
|
||||
cached, err := os.ReadFile(path)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(cached).To(Equal(fat))
|
||||
fat[len(fat)-1] ^= 0xff
|
||||
Expect(os.WriteFile(path, fat, 0o600)).To(Succeed())
|
||||
_, err = readCache(directory)
|
||||
Expect(err).To(MatchError(ContainSubstring("failed integrity verification")))
|
||||
})
|
||||
|
||||
It("rejects invalid universal images", func() {
|
||||
fat := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(fat, types.MagicFat.Int())
|
||||
_, err := compactBundle(Bundle{CoreFP: fat})
|
||||
Expect(err).To(MatchError(ContainSubstring("select CoreFP architecture")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,691 @@
|
||||
//nolint:wsl // Binary format parsing is clearer when related bounds checks remain adjacent.
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
"github.com/blacktop/go-macho/pkg/fixupchains"
|
||||
machotypes "github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
const (
|
||||
dyldHeaderSize = 568
|
||||
dyldMappingSize = 56
|
||||
dyldImageInfoSize = 32
|
||||
dyldSubcacheEntrySize = 56
|
||||
dyldMaximumMappings = 64
|
||||
dyldMaximumImages = 100_000
|
||||
dyldMaximumSubcaches = 128
|
||||
dyldMaximumPathLength = 4096
|
||||
dyldSlideInfo5Size = 24
|
||||
dyldMachHeader64Size = 32
|
||||
dyldMachSegment64Command = 0x19
|
||||
dyldMaximumLoadCommandsSize = 16 << 20
|
||||
dyldMaximumSlideChainPointers = 1 << 16
|
||||
)
|
||||
|
||||
type dyldCache struct {
|
||||
members []*dyldCacheMember
|
||||
primary *dyldCacheMember
|
||||
slide5 *dyldSlideInfo5
|
||||
relativeSelectorBase uint64
|
||||
}
|
||||
|
||||
type dyldCacheMember struct {
|
||||
file io.ReaderAt
|
||||
close func() error
|
||||
size int64
|
||||
uuid [16]byte
|
||||
mappings []dyldCacheMapping
|
||||
}
|
||||
|
||||
type dyldCacheMapping struct {
|
||||
member *dyldCacheMember
|
||||
address uint64
|
||||
size uint64
|
||||
fileOffset uint64
|
||||
slideInfoOffset uint64
|
||||
slideInfoSize uint64
|
||||
}
|
||||
|
||||
type dyldSlideInfo5 struct {
|
||||
pageSize uint32
|
||||
pageStartsCount uint32
|
||||
valueAdd uint64
|
||||
}
|
||||
|
||||
type dyldCacheFile struct {
|
||||
reader io.ReaderAt
|
||||
size int64
|
||||
close func() error
|
||||
}
|
||||
|
||||
type dyldCacheOpener func(suffix string) (*dyldCacheFile, error)
|
||||
|
||||
type dyldImage struct {
|
||||
member *dyldCacheMember
|
||||
address uint64
|
||||
offset uint64
|
||||
}
|
||||
|
||||
type dyldRebase struct {
|
||||
address uint64
|
||||
target uint64
|
||||
}
|
||||
|
||||
func extractDyldImageFromFiles(opener dyldCacheOpener, imagePath, outputPath string) error {
|
||||
cache, err := openDyldCache(opener)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open shared cache: %w", err)
|
||||
}
|
||||
defer cache.Close()
|
||||
|
||||
image, err := cache.image(imagePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("find %s in shared cache: %w", imagePath, err)
|
||||
}
|
||||
imageMachO, err := cache.openImage(image, machotypes.LC_SYMTAB, machotypes.LC_DYSYMTAB)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s from shared cache: %w", imagePath, err)
|
||||
}
|
||||
defer imageMachO.Close()
|
||||
if err = cache.imageSymbols(image, imageMachO); err != nil {
|
||||
return fmt.Errorf("read %s symbols: %w", imagePath, err)
|
||||
}
|
||||
|
||||
var chainedFixups *fixupchains.DyldChainedFixups
|
||||
if imageMachO.HasFixups() {
|
||||
chainedFixups, err = imageMachO.DyldChainedFixups()
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s chained fixups: %w", imagePath, err)
|
||||
}
|
||||
}
|
||||
if err := imageMachO.Export(outputPath, chainedFixups, imageMachO.GetBaseAddress(), nil); err != nil {
|
||||
return fmt.Errorf("export %s from shared cache: %w", imagePath, err)
|
||||
}
|
||||
|
||||
if err := cache.applySlide(outputPath); err != nil {
|
||||
return fmt.Errorf("apply %s shared-cache pointers: %w", imagePath, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *dyldCache) openImage(image *dyldImage, excluding ...machotypes.LoadCmd) (*macho.File, error) {
|
||||
linkeditAddress, err := image.linkeditAddress()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
linkedit, err := c.mappingForAddress(linkeditAddress)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reader := &dyldCacheReader{cache: c, member: linkedit.member, offset: 0}
|
||||
converter := machotypes.VMAddrConverter{
|
||||
Converter: c.slidePointer,
|
||||
VMAddr2Offet: func(address uint64) (uint64, error) {
|
||||
mapping, err := c.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return mapping.fileOffset + address - mapping.address, nil
|
||||
},
|
||||
Offet2VMAddr: func(offset uint64) (uint64, error) {
|
||||
return c.addressForOffset(image.member, offset)
|
||||
},
|
||||
}
|
||||
sectionReader := machotypes.NewCustomSectionReader(image.member.file, &converter, 0, image.member.size)
|
||||
|
||||
file, err := macho.NewFile(
|
||||
io.NewSectionReader(image.member.file, int64(image.offset), image.member.size-int64(image.offset)),
|
||||
macho.FileConfig{
|
||||
Offset: int64(image.offset),
|
||||
SectionReader: sectionReader,
|
||||
CacheReader: reader,
|
||||
VMAddrConverter: converter,
|
||||
RelativeSelectorBase: c.relativeSelectorBase,
|
||||
LoadExcluding: excluding,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse shared-cache image: %w", err)
|
||||
}
|
||||
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func openDyldCache(opener dyldCacheOpener) (*dyldCache, error) {
|
||||
primary, header, err := openDyldCacheMember(opener, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cache := &dyldCache{members: []*dyldCacheMember{primary}, primary: primary}
|
||||
complete := false
|
||||
|
||||
defer func() {
|
||||
if !complete {
|
||||
_ = cache.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
subcacheOffset := uint64(binary.LittleEndian.Uint32(header[392:]))
|
||||
subcacheCount := uint64(binary.LittleEndian.Uint32(header[396:]))
|
||||
if subcacheCount > dyldMaximumSubcaches || subcacheCount > 0 && !validDyldRange(primary.size, subcacheOffset, subcacheCount*dyldSubcacheEntrySize) {
|
||||
return nil, fmt.Errorf("shared cache has an invalid subcache table")
|
||||
}
|
||||
entries := make([]byte, subcacheCount*dyldSubcacheEntrySize)
|
||||
if len(entries) > 0 {
|
||||
if _, err := primary.file.ReadAt(entries, int64(subcacheOffset)); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache subcache table: %w", err)
|
||||
}
|
||||
}
|
||||
for index := uint64(0); index < subcacheCount; index++ {
|
||||
entry := entries[index*dyldSubcacheEntrySize : (index+1)*dyldSubcacheEntrySize]
|
||||
suffix := strings.TrimRight(string(entry[24:56]), "\x00")
|
||||
if suffix == "" || strings.ContainsAny(suffix, `/\\`) {
|
||||
return nil, fmt.Errorf("shared cache has an invalid subcache suffix")
|
||||
}
|
||||
member, _, err := openDyldCacheMember(opener, suffix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open shared-cache member %s: %w", suffix, err)
|
||||
}
|
||||
if !bytes.Equal(member.uuid[:], entry[:16]) {
|
||||
_ = member.close()
|
||||
|
||||
return nil, fmt.Errorf("shared-cache member %s has an unexpected UUID", suffix)
|
||||
}
|
||||
cache.members = append(cache.members, member)
|
||||
}
|
||||
|
||||
for _, member := range cache.members {
|
||||
for _, mapping := range member.mappings {
|
||||
if mapping.slideInfoSize == 0 {
|
||||
continue
|
||||
}
|
||||
version, err := readDyldSlideVersion(mapping)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if version != 5 {
|
||||
return nil, fmt.Errorf("unsupported shared-cache slide version %d", version)
|
||||
}
|
||||
slide, err := readDyldSlideInfo5(mapping)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cache.slide5 == nil {
|
||||
cache.slide5 = slide
|
||||
} else if cache.slide5.pageSize != slide.pageSize || cache.slide5.valueAdd != slide.valueAdd {
|
||||
return nil, fmt.Errorf("shared-cache members use incompatible slide information")
|
||||
}
|
||||
}
|
||||
}
|
||||
if cache.slide5 == nil {
|
||||
return nil, fmt.Errorf("shared cache has no slide information")
|
||||
}
|
||||
complete = true
|
||||
|
||||
return cache, nil
|
||||
}
|
||||
|
||||
func openDyldCacheMember(opener dyldCacheOpener, suffix string) (*dyldCacheMember, []byte, error) {
|
||||
opened, err := opener(suffix)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
fail := func(err error) (*dyldCacheMember, []byte, error) {
|
||||
_ = opened.close()
|
||||
|
||||
return nil, nil, err
|
||||
}
|
||||
if opened.size < dyldHeaderSize {
|
||||
return fail(fmt.Errorf("shared-cache member is too small"))
|
||||
}
|
||||
header := make([]byte, dyldHeaderSize)
|
||||
if _, err := opened.reader.ReadAt(header, 0); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
magic := strings.TrimRight(string(header[:16]), "\x00")
|
||||
if magic != "dyld_v1 arm64e" {
|
||||
return fail(fmt.Errorf("unsupported shared-cache format %q", magic))
|
||||
}
|
||||
|
||||
mappingOffset := uint64(binary.LittleEndian.Uint32(header[312:]))
|
||||
mappingCount := uint64(binary.LittleEndian.Uint32(header[316:]))
|
||||
if mappingCount == 0 || mappingCount > dyldMaximumMappings || !validDyldRange(opened.size, mappingOffset, mappingCount*dyldMappingSize) {
|
||||
return fail(fmt.Errorf("shared-cache member has an invalid mapping table"))
|
||||
}
|
||||
mappingData := make([]byte, mappingCount*dyldMappingSize)
|
||||
if _, err := opened.reader.ReadAt(mappingData, int64(mappingOffset)); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
|
||||
member := &dyldCacheMember{file: opened.reader, close: opened.close, size: opened.size}
|
||||
copy(member.uuid[:], header[88:104])
|
||||
|
||||
for index := uint64(0); index < mappingCount; index++ {
|
||||
data := mappingData[index*dyldMappingSize : (index+1)*dyldMappingSize]
|
||||
mapping := dyldCacheMapping{
|
||||
member: member,
|
||||
address: binary.LittleEndian.Uint64(data[0:]),
|
||||
size: binary.LittleEndian.Uint64(data[8:]),
|
||||
fileOffset: binary.LittleEndian.Uint64(data[16:]),
|
||||
slideInfoOffset: binary.LittleEndian.Uint64(data[24:]),
|
||||
slideInfoSize: binary.LittleEndian.Uint64(data[32:]),
|
||||
}
|
||||
if mapping.size == 0 || mapping.address+mapping.size < mapping.address || !validDyldRange(opened.size, mapping.fileOffset, mapping.size) || mapping.slideInfoSize != 0 && !validDyldRange(opened.size, mapping.slideInfoOffset, mapping.slideInfoSize) {
|
||||
return fail(fmt.Errorf("shared-cache member has an invalid mapping"))
|
||||
}
|
||||
|
||||
member.mappings = append(member.mappings, mapping)
|
||||
}
|
||||
|
||||
return member, header, nil
|
||||
}
|
||||
|
||||
func validDyldRange(size int64, offset, length uint64) bool {
|
||||
return size >= 0 && offset <= uint64(size) && length <= uint64(size)-offset
|
||||
}
|
||||
|
||||
func (c *dyldCache) Close() error {
|
||||
var first error
|
||||
for _, member := range c.members {
|
||||
if err := member.close(); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
|
||||
return first
|
||||
}
|
||||
|
||||
func (c *dyldCache) image(path string) (*dyldImage, error) {
|
||||
header := make([]byte, dyldHeaderSize)
|
||||
if _, err := c.primary.file.ReadAt(header, 0); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache header: %w", err)
|
||||
}
|
||||
imagesOffset := uint64(binary.LittleEndian.Uint32(header[448:]))
|
||||
imagesCount := uint64(binary.LittleEndian.Uint32(header[452:]))
|
||||
if imagesCount == 0 || imagesCount > dyldMaximumImages || !validDyldRange(c.primary.size, imagesOffset, imagesCount*dyldImageInfoSize) {
|
||||
return nil, fmt.Errorf("shared cache has an invalid image table")
|
||||
}
|
||||
images := make([]byte, imagesCount*dyldImageInfoSize)
|
||||
if _, err := c.primary.file.ReadAt(images, int64(imagesOffset)); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache image table: %w", err)
|
||||
}
|
||||
for index := uint64(0); index < imagesCount; index++ {
|
||||
data := images[index*dyldImageInfoSize : (index+1)*dyldImageInfoSize]
|
||||
address := binary.LittleEndian.Uint64(data)
|
||||
pathOffset := uint64(binary.LittleEndian.Uint32(data[24:]))
|
||||
name, err := readDyldCString(c.primary.file, c.primary.size, pathOffset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if name != path {
|
||||
continue
|
||||
}
|
||||
mapping, err := c.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &dyldImage{
|
||||
member: mapping.member,
|
||||
address: address,
|
||||
offset: mapping.fileOffset + address - mapping.address,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("image was not found")
|
||||
}
|
||||
|
||||
func readDyldCString(file io.ReaderAt, size int64, offset uint64) (string, error) {
|
||||
if !validDyldRange(size, offset, 1) {
|
||||
return "", fmt.Errorf("shared cache contains an invalid string offset")
|
||||
}
|
||||
limit := min(uint64(dyldMaximumPathLength), uint64(size)-offset)
|
||||
data := make([]byte, limit)
|
||||
n, err := file.ReadAt(data, int64(offset))
|
||||
if err != nil && err != io.EOF {
|
||||
return "", fmt.Errorf("read shared-cache string: %w", err)
|
||||
}
|
||||
data = data[:n]
|
||||
if end := bytes.IndexByte(data, 0); end >= 0 {
|
||||
return string(data[:end]), nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("shared-cache string is not terminated")
|
||||
}
|
||||
|
||||
func (c *dyldCache) mappingForAddress(address uint64) (*dyldCacheMapping, error) {
|
||||
for _, member := range c.members {
|
||||
for index := range member.mappings {
|
||||
mapping := &member.mappings[index]
|
||||
if mapping.address <= address && address < mapping.address+mapping.size {
|
||||
return mapping, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("address %#x is outside the shared cache", address)
|
||||
}
|
||||
|
||||
func (c *dyldCache) addressForOffset(member *dyldCacheMember, offset uint64) (uint64, error) {
|
||||
for _, mapping := range member.mappings {
|
||||
if mapping.fileOffset <= offset && offset < mapping.fileOffset+mapping.size {
|
||||
return mapping.address + offset - mapping.fileOffset, nil
|
||||
}
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("offset %#x is outside the shared-cache member", offset)
|
||||
}
|
||||
|
||||
func (c *dyldCache) slidePointer(pointer uint64) uint64 {
|
||||
if pointer == 0 {
|
||||
return 0
|
||||
}
|
||||
if _, err := c.mappingForAddress(pointer); err == nil {
|
||||
return pointer
|
||||
}
|
||||
|
||||
return c.slide5.decode(pointer)
|
||||
}
|
||||
|
||||
func (i *dyldImage) linkeditAddress() (uint64, error) {
|
||||
header := make([]byte, dyldMachHeader64Size)
|
||||
if _, err := i.member.file.ReadAt(header, int64(i.offset)); err != nil {
|
||||
return 0, fmt.Errorf("read Mach-O header: %w", err)
|
||||
}
|
||||
if binary.LittleEndian.Uint32(header) != uint32(machotypes.Magic64) {
|
||||
return 0, fmt.Errorf("image has an invalid Mach-O magic")
|
||||
}
|
||||
commandCount := binary.LittleEndian.Uint32(header[16:])
|
||||
commandsSize := uint64(binary.LittleEndian.Uint32(header[20:]))
|
||||
if commandsSize > dyldMaximumLoadCommandsSize || !validDyldRange(i.member.size, i.offset+dyldMachHeader64Size, commandsSize) {
|
||||
return 0, fmt.Errorf("image has invalid load commands")
|
||||
}
|
||||
commands := make([]byte, commandsSize)
|
||||
if _, err := i.member.file.ReadAt(commands, int64(i.offset+dyldMachHeader64Size)); err != nil {
|
||||
return 0, fmt.Errorf("read Mach-O load commands: %w", err)
|
||||
}
|
||||
for index, offset := uint32(0), uint64(0); index < commandCount; index++ {
|
||||
if offset+8 > uint64(len(commands)) {
|
||||
return 0, fmt.Errorf("image load commands are truncated")
|
||||
}
|
||||
commandSize := uint64(binary.LittleEndian.Uint32(commands[offset+4:]))
|
||||
if commandSize < 8 || offset+commandSize > uint64(len(commands)) {
|
||||
return 0, fmt.Errorf("image has an invalid load command")
|
||||
}
|
||||
if binary.LittleEndian.Uint32(commands[offset:]) == dyldMachSegment64Command && commandSize >= 72 {
|
||||
name := strings.TrimRight(string(commands[offset+8:offset+24]), "\x00")
|
||||
if name == "__LINKEDIT" {
|
||||
return binary.LittleEndian.Uint64(commands[offset+24:]), nil
|
||||
}
|
||||
}
|
||||
offset += commandSize
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("image has no __LINKEDIT segment")
|
||||
}
|
||||
|
||||
type dyldCacheReader struct {
|
||||
cache *dyldCache
|
||||
member *dyldCacheMember
|
||||
offset int64
|
||||
}
|
||||
|
||||
func (r *dyldCacheReader) Read(data []byte) (int, error) {
|
||||
n, err := r.member.file.ReadAt(data, r.offset)
|
||||
r.offset += int64(n)
|
||||
|
||||
return n, err //nolint:wrapcheck // Reader adapters must preserve io.EOF.
|
||||
}
|
||||
|
||||
func (r *dyldCacheReader) Seek(offset int64, whence int) (int64, error) {
|
||||
switch whence {
|
||||
case io.SeekStart:
|
||||
case io.SeekCurrent:
|
||||
offset += r.offset
|
||||
case io.SeekEnd:
|
||||
offset += r.member.size
|
||||
default:
|
||||
return 0, fmt.Errorf("invalid seek mode")
|
||||
}
|
||||
if offset < 0 {
|
||||
return 0, fmt.Errorf("negative shared-cache offset")
|
||||
}
|
||||
r.offset = offset
|
||||
|
||||
return offset, nil
|
||||
}
|
||||
|
||||
func (r *dyldCacheReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||
return r.member.file.ReadAt(data, offset) //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
|
||||
func (r *dyldCacheReader) SeekToAddr(address uint64) error {
|
||||
mapping, err := r.cache.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.member = mapping.member
|
||||
r.offset = int64(mapping.fileOffset + address - mapping.address)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *dyldCacheReader) ReadAtAddr(data []byte, address uint64) (int, error) {
|
||||
written := 0
|
||||
for written < len(data) {
|
||||
mapping, err := r.cache.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return written, err
|
||||
}
|
||||
available := mapping.address + mapping.size - address
|
||||
count := min(uint64(len(data)-written), available)
|
||||
offset := mapping.fileOffset + address - mapping.address
|
||||
n, err := mapping.member.file.ReadAt(data[written:written+int(count)], int64(offset))
|
||||
written += n
|
||||
address += uint64(n)
|
||||
if err != nil {
|
||||
return written, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
if n != int(count) {
|
||||
return written, io.ErrUnexpectedEOF
|
||||
}
|
||||
}
|
||||
|
||||
return written, nil
|
||||
}
|
||||
|
||||
func readDyldSlideVersion(mapping dyldCacheMapping) (uint32, error) {
|
||||
if mapping.slideInfoSize < 4 {
|
||||
return 0, fmt.Errorf("shared cache has truncated slide information")
|
||||
}
|
||||
var data [4]byte
|
||||
if _, err := mapping.member.file.ReadAt(data[:], int64(mapping.slideInfoOffset)); err != nil {
|
||||
return 0, fmt.Errorf("read shared-cache slide version: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint32(data[:]), nil
|
||||
}
|
||||
|
||||
func readDyldSlideInfo5(mapping dyldCacheMapping) (*dyldSlideInfo5, error) {
|
||||
if mapping.slideInfoSize < dyldSlideInfo5Size {
|
||||
return nil, fmt.Errorf("shared cache has truncated slide information")
|
||||
}
|
||||
data := make([]byte, dyldSlideInfo5Size)
|
||||
if _, err := mapping.member.file.ReadAt(data, int64(mapping.slideInfoOffset)); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache slide information: %w", err)
|
||||
}
|
||||
if binary.LittleEndian.Uint32(data) != 5 {
|
||||
return nil, fmt.Errorf("unsupported shared-cache slide version %d", binary.LittleEndian.Uint32(data))
|
||||
}
|
||||
slide := &dyldSlideInfo5{
|
||||
pageSize: binary.LittleEndian.Uint32(data[4:]),
|
||||
pageStartsCount: binary.LittleEndian.Uint32(data[8:]),
|
||||
valueAdd: binary.LittleEndian.Uint64(data[16:]),
|
||||
}
|
||||
if slide.pageSize == 0 || uint64(dyldSlideInfo5Size)+uint64(slide.pageStartsCount)*2 > mapping.slideInfoSize {
|
||||
return nil, fmt.Errorf("shared cache has invalid slide information")
|
||||
}
|
||||
|
||||
return slide, nil
|
||||
}
|
||||
|
||||
func (s *dyldSlideInfo5) decode(pointer uint64) uint64 {
|
||||
if pointer == 0 {
|
||||
return 0
|
||||
}
|
||||
target := pointer & ((uint64(1) << 34) - 1)
|
||||
if pointer>>63 == 0 {
|
||||
target |= (pointer >> 34 & 0xff) << 56
|
||||
}
|
||||
|
||||
return s.valueAdd + target
|
||||
}
|
||||
|
||||
func (c *dyldCache) applySlide(path string) error {
|
||||
file, err := os.OpenFile(path, os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open exported image: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
exported, err := macho.NewFile(file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse exported image: %w", err)
|
||||
}
|
||||
defer exported.Close()
|
||||
|
||||
for _, segment := range exported.Segments() {
|
||||
mapping, err := c.mappingForAddress(segment.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mapping.slideInfoOffset == 0 {
|
||||
continue
|
||||
}
|
||||
pageSize, err := c.slidePageSize(*mapping)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
start := (segment.Addr - mapping.address) / pageSize
|
||||
end := (segment.Addr + segment.Memsz - mapping.address + pageSize) / pageSize
|
||||
rebases, err := c.rebases(*mapping, start, end)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, rebase := range rebases {
|
||||
offset, err := exported.GetOffset(rebase.address)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if _, err := file.Seek(int64(offset), io.SeekStart); err != nil {
|
||||
return fmt.Errorf("seek to exported pointer %#x: %w", offset, err)
|
||||
}
|
||||
if err := binary.Write(file, binary.LittleEndian, rebase.target); err != nil {
|
||||
return fmt.Errorf("write exported pointer %#x: %w", rebase.target, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := file.Sync(); err != nil {
|
||||
return fmt.Errorf("sync exported image: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *dyldCache) rebases(mapping dyldCacheMapping, startPage, endPage uint64) ([]dyldRebase, error) {
|
||||
version, err := readDyldSlideVersion(mapping)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if version != 5 {
|
||||
return nil, fmt.Errorf("unsupported shared-cache slide version %d", version)
|
||||
}
|
||||
|
||||
slide, err := readDyldSlideInfo5(mapping)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
starts, err := readDyldSlideArray(mapping, dyldSlideInfo5Size, slide.pageStartsCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if endPage == 0 || endPage > uint64(len(starts)) {
|
||||
endPage = uint64(len(starts))
|
||||
}
|
||||
if startPage > endPage {
|
||||
return nil, fmt.Errorf("invalid shared-cache slide page range")
|
||||
}
|
||||
|
||||
var rebases []dyldRebase
|
||||
|
||||
for page := startPage; page < endPage; page++ {
|
||||
start := starts[page]
|
||||
if start == 0xffff {
|
||||
continue
|
||||
}
|
||||
pageFileOffset := mapping.fileOffset + page*uint64(slide.pageSize)
|
||||
pageAddress := mapping.address + page*uint64(slide.pageSize)
|
||||
offset := uint64(start)
|
||||
for count := 0; count < dyldMaximumSlideChainPointers; count++ {
|
||||
if offset+8 > uint64(slide.pageSize) {
|
||||
return nil, fmt.Errorf("shared-cache slide chain leaves its page")
|
||||
}
|
||||
var data [8]byte
|
||||
if _, err := mapping.member.file.ReadAt(data[:], int64(pageFileOffset+offset)); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache slide pointer: %w", err)
|
||||
}
|
||||
pointer := binary.LittleEndian.Uint64(data[:])
|
||||
rebases = append(rebases, dyldRebase{
|
||||
address: pageAddress + offset,
|
||||
target: slide.decode(pointer),
|
||||
})
|
||||
next := pointer >> 52 & 0x7ff
|
||||
if next == 0 {
|
||||
break
|
||||
}
|
||||
offset += next * 8
|
||||
if count == dyldMaximumSlideChainPointers-1 {
|
||||
return nil, fmt.Errorf("shared-cache slide chain is too long")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rebases, nil
|
||||
}
|
||||
|
||||
func (c *dyldCache) slidePageSize(mapping dyldCacheMapping) (uint64, error) {
|
||||
slide, err := readDyldSlideInfo5(mapping)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return uint64(slide.pageSize), nil
|
||||
}
|
||||
|
||||
func readDyldSlideArray(mapping dyldCacheMapping, offset, count uint32) ([]uint16, error) {
|
||||
if count == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
data := make([]byte, uint64(count)*2)
|
||||
if _, err := mapping.member.file.ReadAt(data, int64(mapping.slideInfoOffset+uint64(offset))); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache slide table: %w", err)
|
||||
}
|
||||
values := make([]uint16, count)
|
||||
for index := range values {
|
||||
values[index] = binary.LittleEndian.Uint16(data[index*2:])
|
||||
}
|
||||
|
||||
return values, nil
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
machotypes "github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
// imageSymbols restores symbol load commands without allocating the cache-wide string table.
|
||||
// Export needs only this image's nlists and the strings they actually reference.
|
||||
func (c *dyldCache) imageSymbols(image *dyldImage, f *macho.File) error {
|
||||
header := make([]byte, dyldMachHeader64Size)
|
||||
if _, err := image.member.file.ReadAt(header, int64(image.offset)); err != nil {
|
||||
return fmt.Errorf("read image header: %w", err)
|
||||
}
|
||||
|
||||
size := uint64(binary.LittleEndian.Uint32(header[20:]))
|
||||
if size > dyldMaximumLoadCommandsSize {
|
||||
return fmt.Errorf("invalid image load command size")
|
||||
}
|
||||
|
||||
commands := make([]byte, size)
|
||||
if _, err := image.member.file.ReadAt(commands, int64(image.offset)+dyldMachHeader64Size); err != nil {
|
||||
return fmt.Errorf("read image commands: %w", err)
|
||||
}
|
||||
|
||||
address, err := image.linkeditAddress()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mapping, err := c.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
loads := make([]macho.Load, 0, len(f.Loads)+2)
|
||||
index := 0
|
||||
|
||||
for offset := 0; offset < len(commands); {
|
||||
if len(commands)-offset < 8 {
|
||||
return fmt.Errorf("truncated image command")
|
||||
}
|
||||
|
||||
length := int(binary.LittleEndian.Uint32(commands[offset+4:]))
|
||||
if length < 8 || length > len(commands)-offset {
|
||||
return fmt.Errorf("invalid image command size")
|
||||
}
|
||||
|
||||
raw := commands[offset : offset+length]
|
||||
offset += length
|
||||
|
||||
command := machotypes.LoadCmd(binary.LittleEndian.Uint32(raw))
|
||||
switch command {
|
||||
case machotypes.LC_SYMTAB:
|
||||
table, err := readImageSymbols(mapping.member, raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
f.Symtab = table
|
||||
loads = append(loads, table)
|
||||
case machotypes.LC_DYSYMTAB:
|
||||
table := &macho.Dysymtab{LoadBytes: raw}
|
||||
if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &table.DysymtabCmd); err != nil {
|
||||
return fmt.Errorf("decode dynamic symbols: %w", err)
|
||||
}
|
||||
|
||||
if f.Symtab == nil || uint64(table.Iundefsym)+uint64(table.Nundefsym) > uint64(len(f.Symtab.Syms)) || table.Nindirectsyms > 4<<20 {
|
||||
return fmt.Errorf("invalid dynamic symbol table")
|
||||
}
|
||||
|
||||
if !validDyldRange(mapping.member.size, uint64(table.Indirectsymoff), uint64(table.Nindirectsyms)*4) {
|
||||
return fmt.Errorf("indirect symbols exceed cache member")
|
||||
}
|
||||
|
||||
encoded := make([]byte, int(table.Nindirectsyms)*4)
|
||||
if _, err := mapping.member.file.ReadAt(encoded, int64(table.Indirectsymoff)); err != nil {
|
||||
return fmt.Errorf("read indirect symbols: %w", err)
|
||||
}
|
||||
|
||||
table.IndirectSyms = make([]uint32, table.Nindirectsyms)
|
||||
if err := binary.Read(bytes.NewReader(encoded), binary.LittleEndian, table.IndirectSyms); err != nil {
|
||||
return fmt.Errorf("decode indirect symbols: %w", err)
|
||||
}
|
||||
|
||||
f.Dysymtab = table
|
||||
loads = append(loads, table)
|
||||
default:
|
||||
if index >= len(f.Loads) || f.Loads[index].Command() != command {
|
||||
return fmt.Errorf("image load command order changed")
|
||||
}
|
||||
|
||||
loads = append(loads, f.Loads[index])
|
||||
index++
|
||||
}
|
||||
}
|
||||
|
||||
f.Loads = loads
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// readImageSymbols decodes just the referenced names, preserving go-macho's symbol normalization.
|
||||
func readImageSymbols(member *dyldCacheMember, raw []byte) (*macho.Symtab, error) {
|
||||
table := &macho.Symtab{LoadBytes: raw}
|
||||
if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &table.SymtabCmd); err != nil {
|
||||
return nil, fmt.Errorf("decode symbols: %w", err)
|
||||
}
|
||||
|
||||
if table.Nsyms > 4<<20 || !validDyldRange(member.size, uint64(table.Symoff), uint64(table.Nsyms)*16) || !validDyldRange(member.size, uint64(table.Stroff), uint64(table.Strsize)) {
|
||||
return nil, fmt.Errorf("invalid image symbol table")
|
||||
}
|
||||
|
||||
encoded := make([]byte, int(table.Nsyms)*16)
|
||||
if _, err := member.file.ReadAt(encoded, int64(table.Symoff)); err != nil {
|
||||
return nil, fmt.Errorf("read image symbols: %w", err)
|
||||
}
|
||||
|
||||
readName := func(offset uint64) (string, error) {
|
||||
if offset >= uint64(table.Strsize) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
name, err := readDyldCString(member.file, int64(uint64(table.Stroff)+uint64(table.Strsize)), uint64(table.Stroff)+offset)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if strings.HasPrefix(name, "_") && strings.Contains(name, ".") {
|
||||
name = name[1:]
|
||||
}
|
||||
|
||||
return name, nil
|
||||
}
|
||||
reader := bytes.NewReader(encoded)
|
||||
|
||||
table.Syms = make([]macho.Symbol, 0, table.Nsyms)
|
||||
for i := uint32(0); i < table.Nsyms; i++ {
|
||||
var n machotypes.Nlist64
|
||||
if err := binary.Read(reader, binary.LittleEndian, &n); err != nil {
|
||||
return nil, fmt.Errorf("decode image symbol: %w", err)
|
||||
}
|
||||
|
||||
name, err := readName(uint64(n.Name))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
indirect := ""
|
||||
if n.Type.IsIndirectSym() {
|
||||
indirect, err = readName(n.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
table.Syms = append(table.Syms, macho.Symbol{Name: name, IndirectName: indirect, Type: n.Type, Sect: n.Sect, Desc: n.Desc, Value: n.Value})
|
||||
}
|
||||
|
||||
return table, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
|
||||
machotypes "github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
type sparseSymbols struct {
|
||||
data []byte
|
||||
largest int
|
||||
}
|
||||
|
||||
// ReadAt simulates a large sparse cache and records the largest requested allocation.
|
||||
func (s *sparseSymbols) ReadAt(output []byte, offset int64) (int, error) {
|
||||
s.largest = max(s.largest, len(output))
|
||||
|
||||
if offset < 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
clear(output)
|
||||
|
||||
if offset < int64(len(s.data)) {
|
||||
copy(output, s.data[offset:])
|
||||
}
|
||||
|
||||
return len(output), nil
|
||||
}
|
||||
|
||||
var _ = Describe("Shared-cache symbol loading", func() {
|
||||
It("reads only referenced strings from a gigabyte-sized string table", func() {
|
||||
raw := &sparseSymbols{data: make([]byte, 2048)}
|
||||
names := []byte("\x00_regular\x00_Go.symbol\x00_target.symbol\x00")
|
||||
copy(raw.data[1024:], names)
|
||||
entries := []machotypes.Nlist64{{Nlist: machotypes.Nlist{Name: 1, Type: 0x0f}, Value: 0x180001000}, {Nlist: machotypes.Nlist{Name: 10, Type: 0x0b}, Value: 21}}
|
||||
var table bytes.Buffer
|
||||
for _, entry := range entries {
|
||||
Expect(binary.Write(&table, binary.LittleEndian, entry)).To(Succeed())
|
||||
}
|
||||
copy(raw.data[128:], table.Bytes())
|
||||
var command bytes.Buffer
|
||||
header := machotypes.SymtabCmd{LoadCmd: machotypes.LC_SYMTAB, Len: 24, Symoff: 128, Nsyms: 2, Stroff: 1024, Strsize: 1 << 30}
|
||||
Expect(binary.Write(&command, binary.LittleEndian, header)).To(Succeed())
|
||||
result, err := readImageSymbols(&dyldCacheMember{file: raw, size: 2 << 30}, command.Bytes())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(result.Syms).To(HaveLen(2))
|
||||
Expect(result.Syms[0].Name).To(Equal("_regular"))
|
||||
Expect(result.Syms[1].Name).To(Equal("Go.symbol"))
|
||||
Expect(result.Syms[1].IndirectName).To(Equal("target.symbol"))
|
||||
Expect(raw.largest).To(BeNumerically("<=", 4096))
|
||||
})
|
||||
It("rejects symbol data extending beyond the cache member", func() {
|
||||
var command bytes.Buffer
|
||||
Expect(binary.Write(&command, binary.LittleEndian, machotypes.SymtabCmd{LoadCmd: machotypes.LC_SYMTAB, Len: 24, Symoff: 128, Nsyms: 10, Stroff: 256, Strsize: 128})).To(Succeed())
|
||||
_, err := readImageSymbols(&dyldCacheMember{file: bytes.NewReader(make([]byte, 256)), size: 256}, command.Bytes())
|
||||
Expect(err).To(MatchError(ContainSubstring("invalid image symbol table")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Buffered remote ranges", func() {
|
||||
var source []byte
|
||||
var remote *remoteFile
|
||||
var requests []string
|
||||
var mu sync.Mutex
|
||||
BeforeEach(func() {
|
||||
source = make([]byte, 1<<20)
|
||||
for n := range source {
|
||||
source[n] = byte(n % 251)
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
requests = append(requests, r.Header.Get("Range"))
|
||||
mu.Unlock()
|
||||
http.ServeContent(w, r, "image", time.Time{}, bytes.NewReader(source))
|
||||
}))
|
||||
DeferCleanup(server.Close)
|
||||
requests = nil
|
||||
remote = &remoteFile{ctx: context.Background(), client: server.Client(), url: server.URL, size: int64(len(source))}
|
||||
})
|
||||
It("serves a small sequential stream in bounded larger transfers", func() {
|
||||
output := make([]byte, len(source))
|
||||
for offset := 0; offset < len(output); offset += 4096 {
|
||||
count, err := remote.ReadAt(output[offset:offset+4096], int64(offset))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(4096))
|
||||
}
|
||||
Expect(output).To(Equal(source))
|
||||
mu.Lock()
|
||||
count := len(requests)
|
||||
mu.Unlock()
|
||||
Expect(count).To(Equal(5))
|
||||
Expect(len(remote.cache)).To(BeNumerically("<=", remoteReadAheadSize))
|
||||
})
|
||||
It("keeps sparse metadata requests exact", func() {
|
||||
for _, offset := range []int64{0, 500000, 900000} {
|
||||
output := make([]byte, 8)
|
||||
_, err := remote.ReadAt(output, offset)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(output).To(Equal(source[offset : offset+8]))
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
Expect(requests).To(Equal([]string{"bytes=0-7", "bytes=500000-500007", "bytes=900000-900007"}))
|
||||
})
|
||||
It("isolates cached bytes from caller mutation and reports EOF correctly", func() {
|
||||
data := make([]byte, 4096)
|
||||
_, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
clear(data)
|
||||
_, err = remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(data).To(Equal(source[:4096]))
|
||||
tail := make([]byte, 32)
|
||||
count, err := remote.ReadAt(tail, int64(len(source)-16))
|
||||
Expect(err).To(MatchError(io.EOF))
|
||||
Expect(count).To(Equal(16))
|
||||
Expect(tail[:count]).To(Equal(source[len(source)-16:]))
|
||||
})
|
||||
It("honors cancellation even when data is buffered", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
remote.ctx = ctx
|
||||
data := make([]byte, 32)
|
||||
_, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
cancel()
|
||||
_, err = remote.ReadAt(data, 0)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
})
|
||||
It("supports concurrent independent reads", func() {
|
||||
finished := make(chan error, 8)
|
||||
for n := range 8 {
|
||||
go func() {
|
||||
offset := int64(n * 40000)
|
||||
output := make([]byte, 4096)
|
||||
_, err := remote.ReadAt(output, offset)
|
||||
if err == nil && !bytes.Equal(output, source[offset:offset+4096]) {
|
||||
err = errors.New("incorrect concurrent range")
|
||||
}
|
||||
finished <- err
|
||||
}()
|
||||
}
|
||||
for range 8 {
|
||||
Eventually(finished).Should(Receive(BeNil()))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Interrupted remote responses", func() {
|
||||
It("resumes a short response at the first unread byte", func() {
|
||||
var ranges []string
|
||||
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 8, client: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
ranges = append(ranges, r.Header.Get("Range"))
|
||||
if len(ranges) == 1 {
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-7/8"}}, Body: io.NopCloser(strings.NewReader("abcd"))}, nil
|
||||
}
|
||||
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 4-7/8"}}, Body: io.NopCloser(strings.NewReader("efgh"))}, nil
|
||||
})}}
|
||||
data := make([]byte, 8)
|
||||
count, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(8))
|
||||
Expect(string(data)).To(Equal("abcdefgh"))
|
||||
Expect(ranges).To(Equal([]string{"bytes=0-7", "bytes=4-7"}))
|
||||
})
|
||||
It("rejects incorrect response ranges without caching them", func() {
|
||||
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 8, client: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 1-7/8"}}, Body: io.NopCloser(strings.NewReader("1234567"))}, nil
|
||||
})}}
|
||||
_, err := remote.ReadAt(make([]byte, 8), 0)
|
||||
Expect(err).To(MatchError(ContainSubstring("server returned bytes")))
|
||||
Expect(remote.cache).To(BeEmpty())
|
||||
})
|
||||
It("does not fail a completed requested prefix when speculative tail reads fail", func() {
|
||||
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 1 << 20}
|
||||
calls := 0
|
||||
remote.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
switch calls {
|
||||
case 1:
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-3/1048576"}}, Body: io.NopCloser(strings.NewReader("abcd"))}, nil
|
||||
case 2:
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{fmt.Sprintf("bytes 4-%d/1048576", 4+remoteReadAheadSize-1)}}, Body: io.NopCloser(strings.NewReader("efgh"))}, nil
|
||||
default:
|
||||
return nil, errors.New("connection interrupted")
|
||||
}
|
||||
})}
|
||||
data := make([]byte, 4)
|
||||
_, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
count, err := remote.ReadAt(data, 4)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(4))
|
||||
Expect(string(data)).To(Equal("efgh"))
|
||||
Expect(remote.cacheOffset).To(BeZero())
|
||||
Expect(remote.cache).To(HaveLen(4))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Remote image size probes", func() {
|
||||
DescribeTable("requires exactly the requested byte", func(body string, valid bool) {
|
||||
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-0/123"}}, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
remote, err := openRemoteFile(context.Background(), client)
|
||||
if valid {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(remote.size).To(Equal(int64(123)))
|
||||
} else {
|
||||
Expect(err).To(MatchError(ContainSubstring("probe has an invalid length")))
|
||||
}
|
||||
}, Entry("one byte", "x", true), Entry("empty body", "", false), Entry("too much data", "xx", false))
|
||||
})
|
||||
Loaded 100 of 393 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user