mirror of
https://github.com/majd/ipatool
synced 2026-11-29 02:37:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
ff43c07a32 | ||
|
|
07a0f3310d | ||
|
|
9cfd72d142 | ||
|
|
a16afb5c7b | ||
|
|
ec4b6cfc29 | ||
|
|
83515013cd | ||
|
|
1577e1b8bc | ||
|
|
8d3167cc6e |
No files matched your search
@@ -1,102 +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: Build
|
||||
run: swift build
|
||||
- name: Run tests
|
||||
run: swift test
|
||||
build:
|
||||
name: Build
|
||||
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
|
||||
- name: Upload binary
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-v${{ needs.get_version.outputs.version }}
|
||||
path: .build/apple/Products/Release/ipatool
|
||||
if-no-files-found: error
|
||||
distribute:
|
||||
name: Distribute
|
||||
runs-on: ubuntu-20.04
|
||||
needs: [get_version, build]
|
||||
steps:
|
||||
- name: Download binary
|
||||
uses: actions/download-artifact@v2
|
||||
with:
|
||||
name: ipatool-v${{ needs.get_version.outputs.version }}
|
||||
path: ipatool-v${{ needs.get_version.outputs.version }}
|
||||
- name: Archive binary
|
||||
run: |
|
||||
mv ipatool-v${{ needs.get_version.outputs.version }}/ipatool ipatool
|
||||
zip ipatool-v${{ needs.get_version.outputs.version }}.zip ipatool
|
||||
- name: Upload binary to release
|
||||
uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-v${{ needs.get_version.outputs.version }}.zip
|
||||
asset_name: ipatool-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-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
|
||||
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,65 @@
|
||||
name: Dry Build
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build_windows:
|
||||
name: Build for Windows
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
build_linux:
|
||||
name: Build for Linux
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
- arch: amd64
|
||||
runner: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -o ipatool-linux-$GOARCH
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
build_macos:
|
||||
name: Build for macOS
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
CGO_ENABLED: 1
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
@@ -8,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
|
||||
- name: Upload binary
|
||||
uses: actions/upload-artifact@v2
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -o ipatool
|
||||
env:
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool
|
||||
path: .build/apple/Products/Release/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.25.0"
|
||||
cache: true
|
||||
- run: go generate github.com/majd/ipatool/...
|
||||
- uses: golangci/golangci-lint-action@v8
|
||||
with:
|
||||
version: v2.9
|
||||
@@ -0,0 +1,224 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
get_version:
|
||||
name: Get version
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: set_output
|
||||
run: echo ::set-output name=version::${GITHUB_REF#refs/tags/v}
|
||||
outputs:
|
||||
version: ${{ steps.set_output.outputs.version }}
|
||||
test:
|
||||
name: Run tests
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go generate github.com/majd/ipatool/...
|
||||
- run: go test -v github.com/majd/ipatool/...
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-latest
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-arm64.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: arm64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-amd64.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: amd64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-macos-arm64
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: arm64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_ENABLED: 1
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-macos-amd64
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: amd64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_ENABLED: 1
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
if-no-files-found: error
|
||||
build_linux:
|
||||
name: Build for Linux
|
||||
runs-on: ${{ matrix.runner }}
|
||||
needs: [get_version, test]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
- arch: amd64
|
||||
runner: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-linux-$GOARCH
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
if-no-files-found: error
|
||||
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 }}
|
||||
@@ -6,23 +6,14 @@ on:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
test-networking:
|
||||
name: Test Networking
|
||||
runs-on: macos-12
|
||||
run_tests:
|
||||
name: Run tests
|
||||
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.25.0"
|
||||
cache: true
|
||||
- run: go generate github.com/majd/ipatool/...
|
||||
- run: go test -v github.com/majd/ipatool/...
|
||||
+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,156 +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>
|
||||
</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>
|
||||
@@ -0,0 +1,34 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance for coding agents working in this repository.
|
||||
|
||||
## Repository overview
|
||||
- Project: `ipatool`
|
||||
- Language: Go
|
||||
- Entry point: `main.go`
|
||||
- CLI command implementations: `cmd/`
|
||||
|
||||
## Development workflow
|
||||
1. Keep changes focused and minimal.
|
||||
2. Prefer idiomatic Go and keep command behavior consistent with existing commands in `cmd/`.
|
||||
3. Run formatting and tests before finalizing changes.
|
||||
|
||||
## Local checks
|
||||
Use these commands from the repository root:
|
||||
|
||||
```bash
|
||||
go generate ./...
|
||||
go test ./...
|
||||
go build ./...
|
||||
```
|
||||
|
||||
## Coding conventions
|
||||
- Follow standard Go formatting (`gofmt`).
|
||||
- Avoid introducing new dependencies unless necessary.
|
||||
- Keep user-facing text consistent with existing CLI help/output tone.
|
||||
- Preserve backward compatibility for CLI flags and output formats unless explicitly asked to change them.
|
||||
|
||||
## Commit/PR guidance
|
||||
- Write clear, scoped commit messages.
|
||||
- Summarize what changed and why in PR descriptions.
|
||||
- Include test/build results in your handoff.
|
||||
@@ -1,17 +0,0 @@
|
||||
prefix ?= /usr/local
|
||||
bindir = $(prefix)/bin
|
||||
|
||||
build:
|
||||
xcrun swift build -c release --arch arm64 --arch x86_64
|
||||
|
||||
install: build
|
||||
install -d "$(bindir)"
|
||||
install ".build/apple/Products/Release/ipatool" "$(bindir)"
|
||||
|
||||
uninstall:
|
||||
rm -rf "$(bindir)/ipatool"
|
||||
|
||||
clean:
|
||||
rm -rf .build
|
||||
|
||||
.PHONY: build install uninstall clean
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "KeychainAccess",
|
||||
"repositoryURL": "https://github.com/kishikawakatsumi/KeychainAccess",
|
||||
"state": {
|
||||
"branch": "v4.2.2",
|
||||
"revision": "84e546727d66f1adc5439debad16270d0fdd04e7",
|
||||
"version": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "swift-argument-parser",
|
||||
"repositoryURL": "https://github.com/apple/swift-argument-parser",
|
||||
"state": {
|
||||
"branch": "1.1.2",
|
||||
"revision": "f3c9084a71ef4376f2fabbdf1d3d90a49f1fabdb",
|
||||
"version": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "ZIPFoundation",
|
||||
"repositoryURL": "https://github.com/weichsel/ZIPFoundation",
|
||||
"state": {
|
||||
"branch": "0.9.14",
|
||||
"revision": "7254c74b49cec2cb81520523ba993c671f71b066",
|
||||
"version": null
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
@@ -1,43 +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: [
|
||||
.executableTarget(
|
||||
name: "CLI",
|
||||
dependencies: [
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
.byName(name: "Networking"),
|
||||
.byName(name: "StoreAPI"),
|
||||
.byName(name: "Persistence")
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "StoreAPI",
|
||||
dependencies: [
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
.product(name: "ZIPFoundation", package: "ZIPFoundation"),
|
||||
.byName(name: "Networking"),
|
||||
]
|
||||
),
|
||||
.target(name: "Networking", dependencies: []),
|
||||
.testTarget(name: "NetworkingTests", dependencies: ["Networking"]),
|
||||
.target(name: "Persistence", dependencies: [
|
||||
.byName(name: "KeychainAccess")
|
||||
]),
|
||||
]
|
||||
)
|
||||
@@ -2,26 +2,24 @@
|
||||
|
||||
[](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)
|
||||

|
||||

|
||||
|
||||
`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)
|
||||
- [Package Manager (macOS)](#package-manager-macos)
|
||||
- [Usage](#usage)
|
||||
- [FAQ](https://github.com/majd/ipatool/wiki/FAQ)
|
||||
- [Compiling](#compiling)
|
||||
- [License](#license)
|
||||
- [Releases](https://github.com/majd/ipatool/releases)
|
||||
- [FAQ](https://github.com/majd/ipatool/wiki/FAQ)
|
||||
|
||||
## Requirements
|
||||
|
||||
- macOS 10.11 or later.
|
||||
- Supported operating system (Windows, Linux or macOS).
|
||||
- Apple ID set up to use the App Store.
|
||||
|
||||
## Installation
|
||||
@@ -30,12 +28,11 @@
|
||||
|
||||
You can grab the latest version of `ipatool` from [GitHub releases](https://github.com/majd/ipatool/releases).
|
||||
|
||||
### Homebrew
|
||||
### Package Manager (macOS)
|
||||
|
||||
You can install `ipatool` using [Homebrew](https://brew.sh).
|
||||
|
||||
```
|
||||
$ brew tap majd/repo
|
||||
```shell
|
||||
$ brew install ipatool
|
||||
```
|
||||
|
||||
@@ -44,87 +41,146 @@ $ brew install ipatool
|
||||
To authenticate with the App Store, use the `auth` command.
|
||||
|
||||
```
|
||||
OVERVIEW: Authenticate with the App Store.
|
||||
Authenticate with the App Store
|
||||
|
||||
USAGE: ipatool auth <subcommand>
|
||||
Usage:
|
||||
ipatool auth [command]
|
||||
|
||||
OPTIONS:
|
||||
--version Show the version.
|
||||
-h, --help Show help information.
|
||||
Available Commands:
|
||||
info Show current account info
|
||||
login Login to the App Store
|
||||
revoke Revoke your App Store credentials
|
||||
|
||||
SUBCOMMANDS:
|
||||
login Login to the App Store.
|
||||
revoke Revoke your App Store credentials.
|
||||
Flags:
|
||||
-h, --help help for auth
|
||||
|
||||
See 'ipatool help auth <subcommand>' for detailed help.
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
|
||||
Use "ipatool auth [command] --help" for more information about a command.
|
||||
```
|
||||
|
||||
To search for apps on the App Store, use the `search` command.
|
||||
To search for apps on the App Store, use the `search` command.
|
||||
|
||||
```
|
||||
OVERVIEW: Search for iOS apps available on the App Store.
|
||||
Search for iOS and tvOS apps available on the App Store
|
||||
|
||||
USAGE: ipatool search <term> [--limit <limit>] [--country <country>] [--device-family <device-family>] [--log-level <log-level>]
|
||||
Usage:
|
||||
ipatool search <term> [flags]
|
||||
|
||||
ARGUMENTS:
|
||||
<term> The term to search for.
|
||||
Flags:
|
||||
-h, --help help for search
|
||||
-l, --limit int maximum amount of search results to retrieve (default 5)
|
||||
--platform string Platform to search: iphone, ipad, or appletv
|
||||
|
||||
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.
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To obtain a license for an app, use the `purchase` command.
|
||||
|
||||
```
|
||||
OVERVIEW: Obtain a license for the app from the App Store.
|
||||
Obtain a license for the app from the App Store
|
||||
|
||||
USAGE: ipatool purchase --bundle-identifier <bundle-identifier> [--country <country>] [--device-family <device-family>] [--log-level <log-level>]
|
||||
Usage:
|
||||
ipatool purchase [flags]
|
||||
|
||||
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.
|
||||
Flags:
|
||||
-b, --bundle-identifier string Bundle identifier of the target iOS app (required)
|
||||
-h, --help help for purchase
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To obtain a list of availble app versions to download, use the `list-versions` command.
|
||||
|
||||
```
|
||||
List the available versions of an iOS app
|
||||
|
||||
Usage:
|
||||
ipatool list-versions [flags]
|
||||
|
||||
Flags:
|
||||
-i, --app-id int ID of the target iOS app (required)
|
||||
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
|
||||
-h, --help help for list-versions
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To download a copy of the ipa file, use the `download` command.
|
||||
|
||||
```
|
||||
OVERVIEW: Download (encrypted) iOS app packages from the App Store.
|
||||
Download (encrypted) iOS and tvOS 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]
|
||||
Usage:
|
||||
ipatool download [flags]
|
||||
|
||||
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.
|
||||
Flags:
|
||||
-i, --app-id int ID of the target iOS app (required)
|
||||
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
|
||||
--external-version-id string External version identifier of the target iOS app (defaults to latest version when not specified)
|
||||
-h, --help help for download
|
||||
-o, --output string The destination path of the downloaded app package
|
||||
--platform string Platform to download for: iphone, ipad, or appletv
|
||||
--purchase Obtain a license for the app if needed
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
**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`.
|
||||
To resolve an external version identifier, returned by the `list-versions` command, use the `get-version-metadata` command.
|
||||
|
||||
```
|
||||
Retrieves the metadata for a specific version of an app
|
||||
|
||||
Usage:
|
||||
ipatool get-version-metadata [flags]
|
||||
|
||||
Flags:
|
||||
-i, --app-id int ID of the target iOS app (required)
|
||||
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
|
||||
--external-version-id string External version identifier of the target iOS app (required)
|
||||
-h, --help help for get-version-metadata
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
**Note:** the tool runs in interactive mode by default. Use the `--non-interactive` flag
|
||||
if running in an automated environment.
|
||||
|
||||
## Compiling
|
||||
|
||||
The tool can be compiled using the Go toolchain.
|
||||
|
||||
```shell
|
||||
$ go build -o ipatool
|
||||
```
|
||||
|
||||
Unit tests can be executed with the following commands.
|
||||
|
||||
```shell
|
||||
$ go generate github.com/majd/ipatool/...
|
||||
$ go test -v github.com/majd/ipatool/...
|
||||
```
|
||||
|
||||
## 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,201 +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,249 +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.", 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.", level: .error)
|
||||
case StoreResponse.Error.passwordTokenExpired:
|
||||
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.", 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.", level: .error)
|
||||
case StoreResponse.Error.passwordTokenExpired:
|
||||
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 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 {
|
||||
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,20 +0,0 @@
|
||||
//
|
||||
// IPATool.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
|
||||
@main
|
||||
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,129 +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.", level: .error)
|
||||
case StoreResponse.Error.passwordTokenExpired:
|
||||
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,30 +0,0 @@
|
||||
//
|
||||
// ConsoleLogger.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
final class ConsoleLogger: Logging {
|
||||
private let level: LogLevel
|
||||
|
||||
init(level: LogLevel) {
|
||||
self.level = level
|
||||
}
|
||||
|
||||
func log(_ message: String, level: LogLevel) {
|
||||
guard level <= self.level else { return }
|
||||
print(compile(message, level: level))
|
||||
}
|
||||
|
||||
func log(_ message: String, prefix: String, level: LogLevel) {
|
||||
guard level <= self.level else { return }
|
||||
print("\(prefix)\(compile(message, level: level))")
|
||||
}
|
||||
|
||||
func compile(_ message: String, level: LogLevel) -> String {
|
||||
return "==> \(level.prefix)\(message)".trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
}
|
||||
@@ -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,84 +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,150 +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,109 +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 metadataUrl = URL(fileURLWithPath: NSTemporaryDirectory().appending("\(UUID().uuidString)/iTunesMetadata.plist"))
|
||||
|
||||
try fileManager.createDirectory(at: metadataUrl.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try PropertyListSerialization.data(fromPropertyList: metadata, format: .xml, options: .zero).write(to: metadataUrl)
|
||||
try archive.addEntry(with: metadataUrl.lastPathComponent, relativeTo: metadataUrl.deletingLastPathComponent())
|
||||
try fileManager.removeItem(at: metadataUrl)
|
||||
}
|
||||
|
||||
public func appendSignature(item: StoreResponse.Item) throws {
|
||||
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
|
||||
throw Error.invalidArchive
|
||||
}
|
||||
|
||||
let manifest = try readPlist(archive: archive, matchingSuffix: ".app/SC_Info/Manifest.plist", type: Manifest.self)
|
||||
|
||||
guard let infoEntry = archive.first(where: { $0.path.hasSuffix(".app/Info.plist") }) else {
|
||||
throw Error.invalidAppBundle
|
||||
}
|
||||
|
||||
let appBundleName = URL(fileURLWithPath: infoEntry.path)
|
||||
.deletingLastPathComponent()
|
||||
.deletingPathExtension()
|
||||
.lastPathComponent
|
||||
|
||||
guard let signatureItem = item.signatures.first(where: { $0.id == 0 }), let signatureTargetPath = manifest.paths.first else {
|
||||
throw Error.invalidSignature
|
||||
}
|
||||
|
||||
let signatureBaseUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
|
||||
let signatureUrl = signatureBaseUrl
|
||||
.appendingPathComponent("Payload")
|
||||
.appendingPathComponent(appBundleName)
|
||||
.appendingPathExtension("app")
|
||||
.appendingPathComponent(signatureTargetPath)
|
||||
|
||||
let signatureRelativePath = signatureUrl.path.replacingOccurrences(of: "\(signatureBaseUrl.path)/", with: "")
|
||||
|
||||
try fileManager.createDirectory(at: signatureUrl.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try signatureItem.sinf.write(to: signatureUrl)
|
||||
try archive.addEntry(with: signatureRelativePath, relativeTo: signatureBaseUrl)
|
||||
try fileManager.removeItem(at: signatureBaseUrl)
|
||||
}
|
||||
|
||||
private func readPlist<T: Decodable>(archive: Archive, matchingSuffix: String, type: T.Type) throws -> T {
|
||||
guard let entry = archive.first(where: { $0.path.hasSuffix(matchingSuffix) }) else {
|
||||
throw Error.fileNotFound(matchingSuffix)
|
||||
}
|
||||
|
||||
let url = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent(UUID().uuidString).appendingPathExtension("plist")
|
||||
_ = try archive.extract(entry, to: url)
|
||||
|
||||
let data = try Data(contentsOf: url)
|
||||
let plist = try PropertyListDecoder().decode(type, from: data)
|
||||
|
||||
try FileManager.default.removeItem(at: url)
|
||||
|
||||
return plist
|
||||
}
|
||||
}
|
||||
|
||||
extension SignatureClient {
|
||||
struct Manifest: Codable {
|
||||
let paths: [String]
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case paths = "SinfPaths"
|
||||
}
|
||||
}
|
||||
|
||||
enum Error: Swift.Error {
|
||||
case invalidArchive
|
||||
case invalidAppBundle
|
||||
case invalidSignature
|
||||
case fileNotFound(String)
|
||||
}
|
||||
}
|
||||
@@ -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,179 +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 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.":
|
||||
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).":
|
||||
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,183 +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() {
|
||||
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()
|
||||
} 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 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,41 +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() {
|
||||
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
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/util"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
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 {
|
||||
promptForAuthCode := func() (string, error) {
|
||||
authCode, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read string: %w", err)
|
||||
}
|
||||
|
||||
authCode = strings.Trim(authCode, "\n")
|
||||
authCode = strings.Trim(authCode, "\r")
|
||||
|
||||
return authCode, nil
|
||||
}
|
||||
|
||||
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 password == "" && !interactive {
|
||||
return errors.New("password is required when not running in interactive mode; use the \"--password\" flag")
|
||||
}
|
||||
|
||||
if password == "" && interactive {
|
||||
dependencies.Logger.Log().Msg("enter password:")
|
||||
|
||||
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read password: %w", err)
|
||||
}
|
||||
password = string(bytes)
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
|
||||
// nolint:wrapcheck
|
||||
return retry.Do(func() error {
|
||||
if errors.Is(lastErr, appstore.ErrAuthCodeRequired) && interactive {
|
||||
dependencies.Logger.Log().Msg("enter 2FA code:")
|
||||
|
||||
var err error
|
||||
authCode, err = promptForAuthCode()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read auth code: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies.Logger.Verbose().
|
||||
Str("password", password).
|
||||
Str("email", email).
|
||||
Str("authCode", util.IfEmpty(authCode, "<nil>")).
|
||||
Msg("logging in")
|
||||
|
||||
bag, err := dependencies.AppStore.Bag(appstore.BagInput{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get bag: %w", err)
|
||||
}
|
||||
|
||||
output, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: email,
|
||||
Password: password,
|
||||
AuthCode: authCode,
|
||||
Endpoint: bag.AuthEndpoint,
|
||||
})
|
||||
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", "", "email address for the Apple ID (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")
|
||||
|
||||
_ = cmd.MarkFlagRequired("email")
|
||||
|
||||
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
|
||||
},
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
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"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
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(machine machine.Machine) http.CookieJar {
|
||||
return util.Must(cookiejar.New(&cookiejar.Options{
|
||||
Filename: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName, CookieJarFileName),
|
||||
}))
|
||||
}
|
||||
|
||||
// newKeychain returns a new keychain instance.
|
||||
func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) keychain.Keychain {
|
||||
ring := util.Must(keyring.Open(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{
|
||||
keyring.KeychainBackend,
|
||||
keyring.SecretServiceBackend,
|
||||
keyring.FileBackend,
|
||||
},
|
||||
ServiceName: KeychainServiceName,
|
||||
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
|
||||
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]
|
||||
logger.Log().Msgf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path)
|
||||
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read password: %w", err)
|
||||
}
|
||||
|
||||
password := string(bytes)
|
||||
password = strings.Trim(password, "\n")
|
||||
password = strings.Trim(password, "\r")
|
||||
|
||||
return password, nil
|
||||
},
|
||||
}))
|
||||
|
||||
return keychain.New(keychain.Args{Keyring: ring})
|
||||
}
|
||||
|
||||
// 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)
|
||||
dependencies.OS = operatingsystem.New()
|
||||
dependencies.Machine = machine.New(machine.Args{OS: dependencies.OS})
|
||||
dependencies.CookieJar = newCookieJar(dependencies.Machine)
|
||||
dependencies.Keychain = newKeychain(dependencies.Machine, dependencies.Logger, interactive)
|
||||
dependencies.AppStore = appstore.NewAppStore(appstore.Args{
|
||||
CookieJar: dependencies.CookieJar,
|
||||
OperatingSystem: dependencies.OS,
|
||||
Keychain: dependencies.Keychain,
|
||||
Machine: dependencies.Machine,
|
||||
})
|
||||
|
||||
util.Must("", createConfigDirectory(dependencies.OS, dependencies.Machine))
|
||||
}
|
||||
|
||||
// createConfigDirectory creates the configuration directory for the CLI tool, if needed.
|
||||
func createConfigDirectory(os operatingsystem.OperatingSystem, machine machine.Machine) error {
|
||||
configDirectoryPath := filepath.Join(machine.HomeDirectory(), ConfigDirectoryName)
|
||||
_, err := os.Stat(configDirectoryPath)
|
||||
|
||||
if err != nil && os.IsNotExist(err) {
|
||||
err = os.MkdirAll(configDirectoryPath, 0700)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("could not read metadata: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package cmd
|
||||
|
||||
const (
|
||||
ConfigDirectoryName = ".ipatool"
|
||||
CookieJarFileName = "cookies"
|
||||
KeychainServiceName = "ipatool-auth.service"
|
||||
)
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"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 {
|
||||
var (
|
||||
acquireLicense bool
|
||||
outputPath string
|
||||
appID int64
|
||||
bundleID string
|
||||
externalVersionID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "download",
|
||||
Short: "Download (encrypted) iOS and tvOS 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")
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
purchased := false
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get bag: %w", err)
|
||||
}
|
||||
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
Endpoint: bagOutput.AuthEndpoint,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{
|
||||
Account: acc,
|
||||
BundleID: bundleID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrLicenseRequired) {
|
||||
err := dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: app})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return err
|
||||
}
|
||||
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 := dependencies.AppStore.Download(appstore.DownloadInput{
|
||||
Account: acc,
|
||||
App: app,
|
||||
OutputPath: outputPath,
|
||||
Progress: progress,
|
||||
ExternalVersionID: externalVersionID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = dependencies.AppStore.ReplicateSinf(appstore.ReplicateSinfInput{Sinfs: out.Sinfs, PackagePath: out.DestinationPath})
|
||||
if 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 iOS app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
|
||||
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 iOS app (defaults to latest version when not specified)")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone, ipad, or appletv")
|
||||
cmd.Flags().BoolVar(&acquireLicense, "purchase", false, "Obtain a license for the app if needed")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
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 getVersionMetadataCmd() *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
externalVersionID 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")
|
||||
}
|
||||
|
||||
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) {
|
||||
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get bag: %w", err)
|
||||
}
|
||||
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
Endpoint: bagOutput.AuthEndpoint,
|
||||
})
|
||||
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})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.GetVersionMetadata(appstore.GetVersionMetadataInput{
|
||||
Account: acc,
|
||||
App: app,
|
||||
VersionID: externalVersionID,
|
||||
})
|
||||
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 iOS app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
|
||||
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target iOS app (required)")
|
||||
|
||||
_ = cmd.MarkFlagRequired("external-version-id")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
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 ListVersionsCmd() *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "list-versions",
|
||||
Short: "List the available versions of an iOS 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")
|
||||
}
|
||||
|
||||
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) {
|
||||
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get bag: %w", err)
|
||||
}
|
||||
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
Endpoint: bagOutput.AuthEndpoint,
|
||||
})
|
||||
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})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Account: acc, App: app})
|
||||
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 iOS app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -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,84 @@
|
||||
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 purchaseCmd() *cobra.Command {
|
||||
var bundleID 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 {
|
||||
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) {
|
||||
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get bag: %w", err)
|
||||
}
|
||||
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
Endpoint: bagOutput.AuthEndpoint,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: lookupResult.App})
|
||||
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().StringVarP(&bundleID, "bundle-identifier", "b", "", "Bundle identifier of the target iOS app (required)")
|
||||
_ = cmd.MarkFlagRequired("bundle-identifier")
|
||||
|
||||
return cmd
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
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(purchaseCmd())
|
||||
cmd.AddCommand(searchCmd())
|
||||
cmd.AddCommand(ListVersionsCmd())
|
||||
cmd.AddCommand(getVersionMetadataCmd())
|
||||
|
||||
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 and tvOS 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")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone, ipad, or appletv")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
module github.com/majd/ipatool/v2
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/avast/retry-go v3.0.0+incompatible
|
||||
github.com/byteness/keyring v1.9.0
|
||||
github.com/juju/persistent-cookiejar v1.0.0
|
||||
github.com/onsi/ginkgo/v2 v2.5.0
|
||||
github.com/onsi/gomega v1.24.0
|
||||
github.com/rs/zerolog v1.28.0
|
||||
github.com/schollz/progressbar/v3 v3.13.1
|
||||
github.com/spf13/cobra v1.6.1
|
||||
github.com/thediveo/enumflag/v2 v2.0.1
|
||||
go.uber.org/mock v0.4.0
|
||||
golang.org/x/term v0.43.0
|
||||
howett.net/plist v1.0.0
|
||||
)
|
||||
|
||||
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/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 // indirect
|
||||
github.com/byteness/percent v0.2.2 // indirect
|
||||
github.com/danieljoos/wincred v1.2.3 // indirect
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0 // indirect
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 // indirect
|
||||
github.com/extism/go-sdk v1.7.1 // indirect
|
||||
github.com/go-logr/logr v1.4.2 // 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/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.1 // indirect
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.17 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.14 // indirect
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
|
||||
github.com/noamcohen97/touchid-go v0.3.0 // indirect
|
||||
github.com/opentracing/opentracing-go v1.2.0 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // 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
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/crypto v0.52.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
|
||||
golang.org/x/mod v0.35.0 // indirect
|
||||
golang.org/x/net v0.55.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.45.0 // indirect
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
golang.org/x/tools v0.44.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/errgo.v1 v1.0.1 // indirect
|
||||
gopkg.in/retry.v1 v1.0.3 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -0,0 +1,160 @@
|
||||
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/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/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:HFl8GFmwK19hYuXB8OQ0rTO9WOCgZY9JUy964zaYawY=
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:9HlL8SWBRtCZE7sCNq+c3//H/oHywgSwtocmPTdOij8=
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 h1:j59wGsxaBk6aFBuuYofk2oznMGZYyzFovjDqavlJHM8=
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0/go.mod h1:3FrDGTXj08zj6qtqlIvt0vS8eWNrrYpnXOEbcQgFmvM=
|
||||
github.com/byteness/keyring v1.9.0 h1:9m+7pru+JkMJ8wxma5id5m6pSt2Zx/xPj77kyM+yAVE=
|
||||
github.com/byteness/keyring v1.9.0/go.mod h1:a6CV8t/qfEUERPTP+dqeVfKgib2wz3PIYbMWRfmvmes=
|
||||
github.com/byteness/percent v0.2.2 h1:vnIFh8WBR1xoC+U2etz0EMB1cgp+vsK6vynqTCeDziU=
|
||||
github.com/byteness/percent v0.2.2/go.mod h1:nwavge92FhIyfnldz4YWZD8uxPVvdh8NlzLRd1VYRDs=
|
||||
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
|
||||
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0 h1:LqkkVKAlHFfH9LOEl5fe4p/zL02OhWE7pCufMBG2jLA=
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 h1:idfl8M8rPW93NehFw5H1qqH8yG158t5POr+LX9avbJY=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
|
||||
github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
|
||||
github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA=
|
||||
github.com/frankban/quicktest v1.2.2 h1:xfmOhhoH5fGPgbEAlhLpJH9p0z/0Qizio9osmvn9IUY=
|
||||
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
|
||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||
github.com/go-logr/logr v1.4.2/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/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f h1:Fnl4pzx8SR7k7JuzyW8lEtSFH6EQ8xgcypgIn8pcGIE=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
|
||||
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
|
||||
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a h1:45JtCyuNYE+QN9aPuR1ID9++BQU+NMTMudHSuaK0Las=
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a/go.mod h1:RVHtZuvrpETIepiNUrNlih2OynoFf1eM6DGC6dloXzk=
|
||||
github.com/juju/persistent-cookiejar v1.0.0 h1:Ag7+QLzqC2m+OYXy2QQnRjb3gTkEBSZagZ6QozwT3EQ=
|
||||
github.com/juju/persistent-cookiejar v1.0.0/go.mod h1:zrbmo4nBKaiP/Ez3F67ewkMbzGYfXyMvRtbOfuAwG0w=
|
||||
github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
|
||||
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
|
||||
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/noamcohen97/touchid-go v0.3.0 h1:fcXxVCizysD7KHRR6hrURt3nyNIs5JBGSbOIidD/3wo=
|
||||
github.com/noamcohen97/touchid-go v0.3.0/go.mod h1:X9MRNIBGEmPqwpDm1G3fQOAQX7fwBlhzUbnkDTxuta0=
|
||||
github.com/onsi/ginkgo/v2 v2.5.0 h1:TRtrvv2vdQqzkwrQ1ke6vtXf7IK34RBUJafIy1wMwls=
|
||||
github.com/onsi/ginkgo/v2 v2.5.0/go.mod h1:Luc4sArBICYCS8THh8v3i3i5CuSZO+RaQRaJoeNwomw=
|
||||
github.com/onsi/gomega v1.24.0 h1:+0glovB9Jd6z3VR+ScSwQqXVTIfJcGA9UBM8yzQxhqg=
|
||||
github.com/onsi/gomega v1.24.0/go.mod h1:Z/NWtiqwBrwUt4/2loMmHL63EDLnYHmVbuBpDr2vQAg=
|
||||
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
|
||||
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a h1:3QH7VyOaaiUHNrA9Se4YQIRkDTCw1EJls9xTUCaCeRM=
|
||||
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a/go.mod h1:4r5QyqhjIWCcK8DO4KMclc5Iknq5qVBAlbYYzAbUScQ=
|
||||
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY=
|
||||
github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/schollz/progressbar/v3 v3.13.1 h1:o8rySDYiQ59Mwzy2FELeHY5ZARXZTVJC7iHD6PEFUiE=
|
||||
github.com/schollz/progressbar/v3 v3.13.1/go.mod h1:xvrbki8kfT1fzWzBT/UZd9L6GA+jdL7HAgq2RFnO6fQ=
|
||||
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
||||
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
|
||||
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk=
|
||||
github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
|
||||
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
|
||||
github.com/thediveo/enumflag/v2 v2.0.1 h1:2bmWZPD2uSARDsOjXIdLRlNcYBFNF9xX0RNUNF2vKic=
|
||||
github.com/thediveo/enumflag/v2 v2.0.1/go.mod h1:SyxyCNvv0QeRtZ7fjuaUz4FRLC3cWuDiD7QdORU0MGg=
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o=
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVKhn2Um6rjCsSsg=
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
|
||||
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=
|
||||
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=
|
||||
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
|
||||
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
|
||||
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U=
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/errgo.v1 v1.0.1 h1:oQFRXzZ7CkBGdm1XZm/EbQYaYNNEElNBOd09M6cqNso=
|
||||
gopkg.in/errgo.v1 v1.0.1/go.mod h1:3NjfXwocQRYAPTq4/fzX+CwUhPRcR/azYRhj8G+LqMo=
|
||||
gopkg.in/retry.v1 v1.0.3 h1:a9CArYczAVv6Qs6VGoLMio99GEs7kY9UzSF9+LD+iGs=
|
||||
gopkg.in/retry.v1 v1.0.3/go.mod h1:FJkXmWiMaAo7xB+xhvDF59zhfjDWyzmyAxiT4dB688g=
|
||||
gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM=
|
||||
howett.net/plist v1.0.0/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
|
||||
@@ -0,0 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/majd/ipatool/v2/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
os.Exit(cmd.Execute())
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package appstore
|
||||
|
||||
type Account struct {
|
||||
Email string `json:"email,omitempty"`
|
||||
PasswordToken string `json:"passwordToken,omitempty"`
|
||||
DirectoryServicesID string `json:"directoryServicesIdentifier,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
StoreFront string `json:"storeFront,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Pod string `json:"pod,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
ID int64 `json:"trackId,omitempty"`
|
||||
BundleID string `json:"bundleId,omitempty"`
|
||||
Name string `json:"trackName,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Price float64 `json:"price,omitempty"`
|
||||
}
|
||||
|
||||
type VersionHistoryInfo struct {
|
||||
App App
|
||||
LatestVersion string
|
||||
VersionIdentifiers []string
|
||||
}
|
||||
|
||||
type VersionDetails struct {
|
||||
VersionID string
|
||||
VersionString string
|
||||
Success bool
|
||||
Error string
|
||||
}
|
||||
|
||||
type Apps []App
|
||||
|
||||
func (apps Apps) MarshalZerologArray(a *zerolog.Array) {
|
||||
for _, app := range apps {
|
||||
a.Object(app)
|
||||
}
|
||||
}
|
||||
|
||||
func (a App) MarshalZerologObject(event *zerolog.Event) {
|
||||
event.
|
||||
Int64("id", a.ID).
|
||||
Str("bundleID", a.BundleID).
|
||||
Str("name", a.Name).
|
||||
Str("version", a.Version).
|
||||
Float64("price", a.Price)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
var _ = Describe("App", func() {
|
||||
It("marshals apps array", func() {
|
||||
apps := Apps{
|
||||
{
|
||||
ID: 42,
|
||||
BundleID: "app.bundle.id",
|
||||
Name: "app name",
|
||||
Version: "1.0",
|
||||
Price: 0,
|
||||
},
|
||||
{
|
||||
ID: 1,
|
||||
BundleID: "app.bundle.id2",
|
||||
Name: "app name2",
|
||||
Version: "2.0",
|
||||
Price: 0.99,
|
||||
},
|
||||
}
|
||||
|
||||
buffer := bytes.NewBuffer([]byte{})
|
||||
logger := zerolog.New(buffer)
|
||||
event := logger.Log().Array("apps", apps)
|
||||
event.Send()
|
||||
|
||||
var out map[string]interface{}
|
||||
err := json.Unmarshal(buffer.Bytes(), &out)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out["apps"]).To(HaveLen(2))
|
||||
})
|
||||
|
||||
It("marshalls app object", func() {
|
||||
app := App{
|
||||
ID: 42,
|
||||
BundleID: "app.bundle.id",
|
||||
Name: "app name",
|
||||
Version: "1.0",
|
||||
Price: 0,
|
||||
}
|
||||
|
||||
buffer := bytes.NewBuffer([]byte{})
|
||||
logger := zerolog.New(buffer)
|
||||
event := logger.Log()
|
||||
app.MarshalZerologObject(event)
|
||||
event.Send()
|
||||
|
||||
var out map[string]interface{}
|
||||
err := json.Unmarshal(buffer.Bytes(), &out)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(out["id"]).To(Equal(float64(42)))
|
||||
Expect(out["bundleID"]).To(Equal("app.bundle.id"))
|
||||
Expect(out["name"]).To(Equal("app name"))
|
||||
Expect(out["version"]).To(Equal("1.0"))
|
||||
Expect(out["price"]).To(Equal(float64(0)))
|
||||
})
|
||||
|
||||
It("formats ipa name correctly", func() {
|
||||
app := App{
|
||||
ID: 42,
|
||||
BundleID: "app.bundle-id1",
|
||||
Name: " some app&symb.ols2 !!!",
|
||||
Version: "1.0",
|
||||
Price: 0,
|
||||
}
|
||||
|
||||
Expect(fileName(app, "1.0")).To(Equal("app.bundle-id1_42_1.0.ipa"))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
)
|
||||
|
||||
type AppStore interface {
|
||||
// Login authenticates with the App Store.
|
||||
Login(input LoginInput) (LoginOutput, error)
|
||||
// AccountInfo returns the information of the authenticated account.
|
||||
AccountInfo() (AccountInfoOutput, error)
|
||||
// Revoke revokes the active credentials.
|
||||
Revoke() error
|
||||
// Lookup looks apps up based on the specified bundle identifier.
|
||||
Lookup(input LookupInput) (LookupOutput, error)
|
||||
// Search searches the App Store for apps matching the specified term.
|
||||
Search(input SearchInput) (SearchOutput, error)
|
||||
// Purchase acquires a license for the desired app.
|
||||
// Note: only free apps are supported.
|
||||
Purchase(input PurchaseInput) error
|
||||
// Download downloads the IPA package from the App Store to the desired location.
|
||||
Download(input DownloadInput) (DownloadOutput, error)
|
||||
// ReplicateSinf replicates the sinf for the IPA package.
|
||||
ReplicateSinf(input ReplicateSinfInput) error
|
||||
// VersionHistory lists the available versions of the specified app.
|
||||
ListVersions(input ListVersionsInput) (ListVersionsOutput, error)
|
||||
// GetVersionMetadata returns the metadata for the specified version.
|
||||
GetVersionMetadata(input GetVersionMetadataInput) (GetVersionMetadataOutput, error)
|
||||
// Bag fetches the bag which contains endpoint definitions.
|
||||
Bag(input BagInput) (BagOutput, error)
|
||||
}
|
||||
|
||||
type appstore struct {
|
||||
keychain keychain.Keychain
|
||||
loginClient http.Client[loginResult]
|
||||
searchClient http.Client[searchResult]
|
||||
purchaseClient http.Client[purchaseResult]
|
||||
downloadClient http.Client[downloadResult]
|
||||
platformClient http.Client[platformVersionLookupResult]
|
||||
bagClient http.Client[bagResult]
|
||||
httpClient http.Client[interface{}]
|
||||
machine machine.Machine
|
||||
os operatingsystem.OperatingSystem
|
||||
}
|
||||
|
||||
type Args struct {
|
||||
Keychain keychain.Keychain
|
||||
CookieJar http.CookieJar
|
||||
OperatingSystem operatingsystem.OperatingSystem
|
||||
Machine machine.Machine
|
||||
}
|
||||
|
||||
func NewAppStore(args Args) AppStore {
|
||||
clientArgs := http.Args{
|
||||
CookieJar: args.CookieJar,
|
||||
}
|
||||
|
||||
return &appstore{
|
||||
keychain: args.Keychain,
|
||||
loginClient: http.NewClient[loginResult](clientArgs),
|
||||
searchClient: http.NewClient[searchResult](clientArgs),
|
||||
purchaseClient: http.NewClient[purchaseResult](clientArgs),
|
||||
downloadClient: http.NewClient[downloadResult](clientArgs),
|
||||
platformClient: http.NewClient[platformVersionLookupResult](clientArgs),
|
||||
bagClient: http.NewClient[bagResult](clientArgs),
|
||||
httpClient: http.NewClient[interface{}](clientArgs),
|
||||
machine: args.Machine,
|
||||
os: args.OperatingSystem,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type AccountInfoOutput struct {
|
||||
Account Account
|
||||
}
|
||||
|
||||
func (t *appstore) AccountInfo() (AccountInfoOutput, error) {
|
||||
data, err := t.keychain.Get("account")
|
||||
if err != nil {
|
||||
return AccountInfoOutput{}, fmt.Errorf("failed to get account: %w", err)
|
||||
}
|
||||
|
||||
var acc Account
|
||||
|
||||
err = json.Unmarshal(data, &acc)
|
||||
if err != nil {
|
||||
return AccountInfoOutput{}, fmt.Errorf("failed to unmarshal json: %w", err)
|
||||
}
|
||||
|
||||
return AccountInfoOutput{
|
||||
Account: acc,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (AccountInfo)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
appstore AppStore
|
||||
mockKeychain *keychain.MockKeychain
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
appstore = NewAppStore(Args{
|
||||
Keychain: mockKeychain,
|
||||
})
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("keychain returns valid data", func() {
|
||||
const (
|
||||
testEmail = "test-email"
|
||||
testName = "test-name"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte(fmt.Sprintf("{\"email\": \"%s\", \"name\": \"%s\"}", testEmail, testName)), nil)
|
||||
})
|
||||
|
||||
It("returns output", func() {
|
||||
out, err := appstore.AccountInfo()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.Account.Email).To(Equal(testEmail))
|
||||
Expect(out.Account.Name).To(Equal(testName))
|
||||
})
|
||||
})
|
||||
|
||||
When("keychain returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
_, err := appstore.AccountInfo()
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("keychain returns invalid data", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("..."), nil)
|
||||
})
|
||||
|
||||
It("fails to unmarshall JSON data", func() {
|
||||
_, err := appstore.AccountInfo()
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type BagInput struct{}
|
||||
|
||||
type BagOutput struct {
|
||||
AuthEndpoint string
|
||||
}
|
||||
|
||||
func (t *appstore) Bag(input BagInput) (BagOutput, error) {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return BagOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
req := t.bagRequest(guid)
|
||||
|
||||
res, err := t.bagClient.Send(req)
|
||||
if err != nil {
|
||||
return BagOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return BagOutput{}, fmt.Errorf("received unexpected status code: %d", res.StatusCode)
|
||||
}
|
||||
|
||||
return BagOutput{
|
||||
AuthEndpoint: res.Data.URLBag.AuthEndpoint,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type bagResult struct {
|
||||
URLBag urlBag `plist:"urlBag,omitempty"`
|
||||
}
|
||||
|
||||
type urlBag struct {
|
||||
AuthEndpoint string `plist:"authenticateAccount,omitempty"`
|
||||
}
|
||||
|
||||
func (*appstore) bagRequest(guid string) http.Request {
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s?guid=%s", PrivateInitDomain, PrivateInitPath, guid),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Accept": "application/xml",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
gohttp "net/http"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Bag)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockBagClient *http.MockClient[bagResult]
|
||||
mockMachine *machine.MockMachine
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockBagClient = http.NewMockClient[bagResult](ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
bagClient: mockBagClient,
|
||||
machine: mockMachine,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("fails to read machine MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New("mac error"))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Bag(BagInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to get mac address"))
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
_, err := as.Bag(BagInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to send http request"))
|
||||
})
|
||||
})
|
||||
|
||||
When("request returns non-200 status code", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusForbidden,
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Bag(BagInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("received unexpected status code"))
|
||||
})
|
||||
})
|
||||
|
||||
When("request is successful with authenticateAccount in urlBag", func() {
|
||||
const testAuthEndpoint = "https://example.com"
|
||||
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("aa:bb:cc:dd:ee:ff", nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.Method).To(Equal(http.MethodGET))
|
||||
Expect(req.URL).To(Equal("https://init.itunes.apple.com/bag.xml?guid=AABBCCDDEEFF"))
|
||||
Expect(req.ResponseFormat).To(Equal(http.ResponseFormatXML))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("Accept", "application/xml"))
|
||||
}).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: bagResult{
|
||||
URLBag: urlBag{
|
||||
AuthEndpoint: testAuthEndpoint,
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns output", func() {
|
||||
out, err := as.Bag(BagInput{})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.AuthEndpoint).To(Equal(testAuthEndpoint))
|
||||
})
|
||||
})
|
||||
|
||||
When("request is successful but authenticateAccount is empty", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("aa:bb:cc:dd:ee:ff", nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: bagResult{},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns empty auth endpoint", func() {
|
||||
out, err := as.Bag(BagInput{})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.AuthEndpoint).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,377 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrLicenseRequired = errors.New("license is required")
|
||||
)
|
||||
|
||||
type DownloadInput struct {
|
||||
Account Account
|
||||
App App
|
||||
OutputPath string
|
||||
Progress *progressbar.ProgressBar
|
||||
ExternalVersionID string
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
type DownloadOutput struct {
|
||||
DestinationPath string
|
||||
Sinfs []Sinf
|
||||
}
|
||||
|
||||
func (t *appstore) Download(input DownloadInput) (DownloadOutput, error) {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
externalVersionID := input.ExternalVersionID
|
||||
if externalVersionID == "" && input.Platform == PlatformAppleTV {
|
||||
externalVersionID, err = t.lookupLatestExternalVersionID(input.Account, input.App, input.Platform)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to resolve platform version: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
req := t.downloadRequest(input.Account, input.App, guid, externalVersionID)
|
||||
|
||||
res, err := t.downloadClient.Send(req)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired ||
|
||||
res.Data.FailureType == FailureTypeSignInRequired ||
|
||||
res.Data.FailureType == FailureTypeDeviceVerificationFailed ||
|
||||
res.Data.FailureType == FailureTypeLicenseAlreadyExists {
|
||||
return DownloadOutput{}, ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseNotFound {
|
||||
return DownloadOutput{}, ErrLicenseRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
return DownloadOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
return DownloadOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.FailureType), res)
|
||||
}
|
||||
|
||||
if len(res.Data.Items) == 0 {
|
||||
return DownloadOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
|
||||
}
|
||||
|
||||
item := res.Data.Items[0]
|
||||
|
||||
version := "unknown"
|
||||
|
||||
// Read the version from the item metadata
|
||||
if itemVersion, ok := item.Metadata["bundleShortVersionString"]; ok {
|
||||
version = fmt.Sprintf("%v", itemVersion)
|
||||
}
|
||||
|
||||
destination, err := t.resolveDestinationPath(input.App, version, input.OutputPath)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to resolve destination path: %w", err)
|
||||
}
|
||||
|
||||
tmpPath := fmt.Sprintf("%s.tmp", destination)
|
||||
|
||||
err = t.downloadFile(item.URL, tmpPath, input.Progress)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to download file: %w", err)
|
||||
}
|
||||
|
||||
err = t.applyPatches(item, input.Account, tmpPath, destination)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to apply patches: %w", err)
|
||||
}
|
||||
|
||||
err = t.validatePackagePlatform(destination, input.Platform)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to validate package platform: %w", err)
|
||||
}
|
||||
|
||||
err = t.os.Remove(fmt.Sprintf("%s.tmp", destination))
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to remove file: %w", err)
|
||||
}
|
||||
|
||||
return DownloadOutput{
|
||||
DestinationPath: destination,
|
||||
Sinfs: item.Sinfs,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type platformPackageInfo struct {
|
||||
SupportedPlatforms []string `plist:"CFBundleSupportedPlatforms,omitempty"`
|
||||
}
|
||||
|
||||
func (*appstore) validatePackagePlatform(path string, platform Platform) error {
|
||||
if platform != PlatformAppleTV {
|
||||
return nil
|
||||
}
|
||||
|
||||
reader, err := zip.OpenReader(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open zip reader: %w", err)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
for _, file := range reader.File {
|
||||
if !strings.HasPrefix(file.Name, "Payload/") || !strings.HasSuffix(file.Name, ".app/Info.plist") {
|
||||
continue
|
||||
}
|
||||
|
||||
infoFile, err := file.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open info plist: %w", err)
|
||||
}
|
||||
|
||||
data, readErr := io.ReadAll(infoFile)
|
||||
closeErr := infoFile.Close()
|
||||
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("failed to read info plist: %w", readErr)
|
||||
}
|
||||
|
||||
if closeErr != nil {
|
||||
return fmt.Errorf("failed to close info plist: %w", closeErr)
|
||||
}
|
||||
|
||||
var info platformPackageInfo
|
||||
|
||||
_, err = plist.Unmarshal(data, &info)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode info plist: %w", err)
|
||||
}
|
||||
|
||||
for _, supportedPlatform := range info.SupportedPlatforms {
|
||||
if supportedPlatform == "AppleTVOS" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return errors.New("downloaded package does not declare AppleTVOS support")
|
||||
}
|
||||
|
||||
type downloadItemResult struct {
|
||||
HashMD5 string `plist:"md5,omitempty"`
|
||||
URL string `plist:"URL,omitempty"`
|
||||
Sinfs []Sinf `plist:"sinfs,omitempty"`
|
||||
Metadata map[string]interface{} `plist:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type downloadResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
Items []downloadItemResult `plist:"songList,omitempty"`
|
||||
}
|
||||
|
||||
func (t *appstore) downloadFile(src, dst string, progress *progressbar.ProgressBar) error {
|
||||
req, err := t.httpClient.NewRequest("GET", src, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
file, err := t.os.OpenFile(dst, os.O_CREATE|os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
stat, err := t.os.Stat(dst)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get file info: %w", err)
|
||||
}
|
||||
|
||||
if req != nil && stat != nil {
|
||||
req.Header.Add("range", fmt.Sprintf("bytes=%d-", stat.Size()))
|
||||
}
|
||||
|
||||
res, err := t.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if progress != nil {
|
||||
progress.ChangeMax64(res.ContentLength + stat.Size())
|
||||
err = progress.Set64(stat.Size())
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("can not set bar progress: %w", err)
|
||||
}
|
||||
|
||||
_, err = file.Seek(0, io.SeekEnd)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can not seek file: %w", err)
|
||||
}
|
||||
|
||||
_, err = io.Copy(io.MultiWriter(file, progress), res.Body)
|
||||
} else {
|
||||
_, err = io.Copy(file, res.Body)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*appstore) downloadRequest(acc Account, app App, guid string, externalVersionID string) http.Request {
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
}
|
||||
|
||||
if externalVersionID != "" {
|
||||
payload["externalVersionId"] = externalVersionID
|
||||
}
|
||||
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func fileName(app App, version string) string {
|
||||
var parts []string
|
||||
|
||||
if app.BundleID != "" {
|
||||
parts = append(parts, app.BundleID)
|
||||
}
|
||||
|
||||
if app.ID != 0 {
|
||||
parts = append(parts, strconv.FormatInt(app.ID, 10))
|
||||
}
|
||||
|
||||
if version != "" {
|
||||
parts = append(parts, version)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s.ipa", strings.Join(parts, "_"))
|
||||
}
|
||||
|
||||
func (t *appstore) resolveDestinationPath(app App, version string, path string) (string, error) {
|
||||
file := fileName(app, version)
|
||||
|
||||
if path == "" {
|
||||
workdir, err := t.os.Getwd()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get current directory: %w", err)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s/%s", workdir, file), nil
|
||||
}
|
||||
|
||||
isDir, err := t.isDirectory(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to determine whether path is a directory: %w", err)
|
||||
}
|
||||
|
||||
if isDir {
|
||||
return fmt.Sprintf("%s/%s", path, file), nil
|
||||
}
|
||||
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func (t *appstore) isDirectory(path string) (bool, error) {
|
||||
info, err := t.os.Stat(path)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return false, fmt.Errorf("failed to read file metadata: %w", err)
|
||||
}
|
||||
|
||||
if info == nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return info.IsDir(), nil
|
||||
}
|
||||
|
||||
func (t *appstore) applyPatches(item downloadItemResult, acc Account, src, dst string) error {
|
||||
srcZip, err := zip.OpenReader(src)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open zip reader: %w", err)
|
||||
}
|
||||
defer srcZip.Close()
|
||||
|
||||
dstFile, err := t.os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer dstFile.Close()
|
||||
|
||||
dstZip := zip.NewWriter(dstFile)
|
||||
defer dstZip.Close()
|
||||
|
||||
err = t.replicateZip(srcZip, dstZip)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to replicate zip: %w", err)
|
||||
}
|
||||
|
||||
err = t.writeMetadata(item.Metadata, acc, dstZip)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write metadata: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *appstore) writeMetadata(metadata map[string]interface{}, acc Account, zip *zip.Writer) error {
|
||||
metadata["apple-id"] = acc.Email
|
||||
metadata["userName"] = acc.Email
|
||||
|
||||
metadataFile, err := zip.Create("iTunesMetadata.plist")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
|
||||
data, err := plist.Marshal(metadata, plist.BinaryFormat)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal data: %w", err)
|
||||
}
|
||||
|
||||
_, err = metadataFile.Write(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write data: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,666 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
type dummyFileInfo struct{}
|
||||
|
||||
func (d *dummyFileInfo) Name() string { return "dummy" }
|
||||
func (d *dummyFileInfo) Size() int64 { return 0 }
|
||||
func (d *dummyFileInfo) Mode() fs.FileMode { return 0 }
|
||||
func (d *dummyFileInfo) ModTime() time.Time { return time.Time{} }
|
||||
func (d *dummyFileInfo) IsDir() bool { return false }
|
||||
func (d *dummyFileInfo) Sys() interface{} { return nil }
|
||||
|
||||
var _ = Describe("AppStore (Download)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockPlatformClient *http.MockClient[platformVersionLookupResult]
|
||||
mockPurchaseClient *http.MockClient[purchaseResult]
|
||||
mockLoginClient *http.MockClient[loginResult]
|
||||
mockHTTPClient *http.MockClient[interface{}]
|
||||
mockOS *operatingsystem.MockOperatingSystem
|
||||
mockMachine *machine.MockMachine
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
mockLoginClient = http.NewMockClient[loginResult](ctrl)
|
||||
mockPurchaseClient = http.NewMockClient[purchaseResult](ctrl)
|
||||
mockHTTPClient = http.NewMockClient[interface{}](ctrl)
|
||||
mockOS = operatingsystem.NewMockOperatingSystem(ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockLoginClient,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: mockOS,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("fails to read MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request uses a custom pod", func() {
|
||||
const (
|
||||
testPod = "42"
|
||||
testGUID = "001122334455"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
expectedURL := "https://p" + testPod + "-" + PrivateAppStoreAPIDomain + PrivateAppStoreAPIPathDownload + "?guid=" + testGUID
|
||||
Expect(req.URL).To(Equal(expectedURL))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("sends the download request to the pod-specific host", func() {
|
||||
_, err := as.Download(DownloadInput{
|
||||
Account: Account{
|
||||
Pod: testPod,
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("platform is AppleTV", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockPlatformClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
parsedURL, err := url.Parse(req.URL)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(parsedURL.Host).To(Equal("uclient-api.itunes.apple.com"))
|
||||
Expect(parsedURL.Query().Get("platform")).To(Equal("atv9"))
|
||||
Expect(parsedURL.Query().Get("cc")).To(Equal("us"))
|
||||
}).
|
||||
Return(http.Result[platformVersionLookupResult]{
|
||||
StatusCode: 200,
|
||||
Data: platformVersionLookupResult{
|
||||
Results: map[string]platformVersionLookupItem{
|
||||
"42": {
|
||||
Offers: []platformVersionLookupOffer{
|
||||
{
|
||||
Version: platformVersionLookupVersion{
|
||||
ExternalID: platformVersionExternalID("123456"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
payload, ok := req.Payload.(*http.XMLPayload)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(payload.Content["externalVersionId"]).To(Equal("123456"))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("resolves and sends the tvOS external version id", func() {
|
||||
_, err := as.Download(DownloadInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
App: App{
|
||||
ID: 42,
|
||||
},
|
||||
Platform: PlatformAppleTV,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
DescribeTable("platform uses the standard download request",
|
||||
func(platform Platform) {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
payload, ok := req.Payload.(*http.XMLPayload)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(payload.Content).ToNot(HaveKey("externalVersionId"))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{}, errors.New("request error"))
|
||||
|
||||
_, err := as.Download(DownloadInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
App: App{
|
||||
ID: 42,
|
||||
},
|
||||
Platform: platform,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
},
|
||||
Entry("iPhone", PlatformIPhone),
|
||||
Entry("iPad", PlatformIPad),
|
||||
)
|
||||
|
||||
When("password token is expired", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("Sign In to the iTunes Store", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeSignInRequired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("license is missing", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeLicenseNotFound,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
})
|
||||
|
||||
When("response contains customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: "test-failure",
|
||||
CustomerMessage: errors.New("").Error(),
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns customer message as error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("response does not contain customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: "test-failure",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns generic error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns no items", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to resolve output path", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{{}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Stat(gomock.Any()).
|
||||
Return(nil, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{
|
||||
OutputPath: "test-out",
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to download file", func() {
|
||||
BeforeEach(func() {
|
||||
|
||||
mockOS.EXPECT().
|
||||
Getwd().
|
||||
Return("", nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{{}},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
When("fails to create download request", func() {
|
||||
BeforeEach(func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(nil, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to open file", func() {
|
||||
BeforeEach(func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(nil, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(nil, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to get file info", func() {
|
||||
BeforeEach(func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(nil, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(nil, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Stat(gomock.Any()).
|
||||
Return(&dummyFileInfo{}, errors.New(""))
|
||||
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(&gohttp.Request{Header: map[string][]string{}}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(nil, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Stat(gomock.Any()).
|
||||
Return(&dummyFileInfo{}, nil)
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(&gohttp.Response{Body: io.NopCloser(strings.NewReader(""))}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to write data to file", func() {
|
||||
BeforeEach(func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(&gohttp.Request{Header: map[string][]string{}}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(nil, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Stat(gomock.Any()).
|
||||
Return(&dummyFileInfo{}, nil)
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(&gohttp.Response{
|
||||
Body: io.NopCloser(strings.NewReader("ping")),
|
||||
}, nil)
|
||||
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
When("successfully downloads file", func() {
|
||||
var testFile *os.File
|
||||
|
||||
BeforeEach(func() {
|
||||
var err error
|
||||
testFile, err = os.CreateTemp("", "test_file")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
Metadata: map[string]interface{}{
|
||||
"bundleShortVersionString": "xyz",
|
||||
},
|
||||
Sinfs: []Sinf{
|
||||
{
|
||||
ID: 0,
|
||||
Data: []byte("test-sinf-data"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", gomock.Any(), nil).
|
||||
Return(&gohttp.Request{Header: map[string][]string{}}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(testFile, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Stat(gomock.Any()).
|
||||
Return(&dummyFileInfo{}, nil)
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(&gohttp.Response{
|
||||
Body: io.NopCloser(strings.NewReader("ping")),
|
||||
}, nil)
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
err := os.Remove(testFile.Name())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("writes data to file", func() {
|
||||
mockOS.EXPECT().
|
||||
Getwd().
|
||||
Return("", nil)
|
||||
|
||||
_, err := as.Download(DownloadInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
|
||||
testData, err := os.ReadFile(testFile.Name())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(string(testData)).To(Equal("ping"))
|
||||
})
|
||||
|
||||
When("successfully applies patches", func() {
|
||||
var (
|
||||
tmpFile *os.File
|
||||
outputPath string
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
|
||||
var err error
|
||||
tmpFile, err = os.OpenFile(fmt.Sprintf("%s.tmp", testFile.Name()), os.O_CREATE|os.O_WRONLY, 0644)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
outputPath = strings.TrimSuffix(tmpFile.Name(), ".tmp")
|
||||
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
DoAndReturn(os.OpenFile)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Stat(gomock.Any()).
|
||||
Return(nil, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Remove(tmpFile.Name()).
|
||||
Return(nil)
|
||||
|
||||
zipFile := zip.NewWriter(tmpFile)
|
||||
w, err := zipFile.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleExecutable": "Test",
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
err = zipFile.Close()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
err := os.Remove(tmpFile.Name())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("succeeds", func() {
|
||||
out, err := as.Download(DownloadInput{
|
||||
OutputPath: outputPath,
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.DestinationPath).ToNot(BeEmpty())
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
Describe("package platform validation", func() {
|
||||
writePackage := func(platforms []string) string {
|
||||
file, err := os.CreateTemp("", "ipatool-platform-*.ipa")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
defer file.Close()
|
||||
|
||||
zipFile := zip.NewWriter(file)
|
||||
w, err := zipFile.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleSupportedPlatforms": platforms,
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(zipFile.Close()).To(Succeed())
|
||||
|
||||
return file.Name()
|
||||
}
|
||||
|
||||
It("accepts AppleTVOS packages", func() {
|
||||
path := writePackage([]string{"AppleTVOS"})
|
||||
defer os.Remove(path)
|
||||
|
||||
err := (&appstore{}).validatePackagePlatform(path, PlatformAppleTV)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("returns an error for packages without AppleTVOS support", func() {
|
||||
path := writePackage([]string{"iPhoneOS"})
|
||||
defer os.Remove(path)
|
||||
|
||||
err := (&appstore{}).validatePackagePlatform(path, PlatformAppleTV)
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("AppleTVOS"))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type GetVersionMetadataInput struct {
|
||||
Account Account
|
||||
App App
|
||||
VersionID string
|
||||
}
|
||||
|
||||
type GetVersionMetadataOutput struct {
|
||||
DisplayVersion string
|
||||
ReleaseDate time.Time
|
||||
}
|
||||
|
||||
func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersionMetadataOutput, error) {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
req := t.getVersionMetadataRequest(input.Account, input.App, guid, input.VersionID)
|
||||
res, err := t.downloadClient.Send(req)
|
||||
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired || res.Data.FailureType == FailureTypeSignInRequired {
|
||||
return GetVersionMetadataOutput{}, ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseNotFound {
|
||||
return GetVersionMetadataOutput{}, ErrLicenseRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
return GetVersionMetadataOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
return GetVersionMetadataOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.FailureType), res)
|
||||
}
|
||||
|
||||
if len(res.Data.Items) == 0 {
|
||||
return GetVersionMetadataOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
|
||||
}
|
||||
|
||||
item := res.Data.Items[0]
|
||||
|
||||
// Do not fall back to item.Metadata here. The App Store download API can
|
||||
// return stale version and release date values, so the IPA Info.plist is the
|
||||
// source of truth and failures should be visible to callers.
|
||||
metadata, err := t.readVersionMetadataFromIPA(item.URL)
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, fmt.Errorf("failed to read version metadata: %w", err)
|
||||
}
|
||||
|
||||
return GetVersionMetadataOutput(metadata), nil
|
||||
}
|
||||
|
||||
func (t *appstore) getVersionMetadataRequest(acc Account, app App, guid string, version string) http.Request {
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
"externalVersionId": version,
|
||||
}
|
||||
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
gohttp "net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
func testIPA(displayVersion string, releaseDate interface{}, modified time.Time) []byte {
|
||||
buffer := new(bytes.Buffer)
|
||||
zipWriter := zip.NewWriter(buffer)
|
||||
|
||||
fillerHeader := &zip.FileHeader{
|
||||
Name: "Payload/Test.app/Filler.bin",
|
||||
Method: zip.Store,
|
||||
}
|
||||
filler, err := zipWriter.CreateHeader(fillerHeader)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = filler.Write(make([]byte, 1024*1024))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
infoHeader := &zip.FileHeader{
|
||||
Name: "Payload/Test.app/Info.plist",
|
||||
Method: zip.Deflate,
|
||||
Modified: modified,
|
||||
}
|
||||
|
||||
infoFile, err := zipWriter.CreateHeader(infoHeader)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info := map[string]interface{}{
|
||||
"CFBundleExecutable": "Test",
|
||||
"CFBundleShortVersionString": displayVersion,
|
||||
}
|
||||
if releaseDate != nil {
|
||||
info["releaseDate"] = releaseDate
|
||||
}
|
||||
|
||||
infoData, err := plist.Marshal(info, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = infoFile.Write(infoData)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
err = zipWriter.Close()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func testIPAServer(data []byte) (*httptest.Server, *int64, *int64) {
|
||||
return testIPAServerWithRangeLog(data, nil)
|
||||
}
|
||||
|
||||
func testIPAServerWithRangeLog(data []byte, rangeLog *[]string) (*httptest.Server, *int64, *int64) {
|
||||
var (
|
||||
servedBytes int64
|
||||
wholeGetCount int64
|
||||
)
|
||||
|
||||
server := httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, r *gohttp.Request) {
|
||||
if r.Method != gohttp.MethodGet {
|
||||
w.WriteHeader(gohttp.StatusMethodNotAllowed)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rangeHeader := r.Header.Get("Range")
|
||||
if rangeLog != nil {
|
||||
*rangeLog = append(*rangeLog, rangeHeader)
|
||||
}
|
||||
|
||||
if rangeHeader == "" {
|
||||
atomic.AddInt64(&wholeGetCount, 1)
|
||||
w.WriteHeader(gohttp.StatusOK)
|
||||
_, _ = w.Write(data)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
start, end, err := testRangeBounds(rangeHeader, len(data))
|
||||
if err != nil {
|
||||
w.WriteHeader(gohttp.StatusRequestedRangeNotSatisfiable)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Accept-Ranges", "bytes")
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(data)))
|
||||
w.Header().Set("Content-Length", strconv.Itoa(end-start+1))
|
||||
w.WriteHeader(gohttp.StatusPartialContent)
|
||||
|
||||
n, _ := w.Write(data[start : end+1])
|
||||
atomic.AddInt64(&servedBytes, int64(n))
|
||||
}))
|
||||
|
||||
return server, &servedBytes, &wholeGetCount
|
||||
}
|
||||
|
||||
func testRangeBounds(header string, size int) (int, int, error) {
|
||||
if !strings.HasPrefix(header, "bytes=") {
|
||||
return 0, 0, fmt.Errorf("invalid range header: %s", header)
|
||||
}
|
||||
|
||||
parts := strings.Split(strings.TrimPrefix(header, "bytes="), "-")
|
||||
if len(parts) != 2 {
|
||||
return 0, 0, fmt.Errorf("invalid range header: %s", header)
|
||||
}
|
||||
|
||||
start, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("failed to parse range start: %w", err)
|
||||
}
|
||||
|
||||
end := size - 1
|
||||
if parts[1] != "" {
|
||||
end, err = strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("failed to parse range end: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if start < 0 || start >= size || end < start {
|
||||
return 0, 0, fmt.Errorf("invalid range bounds: %s", header)
|
||||
}
|
||||
|
||||
if end >= size {
|
||||
end = size - 1
|
||||
}
|
||||
|
||||
return start, end, nil
|
||||
}
|
||||
|
||||
var _ = Describe("HTTPRangeReaderAt", func() {
|
||||
It("clamps reads that cross EOF", func() {
|
||||
data := []byte("abcdef")
|
||||
rangeLog := []string{}
|
||||
server, _, _ := testIPAServerWithRangeLog(data, &rangeLog)
|
||||
defer server.Close()
|
||||
|
||||
reader, size, err := newHTTPRangeReaderAt(http.NewClient[interface{}](http.Args{}), server.URL)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(size).To(Equal(int64(len(data))))
|
||||
|
||||
buf := make([]byte, 4)
|
||||
n, err := reader.ReadAt(buf, 4)
|
||||
Expect(n).To(Equal(2))
|
||||
Expect(err).To(Equal(io.EOF))
|
||||
Expect(string(buf[:n])).To(Equal("ef"))
|
||||
Expect(rangeLog).To(ContainElement("bytes=4-5"))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("AppStore (GetVersionMetadata)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockMachine *machine.MockMachine
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
as = &appstore{
|
||||
machine: mockMachine,
|
||||
downloadClient: mockDownloadClient,
|
||||
httpClient: http.NewClient[interface{}](http.Args{}),
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("fails to get MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New("mac error"))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to get mac address"))
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to send http request"))
|
||||
})
|
||||
})
|
||||
|
||||
When("request uses a custom pod", func() {
|
||||
const (
|
||||
testPod = "42"
|
||||
testGUID = "001122334455"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
expectedURL := "https://p" + testPod + "-" + PrivateAppStoreAPIDomain + PrivateAppStoreAPIPathDownload + "?guid=" + testGUID
|
||||
Expect(req.URL).To(Equal(expectedURL))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("sends the request to the pod-specific host", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{
|
||||
Account: Account{
|
||||
Pod: testPod,
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to send http request"))
|
||||
})
|
||||
})
|
||||
|
||||
When("password token is expired", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(Equal(ErrPasswordTokenExpired))
|
||||
})
|
||||
})
|
||||
|
||||
When("Sign In to the iTunes Store", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeSignInRequired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(Equal(ErrPasswordTokenExpired))
|
||||
})
|
||||
})
|
||||
|
||||
When("license is missing", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeLicenseNotFound,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(Equal(ErrLicenseRequired))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
})
|
||||
|
||||
When("response contains customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: "SOME_ERROR",
|
||||
CustomerMessage: "Customer error message",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns customer message as error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("Customer error message"))
|
||||
})
|
||||
})
|
||||
|
||||
When("response does not contain customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: "SOME_ERROR",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns generic error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("SOME_ERROR"))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns no items", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("invalid response"))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to parse release date", func() {
|
||||
var server *httptest.Server
|
||||
|
||||
BeforeEach(func() {
|
||||
ipa := testIPA("1.0.0", "invalid-date", time.Date(2024, 3, 19, 12, 0, 0, 0, time.UTC))
|
||||
server, _, _ = testIPAServer(ipa)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
URL: server.URL,
|
||||
Metadata: map[string]interface{}{
|
||||
"bundleShortVersionString": "1.0.0",
|
||||
"releaseDate": "invalid-date",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
server.Close()
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to parse release date"))
|
||||
})
|
||||
})
|
||||
|
||||
When("IPA metadata cannot be read", func() {
|
||||
var server *httptest.Server
|
||||
|
||||
BeforeEach(func() {
|
||||
server = httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, r *gohttp.Request) {
|
||||
w.WriteHeader(gohttp.StatusOK)
|
||||
}))
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
URL: server.URL,
|
||||
Metadata: map[string]interface{}{
|
||||
"bundleShortVersionString": "1.0.0",
|
||||
"releaseDate": "2024-03-20T12:00:00Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
server.Close()
|
||||
})
|
||||
|
||||
It("returns error instead of falling back to API metadata", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to read version metadata"))
|
||||
})
|
||||
})
|
||||
|
||||
When("successfully gets version metadata", func() {
|
||||
var (
|
||||
server *httptest.Server
|
||||
ipa []byte
|
||||
servedBytes *int64
|
||||
wholeGetCount *int64
|
||||
releaseDate time.Time
|
||||
displayVersion string
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
releaseDate = time.Date(2024, 4, 2, 12, 0, 0, 0, time.UTC)
|
||||
displayVersion = "2.0.0"
|
||||
ipa = testIPA(displayVersion, fmt.Sprintf(" \n%s\t", releaseDate.Format(time.RFC3339)), time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC))
|
||||
server, servedBytes, wholeGetCount = testIPAServer(ipa)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
URL: server.URL,
|
||||
Metadata: map[string]interface{}{
|
||||
"releaseDate": "2020-01-01T00:00:00Z",
|
||||
"bundleShortVersionString": "1.0.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
server.Close()
|
||||
})
|
||||
|
||||
It("returns version metadata", func() {
|
||||
output, err := as.GetVersionMetadata(GetVersionMetadataInput{
|
||||
Account: Account{
|
||||
DirectoryServicesID: "test-dsid",
|
||||
},
|
||||
App: App{
|
||||
ID: 1234567890,
|
||||
},
|
||||
VersionID: "test-version",
|
||||
})
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(output.DisplayVersion).To(Equal(displayVersion))
|
||||
Expect(output.ReleaseDate).To(Equal(releaseDate))
|
||||
Expect(atomic.LoadInt64(wholeGetCount)).To(BeZero())
|
||||
Expect(atomic.LoadInt64(servedBytes)).To(BeNumerically("<", int64(len(ipa)/2)))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type ListVersionsInput struct {
|
||||
Account Account
|
||||
App App
|
||||
}
|
||||
|
||||
type ListVersionsOutput struct {
|
||||
ExternalVersionIdentifiers []string
|
||||
LatestExternalVersionID string
|
||||
}
|
||||
|
||||
func (t *appstore) ListVersions(input ListVersionsInput) (ListVersionsOutput, error) {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return ListVersionsOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
req := t.listVersionsRequest(input.Account, input.App, guid)
|
||||
res, err := t.downloadClient.Send(req)
|
||||
|
||||
if err != nil {
|
||||
return ListVersionsOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired || res.Data.FailureType == FailureTypeSignInRequired {
|
||||
return ListVersionsOutput{}, ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseNotFound {
|
||||
return ListVersionsOutput{}, ErrLicenseRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.FailureType), res)
|
||||
}
|
||||
|
||||
if len(res.Data.Items) == 0 {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
|
||||
}
|
||||
|
||||
item := res.Data.Items[0]
|
||||
|
||||
rawIdentifiers, ok := item.Metadata["softwareVersionExternalIdentifiers"].([]interface{})
|
||||
if !ok {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("failed to get version identifiers from item metadata"), item.Metadata)
|
||||
}
|
||||
|
||||
externalVersionIdentifiers := make([]string, len(rawIdentifiers))
|
||||
for i, val := range rawIdentifiers {
|
||||
externalVersionIdentifiers[i] = fmt.Sprintf("%v", val)
|
||||
}
|
||||
|
||||
latestExternalVersionID := item.Metadata["softwareVersionExternalIdentifier"]
|
||||
if latestExternalVersionID == nil {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("failed to get latest version from item metadata"), item.Metadata)
|
||||
}
|
||||
|
||||
return ListVersionsOutput{
|
||||
ExternalVersionIdentifiers: externalVersionIdentifiers,
|
||||
LatestExternalVersionID: fmt.Sprintf("%v", latestExternalVersionID),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *appstore) listVersionsRequest(acc Account, app App, guid string) http.Request {
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
}
|
||||
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (ListVersions)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockMachine *machine.MockMachine
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
downloadClient: mockDownloadClient,
|
||||
machine: mockMachine,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("fails to get MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request uses a custom pod", func() {
|
||||
const (
|
||||
testPod = "42"
|
||||
testGUID = "001122334455"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
expectedURL := "https://p" + testPod + "-" + PrivateAppStoreAPIDomain + PrivateAppStoreAPIPathDownload + "?guid=" + testGUID
|
||||
Expect(req.URL).To(Equal(expectedURL))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("sends the request to the pod-specific host", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{
|
||||
Account: Account{
|
||||
Pod: testPod,
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("password token is expired", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("Sign In to the iTunes Store", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeSignInRequired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("license is required", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeLicenseNotFound,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns error with customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: "test-failure",
|
||||
CustomerMessage: "test error message",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error with customer message", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("test error message"))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns error without customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: "test-failure",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error with failure type", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("test-failure"))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns no items", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("version identifiers not found in metadata", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
Metadata: map[string]interface{}{
|
||||
"someOtherKey": "someValue",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to get version identifiers from item metadata"))
|
||||
})
|
||||
})
|
||||
|
||||
When("latest version not found in metadata", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
Metadata: map[string]interface{}{
|
||||
"softwareVersionExternalIdentifiers": []interface{}{"12345678", "87654321"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to get latest version from item metadata"))
|
||||
})
|
||||
})
|
||||
|
||||
When("successfully lists versions", func() {
|
||||
const (
|
||||
testVersion1 = "12345678"
|
||||
testVersion2 = "87654321"
|
||||
testLatest = "87654321"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
Metadata: map[string]interface{}{
|
||||
"softwareVersionExternalIdentifiers": []interface{}{testVersion1, testVersion2},
|
||||
"softwareVersionExternalIdentifier": testLatest,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns versions", func() {
|
||||
out, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.ExternalVersionIdentifiers).To(Equal([]string{testVersion1, testVersion2}))
|
||||
Expect(out.LatestExternalVersionID).To(Equal(testLatest))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,227 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAuthCodeRequired = errors.New("auth code is required")
|
||||
)
|
||||
|
||||
const legacyAuthenticateEndpoint = "https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/authenticate"
|
||||
|
||||
type LoginInput struct {
|
||||
Email string
|
||||
Password string
|
||||
AuthCode string
|
||||
Endpoint string
|
||||
}
|
||||
|
||||
type LoginOutput struct {
|
||||
Account Account
|
||||
}
|
||||
|
||||
func (t *appstore) Login(input LoginInput) (LoginOutput, error) {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return LoginOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
acc, err := t.login(input.Email, input.Password, input.AuthCode, guid, input.Endpoint)
|
||||
if err != nil {
|
||||
return LoginOutput{}, err
|
||||
}
|
||||
|
||||
return LoginOutput{
|
||||
Account: acc,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type loginAddressResult struct {
|
||||
FirstName string `plist:"firstName,omitempty"`
|
||||
LastName string `plist:"lastName,omitempty"`
|
||||
}
|
||||
|
||||
type loginAccountResult struct {
|
||||
Email string `plist:"appleId,omitempty"`
|
||||
Address loginAddressResult `plist:"address,omitempty"`
|
||||
}
|
||||
|
||||
type loginResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
Account loginAccountResult `plist:"accountInfo,omitempty"`
|
||||
DirectoryServicesID string `plist:"dsPersonId,omitempty"`
|
||||
PasswordToken string `plist:"passwordToken,omitempty"`
|
||||
}
|
||||
|
||||
func (t *appstore) login(email, password, authCode, guid, endpoint string) (Account, error) {
|
||||
redirect := ""
|
||||
|
||||
var (
|
||||
err error
|
||||
res http.Result[loginResult]
|
||||
)
|
||||
|
||||
retry := true
|
||||
|
||||
for attempt := 1; retry && attempt <= 4; attempt++ {
|
||||
requestAttempt := attempt
|
||||
if redirect != "" {
|
||||
// The pod redirect is part of the same authentication attempt. Apple
|
||||
// expects the original XML plist body, including its attempt value.
|
||||
requestAttempt = 1
|
||||
}
|
||||
|
||||
request := t.loginRequest(email, password, authCode, guid, endpoint, requestAttempt)
|
||||
request.URL, _ = util.IfEmpty(redirect, request.URL), ""
|
||||
res, err = t.loginClient.Send(request)
|
||||
|
||||
if err != nil {
|
||||
if shouldRetryWithLegacyAuthenticate(endpoint, err) {
|
||||
return t.login(email, password, authCode, guid, legacyAuthenticateEndpoint)
|
||||
}
|
||||
|
||||
return Account{}, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if retry, redirect, err = t.parseLoginResponse(&res, attempt, authCode); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if retry {
|
||||
return Account{}, NewErrorWithMetadata(errors.New("too many attempts"), res)
|
||||
}
|
||||
|
||||
sf, err := res.GetHeader(HTTPHeaderStoreFront)
|
||||
if err != nil {
|
||||
return Account{}, NewErrorWithMetadata(fmt.Errorf("failed to get storefront header: %w", err), res)
|
||||
}
|
||||
|
||||
pod, err := res.GetHeader(HTTPHeaderPod)
|
||||
if err != nil && !errors.Is(err, http.ErrHeaderNotFound) {
|
||||
return Account{}, NewErrorWithMetadata(fmt.Errorf("failed to get pod header: %w", err), res)
|
||||
}
|
||||
|
||||
addr := res.Data.Account.Address
|
||||
acc := Account{
|
||||
Name: strings.Join([]string{addr.FirstName, addr.LastName}, " "),
|
||||
Email: res.Data.Account.Email,
|
||||
PasswordToken: res.Data.PasswordToken,
|
||||
DirectoryServicesID: res.Data.DirectoryServicesID,
|
||||
StoreFront: sf,
|
||||
Password: password,
|
||||
Pod: pod,
|
||||
}
|
||||
|
||||
data, err := json.Marshal(acc)
|
||||
if err != nil {
|
||||
return Account{}, fmt.Errorf("failed to marshal json: %w", err)
|
||||
}
|
||||
|
||||
err = t.keychain.Set("account", data)
|
||||
if err != nil {
|
||||
return Account{}, fmt.Errorf("failed to save account in keychain: %w", err)
|
||||
}
|
||||
|
||||
return acc, nil
|
||||
}
|
||||
|
||||
func shouldRetryWithLegacyAuthenticate(endpoint string, err error) bool {
|
||||
if !strings.Contains(endpoint, "/native/") {
|
||||
return false
|
||||
}
|
||||
|
||||
var responseErr *http.UnexpectedResponseError
|
||||
if !errors.As(err, &responseErr) {
|
||||
return false
|
||||
}
|
||||
|
||||
switch responseErr.StatusCode {
|
||||
case gohttp.StatusNoContent, gohttp.StatusForbidden, gohttp.StatusNotFound, gohttp.StatusServiceUnavailable:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int, authCode string) (bool, string, error) {
|
||||
var (
|
||||
retry bool
|
||||
redirect string
|
||||
err error
|
||||
)
|
||||
|
||||
if res.StatusCode == gohttp.StatusFound {
|
||||
if redirect, err = res.GetHeader("location"); err != nil {
|
||||
err = fmt.Errorf("failed to retrieve redirect location: %w", err)
|
||||
} else {
|
||||
retry = true
|
||||
}
|
||||
} else if attempt == 1 && res.Data.FailureType == FailureTypeInvalidCredentials {
|
||||
retry = true
|
||||
} else if res.Data.FailureType == "" && authCode == "" && res.Data.CustomerMessage == CustomerMessageBadLogin {
|
||||
err = ErrAuthCodeRequired
|
||||
} else if res.Data.FailureType == "" && res.Data.CustomerMessage == CustomerMessageAccountDisabled {
|
||||
err = NewErrorWithMetadata(errors.New("account is disabled"), res)
|
||||
} else if res.Data.FailureType != "" {
|
||||
if res.Data.CustomerMessage != "" {
|
||||
err = NewErrorWithMetadata(errors.New(res.Data.CustomerMessage), res)
|
||||
} else {
|
||||
err = NewErrorWithMetadata(errors.New("something went wrong"), res)
|
||||
}
|
||||
} else if res.StatusCode != gohttp.StatusOK || res.Data.PasswordToken == "" || res.Data.DirectoryServicesID == "" {
|
||||
err = NewErrorWithMetadata(errors.New("something went wrong"), res)
|
||||
}
|
||||
|
||||
return retry, redirect, err
|
||||
}
|
||||
|
||||
func (t *appstore) loginRequest(email, password, authCode, guid, endpoint string, attempt int) http.Request {
|
||||
return http.Request{
|
||||
Method: http.MethodPOST,
|
||||
URL: authenticateURL(endpoint),
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"appleId": email,
|
||||
"attempt": strconv.Itoa(attempt),
|
||||
"guid": guid,
|
||||
"password": fmt.Sprintf("%s%s", password, strings.ReplaceAll(authCode, " ", "")),
|
||||
"rmp": "0",
|
||||
"why": "signIn",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// authenticateURL normalizes the bag-provided authentication endpoint. Apple's
|
||||
// current endpoint (https://auth.itunes.apple.com/auth/v1/native/fast) only
|
||||
// responds correctly when the path has a trailing slash; without it the request
|
||||
// is redirected/dropped and the login silently fails. The legacy MZFinance
|
||||
// authenticate endpoint is left untouched.
|
||||
func authenticateURL(endpoint string) string {
|
||||
if endpoint == "" {
|
||||
return endpoint
|
||||
}
|
||||
|
||||
if strings.Contains(endpoint, "/native/") && !strings.HasSuffix(endpoint, "/") {
|
||||
return endpoint + "/"
|
||||
}
|
||||
|
||||
return endpoint
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Login)", func() {
|
||||
const (
|
||||
testPassword = "test-password"
|
||||
testEmail = "test-email"
|
||||
testFirstName = "test-first-name"
|
||||
testLastName = "test-last-name"
|
||||
testPod = "42"
|
||||
)
|
||||
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
as AppStore
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockClient *http.MockClient[loginResult]
|
||||
mockMachine *machine.MockMachine
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockClient = http.NewMockClient[loginResult](ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockClient,
|
||||
machine: mockMachine,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("fails to read Machine's MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("successfully reads machine's MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
})
|
||||
|
||||
When("client returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("normalizes the native authentication endpoint", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal("https://auth.itunes.apple.com/auth/v1/native/fast/"))
|
||||
}).
|
||||
Return(http.Result[loginResult]{}, errors.New("stop"))
|
||||
})
|
||||
|
||||
It("appends the trailing slash", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
Endpoint: "https://auth.itunes.apple.com/auth/v1/native/fast",
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("native authentication returns an empty response", func() {
|
||||
const podURL = "https://p7-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/authenticate?Pod=7&PRH=7"
|
||||
|
||||
BeforeEach(func() {
|
||||
native := mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal("https://auth.itunes.apple.com/auth/v1/native/fast/"))
|
||||
}).
|
||||
Return(http.Result[loginResult]{}, &http.UnexpectedResponseError{StatusCode: 204})
|
||||
legacy := mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(legacyAuthenticateEndpoint))
|
||||
payload := req.Payload.(*http.XMLPayload)
|
||||
Expect(payload.Content).To(HaveKeyWithValue("attempt", "1"))
|
||||
}).
|
||||
Return(http.Result[loginResult]{
|
||||
StatusCode: 302,
|
||||
Headers: map[string]string{"Location": podURL},
|
||||
}, nil)
|
||||
pod := mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(podURL))
|
||||
payload := req.Payload.(*http.XMLPayload)
|
||||
Expect(payload.Content).To(HaveKeyWithValue("attempt", "1"))
|
||||
}).
|
||||
Return(http.Result[loginResult]{}, errors.New("stop after pod redirect"))
|
||||
gomock.InOrder(native, legacy, pod)
|
||||
})
|
||||
|
||||
It("falls back to legacy authentication and reposts the plist to the assigned pod", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
Endpoint: "https://auth.itunes.apple.com/auth/v1/native/fast",
|
||||
})
|
||||
Expect(err).To(MatchError("request failed: stop after pod redirect"))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns invalid credentials on first attempt", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{
|
||||
Data: loginResult{
|
||||
FailureType: FailureTypeInvalidCredentials,
|
||||
},
|
||||
}, nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("retries once then returns an error", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{
|
||||
Data: loginResult{
|
||||
FailureType: "random-error",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store API indicates account is disabled", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{
|
||||
Data: loginResult{
|
||||
CustomerMessage: CustomerMessageAccountDisabled,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns account disabled error", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("account is disabled"))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API requires 2FA code", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{
|
||||
Data: loginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns ErrAuthCodeRequired error", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(Equal(ErrAuthCodeRequired))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API redirects", func() {
|
||||
const (
|
||||
testRedirectLocation = "https://test-redirect-url.com"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
firstCall := mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
|
||||
x := req.Payload.(*http.XMLPayload)
|
||||
Expect(x.Content).To(HaveKeyWithValue("attempt", "1"))
|
||||
}).
|
||||
Return(http.Result[loginResult]{
|
||||
StatusCode: 302,
|
||||
Headers: map[string]string{"Location": testRedirectLocation},
|
||||
}, nil)
|
||||
secondCall := mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testRedirectLocation))
|
||||
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
|
||||
x := req.Payload.(*http.XMLPayload)
|
||||
Expect(x.Content).To(HaveKeyWithValue("attempt", "1"))
|
||||
}).
|
||||
Return(http.Result[loginResult]{}, errors.New("test complete"))
|
||||
gomock.InOrder(firstCall, secondCall)
|
||||
})
|
||||
|
||||
It("follows the redirect while preserving the original request body", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(MatchError("request failed: test complete"))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns valid response", func() {
|
||||
const (
|
||||
testPasswordToken = "test-password-token"
|
||||
testDirectoryServicesID = "directory-services-id"
|
||||
testStoreFront = "test-storefront"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{
|
||||
StatusCode: 200,
|
||||
Headers: map[string]string{
|
||||
HTTPHeaderStoreFront: testStoreFront,
|
||||
HTTPHeaderPod: testPod,
|
||||
},
|
||||
Data: loginResult{
|
||||
PasswordToken: testPasswordToken,
|
||||
DirectoryServicesID: testDirectoryServicesID,
|
||||
Account: loginAccountResult{
|
||||
Email: testEmail,
|
||||
Address: loginAddressResult{
|
||||
FirstName: testFirstName,
|
||||
LastName: testLastName,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
When("successfully saves account in keychain", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Set("account", gomock.Any()).
|
||||
Do(func(key string, data []byte) {
|
||||
want := Account{
|
||||
Name: fmt.Sprintf("%s %s", testFirstName, testLastName),
|
||||
Email: testEmail,
|
||||
PasswordToken: testPasswordToken,
|
||||
Password: testPassword,
|
||||
DirectoryServicesID: testDirectoryServicesID,
|
||||
StoreFront: testStoreFront,
|
||||
Pod: testPod,
|
||||
}
|
||||
|
||||
var got Account
|
||||
Expect(json.Unmarshal(data, &got)).To(Succeed())
|
||||
Expect(got).To(Equal(want))
|
||||
}).
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
out, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.Account.Email).To(Equal(testEmail))
|
||||
Expect(out.Account.Name).To(Equal(strings.Join([]string{testFirstName, testLastName}, " ")))
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type LookupInput struct {
|
||||
Account Account
|
||||
BundleID string
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
type LookupOutput struct {
|
||||
App App
|
||||
}
|
||||
|
||||
func (t *appstore) Lookup(input LookupInput) (LookupOutput, error) {
|
||||
countryCode, err := countryCodeFromStoreFront(input.Account.StoreFront)
|
||||
if err != nil {
|
||||
return LookupOutput{}, fmt.Errorf("failed to resolve the country code: %w", err)
|
||||
}
|
||||
|
||||
request, err := t.lookupRequest(input.BundleID, countryCode, input.Platform)
|
||||
if err != nil {
|
||||
return LookupOutput{}, fmt.Errorf("failed to create lookup request: %w", err)
|
||||
}
|
||||
|
||||
res, err := t.searchClient.Send(request)
|
||||
if err != nil {
|
||||
return LookupOutput{}, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return LookupOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
|
||||
}
|
||||
|
||||
if len(res.Data.Results) == 0 {
|
||||
return LookupOutput{}, errors.New("app not found")
|
||||
}
|
||||
|
||||
return LookupOutput{
|
||||
App: res.Data.Results[0],
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *appstore) lookupRequest(bundleID, countryCode string, platform Platform) (http.Request, error) {
|
||||
url, err := t.lookupURL(bundleID, countryCode, platform)
|
||||
if err != nil {
|
||||
return http.Request{}, err
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: url,
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatJSON,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *appstore) lookupURL(bundleID, countryCode string, platform Platform) (string, error) {
|
||||
entity, err := platform.lookupEntity()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("entity", entity)
|
||||
params.Add("limit", "1")
|
||||
params.Add("media", "software")
|
||||
params.Add("bundleId", bundleID)
|
||||
params.Add("country", countryCode)
|
||||
|
||||
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathLookup, params.Encode()), nil
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Lookup)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockClient *http.MockClient[searchResult]
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockClient = http.NewMockClient[searchResult](ctrl)
|
||||
as = &appstore{
|
||||
searchClient: mockClient,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("request is successful", func() {
|
||||
When("does not find app", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[searchResult]{
|
||||
StatusCode: 200,
|
||||
Data: searchResult{
|
||||
Count: 0,
|
||||
Results: []App{},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("finds app", func() {
|
||||
var testApp = App{
|
||||
ID: 1,
|
||||
BundleID: "app.bundle.id",
|
||||
Name: "app name",
|
||||
Version: "1.0",
|
||||
Price: 0.99,
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[searchResult]{
|
||||
StatusCode: 200,
|
||||
Data: searchResult{
|
||||
Count: 1,
|
||||
Results: []App{testApp},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns app", func() {
|
||||
app, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(app).To(Equal(LookupOutput{App: testApp}))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("platform is AppleTV", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
parsedURL, err := url.Parse(req.URL)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(parsedURL.Query().Get("entity")).To(Equal("tvSoftware"))
|
||||
}).
|
||||
Return(http.Result[searchResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("uses the tvOS lookup entity", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
Platform: PlatformAppleTV,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store front is invalid", func() {
|
||||
It("returns error", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "xyz",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[searchResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request returns bad status code", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[searchResult]{
|
||||
StatusCode: 400,
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,318 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
var infoPlistReleaseDateKeys = []string{
|
||||
"releaseDate",
|
||||
"ReleaseDate",
|
||||
}
|
||||
|
||||
var infoPlistDisplayVersionKeys = []string{
|
||||
"CFBundleShortVersionString",
|
||||
"bundleShortVersionString",
|
||||
}
|
||||
|
||||
type versionMetadata struct {
|
||||
DisplayVersion string
|
||||
ReleaseDate time.Time
|
||||
}
|
||||
|
||||
type httpRangeReaderAt struct {
|
||||
client apphttp.Client[interface{}]
|
||||
url string
|
||||
size int64
|
||||
}
|
||||
|
||||
func newHTTPRangeReaderAt(client apphttp.Client[interface{}], url string) (*httpRangeReaderAt, int64, error) {
|
||||
if url == "" {
|
||||
return nil, 0, errors.New("url is empty")
|
||||
}
|
||||
|
||||
size, err := remoteFileSize(client, url)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to read remote file size: %w", err)
|
||||
}
|
||||
|
||||
return &httpRangeReaderAt{
|
||||
client: client,
|
||||
url: url,
|
||||
size: size,
|
||||
}, size, nil
|
||||
}
|
||||
|
||||
func remoteFileSize(client apphttp.Client[interface{}], url string) (int64, error) {
|
||||
req, err := client.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept-Encoding", "identity")
|
||||
req.Header.Set("Range", "bytes=0-0")
|
||||
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res != nil && res.Body != nil {
|
||||
defer res.Body.Close()
|
||||
}
|
||||
|
||||
if res.StatusCode != http.StatusPartialContent {
|
||||
return 0, fmt.Errorf("expected partial content response, got status %d", res.StatusCode)
|
||||
}
|
||||
|
||||
size, err := parseContentRangeSize(res.Header.Get("Content-Range"))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return size, nil
|
||||
}
|
||||
|
||||
func parseContentRangeSize(header string) (int64, error) {
|
||||
if header == "" {
|
||||
return 0, errors.New("content range is empty")
|
||||
}
|
||||
|
||||
slash := strings.LastIndex(header, "/")
|
||||
if slash == -1 || slash == len(header)-1 {
|
||||
return 0, fmt.Errorf("invalid content range: %s", header)
|
||||
}
|
||||
|
||||
sizeText := header[slash+1:]
|
||||
if sizeText == "*" {
|
||||
return 0, fmt.Errorf("invalid content range size: %s", sizeText)
|
||||
}
|
||||
|
||||
size, err := strconv.ParseInt(sizeText, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to parse content range size: %w", err)
|
||||
}
|
||||
|
||||
return size, nil
|
||||
}
|
||||
|
||||
func (r *httpRangeReaderAt) ReadAt(p []byte, off int64) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if off < 0 {
|
||||
return 0, errors.New("offset is negative")
|
||||
}
|
||||
|
||||
if off >= r.size {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
requestEnd := off + int64(len(p)) - 1
|
||||
rangeEnd := requestEnd
|
||||
|
||||
if rangeEnd >= r.size {
|
||||
rangeEnd = r.size - 1
|
||||
}
|
||||
|
||||
req, err := r.client.NewRequest("GET", r.url, nil)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept-Encoding", "identity")
|
||||
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", off, rangeEnd))
|
||||
|
||||
res, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res != nil && res.Body != nil {
|
||||
defer res.Body.Close()
|
||||
}
|
||||
|
||||
if res.StatusCode != http.StatusPartialContent {
|
||||
return 0, fmt.Errorf("expected partial content response, got status %d", res.StatusCode)
|
||||
}
|
||||
|
||||
readLength := int(rangeEnd-off) + 1
|
||||
|
||||
n, err := io.ReadFull(res.Body, p[:readLength])
|
||||
if err == io.ErrUnexpectedEOF || err == io.EOF {
|
||||
return n, io.EOF
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return n, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if requestEnd >= r.size {
|
||||
return n, io.EOF
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (t *appstore) readVersionMetadataFromIPA(url string) (versionMetadata, error) {
|
||||
reader, size, err := newHTTPRangeReaderAt(t.httpClient, url)
|
||||
if err != nil {
|
||||
return versionMetadata{}, err
|
||||
}
|
||||
|
||||
zipReader, err := zip.NewReader(reader, size)
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to open zip reader: %w", err)
|
||||
}
|
||||
|
||||
for _, file := range zipReader.File {
|
||||
if !isMainAppInfoPlist(file.Name) {
|
||||
continue
|
||||
}
|
||||
|
||||
metadata, err := readVersionMetadataFromInfoPlist(file)
|
||||
if err != nil {
|
||||
return versionMetadata{}, err
|
||||
}
|
||||
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
return versionMetadata{}, errors.New("could not find Info.plist")
|
||||
}
|
||||
|
||||
func isMainAppInfoPlist(name string) bool {
|
||||
parts := strings.Split(name, "/")
|
||||
|
||||
return len(parts) == 3 && parts[0] == "Payload" && strings.HasSuffix(parts[1], ".app") && parts[2] == "Info.plist"
|
||||
}
|
||||
|
||||
func readVersionMetadataFromInfoPlist(file *zip.File) (versionMetadata, error) {
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to open Info.plist: %w", err)
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
data := new(bytes.Buffer)
|
||||
|
||||
_, err = io.Copy(data, src)
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to read Info.plist: %w", err)
|
||||
}
|
||||
|
||||
metadata := map[string]interface{}{}
|
||||
|
||||
_, err = plist.Unmarshal(data.Bytes(), &metadata)
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to unmarshal Info.plist: %w", err)
|
||||
}
|
||||
|
||||
displayVersion, err := readDisplayVersionFromMetadata(metadata)
|
||||
if err != nil {
|
||||
return versionMetadata{}, err
|
||||
}
|
||||
|
||||
releaseDate, err := readReleaseDateFromInfoPlist(metadata, file.Modified)
|
||||
if err != nil {
|
||||
return versionMetadata{}, err
|
||||
}
|
||||
|
||||
return versionMetadata{
|
||||
DisplayVersion: displayVersion,
|
||||
ReleaseDate: releaseDate,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func readDisplayVersionFromMetadata(metadata map[string]interface{}) (string, error) {
|
||||
for _, key := range infoPlistDisplayVersionKeys {
|
||||
value, ok := metadata[key]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
displayVersion := strings.TrimSpace(fmt.Sprintf("%v", value))
|
||||
if displayVersion == "" || displayVersion == "<nil>" {
|
||||
return "", fmt.Errorf("%s is empty", key)
|
||||
}
|
||||
|
||||
return displayVersion, nil
|
||||
}
|
||||
|
||||
return "", errors.New("info plist does not contain a display version")
|
||||
}
|
||||
|
||||
func readReleaseDateFromInfoPlist(metadata map[string]interface{}, modified time.Time) (time.Time, error) {
|
||||
for _, key := range infoPlistReleaseDateKeys {
|
||||
value, ok := metadata[key]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
releaseDate, err := parseReleaseDateValue(value)
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("failed to parse release date: %w", err)
|
||||
}
|
||||
|
||||
return releaseDate, nil
|
||||
}
|
||||
|
||||
if modified.IsZero() {
|
||||
return time.Time{}, errors.New("info plist does not contain a release date")
|
||||
}
|
||||
|
||||
return modified.UTC(), nil
|
||||
}
|
||||
|
||||
func parseReleaseDateValue(value interface{}) (time.Time, error) {
|
||||
switch val := value.(type) {
|
||||
case time.Time:
|
||||
return val.UTC(), nil
|
||||
case string:
|
||||
return parseReleaseDateString(val)
|
||||
case int:
|
||||
return time.Unix(int64(val), 0).UTC(), nil
|
||||
case int64:
|
||||
return time.Unix(val, 0).UTC(), nil
|
||||
case uint64:
|
||||
if val > math.MaxInt64 {
|
||||
return time.Time{}, fmt.Errorf("timestamp is too large: %d", val)
|
||||
}
|
||||
|
||||
return time.Unix(int64(val), 0).UTC(), nil
|
||||
case float64:
|
||||
return time.Unix(int64(val), 0).UTC(), nil
|
||||
default:
|
||||
return time.Time{}, fmt.Errorf("unsupported release date type %T", value)
|
||||
}
|
||||
}
|
||||
|
||||
func parseReleaseDateString(value string) (time.Time, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
|
||||
for _, layout := range []string{
|
||||
time.RFC3339,
|
||||
time.RFC3339Nano,
|
||||
"Monday, January 2, 2006",
|
||||
"2006-01-02",
|
||||
} {
|
||||
parsed, err := time.Parse(layout, value)
|
||||
if err == nil {
|
||||
return parsed.UTC(), nil
|
||||
}
|
||||
}
|
||||
|
||||
return time.Time{}, fmt.Errorf("invalid release date: %s", value)
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type platformVersionLookupResult struct {
|
||||
Results map[string]platformVersionLookupItem `json:"results,omitempty"`
|
||||
}
|
||||
|
||||
type platformVersionLookupItem struct {
|
||||
BundleID string `json:"bundleId,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Offers []platformVersionLookupOffer `json:"offers,omitempty"`
|
||||
}
|
||||
|
||||
type platformVersionLookupOffer struct {
|
||||
BuyParams string `json:"buyParams,omitempty"`
|
||||
Version platformVersionLookupVersion `json:"version,omitempty"`
|
||||
}
|
||||
|
||||
type platformVersionLookupVersion struct {
|
||||
Display string `json:"display,omitempty"`
|
||||
ExternalID platformVersionExternalID `json:"externalId,omitempty"`
|
||||
}
|
||||
|
||||
type platformVersionExternalID string
|
||||
|
||||
func (id *platformVersionExternalID) UnmarshalJSON(data []byte) error {
|
||||
if string(data) == "null" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var stringID string
|
||||
if err := json.Unmarshal(data, &stringID); err == nil {
|
||||
*id = platformVersionExternalID(stringID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var numberID json.Number
|
||||
if err := json.Unmarshal(data, &numberID); err == nil {
|
||||
*id = platformVersionExternalID(numberID.String())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("invalid external version id %s", string(data))
|
||||
}
|
||||
|
||||
func (t *appstore) lookupLatestExternalVersionID(acc Account, app App, platform Platform) (string, error) {
|
||||
if app.ID == 0 {
|
||||
return "", errors.New("app ID is required for platform version lookup")
|
||||
}
|
||||
|
||||
countryCode, err := countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve the country code: %w", err)
|
||||
}
|
||||
|
||||
request, err := t.platformVersionLookupRequest(app.ID, countryCode, platform)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create platform version lookup request: %w", err)
|
||||
}
|
||||
|
||||
res, err := t.platformClient.Send(request)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("platform version lookup request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup request failed"), res)
|
||||
}
|
||||
|
||||
item, ok := res.Data.Results[strconv.FormatInt(app.ID, 10)]
|
||||
if !ok {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no app"), res)
|
||||
}
|
||||
|
||||
if len(item.Offers) == 0 {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no offers"), res)
|
||||
}
|
||||
|
||||
offer := item.Offers[0]
|
||||
externalVersionID := string(offer.Version.ExternalID)
|
||||
|
||||
if externalVersionID == "" {
|
||||
externalVersionID, err = externalVersionIDFromBuyParams(offer.BuyParams)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse buy params: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if externalVersionID == "" {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no external version id"), res)
|
||||
}
|
||||
|
||||
return externalVersionID, nil
|
||||
}
|
||||
|
||||
func (*appstore) platformVersionLookupRequest(appID int64, countryCode string, platform Platform) (http.Request, error) {
|
||||
metadataPlatform, err := platform.metadataPlatform()
|
||||
if err != nil {
|
||||
return http.Request{}, err
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("version", "2")
|
||||
params.Add("id", strconv.FormatInt(appID, 10))
|
||||
params.Add("p", "mdm-lockup")
|
||||
params.Add("caller", "MDM")
|
||||
params.Add("platform", metadataPlatform)
|
||||
params.Add("cc", strings.ToLower(countryCode))
|
||||
params.Add("l", "en")
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://uclient-api.itunes.apple.com/WebObjects/MZStorePlatform.woa/wa/lookup?%s", params.Encode()),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatJSON,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func externalVersionIDFromBuyParams(buyParams string) (string, error) {
|
||||
if buyParams == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
values, err := url.ParseQuery(buyParams)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse query: %w", err)
|
||||
}
|
||||
|
||||
return values.Get("appExtVrsId"), nil
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrPasswordTokenExpired = errors.New("password token is expired")
|
||||
ErrLicenseAlreadyExists = errors.New("license already exists")
|
||||
ErrSubscriptionRequired = errors.New("subscription required")
|
||||
ErrTemporarilyUnavailable = errors.New("item is temporarily unavailable")
|
||||
)
|
||||
|
||||
type PurchaseInput struct {
|
||||
Account Account
|
||||
App App
|
||||
}
|
||||
|
||||
func (t *appstore) Purchase(input PurchaseInput) error {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
if input.App.Price > 0 {
|
||||
return errors.New("purchasing paid apps is not supported")
|
||||
}
|
||||
|
||||
err = t.purchaseWithParams(input.Account, input.App, guid, PricingParameterAppStore)
|
||||
if err != nil {
|
||||
if err == ErrTemporarilyUnavailable {
|
||||
err = t.purchaseWithParams(input.Account, input.App, guid, PricingParameterAppleArcade)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to purchase item with param '%s': %w", PricingParameterAppleArcade, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("failed to purchase item with param '%s': %w", PricingParameterAppStore, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type purchaseResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
JingleDocType string `plist:"jingleDocType,omitempty"`
|
||||
Status int `plist:"status,omitempty"`
|
||||
}
|
||||
|
||||
func (t *appstore) purchaseWithParams(acc Account, app App, guid string, pricingParameters string) error {
|
||||
req := t.purchaseRequest(acc, app, acc.StoreFront, guid, pricingParameters)
|
||||
res, err := t.purchaseClient.Send(req)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeTemporarilyUnavailable {
|
||||
return ErrTemporarilyUnavailable
|
||||
}
|
||||
|
||||
if res.Data.CustomerMessage == CustomerMessageSubscriptionRequired {
|
||||
return ErrSubscriptionRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired ||
|
||||
res.Data.FailureType == FailureTypeSignInRequired ||
|
||||
res.Data.FailureType == FailureTypeDeviceVerificationFailed ||
|
||||
res.Data.CustomerMessage == CustomerMessagePasswordChanged {
|
||||
return ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseAlreadyExists {
|
||||
return ErrLicenseAlreadyExists
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
return NewErrorWithMetadata(errors.New(res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
return NewErrorWithMetadata(errors.New("something went wrong"), res)
|
||||
}
|
||||
|
||||
if res.StatusCode == gohttp.StatusInternalServerError {
|
||||
return ErrLicenseAlreadyExists
|
||||
}
|
||||
|
||||
if res.Data.JingleDocType != "purchaseSuccess" || res.Data.Status != 0 {
|
||||
return NewErrorWithMetadata(errors.New("failed to purchase app"), res)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *appstore) purchaseRequest(acc Account, app App, storeFront, guid string, pricingParameters string) http.Request {
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathPurchase),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
"X-Apple-Store-Front": storeFront,
|
||||
"X-Token": acc.PasswordToken,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"appExtVrsId": "0",
|
||||
"hasAskedToFulfillPreorder": "true",
|
||||
"buyWithoutAuthorization": "true",
|
||||
"hasDoneAgeCheck": "true",
|
||||
"guid": guid,
|
||||
"needDiv": "0",
|
||||
"origPage": fmt.Sprintf("Software-%d", app.ID),
|
||||
"origPageLocation": "Buy",
|
||||
"price": "0",
|
||||
"pricingParameters": pricingParameters,
|
||||
"productType": "C",
|
||||
"salableAdamId": app.ID,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Purchase)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockMachine *machine.MockMachine
|
||||
mockPurchaseClient *http.MockClient[purchaseResult]
|
||||
mockLoginClient *http.MockClient[loginResult]
|
||||
as *appstore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockPurchaseClient = http.NewMockClient[purchaseResult](ctrl)
|
||||
mockLoginClient = http.NewMockClient[loginResult](ctrl)
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
loginClient: mockLoginClient,
|
||||
machine: mockMachine,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("fails to read MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase(PurchaseInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("app is paid", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
App: App{
|
||||
Price: 0.99,
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("purchase request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request uses a custom pod", func() {
|
||||
const (
|
||||
testPod = "42"
|
||||
testGUID = "001122334455"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
expectedURL := "https://p" + testPod + "-" + PrivateAppStoreAPIDomain + PrivateAppStoreAPIPathPurchase
|
||||
Expect(req.URL).To(Equal(expectedURL))
|
||||
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
|
||||
payload := req.Payload.(*http.XMLPayload)
|
||||
Expect(payload.Content["guid"]).To(Equal(testGUID))
|
||||
}).
|
||||
Return(http.Result[purchaseResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("sends the request to the pod-specific host", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
Pod: testPod,
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("password token is expired", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
Data: purchaseResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("Sign In to the iTunes Store", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
Data: purchaseResult{
|
||||
FailureType: FailureTypeSignInRequired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("customer message indicates password has changed", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
Data: purchaseResult{
|
||||
FailureType: "some_other_failure",
|
||||
CustomerMessage: CustomerMessagePasswordChanged,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns password token expired error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(MatchError(ErrPasswordTokenExpired))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns customer error message", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
Data: purchaseResult{
|
||||
FailureType: "failure",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns unknown error", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
Data: purchaseResult{
|
||||
FailureType: "failure",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("account already has a license for the app (failure type)", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
FailureType: FailureTypeLicenseAlreadyExists,
|
||||
CustomerMessage: "An unknown error has occurred",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns license already exists error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(MatchError(ErrLicenseAlreadyExists))
|
||||
})
|
||||
})
|
||||
|
||||
When("account already has a license for the app (HTTP 500 legacy)", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 500,
|
||||
Data: purchaseResult{},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns license already exists error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(MatchError(ErrLicenseAlreadyExists))
|
||||
})
|
||||
})
|
||||
|
||||
When("device verification fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
FailureType: FailureTypeDeviceVerificationFailed,
|
||||
CustomerMessage: "Your device or computer could not be verified. Contact support for assistance.",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns password token expired error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(MatchError(ErrPasswordTokenExpired))
|
||||
})
|
||||
})
|
||||
|
||||
When("subscription is required", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"STDQ"}).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
CustomerMessage: "This item is temporarily unavailable.",
|
||||
FailureType: FailureTypeTemporarilyUnavailable,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"GAME"}).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
CustomerMessage: CustomerMessageSubscriptionRequired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("successfully purchases the app", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"STDQ"}).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
CustomerMessage: "This item is temporarily unavailable.",
|
||||
FailureType: FailureTypeTemporarilyUnavailable,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"GAME"}).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
JingleDocType: "purchaseSuccess",
|
||||
Status: 0,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("purchasing the app fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
JingleDocType: "failure",
|
||||
Status: -1,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
type pricingParametersMatcher struct {
|
||||
pricingParameters string
|
||||
}
|
||||
|
||||
func (p pricingParametersMatcher) Matches(in interface{}) bool {
|
||||
return in.(http.Request).Payload.(*http.XMLPayload).Content["pricingParameters"] == p.pricingParameters
|
||||
}
|
||||
|
||||
func (p pricingParametersMatcher) String() string {
|
||||
return "payload pricingParameters is " + p.pricingParameters
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/util"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
type Sinf struct {
|
||||
ID int64 `plist:"id,omitempty"`
|
||||
Data []byte `plist:"sinf,omitempty"`
|
||||
}
|
||||
|
||||
type ReplicateSinfInput struct {
|
||||
Sinfs []Sinf
|
||||
PackagePath string
|
||||
}
|
||||
|
||||
func (t *appstore) ReplicateSinf(input ReplicateSinfInput) error {
|
||||
zipReader, err := zip.OpenReader(input.PackagePath)
|
||||
if err != nil {
|
||||
return errors.New("failed to open zip reader")
|
||||
}
|
||||
|
||||
tmpPath := fmt.Sprintf("%s.tmp", input.PackagePath)
|
||||
tmpFile, err := t.os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY, 0644)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
zipWriter := zip.NewWriter(tmpFile)
|
||||
|
||||
err = t.replicateZip(zipReader, zipWriter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to replicate zip: %w", err)
|
||||
}
|
||||
|
||||
bundleName, err := t.readBundleName(zipReader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read bundle name: %w", err)
|
||||
}
|
||||
|
||||
manifest, err := t.readManifestPlist(zipReader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read manifest plist: %w", err)
|
||||
}
|
||||
|
||||
info, err := t.readInfoPlist(zipReader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read info plist: %w", err)
|
||||
}
|
||||
|
||||
if manifest != nil {
|
||||
err = t.replicateSinfFromManifest(*manifest, zipWriter, input.Sinfs, bundleName)
|
||||
} else {
|
||||
err = t.replicateSinfFromInfo(*info, zipWriter, input.Sinfs, bundleName)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to replicate sinf: %w", err)
|
||||
}
|
||||
|
||||
zipReader.Close()
|
||||
zipWriter.Close()
|
||||
tmpFile.Close()
|
||||
|
||||
err = t.os.Remove(input.PackagePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to remove original file: %w", err)
|
||||
}
|
||||
|
||||
err = t.os.Rename(tmpPath, input.PackagePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to remove original file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type packageManifest struct {
|
||||
SinfPaths []string `plist:"SinfPaths,omitempty"`
|
||||
}
|
||||
|
||||
type packageInfo struct {
|
||||
BundleExecutable string `plist:"CFBundleExecutable,omitempty"`
|
||||
}
|
||||
|
||||
func (*appstore) replicateSinfFromManifest(manifest packageManifest, zip *zip.Writer, sinfs []Sinf, bundleName string) error {
|
||||
zipped, err := util.Zip(sinfs, manifest.SinfPaths)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to zip sinfs: %w", err)
|
||||
}
|
||||
|
||||
for _, pair := range zipped {
|
||||
sp := fmt.Sprintf("Payload/%s.app/%s", bundleName, pair.Second)
|
||||
|
||||
file, err := zip.Create(sp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
|
||||
_, err = file.Write(pair.First.Data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write data: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *appstore) replicateSinfFromInfo(info packageInfo, zip *zip.Writer, sinfs []Sinf, bundleName string) error {
|
||||
sp := fmt.Sprintf("Payload/%s.app/SC_Info/%s.sinf", bundleName, info.BundleExecutable)
|
||||
|
||||
file, err := zip.Create(sp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
|
||||
_, err = file.Write(sinfs[0].Data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write data: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *appstore) replicateZip(src *zip.ReadCloser, dst *zip.Writer) error {
|
||||
for _, file := range src.File {
|
||||
err := func() error {
|
||||
srcFile, err := file.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
header := file.FileHeader
|
||||
dstFile, err := dst.CreateHeader(&header)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to copy file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*appstore) readInfoPlist(reader *zip.ReadCloser) (*packageInfo, error) {
|
||||
for _, file := range reader.File {
|
||||
if strings.Contains(file.Name, ".app/Info.plist") {
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
data := new(bytes.Buffer)
|
||||
_, err = io.Copy(data, src)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to copy data: %w", err)
|
||||
}
|
||||
|
||||
var info packageInfo
|
||||
_, err = plist.Unmarshal(data.Bytes(), &info)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal data: %w", err)
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (*appstore) readManifestPlist(reader *zip.ReadCloser) (*packageManifest, error) {
|
||||
for _, file := range reader.File {
|
||||
if strings.HasSuffix(file.Name, ".app/SC_Info/Manifest.plist") {
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
data := new(bytes.Buffer)
|
||||
_, err = io.Copy(data, src)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to copy data: %w", err)
|
||||
}
|
||||
|
||||
var manifest packageManifest
|
||||
|
||||
_, err = plist.Unmarshal(data.Bytes(), &manifest)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal data: %w", err)
|
||||
}
|
||||
|
||||
return &manifest, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (*appstore) readBundleName(reader *zip.ReadCloser) (string, error) {
|
||||
var bundleName string
|
||||
|
||||
for _, file := range reader.File {
|
||||
if strings.Contains(file.Name, ".app/Info.plist") && !strings.Contains(file.Name, "/Watch/") {
|
||||
bundleName = filepath.Base(strings.TrimSuffix(file.Name, ".app/Info.plist"))
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if bundleName == "" {
|
||||
return "", errors.New("could not read bundle name")
|
||||
}
|
||||
|
||||
return bundleName, nil
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (ReplicateSinf)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockPurchaseClient *http.MockClient[purchaseResult]
|
||||
mockLoginClient *http.MockClient[loginResult]
|
||||
mockHTTPClient *http.MockClient[interface{}]
|
||||
mockOS *operatingsystem.MockOperatingSystem
|
||||
mockMachine *machine.MockMachine
|
||||
as AppStore
|
||||
testFile *os.File
|
||||
testZip *zip.Writer
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockLoginClient = http.NewMockClient[loginResult](ctrl)
|
||||
mockPurchaseClient = http.NewMockClient[purchaseResult](ctrl)
|
||||
mockHTTPClient = http.NewMockClient[interface{}](ctrl)
|
||||
mockOS = operatingsystem.NewMockOperatingSystem(ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockLoginClient,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: mockOS,
|
||||
}
|
||||
|
||||
var err error
|
||||
testFile, err = os.CreateTemp("", "test_file")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
testZip = zip.NewWriter(testFile)
|
||||
})
|
||||
|
||||
JustBeforeEach(func() {
|
||||
testZip.Close()
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
err := os.Remove(testFile.Name())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("app includes codesign manifest", func() {
|
||||
BeforeEach(func() {
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
DoAndReturn(os.OpenFile)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Remove(testFile.Name()).
|
||||
Return(nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Rename(fmt.Sprintf("%s.tmp", testFile.Name()), testFile.Name()).
|
||||
Return(nil)
|
||||
|
||||
manifest, err := plist.Marshal(packageManifest{
|
||||
SinfPaths: []string{
|
||||
"SC_Info/TestApp.sinf",
|
||||
},
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err := testZip.Create("Payload/Test.app/SC_Info/Manifest.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(manifest)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err = testZip.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleExecutable": "Test",
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err = testZip.Create("Payload/Test.app/Watch/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
watchInfo, err := plist.Marshal(map[string]interface{}{
|
||||
"WKWatchKitApp": true,
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(watchInfo)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("replicates sinf from manifest plist", func() {
|
||||
err := as.ReplicateSinf(ReplicateSinfInput{
|
||||
PackagePath: testFile.Name(),
|
||||
Sinfs: []Sinf{
|
||||
{
|
||||
ID: 0,
|
||||
Data: []byte(""),
|
||||
},
|
||||
},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("app does not include codesign manifest", func() {
|
||||
BeforeEach(func() {
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
DoAndReturn(os.OpenFile)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Remove(testFile.Name()).
|
||||
Return(nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Rename(fmt.Sprintf("%s.tmp", testFile.Name()), testFile.Name()).
|
||||
Return(nil)
|
||||
|
||||
w, err := testZip.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleExecutable": "Test",
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err = testZip.Create("Payload/Test.app/Watch/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
watchInfo, err := plist.Marshal(map[string]interface{}{
|
||||
"WKWatchKitApp": true,
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(watchInfo)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("replicates sinf", func() {
|
||||
err := as.ReplicateSinf(ReplicateSinfInput{
|
||||
PackagePath: testFile.Name(),
|
||||
Sinfs: []Sinf{
|
||||
{
|
||||
ID: 0,
|
||||
Data: []byte(""),
|
||||
},
|
||||
},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to open file", func() {
|
||||
BeforeEach(func() {
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(nil, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.ReplicateSinf(ReplicateSinfInput{
|
||||
PackagePath: testFile.Name(),
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (t *appstore) Revoke() error {
|
||||
err := t.keychain.Remove("account")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to remove account from keychain: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Revoke)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
appstore AppStore
|
||||
mockKeychain *keychain.MockKeychain
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
appstore = NewAppStore(Args{
|
||||
Keychain: mockKeychain,
|
||||
})
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("keychain removes item", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Remove("account").
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns data", func() {
|
||||
err := appstore.Revoke()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("keychain returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Remove("account").
|
||||
Return(errors.New(""))
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
err := appstore.Revoke()
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type SearchInput struct {
|
||||
Account Account
|
||||
Term string
|
||||
Limit int64
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
type SearchOutput struct {
|
||||
Count int
|
||||
Results []App
|
||||
}
|
||||
|
||||
func (t *appstore) Search(input SearchInput) (SearchOutput, error) {
|
||||
countryCode, err := countryCodeFromStoreFront(input.Account.StoreFront)
|
||||
if err != nil {
|
||||
return SearchOutput{}, fmt.Errorf("country code is invalid: %w", err)
|
||||
}
|
||||
|
||||
request, err := t.searchRequest(input.Term, countryCode, input.Limit, input.Platform)
|
||||
if err != nil {
|
||||
return SearchOutput{}, fmt.Errorf("failed to create search request: %w", err)
|
||||
}
|
||||
|
||||
res, err := t.searchClient.Send(request)
|
||||
if err != nil {
|
||||
return SearchOutput{}, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return SearchOutput{}, NewErrorWithMetadata(errors.New("request failed"), res)
|
||||
}
|
||||
|
||||
return SearchOutput{
|
||||
Count: res.Data.Count,
|
||||
Results: res.Data.Results,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type searchResult struct {
|
||||
Count int `json:"resultCount,omitempty"`
|
||||
Results []App `json:"results,omitempty"`
|
||||
}
|
||||
|
||||
func (t *appstore) searchRequest(term, countryCode string, limit int64, platform Platform) (http.Request, error) {
|
||||
url, err := t.searchURL(term, countryCode, limit, platform)
|
||||
if err != nil {
|
||||
return http.Request{}, err
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: url,
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatJSON,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *appstore) searchURL(term, countryCode string, limit int64, platform Platform) (string, error) {
|
||||
entity, err := platform.searchEntity()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("entity", entity)
|
||||
params.Add("limit", strconv.Itoa(int(limit)))
|
||||
params.Add("media", "software")
|
||||
params.Add("term", term)
|
||||
params.Add("country", countryCode)
|
||||
|
||||
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathSearch, params.Encode()), nil
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Search)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockClient *http.MockClient[searchResult]
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockClient = http.NewMockClient[searchResult](ctrl)
|
||||
as = &appstore{
|
||||
searchClient: mockClient,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("request is successful", func() {
|
||||
const (
|
||||
testID = 0
|
||||
testBundleID = "test-bundle-id"
|
||||
testName = "test-name"
|
||||
testVersion = "test-version"
|
||||
testPrice = 0.0
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[searchResult]{
|
||||
StatusCode: 200,
|
||||
Data: searchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: testID,
|
||||
BundleID: testBundleID,
|
||||
Name: testName,
|
||||
Version: testVersion,
|
||||
Price: testPrice,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns output", func() {
|
||||
out, err := as.Search(SearchInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.Count).To(Equal(1))
|
||||
Expect(out.Results).To(HaveLen(1))
|
||||
Expect(out.Results[0]).To(Equal(App{
|
||||
ID: testID,
|
||||
BundleID: testBundleID,
|
||||
Name: testName,
|
||||
Version: testVersion,
|
||||
Price: testPrice,
|
||||
}))
|
||||
})
|
||||
})
|
||||
|
||||
When("platform is AppleTV", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
parsedURL, err := url.Parse(req.URL)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(parsedURL.Query().Get("entity")).To(Equal("software,tvSoftware"))
|
||||
}).
|
||||
Return(http.Result[searchResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("uses the tvOS search entity", func() {
|
||||
_, err := as.Search(SearchInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
Platform: PlatformAppleTV,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store front is invalid", func() {
|
||||
It("returns error", func() {
|
||||
_, err := as.Search(SearchInput{
|
||||
Account: Account{
|
||||
StoreFront: "xyz",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[searchResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Search(SearchInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request returns bad status code", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[searchResult]{
|
||||
StatusCode: 400,
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Search(SearchInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestAppStore(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "App Store Suite")
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package appstore
|
||||
|
||||
const (
|
||||
FailureTypeInvalidCredentials = "-5000"
|
||||
FailureTypePasswordTokenExpired = "2034"
|
||||
FailureTypeSignInRequired = "2042"
|
||||
FailureTypeLicenseNotFound = "9610"
|
||||
FailureTypeTemporarilyUnavailable = "2059"
|
||||
FailureTypeLicenseAlreadyExists = "5002"
|
||||
FailureTypeDeviceVerificationFailed = "1008"
|
||||
|
||||
CustomerMessageBadLogin = "MZFinance.BadLogin.Configurator_message"
|
||||
CustomerMessageAccountDisabled = "Your account is disabled."
|
||||
CustomerMessageSubscriptionRequired = "Subscription Required"
|
||||
CustomerMessagePasswordChanged = "Your password has changed."
|
||||
|
||||
iTunesAPIDomain = "itunes.apple.com"
|
||||
iTunesAPIPathSearch = "/search"
|
||||
iTunesAPIPathLookup = "/lookup"
|
||||
|
||||
PrivateInitDomain = "init." + iTunesAPIDomain
|
||||
PrivateInitPath = "/bag.xml"
|
||||
|
||||
PrivateAppStoreAPIDomain = "buy." + iTunesAPIDomain
|
||||
PrivateAppStoreAPIPathPurchase = "/WebObjects/MZFinance.woa/wa/buyProduct"
|
||||
PrivateAppStoreAPIPathDownload = "/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct"
|
||||
|
||||
HTTPHeaderStoreFront = "X-Set-Apple-Store-Front"
|
||||
HTTPHeaderPod = "pod"
|
||||
|
||||
PricingParameterAppStore = "STDQ"
|
||||
PricingParameterAppleArcade = "GAME"
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
package appstore
|
||||
|
||||
type Error struct {
|
||||
Metadata interface{}
|
||||
underlyingError error
|
||||
}
|
||||
|
||||
func (t Error) Error() string {
|
||||
return t.underlyingError.Error()
|
||||
}
|
||||
|
||||
func NewErrorWithMetadata(err error, metadata interface{}) *Error {
|
||||
return &Error{
|
||||
underlyingError: err,
|
||||
Metadata: metadata,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package appstore
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Platform string
|
||||
|
||||
const (
|
||||
PlatformIPhone Platform = "iphone"
|
||||
PlatformIPad Platform = "ipad"
|
||||
PlatformAppleTV Platform = "appletv"
|
||||
)
|
||||
|
||||
func ParsePlatform(value string) (Platform, error) {
|
||||
switch value {
|
||||
case "":
|
||||
return "", nil
|
||||
case "iphone", "iPhone", "ios", "iOS":
|
||||
return PlatformIPhone, nil
|
||||
case "ipad", "iPad":
|
||||
return PlatformIPad, nil
|
||||
case "appletv", "AppleTV", "apple-tv", "tvos", "tvOS":
|
||||
return PlatformAppleTV, nil
|
||||
default:
|
||||
return "", fmt.Errorf("invalid platform %q", value)
|
||||
}
|
||||
}
|
||||
|
||||
func (p Platform) lookupEntity() (string, error) {
|
||||
switch p {
|
||||
case "":
|
||||
return "software,iPadSoftware", nil
|
||||
case PlatformIPhone:
|
||||
return "software", nil
|
||||
case PlatformIPad:
|
||||
return "iPadSoftware", nil
|
||||
case PlatformAppleTV:
|
||||
return "tvSoftware", nil
|
||||
default:
|
||||
return "", fmt.Errorf("invalid platform %q", p)
|
||||
}
|
||||
}
|
||||
|
||||
func (p Platform) searchEntity() (string, error) {
|
||||
switch p {
|
||||
case "":
|
||||
return "software,iPadSoftware", nil
|
||||
case PlatformIPhone:
|
||||
return "software", nil
|
||||
case PlatformIPad:
|
||||
return "iPadSoftware", nil
|
||||
case PlatformAppleTV:
|
||||
return "software,tvSoftware", nil
|
||||
default:
|
||||
return "", fmt.Errorf("invalid platform %q", p)
|
||||
}
|
||||
}
|
||||
|
||||
func (p Platform) metadataPlatform() (string, error) {
|
||||
switch p {
|
||||
case PlatformIPhone, PlatformIPad:
|
||||
return "enterprisestore", nil
|
||||
case PlatformAppleTV:
|
||||
return "atv9", nil
|
||||
default:
|
||||
return "", fmt.Errorf("invalid platform %q", p)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Platform", func() {
|
||||
DescribeTable("parses aliases",
|
||||
func(value string, expected Platform) {
|
||||
platform, err := ParsePlatform(value)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(platform).To(Equal(expected))
|
||||
},
|
||||
Entry("default", "", Platform("")),
|
||||
Entry("iPhone", "iphone", PlatformIPhone),
|
||||
Entry("iOS", "ios", PlatformIPhone),
|
||||
Entry("iPad", "ipad", PlatformIPad),
|
||||
Entry("AppleTV", "appletv", PlatformAppleTV),
|
||||
Entry("tvOS", "tvos", PlatformAppleTV),
|
||||
)
|
||||
|
||||
It("returns an error for invalid platforms", func() {
|
||||
_, err := ParsePlatform("watch")
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func countryCodeFromStoreFront(storeFront string) (string, error) {
|
||||
for key, val := range storeFronts {
|
||||
parts := strings.Split(storeFront, "-")
|
||||
|
||||
if len(parts) >= 1 && parts[0] == val {
|
||||
return key, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("country code mapping for store front (%s) was not found", storeFront)
|
||||
}
|
||||
|
||||
var storeFronts = map[string]string{
|
||||
"AE": "143481",
|
||||
"AG": "143540",
|
||||
"AI": "143538",
|
||||
"AL": "143575",
|
||||
"AM": "143524",
|
||||
"AO": "143564",
|
||||
"AR": "143505",
|
||||
"AT": "143445",
|
||||
"AU": "143460",
|
||||
"AZ": "143568",
|
||||
"BB": "143541",
|
||||
"BD": "143490",
|
||||
"BE": "143446",
|
||||
"BG": "143526",
|
||||
"BH": "143559",
|
||||
"BM": "143542",
|
||||
"BN": "143560",
|
||||
"BO": "143556",
|
||||
"BR": "143503",
|
||||
"BS": "143539",
|
||||
"BW": "143525",
|
||||
"BY": "143565",
|
||||
"BZ": "143555",
|
||||
"CA": "143455",
|
||||
"CH": "143459",
|
||||
"CI": "143527",
|
||||
"CL": "143483",
|
||||
"CN": "143465",
|
||||
"CO": "143501",
|
||||
"CR": "143495",
|
||||
"CY": "143557",
|
||||
"CZ": "143489",
|
||||
"DE": "143443",
|
||||
"DK": "143458",
|
||||
"DM": "143545",
|
||||
"DO": "143508",
|
||||
"DZ": "143563",
|
||||
"EC": "143509",
|
||||
"EE": "143518",
|
||||
"EG": "143516",
|
||||
"ES": "143454",
|
||||
"FI": "143447",
|
||||
"FR": "143442",
|
||||
"GB": "143444",
|
||||
"GD": "143546",
|
||||
"GE": "143615",
|
||||
"GH": "143573",
|
||||
"GR": "143448",
|
||||
"GT": "143504",
|
||||
"GY": "143553",
|
||||
"HK": "143463",
|
||||
"HN": "143510",
|
||||
"HR": "143494",
|
||||
"HU": "143482",
|
||||
"ID": "143476",
|
||||
"IE": "143449",
|
||||
"IL": "143491",
|
||||
"IN": "143467",
|
||||
"IS": "143558",
|
||||
"IT": "143450",
|
||||
"IQ": "143617",
|
||||
"JM": "143511",
|
||||
"JO": "143528",
|
||||
"JP": "143462",
|
||||
"KE": "143529",
|
||||
"KN": "143548",
|
||||
"KR": "143466",
|
||||
"KW": "143493",
|
||||
"KY": "143544",
|
||||
"KZ": "143517",
|
||||
"LB": "143497",
|
||||
"LC": "143549",
|
||||
"LI": "143522",
|
||||
"LK": "143486",
|
||||
"LT": "143520",
|
||||
"LU": "143451",
|
||||
"LV": "143519",
|
||||
"MD": "143523",
|
||||
"MG": "143531",
|
||||
"MK": "143530",
|
||||
"ML": "143532",
|
||||
"MN": "143592",
|
||||
"MO": "143515",
|
||||
"MS": "143547",
|
||||
"MT": "143521",
|
||||
"MU": "143533",
|
||||
"MV": "143488",
|
||||
"MX": "143468",
|
||||
"MY": "143473",
|
||||
"NE": "143534",
|
||||
"NG": "143561",
|
||||
"NI": "143512",
|
||||
"NL": "143452",
|
||||
"NO": "143457",
|
||||
"NP": "143484",
|
||||
"NZ": "143461",
|
||||
"OM": "143562",
|
||||
"PA": "143485",
|
||||
"PE": "143507",
|
||||
"PH": "143474",
|
||||
"PK": "143477",
|
||||
"PL": "143478",
|
||||
"PT": "143453",
|
||||
"PY": "143513",
|
||||
"QA": "143498",
|
||||
"RO": "143487",
|
||||
"RS": "143500",
|
||||
"RU": "143469",
|
||||
"SA": "143479",
|
||||
"SE": "143456",
|
||||
"SG": "143464",
|
||||
"SI": "143499",
|
||||
"SK": "143496",
|
||||
"SN": "143535",
|
||||
"SR": "143554",
|
||||
"SV": "143506",
|
||||
"TC": "143552",
|
||||
"TH": "143475",
|
||||
"TN": "143536",
|
||||
"TR": "143480",
|
||||
"TT": "143551",
|
||||
"TW": "143470",
|
||||
"TZ": "143572",
|
||||
"UA": "143492",
|
||||
"UG": "143537",
|
||||
"US": "143441",
|
||||
"UY": "143514",
|
||||
"UZ": "143566",
|
||||
"VC": "143550",
|
||||
"VE": "143502",
|
||||
"VG": "143543",
|
||||
"VN": "143471",
|
||||
"YE": "143571",
|
||||
"ZA": "143472",
|
||||
}
|
||||
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user