mirror of
https://github.com/majd/ipatool
synced 2026-11-28 18:27:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b02b4c555 | ||
|
|
d69faf83c8 | ||
|
|
5a6dfe0582 | ||
|
|
b352566155 | ||
|
|
6194bf4ecd | ||
|
|
20290220cd | ||
|
|
3e84853e2e | ||
|
|
2cfd33fa45 | ||
|
|
e4b0aaee61 | ||
|
|
9df35a6d84 | ||
|
|
8771e57445 | ||
|
|
e0e2908dc8 | ||
|
|
f137223276 | ||
|
|
536d7bacc1 | ||
|
|
856323251a | ||
|
|
0d99fc2d96 | ||
|
|
72c47d538b | ||
|
|
001d889896 | ||
|
|
d9c0247dae | ||
|
|
5dc4c8058d | ||
|
|
1b9ff28eb4 | ||
|
|
7578671482 | ||
|
|
b0fe32d8a1 | ||
|
|
0259df3c09 | ||
|
|
5b7a812a77 | ||
|
|
9d343753c4 | ||
|
|
987900b417 | ||
|
|
4484b55d36 | ||
|
|
e3932cec31 | ||
|
|
cde7d00355 | ||
|
|
93b527a839 | ||
|
|
ed45c02852 | ||
|
|
f11d9abafe | ||
|
|
f9aa6536cd | ||
|
|
3411d57f45 | ||
|
|
0cc226a3d7 | ||
|
|
e258fed14a | ||
|
|
1ec8b3e5dc | ||
|
|
387d1a4f47 | ||
|
|
294488012f | ||
|
|
5deb9b521b | ||
|
|
acd9e7a972 | ||
|
|
50312a928b | ||
|
|
735b689ac3 | ||
|
|
e5211d6fd9 | ||
|
|
747d66fc0a | ||
|
|
1ed3bf94dd | ||
|
|
fb1ca3521b | ||
|
|
ad88910ad6 | ||
|
|
c66d6537f4 | ||
|
|
7b4913a71c | ||
|
|
c4323e4c55 | ||
|
|
2aaf18b832 | ||
|
|
e3dea14461 | ||
|
|
dd28a3a9d8 | ||
|
|
5a47056bc3 | ||
|
|
ba85241c88 | ||
|
|
394cd643de | ||
|
|
62f1c8b435 | ||
|
|
5c522b685d | ||
|
|
ba180d741d | ||
|
|
d1845ba678 | ||
|
|
a814a71a9f | ||
|
|
843f5c6c29 | ||
|
|
b8bac296b8 | ||
|
|
24f93d332f | ||
|
|
e6acb9c3c2 | ||
|
|
abdb5902cb | ||
|
|
91d4294085 | ||
|
|
73fabcc283 | ||
|
|
30b2909231 | ||
|
|
a9bd16c9a2 | ||
|
|
cee3674258 | ||
|
|
8f9748fa51 | ||
|
|
d5d0b56faf | ||
|
|
30d19a6859 | ||
|
|
27e8902d7e | ||
|
|
acaf6c566e | ||
|
|
652b9d0083 | ||
|
|
a53550f9c4 | ||
|
|
161888d240 | ||
|
|
abd86cb01a | ||
|
|
5f776fe2f5 | ||
|
|
ab79e429d5 | ||
|
|
9032d4c192 | ||
|
|
779a2e66cb | ||
|
|
fd630343bc | ||
|
|
dcddce4650 | ||
|
|
a3fa2f09b3 | ||
|
|
85ae82d9c4 | ||
|
|
1bee8bc568 | ||
|
|
abaeccefec | ||
|
|
8c4e037aa3 | ||
|
|
4142ab48ad | ||
|
|
1858ad7a72 | ||
|
|
2140a26bdf | ||
|
|
e914156036 | ||
|
|
19ffd1bf6b | ||
|
|
7ffd4bf050 | ||
|
|
496595a039 | ||
|
|
7765fd5445 | ||
|
|
6f63cd4776 | ||
|
|
65242569b3 | ||
|
|
14883b4631 | ||
|
|
91ae69cc58 | ||
|
|
80dbbef6c8 | ||
|
|
e3e604925f | ||
|
|
cffa279e31 | ||
|
|
034a0978ab | ||
|
|
9657750fc1 | ||
|
|
9969c18cef | ||
|
|
f09439ecde | ||
|
|
55ef41fc20 | ||
|
|
b4bd8d6580 | ||
|
|
79250ae2a3 | ||
|
|
a3212e0fd2 | ||
|
|
805678138e | ||
|
|
3a537e7571 | ||
|
|
e686248270 | ||
|
|
ac081fa19d | ||
|
|
7136f81fd1 | ||
|
|
34866f5833 | ||
|
|
46f3369de0 | ||
|
|
0bb134e9d7 | ||
|
|
bbf3717456 | ||
|
|
e1eda9f776 | ||
|
|
c406c36819 | ||
|
|
e5291ba16b | ||
|
|
37af8f8468 | ||
|
|
21cbd596bc | ||
|
|
f3c9076ff0 | ||
|
|
d147788501 | ||
|
|
8a23d6fadd | ||
|
|
63ee6fc6a4 | ||
|
|
5b547457f1 | ||
|
|
169af4b2ea | ||
|
|
f68a119963 | ||
|
|
58e9a18778 | ||
|
|
c8624b26d5 | ||
|
|
3199afc494 | ||
|
|
6597f5ac77 | ||
|
|
6ccb4a7f0b | ||
|
|
64c5cc9843 | ||
|
|
19e7261713 | ||
|
|
b031cd20d1 | ||
|
|
9db93c83c0 | ||
|
|
90253c336f | ||
|
|
e1141bd6d2 | ||
|
|
6a7adabbfa | ||
|
|
cfc4a075ae | ||
|
|
74e7588c6d | ||
|
|
67e557e9a7 | ||
|
|
bf33e0d1c4 | ||
|
|
95c3aa6629 | ||
|
|
cf926d7911 | ||
|
|
9a361cf7a0 | ||
|
|
574d5b5148 | ||
|
|
5abc5d1777 | ||
|
|
8762eaf192 | ||
|
|
4f3115d60f | ||
|
|
0e38e43d8b | ||
|
|
73e9bd90d1 | ||
|
|
e76dbf044e | ||
|
|
d82e819d4e | ||
|
|
19ac47d098 | ||
|
|
fece9ea79c | ||
|
|
1b31ee6556 | ||
|
|
fbd9d74729 | ||
|
|
8d2467491e | ||
|
|
4eba914bff | ||
|
|
56cc64fcef | ||
|
|
7813e78e3c | ||
|
|
50a1e546ef | ||
|
|
094ff93693 | ||
|
|
5d014266e3 | ||
|
|
8dd1a8508d | ||
|
|
dff5a5ad0b | ||
|
|
6356b522df | ||
|
|
a2cb7c653e | ||
|
|
2f154ad4f9 | ||
|
|
a3b322c8da | ||
|
|
5386d36275 | ||
|
|
7e21c8571a | ||
|
|
ff582bb97b | ||
|
|
98bd6f0e45 | ||
|
|
40d1f700b5 | ||
|
|
a2ce1c4213 | ||
|
|
d42ba7ef4b | ||
|
|
721e23fd8a | ||
|
|
15dbfe423a | ||
|
|
f77b0d94d9 | ||
|
|
99c1bf1013 | ||
|
|
1a71cf89b4 | ||
|
|
3088cde9ba | ||
|
|
5d6e83c2e9 | ||
|
|
001ee4ca12 | ||
|
|
0e57952e06 | ||
|
|
12db867c54 | ||
|
|
d5c4f88533 | ||
|
|
65439346eb | ||
|
|
eb42a63845 | ||
|
|
4633cf17b6 | ||
|
|
b73de7cd88 | ||
|
|
169a17f7ac | ||
|
|
d913b16c55 | ||
|
|
915c70dcfa | ||
|
|
b2711aa8b4 | ||
|
|
9c00557474 | ||
|
|
5e06154ccb | ||
|
|
102f510ddb | ||
|
|
bd8d4e7e3f | ||
|
|
19196d70ce | ||
|
|
bdee2b94c2 | ||
|
|
ff43c07a32 | ||
|
|
07a0f3310d | ||
|
|
9cfd72d142 | ||
|
|
a16afb5c7b | ||
|
|
ec4b6cfc29 | ||
|
|
83515013cd | ||
|
|
1577e1b8bc | ||
|
|
8d3167cc6e | ||
|
|
964fbe1fe7 | ||
|
|
943a7aff05 | ||
|
|
8c591f0a1f | ||
|
|
119c55359b | ||
|
|
4df3c492f6 | ||
|
|
cea1db77e9 | ||
|
|
3040955de1 | ||
|
|
f0c7e02db9 | ||
|
|
cd54b3bbcb | ||
|
|
82f70f23c7 | ||
|
|
96115462d0 | ||
|
|
1b65463007 | ||
|
|
dba1d3b195 | ||
|
|
eee3416b67 | ||
|
|
2f3b0330e0 | ||
|
|
b257a5c8b1 | ||
|
|
df45f1cc44 | ||
|
|
a92c829fb7 | ||
|
|
7569f89208 | ||
|
|
8003c042f4 | ||
|
|
74165461cb | ||
|
|
fdccf874b9 | ||
|
|
29731ec0b1 | ||
|
|
97edbccc58 | ||
|
|
1463c85279 | ||
|
|
7d8531b3e0 | ||
|
|
7507290769 | ||
|
|
644d6a7104 | ||
|
|
dfd2709d2a | ||
|
|
e3adde06b3 | ||
|
|
fc49c7af91 | ||
|
|
234ee2fe52 | ||
|
|
b030cd454f | ||
|
|
f3a54098ea | ||
|
|
69c07d0062 | ||
|
|
f0922b303e | ||
|
|
5a4d2f5e8d | ||
|
|
972f0b2cd0 | ||
|
|
03993b2b93 | ||
|
|
5009048d44 | ||
|
|
59fb28cee0 | ||
|
|
5f1fb02a12 | ||
|
|
32c6012918 | ||
|
|
f55e9ac53b | ||
|
|
a83dcb2849 | ||
|
|
6ff82c66aa | ||
|
|
c4610ca808 | ||
|
|
1563a82a20 | ||
|
|
48ed1df5c7 | ||
|
|
1448ca3ebc | ||
|
|
a3e483830f | ||
|
|
8cfd902bbf | ||
|
|
8165331378 | ||
|
|
bed12a55a9 | ||
|
|
73a416c917 |
No files matched your search
@@ -0,0 +1 @@
|
||||
github: majd
|
||||
@@ -0,0 +1,25 @@
|
||||
name: Bug Report
|
||||
description: File a bug report
|
||||
labels:
|
||||
- bug
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: What happened?
|
||||
description: Also share, what did you expect to happen?
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: What version of ipatool are you running?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Relevant log output
|
||||
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
|
||||
render: shell
|
||||
@@ -0,0 +1,12 @@
|
||||
name: Feature Request
|
||||
description: Submit a feature request
|
||||
labels:
|
||||
- feature request
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Description
|
||||
description: Please provide details about the desired feature.
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,76 @@
|
||||
name: Dry Build
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build_windows:
|
||||
name: Build for Windows
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
build_linux:
|
||||
name: Build for Linux
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
- arch: amd64
|
||||
runner: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: go build -o ipatool-linux-$GOARCH
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
build_macos:
|
||||
name: Build for macOS
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
CGO_ENABLED: 1
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
build_ios:
|
||||
name: Build for iOS
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: brew install ldid cmake
|
||||
- run: ./tools/build-ios.sh
|
||||
@@ -0,0 +1,41 @@
|
||||
name: Integration Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: go build -o ipatool
|
||||
env:
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool
|
||||
path: ipatool
|
||||
if-no-files-found: error
|
||||
test:
|
||||
name: Test
|
||||
runs-on: macos-latest
|
||||
needs: [build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
command: [auth, download, purchase, search]
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool
|
||||
path: build
|
||||
- run: chmod +x ./build/ipatool
|
||||
- run: ./build/ipatool ${{ matrix.command }} --help
|
||||
@@ -0,0 +1,21 @@
|
||||
name: Lint
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: go generate ./...
|
||||
- uses: golangci/golangci-lint-action@v8
|
||||
with:
|
||||
version: v2.9
|
||||
@@ -0,0 +1,266 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
get_version:
|
||||
name: Get version
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: set_output
|
||||
run: echo ::set-output name=version::${GITHUB_REF#refs/tags/v}
|
||||
outputs:
|
||||
version: ${{ steps.set_output.outputs.version }}
|
||||
test:
|
||||
name: Run tests
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: go generate ./...
|
||||
- run: go test -v -timeout 20m ./...
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-latest
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-arm64.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: arm64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-amd64.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: amd64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-macos-arm64
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: arm64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_ENABLED: 1
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-macos-amd64
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: amd64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_ENABLED: 1
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
if-no-files-found: error
|
||||
build_linux:
|
||||
name: Build for Linux
|
||||
runs-on: ${{ matrix.runner }}
|
||||
needs: [get_version, test]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
- arch: amd64
|
||||
runner: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-linux-$GOARCH
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
if-no-files-found: error
|
||||
build_ios:
|
||||
name: Build for iOS
|
||||
runs-on: macos-latest
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: brew install ldid cmake
|
||||
- run: ./tools/build-ios.sh "ipatool-$VERSION-ios-arm64"
|
||||
env:
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
if-no-files-found: error
|
||||
release_ios:
|
||||
name: Release for iOS
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build_ios, release_windows]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
path: bin
|
||||
- run: chmod +x "bin/$FILE" && tar -czvf "$FILE.tar.gz" "bin/$FILE"
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
- run: ./tools/sha256sum.sh "$TARBALL" > "$TARBALL.sha256sum"
|
||||
env:
|
||||
TARBALL: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64.tar.gz
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64.*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
release_windows:
|
||||
name: Release for Windows
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.exe
|
||||
path: bin
|
||||
- run: tar -czvf $FILE.tar.gz bin/$FILE.exe
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}
|
||||
- run: ./tools/sha256sum.sh $TARBALL > $TARBALL.sha256sum
|
||||
env:
|
||||
TARBALL: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.tar.gz
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
release_linux:
|
||||
name: Release for Linux
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build_linux, release_windows]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
path: bin
|
||||
- run: chmod +x bin/$FILE && tar -czvf $FILE.tar.gz bin/$FILE
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
- run: ./tools/sha256sum.sh $TARBALL > $TARBALL.sha256sum
|
||||
env:
|
||||
TARBALL: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}.tar.gz
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}.*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
release_macos:
|
||||
name: Release for macOS
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build, build_linux, release_windows, release_linux]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
path: ./ipatool
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
path: bin
|
||||
- run: chmod +x bin/$BIN && tar -czvf $BIN.tar.gz bin/$BIN && rm -rf bin/
|
||||
env:
|
||||
BIN: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
path: bin
|
||||
- run: chmod +x bin/$FILE && tar -czvf $FILE.tar.gz bin/$FILE && rm -rf bin/
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
- id: sha256
|
||||
run: |
|
||||
SHA256_ARM64=$(./ipatool/tools/sha256sum.sh ipatool-${{ needs.get_version.outputs.version }}-macos-arm64.tar.gz)
|
||||
SHA256_AMD64=$(./ipatool/tools/sha256sum.sh ipatool-${{ needs.get_version.outputs.version }}-macos-amd64.tar.gz)
|
||||
echo $SHA256_ARM64 > ipatool-${{ needs.get_version.outputs.version }}-macos-arm64.tar.gz.sha256sum
|
||||
echo $SHA256_AMD64 > ipatool-${{ needs.get_version.outputs.version }}-macos-amd64.tar.gz.sha256sum
|
||||
echo ::set-output name=sha256_arm64::$SHA256_ARM64
|
||||
echo ::set-output name=sha256_amd64::$SHA256_AMD64
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-macos-*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: ${{ secrets.HOMEBREW_REPO }}
|
||||
ref: main
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
path: homebrew-repo
|
||||
- run: |
|
||||
cd homebrew-repo
|
||||
sed -i "3s/.*/ sha256 \"$SHA256_ARM64\"/" Casks/ipatool.rb
|
||||
sed -i "4s/.*/ url \"https:\/\/github.com\/majd\/ipatool\/releases\/download\/v${{ needs.get_version.outputs.version }}\/ipatool-${{ needs.get_version.outputs.version }}-macos-arm64.tar.gz\"/" Casks/ipatool.rb
|
||||
sed -i "5s/.*/ binary \"bin\/ipatool-${{ needs.get_version.outputs.version }}-macos-arm64\", target: \"ipatool\"/" Casks/ipatool.rb
|
||||
sed -i "7s/.*/ sha256 \"$SHA256_AMD64\"/" Casks/ipatool.rb
|
||||
sed -i "8s/.*/ url \"https:\/\/github.com\/majd\/ipatool\/releases\/download\/v${{ needs.get_version.outputs.version }}\/ipatool-${{ needs.get_version.outputs.version }}-macos-amd64.tar.gz\"/" Casks/ipatool.rb
|
||||
sed -i "9s/.*/ binary \"bin\/ipatool-${{ needs.get_version.outputs.version }}-macos-amd64\", target: \"ipatool\"/" Casks/ipatool.rb
|
||||
sed -i "12s/.*/ version \"${{ needs.get_version.outputs.version }}\"/" Casks/ipatool.rb
|
||||
git config --local user.name ${{ secrets.GH_NAME }}
|
||||
git config --local user.email ${{ secrets.GH_EMAIL }}
|
||||
git add Casks/ipatool.rb
|
||||
git commit -m "Update ipatool to v${{ needs.get_version.outputs.version }}"
|
||||
git push "https://${{ secrets.GH_TOKEN }}@github.com/${{ secrets.HOMEBREW_REPO }}.git" --set-upstream "main"
|
||||
env:
|
||||
SHA256_ARM64: ${{ steps.sha256.outputs.sha256_arm64 }}
|
||||
SHA256_AMD64: ${{ steps.sha256.outputs.sha256_amd64 }}
|
||||
@@ -0,0 +1,62 @@
|
||||
name: Unit Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
cross_build_library:
|
||||
name: Cross-build Windows library consumer
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- name: Build from an independent module without dependency replacements
|
||||
shell: bash
|
||||
env:
|
||||
GOWORK: "off"
|
||||
CGO_ENABLED: "0"
|
||||
run: |
|
||||
consumer_dir=$(mktemp -d)
|
||||
cd "$consumer_dir"
|
||||
go mod init example.com/ipatool-consumer
|
||||
go mod edit -require=github.com/majd/ipatool/v2@v2.0.0
|
||||
go mod edit -replace="github.com/majd/ipatool/v2=$GITHUB_WORKSPACE"
|
||||
cat > main.go <<'EOF'
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
)
|
||||
|
||||
func main() {
|
||||
_ = appstore.NewAppStore(appstore.Args{})
|
||||
if err := appstore.Prepare(context.Background()); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
EOF
|
||||
go mod tidy
|
||||
GOOS=windows GOARCH=amd64 go build -o consumer-amd64.exe .
|
||||
GOOS=windows GOARCH=arm64 go build -o consumer-arm64.exe .
|
||||
|
||||
run_tests:
|
||||
name: Run tests
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
runner: [ubuntu-latest, windows-latest, windows-11-arm]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.26.5"
|
||||
cache: true
|
||||
- run: go generate ./...
|
||||
- run: go test -v -timeout 20m ./...
|
||||
+4
-126
@@ -1,129 +1,7 @@
|
||||
### macOS ###
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
### Swift ###
|
||||
# Xcode
|
||||
#
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
## User settings
|
||||
xcuserdata/
|
||||
|
||||
## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
|
||||
*.xcscmblueprint
|
||||
*.xccheckout
|
||||
|
||||
## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
|
||||
build/
|
||||
DerivedData/
|
||||
*.moved-aside
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
|
||||
## Obj-C/Swift specific
|
||||
*.hmap
|
||||
|
||||
## App packaging
|
||||
*.ipa
|
||||
*.dSYM.zip
|
||||
*.dSYM
|
||||
|
||||
## Playgrounds
|
||||
timeline.xctimeline
|
||||
playground.xcworkspace
|
||||
|
||||
# Swift Package Manager
|
||||
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
|
||||
# Packages/
|
||||
# Package.pins
|
||||
# Package.resolved
|
||||
# *.xcodeproj
|
||||
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
|
||||
# hence it is not needed unless you have added a package configuration file to your project
|
||||
# .swiftpm
|
||||
|
||||
.build/
|
||||
|
||||
# CocoaPods
|
||||
# We recommend against adding the Pods directory to your .gitignore. However
|
||||
# you should judge for yourself, the pros and cons are mentioned at:
|
||||
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
|
||||
# Pods/
|
||||
# Add this line if you want to avoid checking in source code from the Xcode workspace
|
||||
# *.xcworkspace
|
||||
|
||||
# Carthage
|
||||
# Add this line if you want to avoid checking in source code from Carthage dependencies.
|
||||
# Carthage/Checkouts
|
||||
|
||||
Carthage/Build/
|
||||
|
||||
# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12)
|
||||
# Dependencies/
|
||||
# .accio/
|
||||
|
||||
# fastlane
|
||||
# It is recommended to not store the screenshots in the git repo.
|
||||
# Instead, use fastlane to re-generate the screenshots whenever they are needed.
|
||||
# For more information about the recommended setup visit:
|
||||
# https://docs.fastlane.tools/best-practices/source-control/#source-control
|
||||
|
||||
fastlane/report.xml
|
||||
fastlane/Preview.html
|
||||
fastlane/screenshots/**/*.png
|
||||
fastlane/test_output
|
||||
|
||||
# Code Injection
|
||||
# After new code Injection tools there's a generated folder /iOSInjectionProject
|
||||
# https://github.com/johnno1962/injectionforxcode
|
||||
|
||||
iOSInjectionProject/
|
||||
|
||||
### Xcode ###
|
||||
# Xcode
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
|
||||
|
||||
|
||||
|
||||
## Gcc Patch
|
||||
/*.gcno
|
||||
|
||||
### Xcode Patch ###
|
||||
*.xcodeproj/*
|
||||
!*.xcodeproj/project.pbxproj
|
||||
!*.xcodeproj/xcshareddata/
|
||||
!*.xcworkspace/contents.xcworkspacedata
|
||||
**/xcshareddata/WorkspaceSettings.xcsettings
|
||||
.vscode/
|
||||
.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$
|
||||
@@ -0,0 +1,103 @@
|
||||
<p align="center">
|
||||
<a href="https://GitHub.com/majd/ipatool/releases/"><img src="https://img.shields.io/github/release/majd/ipatool.svg?label=Release" alt="Release"></a>
|
||||
<a href="https://github.com/majd/ipatool/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License"></a>
|
||||
<a href="https://github.com/sponsors/majd"><img src="https://img.shields.io/badge/Sponsor-%E2%9D%A4-pink.svg" alt="Sponsor"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<code>ipatool</code> is a command line tool that allows you to search for iOS, iPadOS, tvOS, watchOS, visionOS, and macOS apps on the <a href="https://apps.apple.com">App Store</a>, and download <code>.ipa</code> or macOS <code>.pkg</code> app packages.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="./resources/demo.gif" alt="Demo">
|
||||
</p>
|
||||
|
||||
## Requirements
|
||||
|
||||
- A supported operating system (macOS, Linux, Windows or iOS).
|
||||
- An Apple Account already configured to use the App Store.
|
||||
|
||||
## Installation
|
||||
|
||||
### Linux and Windows
|
||||
|
||||
You can grab the latest version of `ipatool` from [GitHub releases](https://github.com/majd/ipatool/releases).
|
||||
|
||||
### macOS
|
||||
|
||||
You can install `ipatool` using [Homebrew](https://brew.sh).
|
||||
|
||||
```shell
|
||||
$ brew install ipatool
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
To get started, run the following command.
|
||||
|
||||
```text
|
||||
$ ipatool --help
|
||||
A cli tool for interacting with Apple's ipa files
|
||||
|
||||
Usage:
|
||||
ipatool [command]
|
||||
|
||||
Available Commands:
|
||||
auth Authenticate with the App Store
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
download Download iOS, iPadOS, tvOS, watchOS, visionOS, and macOS app packages from the App Store
|
||||
get-version-metadata Retrieves the metadata for a specific version of an app
|
||||
help Help about any command
|
||||
list-purchases List apps owned by the authenticated App Store account
|
||||
list-versions List the available versions of an App Store app
|
||||
mcp Serve App Store tools over MCP using stdio
|
||||
purchase Obtain a license for the app from the App Store
|
||||
search Search for iOS, iPadOS, tvOS, watchOS, visionOS, and macOS apps available on the App Store
|
||||
|
||||
Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
-h, --help help for ipatool
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
-v, --version version for ipatool
|
||||
|
||||
Use "ipatool [command] --help" for more information about a command.
|
||||
```
|
||||
|
||||
**Note:** the tool runs in interactive mode by default. Use the `--non-interactive` flag
|
||||
if running in an automated environment.
|
||||
|
||||
### MCP tools
|
||||
|
||||
Run `ipatool auth login` in a terminal, then configure your MCP client to launch the stdio server:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"ipatool": {
|
||||
"command": "ipatool",
|
||||
"args": ["mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 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 ./...
|
||||
$ go test -v ./...
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
ipatool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
|
||||
@@ -1,166 +0,0 @@
|
||||
//
|
||||
// Download.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
|
||||
struct Download: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Download (encrypted) iOS app packages from the App Store.")
|
||||
}
|
||||
|
||||
@Option(name: [.short, .long], help: "The bundle identifier of the target iOS app.")
|
||||
private var bundleIdentifier: String
|
||||
|
||||
@Option(name: [.short, .long], help: "The email address for the Apple ID.")
|
||||
private var email: String?
|
||||
|
||||
@Option(name: [.short, .long], help: "The password for the Apple ID.")
|
||||
private var password: String?
|
||||
|
||||
@Option
|
||||
private var logLevel: LogLevel = .info
|
||||
}
|
||||
|
||||
extension Download {
|
||||
func run() throws {
|
||||
let logger = ConsoleLogger(level: logLevel)
|
||||
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(urlSession: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
logger.log("Creating App Store client...", level: .debug)
|
||||
let storeClient = StoreClient(httpClient: httpClient)
|
||||
|
||||
logger.log("Creating download client...", level: .debug)
|
||||
let downloadClient = HTTPDownloadClient()
|
||||
|
||||
logger.log("Querying the iTunes store for '\(bundleIdentifier)'...", level: .info)
|
||||
let app: iTunesResponse.Result
|
||||
|
||||
do {
|
||||
app = try itunesClient.lookup(bundleIdentifier: bundleIdentifier)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case iTunesClient.Error.appNotFound:
|
||||
logger.log("Could not find app.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
logger.log("Found app: \(app.name) (\(app.version)).", level: .debug)
|
||||
|
||||
let email: String
|
||||
let password: String
|
||||
|
||||
if let cliEmail = self.email {
|
||||
email = cliEmail
|
||||
} else if let envEmail = ProcessInfo.processInfo.environment["IPATOOL_EMAIL"] {
|
||||
email = envEmail
|
||||
} else if let inputEmail = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID email: ", level: .warning)))) {
|
||||
email = inputEmail
|
||||
} else {
|
||||
logger.log("An Apple ID email address is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
if let cliPassword = self.password {
|
||||
password = cliPassword
|
||||
} else if let envPassword = ProcessInfo.processInfo.environment["IPATOOL_PASSWORD"] {
|
||||
password = envPassword
|
||||
} else if let inputPassword = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter Apple ID password: ", level: .warning)))) {
|
||||
password = inputPassword
|
||||
} else {
|
||||
logger.log("An Apple ID password is required.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
let account: StoreResponse.Account
|
||||
|
||||
do {
|
||||
logger.log("Authenticating with the App Store...", level: .info)
|
||||
account = try storeClient.authenticate(email: email, password: password)
|
||||
} catch {
|
||||
switch error {
|
||||
case StoreResponse.Error.codeRequired:
|
||||
let code = String(validatingUTF8: UnsafePointer<CChar>(getpass(logger.compile("Enter 2FA code: ", level: .warning))))
|
||||
|
||||
do {
|
||||
account = try storeClient.authenticate(email: email, password: password, code: code)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.invalidResponse:
|
||||
logger.log("Received invalid response.", level: .error)
|
||||
case StoreResponse.Error.invalidAccount:
|
||||
logger.log("This Apple ID has not been set up to use the App Store.", level: .error)
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
logger.log("Invalid credentials.", level: .error)
|
||||
case StoreResponse.Error.lockedAccount:
|
||||
logger.log("This Apple ID has been disabled for security reasons.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
default:
|
||||
logger.log("\(error)", level: .debug)
|
||||
|
||||
switch error {
|
||||
case StoreClient.Error.invalidResponse:
|
||||
logger.log("Received invalid response.", level: .error)
|
||||
case StoreResponse.Error.invalidAccount:
|
||||
logger.log("This Apple ID has not been set up to use the App Store.", level: .error)
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
logger.log("Invalid credentials.", level: .error)
|
||||
case StoreResponse.Error.lockedAccount:
|
||||
logger.log("This Apple ID has been disabled for security reasons.", level: .error)
|
||||
default:
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
}
|
||||
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
logger.log("Authenticated as '\(account.firstName) \(account.lastName)'.", level: .info)
|
||||
|
||||
logger.log("Requesting a signed copy of '\(app.identifier)' from the App Store...", level: .info)
|
||||
let item = try storeClient.item(identifier: "\(app.identifier)", directoryServicesIdentifier: account.directoryServicesIdentifier)
|
||||
logger.log("Received a response of the signed copy: \(item.md5).", level: .debug)
|
||||
|
||||
logger.log("Creating signature client...", level: .debug)
|
||||
let path = FileManager.default.currentDirectoryPath
|
||||
.appending("/\(bundleIdentifier)_\(app.identifier)_v\(app.version)_\(Int.random(in: 100...999))")
|
||||
.appending(".ipa")
|
||||
|
||||
logger.log("Output path: \(path).", level: .debug)
|
||||
let signatureClient = SignatureClient(fileManager: .default, filePath: path)
|
||||
|
||||
logger.log("Downloading app package...", level: .info)
|
||||
try downloadClient.download(from: item.url, to: URL(fileURLWithPath: path)) { progress in
|
||||
logger.log("Downloading app package... [\(Int((progress * 100).rounded()))%]",
|
||||
prefix: "\u{1B}[1A\u{1B}[K",
|
||||
level: .info)
|
||||
}
|
||||
logger.log("Saved app package to \(URL(fileURLWithPath: path).lastPathComponent).", level: .info)
|
||||
|
||||
logger.log("Applying patches...", level: .info)
|
||||
try signatureClient.appendMetadata(item: item, email: email)
|
||||
try signatureClient.appendSignature(item: item)
|
||||
|
||||
logger.log("Done.", level: .info)
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
//
|
||||
// Search.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
|
||||
struct Search: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(abstract: "Search for iOS apps available on the App Store.")
|
||||
}
|
||||
|
||||
@Option
|
||||
private var logLevel: LogLevel = .info
|
||||
|
||||
@Option
|
||||
private var limit: Int = 5
|
||||
|
||||
@Argument(help: "The term to search for.")
|
||||
var term: String
|
||||
}
|
||||
|
||||
extension Search {
|
||||
func run() throws {
|
||||
let logger = ConsoleLogger(level: logLevel)
|
||||
|
||||
logger.log("Creating HTTP client...", level: .debug)
|
||||
let httpClient = HTTPClient(urlSession: URLSession.shared)
|
||||
|
||||
logger.log("Creating iTunes client...", level: .debug)
|
||||
let itunesClient = iTunesClient(httpClient: httpClient)
|
||||
|
||||
do {
|
||||
logger.log("Searching for '\(term)'...", level: .info)
|
||||
let results = try itunesClient.search(term: term, limit: limit)
|
||||
|
||||
guard !results.isEmpty else {
|
||||
logger.log("No results found.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
|
||||
logger.log("Found \(results.count) results:\n\(results.enumerated().map({ "\($0 + 1). \($1.name): \($1.bundleIdentifier) (\($1.version))." }).joined(separator: "\n"))", level: .info)
|
||||
} catch {
|
||||
logger.log("\(error)", level: .debug)
|
||||
logger.log("An unknown error has occurred.", level: .error)
|
||||
_exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
//
|
||||
// IPATool.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import ArgumentParser
|
||||
|
||||
struct IPATool: ParsableCommand {
|
||||
static var configuration: CommandConfiguration {
|
||||
return .init(commandName: "ipatool",
|
||||
abstract: "A cli tool for interacting with Apple's ipa files.",
|
||||
version: "1.0.0",
|
||||
subcommands: [Download.self, Search.self])
|
||||
}
|
||||
}
|
||||
@@ -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,99 +0,0 @@
|
||||
//
|
||||
// HTTPClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPClientInterface {
|
||||
func send(_ request: HTTPRequest, completion: @escaping (Result<HTTPResponse, Error>) -> Void)
|
||||
}
|
||||
|
||||
extension HTTPClientInterface {
|
||||
func send(_ request: HTTPRequest) throws -> HTTPResponse {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<HTTPResponse, Error>?
|
||||
|
||||
send(request) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw HTTPClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(response):
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class HTTPClient: HTTPClientInterface {
|
||||
private let urlSession: URLSessionInterface
|
||||
|
||||
init(urlSession: URLSessionInterface) {
|
||||
self.urlSession = urlSession
|
||||
}
|
||||
|
||||
func send(_ request: HTTPRequest, completion: @escaping (Result<HTTPResponse, Swift.Error>) -> Void) {
|
||||
do {
|
||||
let urlRequest = try makeURLRequest(from: request)
|
||||
|
||||
urlSession.dataTask(with: urlRequest) { (data, response, error) in
|
||||
if let error = error {
|
||||
return completion(.failure(error))
|
||||
}
|
||||
|
||||
guard let response = response as? HTTPURLResponse else {
|
||||
return completion(.failure(Error.invalidResponse(response)))
|
||||
}
|
||||
|
||||
completion(.success(.init(statusCode: response.statusCode, data: data)))
|
||||
}.resume()
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
private func makeURLRequest(from request: HTTPRequest) throws -> URLRequest {
|
||||
var urlRequest = URLRequest(url: request.endpoint.url)
|
||||
urlRequest.httpMethod = request.method.rawValue
|
||||
|
||||
switch request.payload {
|
||||
case .none:
|
||||
urlRequest.httpBody = nil
|
||||
case let .urlEncoding(propertyList):
|
||||
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
||||
|
||||
var urlComponents = URLComponents(string: request.endpoint.url.absoluteString)
|
||||
urlComponents?.queryItems = !propertyList.isEmpty ? propertyList.map { URLQueryItem(name: $0.0, value: $0.1.description) } : nil
|
||||
|
||||
switch request.method {
|
||||
case .get:
|
||||
urlRequest.url = urlComponents?.url
|
||||
case .post:
|
||||
urlRequest.httpBody = urlComponents?.percentEncodedQuery?.data(using: .utf8, allowLossyConversion: false)
|
||||
}
|
||||
case let .xml(value):
|
||||
urlRequest.setValue("application/xml", forHTTPHeaderField: "Content-Type")
|
||||
urlRequest.httpBody = try PropertyListSerialization.data(fromPropertyList: value, format: .xml, options: 0)
|
||||
}
|
||||
|
||||
request.headers.forEach { urlRequest.setValue($0.value, forHTTPHeaderField: $0.key) }
|
||||
|
||||
return urlRequest
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPClient {
|
||||
enum Error: Swift.Error {
|
||||
case invalidResponse(URLResponse?)
|
||||
case timeout
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
//
|
||||
// HTTPDownloadClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPDownloadClientInterface {
|
||||
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void, completion: @escaping (Result<Void, Error>) -> Void)
|
||||
}
|
||||
|
||||
extension HTTPDownloadClientInterface {
|
||||
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void) throws {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<Void, Error>?
|
||||
|
||||
download(from: source, to: target, progress: progress) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw HTTPClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class HTTPDownloadClient: NSObject, HTTPDownloadClientInterface {
|
||||
private var urlSession: URLSession!
|
||||
private var progressHandler: ((Float) -> Void)?
|
||||
private var completionHandler: ((Result<Void, Swift.Error>) -> Void)?
|
||||
private var targetURL: URL?
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
self.urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
|
||||
}
|
||||
|
||||
func download(from source: URL, to target: URL, progress: @escaping (Float) -> Void, completion: @escaping (Result<Void, Swift.Error>) -> Void) {
|
||||
assert(progressHandler == nil)
|
||||
assert(completionHandler == nil)
|
||||
assert(targetURL == nil)
|
||||
|
||||
progressHandler = progress
|
||||
completionHandler = completion
|
||||
targetURL = target
|
||||
urlSession.downloadTask(with: source).resume()
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPDownloadClient: URLSessionDownloadDelegate {
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
||||
progressHandler?(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
|
||||
defer {
|
||||
progressHandler = nil
|
||||
completionHandler = nil
|
||||
targetURL = nil
|
||||
}
|
||||
|
||||
guard let target = targetURL else {
|
||||
return completionHandler?(.failure(Error.invalidTarget)) ?? ()
|
||||
}
|
||||
|
||||
do {
|
||||
try FileManager.default.moveItem(at: location, to: target)
|
||||
completionHandler?(.success(()))
|
||||
} catch {
|
||||
completionHandler?(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPDownloadClient {
|
||||
enum Error: Swift.Error {
|
||||
case invalidTarget
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
//
|
||||
// HTTPEndpoint.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPEndpoint {
|
||||
var url: URL { get }
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
//
|
||||
// HTTPMethod.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum HTTPMethod: String {
|
||||
case get = "GET"
|
||||
case post = "POST"
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
//
|
||||
// HTTPPayload.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum HTTPPayload {
|
||||
case xml([String: String])
|
||||
case urlEncoding([String: String])
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
//
|
||||
// HTTPRequest.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol HTTPRequest {
|
||||
var method: HTTPMethod { get }
|
||||
var endpoint: HTTPEndpoint { get }
|
||||
var headers: [String: String] { get }
|
||||
var payload: HTTPPayload? { get }
|
||||
}
|
||||
|
||||
extension HTTPRequest {
|
||||
var headers: [String: String] { [:] }
|
||||
var payload: HTTPPayload? { nil }
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
//
|
||||
// HTTPResponse.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct HTTPResponse {
|
||||
let statusCode: Int
|
||||
let data: Data?
|
||||
}
|
||||
|
||||
extension HTTPResponse {
|
||||
func decode<T: Decodable>(_ type: T.Type, as decoder: Decoder) throws -> T {
|
||||
guard let data = data else {
|
||||
throw Error.noData
|
||||
}
|
||||
|
||||
switch decoder {
|
||||
case .json:
|
||||
let decoder = JSONDecoder()
|
||||
decoder.userInfo = [.init(rawValue: "data")!: data]
|
||||
return try decoder.decode(type, from: data)
|
||||
case .xml:
|
||||
let decoder = PropertyListDecoder()
|
||||
decoder.userInfo = [.init(rawValue: "data")!: data]
|
||||
return try decoder.decode(type, from: data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPResponse {
|
||||
enum Decoder {
|
||||
case json
|
||||
case xml
|
||||
}
|
||||
|
||||
enum Error: Swift.Error {
|
||||
case noData
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
//
|
||||
// URLSession.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol URLSessionInterface {
|
||||
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
|
||||
}
|
||||
|
||||
extension URLSession: URLSessionInterface {}
|
||||
@@ -1,109 +0,0 @@
|
||||
//
|
||||
// SignatureClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ZIPFoundation
|
||||
|
||||
protocol SignatureClientInterface {
|
||||
func appendMetadata(item: StoreResponse.Item, email: String) throws
|
||||
func appendSignature(item: StoreResponse.Item) throws
|
||||
}
|
||||
|
||||
final class SignatureClient: SignatureClientInterface {
|
||||
private let fileManager: FileManager
|
||||
private let filePath: String
|
||||
|
||||
init(fileManager: FileManager, filePath: String) {
|
||||
self.fileManager = fileManager
|
||||
self.filePath = filePath
|
||||
}
|
||||
|
||||
func appendMetadata(item: StoreResponse.Item, email: String) throws {
|
||||
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
|
||||
throw Error.invalidArchive
|
||||
}
|
||||
|
||||
var metadata = item.metadata
|
||||
metadata["apple-id"] = email
|
||||
metadata["userName"] = email
|
||||
|
||||
let metadataUrl = URL(fileURLWithPath: NSTemporaryDirectory().appending("\(UUID().uuidString)/iTunesMetadata.plist"))
|
||||
|
||||
try fileManager.createDirectory(at: metadataUrl.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try PropertyListSerialization.data(fromPropertyList: metadata, format: .xml, options: .zero).write(to: metadataUrl)
|
||||
try archive.addEntry(with: metadataUrl.lastPathComponent, relativeTo: metadataUrl.deletingLastPathComponent())
|
||||
try fileManager.removeItem(at: metadataUrl)
|
||||
}
|
||||
|
||||
func appendSignature(item: StoreResponse.Item) throws {
|
||||
guard let archive = Archive(url: URL(fileURLWithPath: filePath), accessMode: .update) else {
|
||||
throw Error.invalidArchive
|
||||
}
|
||||
|
||||
let manifest = try readPlist(archive: archive, matchingSuffix: ".app/SC_Info/Manifest.plist", type: Manifest.self)
|
||||
|
||||
guard let infoEntry = archive.first(where: { $0.path.hasSuffix(".app/Info.plist") }) else {
|
||||
throw Error.invalidAppBundle
|
||||
}
|
||||
|
||||
let appBundleName = URL(fileURLWithPath: infoEntry.path)
|
||||
.deletingLastPathComponent()
|
||||
.deletingPathExtension()
|
||||
.lastPathComponent
|
||||
|
||||
guard let signatureItem = item.signatures.first(where: { $0.id == 0 }), let signatureTargetPath = manifest.paths.first else {
|
||||
throw Error.invalidSignature
|
||||
}
|
||||
|
||||
let signatureBaseUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
|
||||
let signatureUrl = signatureBaseUrl
|
||||
.appendingPathComponent("Payload")
|
||||
.appendingPathComponent(appBundleName)
|
||||
.appendingPathExtension("app")
|
||||
.appendingPathComponent(signatureTargetPath)
|
||||
|
||||
let signatureRelativePath = signatureUrl.path.replacingOccurrences(of: "\(signatureBaseUrl.path)/", with: "")
|
||||
|
||||
try fileManager.createDirectory(at: signatureUrl.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try signatureItem.sinf.write(to: signatureUrl)
|
||||
try archive.addEntry(with: signatureRelativePath, relativeTo: signatureBaseUrl)
|
||||
try fileManager.removeItem(at: signatureBaseUrl)
|
||||
}
|
||||
|
||||
private func readPlist<T: Decodable>(archive: Archive, matchingSuffix: String, type: T.Type) throws -> T {
|
||||
guard let entry = archive.first(where: { $0.path.hasSuffix(matchingSuffix) }) else {
|
||||
throw Error.fileNotFound(matchingSuffix)
|
||||
}
|
||||
|
||||
let url = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent(UUID().uuidString).appendingPathExtension("plist")
|
||||
_ = try archive.extract(entry, to: url)
|
||||
|
||||
let data = try Data(contentsOf: url)
|
||||
let plist = try PropertyListDecoder().decode(type, from: data)
|
||||
|
||||
try FileManager.default.removeItem(at: url)
|
||||
|
||||
return plist
|
||||
}
|
||||
}
|
||||
|
||||
extension SignatureClient {
|
||||
struct Manifest: Codable {
|
||||
let paths: [String]
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case paths = "SinfPaths"
|
||||
}
|
||||
}
|
||||
|
||||
enum Error: Swift.Error {
|
||||
case invalidArchive
|
||||
case invalidAppBundle
|
||||
case invalidSignature
|
||||
case fileNotFound(String)
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
//
|
||||
// StoreClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol StoreClientInterface {
|
||||
func authenticate(email: String, password: String, code: String?, completion: @escaping (Result<StoreResponse.Account, Error>) -> Void)
|
||||
func item(identifier: String, directoryServicesIdentifier: String, completion: @escaping (Result<StoreResponse.Item, Error>) -> Void)
|
||||
}
|
||||
|
||||
extension StoreClientInterface {
|
||||
func authenticate(email: String,
|
||||
password: String,
|
||||
code: String? = nil,
|
||||
completion: @escaping (Result<StoreResponse.Account, Swift.Error>) -> Void) {
|
||||
authenticate(email: email, password: password, code: code, completion: completion)
|
||||
}
|
||||
|
||||
func authenticate(email: String, password: String, code: String? = nil) throws -> StoreResponse.Account {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<StoreResponse.Account, Error>?
|
||||
|
||||
authenticate(email: email, password: password, code: code) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw StoreClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
func item(identifier: String, directoryServicesIdentifier: String) throws -> StoreResponse.Item {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<StoreResponse.Item, Error>?
|
||||
|
||||
item(identifier: identifier, directoryServicesIdentifier: directoryServicesIdentifier) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw StoreClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class StoreClient: StoreClientInterface {
|
||||
private let httpClient: HTTPClient
|
||||
|
||||
init(httpClient: HTTPClient) {
|
||||
self.httpClient = httpClient
|
||||
}
|
||||
|
||||
func authenticate(email: String, password: String, code: String?, completion: @escaping (Result<StoreResponse.Account, Swift.Error>) -> Void) {
|
||||
authenticate(email: email,
|
||||
password: password,
|
||||
code: code,
|
||||
isFirstAttempt: true,
|
||||
completion: completion)
|
||||
}
|
||||
|
||||
private func authenticate(email: String,
|
||||
password: String,
|
||||
code: String?,
|
||||
isFirstAttempt: Bool,
|
||||
completion: @escaping (Result<StoreResponse.Account, Swift.Error>) -> Void) {
|
||||
let request = StoreRequest.authenticate(email: email, password: password, code: code)
|
||||
|
||||
httpClient.send(request) { [weak self] result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch decoded {
|
||||
case let .account(account):
|
||||
completion(.success(account))
|
||||
case .item:
|
||||
completion(.failure(Error.invalidResponse))
|
||||
case let .failure(error):
|
||||
switch error {
|
||||
case StoreResponse.Error.invalidCredentials:
|
||||
if isFirstAttempt {
|
||||
return self?.authenticate(email: email,
|
||||
password: password,
|
||||
code: code,
|
||||
isFirstAttempt: false,
|
||||
completion: completion) ?? ()
|
||||
}
|
||||
|
||||
completion(.failure(error))
|
||||
default:
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func item(identifier: String, directoryServicesIdentifier: String, completion: @escaping (Result<StoreResponse.Item, Swift.Error>) -> Void) {
|
||||
let request = StoreRequest.download(appIdentifier: identifier, directoryServicesIdentifier: directoryServicesIdentifier)
|
||||
|
||||
httpClient.send(request) { result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(StoreResponse.self, as: .xml)
|
||||
|
||||
switch decoded {
|
||||
case let .item(item):
|
||||
completion(.success(item))
|
||||
case .account:
|
||||
completion(.failure(Error.invalidResponse))
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreClient {
|
||||
enum Error: Swift.Error {
|
||||
case timeout
|
||||
case invalidResponse
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
//
|
||||
// StoreEndpoint.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum StoreEndpoint {
|
||||
case authenticate(prefix: String, guid: String)
|
||||
case download(guid: String)
|
||||
}
|
||||
|
||||
extension StoreEndpoint: HTTPEndpoint {
|
||||
var url: URL {
|
||||
var components = URLComponents(string: path)!
|
||||
components.scheme = "https"
|
||||
components.host = host
|
||||
return components.url!
|
||||
}
|
||||
|
||||
private var host: String {
|
||||
switch self {
|
||||
case let .authenticate(prefix, _):
|
||||
return "\(prefix)-buy.itunes.apple.com"
|
||||
case .download:
|
||||
return "p25-buy.itunes.apple.com"
|
||||
}
|
||||
}
|
||||
|
||||
private var path: String {
|
||||
switch self {
|
||||
case let .authenticate(_, guid):
|
||||
return "/WebObjects/MZFinance.woa/wa/authenticate?guid=\(guid)"
|
||||
case let .download(guid):
|
||||
return "/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct?guid=\(guid)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
//
|
||||
// StoreRequest.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum StoreRequest {
|
||||
case authenticate(email: String, password: String, code: String? = nil)
|
||||
case download(appIdentifier: String, directoryServicesIdentifier: String)
|
||||
}
|
||||
|
||||
extension StoreRequest: HTTPRequest {
|
||||
var endpoint: HTTPEndpoint {
|
||||
switch self {
|
||||
case let .authenticate(_, _, code):
|
||||
return StoreEndpoint.authenticate(prefix: (code == nil) ? "p25" : "p71", guid: guid)
|
||||
case .download:
|
||||
return StoreEndpoint.download(guid: guid)
|
||||
}
|
||||
}
|
||||
|
||||
var method: HTTPMethod {
|
||||
return .post
|
||||
}
|
||||
|
||||
var headers: [String: String] {
|
||||
var headers: [String: String] = [
|
||||
"User-Agent": "Configurator/2.0 (Macintosh; OS X 10.12.6; 16G29) AppleWebKit/2603.3.8",
|
||||
"Content-Type": "application/x-www-form-urlencoded"
|
||||
]
|
||||
|
||||
switch self {
|
||||
case .authenticate:
|
||||
break
|
||||
case let .download(_, directoryServicesIdentifier):
|
||||
headers["X-Dsid"] = directoryServicesIdentifier
|
||||
headers["iCloud-DSID"] = directoryServicesIdentifier
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
var payload: HTTPPayload? {
|
||||
switch self {
|
||||
case let .authenticate(email, password, code):
|
||||
return .xml([
|
||||
"appleId": email,
|
||||
"attempt": "\(code == nil ? "4" : "2")",
|
||||
"createSession": "true",
|
||||
"guid": guid,
|
||||
"password": "\(password)\(code ?? "")",
|
||||
"rmp": "0",
|
||||
"why": "signIn"
|
||||
])
|
||||
case let .download(appIdentifier, _):
|
||||
return .xml([
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": "\(appIdentifier)"
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreRequest {
|
||||
// This identifier is calculated by reading the MAC address of the device and stripping the nonalphabetic characters from the string.
|
||||
// https://stackoverflow.com/a/31838376
|
||||
private var guid: String {
|
||||
let MAC_ADDRESS_LENGTH = 6
|
||||
let bsds: [String] = ["en0", "en1"]
|
||||
var bsd: String = bsds[0]
|
||||
|
||||
var length : size_t = 0
|
||||
var buffer : [CChar]
|
||||
|
||||
var bsdIndex = Int32(if_nametoindex(bsd))
|
||||
if bsdIndex == 0 {
|
||||
bsd = bsds[1]
|
||||
bsdIndex = Int32(if_nametoindex(bsd))
|
||||
guard bsdIndex != 0 else { fatalError("Could not read MAC address") }
|
||||
}
|
||||
|
||||
let bsdData = Data(bsd.utf8)
|
||||
var managementInfoBase = [CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, bsdIndex]
|
||||
|
||||
guard sysctl(&managementInfoBase, 6, nil, &length, nil, 0) >= 0 else { fatalError("Could not read MAC address") }
|
||||
|
||||
buffer = [CChar](unsafeUninitializedCapacity: length, initializingWith: {buffer, initializedCount in
|
||||
for x in 0..<length { buffer[x] = 0 }
|
||||
initializedCount = length
|
||||
})
|
||||
|
||||
guard sysctl(&managementInfoBase, 6, &buffer, &length, nil, 0) >= 0 else { fatalError("Could not read MAC address") }
|
||||
|
||||
let infoData = Data(bytes: buffer, count: length)
|
||||
let indexAfterMsghdr = MemoryLayout<if_msghdr>.stride + 1
|
||||
let rangeOfToken = infoData[indexAfterMsghdr...].range(of: bsdData)!
|
||||
let lower = rangeOfToken.upperBound
|
||||
let upper = lower + MAC_ADDRESS_LENGTH
|
||||
let macAddressData = infoData[lower..<upper]
|
||||
let addressBytes = macAddressData.map{ String(format:"%02x", $0) }
|
||||
return addressBytes.joined().uppercased()
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
//
|
||||
// StoreResponse.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum StoreResponse {
|
||||
case failure(error: Swift.Error)
|
||||
case account(Account)
|
||||
case item(Item)
|
||||
}
|
||||
|
||||
extension StoreResponse {
|
||||
struct Account {
|
||||
let firstName: String
|
||||
let lastName: String
|
||||
let directoryServicesIdentifier: String
|
||||
}
|
||||
|
||||
struct Item {
|
||||
let url: URL
|
||||
let md5: String
|
||||
let signatures: [Signature]
|
||||
let metadata: [String: Any]
|
||||
}
|
||||
|
||||
enum Error: Int, Swift.Error {
|
||||
case unknownError = 0
|
||||
case genericError = 5002
|
||||
case codeRequired = 1
|
||||
case invalidLicense = 9610
|
||||
case invalidCredentials = -5000
|
||||
case invalidAccount = 5001
|
||||
case invalidItem = -10000
|
||||
case lockedAccount = -10001
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreResponse: Decodable {
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
|
||||
let error = try container.decodeIfPresent(String.self, forKey: .error)
|
||||
let message = try container.decodeIfPresent(String.self, forKey: .message)
|
||||
|
||||
if container.contains(.account) {
|
||||
let directoryServicesIdentifier = try container.decode(String.self, forKey: .directoryServicesIdentifier)
|
||||
let accountContainer = try container.nestedContainer(keyedBy: AccountInfoCodingKeys.self, forKey: .account)
|
||||
let addressContainer = try accountContainer.nestedContainer(keyedBy: AddressCodingKeys.self, forKey: .address)
|
||||
let firstName = try addressContainer.decode(String.self, forKey: .firstName)
|
||||
let lastName = try addressContainer.decode(String.self, forKey: .lastName)
|
||||
|
||||
self = .account(.init(firstName: firstName, lastName: lastName, directoryServicesIdentifier: directoryServicesIdentifier))
|
||||
} else if let items = try container.decodeIfPresent([Item].self, forKey: .items), let item = items.first {
|
||||
self = .item(item)
|
||||
} else if let error = error, !error.isEmpty {
|
||||
self = .failure(error: Error(rawValue: Int(error) ?? 0) ?? .unknownError)
|
||||
} else {
|
||||
switch message {
|
||||
case "Your account information was entered incorrectly.":
|
||||
self = .failure(error: Error.invalidCredentials)
|
||||
case "An Apple ID verification code is required to sign in. Type your password followed by the verification code shown on your other devices.":
|
||||
self = .failure(error: Error.codeRequired)
|
||||
case "This Apple ID has been locked for security reasons. Visit iForgot to reset your account (https://iforgot.apple.com).":
|
||||
self = .failure(error: Error.lockedAccount)
|
||||
default:
|
||||
self = .failure(error: Error.unknownError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case directoryServicesIdentifier = "dsPersonId"
|
||||
case message = "customerMessage"
|
||||
case items = "songList"
|
||||
case error = "failureType"
|
||||
case account = "accountInfo"
|
||||
}
|
||||
|
||||
private enum AccountInfoCodingKeys: String, CodingKey {
|
||||
case address
|
||||
}
|
||||
|
||||
private enum AddressCodingKeys: String, CodingKey {
|
||||
case firstName
|
||||
case lastName
|
||||
}
|
||||
}
|
||||
|
||||
extension StoreResponse.Item: Decodable {
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let md5 = try container.decode(String.self, forKey: .md5)
|
||||
|
||||
guard let key = CodingUserInfoKey(rawValue: "data"),
|
||||
let data = decoder.userInfo[key] as? Data,
|
||||
let json = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any],
|
||||
let items = json["songList"] as? [[String: Any]],
|
||||
let item = items.first(where: { $0["md5"] as? String == md5 }),
|
||||
let metadata = item["metadata"] as? [String: Any]
|
||||
else { throw StoreResponse.Error.invalidItem }
|
||||
|
||||
let absoluteUrl = try container.decode(String.self, forKey: .url)
|
||||
|
||||
self.md5 = md5
|
||||
self.metadata = metadata
|
||||
self.signatures = try container.decode([Signature].self, forKey: .signatures)
|
||||
|
||||
if let url = URL(string: absoluteUrl) {
|
||||
self.url = url
|
||||
} else {
|
||||
let context = DecodingError.Context(codingPath: [CodingKeys.url], debugDescription: "URL contains illegal characters: \(absoluteUrl).")
|
||||
throw DecodingError.keyNotFound(CodingKeys.url, context)
|
||||
}
|
||||
}
|
||||
|
||||
struct Signature: Decodable {
|
||||
let id: Int
|
||||
let sinf: Data
|
||||
}
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case url = "URL"
|
||||
case metadata
|
||||
case md5
|
||||
case signatures = "sinfs"
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
//
|
||||
// iTunesClient.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
protocol iTunesClientInterface {
|
||||
func lookup(bundleIdentifier: String, completion: @escaping (Result<iTunesResponse.Result, Error>) -> Void)
|
||||
func search(term: String, limit: Int, completion: @escaping (Result<[iTunesResponse.Result], Error>) -> Void)
|
||||
}
|
||||
|
||||
extension iTunesClientInterface {
|
||||
func lookup(bundleIdentifier: String) throws -> iTunesResponse.Result {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<iTunesResponse.Result, Error>?
|
||||
|
||||
lookup(bundleIdentifier: bundleIdentifier) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw iTunesClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
func search(term: String, limit: Int) throws -> [iTunesResponse.Result] {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<[iTunesResponse.Result], Error>?
|
||||
|
||||
search(term: term, limit: limit) {
|
||||
result = $0
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
|
||||
switch result {
|
||||
case .none:
|
||||
throw iTunesClient.Error.timeout
|
||||
case let .failure(error):
|
||||
throw error
|
||||
case let .success(result):
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class iTunesClient: iTunesClientInterface {
|
||||
private let httpClient: HTTPClient
|
||||
|
||||
init(httpClient: HTTPClient) {
|
||||
self.httpClient = httpClient
|
||||
}
|
||||
|
||||
func lookup(bundleIdentifier: String, completion: @escaping (Result<iTunesResponse.Result, Swift.Error>) -> Void) {
|
||||
let request = iTunesRequest.lookup(bundleIdentifier: bundleIdentifier)
|
||||
|
||||
httpClient.send(request) { result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(iTunesResponse.self, as: .json)
|
||||
guard let result = decoded.results.first else { return completion(.failure(Error.appNotFound)) }
|
||||
completion(.success(result))
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func search(term: String, limit: Int, completion: @escaping (Result<[iTunesResponse.Result], Swift.Error>) -> Void) {
|
||||
let request = iTunesRequest.search(term: term, limit: limit)
|
||||
|
||||
httpClient.send(request) { result in
|
||||
switch result {
|
||||
case let .success(response):
|
||||
do {
|
||||
let decoded = try response.decode(iTunesResponse.self, as: .json)
|
||||
completion(.success(decoded.results))
|
||||
} catch {
|
||||
completion(.failure(error))
|
||||
}
|
||||
case let .failure(error):
|
||||
completion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension iTunesClient {
|
||||
enum Error: Swift.Error {
|
||||
case timeout
|
||||
case appNotFound
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
//
|
||||
// iTunesEndpoint.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum iTunesEndpoint {
|
||||
case search
|
||||
case lookup
|
||||
}
|
||||
|
||||
extension iTunesEndpoint: HTTPEndpoint {
|
||||
var url: URL {
|
||||
var components = URLComponents(string: path)!
|
||||
components.scheme = "https"
|
||||
components.host = "itunes.apple.com"
|
||||
return components.url!
|
||||
}
|
||||
|
||||
private var path: String {
|
||||
switch self {
|
||||
case .search:
|
||||
return "/search"
|
||||
case .lookup:
|
||||
return "/lookup"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
//
|
||||
// iTunesRequest.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum iTunesRequest {
|
||||
case search(term: String, limit: Int)
|
||||
case lookup(bundleIdentifier: String)
|
||||
}
|
||||
|
||||
extension iTunesRequest: HTTPRequest {
|
||||
var method: HTTPMethod {
|
||||
return .get
|
||||
}
|
||||
|
||||
var endpoint: HTTPEndpoint {
|
||||
switch self {
|
||||
case .lookup:
|
||||
return iTunesEndpoint.lookup
|
||||
case .search:
|
||||
return iTunesEndpoint.search
|
||||
}
|
||||
}
|
||||
|
||||
var payload: HTTPPayload? {
|
||||
switch self {
|
||||
case let .lookup(bundleIdentifier):
|
||||
return .urlEncoding(["media": "software", "bundleId": bundleIdentifier, "limit": "1"])
|
||||
case let .search(term, limit):
|
||||
return .urlEncoding(["media": "software", "term": term, "limit": "\(limit)"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
//
|
||||
// iTunesResponse.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct iTunesResponse {
|
||||
let results: [Result]
|
||||
let count: Int
|
||||
}
|
||||
|
||||
extension iTunesResponse {
|
||||
struct Result {
|
||||
let bundleIdentifier: String
|
||||
let version: String
|
||||
let identifier: Int
|
||||
let name: String
|
||||
}
|
||||
}
|
||||
|
||||
extension iTunesResponse: Codable {
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case count = "resultCount"
|
||||
case results
|
||||
}
|
||||
}
|
||||
|
||||
extension iTunesResponse.Result: Codable {
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case identifier = "trackId"
|
||||
case name = "trackName"
|
||||
case bundleIdentifier = "bundleId"
|
||||
case version
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
//
|
||||
// main.swift
|
||||
// IPATool
|
||||
//
|
||||
// Created by Majd Alfhaily on 22.05.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
IPATool.main()
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func authCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "auth",
|
||||
Short: "Authenticate with the App Store",
|
||||
}
|
||||
|
||||
cmd.AddCommand(loginCmd())
|
||||
cmd.AddCommand(infoCmd())
|
||||
cmd.AddCommand(revokeCmd())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func loginCmd() *cobra.Command {
|
||||
var email, password, authCode string
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "login",
|
||||
Short: "Login to the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
interactive := cmd.Context().Value(interactiveKey).(bool)
|
||||
|
||||
if email == "" && !interactive {
|
||||
return errors.New("an Apple ID is required when not running in interactive mode; use the \"--email\" flag")
|
||||
}
|
||||
|
||||
if email == "" && interactive {
|
||||
value, err := readPrompt("enter Apple ID (email address or phone number): ", false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read Apple ID: %w", err)
|
||||
}
|
||||
email = value
|
||||
}
|
||||
|
||||
if password == "" && !interactive {
|
||||
return errors.New("password is required when not running in interactive mode; use the \"--password\" flag")
|
||||
}
|
||||
|
||||
if password == "" && interactive {
|
||||
value, err := readPrompt("enter password: ", true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read password: %w", err)
|
||||
}
|
||||
password = value
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().Msg("preparing authentication; the first login may take a few minutes")
|
||||
|
||||
var lastErr error
|
||||
|
||||
// nolint:wrapcheck
|
||||
return retry.Do(func() error {
|
||||
if errors.Is(lastErr, appstore.ErrAuthCodeRequired) && interactive {
|
||||
var err error
|
||||
authCode, err = readPrompt("enter 2FA code: ", false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read auth code: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies.Logger.Verbose().
|
||||
Str("email", email).
|
||||
Bool("authCodeProvided", authCode != "").
|
||||
Msg("logging in")
|
||||
|
||||
output, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: email,
|
||||
Password: password,
|
||||
AuthCode: authCode,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, appstore.ErrAuthCodeRequired) && !interactive {
|
||||
dependencies.Logger.Log().Msg("2FA code is required; run the command again and supply a code using the `--auth-code` flag")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("name", output.Account.Name).
|
||||
Str("email", output.Account.Email).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrAuthCodeRequired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&email, "email", "e", "", "Apple ID email address or phone number (required)")
|
||||
cmd.Flags().StringVarP(&password, "password", "p", "", "password for the Apple ID (required)")
|
||||
cmd.Flags().StringVar(&authCode, "auth-code", "", "2FA code for the Apple ID")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
// nolint:wrapcheck
|
||||
func infoCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "info",
|
||||
Short: "Show current account info",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
output, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("name", output.Account.Name).
|
||||
Str("email", output.Account.Email).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// nolint:wrapcheck
|
||||
func revokeCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "revoke",
|
||||
Short: "Revoke your App Store credentials",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
err := dependencies.AppStore.Revoke()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().Bool("success", true).Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Login command", func() {
|
||||
var store *fakeLoginAppStore
|
||||
|
||||
BeforeEach(func() {
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
store = &fakeLoginAppStore{}
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
})
|
||||
|
||||
DescribeTable("requires credentials in non-interactive mode", func(args []string, message string) {
|
||||
cmd := loginCmd()
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
cmd.SetArgs(args)
|
||||
|
||||
Expect(cmd.Execute()).To(MatchError(message))
|
||||
Expect(store.loginCalls).To(BeZero())
|
||||
},
|
||||
Entry("missing Apple ID", []string{"--password", "secret"}, "an Apple ID is required when not running in interactive mode; use the \"--email\" flag"),
|
||||
Entry("missing password", []string{"--email", "user@example.com"}, "password is required when not running in interactive mode; use the \"--password\" flag"),
|
||||
)
|
||||
|
||||
DescribeTable("uses supplied credentials", func(interactive bool, appleID string) {
|
||||
cmd := loginCmd()
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, interactive))
|
||||
cmd.SetArgs([]string{"--email", appleID, "--password", "secret"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.loginCalls).To(Equal(1))
|
||||
Expect(store.input).To(Equal(appstore.LoginInput{Email: appleID, Password: "secret"}))
|
||||
},
|
||||
Entry("interactive email", true, "user@example.com"),
|
||||
Entry("non-interactive email", false, "user@example.com"),
|
||||
Entry("interactive Chinese phone number", true, "+8613912345678"),
|
||||
Entry("non-interactive Chinese phone number", false, "+8613912345678"),
|
||||
Entry("interactive Indian phone number", true, "9123456789"),
|
||||
Entry("non-interactive Indian phone number", false, "9123456789"),
|
||||
)
|
||||
|
||||
DescribeTable("prompts for an Apple ID", func(input, appleID, message string) {
|
||||
dir := GinkgoT().TempDir()
|
||||
inputPath := filepath.Join(dir, "stdin")
|
||||
Expect(os.WriteFile(inputPath, []byte(input), 0o600)).To(Succeed())
|
||||
stdin, err := os.Open(inputPath)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(stdin.Close)
|
||||
stderr, err := os.Create(filepath.Join(dir, "stderr"))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(stderr.Close)
|
||||
|
||||
previousStdin, previousStderr := os.Stdin, os.Stderr
|
||||
os.Stdin, os.Stderr = stdin, stderr
|
||||
DeferCleanup(func() { os.Stdin, os.Stderr = previousStdin, previousStderr })
|
||||
|
||||
cmd := loginCmd()
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, true))
|
||||
cmd.SetArgs([]string{"--password", "secret"})
|
||||
cmd.SilenceErrors = true
|
||||
cmd.SilenceUsage = true
|
||||
|
||||
err = cmd.Execute()
|
||||
if message == "" {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(store.loginCalls).To(Equal(1))
|
||||
Expect(store.input).To(Equal(appstore.LoginInput{Email: appleID, Password: "secret"}))
|
||||
} else {
|
||||
Expect(err).To(MatchError(message))
|
||||
Expect(store.loginCalls).To(BeZero())
|
||||
}
|
||||
|
||||
prompt, err := os.ReadFile(stderr.Name())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(prompt)).To(Equal("enter Apple ID (email address or phone number): "))
|
||||
},
|
||||
Entry("reads email without requiring a terminal", "user@example.com\n", "user@example.com", ""),
|
||||
Entry("reads a phone number without requiring a terminal", "+91 91234-56789\n", "+91 91234-56789", ""),
|
||||
Entry("reports input errors", "", "", "failed to read Apple ID: failed to read input: EOF"),
|
||||
)
|
||||
})
|
||||
|
||||
type fakeLoginAppStore struct {
|
||||
appstore.AppStore
|
||||
input appstore.LoginInput
|
||||
loginCalls int
|
||||
}
|
||||
|
||||
func (f *fakeLoginAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
f.input = input
|
||||
f.loginCalls++
|
||||
|
||||
return appstore.LoginOutput{}, nil
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestCmd(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Command Suite")
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
cookiejar "github.com/juju/persistent-cookiejar"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
"github.com/majd/ipatool/v2/pkg/util"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var dependencies = Dependencies{}
|
||||
var keychainPassphrase string
|
||||
|
||||
type Dependencies struct {
|
||||
Logger log.Logger
|
||||
OS operatingsystem.OperatingSystem
|
||||
Machine machine.Machine
|
||||
CookieJar http.CookieJar
|
||||
Keychain keychain.Keychain
|
||||
AppStore appstore.AppStore
|
||||
}
|
||||
|
||||
// newLogger returns a new logger instance.
|
||||
func newLogger(format OutputFormat, verbose bool) log.Logger {
|
||||
var writer io.Writer
|
||||
|
||||
switch format {
|
||||
case OutputFormatJSON:
|
||||
writer = zerolog.SyncWriter(os.Stdout)
|
||||
case OutputFormatText:
|
||||
writer = log.NewWriter()
|
||||
}
|
||||
|
||||
return log.NewLogger(log.Args{
|
||||
Verbose: verbose,
|
||||
Writer: writer,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// newCookieJar returns a new cookie jar instance.
|
||||
func newCookieJar(stateDirectory string) http.CookieJar {
|
||||
return util.Must(cookiejar.New(&cookiejar.Options{
|
||||
Filename: filepath.Join(stateDirectory, CookieJarFileName),
|
||||
}))
|
||||
}
|
||||
|
||||
// newKeychain returns a new keychain instance.
|
||||
func newKeychain(stateDirectory string, interactive bool) keychain.Keychain {
|
||||
ring := util.Must(openKeyring(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{
|
||||
keyring.KeychainBackend,
|
||||
keyring.SecretServiceBackend,
|
||||
keyring.FileBackend,
|
||||
},
|
||||
ServiceName: KeychainServiceName,
|
||||
KeychainTrustApplication: true,
|
||||
FileDir: stateDirectory,
|
||||
FilePasswordFunc: func(s string) (string, error) {
|
||||
if keychainPassphrase == "" && !interactive {
|
||||
return "", errors.New("keychain passphrase is required when not running in interactive mode; use the \"--keychain-passphrase\" flag")
|
||||
}
|
||||
|
||||
if keychainPassphrase != "" {
|
||||
return keychainPassphrase, nil
|
||||
}
|
||||
|
||||
path := strings.Split(s, " unlock ")[1]
|
||||
password, err := readPrompt(fmt.Sprintf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path), true)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read password: %w", err)
|
||||
}
|
||||
|
||||
return password, nil
|
||||
},
|
||||
}))
|
||||
|
||||
return keychain.New(keychain.Args{
|
||||
Keyring: ring,
|
||||
Label: KeychainServiceName,
|
||||
})
|
||||
}
|
||||
|
||||
// initWithCommand initializes the dependencies of the command.
|
||||
func initWithCommand(cmd *cobra.Command) {
|
||||
verbose := cmd.Flag("verbose").Value.String() == "true"
|
||||
interactive, _ := cmd.Context().Value(interactiveKey).(bool)
|
||||
format := util.Must(OutputFormatFromString(cmd.Flag("format").Value.String()))
|
||||
|
||||
dependencies.Logger = newLogger(format, verbose)
|
||||
if cmd.Name() == "mcp" {
|
||||
dependencies.Logger = log.NewLogger(log.Args{Verbose: verbose, Writer: zerolog.SyncWriter(os.Stderr)})
|
||||
}
|
||||
|
||||
dependencies.OS = operatingsystem.New()
|
||||
dependencies.Machine = machine.New(machine.Args{OS: dependencies.OS})
|
||||
stateDirectory := util.Must(prepareStateDirectory(dependencies.OS, dependencies.Machine.HomeDirectory()))
|
||||
dependencies.CookieJar = newCookieJar(stateDirectory)
|
||||
dependencies.Keychain = newKeychain(stateDirectory, interactive)
|
||||
dependencies.AppStore = appstore.NewAppStore(appstore.Args{
|
||||
CookieJar: dependencies.CookieJar,
|
||||
OperatingSystem: dependencies.OS,
|
||||
Keychain: dependencies.Keychain,
|
||||
Machine: dependencies.Machine,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package cmd
|
||||
|
||||
const (
|
||||
ConfigDirectoryName = ".ipatool"
|
||||
CookieJarFileName = "cookies"
|
||||
KeychainServiceName = "ipatool-auth.service"
|
||||
)
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func downloadCmd() *cobra.Command {
|
||||
return downloadCmdWithAppStore(func() appstore.AppStore { return dependencies.AppStore })
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func downloadCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
|
||||
var (
|
||||
acquireLicense bool
|
||||
outputPath string
|
||||
appID int64
|
||||
bundleID string
|
||||
externalVersionID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "download",
|
||||
Short: "Download iOS, iPadOS, tvOS, watchOS, visionOS, and macOS app packages from the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
store := appStore()
|
||||
infoResult, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc := infoResult.Account
|
||||
var lastErr error
|
||||
purchaseRequired := false
|
||||
purchased := false
|
||||
|
||||
return retry.Do(func() error {
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := store.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID, BundleID: bundleID}
|
||||
|
||||
if bundleID != "" {
|
||||
lookupResult, err := store.Lookup(appstore.LookupInput{
|
||||
Account: acc,
|
||||
BundleID: bundleID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil && (appID == 0 || !errors.Is(err, appstore.ErrAppNotFound)) {
|
||||
return err
|
||||
}
|
||||
|
||||
// Delisted apps may still be downloadable by their numeric ID.
|
||||
if err == nil {
|
||||
app = lookupResult.App
|
||||
}
|
||||
}
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrLicenseRequired) {
|
||||
purchaseRequired = true
|
||||
}
|
||||
|
||||
if purchaseRequired {
|
||||
err := store.Purchase(appstore.PurchaseInput{
|
||||
Account: acc,
|
||||
App: app,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return err
|
||||
}
|
||||
|
||||
// Purchasing may persist a server-corrected storefront.
|
||||
info, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = info.Account
|
||||
purchaseRequired = false
|
||||
purchased = true
|
||||
dependencies.Logger.Verbose().
|
||||
Bool("success", true).
|
||||
Msg("purchase")
|
||||
}
|
||||
|
||||
interactive, _ := cmd.Context().Value(interactiveKey).(bool)
|
||||
var progress *progressbar.ProgressBar
|
||||
if interactive {
|
||||
progress = progressbar.NewOptions64(1,
|
||||
progressbar.OptionSetDescription("downloading"),
|
||||
progressbar.OptionSetWriter(os.Stdout),
|
||||
progressbar.OptionShowBytes(true),
|
||||
progressbar.OptionSetWidth(20),
|
||||
progressbar.OptionFullWidth(),
|
||||
progressbar.OptionThrottle(65*time.Millisecond),
|
||||
progressbar.OptionShowCount(),
|
||||
progressbar.OptionClearOnFinish(),
|
||||
progressbar.OptionSpinnerType(14),
|
||||
progressbar.OptionSetRenderBlankState(true),
|
||||
progressbar.OptionSetElapsedTime(false),
|
||||
progressbar.OptionSetPredictTime(false),
|
||||
)
|
||||
}
|
||||
|
||||
out, err := store.Download(appstore.DownloadInput{
|
||||
Context: cmd.Context(),
|
||||
Account: acc,
|
||||
App: app,
|
||||
OutputPath: outputPath,
|
||||
Progress: progress,
|
||||
ExternalVersionID: externalVersionID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := replicateDownloadSinf(store, platform, out); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("output", out.DestinationPath).
|
||||
Bool("purchased", purchased).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(3),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
if errors.Is(err, appstore.ErrPasswordTokenExpired) {
|
||||
return true
|
||||
}
|
||||
|
||||
if errors.Is(err, appstore.ErrLicenseRequired) && acquireLicense {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID when found)")
|
||||
cmd.Flags().StringVarP(&outputPath, "output", "o", "", "The destination path of the downloaded app package")
|
||||
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target app (defaults to latest version when not specified)")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
cmd.Flags().BoolVar(&acquireLicense, "purchase", false, "Obtain a license for the app if needed")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
type sinfReplicator interface {
|
||||
ReplicateSinf(input appstore.ReplicateSinfInput) error
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func replicateDownloadSinf(store sinfReplicator, platform appstore.Platform, out appstore.DownloadOutput) error {
|
||||
if platform == appstore.PlatformMacOS && len(out.Sinfs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return store.ReplicateSinf(appstore.ReplicateSinfInput{Sinfs: out.Sinfs, PackagePath: out.DestinationPath})
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Download command", func() {
|
||||
Describe("app resolution", func() {
|
||||
var store *fakeDownloadAppStore
|
||||
|
||||
BeforeEach(func() {
|
||||
store = &fakeDownloadAppStore{account: appstore.Account{StoreFront: "143441"}}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
})
|
||||
|
||||
execute := func(args ...string) error {
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs(args)
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
return cmd.Execute()
|
||||
}
|
||||
|
||||
It("uses the app ID when the bundle is absent from the catalog", func() {
|
||||
store.lookupError = fmt.Errorf("lookup: %w", appstore.ErrAppNotFound)
|
||||
Expect(execute("-i", "42", "-b", "com.example.delisted", "--platform", "appletv")).To(Succeed())
|
||||
Expect(store.lookupInputs).To(Equal([]appstore.LookupInput{{
|
||||
Account: appstore.Account{StoreFront: "143441"},
|
||||
BundleID: "com.example.delisted",
|
||||
Platform: appstore.PlatformAppleTV,
|
||||
}}))
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.delisted"}))
|
||||
Expect(store.downloadInputs[0].Platform).To(Equal(appstore.PlatformAppleTV))
|
||||
})
|
||||
|
||||
It("preserves bundle identifier precedence when lookup succeeds", func() {
|
||||
store.lookupOutput.App = appstore.App{ID: 43, BundleID: "com.example.listed"}
|
||||
Expect(execute("-i", "42", "-b", "com.example.listed")).To(Succeed())
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(store.lookupOutput.App))
|
||||
})
|
||||
|
||||
It("resolves a bundle identifier without an app ID", func() {
|
||||
store.lookupOutput.App = appstore.App{ID: 43, BundleID: "com.example.listed"}
|
||||
Expect(execute("-b", "com.example.listed")).To(Succeed())
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(store.lookupOutput.App))
|
||||
})
|
||||
|
||||
It("does not look up the bundle for an explicit app ID and version", func() {
|
||||
Expect(execute("-i", "42", "--platform", "appletv", "--external-version-id", "123456")).To(Succeed())
|
||||
Expect(store.lookupInputs).To(BeEmpty())
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(appstore.App{ID: 42}))
|
||||
Expect(store.downloadInputs[0].ExternalVersionID).To(Equal("123456"))
|
||||
})
|
||||
|
||||
DescribeTable("preserves lookup errors", func(args []string, lookupError error) {
|
||||
store.lookupError = lookupError
|
||||
Expect(execute(args...)).To(MatchError(lookupError))
|
||||
Expect(store.downloadInputs).To(BeEmpty())
|
||||
},
|
||||
Entry("missing bundle without an app ID", []string{"-b", "com.example.delisted"}, appstore.ErrAppNotFound),
|
||||
Entry("request failure with an app ID", []string{"-i", "42", "-b", "com.example.app"}, errors.New("request failed")),
|
||||
)
|
||||
})
|
||||
|
||||
It("exposes macOS in platform help", func() {
|
||||
cmd := downloadCmd()
|
||||
Expect(cmd.Flag("platform").Usage).To(ContainSubstring("macos"))
|
||||
})
|
||||
|
||||
It("skips sinf replication for macOS packages", func() {
|
||||
replicator := &fakeSinfReplicator{}
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformMacOS, appstore.DownloadOutput{
|
||||
DestinationPath: "app.pkg",
|
||||
})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(replicator.called).To(BeFalse())
|
||||
})
|
||||
|
||||
It("replicates sinf for mobile packages downloaded for macOS", func() {
|
||||
replicator := &fakeSinfReplicator{}
|
||||
out := appstore.DownloadOutput{
|
||||
DestinationPath: "app.ipa",
|
||||
Sinfs: []appstore.Sinf{{Data: []byte("sinf")}},
|
||||
}
|
||||
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformMacOS, out)
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(replicator.called).To(BeTrue())
|
||||
Expect(replicator.input).To(Equal(appstore.ReplicateSinfInput{
|
||||
PackagePath: out.DestinationPath,
|
||||
Sinfs: out.Sinfs,
|
||||
}))
|
||||
})
|
||||
|
||||
It("replicates sinf for non-macOS packages", func() {
|
||||
replicator := &fakeSinfReplicator{}
|
||||
out := appstore.DownloadOutput{
|
||||
DestinationPath: "app.ipa",
|
||||
Sinfs: []appstore.Sinf{{Data: []byte("sinf")}},
|
||||
}
|
||||
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformIPhone, out)
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(replicator.called).To(BeTrue())
|
||||
Expect(replicator.input).To(Equal(appstore.ReplicateSinfInput{
|
||||
PackagePath: out.DestinationPath,
|
||||
Sinfs: out.Sinfs,
|
||||
}))
|
||||
})
|
||||
|
||||
It("returns sinf replication errors for non-macOS packages", func() {
|
||||
replicator := &fakeSinfReplicator{err: errors.New("replication failed")}
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformIPhone, appstore.DownloadOutput{})
|
||||
Expect(err).To(MatchError("replication failed"))
|
||||
})
|
||||
|
||||
DescribeTable("preserves the platform when automatic purchase retries the download", func(platform appstore.Platform) {
|
||||
store := &fakeDownloadAppStore{downloadErrors: []error{appstore.ErrLicenseRequired, nil}}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--app-id", "42", "--platform", string(platform), "--purchase"})
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(2))
|
||||
Expect(store.purchaseInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs[0].Platform).To(Equal(platform))
|
||||
Expect(store.purchaseInputs[0].App).To(Equal(appstore.App{ID: 42}))
|
||||
Expect(store.downloadInputs).To(HaveLen(2))
|
||||
Expect(store.downloadInputs[0].Platform).To(Equal(platform))
|
||||
Expect(store.downloadInputs[1].Platform).To(Equal(platform))
|
||||
},
|
||||
Entry("macOS", appstore.PlatformMacOS),
|
||||
Entry("watchOS", appstore.PlatformWatchOS),
|
||||
)
|
||||
|
||||
It("retains the pending automatic purchase after refreshing authentication", func() {
|
||||
store := &fakeDownloadAppStore{
|
||||
downloadErrors: []error{appstore.ErrLicenseRequired, nil},
|
||||
purchaseErrors: []error{appstore.ErrPasswordTokenExpired, nil},
|
||||
}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--app-id", "42", "--platform", "macos", "--purchase"})
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(2))
|
||||
Expect(store.loginInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs).To(HaveLen(2))
|
||||
Expect(store.purchaseInputs[0].Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.purchaseInputs[1].Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.downloadInputs).To(HaveLen(2))
|
||||
})
|
||||
|
||||
DescribeTable("reuses the account throughout download retries", func(downloadErrors []error, purchaseCount int) {
|
||||
account := appstore.Account{
|
||||
Email: "user@example.com",
|
||||
Password: "password",
|
||||
PasswordToken: "expired-token",
|
||||
StoreFront: "143441",
|
||||
}
|
||||
refreshedAccount := account
|
||||
refreshedAccount.PasswordToken = "refreshed-token"
|
||||
store := &fakeDownloadAppStore{
|
||||
account: account,
|
||||
loginAccount: refreshedAccount,
|
||||
downloadErrors: downloadErrors,
|
||||
}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--bundle-identifier", "com.example.app", "--purchase"})
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(1 + purchaseCount))
|
||||
Expect(store.loginInputs).To(Equal([]appstore.LoginInput{{Email: account.Email, Password: account.Password}}))
|
||||
Expect(store.lookupInputs).To(HaveLen(len(downloadErrors)))
|
||||
Expect(store.lookupInputs[0].Account).To(Equal(account))
|
||||
Expect(store.downloadInputs).To(HaveLen(len(downloadErrors)))
|
||||
Expect(store.downloadInputs[0].Account).To(Equal(account))
|
||||
|
||||
for _, input := range store.lookupInputs[1:] {
|
||||
Expect(input.Account).To(Equal(refreshedAccount))
|
||||
}
|
||||
|
||||
for _, input := range store.downloadInputs[1:] {
|
||||
Expect(input.Account).To(Equal(refreshedAccount))
|
||||
}
|
||||
|
||||
Expect(store.purchaseInputs).To(HaveLen(purchaseCount))
|
||||
|
||||
for _, input := range store.purchaseInputs {
|
||||
Expect(input.Account).To(Equal(refreshedAccount))
|
||||
}
|
||||
},
|
||||
Entry("refreshes an expired token", []error{appstore.ErrPasswordTokenExpired, nil}, 0),
|
||||
Entry("retains the refreshed token for a subsequent purchase", []error{appstore.ErrPasswordTokenExpired, appstore.ErrLicenseRequired, nil}, 1),
|
||||
)
|
||||
|
||||
DescribeTable("downloads using the storefront persisted during purchase", func(refresh bool) {
|
||||
original := appstore.Account{Email: "user@example.com", Password: "password", PasswordToken: "old-token", StoreFront: "143441-1,34"}
|
||||
corrected := original
|
||||
corrected.StoreFront = "143462-1,34"
|
||||
store := &fakeDownloadAppStore{
|
||||
account: original, downloadErrors: []error{appstore.ErrLicenseRequired, nil},
|
||||
purchaseStorefront: corrected.StoreFront,
|
||||
}
|
||||
if refresh {
|
||||
corrected.PasswordToken = "new-token"
|
||||
store.loginAccount = corrected
|
||||
store.purchaseErrors = []error{appstore.ErrPasswordTokenExpired, nil}
|
||||
}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
command := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
command.SetArgs([]string{"--app-id", "42", "--purchase"})
|
||||
command.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
Expect(command.Execute()).To(Succeed())
|
||||
Expect(store.downloadInputs).To(HaveLen(2))
|
||||
Expect(store.downloadInputs[0].Account).To(Equal(original))
|
||||
Expect(store.downloadInputs[1].Account).To(Equal(corrected))
|
||||
if refresh {
|
||||
Expect(store.loginInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs).To(HaveLen(2))
|
||||
Expect(store.purchaseInputs[1].Account).To(Equal(corrected))
|
||||
} else {
|
||||
Expect(store.loginInputs).To(BeEmpty())
|
||||
}
|
||||
}, Entry("immediate success", false), Entry("token refresh after correction", true))
|
||||
|
||||
It("returns an account read error before attempting a download", func() {
|
||||
store := &fakeDownloadAppStore{accountInfoError: errors.New("account unavailable")}
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--app-id", "42"})
|
||||
|
||||
Expect(cmd.Execute()).To(MatchError(store.accountInfoError))
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.loginInputs).To(BeEmpty())
|
||||
Expect(store.lookupInputs).To(BeEmpty())
|
||||
Expect(store.purchaseInputs).To(BeEmpty())
|
||||
Expect(store.downloadInputs).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
||||
type fakeSinfReplicator struct {
|
||||
called bool
|
||||
input appstore.ReplicateSinfInput
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeSinfReplicator) ReplicateSinf(input appstore.ReplicateSinfInput) error {
|
||||
f.called = true
|
||||
f.input = input
|
||||
|
||||
return f.err
|
||||
}
|
||||
|
||||
type fakeDownloadAppStore struct {
|
||||
account appstore.Account
|
||||
accountInfoCalls int
|
||||
accountInfoError error
|
||||
downloadErrors []error
|
||||
downloadInputs []appstore.DownloadInput
|
||||
loginAccount appstore.Account
|
||||
loginInputs []appstore.LoginInput
|
||||
lookupInputs []appstore.LookupInput
|
||||
lookupOutput appstore.LookupOutput
|
||||
lookupError error
|
||||
purchaseErrors []error
|
||||
purchaseInputs []appstore.PurchaseInput
|
||||
purchaseStorefront string
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
f.loginInputs = append(f.loginInputs, input)
|
||||
f.account = f.loginAccount
|
||||
|
||||
return appstore.LoginOutput{Account: f.loginAccount}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
f.accountInfoCalls++
|
||||
|
||||
return appstore.AccountInfoOutput{Account: f.account}, f.accountInfoError
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) Revoke() error { return nil }
|
||||
|
||||
func (f *fakeDownloadAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
f.lookupInputs = append(f.lookupInputs, input)
|
||||
|
||||
return f.lookupOutput, f.lookupError
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Purchase(input appstore.PurchaseInput) error {
|
||||
f.purchaseInputs = append(f.purchaseInputs, input)
|
||||
if f.purchaseStorefront != "" {
|
||||
f.account.StoreFront = f.purchaseStorefront
|
||||
}
|
||||
|
||||
index := len(f.purchaseInputs) - 1
|
||||
|
||||
if index < len(f.purchaseErrors) && f.purchaseErrors[index] != nil {
|
||||
return f.purchaseErrors[index]
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
f.downloadInputs = append(f.downloadInputs, input)
|
||||
index := len(f.downloadInputs) - 1
|
||||
|
||||
if index < len(f.downloadErrors) && f.downloadErrors[index] != nil {
|
||||
return appstore.DownloadOutput{}, f.downloadErrors[index]
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "app.pkg"}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error { return nil }
|
||||
|
||||
func (*fakeDownloadAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) Bag(input appstore.BagInput) (appstore.BagOutput, error) {
|
||||
return appstore.BagOutput{}, nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func getVersionMetadataCmd() *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
externalVersionID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get-version-metadata",
|
||||
Short: "Retrieves the metadata for a specific version of an app",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID, Platform: platform})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.GetVersionMetadata(appstore.GetVersionMetadataInput{
|
||||
Context: cmd.Context(),
|
||||
Account: acc,
|
||||
App: app,
|
||||
VersionID: externalVersionID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("externalVersionID", externalVersionID).
|
||||
Str("displayVersion", out.DisplayVersion).
|
||||
Time("releaseDate", out.ReleaseDate).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
|
||||
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target app (required)")
|
||||
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to retrieve metadata for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
|
||||
_ = cmd.MarkFlagRequired("external-version-id")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Get Version Metadata command", func() {
|
||||
DescribeTable("passes the platform and exact version to metadata lookup", func(args []string, platform appstore.Platform, lookup bool) {
|
||||
store := &fakeVersionMetadataAppStore{}
|
||||
previous := dependencies
|
||||
DeferCleanup(func() { dependencies = previous })
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
cmd := getVersionMetadataCmd()
|
||||
cmd.SetArgs(append(args, "--external-version-id", "876660716"))
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.input.Platform).To(Equal(platform))
|
||||
Expect(store.input.VersionID).To(Equal("876660716"))
|
||||
Expect(store.input.App.ID).To(Equal(int64(42)))
|
||||
Expect(store.lookupCalled).To(Equal(lookup))
|
||||
if lookup {
|
||||
Expect(store.lookupInput.Platform).To(Equal(platform))
|
||||
}
|
||||
},
|
||||
Entry("Mac bundle", []string{"-b", "com.example.mac", "--platform", "macos"}, appstore.PlatformMacOS, true),
|
||||
Entry("Mac ID alias", []string{"-i", "42", "--platform", "mac"}, appstore.PlatformMacOS, false),
|
||||
Entry("default", []string{"-i", "42"}, appstore.Platform(""), false),
|
||||
)
|
||||
It("rejects unknown as a filter", func() {
|
||||
cmd := getVersionMetadataCmd()
|
||||
cmd.SetArgs([]string{"-i", "42", "--external-version-id", "123", "--platform", "unknown"})
|
||||
Expect(cmd.Execute()).To(MatchError(`invalid platform "unknown"`))
|
||||
})
|
||||
})
|
||||
|
||||
type fakeVersionMetadataAppStore struct {
|
||||
fakeListVersionsAppStore
|
||||
input appstore.GetVersionMetadataInput
|
||||
}
|
||||
|
||||
func (s *fakeVersionMetadataAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
s.input = input
|
||||
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !ios
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
)
|
||||
|
||||
func openKeyring(config keyring.Config) (keychain.Keyring, error) {
|
||||
return keyring.Open(config) //nolint:wrapcheck
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
gokeychain "github.com/byteness/go-keychain"
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
)
|
||||
|
||||
// iosKeyring fixes the update query in keyring v1.9.0, which includes attributes
|
||||
// that SecItemUpdate rejects on iOS (kSecMatchLimit and kSecReturnAttributes).
|
||||
type iosKeyring struct {
|
||||
keyring.Keyring
|
||||
service string
|
||||
}
|
||||
|
||||
func openKeyring(config keyring.Config) (keychain.Keyring, error) {
|
||||
ring, err := keyring.Open(config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open iOS keyring: %w", err)
|
||||
}
|
||||
|
||||
return &iosKeyring{Keyring: ring, service: config.ServiceName}, nil
|
||||
}
|
||||
|
||||
func (k *iosKeyring) Set(item keyring.Item) error {
|
||||
query := gokeychain.NewItem()
|
||||
query.SetSecClass(gokeychain.SecClassGenericPassword)
|
||||
query.SetService(k.service)
|
||||
query.SetAccount(item.Key)
|
||||
|
||||
attributes := gokeychain.NewItem()
|
||||
attributes.SetData(item.Data)
|
||||
attributes.SetLabel(item.Label)
|
||||
attributes.SetDescription(item.Description)
|
||||
|
||||
err := gokeychain.UpdateItem(query, attributes)
|
||||
if err == gokeychain.ErrorItemNotFound {
|
||||
return k.Keyring.Set(item) //nolint:wrapcheck
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("update iOS keyring item: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("iOS keyring", func() {
|
||||
It("persists and updates credentials without invalid SecItemUpdate parameters", func() {
|
||||
ring, err := openKeyring(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{keyring.KeychainBackend},
|
||||
ServiceName: fmt.Sprintf("ipatool-test-%d", time.Now().UnixNano()),
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(func() { Expect(ring.Remove("account")).To(Succeed()) })
|
||||
Expect(ring.Set(keyring.Item{Key: "account", Data: []byte("first"), Label: "ipatool"})).To(Succeed())
|
||||
Expect(ring.Set(keyring.Item{Key: "account", Data: []byte("updated"), Label: "ipatool"})).To(Succeed())
|
||||
item, err := ring.Get("account")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(item.Data).To(Equal([]byte("updated")))
|
||||
Expect(item.Label).To(Equal("ipatool"))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func ListVersionsCmd() *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "list-versions",
|
||||
Short: "List the available versions of an App Store app",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID, Platform: platform})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Context: cmd.Context(), Account: acc, App: app, Platform: platform})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Interface("externalVersionIdentifiers", out.ExternalVersionIdentifiers).
|
||||
Str("bundleID", app.BundleID).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
|
||||
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to list versions for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("List Versions command", func() {
|
||||
DescribeTable("passes the selected platform to lookup and version listing", func(args []string, expected appstore.Platform, lookup bool) {
|
||||
store := &fakeListVersionsAppStore{}
|
||||
previous := dependencies
|
||||
DeferCleanup(func() { dependencies = previous })
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
cmd := ListVersionsCmd()
|
||||
cmd.SetArgs(args)
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.input.Platform).To(Equal(expected))
|
||||
Expect(store.input.App.ID).To(Equal(int64(42)))
|
||||
Expect(store.lookupCalled).To(Equal(lookup))
|
||||
if lookup {
|
||||
Expect(store.lookupInput.Platform).To(Equal(expected))
|
||||
}
|
||||
},
|
||||
Entry("Mac bundle ID", []string{"-b", "com.example.mac", "--platform", "macos"}, appstore.PlatformMacOS, true),
|
||||
Entry("Mac app ID alias", []string{"-i", "42", "--platform", "mac"}, appstore.PlatformMacOS, false),
|
||||
Entry("default platform", []string{"-i", "42"}, appstore.Platform(""), false),
|
||||
Entry("iOS alias", []string{"-i", "42", "--platform", "ios"}, appstore.PlatformIPhone, false),
|
||||
)
|
||||
|
||||
It("rejects unknown as a platform before accessing the account", func() {
|
||||
cmd := ListVersionsCmd()
|
||||
cmd.SetArgs([]string{"-i", "42", "--platform", "unknown"})
|
||||
Expect(cmd.Execute()).To(MatchError(`invalid platform "unknown"`))
|
||||
})
|
||||
})
|
||||
|
||||
type fakeListVersionsAppStore struct {
|
||||
appstore.AppStore
|
||||
input appstore.ListVersionsInput
|
||||
lookupInput appstore.LookupInput
|
||||
lookupCalled bool
|
||||
}
|
||||
|
||||
func (*fakeListVersionsAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, nil
|
||||
}
|
||||
func (s *fakeListVersionsAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
s.lookupCalled = true
|
||||
s.lookupInput = input
|
||||
|
||||
return appstore.LookupOutput{App: appstore.App{ID: 42, BundleID: input.BundleID}}, nil
|
||||
}
|
||||
func (s *fakeListVersionsAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
s.input = input
|
||||
|
||||
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"123"}}, nil
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func mcpCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "mcp",
|
||||
Short: "Serve App Store tools over MCP using stdio",
|
||||
Long: "Serve App Store tools over the Model Context Protocol using stdio.\n" +
|
||||
"Authenticate with 'ipatool auth login' before using the tools.\n" +
|
||||
"Runs non-interactively; authentication tools are not exposed.",
|
||||
Args: cobra.NoArgs,
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
cmd.SetContext(context.WithValue(cmd.Context(), interactiveKey, false))
|
||||
initWithCommand(cmd)
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt)
|
||||
defer stop()
|
||||
|
||||
server := newMCPServer(dependencies.AppStore)
|
||||
if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil {
|
||||
return fmt.Errorf("MCP server failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type mcpTools struct {
|
||||
store appstore.AppStore
|
||||
gate chan struct{}
|
||||
}
|
||||
|
||||
func newMCPServer(store appstore.AppStore) *mcp.Server {
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "ipatool", Version: version}, &mcp.ServerOptions{
|
||||
Instructions: "Use the existing ipatool account. If authentication is required, ask the user to run ipatool auth login outside MCP. Purchases support free apps only.",
|
||||
})
|
||||
tools := &mcpTools{store: store, gate: make(chan struct{}, 1)}
|
||||
addMCPTool(server, tools, "search_apps", "Search for apps on the App Store.", true, tools.search)
|
||||
addMCPTool(server, tools, "download_app", "Download an app package to the local filesystem. Optionally acquire a free license if purchase is true.", false, tools.download)
|
||||
addMCPTool(server, tools, "list_app_versions", "List available external version identifiers for an app.", true, tools.listVersions)
|
||||
addMCPTool(server, tools, "get_version_metadata", "Retrieve the display version and release date for a specific external version identifier of an app.", true, tools.getVersionMetadata)
|
||||
addMCPTool(server, tools, "list_purchases", "List apps owned by the authenticated account, with pagination.", true, tools.listPurchases)
|
||||
addMCPTool(server, tools, "purchase_app", "Obtain a license for a free app. Paid apps are not supported.", false, tools.purchase)
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
func addMCPTool[In, Out any](server *mcp.Server, tools *mcpTools, name, description string, readOnly bool, handler func(context.Context, In) (Out, error)) {
|
||||
mcp.AddTool(server, &mcp.Tool{
|
||||
Name: name,
|
||||
Description: description,
|
||||
Annotations: &mcp.ToolAnnotations{ReadOnlyHint: readOnly},
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, input In) (*mcp.CallToolResult, Out, error) {
|
||||
var zero Out
|
||||
|
||||
// The App Store client shares account state and caches across calls.
|
||||
select {
|
||||
case tools.gate <- struct{}{}:
|
||||
defer func() { <-tools.gate }()
|
||||
case <-ctx.Done():
|
||||
return nil, zero, fmt.Errorf("tool call canceled: %w", ctx.Err())
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, zero, fmt.Errorf("tool call canceled: %w", err)
|
||||
}
|
||||
|
||||
output, err := handler(ctx, input)
|
||||
if err != nil {
|
||||
return nil, zero, fmt.Errorf("%s failed: %w", name, err)
|
||||
}
|
||||
|
||||
return nil, output, nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
)
|
||||
|
||||
// mcpApp keeps every metadata field in the MCP response, including zero values.
|
||||
// The App Store's JSON representation is also used by other callers, so its
|
||||
// omission rules are left unchanged.
|
||||
type mcpApp struct {
|
||||
ID int64 `json:"trackId"`
|
||||
BundleID string `json:"bundleId"`
|
||||
Name string `json:"trackName"`
|
||||
Version string `json:"version"`
|
||||
Price float64 `json:"price"`
|
||||
PurchaseDate *time.Time `json:"purchaseDate"`
|
||||
Platforms []appstore.Platform `json:"platforms"`
|
||||
}
|
||||
|
||||
func newMCPApp(app appstore.App) mcpApp {
|
||||
output := mcpApp{
|
||||
ID: app.ID, BundleID: app.BundleID, Name: app.Name, Version: app.Version, Price: app.Price,
|
||||
Platforms: append([]appstore.Platform{}, app.Platforms...),
|
||||
}
|
||||
if !app.PurchaseDate.IsZero() {
|
||||
output.PurchaseDate = &app.PurchaseDate
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
// completeApp supplements sparse metadata without making catalog availability a
|
||||
// prerequisite for operating on owned or delisted apps.
|
||||
func (t *mcpTools) completeApp(acc appstore.Account, app appstore.App, platform appstore.Platform) appstore.App {
|
||||
knownPlatforms := len(app.Platforms) > 0 && app.Platforms[0] != appstore.PlatformUnknown
|
||||
if app.ID <= 0 || (app.BundleID != "" && app.Name != "" && app.Version != "" && knownPlatforms) {
|
||||
return app
|
||||
}
|
||||
|
||||
// Purchase history can contain several platforms when no filter was supplied.
|
||||
// Use an app's known platform for its catalog lookup in that case.
|
||||
if platform == "" && len(app.Platforms) > 0 && app.Platforms[0] != appstore.PlatformUnknown {
|
||||
platform = app.Platforms[0]
|
||||
}
|
||||
|
||||
out, err := t.store.Lookup(appstore.LookupInput{Account: acc, AppID: app.ID, Platform: platform})
|
||||
if err != nil || out.App.ID != app.ID {
|
||||
return app
|
||||
}
|
||||
|
||||
if app.BundleID == "" {
|
||||
app.BundleID = out.App.BundleID
|
||||
}
|
||||
|
||||
if app.Name == "" {
|
||||
app.Name = out.App.Name
|
||||
}
|
||||
|
||||
if app.Version == "" {
|
||||
app.Version = out.App.Version
|
||||
}
|
||||
|
||||
if len(out.App.Platforms) > 0 && (len(app.Platforms) == 0 || (len(app.Platforms) == 1 && app.Platforms[0] == appstore.PlatformUnknown)) {
|
||||
app.Platforms = out.App.Platforms
|
||||
}
|
||||
|
||||
if app.Price == 0 {
|
||||
app.Price = out.App.Price
|
||||
}
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
func (t *mcpTools) appResults(acc appstore.Account, apps []appstore.App, platform appstore.Platform) []mcpApp {
|
||||
results := make([]mcpApp, 0, len(apps))
|
||||
for _, app := range apps {
|
||||
results = append(results, newMCPApp(t.completeApp(acc, app, platform)))
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
type mcpAppParameters struct {
|
||||
AppID int64 `json:"app_id"`
|
||||
BundleIdentifier string `json:"bundle_identifier"`
|
||||
Platform appstore.Platform `json:"platform"`
|
||||
}
|
||||
|
||||
func appParameters(app appstore.App, platform appstore.Platform) mcpAppParameters {
|
||||
return mcpAppParameters{AppID: app.ID, BundleIdentifier: app.BundleID, Platform: platform}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("MCP app metadata", func() {
|
||||
DescribeTable("preserves source data when catalog metadata cannot be used", func(catalog appstore.App, lookupErr error) {
|
||||
original := appstore.App{ID: 123, Name: "Original name", Price: 2.99, Platforms: []appstore.Platform{appstore.PlatformUnknown}}
|
||||
store := &fakeMCPAppStore{lookup: func(appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return appstore.LookupOutput{App: catalog}, lookupErr
|
||||
}}
|
||||
tools := &mcpTools{store: store}
|
||||
|
||||
Expect(tools.completeApp(appstore.Account{}, original, "")).To(Equal(original))
|
||||
},
|
||||
Entry("delisted app", appstore.App{}, appstore.ErrAppNotFound),
|
||||
Entry("network failure", appstore.App{}, errors.New("network failure")),
|
||||
Entry("wrong app ID", appstore.App{ID: 999, BundleID: "wrong.bundle"}, nil),
|
||||
Entry("missing catalog values", appstore.App{ID: 123}, nil),
|
||||
)
|
||||
|
||||
It("avoids catalog lookups when app metadata is already complete", func() {
|
||||
tools := &mcpTools{store: &fakeMCPAppStore{}}
|
||||
app := appstore.App{ID: 123, BundleID: "com.example.app", Name: "Example", Version: "1.0", Platforms: []appstore.Platform{appstore.PlatformIPhone}}
|
||||
Expect(tools.completeApp(appstore.Account{}, app, "")).To(Equal(app))
|
||||
})
|
||||
})
|
||||
+670
@@ -0,0 +1,670 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("MCP server", func() {
|
||||
var (
|
||||
ctx context.Context
|
||||
store *fakeMCPAppStore
|
||||
session *mcp.ClientSession
|
||||
account appstore.Account
|
||||
app appstore.App
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
var cancel context.CancelFunc
|
||||
|
||||
ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
|
||||
DeferCleanup(cancel)
|
||||
account = appstore.Account{Email: "private-email", Password: "private-password", PasswordToken: "private-token"}
|
||||
app = appstore.App{ID: 123, BundleID: "com.example.app", Name: "Example"}
|
||||
store = &fakeMCPAppStore{}
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{Account: account}, nil
|
||||
}
|
||||
store.lookup = func(appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return appstore.LookupOutput{}, appstore.ErrAppNotFound
|
||||
}
|
||||
clientTransport, serverTransport := mcp.NewInMemoryTransports()
|
||||
serverSession, err := newMCPServer(store).Connect(ctx, serverTransport, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(func() { Expect(serverSession.Close()).To(Succeed()) })
|
||||
session, err = mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil).Connect(ctx, clientTransport, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(func() { Expect(session.Close()).To(Succeed()) })
|
||||
})
|
||||
|
||||
call := func(name string, args map[string]any) *mcp.CallToolResult {
|
||||
result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
It("registers the mcp subcommand", func() {
|
||||
command, _, err := rootCmd().Find([]string{"mcp"})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(command.Name()).To(Equal("mcp"))
|
||||
Expect(command.Args(command, []string{"unexpected"})).NotTo(Succeed())
|
||||
})
|
||||
|
||||
It("advertises exactly six tools and their schemas without auth functions", func() {
|
||||
result, err := session.ListTools(ctx, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
names := make([]string, 0, len(result.Tools))
|
||||
for _, tool := range result.Tools {
|
||||
names = append(names, tool.Name)
|
||||
Expect(tool.InputSchema).NotTo(BeNil())
|
||||
Expect(tool.OutputSchema).NotTo(BeNil())
|
||||
Expect(tool.Annotations.ReadOnlyHint).To(Equal(tool.Name != "download_app" && tool.Name != "purchase_app"))
|
||||
}
|
||||
Expect(names).To(ConsistOf("search_apps", "download_app", "list_app_versions", "get_version_metadata", "list_purchases", "purchase_app"))
|
||||
})
|
||||
|
||||
It("searches with CLI defaults and returns structured app data without credentials", func() {
|
||||
var input appstore.SearchInput
|
||||
|
||||
store.search = func(in appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.SearchOutput{Count: 1, Results: []appstore.App{app}}, nil
|
||||
}
|
||||
result := call("search_apps", map[string]any{"term": "example"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input).To(Equal(appstore.SearchInput{Account: account, Term: "example", Limit: 5}))
|
||||
data, err := json.Marshal(result.StructuredContent)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).To(ContainSubstring("com.example.app"))
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
Expect(result.Content).To(HaveLen(1))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("term", "example"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("limit", float64(5)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", ""))
|
||||
})
|
||||
|
||||
DescribeTable("passes search platform aliases and limits to the App Store", func(value string, platform appstore.Platform) {
|
||||
var input appstore.SearchInput
|
||||
|
||||
store.search = func(in appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.SearchOutput{}, nil
|
||||
}
|
||||
Expect(call("search_apps", map[string]any{"term": "example", "platform": value, "limit": 7}).IsError).To(BeFalse())
|
||||
Expect(input.Platform).To(Equal(platform))
|
||||
Expect(input.Limit).To(Equal(int64(7)))
|
||||
},
|
||||
Entry("tvOS", "tvos", appstore.PlatformAppleTV),
|
||||
Entry("watchOS", "watch", appstore.PlatformWatchOS),
|
||||
)
|
||||
|
||||
DescribeTable("rejects invalid inputs before accessing the account", func(name string, args map[string]any) {
|
||||
accountCalls := 0
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
accountCalls++
|
||||
|
||||
return appstore.AccountInfoOutput{}, errors.New("unexpected account access")
|
||||
}
|
||||
result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
|
||||
Expect(err != nil || (result != nil && result.IsError)).To(BeTrue())
|
||||
Expect(accountCalls).To(BeZero())
|
||||
},
|
||||
Entry("missing search term", "search_apps", map[string]any{}),
|
||||
Entry("blank search term", "search_apps", map[string]any{"term": " "}),
|
||||
Entry("invalid search limit", "search_apps", map[string]any{"term": "app", "limit": 0}),
|
||||
Entry("wrong argument type", "search_apps", map[string]any{"term": 123}),
|
||||
Entry("credentials are not arguments", "search_apps", map[string]any{"term": "app", "password": "secret"}),
|
||||
Entry("invalid platform", "search_apps", map[string]any{"term": "app", "platform": "unknown"}),
|
||||
Entry("missing download app", "download_app", map[string]any{}),
|
||||
Entry("negative app ID", "purchase_app", map[string]any{"app_id": -1}),
|
||||
Entry("missing versions app", "list_app_versions", map[string]any{}),
|
||||
Entry("missing metadata app", "get_version_metadata", map[string]any{"external_version_id": "200"}),
|
||||
Entry("missing metadata version", "get_version_metadata", map[string]any{"app_id": 123}),
|
||||
Entry("empty metadata version", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": ""}),
|
||||
Entry("blank metadata version", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": " "}),
|
||||
Entry("invalid metadata version type", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": 200}),
|
||||
Entry("invalid metadata platform", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200", "platform": "unknown"}),
|
||||
Entry("invalid page", "list_purchases", map[string]any{"page": 0}),
|
||||
Entry("invalid page size", "list_purchases", map[string]any{"max_results": 101}),
|
||||
)
|
||||
|
||||
It("returns actionable account errors and keeps serving requests", func() {
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, errors.New("account not found")
|
||||
}
|
||||
result := call("list_purchases", map[string]any{})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("ipatool auth login"))
|
||||
_, err := session.ListTools(ctx, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
})
|
||||
|
||||
DescribeTable("lists purchases with pagination", func(args map[string]any, page, limit int, platform appstore.Platform) {
|
||||
var input appstore.OwnedAppsInput
|
||||
|
||||
store.ownedApps = func(in appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 11, Page: in.Page, Results: []appstore.App{app}}, nil
|
||||
}
|
||||
result := call("list_purchases", args)
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input).To(Equal(appstore.OwnedAppsInput{Account: account, Page: page, Limit: limit, Platform: platform}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("totalCount", float64(11)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("page", float64(page)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("max_results", float64(limit)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", string(platform)))
|
||||
},
|
||||
Entry("defaults", map[string]any{}, 1, 10, appstore.Platform("")),
|
||||
Entry("explicit values", map[string]any{"page": 2, "max_results": 5, "platform": "macos"}, 2, 5, appstore.PlatformMacOS),
|
||||
)
|
||||
|
||||
It("resolves bundle identifiers and lists versions", func() {
|
||||
var lookup appstore.LookupInput
|
||||
var input appstore.ListVersionsInput
|
||||
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: app}, nil
|
||||
}
|
||||
store.listVersions = func(in appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"100", "200"}, LatestExternalVersionID: "200"}, nil
|
||||
}
|
||||
result := call("list_app_versions", map[string]any{"app_id": 999, "bundle_identifier": app.BundleID, "platform": "ipados"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, BundleID: app.BundleID, Platform: appstore.PlatformIPad}))
|
||||
Expect(input.App).To(Equal(app))
|
||||
Expect(input.Context).NotTo(BeNil())
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("externalVersionIdentifiers", []any{"100", "200"}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(app.ID)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", "ipad"))
|
||||
})
|
||||
|
||||
It("resolves a bundle identifier and returns metadata for the requested version", func() {
|
||||
var lookup appstore.LookupInput
|
||||
var input appstore.GetVersionMetadataInput
|
||||
|
||||
app.Version = "2.0"
|
||||
releasedAt := time.Date(2025, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: app}, nil
|
||||
}
|
||||
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3", ReleaseDate: releasedAt}, nil
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 999, "bundle_identifier": app.BundleID, "external_version_id": "200", "platform": "ipados"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, BundleID: app.BundleID, Platform: appstore.PlatformIPad}))
|
||||
Expect(input.Context).NotTo(BeNil())
|
||||
Expect(input.Account).To(Equal(account))
|
||||
Expect(input.App).To(Equal(app))
|
||||
Expect(input.VersionID).To(Equal("200"))
|
||||
Expect(input.Platform).To(Equal(appstore.PlatformIPad))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(app.ID)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", "ipad"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("external_version_id", "200"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("displayVersion", "1.2.3"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("releaseDate", releasedAt.Format(time.RFC3339)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("success", true))
|
||||
Expect(result.StructuredContent.(map[string]any)["app"]).To(HaveKeyWithValue("version", "2.0"))
|
||||
data, err := json.Marshal(result.StructuredContent)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(MatchJSON(string(data)))
|
||||
})
|
||||
|
||||
DescribeTable("retrieves version metadata by app ID when catalog metadata is unavailable", func(platform string, expected appstore.Platform) {
|
||||
var input appstore.GetVersionMetadataInput
|
||||
|
||||
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3"}, nil
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200", "platform": platform})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input.App).To(Equal(appstore.App{ID: 123}))
|
||||
Expect(input.VersionID).To(Equal("200"))
|
||||
Expect(input.Platform).To(Equal(expected))
|
||||
},
|
||||
Entry("CLI default", "", appstore.Platform("")),
|
||||
Entry("iOS alias", "ios", appstore.PlatformIPhone),
|
||||
Entry("macOS", "macos", appstore.PlatformMacOS),
|
||||
)
|
||||
|
||||
It("returns bundle lookup failures as metadata tool errors", func() {
|
||||
result := call("get_version_metadata", map[string]any{"bundle_identifier": app.BundleID, "external_version_id": "200"})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(appstore.ErrAppNotFound.Error()))
|
||||
})
|
||||
|
||||
DescribeTable("returns metadata failures as tool errors without acquiring a license", func(metadataErr error) {
|
||||
store.getVersionMetadata = func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, appstore.NewErrorWithMetadata(metadataErr, account)
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(metadataErr.Error()))
|
||||
data, err := json.Marshal(result)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
},
|
||||
Entry("missing license", appstore.ErrLicenseRequired),
|
||||
Entry("metadata unavailable", errors.New("metadata unavailable")),
|
||||
)
|
||||
|
||||
It("refreshes an expired session when retrieving version metadata", func() {
|
||||
var login appstore.LoginInput
|
||||
var accounts []appstore.Account
|
||||
|
||||
refreshed := appstore.Account{PasswordToken: "refreshed-private-token"}
|
||||
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
accounts = append(accounts, in.Account)
|
||||
if len(accounts) == 1 {
|
||||
return appstore.GetVersionMetadataOutput{}, appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3"}, nil
|
||||
}
|
||||
store.login = func(in appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
login = in
|
||||
|
||||
return appstore.LoginOutput{Account: refreshed}, nil
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(login).To(Equal(appstore.LoginInput{Email: account.Email, Password: account.Password}))
|
||||
Expect(accounts).To(Equal([]appstore.Account{account, refreshed}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("displayVersion", "1.2.3"))
|
||||
})
|
||||
|
||||
DescribeTable("purchases a free license", func(purchaseErr error, alreadyOwned bool) {
|
||||
var input appstore.PurchaseInput
|
||||
|
||||
store.purchase = func(in appstore.PurchaseInput) error {
|
||||
input = in
|
||||
|
||||
return purchaseErr
|
||||
}
|
||||
result := call("purchase_app", map[string]any{"app_id": 123, "platform": "visionos"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input).To(Equal(appstore.PurchaseInput{Account: account, App: appstore.App{ID: 123}, Platform: appstore.PlatformVisionOS}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("alreadyOwned", alreadyOwned))
|
||||
},
|
||||
Entry("new license", nil, false),
|
||||
Entry("existing license", appstore.ErrLicenseAlreadyExists, true),
|
||||
)
|
||||
|
||||
It("downloads a selected version and finalizes the package without a progress bar", func() {
|
||||
var input appstore.DownloadInput
|
||||
var sinfInput appstore.ReplicateSinfInput
|
||||
|
||||
store.download = func(in appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(in appstore.ReplicateSinfInput) error {
|
||||
sinfInput = in
|
||||
|
||||
return nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "output": "/tmp/example.ipa", "external_version_id": "200", "platform": "ios"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input.App.ID).To(Equal(int64(123)))
|
||||
Expect(input.OutputPath).To(Equal("/tmp/example.ipa"))
|
||||
Expect(input.ExternalVersionID).To(Equal("200"))
|
||||
Expect(input.Platform).To(Equal(appstore.PlatformIPhone))
|
||||
Expect(input.Context).NotTo(BeNil())
|
||||
Expect(input.Progress).To(BeNil())
|
||||
Expect(sinfInput.PackagePath).To(Equal(input.OutputPath))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("output", input.OutputPath))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("external_version_id", "200"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("purchase", false))
|
||||
})
|
||||
|
||||
It("downloads delisted macOS apps by ID without attempting IPA finalization", func() {
|
||||
var input appstore.DownloadInput
|
||||
|
||||
store.lookup = func(appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return appstore.LookupOutput{}, appstore.ErrAppNotFound
|
||||
}
|
||||
store.download = func(in appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "bundle_identifier": app.BundleID, "platform": "macos"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input.App.ID).To(Equal(int64(123)))
|
||||
})
|
||||
|
||||
DescribeTable("only acquires a license during download when requested", func(purchase bool) {
|
||||
downloads, purchases := 0, 0
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
downloads++
|
||||
if downloads == 1 {
|
||||
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error {
|
||||
purchases++
|
||||
|
||||
return nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": purchase})
|
||||
Expect(result.IsError).To(Equal(!purchase))
|
||||
if purchase {
|
||||
Expect(purchases).To(Equal(1))
|
||||
Expect(downloads).To(Equal(2))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("purchased", true))
|
||||
} else {
|
||||
Expect(purchases).To(BeZero())
|
||||
Expect(downloads).To(Equal(1))
|
||||
}
|
||||
}, Entry("explicit opt in", true), Entry("no opt in", false))
|
||||
|
||||
DescribeTable("uses a purchase-corrected storefront for MCP downloads", func(refresh bool) {
|
||||
account.DirectoryServicesID = "123456"
|
||||
account.StoreFront = "143441-1,34"
|
||||
var downloads []appstore.Account
|
||||
purchases := 0
|
||||
expectedPurchases := 1
|
||||
if refresh {
|
||||
expectedPurchases = 2
|
||||
}
|
||||
store.download = func(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
downloads = append(downloads, input.Account)
|
||||
if purchases < expectedPurchases {
|
||||
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
|
||||
}
|
||||
store.purchase = func(input appstore.PurchaseInput) error {
|
||||
purchases++
|
||||
account.StoreFront = "143462-1,34"
|
||||
if refresh && purchases == 1 {
|
||||
return appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
store.login = func(appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
account.PasswordToken = "new-token"
|
||||
|
||||
return appstore.LoginOutput{Account: account}, nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": true})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(purchases).To(Equal(expectedPurchases))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("purchased", true))
|
||||
Expect(downloads[0].StoreFront).To(Equal("143441-1,34"))
|
||||
Expect(downloads[len(downloads)-1].StoreFront).To(Equal("143462-1,34"))
|
||||
if refresh {
|
||||
Expect(downloads[len(downloads)-1].PasswordToken).To(Equal("new-token"))
|
||||
}
|
||||
}, Entry("immediate success", false), Entry("after token refresh", true))
|
||||
|
||||
DescribeTable("propagates errors after purchasing during an MCP download", func(accountReadFails bool) {
|
||||
failure := errors.New("fixture post-purchase failure")
|
||||
downloads := 0
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
downloads++
|
||||
if downloads == 1 {
|
||||
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{}, failure
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error {
|
||||
if accountReadFails {
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, failure
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": true})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(failure.Error()))
|
||||
}, Entry("reloading the saved account", true), Entry("retrying the download", false))
|
||||
|
||||
It("refreshes an expired session using saved credentials", func() {
|
||||
var login appstore.LoginInput
|
||||
var accounts []appstore.Account
|
||||
|
||||
refreshed := appstore.Account{PasswordToken: "refreshed-private-token"}
|
||||
store.purchase = func(in appstore.PurchaseInput) error {
|
||||
accounts = append(accounts, in.Account)
|
||||
if len(accounts) == 1 {
|
||||
return appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
store.login = func(in appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
login = in
|
||||
|
||||
return appstore.LoginOutput{Account: refreshed}, nil
|
||||
}
|
||||
Expect(call("purchase_app", map[string]any{"app_id": 123}).IsError).To(BeFalse())
|
||||
Expect(login).To(Equal(appstore.LoginInput{Email: account.Email, Password: account.Password}))
|
||||
Expect(accounts).To(Equal([]appstore.Account{account, refreshed}))
|
||||
})
|
||||
|
||||
It("reports two-factor requirements as tool errors without requesting credentials", func() {
|
||||
store.purchase = func(appstore.PurchaseInput) error {
|
||||
return appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
store.login = func(appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
return appstore.LoginOutput{}, appstore.ErrAuthCodeRequired
|
||||
}
|
||||
result := call("purchase_app", map[string]any{"app_id": 123})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("ipatool auth login"))
|
||||
})
|
||||
|
||||
It("does not expose App Store error metadata", func() {
|
||||
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{}, appstore.NewErrorWithMetadata(errors.New("request failed"), account)
|
||||
}
|
||||
result := call("search_apps", map[string]any{"term": "example"})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
data, err := json.Marshal(result)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).To(ContainSubstring("request failed"))
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
})
|
||||
|
||||
It("reports package finalization failures as tool errors", func() {
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(appstore.ReplicateSinfInput) error {
|
||||
return errors.New("finalization failed")
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("finalization failed"))
|
||||
})
|
||||
|
||||
DescribeTable("returns every parameter and app field even when metadata is unavailable", func(name string, args map[string]any, expectedKeys []string) {
|
||||
partial := appstore.App{ID: 123}
|
||||
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{Count: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
store.ownedApps = func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 1, Page: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
store.listVersions = func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"200"}}, nil
|
||||
}
|
||||
store.getVersionMetadata = func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error { return nil }
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(appstore.ReplicateSinfInput) error { return nil }
|
||||
result := call(name, args)
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
output := result.StructuredContent.(map[string]any)
|
||||
for _, key := range expectedKeys {
|
||||
Expect(output).To(HaveKey(key))
|
||||
}
|
||||
|
||||
metadata := output["app"]
|
||||
if metadata == nil {
|
||||
metadata = output["apps"].([]any)[0]
|
||||
}
|
||||
Expect(metadata).To(Equal(map[string]any{
|
||||
"trackId": float64(123), "bundleId": "", "trackName": "", "version": "",
|
||||
"price": float64(0), "purchaseDate": nil, "platforms": []any{},
|
||||
}))
|
||||
textJSON, err := json.Marshal(result.StructuredContent)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(MatchJSON(string(textJSON)))
|
||||
},
|
||||
Entry("search", "search_apps", map[string]any{"term": "example"}, []string{"term", "limit", "platform", "count", "apps"}),
|
||||
Entry("purchases", "list_purchases", map[string]any{}, []string{"page", "max_results", "platform", "count", "totalCount", "apps"}),
|
||||
Entry("versions", "list_app_versions", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "bundleID", "app", "externalVersionIdentifiers", "latestExternalVersionID", "success"}),
|
||||
Entry("version metadata", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"}, []string{"app_id", "bundle_identifier", "platform", "app", "external_version_id", "displayVersion", "releaseDate", "success"}),
|
||||
Entry("purchase", "purchase_app", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "app", "alreadyOwned", "success"}),
|
||||
Entry("download", "download_app", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "app", "output", "external_version_id", "purchase", "purchased", "success"}),
|
||||
)
|
||||
|
||||
DescribeTable("fills missing bundle identifiers in app lists without losing purchase metadata", func(name string, args map[string]any) {
|
||||
purchasedAt := time.Date(2025, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
partial := appstore.App{ID: 123, Name: "Original name", PurchaseDate: purchasedAt, Platforms: []appstore.Platform{appstore.PlatformMacOS}}
|
||||
var lookup appstore.LookupInput
|
||||
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: appstore.App{ID: 123, BundleID: app.BundleID, Name: "Catalog name", Version: "2.0", Price: 4.99}}, nil
|
||||
}
|
||||
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{Count: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
store.ownedApps = func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 1, Page: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
result := call(name, args)
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, AppID: 123, Platform: appstore.PlatformMacOS}))
|
||||
metadata := result.StructuredContent.(map[string]any)["apps"].([]any)[0]
|
||||
Expect(metadata).To(Equal(map[string]any{
|
||||
"trackId": float64(123), "bundleId": app.BundleID, "trackName": "Original name", "version": "2.0",
|
||||
"price": 4.99, "purchaseDate": purchasedAt.Format(time.RFC3339), "platforms": []any{"macos"},
|
||||
}))
|
||||
},
|
||||
Entry("search", "search_apps", map[string]any{"term": "example"}),
|
||||
Entry("purchases", "list_purchases", map[string]any{}),
|
||||
)
|
||||
|
||||
DescribeTable("resolves bundle identifiers for numeric app IDs", func(name string) {
|
||||
var lookup appstore.LookupInput
|
||||
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: app}, nil
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error { return nil }
|
||||
store.listVersions = func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{}, nil
|
||||
}
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(appstore.ReplicateSinfInput) error { return nil }
|
||||
result := call(name, map[string]any{"app_id": 123})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup.AppID).To(Equal(int64(123)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(123)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
|
||||
Expect(result.StructuredContent.(map[string]any)["app"]).To(HaveKeyWithValue("bundleId", app.BundleID))
|
||||
if name == "list_app_versions" {
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundleID", app.BundleID))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("externalVersionIdentifiers", []any{}))
|
||||
}
|
||||
}, Entry("purchase", "purchase_app"), Entry("download", "download_app"), Entry("versions", "list_app_versions"))
|
||||
})
|
||||
|
||||
type fakeMCPAppStore struct {
|
||||
appstore.AppStore
|
||||
accountInfo func() (appstore.AccountInfoOutput, error)
|
||||
search func(appstore.SearchInput) (appstore.SearchOutput, error)
|
||||
lookup func(appstore.LookupInput) (appstore.LookupOutput, error)
|
||||
ownedApps func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error)
|
||||
listVersions func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error)
|
||||
getVersionMetadata func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error)
|
||||
purchase func(appstore.PurchaseInput) error
|
||||
download func(appstore.DownloadInput) (appstore.DownloadOutput, error)
|
||||
replicateSinf func(appstore.ReplicateSinfInput) error
|
||||
login func(appstore.LoginInput) (appstore.LoginOutput, error)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return s.accountInfo()
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return s.search(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return s.lookup(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return s.ownedApps(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return s.listVersions(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return s.getVersionMetadata(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Purchase(input appstore.PurchaseInput) error {
|
||||
return s.purchase(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return s.download(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error {
|
||||
return s.replicateSinf(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
return s.login(input)
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
)
|
||||
|
||||
type mcpSearchInput struct {
|
||||
Term string `json:"term" jsonschema:"Search term"`
|
||||
Limit *int64 `json:"limit,omitempty" jsonschema:"Maximum results; defaults to 5. visionOS supports up to 12."`
|
||||
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), watchos, visionos, or macos; defaults to iOS and iPadOS"`
|
||||
}
|
||||
|
||||
type mcpSearchOutput struct {
|
||||
Term string `json:"term"`
|
||||
Limit int64 `json:"limit"`
|
||||
Platform appstore.Platform `json:"platform"`
|
||||
Count int `json:"count"`
|
||||
Apps []mcpApp `json:"apps"`
|
||||
}
|
||||
|
||||
type mcpAppInput struct {
|
||||
AppID int64 `json:"app_id,omitempty" jsonschema:"Numeric app ID; required unless bundle_identifier is provided"`
|
||||
BundleID string `json:"bundle_identifier,omitempty" jsonschema:"Bundle identifier; overrides app_id when found"`
|
||||
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), watchos, visionos, or macos; uses the CLI default when omitted"`
|
||||
}
|
||||
|
||||
type mcpDownloadInput struct {
|
||||
mcpAppInput
|
||||
Output string `json:"output,omitempty" jsonschema:"Destination file or directory; defaults to the server's working directory"`
|
||||
ExternalVersionID string `json:"external_version_id,omitempty" jsonschema:"External version identifier; defaults to the latest version"`
|
||||
Purchase bool `json:"purchase,omitempty" jsonschema:"Acquire a free license if needed; defaults to false"`
|
||||
}
|
||||
|
||||
type mcpDownloadOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
Output string `json:"output"`
|
||||
ExternalVersionID string `json:"external_version_id"`
|
||||
Purchase bool `json:"purchase"`
|
||||
Purchased bool `json:"purchased"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type mcpVersionsOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
ExternalVersionIdentifiers []string `json:"externalVersionIdentifiers"`
|
||||
LatestExternalVersionID string `json:"latestExternalVersionID"`
|
||||
BundleID string `json:"bundleID"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type mcpVersionMetadataInput struct {
|
||||
mcpAppInput
|
||||
ExternalVersionID string `json:"external_version_id" jsonschema:"External version identifier of the target app (required)"`
|
||||
}
|
||||
|
||||
type mcpVersionMetadataOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
ExternalVersionID string `json:"external_version_id"`
|
||||
DisplayVersion string `json:"displayVersion" jsonschema:"Display version of the requested external version identifier"`
|
||||
ReleaseDate time.Time `json:"releaseDate"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type mcpPurchasesInput struct {
|
||||
Page *int `json:"page,omitempty" jsonschema:"Page number starting at 1; defaults to 1"`
|
||||
MaxResults *int `json:"max_results,omitempty" jsonschema:"Apps per page from 1 to 100; defaults to 10"`
|
||||
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), visionos, or macos; defaults to all platforms"`
|
||||
}
|
||||
|
||||
type mcpPurchasesOutput struct {
|
||||
Count int `json:"count"`
|
||||
TotalCount int `json:"totalCount"`
|
||||
Page int `json:"page"`
|
||||
MaxResults int `json:"max_results"`
|
||||
Platform appstore.Platform `json:"platform"`
|
||||
Apps []mcpApp `json:"apps"`
|
||||
}
|
||||
|
||||
type mcpPurchaseOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
AlreadyOwned bool `json:"alreadyOwned"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// withMCPAccount refreshes expired tokens using the saved credentials, as the CLI does.
|
||||
// Authentication and account details are never included in tool results.
|
||||
func withMCPAccount[Out any](ctx context.Context, store appstore.AppStore, operation func(appstore.Account) (Out, error)) (Out, error) {
|
||||
var zero Out
|
||||
|
||||
info, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("account unavailable; run 'ipatool auth login' before using MCP: %w", err)
|
||||
}
|
||||
|
||||
output, err := operation(info.Account)
|
||||
if !errors.Is(err, appstore.ErrPasswordTokenExpired) {
|
||||
return output, err
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return zero, fmt.Errorf("tool call canceled: %w", err)
|
||||
}
|
||||
|
||||
login, err := store.Login(appstore.LoginInput{Email: info.Account.Email, Password: info.Account.Password})
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("session refresh failed; run 'ipatool auth login' outside MCP: %w", err)
|
||||
}
|
||||
|
||||
output, err = operation(login.Account)
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("operation failed after session refresh: %w", err)
|
||||
}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) search(ctx context.Context, input mcpSearchInput) (mcpSearchOutput, error) {
|
||||
if strings.TrimSpace(input.Term) == "" {
|
||||
return mcpSearchOutput{}, errors.New("search term must not be empty")
|
||||
}
|
||||
|
||||
limit := int64(5)
|
||||
if input.Limit != nil {
|
||||
limit = *input.Limit
|
||||
}
|
||||
|
||||
if limit < 1 {
|
||||
return mcpSearchOutput{}, errors.New("limit must be greater than 0")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(input.Platform)
|
||||
if err != nil {
|
||||
return mcpSearchOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpSearchOutput, error) {
|
||||
out, err := t.store.Search(appstore.SearchInput{Account: acc, Term: input.Term, Limit: limit, Platform: platform})
|
||||
if err != nil {
|
||||
return mcpSearchOutput{}, err
|
||||
}
|
||||
|
||||
return mcpSearchOutput{
|
||||
Term: input.Term, Limit: limit, Platform: platform,
|
||||
Count: out.Count, Apps: t.appResults(acc, out.Results, platform),
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (input mcpAppInput) validate() (appstore.Platform, error) {
|
||||
if input.AppID < 0 || (input.AppID == 0 && strings.TrimSpace(input.BundleID) == "") {
|
||||
return "", errors.New("a positive app ID or a bundle identifier must be specified")
|
||||
}
|
||||
|
||||
return appstore.ParsePlatform(input.Platform)
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) resolveApp(acc appstore.Account, input mcpAppInput, platform appstore.Platform, allowDelisted bool) (appstore.App, error) {
|
||||
app := appstore.App{ID: input.AppID, BundleID: input.BundleID}
|
||||
if input.BundleID == "" {
|
||||
return t.completeApp(acc, app, platform), nil
|
||||
}
|
||||
|
||||
out, err := t.store.Lookup(appstore.LookupInput{Account: acc, BundleID: input.BundleID, Platform: platform})
|
||||
if allowDelisted && input.AppID > 0 && errors.Is(err, appstore.ErrAppNotFound) {
|
||||
return app, nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return appstore.App{}, err
|
||||
}
|
||||
|
||||
// Preserve a known bundle identifier even if the catalog omits it.
|
||||
if out.App.BundleID == "" {
|
||||
out.App.BundleID = input.BundleID
|
||||
}
|
||||
|
||||
return out.App, nil
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) download(ctx context.Context, input mcpDownloadInput) (mcpDownloadOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
purchased := false
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpDownloadOutput, error) {
|
||||
app, err := t.resolveApp(acc, input.mcpAppInput, platform, true)
|
||||
if err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
downloadInput := appstore.DownloadInput{
|
||||
Context: ctx, Account: acc, App: app, OutputPath: input.Output,
|
||||
ExternalVersionID: input.ExternalVersionID, Platform: platform,
|
||||
}
|
||||
|
||||
out, err := t.store.Download(downloadInput)
|
||||
if errors.Is(err, appstore.ErrLicenseRequired) && input.Purchase && !purchased {
|
||||
err = t.store.Purchase(appstore.PurchaseInput{Account: acc, App: app, Platform: platform})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
info, accountErr := t.store.AccountInfo()
|
||||
if accountErr != nil {
|
||||
return mcpDownloadOutput{}, accountErr
|
||||
}
|
||||
|
||||
downloadInput.Account = info.Account
|
||||
purchased = true
|
||||
out, err = t.store.Download(downloadInput)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
if err := replicateDownloadSinf(t.store, platform, out); err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
return mcpDownloadOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
Output: out.DestinationPath, ExternalVersionID: input.ExternalVersionID,
|
||||
Purchase: input.Purchase, Purchased: purchased, Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) listVersions(ctx context.Context, input mcpAppInput) (mcpVersionsOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpVersionsOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpVersionsOutput, error) {
|
||||
app, err := t.resolveApp(acc, input, platform, false)
|
||||
if err != nil {
|
||||
return mcpVersionsOutput{}, err
|
||||
}
|
||||
|
||||
out, err := t.store.ListVersions(appstore.ListVersionsInput{Context: ctx, Account: acc, App: app, Platform: platform})
|
||||
if err != nil {
|
||||
return mcpVersionsOutput{}, err
|
||||
}
|
||||
|
||||
return mcpVersionsOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
ExternalVersionIdentifiers: append([]string{}, out.ExternalVersionIdentifiers...),
|
||||
LatestExternalVersionID: out.LatestExternalVersionID, BundleID: app.BundleID, Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) getVersionMetadata(ctx context.Context, input mcpVersionMetadataInput) (mcpVersionMetadataOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
if strings.TrimSpace(input.ExternalVersionID) == "" {
|
||||
return mcpVersionMetadataOutput{}, errors.New("external version identifier must not be empty")
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpVersionMetadataOutput, error) {
|
||||
app, err := t.resolveApp(acc, input.mcpAppInput, platform, false)
|
||||
if err != nil {
|
||||
return mcpVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
out, err := t.store.GetVersionMetadata(appstore.GetVersionMetadataInput{
|
||||
Context: ctx, Account: acc, App: app, VersionID: input.ExternalVersionID, Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return mcpVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
return mcpVersionMetadataOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
ExternalVersionID: input.ExternalVersionID, DisplayVersion: out.DisplayVersion,
|
||||
ReleaseDate: out.ReleaseDate, Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) listPurchases(ctx context.Context, input mcpPurchasesInput) (mcpPurchasesOutput, error) {
|
||||
page, limit := 1, appstore.DefaultOwnedAppsLimit
|
||||
if input.Page != nil {
|
||||
page = *input.Page
|
||||
}
|
||||
|
||||
if input.MaxResults != nil {
|
||||
limit = *input.MaxResults
|
||||
}
|
||||
|
||||
if page < 1 {
|
||||
return mcpPurchasesOutput{}, errors.New("page must be greater than 0")
|
||||
}
|
||||
|
||||
if limit < 1 || limit > appstore.MaxOwnedAppsLimit {
|
||||
return mcpPurchasesOutput{}, fmt.Errorf("max results must be between 1 and %d", appstore.MaxOwnedAppsLimit)
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(input.Platform)
|
||||
if err != nil {
|
||||
return mcpPurchasesOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpPurchasesOutput, error) {
|
||||
out, err := t.store.OwnedApps(appstore.OwnedAppsInput{Account: acc, Page: page, Limit: limit, Platform: platform})
|
||||
if err != nil {
|
||||
return mcpPurchasesOutput{}, err
|
||||
}
|
||||
|
||||
return mcpPurchasesOutput{
|
||||
Count: out.Count, TotalCount: out.TotalCount, Page: out.Page, MaxResults: limit, Platform: platform,
|
||||
Apps: t.appResults(acc, out.Results, platform),
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) purchase(ctx context.Context, input mcpAppInput) (mcpPurchaseOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpPurchaseOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpPurchaseOutput, error) {
|
||||
app, err := t.resolveApp(acc, input, platform, false)
|
||||
if err != nil {
|
||||
return mcpPurchaseOutput{}, err
|
||||
}
|
||||
|
||||
err = t.store.Purchase(appstore.PurchaseInput{Account: acc, App: app, Platform: platform})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return mcpPurchaseOutput{}, err
|
||||
}
|
||||
|
||||
return mcpPurchaseOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
AlreadyOwned: errors.Is(err, appstore.ErrLicenseAlreadyExists), Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/thediveo/enumflag/v2"
|
||||
)
|
||||
|
||||
type OutputFormat enumflag.Flag
|
||||
|
||||
const (
|
||||
OutputFormatText OutputFormat = iota
|
||||
OutputFormatJSON
|
||||
)
|
||||
|
||||
func OutputFormatFromString(value string) (OutputFormat, error) {
|
||||
switch value {
|
||||
case "json":
|
||||
return OutputFormatJSON, nil
|
||||
case "text":
|
||||
return OutputFormatText, nil
|
||||
default:
|
||||
return OutputFormatJSON, fmt.Errorf("invalid output format '%s'", value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func readPrompt(prompt string, masked bool) (string, error) {
|
||||
if masked {
|
||||
state, err := term.MakeRaw(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to configure terminal: %w", err)
|
||||
}
|
||||
defer term.Restore(int(os.Stdin.Fd()), state) //nolint:errcheck
|
||||
}
|
||||
|
||||
// Prompts belong on stderr so structured output on stdout stays valid.
|
||||
if _, err := io.WriteString(os.Stderr, prompt); err != nil {
|
||||
return "", fmt.Errorf("failed to write prompt: %w", err)
|
||||
}
|
||||
|
||||
if masked {
|
||||
defer fmt.Fprint(os.Stderr, "\r\n")
|
||||
|
||||
return readMaskedInput(os.Stdin, os.Stderr)
|
||||
}
|
||||
|
||||
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read input: %w", err)
|
||||
}
|
||||
|
||||
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
|
||||
}
|
||||
|
||||
func readMaskedInput(input io.Reader, output io.Writer) (string, error) {
|
||||
reader := bufio.NewReader(input)
|
||||
|
||||
var (
|
||||
password []rune
|
||||
escape int
|
||||
)
|
||||
|
||||
for {
|
||||
key, _, err := reader.ReadRune()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read input: %w", err)
|
||||
}
|
||||
|
||||
// Ignore terminal escape sequences (for example, arrow keys).
|
||||
if escape != 0 {
|
||||
if escape == 1 && (key == '[' || key == 'O') {
|
||||
escape = 2
|
||||
} else if escape == 1 || (key >= 0x40 && key <= 0x7e) {
|
||||
escape = 0
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var echo string
|
||||
|
||||
switch key {
|
||||
case '\r', '\n':
|
||||
return string(password), nil
|
||||
case 3:
|
||||
return "", errors.New("input interrupted")
|
||||
case 4:
|
||||
return "", io.EOF
|
||||
case 27:
|
||||
escape = 1
|
||||
case '\b', 127:
|
||||
if len(password) > 0 {
|
||||
password = password[:len(password)-1]
|
||||
echo = "\b \b"
|
||||
}
|
||||
case 21:
|
||||
echo = strings.Repeat("\b \b", len(password))
|
||||
password = password[:0]
|
||||
default:
|
||||
if unicode.IsPrint(key) {
|
||||
password = append(password, key)
|
||||
echo = "*"
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := io.WriteString(output, echo); err != nil {
|
||||
return "", fmt.Errorf("failed to echo input: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Masked input", func() {
|
||||
DescribeTable("echoes masks while preserving the entered password", func(input, password, echo string) {
|
||||
var output bytes.Buffer
|
||||
value, err := readMaskedInput(strings.NewReader(input), &output)
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(value).To(Equal(password))
|
||||
Expect(output.String()).To(Equal(echo))
|
||||
},
|
||||
Entry("enter", "secret\r", "secret", "******"),
|
||||
Entry("newline", "secret\n", "secret", "******"),
|
||||
Entry("unicode", "pä密🔑\r", "pä密🔑", "****"),
|
||||
Entry("delete", "ab\x7fc\r", "ac", "**\b \b*"),
|
||||
Entry("unicode backspace", "a密\bc\r", "ac", "**\b \b*"),
|
||||
Entry("backspace on empty input", "\b\x7fa\r", "a", "*"),
|
||||
Entry("clear line", "ab\x15c\r", "c", "**\b \b\b \b*"),
|
||||
Entry("arrow keys", "ab\x1b[D\x1bOCc\r", "abc", "***"),
|
||||
Entry("empty input", "\r", "", ""),
|
||||
)
|
||||
|
||||
It("cancels without returning the password on Ctrl-C", func() {
|
||||
value, err := readMaskedInput(strings.NewReader("secret\x03"), io.Discard)
|
||||
|
||||
Expect(err).To(MatchError("input interrupted"))
|
||||
Expect(value).To(BeEmpty())
|
||||
})
|
||||
|
||||
DescribeTable("discards incomplete input", func(input string) {
|
||||
value, err := readMaskedInput(strings.NewReader(input), io.Discard)
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("EOF")))
|
||||
Expect(value).To(BeEmpty())
|
||||
},
|
||||
Entry("end of stream", "secret"),
|
||||
Entry("Ctrl-D", "secret\x04"),
|
||||
)
|
||||
})
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func purchaseCmd() *cobra.Command {
|
||||
return purchaseCmdWithAppStore(func() appstore.AppStore { return dependencies.AppStore })
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func purchaseCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "purchase",
|
||||
Short: "Obtain a license for the app from the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
return retry.Do(func() error {
|
||||
store := appStore()
|
||||
infoResult, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := store.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := store.Lookup(appstore.LookupInput{
|
||||
Account: acc,
|
||||
BundleID: bundleID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
err = store.Purchase(appstore.PurchaseInput{
|
||||
Account: acc,
|
||||
App: app,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Bool("alreadyOwned", errors.Is(err, appstore.ErrLicenseAlreadyExists)).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to purchase for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Purchase command", func() {
|
||||
It("accepts a platform flag with macOS help", func() {
|
||||
cmd := purchaseCmd()
|
||||
platform, err := cmd.Flags().GetString("platform")
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(platform).To(BeEmpty())
|
||||
Expect(cmd.Flag("platform").Usage).To(ContainSubstring("macos"))
|
||||
})
|
||||
|
||||
DescribeTable("purchasing by app ID", func(flag string) {
|
||||
store := &fakePurchaseAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{flag, "123456789", "--platform", "macos"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.lookupCalls).To(BeZero())
|
||||
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 123456789}))
|
||||
Expect(store.purchaseInput.Platform).To(Equal(appstore.PlatformMacOS))
|
||||
},
|
||||
Entry("accepts the long flag", "--app-id"),
|
||||
Entry("accepts the short flag", "-i"),
|
||||
)
|
||||
|
||||
It("requires an app ID or bundle identifier before accessing the account", func() {
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore {
|
||||
Fail("must not access the app store without a target")
|
||||
|
||||
return nil
|
||||
})
|
||||
cmd.SetArgs([]string{})
|
||||
|
||||
Expect(cmd.Execute()).To(MatchError("either the app ID or the bundle identifier must be specified"))
|
||||
})
|
||||
|
||||
It("lets the bundle identifier override the app ID", func() {
|
||||
store := &fakePurchaseAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"-i", "123456789", "-b", "com.example.app"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.lookupCalls).To(Equal(1))
|
||||
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.app"}))
|
||||
})
|
||||
|
||||
It("propagates macOS to lookup and purchase", func() {
|
||||
store := &fakePurchaseAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--bundle-identifier", "com.example.mac", "--platform", "macos"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.lookupInput.BundleID).To(Equal("com.example.mac"))
|
||||
Expect(store.lookupInput.Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.purchaseInput.Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.mac"}))
|
||||
})
|
||||
})
|
||||
|
||||
type fakePurchaseAppStore struct {
|
||||
lookupCalls int
|
||||
lookupInput appstore.LookupInput
|
||||
purchaseInput appstore.PurchaseInput
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
return appstore.LoginOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{Account: appstore.Account{StoreFront: "143441"}}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Revoke() error { return nil }
|
||||
|
||||
func (f *fakePurchaseAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
f.lookupCalls++
|
||||
f.lookupInput = input
|
||||
|
||||
return appstore.LookupOutput{App: appstore.App{ID: 42, BundleID: input.BundleID}}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{}, nil
|
||||
}
|
||||
|
||||
func (f *fakePurchaseAppStore) Purchase(input appstore.PurchaseInput) error {
|
||||
f.purchaseInput = input
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error { return nil }
|
||||
|
||||
func (*fakePurchaseAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Bag(input appstore.BagInput) (appstore.BagOutput, error) {
|
||||
return appstore.BagOutput{}, nil
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func listPurchasesCmd() *cobra.Command {
|
||||
var page, maxResults int
|
||||
|
||||
var platformValue string
|
||||
|
||||
var platform appstore.Platform
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "list-purchases",
|
||||
Short: "List apps owned by the authenticated App Store account",
|
||||
Args: cobra.NoArgs,
|
||||
PreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
if page < 1 {
|
||||
return errors.New("page must be greater than 0")
|
||||
}
|
||||
if maxResults < 1 {
|
||||
return errors.New("max results must be greater than 0")
|
||||
}
|
||||
if maxResults > appstore.MaxOwnedAppsLimit {
|
||||
return fmt.Errorf("max results must not exceed %d", appstore.MaxOwnedAppsLimit)
|
||||
}
|
||||
|
||||
var err error
|
||||
platform, err = appstore.ParsePlatform(platformValue)
|
||||
|
||||
return err
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
var lastErr error
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc := infoResult.Account
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
output, err := dependencies.AppStore.OwnedApps(appstore.OwnedAppsInput{
|
||||
Account: acc,
|
||||
Page: page,
|
||||
Limit: maxResults,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Int("count", output.Count).
|
||||
Int("totalCount", output.TotalCount).
|
||||
Int("page", output.Page).
|
||||
Array("apps", appstore.Apps(output.Results)).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().IntVarP(&maxResults, "max-results", "l", appstore.DefaultOwnedAppsLimit, "maximum number of apps to return per page")
|
||||
cmd.Flags().IntVarP(&page, "page", "p", 1, "page of owned apps to return")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Filter by platform: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("List Purchases command", func() {
|
||||
DescribeTable("passes the platform filter to owned apps",
|
||||
func(value string, expected appstore.Platform) {
|
||||
store := &fakePurchasesAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
cmd := listPurchasesCmd()
|
||||
cmd.SetArgs([]string{"--platform", value})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.input.Platform).To(Equal(expected))
|
||||
},
|
||||
Entry("all platforms by default", "", appstore.Platform("")),
|
||||
Entry("iOS alias", "ios", appstore.PlatformIPhone),
|
||||
Entry("iPadOS alias", "ipados", appstore.PlatformIPad),
|
||||
Entry("tvOS alias", "tvos", appstore.PlatformAppleTV),
|
||||
Entry("visionOS", "visionos", appstore.PlatformVisionOS),
|
||||
Entry("macOS", "macos", appstore.PlatformMacOS),
|
||||
)
|
||||
|
||||
DescribeTable("rejects an invalid platform before accessing the account", func(value string) {
|
||||
cmd := listPurchasesCmd()
|
||||
Expect(cmd.Flags().Set("platform", value)).To(Succeed())
|
||||
Expect(cmd.PreRunE(cmd, nil)).To(MatchError(ContainSubstring("invalid platform")))
|
||||
},
|
||||
Entry("invalid value", "invalid"),
|
||||
Entry("unknown is output only", "unknown"),
|
||||
Entry("uppercase unknown", "UNKNOWN"),
|
||||
)
|
||||
|
||||
It("uses the pagination defaults", func() {
|
||||
cmd := listPurchasesCmd()
|
||||
|
||||
page, err := cmd.Flags().GetInt("page")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(page).To(Equal(1))
|
||||
|
||||
maxResults, err := cmd.Flags().GetInt("max-results")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(maxResults).To(Equal(appstore.DefaultOwnedAppsLimit))
|
||||
})
|
||||
|
||||
DescribeTable("rejects invalid pagination",
|
||||
func(flag, value, errorText string) {
|
||||
cmd := listPurchasesCmd()
|
||||
Expect(cmd.Flags().Set(flag, value)).To(Succeed())
|
||||
|
||||
err := cmd.PreRunE(cmd, nil)
|
||||
Expect(err).To(MatchError(ContainSubstring(errorText)))
|
||||
},
|
||||
Entry("page below one", "page", "0", "page"),
|
||||
Entry("max results below one", "max-results", "0", "max results"),
|
||||
Entry("max results over limit", "max-results", "101", "100"),
|
||||
)
|
||||
|
||||
It("is registered on the root command", func() {
|
||||
cmd, _, err := rootCmd().Find([]string{"list-purchases"})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(cmd.Name()).To(Equal("list-purchases"))
|
||||
})
|
||||
})
|
||||
|
||||
type fakePurchasesAppStore struct {
|
||||
appstore.AppStore
|
||||
input appstore.OwnedAppsInput
|
||||
}
|
||||
|
||||
func (*fakePurchasesAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, nil
|
||||
}
|
||||
|
||||
func (s *fakePurchasesAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
s.input = input
|
||||
|
||||
return appstore.OwnedAppsOutput{}, nil
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/thediveo/enumflag/v2"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
type contextKey string
|
||||
|
||||
const interactiveKey contextKey = "interactive"
|
||||
|
||||
func rootCmd() *cobra.Command {
|
||||
var (
|
||||
verbose bool
|
||||
nonInteractive bool
|
||||
format OutputFormat
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "ipatool",
|
||||
Short: "A cli tool for interacting with Apple's ipa files",
|
||||
SilenceErrors: true,
|
||||
SilenceUsage: true,
|
||||
Version: version,
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
ctx := context.WithValue(context.Background(), interactiveKey, !nonInteractive)
|
||||
cmd.SetContext(ctx)
|
||||
initWithCommand(cmd)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.PersistentFlags().VarP(
|
||||
enumflag.New(&format, "format", map[OutputFormat][]string{
|
||||
OutputFormatText: {"text"},
|
||||
OutputFormatJSON: {"json"},
|
||||
}, enumflag.EnumCaseSensitive), "format", "", "sets output format for command; can be 'text', 'json'")
|
||||
cmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "enables verbose logs")
|
||||
cmd.PersistentFlags().BoolVarP(&nonInteractive, "non-interactive", "", false, "run in non-interactive session")
|
||||
cmd.PersistentFlags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
|
||||
cmd.AddCommand(authCmd())
|
||||
cmd.AddCommand(downloadCmd())
|
||||
cmd.AddCommand(listPurchasesCmd())
|
||||
cmd.AddCommand(purchaseCmd())
|
||||
cmd.AddCommand(searchCmd())
|
||||
cmd.AddCommand(ListVersionsCmd())
|
||||
cmd.AddCommand(getVersionMetadataCmd())
|
||||
cmd.AddCommand(mcpCmd())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
// Execute runs the program and returns the appropriate exit status code.
|
||||
func Execute() int {
|
||||
cmd := rootCmd()
|
||||
err := cmd.Execute()
|
||||
|
||||
if err != nil {
|
||||
if reflect.ValueOf(dependencies).IsZero() {
|
||||
initWithCommand(cmd)
|
||||
}
|
||||
|
||||
var appstoreErr *appstore.Error
|
||||
if errors.As(err, &appstoreErr) {
|
||||
dependencies.Logger.Verbose().Stack().
|
||||
Err(err).
|
||||
Interface("metadata", appstoreErr.Metadata).
|
||||
Send()
|
||||
} else {
|
||||
dependencies.Logger.Verbose().Stack().Err(err).Send()
|
||||
}
|
||||
|
||||
dependencies.Logger.Error().
|
||||
Err(err).
|
||||
Bool("success", false).
|
||||
Send()
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func searchCmd() *cobra.Command {
|
||||
var (
|
||||
limit int64
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "search <term>",
|
||||
Short: "Search for iOS, iPadOS, tvOS, watchOS, visionOS, and macOS apps available on the App Store",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
output, err := dependencies.AppStore.Search(appstore.SearchInput{
|
||||
Account: infoResult.Account,
|
||||
Term: args[0],
|
||||
Limit: limit,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Int("count", output.Count).
|
||||
Array("apps", appstore.Apps(output.Results)).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&limit, "limit", "l", 5, "maximum amount of search results to retrieve; visionOS supports up to 12")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
)
|
||||
|
||||
// prepareStateDirectory resolves and migrates session storage before it is opened.
|
||||
func prepareStateDirectory(os operatingsystem.OperatingSystem, homeDirectory string) (string, error) {
|
||||
legacyDirectory := filepath.Join(homeDirectory, ConfigDirectoryName)
|
||||
stateDirectory := legacyDirectory
|
||||
|
||||
for _, variable := range []string{"XDG_STATE_HOME", "XDG_DATA_HOME"} {
|
||||
if base := os.Getenv(variable); filepath.IsAbs(base) {
|
||||
stateDirectory = filepath.Join(base, "ipatool")
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
info, err := os.Stat(legacyDirectory)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return "", fmt.Errorf("could not read legacy state directory metadata: %w", err)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
if !info.IsDir() {
|
||||
return "", fmt.Errorf("legacy state path is not a directory: %s", legacyDirectory)
|
||||
}
|
||||
// Never merge sessions or move a directory into itself. Keeping the legacy
|
||||
// directory also preserves authentication when migration is unavailable.
|
||||
relative, err := filepath.Rel(legacyDirectory, stateDirectory)
|
||||
if err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
|
||||
if _, err := os.Stat(stateDirectory); err == nil || !os.IsNotExist(err) {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(stateDirectory), 0700); err != nil {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
// Rename keeps cookies and encrypted credentials together, with their
|
||||
// existing permissions. Cross-filesystem moves fall back to legacy storage.
|
||||
if err := os.Rename(legacyDirectory, stateDirectory); err != nil {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
|
||||
return stateDirectory, nil
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(stateDirectory, 0700); err != nil {
|
||||
return "", fmt.Errorf("failed to create state directory: %w", err)
|
||||
}
|
||||
|
||||
return stateDirectory, nil
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("State directory", func() {
|
||||
var home, legacy, target string
|
||||
|
||||
BeforeEach(func() {
|
||||
home = GinkgoT().TempDir()
|
||||
legacy = filepath.Join(home, ConfigDirectoryName)
|
||||
target = filepath.Join(home, "state", "ipatool")
|
||||
GinkgoT().Setenv("XDG_STATE_HOME", filepath.Dir(target))
|
||||
GinkgoT().Setenv("XDG_DATA_HOME", "")
|
||||
})
|
||||
|
||||
DescribeTable("selects the session directory", func(state, data, want string) {
|
||||
for variable, value := range map[string]string{"XDG_STATE_HOME": state, "XDG_DATA_HOME": data} {
|
||||
if value != "" && value != "relative" {
|
||||
value = filepath.Join(home, value)
|
||||
}
|
||||
|
||||
GinkgoT().Setenv(variable, value)
|
||||
}
|
||||
|
||||
got, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(filepath.Join(home, want)))
|
||||
Expect(got).To(BeADirectory())
|
||||
|
||||
if got != legacy {
|
||||
Expect(legacy).ToNot(BeAnExistingFile())
|
||||
}
|
||||
},
|
||||
Entry("defaults to legacy storage", "", "", ConfigDirectoryName),
|
||||
Entry("prefers state storage", "state", "data", "state/ipatool"),
|
||||
Entry("falls back to data storage", "", "data", "data/ipatool"),
|
||||
Entry("ignores a relative state path", "relative", "data", "data/ipatool"),
|
||||
Entry("ignores relative paths", "relative", "relative", ConfigDirectoryName),
|
||||
)
|
||||
|
||||
It("preserves authentication after migration and subsequent startup", func() {
|
||||
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
|
||||
|
||||
openKeyring := func(directory string) keyring.Keyring {
|
||||
ring, err := keyring.Open(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{keyring.FileBackend},
|
||||
ServiceName: KeychainServiceName,
|
||||
FileDir: directory,
|
||||
FilePasswordFunc: keyring.FixedStringPrompt("test-passphrase"),
|
||||
})
|
||||
ExpectWithOffset(1, err).ToNot(HaveOccurred())
|
||||
|
||||
return ring
|
||||
}
|
||||
item := keyring.Item{Key: "account", Data: []byte("existing-session"), Label: KeychainServiceName}
|
||||
Expect(openKeyring(legacy).Set(item)).To(Succeed())
|
||||
|
||||
cookieURL, err := url.Parse("https://apps.apple.com/")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
jar := newCookieJar(legacy)
|
||||
jar.SetCookies(cookieURL, []*http.Cookie{{Name: "session", Value: "existing-cookie", Path: "/", Expires: time.Now().Add(time.Hour)}})
|
||||
Expect(jar.Save()).To(Succeed())
|
||||
|
||||
before, err := os.ReadFile(filepath.Join(legacy, item.Key))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
directory, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(directory).To(Equal(target))
|
||||
|
||||
got, err := openKeyring(directory).Get(item.Key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got.Data).To(Equal(item.Data))
|
||||
|
||||
after, err := os.ReadFile(filepath.Join(directory, item.Key))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(after).To(Equal(before), "encrypted credentials must remain unchanged")
|
||||
|
||||
cookies := newCookieJar(directory).Cookies(cookieURL)
|
||||
Expect(cookies).To(HaveLen(1))
|
||||
Expect(cookies[0].Name).To(Equal("session"))
|
||||
Expect(cookies[0].Value).To(Equal("existing-cookie"))
|
||||
}
|
||||
|
||||
Expect(legacy).ToNot(BeAnExistingFile())
|
||||
})
|
||||
|
||||
DescribeTable("preserves legacy storage when migration fails", func(mkdirErr, renameErr error) {
|
||||
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(legacy, CookieJarFileName), []byte("session"), 0600)).To(Succeed())
|
||||
|
||||
got, err := prepareStateDirectory(migrationFailureOS{operatingsystem.New(), mkdirErr, renameErr}, home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(legacy))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(got, CookieJarFileName))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(string(data)).To(Equal("session"))
|
||||
},
|
||||
Entry("parent creation denied", os.ErrPermission, nil),
|
||||
Entry("rename denied", nil, os.ErrPermission),
|
||||
Entry("cross filesystem", nil, errors.New("cross-device link")),
|
||||
)
|
||||
|
||||
It("preserves conflicting sessions and uses legacy storage", func() {
|
||||
for _, directory := range []string{legacy, target} {
|
||||
Expect(os.MkdirAll(directory, 0700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(directory, "account"), []byte(directory), 0600)).To(Succeed())
|
||||
}
|
||||
|
||||
got, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(legacy))
|
||||
|
||||
for _, directory := range []string{legacy, target} {
|
||||
data, err := os.ReadFile(filepath.Join(directory, "account"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(string(data)).To(Equal(directory))
|
||||
}
|
||||
})
|
||||
|
||||
DescribeTable("rejects files at directory paths", func(useLegacy bool) {
|
||||
path := target
|
||||
if useLegacy {
|
||||
path = legacy
|
||||
}
|
||||
|
||||
Expect(os.MkdirAll(filepath.Dir(path), 0700)).To(Succeed())
|
||||
Expect(os.WriteFile(path, []byte("existing file"), 0600)).To(Succeed())
|
||||
|
||||
_, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).To(HaveOccurred())
|
||||
},
|
||||
Entry("legacy", true),
|
||||
Entry("destination", false),
|
||||
)
|
||||
|
||||
It("preserves legacy storage for a nested destination", func() {
|
||||
GinkgoT().Setenv("XDG_STATE_HOME", filepath.Join(legacy, "state"))
|
||||
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
|
||||
|
||||
got, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(legacy))
|
||||
|
||||
entries, err := os.ReadDir(legacy)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(entries).To(BeEmpty(), "migration must not create directories inside legacy storage")
|
||||
})
|
||||
})
|
||||
|
||||
type migrationFailureOS struct {
|
||||
operatingsystem.OperatingSystem
|
||||
mkdirErr, renameErr error
|
||||
}
|
||||
|
||||
// nolint:wrapcheck
|
||||
func (o migrationFailureOS) MkdirAll(path string, mode os.FileMode) error {
|
||||
if o.mkdirErr != nil {
|
||||
return o.mkdirErr
|
||||
}
|
||||
|
||||
return o.OperatingSystem.MkdirAll(path, mode)
|
||||
}
|
||||
|
||||
func (o migrationFailureOS) Rename(from, to string) error {
|
||||
return o.renameErr
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
module github.com/majd/ipatool/v2
|
||||
|
||||
go 1.26.5
|
||||
|
||||
require (
|
||||
github.com/avast/retry-go v3.0.0+incompatible
|
||||
github.com/blacktop/go-macho v1.1.282
|
||||
github.com/bodgit/sevenzip v1.6.3
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4
|
||||
github.com/byteness/keyring v1.9.0
|
||||
github.com/deploymenttheory/go-macos-pkg v0.3.0
|
||||
github.com/ebitengine/purego v0.10.2
|
||||
github.com/go-compressions/lzfse v0.3.0
|
||||
github.com/juju/persistent-cookiejar v1.0.0
|
||||
github.com/klauspost/compress v1.18.7
|
||||
github.com/majd/go-apfs v1.0.29
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0
|
||||
github.com/onsi/ginkgo/v2 v2.5.0
|
||||
github.com/onsi/gomega v1.24.0
|
||||
github.com/rs/zerolog v1.28.0
|
||||
github.com/schollz/progressbar/v3 v3.19.1
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/thediveo/enumflag/v2 v2.0.1
|
||||
go.uber.org/mock v0.4.0
|
||||
golang.org/x/sys v0.48.0
|
||||
golang.org/x/term v0.46.0
|
||||
golang.org/x/text v0.42.0
|
||||
howett.net/plist v1.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b // indirect
|
||||
github.com/1password/onepassword-sdk-go v0.4.1-beta.1 // indirect
|
||||
github.com/VividCortex/ewma v1.2.0 // indirect
|
||||
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect
|
||||
github.com/andybalholm/brotli v1.2.1 // indirect
|
||||
github.com/apex/log v1.9.0 // indirect
|
||||
github.com/blacktop/go-dwarf v1.0.14 // indirect
|
||||
github.com/blacktop/go-plist v1.0.2 // indirect
|
||||
github.com/bodgit/plumbing v1.3.0 // indirect
|
||||
github.com/bodgit/windows v1.0.1 // indirect
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 // indirect
|
||||
github.com/byteness/percent v0.2.2 // indirect
|
||||
github.com/danieljoos/wincred v1.2.3 // indirect
|
||||
github.com/dustin/go-humanize v1.1.0 // indirect
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0 // indirect
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 // indirect
|
||||
github.com/extism/go-sdk v1.7.1 // indirect
|
||||
github.com/fatih/color v1.19.0 // indirect
|
||||
github.com/frankban/quicktest v1.14.6 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/gobwas/glob v0.2.3 // indirect
|
||||
github.com/godbus/dbus/v5 v5.2.2 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/jsonschema-go v0.4.3 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.22 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
|
||||
github.com/noamcohen97/touchid-go v0.3.0 // indirect
|
||||
github.com/opentracing/opentracing-go v1.2.0 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.29 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/segmentio/asm v1.1.3 // indirect
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/stangelandcl/ppmd v0.1.0 // indirect
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect
|
||||
github.com/tetratelabs/wazero v1.11.0 // indirect
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible // indirect
|
||||
github.com/ulikunitz/xz v0.5.17 // indirect
|
||||
github.com/vbauerster/mpb/v7 v7.5.3 // indirect
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f // indirect
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
|
||||
golang.org/x/mod v0.41.0 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/oauth2 v0.35.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/tools v0.49.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||
gopkg.in/errgo.v1 v1.0.1 // indirect
|
||||
gopkg.in/retry.v1 v1.0.3 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -0,0 +1,306 @@
|
||||
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b h1:sVddTkAGVmDXJbZKgp+W1zC7hN4lLz9Nus1XmjbY7eo=
|
||||
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b/go.mod h1:5rSymY4oIYtS4G3t0oMkGAXBeoYiukV3vkqlnEjIDJs=
|
||||
github.com/1password/onepassword-sdk-go v0.4.1-beta.1 h1:b/tt+bAXFXR5f3/irmPAaytfmsN6+5Nj6pbsx5nmKZA=
|
||||
github.com/1password/onepassword-sdk-go v0.4.1-beta.1/go.mod h1:j/CbzhucTywjlYrd6SE6k0LcQaFZ2l8OLBsAsOYtvD0=
|
||||
github.com/HdrHistogram/hdrhistogram-go v1.1.2 h1:5IcZpTvzydCQeHzK4Ef/D5rrSqwxob0t8PQPMybUNFM=
|
||||
github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo=
|
||||
github.com/VividCortex/ewma v1.2.0 h1:f58SaIzcDXrSy3kWaHNvuJgJ3Nmz59Zji6XoJR/q1ow=
|
||||
github.com/VividCortex/ewma v1.2.0/go.mod h1:nz4BbCtbLyFDeC9SUHbtcT5644juEuWfUAUnGx7j5l4=
|
||||
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8=
|
||||
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo=
|
||||
github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro=
|
||||
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/apex/log v1.9.0 h1:FHtw/xuaM8AgmvDDTI9fiwoAL25Sq2cxojnZICUU8l0=
|
||||
github.com/apex/log v1.9.0/go.mod h1:m82fZlWIuiWzWP04XCTXmnX0xRkYYbCdYn8jbJeLBEA=
|
||||
github.com/apex/logs v1.0.0/go.mod h1:XzxuLZ5myVHDy9SAmYpamKKRNApGj54PfYLcFrXqDwo=
|
||||
github.com/aphistic/golf v0.0.0-20180712155816-02c07f170c5a/go.mod h1:3NqKYiepwy8kCu4PNA+aP7WUV72eXWJeP9/r3/K9aLE=
|
||||
github.com/aphistic/sweet v0.2.0/go.mod h1:fWDlIh/isSE9n6EPsRmC0det+whmX6dJid3stzu0Xys=
|
||||
github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0=
|
||||
github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY=
|
||||
github.com/aws/aws-sdk-go v1.20.6/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
|
||||
github.com/aybabtme/rgbterm v0.0.0-20170906152045-cc83f3b3ce59/go.mod h1:q/89r3U2H7sSsE2t6Kca0lfwTK8JdoNGS/yzM/4iH5I=
|
||||
github.com/blacktop/go-dwarf v1.0.14 h1:OjmzfSgg/qAKckn2tWFebcgKgJ7HOqCj7bS+CiE1lrY=
|
||||
github.com/blacktop/go-dwarf v1.0.14/go.mod h1:4W2FKgSFYcZLDwnR7k+apv5i3nrau4NGl9N6VQ9DSTo=
|
||||
github.com/blacktop/go-macho v1.1.282 h1:DW3HYz5zVCT6+Jlp1+hxauYvEgxqZsGMvu8/1j4+Ibg=
|
||||
github.com/blacktop/go-macho v1.1.282/go.mod h1:Hc5E2Lvt/U1VT+jOxr1O5l/LNFJeMYK4eAmDfazTiGc=
|
||||
github.com/blacktop/go-plist v1.0.2 h1:DMX8uBiE308HWZkO9o37j7Z2b0neI3GSzN2caNa2zXk=
|
||||
github.com/blacktop/go-plist v1.0.2/go.mod h1:fqVhCVVXVJWsIGY9QPgdK0mDWZD82HrRMfU5PanvdTA=
|
||||
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
|
||||
github.com/bodgit/plumbing v1.3.0/go.mod h1:JOTb4XiRu5xfnmdnDJo6GmSbSbtSyufrsyZFByMtKEs=
|
||||
github.com/bodgit/sevenzip v1.6.3 h1:t7K1jcgPnXdZyRHr68vq5L9vO/WmjDJEiGUwTR6i6gk=
|
||||
github.com/bodgit/sevenzip v1.6.3/go.mod h1:a29jn+ZL8UfQr/L+8jJT1wmhCMulGOfaT5d1HWxwD5g=
|
||||
github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4=
|
||||
github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM=
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:HFl8GFmwK19hYuXB8OQ0rTO9WOCgZY9JUy964zaYawY=
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:9HlL8SWBRtCZE7sCNq+c3//H/oHywgSwtocmPTdOij8=
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 h1:j59wGsxaBk6aFBuuYofk2oznMGZYyzFovjDqavlJHM8=
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0/go.mod h1:3FrDGTXj08zj6qtqlIvt0vS8eWNrrYpnXOEbcQgFmvM=
|
||||
github.com/byteness/keyring v1.9.0 h1:9m+7pru+JkMJ8wxma5id5m6pSt2Zx/xPj77kyM+yAVE=
|
||||
github.com/byteness/keyring v1.9.0/go.mod h1:a6CV8t/qfEUERPTP+dqeVfKgib2wz3PIYbMWRfmvmes=
|
||||
github.com/byteness/percent v0.2.2 h1:vnIFh8WBR1xoC+U2etz0EMB1cgp+vsK6vynqTCeDziU=
|
||||
github.com/byteness/percent v0.2.2/go.mod h1:nwavge92FhIyfnldz4YWZD8uxPVvdh8NlzLRd1VYRDs=
|
||||
github.com/chengxilo/virtualterm v1.0.4 h1:Z6IpERbRVlfB8WkOmtbHiDbBANU7cimRIof7mk9/PwM=
|
||||
github.com/chengxilo/virtualterm v1.0.4/go.mod h1:DyxxBZz/x1iqJjFxTFcr6/x+jSpqN0iwWCOK1q10rlY=
|
||||
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
|
||||
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/deploymenttheory/go-macos-pkg v0.3.0 h1:1pbCbFpib7lzAdu0FUnCW5frhYtjEmqO1iNg0kIKthI=
|
||||
github.com/deploymenttheory/go-macos-pkg v0.3.0/go.mod h1:aSMBLo4teBpMNx6bioyGfF22Kkdu1dodyWiyn0PLFjg=
|
||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0 h1:LqkkVKAlHFfH9LOEl5fe4p/zL02OhWE7pCufMBG2jLA=
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 h1:idfl8M8rPW93NehFw5H1qqH8yG158t5POr+LX9avbJY=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
|
||||
github.com/ebitengine/purego v0.10.2 h1:W809HbnvzAxgdm+aOvlSekrM16wGCdT/e76+9tS7gzE=
|
||||
github.com/ebitengine/purego v0.10.2/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
|
||||
github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA=
|
||||
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
||||
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
|
||||
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
|
||||
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/go-compressions/lzfse v0.3.0 h1:slxIjY9HeG2llJSoXTwTnQ+u/iKMbr2WHUwaNAl/2yI=
|
||||
github.com/go-compressions/lzfse v0.3.0/go.mod h1:geg9IRFbMNHPgbm8xNwF3AnYTsldTX9YptJ0DOWzYv8=
|
||||
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
|
||||
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
|
||||
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
|
||||
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f h1:Fnl4pzx8SR7k7JuzyW8lEtSFH6EQ8xgcypgIn8pcGIE=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
|
||||
github.com/jpillora/backoff v0.0.0-20180909062703-3050d21c67d7/go.mod h1:2iMrUgbbvHEiQClaW2NsSzMyGHqN+rDFqY705q49KG0=
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a h1:45JtCyuNYE+QN9aPuR1ID9++BQU+NMTMudHSuaK0Las=
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a/go.mod h1:RVHtZuvrpETIepiNUrNlih2OynoFf1eM6DGC6dloXzk=
|
||||
github.com/juju/persistent-cookiejar v1.0.0 h1:Ag7+QLzqC2m+OYXy2QQnRjb3gTkEBSZagZ6QozwT3EQ=
|
||||
github.com/juju/persistent-cookiejar v1.0.0/go.mod h1:zrbmo4nBKaiP/Ez3F67ewkMbzGYfXyMvRtbOfuAwG0w=
|
||||
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
|
||||
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/majd/go-apfs v1.0.29 h1:UogjWvwkvNIcDRjiEQvIpOxrK5PgFo48yRern2mnrVM=
|
||||
github.com/majd/go-apfs v1.0.29/go.mod h1:gA+fjwBmzHsm5ubsWtRJJUdRcu/8qhyuAJ4jFGGNYdk=
|
||||
github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
|
||||
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
|
||||
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/noamcohen97/touchid-go v0.3.0 h1:fcXxVCizysD7KHRR6hrURt3nyNIs5JBGSbOIidD/3wo=
|
||||
github.com/noamcohen97/touchid-go v0.3.0/go.mod h1:X9MRNIBGEmPqwpDm1G3fQOAQX7fwBlhzUbnkDTxuta0=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo/v2 v2.5.0 h1:TRtrvv2vdQqzkwrQ1ke6vtXf7IK34RBUJafIy1wMwls=
|
||||
github.com/onsi/ginkgo/v2 v2.5.0/go.mod h1:Luc4sArBICYCS8THh8v3i3i5CuSZO+RaQRaJoeNwomw=
|
||||
github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/onsi/gomega v1.24.0 h1:+0glovB9Jd6z3VR+ScSwQqXVTIfJcGA9UBM8yzQxhqg=
|
||||
github.com/onsi/gomega v1.24.0/go.mod h1:Z/NWtiqwBrwUt4/2loMmHL63EDLnYHmVbuBpDr2vQAg=
|
||||
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
|
||||
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
|
||||
github.com/pierrec/lz4/v4 v4.1.29 h1:CDQY6qZOLI4DW0Nx6R1vRrifrCeQHnNXkMb0hZWXFjg=
|
||||
github.com/pierrec/lz4/v4 v4.1.29/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a h1:3QH7VyOaaiUHNrA9Se4YQIRkDTCw1EJls9xTUCaCeRM=
|
||||
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a/go.mod h1:4r5QyqhjIWCcK8DO4KMclc5Iknq5qVBAlbYYzAbUScQ=
|
||||
github.com/rogpeppe/fastuuid v1.1.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY=
|
||||
github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/schollz/progressbar/v3 v3.19.1 h1:iv8BgwOvdML/S3p84uBpy/IMigv4U9594vPZYa2EdrU=
|
||||
github.com/schollz/progressbar/v3 v3.19.1/go.mod h1:LFL7jqimKxfhero4K1eCkUr/6R39AgQeiPCJtlTWIW8=
|
||||
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
|
||||
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
|
||||
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
|
||||
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/smartystreets/assertions v1.0.0/go.mod h1:kHHU4qYBaI3q23Pp3VPrmWhuIUrLW/7eUrw0BU5VaoM=
|
||||
github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9/go.mod h1:SnhjPscd9TpLiy1LpzGSKh3bXCfxxXuqd9xmQJy3slM=
|
||||
github.com/smartystreets/gunit v1.0.0/go.mod h1:qwPWnhz6pn0NnRBP++URONOVyNkPyr4SauJk4cUOwJs=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/stangelandcl/ppmd v0.1.0 h1:0gOKtSdWyXxpRW55H/dZ3AgaJqjrtlIrAvsokFwp7ug=
|
||||
github.com/stangelandcl/ppmd v0.1.0/go.mod h1:Rrv7M+/2P5jYr/GMLhBl7Ug3uJ1bUiVzr5LbbaV6xgY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk=
|
||||
github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
|
||||
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
|
||||
github.com/thediveo/enumflag/v2 v2.0.1 h1:2bmWZPD2uSARDsOjXIdLRlNcYBFNF9xX0RNUNF2vKic=
|
||||
github.com/thediveo/enumflag/v2 v2.0.1/go.mod h1:SyxyCNvv0QeRtZ7fjuaUz4FRLC3cWuDiD7QdORU0MGg=
|
||||
github.com/tj/assert v0.0.0-20171129193455-018094318fb0/go.mod h1:mZ9/Rh9oLWpLLDRpvE+3b7gP/C2YyLFYxNmcLnPTMe0=
|
||||
github.com/tj/assert v0.0.3 h1:Df/BlaZ20mq6kuai7f5z2TvPFiwC3xaWJSDQNiIS3Rk=
|
||||
github.com/tj/assert v0.0.3/go.mod h1:Ne6X72Q+TB1AteidzQncjw9PabbMp4PBMZ1k+vd1Pvk=
|
||||
github.com/tj/go-buffer v1.1.0/go.mod h1:iyiJpfFcR2B9sXu7KvjbT9fpM4mOelRSDTbntVj52Uc=
|
||||
github.com/tj/go-elastic v0.0.0-20171221160941-36157cbbebc2/go.mod h1:WjeM0Oo1eNAjXGDx2yma7uG2XoyRZTq1uv3M/o7imD0=
|
||||
github.com/tj/go-kinesis v0.0.0-20171128231115-08b17f58cb1b/go.mod h1:/yhzCV0xPfx6jb1bBgRFjl5lytqVqZXEaeqWP8lTEao=
|
||||
github.com/tj/go-spin v1.1.0/go.mod h1:Mg1mzmePZm4dva8Qz60H2lHwmJ2loum4VIrLgVnKwh4=
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o=
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVKhn2Um6rjCsSsg=
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
|
||||
github.com/ulikunitz/xz v0.5.17 h1:flR0y/x1hgM8EGV1AW3Xll6T413G0glV8UfBwR617V4=
|
||||
github.com/ulikunitz/xz v0.5.17/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw=
|
||||
github.com/vbauerster/mpb/v7 v7.5.3 h1:BkGfmb6nMrrBQDFECR/Q7RkKCw7ylMetCb4079CGs4w=
|
||||
github.com/vbauerster/mpb/v7 v7.5.3/go.mod h1:i+h4QY6lmLvBNK2ah1fSreiw3ajskRlBp9AhY/PnuOE=
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
|
||||
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f h1:ziUVAjmTPwQMBmYR1tbdRFJPtTcQUI12fH9QQjfb0Sw=
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f/go.mod h1:ZRJnO5ZI4zAwMFp+dS1+V6J6MSyAowhRqAE+DPa1Xp0=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=
|
||||
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
|
||||
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220909162455-aba9fc2a8ff2/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
||||
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/errgo.v1 v1.0.1 h1:oQFRXzZ7CkBGdm1XZm/EbQYaYNNEElNBOd09M6cqNso=
|
||||
gopkg.in/errgo.v1 v1.0.1/go.mod h1:3NjfXwocQRYAPTq4/fzX+CwUhPRcR/azYRhj8G+LqMo=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/retry.v1 v1.0.3 h1:a9CArYczAVv6Qs6VGoLMio99GEs7kY9UzSF9+LD+iGs=
|
||||
gopkg.in/retry.v1 v1.0.3/go.mod h1:FJkXmWiMaAo7xB+xhvDF59zhfjDWyzmyAxiT4dB688g=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
howett.net/plist v1.0.1 h1:37GdZ8tP09Q35o9ych3ehygcsL+HqKSwzctveSlarvM=
|
||||
howett.net/plist v1.0.1/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
|
||||
@@ -0,0 +1,641 @@
|
||||
//nolint:wsl // Binary format parsing is clearer when related bounds checks remain adjacent.
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/ecdh"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hkdf"
|
||||
"crypto/hmac"
|
||||
"crypto/hpke"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/go-compressions/lzfse"
|
||||
)
|
||||
|
||||
const (
|
||||
aeaMagic = "AEA1"
|
||||
aeaSymmetricProfile = 1
|
||||
aeaMainKeyInfo = "AEA_AMK"
|
||||
aeaRootKeyInfo = "AEA_RHEK"
|
||||
aeaClusterKeyInfo = "AEA_CK"
|
||||
aeaClusterHeaderKeyInfo = "AEA_CHEK"
|
||||
aeaSegmentKeyInfo = "AEA_SK"
|
||||
aeaLZFSECompression = 'e'
|
||||
aeaSHA256Checksum = 2
|
||||
aeaDecodedSegmentCacheCount = 64
|
||||
maxAEAAuthDataSize = 1 << 20
|
||||
maxFCSKeySize = 64 << 10
|
||||
)
|
||||
|
||||
type aeaHeader struct {
|
||||
Magic [4]byte
|
||||
ProfileAndScryptStrength uint32
|
||||
AuthDataLength uint32
|
||||
}
|
||||
|
||||
type aeaMAC [sha256.Size]byte
|
||||
|
||||
type encryptedAEARootHeader struct {
|
||||
MAC aeaMAC
|
||||
Data [48]byte
|
||||
ClusterMAC aeaMAC
|
||||
}
|
||||
|
||||
type aeaRootHeader struct {
|
||||
FileSize uint64
|
||||
EncryptedSize uint64
|
||||
SegmentSize uint32
|
||||
SegmentsPerCluster uint32
|
||||
Compression uint8
|
||||
Checksum uint8
|
||||
_ [22]byte
|
||||
}
|
||||
|
||||
type aeaHeaderKey struct {
|
||||
MAC aeaMAC
|
||||
Key [32]byte
|
||||
IV [aes.BlockSize]byte
|
||||
}
|
||||
|
||||
type aeaSegmentHeader struct {
|
||||
DecompressedSize uint32
|
||||
CompressedSize uint32
|
||||
Checksum [sha256.Size]byte
|
||||
}
|
||||
|
||||
type aeaSegment struct {
|
||||
inputOffset int64
|
||||
outputOffset int64
|
||||
compressedSize uint32
|
||||
decompressedSize uint32
|
||||
checksum [sha256.Size]byte
|
||||
mac aeaMAC
|
||||
cluster uint32
|
||||
index uint32
|
||||
}
|
||||
|
||||
type aeaReader struct {
|
||||
source io.ReaderAt
|
||||
size int64
|
||||
segmentSize uint32
|
||||
mainKey []byte
|
||||
segments []aeaSegment
|
||||
cache map[int][]byte
|
||||
cacheOrder []int
|
||||
cacheMu sync.Mutex
|
||||
}
|
||||
|
||||
type fcsResponse struct {
|
||||
EncRequest string `json:"enc-request"`
|
||||
WrappedKey string `json:"wrapped-key"`
|
||||
}
|
||||
|
||||
func newAEAReader(ctx context.Context, client *http.Client, source io.ReaderAt, sourceSize int64) (*aeaReader, error) {
|
||||
var header aeaHeader
|
||||
if err := readBinaryAt(source, 0, &header); err != nil {
|
||||
return nil, fmt.Errorf("read AEA header: %w", err)
|
||||
}
|
||||
|
||||
if string(header.Magic[:]) != aeaMagic {
|
||||
return nil, fmt.Errorf("invalid AEA magic %q", header.Magic)
|
||||
}
|
||||
|
||||
if header.ProfileAndScryptStrength&0xffffff != aeaSymmetricProfile {
|
||||
return nil, fmt.Errorf("unsupported AEA profile %d", header.ProfileAndScryptStrength&0xffffff)
|
||||
}
|
||||
|
||||
if header.AuthDataLength > maxAEAAuthDataSize {
|
||||
return nil, fmt.Errorf("AEA authentication data is too large: %d", header.AuthDataLength)
|
||||
}
|
||||
|
||||
headerSize := int64(binary.Size(header))
|
||||
authData := make([]byte, header.AuthDataLength)
|
||||
if _, err := source.ReadAt(authData, headerSize); err != nil {
|
||||
return nil, fmt.Errorf("read AEA authentication data: %w", err)
|
||||
}
|
||||
|
||||
metadata, err := parseAEAMetadata(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
symmetricKey, err := resolveAEASymmetricKey(ctx, client, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mainSaltOffset := headerSize + int64(len(authData))
|
||||
mainSalt := make([]byte, sha256.Size)
|
||||
if _, err := source.ReadAt(mainSalt, mainSaltOffset); err != nil {
|
||||
return nil, fmt.Errorf("read AEA main salt: %w", err)
|
||||
}
|
||||
|
||||
mainKey, err := deriveAEAKey(symmetricKey, mainSalt, binary.LittleEndian.AppendUint32([]byte(aeaMainKeyInfo), header.ProfileAndScryptStrength), len(symmetricKey))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive AEA main key: %w", err)
|
||||
}
|
||||
|
||||
rootOffset := mainSaltOffset + int64(len(mainSalt))
|
||||
|
||||
var encryptedRoot encryptedAEARootHeader
|
||||
if err := readBinaryAt(source, rootOffset, &encryptedRoot); err != nil {
|
||||
return nil, fmt.Errorf("read encrypted AEA root header: %w", err)
|
||||
}
|
||||
|
||||
rootKey, err := deriveAEAHeaderKey(mainKey, []byte(aeaRootKeyInfo))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive AEA root key: %w", err)
|
||||
}
|
||||
|
||||
rootSalt := make([]byte, 0, len(encryptedRoot.ClusterMAC)+len(authData))
|
||||
rootSalt = append(rootSalt, encryptedRoot.ClusterMAC[:]...)
|
||||
rootSalt = append(rootSalt, authData...)
|
||||
computedRootMAC := calculateAEAMAC(rootKey.MAC[:], encryptedRoot.Data[:], rootSalt)
|
||||
if !hmac.Equal(encryptedRoot.MAC[:], computedRootMAC[:]) {
|
||||
return nil, errors.New("AEA root header failed authentication")
|
||||
}
|
||||
|
||||
rootData, err := decryptAEACTR(encryptedRoot.Data[:], rootKey.Key[:], rootKey.IV[:])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt AEA root header: %w", err)
|
||||
}
|
||||
|
||||
var root aeaRootHeader
|
||||
if err := binary.Read(bytes.NewReader(rootData), binary.LittleEndian, &root); err != nil {
|
||||
return nil, fmt.Errorf("decode AEA root header: %w", err)
|
||||
}
|
||||
|
||||
if root.FileSize == 0 || root.FileSize > ^uint64(0)>>1 {
|
||||
return nil, fmt.Errorf("invalid AEA output size %d", root.FileSize)
|
||||
}
|
||||
|
||||
if root.EncryptedSize != uint64(sourceSize) {
|
||||
return nil, fmt.Errorf("AEA encrypted size is %d, expected %d", root.EncryptedSize, sourceSize)
|
||||
}
|
||||
|
||||
if root.SegmentSize == 0 || root.SegmentsPerCluster == 0 {
|
||||
return nil, errors.New("AEA has an invalid segment layout")
|
||||
}
|
||||
|
||||
if root.Compression != aeaLZFSECompression || root.Checksum != aeaSHA256Checksum {
|
||||
return nil, fmt.Errorf("unsupported AEA encoding: compression %q, checksum %d", root.Compression, root.Checksum)
|
||||
}
|
||||
|
||||
reader := &aeaReader{
|
||||
source: source,
|
||||
size: int64(root.FileSize),
|
||||
segmentSize: root.SegmentSize,
|
||||
mainKey: mainKey,
|
||||
segments: make([]aeaSegment, (root.FileSize+uint64(root.SegmentSize)-1)/uint64(root.SegmentSize)),
|
||||
cache: make(map[int][]byte, aeaDecodedSegmentCacheCount),
|
||||
}
|
||||
|
||||
clusterOffset := rootOffset + int64(binary.Size(encryptedRoot))
|
||||
if err := reader.indexClusters(clusterOffset, encryptedRoot.ClusterMAC, root, sourceSize); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return reader, nil
|
||||
}
|
||||
|
||||
func parseAEAMetadata(data []byte) (map[string][]byte, error) {
|
||||
metadata := make(map[string][]byte)
|
||||
reader := bytes.NewReader(data)
|
||||
|
||||
for reader.Len() != 0 {
|
||||
var length uint32
|
||||
if err := binary.Read(reader, binary.LittleEndian, &length); err != nil {
|
||||
return nil, fmt.Errorf("read AEA metadata length: %w", err)
|
||||
}
|
||||
|
||||
if length < 5 || uint64(length-4) > uint64(reader.Len()) {
|
||||
return nil, fmt.Errorf("invalid AEA metadata record length %d", length)
|
||||
}
|
||||
|
||||
record := make([]byte, length-4)
|
||||
if _, err := io.ReadFull(reader, record); err != nil {
|
||||
return nil, fmt.Errorf("read AEA metadata record: %w", err)
|
||||
}
|
||||
|
||||
key, value, ok := bytes.Cut(record, []byte{0})
|
||||
if !ok || len(key) == 0 {
|
||||
return nil, errors.New("invalid AEA metadata record")
|
||||
}
|
||||
|
||||
metadata[string(key)] = value
|
||||
}
|
||||
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
// resolveAEASymmetricKey downloads the Apple-published FCS P-256 private key
|
||||
// identified by the AEA metadata. That key is the HPKE recipient key for this
|
||||
// image's wrapped symmetric key; the unwrapped key is then used to derive the
|
||||
// AES and HMAC keys that decrypt and authenticate the AEA headers and segments.
|
||||
// It is restore-image key material, not a user credential.
|
||||
func resolveAEASymmetricKey(ctx context.Context, client *http.Client, metadata map[string][]byte) ([]byte, error) {
|
||||
keyURLData, ok := metadata["com.apple.wkms.fcs-key-url"]
|
||||
if !ok {
|
||||
return nil, errors.New("AEA metadata does not contain an FCS key URL")
|
||||
}
|
||||
|
||||
keyURL, err := url.Parse(string(keyURLData))
|
||||
if err != nil || keyURL.Scheme != "https" || keyURL.Hostname() != "wkms-public.apple.com" {
|
||||
return nil, fmt.Errorf("invalid Apple FCS key URL %q", keyURLData)
|
||||
}
|
||||
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, keyURL.String(), nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create Apple FCS key request: %w", err)
|
||||
}
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download Apple FCS key: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("download Apple FCS key: server returned %s", response.Status)
|
||||
}
|
||||
|
||||
pemData, err := io.ReadAll(io.LimitReader(response.Body, maxFCSKeySize+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read Apple FCS key: %w", err)
|
||||
}
|
||||
|
||||
if len(pemData) > maxFCSKeySize {
|
||||
return nil, errors.New("apple FCS key response is too large")
|
||||
}
|
||||
|
||||
block, _ := pem.Decode(pemData)
|
||||
if block == nil {
|
||||
return nil, errors.New("apple FCS key response is not PEM encoded")
|
||||
}
|
||||
|
||||
privateKeyValue, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse Apple FCS private key: %w", err)
|
||||
}
|
||||
|
||||
privateKey, ok := privateKeyValue.(*ecdsa.PrivateKey)
|
||||
if !ok || privateKey.Curve != elliptic.P256() {
|
||||
return nil, errors.New("apple FCS key is not a P-256 private key")
|
||||
}
|
||||
|
||||
responseData, ok := metadata["com.apple.wkms.fcs-response"]
|
||||
if !ok {
|
||||
return nil, errors.New("AEA metadata does not contain an FCS response")
|
||||
}
|
||||
|
||||
var wrapped fcsResponse
|
||||
if err := json.Unmarshal(responseData, &wrapped); err != nil {
|
||||
return nil, fmt.Errorf("parse AEA FCS response: %w", err)
|
||||
}
|
||||
|
||||
encapsulation, err := base64.StdEncoding.DecodeString(wrapped.EncRequest)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode AEA FCS encapsulation: %w", err)
|
||||
}
|
||||
|
||||
wrappedKey, err := base64.StdEncoding.DecodeString(wrapped.WrappedKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode AEA wrapped key: %w", err)
|
||||
}
|
||||
|
||||
kem := hpke.DHKEM(ecdh.P256())
|
||||
ecdhPrivateKey, err := privateKey.ECDH()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("convert AEA FCS private key: %w", err)
|
||||
}
|
||||
hpkePrivateKey, err := kem.NewPrivateKey(ecdhPrivateKey.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load AEA FCS private key: %w", err)
|
||||
}
|
||||
|
||||
recipient, err := hpke.NewRecipient(encapsulation, hpkePrivateKey, hpke.HKDFSHA256(), hpke.AES256GCM(), nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initialize AEA FCS recipient: %w", err)
|
||||
}
|
||||
|
||||
symmetricKey, err := recipient.Open(nil, wrappedKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unwrap AEA symmetric key: %w", err)
|
||||
}
|
||||
|
||||
return symmetricKey, nil
|
||||
}
|
||||
|
||||
func (r *aeaReader) indexClusters(offset int64, clusterMAC aeaMAC, root aeaRootHeader, sourceSize int64) error {
|
||||
const segmentHeaderSize = 8 + sha256.Size
|
||||
|
||||
headerSize := int64(segmentHeaderSize*root.SegmentsPerCluster + sha256.Size + sha256.Size*root.SegmentsPerCluster)
|
||||
outputSize := uint64(0)
|
||||
clusterIndex := uint32(0)
|
||||
|
||||
for outputSize < root.FileSize {
|
||||
if offset < 0 || headerSize > sourceSize-offset {
|
||||
return errors.New("AEA cluster header extends beyond the encrypted image")
|
||||
}
|
||||
|
||||
headerData := make([]byte, headerSize)
|
||||
if _, err := r.source.ReadAt(headerData, offset); err != nil {
|
||||
return fmt.Errorf("read AEA cluster %d header: %w", clusterIndex, err)
|
||||
}
|
||||
|
||||
clusterKey, err := deriveAEAKey(r.mainKey, nil, binary.LittleEndian.AppendUint32([]byte(aeaClusterKeyInfo), clusterIndex), len(r.mainKey))
|
||||
if err != nil {
|
||||
return fmt.Errorf("derive AEA cluster %d key: %w", clusterIndex, err)
|
||||
}
|
||||
|
||||
clusterHeaderKey, err := deriveAEAHeaderKey(clusterKey, []byte(aeaClusterHeaderKeyInfo))
|
||||
if err != nil {
|
||||
return fmt.Errorf("derive AEA cluster %d header key: %w", clusterIndex, err)
|
||||
}
|
||||
|
||||
encryptedHeadersSize := int(segmentHeaderSize * root.SegmentsPerCluster)
|
||||
encryptedHeaders := headerData[:encryptedHeadersSize]
|
||||
var nextClusterMAC aeaMAC
|
||||
copy(nextClusterMAC[:], headerData[encryptedHeadersSize:encryptedHeadersSize+sha256.Size])
|
||||
segmentMACData := headerData[encryptedHeadersSize+sha256.Size:]
|
||||
|
||||
hmacSalt := make([]byte, 0, len(nextClusterMAC)+len(segmentMACData))
|
||||
hmacSalt = append(hmacSalt, nextClusterMAC[:]...)
|
||||
hmacSalt = append(hmacSalt, segmentMACData...)
|
||||
computedMAC := calculateAEAMAC(clusterHeaderKey.MAC[:], encryptedHeaders, hmacSalt)
|
||||
if !hmac.Equal(clusterMAC[:], computedMAC[:]) {
|
||||
return fmt.Errorf("AEA cluster %d failed authentication", clusterIndex)
|
||||
}
|
||||
|
||||
decryptedHeaders, err := decryptAEACTR(encryptedHeaders, clusterHeaderKey.Key[:], clusterHeaderKey.IV[:])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decrypt AEA cluster %d headers: %w", clusterIndex, err)
|
||||
}
|
||||
|
||||
dataOffset := offset + headerSize
|
||||
for segmentIndex := range root.SegmentsPerCluster {
|
||||
start := int(segmentIndex) * segmentHeaderSize
|
||||
var segmentHeader aeaSegmentHeader
|
||||
if err := binary.Read(bytes.NewReader(decryptedHeaders[start:start+segmentHeaderSize]), binary.LittleEndian, &segmentHeader); err != nil {
|
||||
return fmt.Errorf("decode AEA cluster %d segment %d header: %w", clusterIndex, segmentIndex, err)
|
||||
}
|
||||
|
||||
if segmentHeader.DecompressedSize == 0 {
|
||||
if segmentHeader.CompressedSize != 0 {
|
||||
return fmt.Errorf("AEA cluster %d segment %d has compressed data without output", clusterIndex, segmentIndex)
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if segmentHeader.DecompressedSize > root.SegmentSize || segmentHeader.CompressedSize == 0 {
|
||||
return fmt.Errorf("AEA cluster %d segment %d has invalid sizes", clusterIndex, segmentIndex)
|
||||
}
|
||||
|
||||
if int64(segmentHeader.CompressedSize) > sourceSize-dataOffset {
|
||||
return fmt.Errorf("AEA cluster %d segment %d extends beyond the encrypted image", clusterIndex, segmentIndex)
|
||||
}
|
||||
|
||||
var segmentMAC aeaMAC
|
||||
copy(segmentMAC[:], segmentMACData[int(segmentIndex)*sha256.Size:(int(segmentIndex)+1)*sha256.Size])
|
||||
|
||||
globalIndex := uint64(clusterIndex)*uint64(root.SegmentsPerCluster) + uint64(segmentIndex)
|
||||
if globalIndex >= uint64(len(r.segments)) {
|
||||
return fmt.Errorf("AEA cluster %d segment %d is outside the declared output", clusterIndex, segmentIndex)
|
||||
}
|
||||
|
||||
outputOffset := int64(globalIndex * uint64(root.SegmentSize))
|
||||
if uint64(outputOffset)+uint64(segmentHeader.DecompressedSize) > root.FileSize {
|
||||
return fmt.Errorf("AEA cluster %d segment %d extends beyond the declared output", clusterIndex, segmentIndex)
|
||||
}
|
||||
|
||||
r.segments[globalIndex] = aeaSegment{
|
||||
inputOffset: dataOffset,
|
||||
outputOffset: outputOffset,
|
||||
compressedSize: segmentHeader.CompressedSize,
|
||||
decompressedSize: segmentHeader.DecompressedSize,
|
||||
checksum: segmentHeader.Checksum,
|
||||
mac: segmentMAC,
|
||||
cluster: clusterIndex,
|
||||
index: segmentIndex,
|
||||
}
|
||||
|
||||
dataOffset += int64(segmentHeader.CompressedSize)
|
||||
outputSize += uint64(segmentHeader.DecompressedSize)
|
||||
if outputSize > root.FileSize {
|
||||
return errors.New("AEA segment data exceeds the declared output size")
|
||||
}
|
||||
}
|
||||
|
||||
offset = dataOffset
|
||||
clusterMAC = nextClusterMAC
|
||||
clusterIndex++
|
||||
}
|
||||
|
||||
if outputSize != root.FileSize {
|
||||
return fmt.Errorf("AEA segment data has size %d, expected %d", outputSize, root.FileSize)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *aeaReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||
if len(data) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if offset < 0 {
|
||||
return 0, errors.New("negative AEA output offset")
|
||||
}
|
||||
|
||||
if offset >= r.size {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
wanted := len(data)
|
||||
if remaining := r.size - offset; int64(wanted) > remaining {
|
||||
wanted = int(remaining)
|
||||
}
|
||||
|
||||
written := 0
|
||||
for written < wanted {
|
||||
segmentIndex := int((offset + int64(written)) / int64(r.segmentSize))
|
||||
if segmentIndex >= len(r.segments) {
|
||||
return written, errors.New("AEA segment index is incomplete")
|
||||
}
|
||||
|
||||
segment := r.segments[segmentIndex]
|
||||
if segment.decompressedSize == 0 {
|
||||
return written, fmt.Errorf("AEA segment %d is missing", segmentIndex)
|
||||
}
|
||||
decoded, err := r.decodeSegment(segmentIndex, segment)
|
||||
if err != nil {
|
||||
return written, err
|
||||
}
|
||||
|
||||
inside := int(offset + int64(written) - segment.outputOffset)
|
||||
if inside < 0 || inside >= len(decoded) {
|
||||
return written, errors.New("AEA segment has an invalid output offset")
|
||||
}
|
||||
|
||||
count := min(wanted-written, len(decoded)-inside)
|
||||
copy(data[written:written+count], decoded[inside:inside+count])
|
||||
written += count
|
||||
}
|
||||
|
||||
if wanted != len(data) {
|
||||
return written, io.EOF
|
||||
}
|
||||
|
||||
return written, nil
|
||||
}
|
||||
|
||||
func (r *aeaReader) decodeSegment(cacheIndex int, segment aeaSegment) ([]byte, error) {
|
||||
r.cacheMu.Lock()
|
||||
defer r.cacheMu.Unlock()
|
||||
|
||||
if data, ok := r.cache[cacheIndex]; ok {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
encrypted := make([]byte, segment.compressedSize)
|
||||
if _, err := r.source.ReadAt(encrypted, segment.inputOffset); err != nil {
|
||||
return nil, fmt.Errorf("read AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
|
||||
}
|
||||
|
||||
clusterKey, err := deriveAEAKey(r.mainKey, nil, binary.LittleEndian.AppendUint32([]byte(aeaClusterKeyInfo), segment.cluster), len(r.mainKey))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive AEA cluster %d key: %w", segment.cluster, err)
|
||||
}
|
||||
|
||||
segmentKey, err := deriveAEAHeaderKey(clusterKey, binary.LittleEndian.AppendUint32([]byte(aeaSegmentKeyInfo), segment.index))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("derive AEA cluster %d segment %d key: %w", segment.cluster, segment.index, err)
|
||||
}
|
||||
|
||||
computedMAC := calculateAEAMAC(segmentKey.MAC[:], encrypted, nil)
|
||||
if !hmac.Equal(segment.mac[:], computedMAC[:]) {
|
||||
return nil, fmt.Errorf("AEA cluster %d segment %d failed authentication", segment.cluster, segment.index)
|
||||
}
|
||||
|
||||
compressed, err := decryptAEACTR(encrypted, segmentKey.Key[:], segmentKey.IV[:])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
|
||||
}
|
||||
|
||||
var decoded []byte
|
||||
if segment.compressedSize == segment.decompressedSize {
|
||||
decoded = compressed
|
||||
} else {
|
||||
decoded, err = lzfse.Decompress(compressed)
|
||||
if err != nil && strings.Contains(err.Error(), "fse: stream too short") {
|
||||
padded, e := padLZFSEStreams(compressed)
|
||||
if e == nil {
|
||||
decoded, err = lzfse.Decompress(padded)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decompress AEA cluster %d segment %d: %w", segment.cluster, segment.index, err)
|
||||
}
|
||||
if len(decoded) != int(segment.decompressedSize) {
|
||||
return nil, fmt.Errorf("decompress AEA cluster %d segment %d: produced %d bytes, expected %d", segment.cluster, segment.index, len(decoded), segment.decompressedSize)
|
||||
}
|
||||
}
|
||||
|
||||
if sha256.Sum256(decoded) != segment.checksum {
|
||||
return nil, fmt.Errorf("AEA cluster %d segment %d failed checksum verification", segment.cluster, segment.index)
|
||||
}
|
||||
|
||||
if len(r.cacheOrder) == aeaDecodedSegmentCacheCount {
|
||||
delete(r.cache, r.cacheOrder[0])
|
||||
copy(r.cacheOrder, r.cacheOrder[1:])
|
||||
r.cacheOrder = r.cacheOrder[:len(r.cacheOrder)-1]
|
||||
}
|
||||
|
||||
r.cache[cacheIndex] = decoded
|
||||
r.cacheOrder = append(r.cacheOrder, cacheIndex)
|
||||
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
func deriveAEAKey(key, salt, info []byte, size int) ([]byte, error) {
|
||||
derived, err := hkdf.Key(sha256.New, key, salt, string(info), size)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("expand AEA key: %w", err)
|
||||
}
|
||||
|
||||
return derived, nil
|
||||
}
|
||||
|
||||
func deriveAEAHeaderKey(key, info []byte) (aeaHeaderKey, error) {
|
||||
var headerKey aeaHeaderKey
|
||||
derived, err := deriveAEAKey(key, nil, info, binary.Size(headerKey))
|
||||
if err != nil {
|
||||
return aeaHeaderKey{}, fmt.Errorf("derive AEA header key: %w", err)
|
||||
}
|
||||
|
||||
if err := binary.Read(bytes.NewReader(derived), binary.LittleEndian, &headerKey); err != nil {
|
||||
return aeaHeaderKey{}, fmt.Errorf("decode AEA header key: %w", err)
|
||||
}
|
||||
|
||||
return headerKey, nil
|
||||
}
|
||||
|
||||
func calculateAEAMAC(key, data, salt []byte) aeaMAC {
|
||||
mac := hmac.New(sha256.New, key)
|
||||
_, _ = mac.Write(salt)
|
||||
_, _ = mac.Write(data)
|
||||
|
||||
var length [8]byte
|
||||
binary.LittleEndian.PutUint64(length[:], uint64(len(salt)))
|
||||
_, _ = mac.Write(length[:])
|
||||
|
||||
return aeaMAC(mac.Sum(nil))
|
||||
}
|
||||
|
||||
func decryptAEACTR(data, key, iv []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initialize AEA cipher: %w", err)
|
||||
}
|
||||
|
||||
decrypted := make([]byte, len(data))
|
||||
cipher.NewCTR(block, iv).XORKeyStream(decrypted, data)
|
||||
|
||||
return decrypted, nil
|
||||
}
|
||||
|
||||
func readBinaryAt(source io.ReaderAt, offset int64, value any) error {
|
||||
size := binary.Size(value)
|
||||
if size < 0 {
|
||||
return errors.New("invalid binary value")
|
||||
}
|
||||
|
||||
data := make([]byte, size)
|
||||
if _, err := source.ReadAt(data, offset); err != nil {
|
||||
return fmt.Errorf("read binary value: %w", err)
|
||||
}
|
||||
|
||||
if err := binary.Read(bytes.NewReader(data), binary.LittleEndian, value); err != nil {
|
||||
return fmt.Errorf("decode binary value: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,872 @@
|
||||
//nolint:wsl // Binary tree traversal is clearer when related bounds checks remain adjacent.
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/deploymenttheory/go-macos-pkg/pkg/lzbitmap"
|
||||
"github.com/go-compressions/lzfse"
|
||||
"github.com/majd/go-apfs"
|
||||
"github.com/majd/go-apfs/pkg/disk"
|
||||
"github.com/majd/go-apfs/pkg/disk/dmg"
|
||||
"github.com/majd/go-apfs/types"
|
||||
"github.com/majd/ipatool/v2/internal/sap/machimage"
|
||||
)
|
||||
|
||||
const (
|
||||
apfsObjectHeaderSize = 32
|
||||
apfsObjectTypeBTree = 2
|
||||
apfsObjectTypeNode = 3
|
||||
apfsObjectTypeFSTree = 14
|
||||
apfsObjectNoHeader = 0x20000000
|
||||
apfsNodeRoot = 0x0001
|
||||
apfsNodeNoHeader = 0x0010
|
||||
apfsBlockSize = 4096
|
||||
apfsMaximumTreeDepth = 32
|
||||
decmpfsLZVN = 8
|
||||
decmpfsLZFSE = 12
|
||||
decmpfsLZBitmap = 14
|
||||
decmpfsBlockSize = 64 << 10
|
||||
)
|
||||
|
||||
type apfsExtractor struct {
|
||||
device disk.Device
|
||||
filesystem *apfs.APFS
|
||||
volumeOMap types.BTreeNodePhys
|
||||
rootTreeBase uint64
|
||||
transactionID types.XidT
|
||||
}
|
||||
|
||||
type apfsExtent struct {
|
||||
logical uint64
|
||||
physical uint64
|
||||
length uint64
|
||||
}
|
||||
|
||||
type apfsFile struct {
|
||||
io.ReaderAt
|
||||
size int64
|
||||
}
|
||||
|
||||
func extractAPFSFiles(ctx context.Context, source io.ReaderAt, size int64, paths []string, destination string) error {
|
||||
extractor, closeExtractor, err := newAPFSExtractor(source, size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = closeExtractor() }()
|
||||
|
||||
if err := os.MkdirAll(destination, 0o700); err != nil {
|
||||
return fmt.Errorf("create Apple filesystem extraction directory: %w", err)
|
||||
}
|
||||
|
||||
for _, path := range paths {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return fmt.Errorf("extract Apple filesystem files: %w", err)
|
||||
}
|
||||
if err := extractor.extractImageFile(ctx, path, destination, filepath.Ext(path) != ".icxs"); err != nil {
|
||||
return fmt.Errorf("extract %s from Apple filesystem: %w", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func newAPFSExtractor(source io.ReaderAt, size int64) (*apfsExtractor, func() error, error) {
|
||||
device, closeDevice, err := openAPFSDevice(source, size)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
filesystem, err := apfs.NewAPFS(device)
|
||||
if err != nil {
|
||||
_ = closeDevice()
|
||||
|
||||
return nil, nil, fmt.Errorf("open Apple filesystem: %w", err)
|
||||
}
|
||||
fail := func(err error) (*apfsExtractor, func() error, error) {
|
||||
filesystem.Close()
|
||||
_ = closeDevice()
|
||||
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
volumeOMap, ok := filesystem.Volume.OMap.Body.(types.OMap)
|
||||
if !ok {
|
||||
return fail(fmt.Errorf("apple filesystem volume has an invalid object map"))
|
||||
}
|
||||
if volumeOMap.Tree == nil {
|
||||
return fail(fmt.Errorf("apple filesystem volume has no object-map tree"))
|
||||
}
|
||||
volumeOMapRoot, ok := volumeOMap.Tree.Body.(types.BTreeNodePhys)
|
||||
if !ok {
|
||||
return fail(fmt.Errorf("apple filesystem volume has an invalid object-map tree"))
|
||||
}
|
||||
|
||||
extractor := &apfsExtractor{
|
||||
device: device,
|
||||
filesystem: filesystem,
|
||||
volumeOMap: volumeOMapRoot,
|
||||
rootTreeBase: uint64(filesystem.Volume.RootTreeOid),
|
||||
transactionID: filesystem.Volume.OMap.Hdr.Xid,
|
||||
}
|
||||
closeExtractor := func() error {
|
||||
filesystem.Close()
|
||||
|
||||
return closeDevice()
|
||||
}
|
||||
|
||||
return extractor, closeExtractor, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) extractImageFile(ctx context.Context, path, destination string, thin bool) (err error) {
|
||||
file, err := e.openFile(ctx, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
outputPath := filepath.Join(destination, filepath.Base(path))
|
||||
output, err := os.OpenFile(outputPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create output: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := output.Close(); err == nil && closeErr != nil {
|
||||
err = fmt.Errorf("close output: %w", closeErr)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
_ = os.Remove(outputPath)
|
||||
}
|
||||
}()
|
||||
|
||||
offset, size := int64(0), file.size
|
||||
if thin {
|
||||
offset, size, err = machimage.ARM64Range(file, file.size)
|
||||
if err != nil {
|
||||
return fmt.Errorf("select runtime image architecture: %w", err)
|
||||
}
|
||||
}
|
||||
reader := &contextReader{ctx: ctx, reader: io.NewSectionReader(file, offset, size)}
|
||||
if _, err := io.CopyN(output, reader, size); err != nil {
|
||||
return fmt.Errorf("copy file data: %w", err)
|
||||
}
|
||||
|
||||
if err := output.Sync(); err != nil {
|
||||
return fmt.Errorf("sync output: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) openFile(ctx context.Context, path string) (*apfsFile, error) {
|
||||
records, err := e.resolvePath(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var inode *types.JInodeVal
|
||||
var compression *types.DecmpfsDiskHeader
|
||||
var resource *types.JXattrDstreamT
|
||||
var extents []apfsExtent
|
||||
for _, record := range records {
|
||||
switch record.Hdr.GetType() {
|
||||
case types.APFS_TYPE_INODE:
|
||||
value, ok := record.Val.(types.JInodeVal)
|
||||
if ok {
|
||||
inode = &value
|
||||
}
|
||||
case types.APFS_TYPE_FILE_EXTENT:
|
||||
key, keyOK := record.Key.(types.JFileExtentKeyT)
|
||||
value, valueOK := record.Val.(types.JFileExtentValT)
|
||||
if keyOK && valueOK {
|
||||
extents = append(extents, apfsExtent{
|
||||
logical: key.LogicalAddr,
|
||||
physical: value.PhysBlockNum,
|
||||
length: value.Length(),
|
||||
})
|
||||
}
|
||||
case types.APFS_TYPE_XATTR:
|
||||
key, keyOK := record.Key.(types.JXattrKeyT)
|
||||
value, valueOK := record.Val.(types.JXattrValT)
|
||||
if !keyOK || !valueOK {
|
||||
continue
|
||||
}
|
||||
|
||||
switch key.Name {
|
||||
case types.DECMPFS_XATTR_NAME:
|
||||
compression, err = types.GetDecmpfsHeader(record)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read compression metadata: %w", err)
|
||||
}
|
||||
case "com.apple.ResourceFork":
|
||||
stream, ok := value.Data.(types.JXattrDstreamT)
|
||||
if ok {
|
||||
resource = &stream
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if inode == nil {
|
||||
return nil, fmt.Errorf("file has no inode record")
|
||||
}
|
||||
|
||||
if compression != nil {
|
||||
method := uint32(compression.CompressionType)
|
||||
if method != decmpfsLZVN && method != decmpfsLZFSE && method != decmpfsLZBitmap {
|
||||
return nil, fmt.Errorf("unsupported compression type %d", compression.CompressionType)
|
||||
}
|
||||
if resource == nil {
|
||||
return nil, fmt.Errorf("compressed file has no resource fork")
|
||||
}
|
||||
|
||||
extents, err = e.dataExtents(resource.XattrObjID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read resource-fork extents: %w", err)
|
||||
}
|
||||
resourceReader, err := newAPFSExtentReader(e.device, extents, resource.DStream.Size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reader, err := newDecmpfsReader(ctx, resourceReader, resource.DStream.Size, compression.UncompressedSize, method)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &apfsFile{ReaderAt: reader, size: int64(compression.UncompressedSize)}, nil
|
||||
}
|
||||
|
||||
size := inode.UncompressedSize
|
||||
for _, field := range inode.Xfields {
|
||||
if stream, ok := field.Field.(types.JDstreamT); ok {
|
||||
size = stream.Size
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(extents) == 0 && size != 0 {
|
||||
extents, err = e.dataExtents(inode.PrivateID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read file extents: %w", err)
|
||||
}
|
||||
}
|
||||
reader, err := newAPFSExtentReader(e.device, extents, size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &apfsFile{ReaderAt: reader, size: int64(size)}, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) resolvePath(path string) ([]types.NodeEntry, error) {
|
||||
objectID := uint64(types.FSROOT_OID)
|
||||
for _, name := range strings.Split(strings.Trim(path, "/"), "/") {
|
||||
records, err := e.recordsForObject(objectID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, record := range records {
|
||||
if record.Hdr.GetType() != types.APFS_TYPE_DIR_REC {
|
||||
continue
|
||||
}
|
||||
key, keyOK := record.Key.(types.JDrecHashedKeyT)
|
||||
value, valueOK := record.Val.(types.JDrecVal)
|
||||
if keyOK && valueOK && key.Name == name {
|
||||
objectID = value.FileID
|
||||
found = true
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, fmt.Errorf("path component %q was not found", name)
|
||||
}
|
||||
}
|
||||
|
||||
return e.recordsForObject(objectID)
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) recordsForObject(objectID uint64) ([]types.NodeEntry, error) {
|
||||
visited := make(map[uint64]struct{})
|
||||
|
||||
return e.collectRecords(e.filesystem.FSRootBtree, objectID, visited, 0)
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) collectRecords(node types.BTreeNodePhys, objectID uint64, visited map[uint64]struct{}, depth int) ([]types.NodeEntry, error) {
|
||||
if depth > apfsMaximumTreeDepth {
|
||||
return nil, fmt.Errorf("filesystem tree exceeds maximum depth")
|
||||
}
|
||||
if node.IsLeaf() {
|
||||
var records []types.NodeEntry
|
||||
for _, raw := range node.Entries {
|
||||
record, ok := raw.(types.NodeEntry)
|
||||
if ok && record.Hdr.GetID() == objectID {
|
||||
records = append(records, record)
|
||||
}
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
var records []types.NodeEntry
|
||||
for index, raw := range node.Entries {
|
||||
entry, ok := raw.(types.NodeEntry)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("filesystem tree contains an invalid index entry")
|
||||
}
|
||||
lower := entry.Hdr.GetID()
|
||||
upper := ^uint64(0)
|
||||
if index+1 < len(node.Entries) {
|
||||
next, ok := node.Entries[index+1].(types.NodeEntry)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("filesystem tree contains an invalid index entry")
|
||||
}
|
||||
upper = next.Hdr.GetID()
|
||||
}
|
||||
if objectID < lower || objectID > upper {
|
||||
continue
|
||||
}
|
||||
|
||||
child, address, err := e.filesystemChild(entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, seen := visited[address]; seen {
|
||||
continue
|
||||
}
|
||||
visited[address] = struct{}{}
|
||||
childRecords, err := e.collectRecords(child, objectID, visited, depth+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
records = append(records, childRecords...)
|
||||
}
|
||||
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) filesystemChild(entry types.NodeEntry) (types.BTreeNodePhys, uint64, error) {
|
||||
var objectID types.OidT
|
||||
var expectedHash *[sha256.Size]byte
|
||||
switch value := entry.Val.(type) {
|
||||
case types.BTreeNodeIndexNodeValT:
|
||||
objectID = types.OidT(e.rootTreeBase + uint64(value.ChildOid))
|
||||
expectedHash = &value.ChildHash
|
||||
case uint64:
|
||||
objectID = types.OidT(value)
|
||||
default:
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("sealed filesystem tree contains an invalid child reference")
|
||||
}
|
||||
|
||||
mapping, err := e.volumeOMap.GetOMapEntry(e.device, objectID, e.transactionID)
|
||||
if err != nil {
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("resolve filesystem child %#x: %w", objectID, err)
|
||||
}
|
||||
|
||||
if expectedHash != nil {
|
||||
raw := make([]byte, apfsBlockSize)
|
||||
if _, err := readAPFSBlock(e.device, raw, mapping.Val.Paddr); err != nil {
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("read filesystem child %#x: %w", objectID, err)
|
||||
}
|
||||
if digest := sha256.Sum256(raw); digest != *expectedHash {
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("filesystem child %#x failed SHA-256 verification", objectID)
|
||||
}
|
||||
}
|
||||
|
||||
object, err := types.ReadObj(e.device, mapping.Val.Paddr)
|
||||
if err != nil {
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("decode filesystem child %#x: %w", objectID, err)
|
||||
}
|
||||
child, ok := object.Body.(types.BTreeNodePhys)
|
||||
if !ok {
|
||||
return types.BTreeNodePhys{}, 0, fmt.Errorf("filesystem child %#x is not a tree node", objectID)
|
||||
}
|
||||
|
||||
return child, mapping.Val.Paddr, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) physicalExtents(objectID uint64) ([]apfsExtent, error) {
|
||||
object, err := types.ReadObj(e.device, uint64(e.filesystem.Volume.FextTreeOid))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read physical extent tree: %w", err)
|
||||
}
|
||||
root, ok := object.Body.(types.BTreeNodePhys)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("physical extent tree root is not a tree node")
|
||||
}
|
||||
|
||||
extents, err := e.collectPhysicalExtents(root, objectID, make(map[uint64]struct{}), 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.Slice(extents, func(i, j int) bool { return extents[i].logical < extents[j].logical })
|
||||
|
||||
return extents, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) dataExtents(objectID uint64) ([]apfsExtent, error) {
|
||||
if e.filesystem.Volume.FextTreeOid != 0 {
|
||||
return e.physicalExtents(objectID)
|
||||
}
|
||||
|
||||
records, err := e.recordsForObject(objectID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var extents []apfsExtent
|
||||
for _, record := range records {
|
||||
if record.Hdr.GetType() != types.APFS_TYPE_FILE_EXTENT {
|
||||
continue
|
||||
}
|
||||
key, keyOK := record.Key.(types.JFileExtentKeyT)
|
||||
value, valueOK := record.Val.(types.JFileExtentValT)
|
||||
if keyOK && valueOK {
|
||||
extents = append(extents, apfsExtent{
|
||||
logical: key.LogicalAddr,
|
||||
physical: value.PhysBlockNum,
|
||||
length: value.Length(),
|
||||
})
|
||||
}
|
||||
}
|
||||
sort.Slice(extents, func(i, j int) bool { return extents[i].logical < extents[j].logical })
|
||||
|
||||
return extents, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) collectPhysicalExtents(node types.BTreeNodePhys, objectID uint64, visited map[uint64]struct{}, depth int) ([]apfsExtent, error) {
|
||||
if depth > apfsMaximumTreeDepth {
|
||||
return nil, fmt.Errorf("physical extent tree exceeds maximum depth")
|
||||
}
|
||||
if node.IsLeaf() {
|
||||
var extents []apfsExtent
|
||||
for _, raw := range node.Entries {
|
||||
entry, ok := raw.(types.FextNodeEntry)
|
||||
if ok && entry.Key.PrivateID == objectID {
|
||||
extents = append(extents, apfsExtent{
|
||||
logical: entry.Key.LogicalAddr,
|
||||
physical: entry.Val.PhysBlockNum,
|
||||
length: entry.Val.Length(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return extents, nil
|
||||
}
|
||||
|
||||
var extents []apfsExtent
|
||||
for index, raw := range node.Entries {
|
||||
entry, ok := raw.(types.OMapNodeEntry)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("physical extent tree contains an invalid index entry")
|
||||
}
|
||||
lower := uint64(entry.Key.Oid)
|
||||
upper := ^uint64(0)
|
||||
if index+1 < len(node.Entries) {
|
||||
next, ok := node.Entries[index+1].(types.OMapNodeEntry)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("physical extent tree contains an invalid index entry")
|
||||
}
|
||||
upper = uint64(next.Key.Oid)
|
||||
}
|
||||
if objectID < lower || objectID > upper {
|
||||
continue
|
||||
}
|
||||
if _, seen := visited[entry.PAddr]; seen {
|
||||
continue
|
||||
}
|
||||
visited[entry.PAddr] = struct{}{}
|
||||
|
||||
object, err := types.ReadObj(e.device, entry.PAddr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read physical extent child %#x: %w", entry.PAddr, err)
|
||||
}
|
||||
child, ok := object.Body.(types.BTreeNodePhys)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("physical extent child %#x is not a tree node", entry.PAddr)
|
||||
}
|
||||
childExtents, err := e.collectPhysicalExtents(child, objectID, visited, depth+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
extents = append(extents, childExtents...)
|
||||
}
|
||||
|
||||
return extents, nil
|
||||
}
|
||||
|
||||
func readAPFSBlock(device disk.Device, data []byte, physicalAddress uint64) (int, error) {
|
||||
var count int
|
||||
var err error
|
||||
if raw, ok := device.(*readerDevice); ok {
|
||||
count, err = raw.source.ReadAt(data, int64(physicalAddress*apfsBlockSize))
|
||||
} else {
|
||||
count, err = device.ReadAt(data, int64(physicalAddress*apfsBlockSize))
|
||||
}
|
||||
if err != nil {
|
||||
return count, fmt.Errorf("read Apple filesystem block: %w", err)
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
type apfsExtentReader struct {
|
||||
device disk.Device
|
||||
extents []apfsExtent
|
||||
size uint64
|
||||
}
|
||||
|
||||
func newAPFSExtentReader(device disk.Device, extents []apfsExtent, size uint64) (*apfsExtentReader, error) {
|
||||
if size > math.MaxInt64 {
|
||||
return nil, fmt.Errorf("file size %d exceeds the supported maximum", size)
|
||||
}
|
||||
|
||||
sort.Slice(extents, func(i, j int) bool { return extents[i].logical < extents[j].logical })
|
||||
position := uint64(0)
|
||||
for _, extent := range extents {
|
||||
if extent.length == 0 || extent.logical != position || extent.physical > ^uint64(0)/apfsBlockSize {
|
||||
return nil, fmt.Errorf("file has invalid or sparse physical extents")
|
||||
}
|
||||
physicalOffset := extent.physical * apfsBlockSize
|
||||
if physicalOffset > device.GetSize() || extent.length > device.GetSize()-physicalOffset {
|
||||
return nil, fmt.Errorf("file extent exceeds the Apple filesystem image")
|
||||
}
|
||||
position += extent.length
|
||||
if position < extent.logical {
|
||||
return nil, fmt.Errorf("file extent length overflows")
|
||||
}
|
||||
}
|
||||
if position < size {
|
||||
return nil, fmt.Errorf("file extents cover %d bytes, expected %d", position, size)
|
||||
}
|
||||
|
||||
return &apfsExtentReader{device: device, extents: extents, size: size}, nil
|
||||
}
|
||||
|
||||
func (r *apfsExtentReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||
if offset < 0 {
|
||||
return 0, fmt.Errorf("negative file offset")
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
position := uint64(offset)
|
||||
if position >= r.size {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
written := 0
|
||||
for written < len(data) && position < r.size {
|
||||
index := sort.Search(len(r.extents), func(index int) bool {
|
||||
extent := r.extents[index]
|
||||
|
||||
return extent.logical+extent.length > position
|
||||
})
|
||||
if index == len(r.extents) || position < r.extents[index].logical {
|
||||
return written, io.ErrUnexpectedEOF
|
||||
}
|
||||
extent := r.extents[index]
|
||||
available := min(extent.logical+extent.length-position, r.size-position)
|
||||
count := min(uint64(len(data)-written), available)
|
||||
physicalOffset := extent.physical*apfsBlockSize + position - extent.logical
|
||||
n, err := r.device.ReadAt(data[written:written+int(count)], int64(physicalOffset))
|
||||
written += n
|
||||
position += uint64(n)
|
||||
if err != nil {
|
||||
return written, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
if n != int(count) {
|
||||
return written, io.ErrUnexpectedEOF
|
||||
}
|
||||
}
|
||||
if written != len(data) {
|
||||
return written, io.EOF
|
||||
}
|
||||
|
||||
return written, nil
|
||||
}
|
||||
|
||||
type decmpfsReader struct {
|
||||
ctx context.Context
|
||||
source io.ReaderAt
|
||||
outputSize uint64
|
||||
method uint32
|
||||
offsets []uint32
|
||||
mu sync.Mutex
|
||||
cache map[uint64][]byte
|
||||
cacheOrder []uint64
|
||||
}
|
||||
|
||||
func newDecmpfsReader(ctx context.Context, source io.ReaderAt, sourceSize, outputSize uint64, method uint32) (*decmpfsReader, error) {
|
||||
if outputSize > math.MaxInt64 {
|
||||
return nil, fmt.Errorf("compressed file size %d exceeds the supported maximum", outputSize)
|
||||
}
|
||||
if sourceSize < 8 {
|
||||
return nil, fmt.Errorf("compressed resource fork is too small")
|
||||
}
|
||||
|
||||
var first [4]byte
|
||||
if _, err := source.ReadAt(first[:], 0); err != nil {
|
||||
return nil, fmt.Errorf("read compression index: %w", err)
|
||||
}
|
||||
tableSize := uint64(binary.LittleEndian.Uint32(first[:]))
|
||||
blockCount := (outputSize + decmpfsBlockSize - 1) / decmpfsBlockSize
|
||||
expectedTableSize := (blockCount + 1) * 4
|
||||
if tableSize != expectedTableSize || tableSize > sourceSize {
|
||||
return nil, fmt.Errorf("compression index has size %d, expected %d", tableSize, expectedTableSize)
|
||||
}
|
||||
|
||||
table := make([]byte, tableSize)
|
||||
if _, err := source.ReadAt(table, 0); err != nil {
|
||||
return nil, fmt.Errorf("read compression index: %w", err)
|
||||
}
|
||||
offsets := make([]uint32, blockCount+1)
|
||||
for index := range offsets {
|
||||
offsets[index] = binary.LittleEndian.Uint32(table[index*4:])
|
||||
}
|
||||
for index := uint64(0); index < blockCount; index++ {
|
||||
start, end := uint64(offsets[index]), uint64(offsets[index+1])
|
||||
if start < tableSize || end <= start || end > sourceSize || end-start > decmpfsBlockSize+1 {
|
||||
return nil, fmt.Errorf("compressed block %d has invalid range %d..%d", index, start, end)
|
||||
}
|
||||
}
|
||||
if uint64(offsets[len(offsets)-1]) != sourceSize {
|
||||
return nil, fmt.Errorf("compressed blocks end at %d, expected %d", offsets[len(offsets)-1], sourceSize)
|
||||
}
|
||||
|
||||
return &decmpfsReader{
|
||||
ctx: ctx,
|
||||
source: source,
|
||||
outputSize: outputSize,
|
||||
method: method,
|
||||
offsets: offsets,
|
||||
cache: make(map[uint64][]byte),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *decmpfsReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||
if offset < 0 {
|
||||
return 0, fmt.Errorf("negative compressed file offset")
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err //nolint:wrapcheck // ReaderAt must preserve context cancellation.
|
||||
}
|
||||
position := uint64(offset)
|
||||
if position >= r.outputSize {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
wanted := len(data)
|
||||
if remaining := r.outputSize - position; uint64(wanted) > remaining {
|
||||
wanted = int(remaining)
|
||||
}
|
||||
written := 0
|
||||
for written < wanted {
|
||||
blockIndex := position / decmpfsBlockSize
|
||||
block, err := r.block(blockIndex)
|
||||
if err != nil {
|
||||
return written, err
|
||||
}
|
||||
blockOffset := position % decmpfsBlockSize
|
||||
count := min(wanted-written, len(block)-int(blockOffset))
|
||||
copy(data[written:written+count], block[blockOffset:uint64(count)+blockOffset])
|
||||
written += count
|
||||
position += uint64(count)
|
||||
}
|
||||
if written != len(data) {
|
||||
return written, io.EOF
|
||||
}
|
||||
|
||||
return written, nil
|
||||
}
|
||||
|
||||
func (r *decmpfsReader) block(index uint64) ([]byte, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
if block, ok := r.cache[index]; ok {
|
||||
return block, nil
|
||||
}
|
||||
if index+1 >= uint64(len(r.offsets)) {
|
||||
return nil, io.EOF
|
||||
}
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("read compressed file: %w", err)
|
||||
}
|
||||
|
||||
start, end := uint64(r.offsets[index]), uint64(r.offsets[index+1])
|
||||
compressed := make([]byte, end-start)
|
||||
if _, err := r.source.ReadAt(compressed, int64(start)); err != nil {
|
||||
return nil, fmt.Errorf("read compressed block %d: %w", index, err)
|
||||
}
|
||||
expected := min(uint64(decmpfsBlockSize), r.outputSize-index*decmpfsBlockSize)
|
||||
plain, err := decompressBlock(compressed, r.method, int(expected))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode compressed block %d: %w", index, err)
|
||||
}
|
||||
if uint64(len(plain)) != expected {
|
||||
return nil, fmt.Errorf("decompressed block %d has size %d, expected %d", index, len(plain), expected)
|
||||
}
|
||||
|
||||
const maximumCachedBlocks = 128
|
||||
if len(r.cacheOrder) == maximumCachedBlocks {
|
||||
delete(r.cache, r.cacheOrder[0])
|
||||
r.cacheOrder = r.cacheOrder[1:]
|
||||
}
|
||||
r.cache[index] = plain
|
||||
r.cacheOrder = append(r.cacheOrder, index)
|
||||
|
||||
return plain, nil
|
||||
}
|
||||
|
||||
func decompressBlock(compressed []byte, method uint32, maximumSize int) ([]byte, error) {
|
||||
switch method {
|
||||
case decmpfsLZVN:
|
||||
if compressed[0] == 0x06 {
|
||||
return compressed[1:], nil
|
||||
}
|
||||
|
||||
decoded, err := lzfse.DecompressLZVN(compressed, maximumSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decompress LZVN block: %w", err)
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
case decmpfsLZFSE:
|
||||
if compressed[0] != 'b' {
|
||||
return compressed[1:], nil
|
||||
}
|
||||
|
||||
decoded, err := lzfse.Decompress(compressed)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decompress LZFSE block: %w", err)
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
case decmpfsLZBitmap:
|
||||
if compressed[0] == 0xff {
|
||||
return compressed[1:], nil
|
||||
}
|
||||
|
||||
decoded, err := lzbitmap.Decompress(compressed)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decompress LZBITMAP block: %w", err)
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported compression type %d", method)
|
||||
}
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
ctx context.Context
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func (r *contextReader) Read(data []byte) (int, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err //nolint:wrapcheck // Preserve context cancellation for io.CopyN.
|
||||
}
|
||||
|
||||
return r.reader.Read(data) //nolint:wrapcheck // Reader adapters must preserve io.EOF.
|
||||
}
|
||||
|
||||
func openAPFSDevice(source io.ReaderAt, size int64) (disk.Device, func() error, error) {
|
||||
if size < 36 {
|
||||
return nil, nil, fmt.Errorf("apple filesystem image is too small: %d", size)
|
||||
}
|
||||
|
||||
header := make([]byte, 36)
|
||||
if _, err := source.ReadAt(header, 0); err != nil {
|
||||
return nil, nil, fmt.Errorf("read Apple filesystem header: %w", err)
|
||||
}
|
||||
|
||||
if bytes.Equal(header[32:36], []byte("NXSB")) {
|
||||
device := &readerDevice{source: source, size: uint64(size)}
|
||||
|
||||
return device, device.Close, nil
|
||||
}
|
||||
|
||||
image, err := dmg.NewDMG(io.NewSectionReader(source, 0, size))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("open Apple disk image: %w", err)
|
||||
}
|
||||
|
||||
return image, image.Close, nil
|
||||
}
|
||||
|
||||
type readerDevice struct {
|
||||
source io.ReaderAt
|
||||
size uint64
|
||||
}
|
||||
|
||||
func (d *readerDevice) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *readerDevice) ReadFile(writer *bufio.Writer, offset, length int64) error {
|
||||
if offset < 0 || length < 0 || uint64(offset) > d.size || uint64(length) > d.size-uint64(offset) {
|
||||
return fmt.Errorf("invalid Apple filesystem range %d+%d", offset, length)
|
||||
}
|
||||
|
||||
if _, err := io.CopyN(writer, io.NewSectionReader(d.source, offset, length), length); err != nil {
|
||||
return fmt.Errorf("copy Apple filesystem range: %w", err)
|
||||
}
|
||||
|
||||
if err := writer.Flush(); err != nil {
|
||||
return fmt.Errorf("flush Apple filesystem range: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *readerDevice) GetSize() uint64 {
|
||||
return d.size
|
||||
}
|
||||
|
||||
func (d *readerDevice) ReadAt(data []byte, offset int64) (int, error) {
|
||||
count, err := d.source.ReadAt(data, offset)
|
||||
if count != len(data) || len(data) != int(types.BLOCK_SIZE) || offset%int64(types.BLOCK_SIZE) != 0 {
|
||||
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
|
||||
if !bytes.Equal(data[:apfsObjectHeaderSize], make([]byte, apfsObjectHeaderSize)) {
|
||||
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
|
||||
flags := binary.LittleEndian.Uint16(data[apfsObjectHeaderSize:])
|
||||
if flags&apfsNodeNoHeader == 0 {
|
||||
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
|
||||
objectType := uint32(apfsObjectTypeNode)
|
||||
if flags&apfsNodeRoot != 0 {
|
||||
objectType = apfsObjectTypeBTree
|
||||
}
|
||||
|
||||
// Sealed APFS tree nodes omit the normal object header. Add a synthetic
|
||||
// header after their hash has been verified so go-apfs can decode them.
|
||||
binary.LittleEndian.PutUint64(data[8:16], uint64(offset/int64(types.BLOCK_SIZE)))
|
||||
binary.LittleEndian.PutUint32(data[24:28], apfsObjectNoHeader|objectType)
|
||||
binary.LittleEndian.PutUint32(data[28:32], apfsObjectTypeFSTree)
|
||||
binary.LittleEndian.PutUint64(data[:8], types.CreateChecksum(data))
|
||||
|
||||
return count, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/machimage"
|
||||
)
|
||||
|
||||
const (
|
||||
macOSVersion = "27.0.1"
|
||||
macOSBuild = "26A434"
|
||||
macOSRestoreURL = "https://updates.cdn-apple.com/2026FallFCS/59241290-5d51-4ca8-9df4-31624b9a4eac/UniversalMac_27.0.1_26A434_Restore.ipsw"
|
||||
assetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v5"
|
||||
legacyAssetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v4"
|
||||
)
|
||||
|
||||
type Bundle struct {
|
||||
AppleMediaServices []byte
|
||||
Commerce []byte
|
||||
ADID []byte
|
||||
CoreFP []byte
|
||||
CoreFPICXS []byte
|
||||
FairPlayD []byte
|
||||
FairPlayKext []byte
|
||||
}
|
||||
|
||||
type fileSpec struct {
|
||||
name string
|
||||
size int
|
||||
digest [32]byte
|
||||
}
|
||||
|
||||
var requiredFiles = []fileSpec{
|
||||
{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
|
||||
{name: "commerce", size: 2735088, digest: mustDigest("c4b2088dd39aeb353f59cb57597902e8317aec66ae7da0414b03c5f932771343")},
|
||||
{name: "adid", size: 3047808, digest: mustDigest("43419a206c28bc93ecb8884256088d18306a0a462350f83adbced8e60a94e390")},
|
||||
{name: "CoreFP", size: 30764976, digest: mustDigest("afbc123e688a822d980d5816cc2b52f69fde669d1dca92cf85627e1cbee587f6")},
|
||||
{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
|
||||
{name: "fairplayd", size: 17389744, digest: mustDigest("1e58d37e9602dd0ca5e24b14762063b6c310248b4d3a94272771d815e4ea1784")},
|
||||
{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
|
||||
}
|
||||
|
||||
var legacyFiles = []fileSpec{
|
||||
{
|
||||
name: "AppleMediaServices",
|
||||
size: 14813888,
|
||||
digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4"),
|
||||
},
|
||||
{
|
||||
name: "commerce",
|
||||
size: 8092640,
|
||||
digest: mustDigest("76de40a4a32f691947cb926ce3b128d2fc446f7cac9755f831c406cf5a316ac9"),
|
||||
},
|
||||
{
|
||||
name: "adid",
|
||||
size: 9797952,
|
||||
digest: mustDigest("1fec225b6917206e3d9b00fe636c04878f82bfd06a87a4b6941711de60efab5b"),
|
||||
},
|
||||
{
|
||||
name: "CoreFP",
|
||||
size: 94842464,
|
||||
digest: mustDigest("2c30fa2b5f695fd66c0360dce72f54757d03ddb7107549715c12cb359a003b46"),
|
||||
},
|
||||
{
|
||||
name: "CoreFP.icxs",
|
||||
size: 7365344,
|
||||
digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b"),
|
||||
},
|
||||
{
|
||||
name: "fairplayd",
|
||||
size: 37689264,
|
||||
digest: mustDigest("28b4c7b2a5a0409c5020da55fc3984713a8e2b0eec8557076c8717f7166d003e"),
|
||||
},
|
||||
{
|
||||
name: "FairPlayIOKit",
|
||||
size: 2132320,
|
||||
digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025"),
|
||||
},
|
||||
}
|
||||
|
||||
type bundleLoader struct {
|
||||
gate chan struct{}
|
||||
installed *Bundle
|
||||
resolve func(context.Context) (Bundle, error)
|
||||
}
|
||||
|
||||
var defaultLoader = bundleLoader{gate: make(chan struct{}, 1), resolve: loadBundle}
|
||||
|
||||
// Load resolves and verifies the pinned macOS framework profile once per process.
|
||||
// The returned slices are shared and must not be modified by callers.
|
||||
func Load(ctx context.Context) (Bundle, error) {
|
||||
return defaultLoader.load(ctx)
|
||||
}
|
||||
|
||||
func (l *bundleLoader) load(ctx context.Context) (Bundle, error) {
|
||||
if ctx == nil {
|
||||
return Bundle{}, errors.New("apple asset context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case l.gate <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", ctx.Err())
|
||||
}
|
||||
|
||||
defer func() { <-l.gate }()
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
|
||||
}
|
||||
|
||||
if l.installed != nil {
|
||||
return *l.installed, nil
|
||||
}
|
||||
|
||||
bundle, err := l.resolve(ctx)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
|
||||
}
|
||||
|
||||
l.installed = &bundle
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func loadBundle(ctx context.Context) (Bundle, error) {
|
||||
directory, err := cacheDirectory()
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if bundle, found := loadCachedBundle(directory); found {
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
bundle, err := resolveRemoteImage(ctx)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if err := writeCache(directory, bundle); err != nil {
|
||||
return Bundle{}, fmt.Errorf("cache Apple SAP assets: %w", err)
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
// Keep only the architecture used by the emulator after verifying and caching
|
||||
// the original files. Cloning releases the unused slices of universal binaries.
|
||||
func compactBundle(bundle Bundle) (Bundle, error) {
|
||||
for _, image := range []struct {
|
||||
name string
|
||||
data *[]byte
|
||||
}{
|
||||
{"AppleMediaServices", &bundle.AppleMediaServices},
|
||||
{"commerce", &bundle.Commerce},
|
||||
{"adid", &bundle.ADID},
|
||||
{"CoreFP", &bundle.CoreFP},
|
||||
{"fairplayd", &bundle.FairPlayD},
|
||||
{"FairPlayIOKit", &bundle.FairPlayKext},
|
||||
} {
|
||||
data, err := compactImage(image.name, *image.data)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
*image.data = data
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func compactImage(name string, input []byte) ([]byte, error) {
|
||||
data, err := machimage.ARM64Slice(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select %s architecture: %w", name, err)
|
||||
}
|
||||
|
||||
if len(data) != len(input) {
|
||||
return bytes.Clone(data), nil
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func cacheDirectory() (string, error) {
|
||||
root, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("find user cache directory: %w", err)
|
||||
}
|
||||
|
||||
return filepath.Join(root, "ipatool", "sap", assetCacheDirectory), nil
|
||||
}
|
||||
|
||||
func loadCachedBundle(directory string) (Bundle, bool) {
|
||||
if bundle, err := readCache(directory); err == nil {
|
||||
return bundle, true
|
||||
}
|
||||
|
||||
legacyDirectory := filepath.Join(filepath.Dir(directory), legacyAssetCacheDirectory)
|
||||
|
||||
bundle, err := readCacheSpecs(legacyDirectory, legacyFiles)
|
||||
if err != nil {
|
||||
return Bundle{}, false
|
||||
}
|
||||
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, false
|
||||
}
|
||||
|
||||
// A verified legacy cache remains usable on read-only mounts. Persist the
|
||||
// smaller representation when possible without requiring a new download.
|
||||
_ = writeCache(directory, bundle)
|
||||
|
||||
return bundle, true
|
||||
}
|
||||
|
||||
func readCache(directory string) (Bundle, error) {
|
||||
return readCacheSpecs(directory, requiredFiles)
|
||||
}
|
||||
|
||||
func readCacheSpecs(directory string, specs []fileSpec) (Bundle, error) {
|
||||
files := make(map[string][]byte, len(specs))
|
||||
|
||||
for _, spec := range specs {
|
||||
data, err := readCacheData(filepath.Join(directory, spec.name), spec.size, &spec)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read cached Apple SAP asset %s: %w", spec.name, err)
|
||||
}
|
||||
|
||||
files[spec.name] = data
|
||||
}
|
||||
|
||||
return bundleFrom(files), nil
|
||||
}
|
||||
|
||||
func readCacheFile(path string, expectedSize int) ([]byte, error) {
|
||||
return readCacheData(path, expectedSize, nil)
|
||||
}
|
||||
|
||||
func readCacheData(path string, expectedSize int, spec *fileSpec) ([]byte, error) {
|
||||
if expectedSize < 0 {
|
||||
return nil, errors.New("invalid expected size")
|
||||
}
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open cached asset: %w", err)
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("inspect cached asset: %w", err)
|
||||
}
|
||||
|
||||
if info.Size() != int64(expectedSize) {
|
||||
return nil, fmt.Errorf("has size %d, expected %d", info.Size(), expectedSize)
|
||||
}
|
||||
|
||||
var reader io.Reader = file
|
||||
|
||||
var digest hash.Hash
|
||||
if spec != nil {
|
||||
digest = sha256.New()
|
||||
reader = io.TeeReader(file, digest)
|
||||
}
|
||||
|
||||
var data []byte
|
||||
if spec != nil && spec.name != "CoreFP.icxs" {
|
||||
data, err = machimage.ReadARM64(reader, expectedSize)
|
||||
} else {
|
||||
data = make([]byte, expectedSize)
|
||||
_, err = io.ReadFull(reader, data)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read cached asset: %w", err)
|
||||
}
|
||||
|
||||
var extra [1]byte
|
||||
if count, err := io.ReadFull(file, extra[:]); err == nil || count != 0 {
|
||||
return nil, fmt.Errorf("grew beyond expected size %d while being read", expectedSize)
|
||||
} else if !errors.Is(err, io.EOF) {
|
||||
return nil, fmt.Errorf("verify cached asset length: %w", err)
|
||||
}
|
||||
|
||||
if spec != nil && !bytes.Equal(digest.Sum(nil), spec.digest[:]) {
|
||||
return nil, fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func writeCache(directory string, bundle Bundle) error {
|
||||
if err := validate(bundle); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
return fmt.Errorf("create SAP asset cache: %w", err)
|
||||
}
|
||||
|
||||
files := bundleFiles(bundle)
|
||||
for _, spec := range requiredFiles {
|
||||
if err := replaceFile(filepath.Join(directory, spec.name), files[spec.name]); err != nil {
|
||||
return fmt.Errorf("write cached SAP asset %s: %w", spec.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func replaceFile(path string, data []byte) error {
|
||||
temporary, err := os.CreateTemp(filepath.Dir(path), ".download-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temporary cache file: %w", err)
|
||||
}
|
||||
|
||||
temporaryPath := temporary.Name()
|
||||
defer os.Remove(temporaryPath)
|
||||
|
||||
if err := temporary.Chmod(0o600); err != nil {
|
||||
_ = temporary.Close()
|
||||
|
||||
return fmt.Errorf("set cache file permissions: %w", err)
|
||||
}
|
||||
|
||||
if _, err := temporary.Write(data); err != nil {
|
||||
_ = temporary.Close()
|
||||
|
||||
return fmt.Errorf("write temporary cache file: %w", err)
|
||||
}
|
||||
|
||||
if err := temporary.Close(); err != nil {
|
||||
return fmt.Errorf("close temporary cache file: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(temporaryPath, path); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("remove existing cache file: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(temporaryPath, path); err != nil {
|
||||
return fmt.Errorf("install cache file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validate(bundle Bundle) error {
|
||||
files := bundleFiles(bundle)
|
||||
for _, spec := range requiredFiles {
|
||||
if err := validateFile(spec, files[spec.name]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateFile(spec fileSpec, data []byte) error {
|
||||
if len(data) != spec.size {
|
||||
return fmt.Errorf("apple SAP asset %s has size %d, expected %d", spec.name, len(data), spec.size)
|
||||
}
|
||||
|
||||
if sha256.Sum256(data) != spec.digest {
|
||||
return fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func bundleFrom(files map[string][]byte) Bundle {
|
||||
return Bundle{
|
||||
AppleMediaServices: files["AppleMediaServices"],
|
||||
Commerce: files["commerce"],
|
||||
ADID: files["adid"],
|
||||
CoreFP: files["CoreFP"],
|
||||
CoreFPICXS: files["CoreFP.icxs"],
|
||||
FairPlayD: files["fairplayd"],
|
||||
FairPlayKext: files["FairPlayIOKit"],
|
||||
}
|
||||
}
|
||||
|
||||
func bundleFiles(bundle Bundle) map[string][]byte {
|
||||
return map[string][]byte{
|
||||
"AppleMediaServices": bundle.AppleMediaServices,
|
||||
"commerce": bundle.Commerce,
|
||||
"adid": bundle.ADID,
|
||||
"CoreFP": bundle.CoreFP,
|
||||
"CoreFP.icxs": bundle.CoreFPICXS,
|
||||
"fairplayd": bundle.FairPlayD,
|
||||
"FairPlayIOKit": bundle.FairPlayKext,
|
||||
}
|
||||
}
|
||||
|
||||
func mustDigest(value string) [32]byte {
|
||||
var digest [32]byte
|
||||
|
||||
decoded, err := hex.DecodeString(value)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if len(decoded) != len(digest) {
|
||||
panic("invalid SHA-256 length")
|
||||
}
|
||||
|
||||
copy(digest[:], decoded)
|
||||
|
||||
return digest
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestAssetsGinkgo(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "SAP Assets Suite")
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadCacheFile(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
data []byte
|
||||
expectedSize int
|
||||
wantErr string
|
||||
}{
|
||||
{name: "exact size", data: []byte("12345678"), expectedSize: 8},
|
||||
{name: "too short", data: []byte("1234"), expectedSize: 8, wantErr: "has size 4, expected 8"},
|
||||
{name: "too large", data: bytes.Repeat([]byte{1}, 64), expectedSize: 8, wantErr: "has size 64, expected 8"},
|
||||
{name: "invalid expected size", expectedSize: -1, wantErr: "invalid expected size"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "asset")
|
||||
if err := os.WriteFile(path, test.data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := readCacheFile(path, test.expectedSize)
|
||||
if test.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("readCacheFile() error = %v", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(got, test.data) {
|
||||
t.Fatalf("readCacheFile() = %q, want %q", got, test.data)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||||
t.Fatalf("readCacheFile() error = %v, want error containing %q", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Verified bundle cache", func() {
|
||||
It("shares one successful load across concurrent callers", func() {
|
||||
var calls atomic.Int32
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
data := []byte("verified bundle")
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls.Add(1)
|
||||
close(entered)
|
||||
<-release
|
||||
|
||||
return Bundle{CoreFP: data}, nil
|
||||
}}
|
||||
var workers sync.WaitGroup
|
||||
results := make(chan Bundle, 8)
|
||||
failures := make(chan error, 8)
|
||||
for range 8 {
|
||||
workers.Go(func() {
|
||||
bundle, err := loader.load(context.Background())
|
||||
results <- bundle
|
||||
failures <- err
|
||||
})
|
||||
}
|
||||
Eventually(entered).Should(BeClosed())
|
||||
close(release)
|
||||
workers.Wait()
|
||||
Expect(calls.Load()).To(Equal(int32(1)))
|
||||
for range 8 {
|
||||
Expect(<-failures).NotTo(HaveOccurred())
|
||||
Expect(&(<-results).CoreFP[0]).To(BeIdenticalTo(&data[0]))
|
||||
}
|
||||
})
|
||||
|
||||
It("lets a waiting caller cancel without interrupting the load", func() {
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
close(entered)
|
||||
<-release
|
||||
|
||||
return Bundle{CoreFP: []byte("ready")}, nil
|
||||
}}
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := loader.load(context.Background()); done <- err }()
|
||||
Eventually(entered).Should(BeClosed())
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err := loader.load(ctx)
|
||||
Expect(errors.Is(err, context.DeadlineExceeded)).To(BeTrue())
|
||||
close(release)
|
||||
Eventually(done).Should(Receive(BeNil()))
|
||||
bundle, err := loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(bundle.CoreFP)).To(Equal("ready"))
|
||||
})
|
||||
|
||||
It("retries failed loads", func() {
|
||||
calls := 0
|
||||
failed := errors.New("temporary failure")
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return Bundle{}, failed
|
||||
}
|
||||
|
||||
return Bundle{CoreFP: []byte("ready")}, nil
|
||||
}}
|
||||
_, err := loader.load(context.Background())
|
||||
Expect(err).To(MatchError(failed))
|
||||
bundle, err := loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(bundle.CoreFP)).To(Equal("ready"))
|
||||
Expect(calls).To(Equal(2))
|
||||
})
|
||||
|
||||
It("does not publish a load canceled before completion", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
calls := 0
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls++
|
||||
cancel()
|
||||
|
||||
return Bundle{CoreFP: []byte("ready")}, nil
|
||||
}}
|
||||
_, err := loader.load(ctx)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(loader.installed).To(BeNil())
|
||||
_, err = loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(calls).To(Equal(2))
|
||||
})
|
||||
|
||||
It("rejects nil and canceled contexts even after a successful load", func() {
|
||||
calls := 0
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls++
|
||||
|
||||
return Bundle{}, nil
|
||||
}}
|
||||
_, err := loader.load(nil) //nolint:staticcheck // Verify invalid caller input.
|
||||
Expect(err).To(MatchError(ContainSubstring("context is nil")))
|
||||
_, err = loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err = loader.load(ctx)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(calls).To(Equal(1))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Runtime bundle compaction", func() {
|
||||
It("retains independent arm64e images and preserves thin images and ICXS", func() {
|
||||
fat := make([]byte, 32)
|
||||
for i, value := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
|
||||
binary.BigEndian.PutUint32(fat[i*4:], value)
|
||||
}
|
||||
copy(fat[28:], "arm!")
|
||||
thin, icxs := []byte("thin"), []byte("ICXS")
|
||||
bundle := Bundle{CoreFP: fat, Commerce: fat, ADID: fat, FairPlayD: fat, AppleMediaServices: thin, FairPlayKext: thin, CoreFPICXS: icxs}
|
||||
original := bytes.Clone(fat)
|
||||
compact, err := compactBundle(bundle)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
for _, data := range [][]byte{compact.CoreFP, compact.Commerce, compact.ADID, compact.FairPlayD} {
|
||||
Expect(string(data)).To(Equal("arm!"))
|
||||
Expect(&data[0]).NotTo(BeIdenticalTo(&fat[28]))
|
||||
Expect(cap(data)).To(BeNumerically("<", len(fat)))
|
||||
}
|
||||
Expect(&compact.AppleMediaServices[0]).To(BeIdenticalTo(&thin[0]))
|
||||
Expect(&compact.FairPlayKext[0]).To(BeIdenticalTo(&thin[0]))
|
||||
Expect(&compact.CoreFPICXS[0]).To(BeIdenticalTo(&icxs[0]))
|
||||
Expect(fat).To(Equal(original))
|
||||
Expect(bundle.CoreFP).To(HaveLen(32))
|
||||
})
|
||||
It("verifies the entire cached file before discarding unused architectures", func() {
|
||||
fat := make([]byte, 40)
|
||||
for i, value := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
|
||||
binary.BigEndian.PutUint32(fat[i*4:], value)
|
||||
}
|
||||
copy(fat[28:], "arm!unused!!")
|
||||
originalSpecs := requiredFiles
|
||||
DeferCleanup(func() { requiredFiles = originalSpecs })
|
||||
requiredFiles = []fileSpec{{name: "CoreFP", size: len(fat), digest: sha256.Sum256(fat)}}
|
||||
directory := GinkgoT().TempDir()
|
||||
path := filepath.Join(directory, "CoreFP")
|
||||
Expect(os.WriteFile(path, fat, 0o600)).To(Succeed())
|
||||
bundle, err := readCache(directory)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(bundle.CoreFP)).To(Equal("arm!"))
|
||||
cached, err := os.ReadFile(path)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(cached).To(Equal(fat))
|
||||
fat[len(fat)-1] ^= 0xff
|
||||
Expect(os.WriteFile(path, fat, 0o600)).To(Succeed())
|
||||
_, err = readCache(directory)
|
||||
Expect(err).To(MatchError(ContainSubstring("failed integrity verification")))
|
||||
})
|
||||
|
||||
It("rejects invalid universal images", func() {
|
||||
fat := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(fat, types.MagicFat.Int())
|
||||
_, err := compactBundle(Bundle{CoreFP: fat})
|
||||
Expect(err).To(MatchError(ContainSubstring("select CoreFP architecture")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,691 @@
|
||||
//nolint:wsl // Binary format parsing is clearer when related bounds checks remain adjacent.
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
"github.com/blacktop/go-macho/pkg/fixupchains"
|
||||
machotypes "github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
const (
|
||||
dyldHeaderSize = 568
|
||||
dyldMappingSize = 56
|
||||
dyldImageInfoSize = 32
|
||||
dyldSubcacheEntrySize = 56
|
||||
dyldMaximumMappings = 64
|
||||
dyldMaximumImages = 100_000
|
||||
dyldMaximumSubcaches = 128
|
||||
dyldMaximumPathLength = 4096
|
||||
dyldSlideInfo5Size = 24
|
||||
dyldMachHeader64Size = 32
|
||||
dyldMachSegment64Command = 0x19
|
||||
dyldMaximumLoadCommandsSize = 16 << 20
|
||||
dyldMaximumSlideChainPointers = 1 << 16
|
||||
)
|
||||
|
||||
type dyldCache struct {
|
||||
members []*dyldCacheMember
|
||||
primary *dyldCacheMember
|
||||
slide5 *dyldSlideInfo5
|
||||
relativeSelectorBase uint64
|
||||
}
|
||||
|
||||
type dyldCacheMember struct {
|
||||
file io.ReaderAt
|
||||
close func() error
|
||||
size int64
|
||||
uuid [16]byte
|
||||
mappings []dyldCacheMapping
|
||||
}
|
||||
|
||||
type dyldCacheMapping struct {
|
||||
member *dyldCacheMember
|
||||
address uint64
|
||||
size uint64
|
||||
fileOffset uint64
|
||||
slideInfoOffset uint64
|
||||
slideInfoSize uint64
|
||||
}
|
||||
|
||||
type dyldSlideInfo5 struct {
|
||||
pageSize uint32
|
||||
pageStartsCount uint32
|
||||
valueAdd uint64
|
||||
}
|
||||
|
||||
type dyldCacheFile struct {
|
||||
reader io.ReaderAt
|
||||
size int64
|
||||
close func() error
|
||||
}
|
||||
|
||||
type dyldCacheOpener func(suffix string) (*dyldCacheFile, error)
|
||||
|
||||
type dyldImage struct {
|
||||
member *dyldCacheMember
|
||||
address uint64
|
||||
offset uint64
|
||||
}
|
||||
|
||||
type dyldRebase struct {
|
||||
address uint64
|
||||
target uint64
|
||||
}
|
||||
|
||||
func extractDyldImageFromFiles(opener dyldCacheOpener, imagePath, outputPath string) error {
|
||||
cache, err := openDyldCache(opener)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open shared cache: %w", err)
|
||||
}
|
||||
defer cache.Close()
|
||||
|
||||
image, err := cache.image(imagePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("find %s in shared cache: %w", imagePath, err)
|
||||
}
|
||||
imageMachO, err := cache.openImage(image, machotypes.LC_SYMTAB, machotypes.LC_DYSYMTAB)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s from shared cache: %w", imagePath, err)
|
||||
}
|
||||
defer imageMachO.Close()
|
||||
if err = cache.imageSymbols(image, imageMachO); err != nil {
|
||||
return fmt.Errorf("read %s symbols: %w", imagePath, err)
|
||||
}
|
||||
|
||||
var chainedFixups *fixupchains.DyldChainedFixups
|
||||
if imageMachO.HasFixups() {
|
||||
chainedFixups, err = imageMachO.DyldChainedFixups()
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s chained fixups: %w", imagePath, err)
|
||||
}
|
||||
}
|
||||
if err := imageMachO.Export(outputPath, chainedFixups, imageMachO.GetBaseAddress(), nil); err != nil {
|
||||
return fmt.Errorf("export %s from shared cache: %w", imagePath, err)
|
||||
}
|
||||
|
||||
if err := cache.applySlide(outputPath); err != nil {
|
||||
return fmt.Errorf("apply %s shared-cache pointers: %w", imagePath, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *dyldCache) openImage(image *dyldImage, excluding ...machotypes.LoadCmd) (*macho.File, error) {
|
||||
linkeditAddress, err := image.linkeditAddress()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
linkedit, err := c.mappingForAddress(linkeditAddress)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reader := &dyldCacheReader{cache: c, member: linkedit.member, offset: 0}
|
||||
converter := machotypes.VMAddrConverter{
|
||||
Converter: c.slidePointer,
|
||||
VMAddr2Offet: func(address uint64) (uint64, error) {
|
||||
mapping, err := c.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return mapping.fileOffset + address - mapping.address, nil
|
||||
},
|
||||
Offet2VMAddr: func(offset uint64) (uint64, error) {
|
||||
return c.addressForOffset(image.member, offset)
|
||||
},
|
||||
}
|
||||
sectionReader := machotypes.NewCustomSectionReader(image.member.file, &converter, 0, image.member.size)
|
||||
|
||||
file, err := macho.NewFile(
|
||||
io.NewSectionReader(image.member.file, int64(image.offset), image.member.size-int64(image.offset)),
|
||||
macho.FileConfig{
|
||||
Offset: int64(image.offset),
|
||||
SectionReader: sectionReader,
|
||||
CacheReader: reader,
|
||||
VMAddrConverter: converter,
|
||||
RelativeSelectorBase: c.relativeSelectorBase,
|
||||
LoadExcluding: excluding,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse shared-cache image: %w", err)
|
||||
}
|
||||
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func openDyldCache(opener dyldCacheOpener) (*dyldCache, error) {
|
||||
primary, header, err := openDyldCacheMember(opener, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cache := &dyldCache{members: []*dyldCacheMember{primary}, primary: primary}
|
||||
complete := false
|
||||
|
||||
defer func() {
|
||||
if !complete {
|
||||
_ = cache.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
subcacheOffset := uint64(binary.LittleEndian.Uint32(header[392:]))
|
||||
subcacheCount := uint64(binary.LittleEndian.Uint32(header[396:]))
|
||||
if subcacheCount > dyldMaximumSubcaches || subcacheCount > 0 && !validDyldRange(primary.size, subcacheOffset, subcacheCount*dyldSubcacheEntrySize) {
|
||||
return nil, fmt.Errorf("shared cache has an invalid subcache table")
|
||||
}
|
||||
entries := make([]byte, subcacheCount*dyldSubcacheEntrySize)
|
||||
if len(entries) > 0 {
|
||||
if _, err := primary.file.ReadAt(entries, int64(subcacheOffset)); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache subcache table: %w", err)
|
||||
}
|
||||
}
|
||||
for index := uint64(0); index < subcacheCount; index++ {
|
||||
entry := entries[index*dyldSubcacheEntrySize : (index+1)*dyldSubcacheEntrySize]
|
||||
suffix := strings.TrimRight(string(entry[24:56]), "\x00")
|
||||
if suffix == "" || strings.ContainsAny(suffix, `/\\`) {
|
||||
return nil, fmt.Errorf("shared cache has an invalid subcache suffix")
|
||||
}
|
||||
member, _, err := openDyldCacheMember(opener, suffix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open shared-cache member %s: %w", suffix, err)
|
||||
}
|
||||
if !bytes.Equal(member.uuid[:], entry[:16]) {
|
||||
_ = member.close()
|
||||
|
||||
return nil, fmt.Errorf("shared-cache member %s has an unexpected UUID", suffix)
|
||||
}
|
||||
cache.members = append(cache.members, member)
|
||||
}
|
||||
|
||||
for _, member := range cache.members {
|
||||
for _, mapping := range member.mappings {
|
||||
if mapping.slideInfoSize == 0 {
|
||||
continue
|
||||
}
|
||||
version, err := readDyldSlideVersion(mapping)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if version != 5 {
|
||||
return nil, fmt.Errorf("unsupported shared-cache slide version %d", version)
|
||||
}
|
||||
slide, err := readDyldSlideInfo5(mapping)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cache.slide5 == nil {
|
||||
cache.slide5 = slide
|
||||
} else if cache.slide5.pageSize != slide.pageSize || cache.slide5.valueAdd != slide.valueAdd {
|
||||
return nil, fmt.Errorf("shared-cache members use incompatible slide information")
|
||||
}
|
||||
}
|
||||
}
|
||||
if cache.slide5 == nil {
|
||||
return nil, fmt.Errorf("shared cache has no slide information")
|
||||
}
|
||||
complete = true
|
||||
|
||||
return cache, nil
|
||||
}
|
||||
|
||||
func openDyldCacheMember(opener dyldCacheOpener, suffix string) (*dyldCacheMember, []byte, error) {
|
||||
opened, err := opener(suffix)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
fail := func(err error) (*dyldCacheMember, []byte, error) {
|
||||
_ = opened.close()
|
||||
|
||||
return nil, nil, err
|
||||
}
|
||||
if opened.size < dyldHeaderSize {
|
||||
return fail(fmt.Errorf("shared-cache member is too small"))
|
||||
}
|
||||
header := make([]byte, dyldHeaderSize)
|
||||
if _, err := opened.reader.ReadAt(header, 0); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
magic := strings.TrimRight(string(header[:16]), "\x00")
|
||||
if magic != "dyld_v1 arm64e" {
|
||||
return fail(fmt.Errorf("unsupported shared-cache format %q", magic))
|
||||
}
|
||||
|
||||
mappingOffset := uint64(binary.LittleEndian.Uint32(header[312:]))
|
||||
mappingCount := uint64(binary.LittleEndian.Uint32(header[316:]))
|
||||
if mappingCount == 0 || mappingCount > dyldMaximumMappings || !validDyldRange(opened.size, mappingOffset, mappingCount*dyldMappingSize) {
|
||||
return fail(fmt.Errorf("shared-cache member has an invalid mapping table"))
|
||||
}
|
||||
mappingData := make([]byte, mappingCount*dyldMappingSize)
|
||||
if _, err := opened.reader.ReadAt(mappingData, int64(mappingOffset)); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
|
||||
member := &dyldCacheMember{file: opened.reader, close: opened.close, size: opened.size}
|
||||
copy(member.uuid[:], header[88:104])
|
||||
|
||||
for index := uint64(0); index < mappingCount; index++ {
|
||||
data := mappingData[index*dyldMappingSize : (index+1)*dyldMappingSize]
|
||||
mapping := dyldCacheMapping{
|
||||
member: member,
|
||||
address: binary.LittleEndian.Uint64(data[0:]),
|
||||
size: binary.LittleEndian.Uint64(data[8:]),
|
||||
fileOffset: binary.LittleEndian.Uint64(data[16:]),
|
||||
slideInfoOffset: binary.LittleEndian.Uint64(data[24:]),
|
||||
slideInfoSize: binary.LittleEndian.Uint64(data[32:]),
|
||||
}
|
||||
if mapping.size == 0 || mapping.address+mapping.size < mapping.address || !validDyldRange(opened.size, mapping.fileOffset, mapping.size) || mapping.slideInfoSize != 0 && !validDyldRange(opened.size, mapping.slideInfoOffset, mapping.slideInfoSize) {
|
||||
return fail(fmt.Errorf("shared-cache member has an invalid mapping"))
|
||||
}
|
||||
|
||||
member.mappings = append(member.mappings, mapping)
|
||||
}
|
||||
|
||||
return member, header, nil
|
||||
}
|
||||
|
||||
func validDyldRange(size int64, offset, length uint64) bool {
|
||||
return size >= 0 && offset <= uint64(size) && length <= uint64(size)-offset
|
||||
}
|
||||
|
||||
func (c *dyldCache) Close() error {
|
||||
var first error
|
||||
for _, member := range c.members {
|
||||
if err := member.close(); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
|
||||
return first
|
||||
}
|
||||
|
||||
func (c *dyldCache) image(path string) (*dyldImage, error) {
|
||||
header := make([]byte, dyldHeaderSize)
|
||||
if _, err := c.primary.file.ReadAt(header, 0); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache header: %w", err)
|
||||
}
|
||||
imagesOffset := uint64(binary.LittleEndian.Uint32(header[448:]))
|
||||
imagesCount := uint64(binary.LittleEndian.Uint32(header[452:]))
|
||||
if imagesCount == 0 || imagesCount > dyldMaximumImages || !validDyldRange(c.primary.size, imagesOffset, imagesCount*dyldImageInfoSize) {
|
||||
return nil, fmt.Errorf("shared cache has an invalid image table")
|
||||
}
|
||||
images := make([]byte, imagesCount*dyldImageInfoSize)
|
||||
if _, err := c.primary.file.ReadAt(images, int64(imagesOffset)); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache image table: %w", err)
|
||||
}
|
||||
for index := uint64(0); index < imagesCount; index++ {
|
||||
data := images[index*dyldImageInfoSize : (index+1)*dyldImageInfoSize]
|
||||
address := binary.LittleEndian.Uint64(data)
|
||||
pathOffset := uint64(binary.LittleEndian.Uint32(data[24:]))
|
||||
name, err := readDyldCString(c.primary.file, c.primary.size, pathOffset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if name != path {
|
||||
continue
|
||||
}
|
||||
mapping, err := c.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &dyldImage{
|
||||
member: mapping.member,
|
||||
address: address,
|
||||
offset: mapping.fileOffset + address - mapping.address,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("image was not found")
|
||||
}
|
||||
|
||||
func readDyldCString(file io.ReaderAt, size int64, offset uint64) (string, error) {
|
||||
if !validDyldRange(size, offset, 1) {
|
||||
return "", fmt.Errorf("shared cache contains an invalid string offset")
|
||||
}
|
||||
limit := min(uint64(dyldMaximumPathLength), uint64(size)-offset)
|
||||
data := make([]byte, limit)
|
||||
n, err := file.ReadAt(data, int64(offset))
|
||||
if err != nil && err != io.EOF {
|
||||
return "", fmt.Errorf("read shared-cache string: %w", err)
|
||||
}
|
||||
data = data[:n]
|
||||
if end := bytes.IndexByte(data, 0); end >= 0 {
|
||||
return string(data[:end]), nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("shared-cache string is not terminated")
|
||||
}
|
||||
|
||||
func (c *dyldCache) mappingForAddress(address uint64) (*dyldCacheMapping, error) {
|
||||
for _, member := range c.members {
|
||||
for index := range member.mappings {
|
||||
mapping := &member.mappings[index]
|
||||
if mapping.address <= address && address < mapping.address+mapping.size {
|
||||
return mapping, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("address %#x is outside the shared cache", address)
|
||||
}
|
||||
|
||||
func (c *dyldCache) addressForOffset(member *dyldCacheMember, offset uint64) (uint64, error) {
|
||||
for _, mapping := range member.mappings {
|
||||
if mapping.fileOffset <= offset && offset < mapping.fileOffset+mapping.size {
|
||||
return mapping.address + offset - mapping.fileOffset, nil
|
||||
}
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("offset %#x is outside the shared-cache member", offset)
|
||||
}
|
||||
|
||||
func (c *dyldCache) slidePointer(pointer uint64) uint64 {
|
||||
if pointer == 0 {
|
||||
return 0
|
||||
}
|
||||
if _, err := c.mappingForAddress(pointer); err == nil {
|
||||
return pointer
|
||||
}
|
||||
|
||||
return c.slide5.decode(pointer)
|
||||
}
|
||||
|
||||
func (i *dyldImage) linkeditAddress() (uint64, error) {
|
||||
header := make([]byte, dyldMachHeader64Size)
|
||||
if _, err := i.member.file.ReadAt(header, int64(i.offset)); err != nil {
|
||||
return 0, fmt.Errorf("read Mach-O header: %w", err)
|
||||
}
|
||||
if binary.LittleEndian.Uint32(header) != uint32(machotypes.Magic64) {
|
||||
return 0, fmt.Errorf("image has an invalid Mach-O magic")
|
||||
}
|
||||
commandCount := binary.LittleEndian.Uint32(header[16:])
|
||||
commandsSize := uint64(binary.LittleEndian.Uint32(header[20:]))
|
||||
if commandsSize > dyldMaximumLoadCommandsSize || !validDyldRange(i.member.size, i.offset+dyldMachHeader64Size, commandsSize) {
|
||||
return 0, fmt.Errorf("image has invalid load commands")
|
||||
}
|
||||
commands := make([]byte, commandsSize)
|
||||
if _, err := i.member.file.ReadAt(commands, int64(i.offset+dyldMachHeader64Size)); err != nil {
|
||||
return 0, fmt.Errorf("read Mach-O load commands: %w", err)
|
||||
}
|
||||
for index, offset := uint32(0), uint64(0); index < commandCount; index++ {
|
||||
if offset+8 > uint64(len(commands)) {
|
||||
return 0, fmt.Errorf("image load commands are truncated")
|
||||
}
|
||||
commandSize := uint64(binary.LittleEndian.Uint32(commands[offset+4:]))
|
||||
if commandSize < 8 || offset+commandSize > uint64(len(commands)) {
|
||||
return 0, fmt.Errorf("image has an invalid load command")
|
||||
}
|
||||
if binary.LittleEndian.Uint32(commands[offset:]) == dyldMachSegment64Command && commandSize >= 72 {
|
||||
name := strings.TrimRight(string(commands[offset+8:offset+24]), "\x00")
|
||||
if name == "__LINKEDIT" {
|
||||
return binary.LittleEndian.Uint64(commands[offset+24:]), nil
|
||||
}
|
||||
}
|
||||
offset += commandSize
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("image has no __LINKEDIT segment")
|
||||
}
|
||||
|
||||
type dyldCacheReader struct {
|
||||
cache *dyldCache
|
||||
member *dyldCacheMember
|
||||
offset int64
|
||||
}
|
||||
|
||||
func (r *dyldCacheReader) Read(data []byte) (int, error) {
|
||||
n, err := r.member.file.ReadAt(data, r.offset)
|
||||
r.offset += int64(n)
|
||||
|
||||
return n, err //nolint:wrapcheck // Reader adapters must preserve io.EOF.
|
||||
}
|
||||
|
||||
func (r *dyldCacheReader) Seek(offset int64, whence int) (int64, error) {
|
||||
switch whence {
|
||||
case io.SeekStart:
|
||||
case io.SeekCurrent:
|
||||
offset += r.offset
|
||||
case io.SeekEnd:
|
||||
offset += r.member.size
|
||||
default:
|
||||
return 0, fmt.Errorf("invalid seek mode")
|
||||
}
|
||||
if offset < 0 {
|
||||
return 0, fmt.Errorf("negative shared-cache offset")
|
||||
}
|
||||
r.offset = offset
|
||||
|
||||
return offset, nil
|
||||
}
|
||||
|
||||
func (r *dyldCacheReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||
return r.member.file.ReadAt(data, offset) //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
|
||||
func (r *dyldCacheReader) SeekToAddr(address uint64) error {
|
||||
mapping, err := r.cache.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.member = mapping.member
|
||||
r.offset = int64(mapping.fileOffset + address - mapping.address)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *dyldCacheReader) ReadAtAddr(data []byte, address uint64) (int, error) {
|
||||
written := 0
|
||||
for written < len(data) {
|
||||
mapping, err := r.cache.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return written, err
|
||||
}
|
||||
available := mapping.address + mapping.size - address
|
||||
count := min(uint64(len(data)-written), available)
|
||||
offset := mapping.fileOffset + address - mapping.address
|
||||
n, err := mapping.member.file.ReadAt(data[written:written+int(count)], int64(offset))
|
||||
written += n
|
||||
address += uint64(n)
|
||||
if err != nil {
|
||||
return written, err //nolint:wrapcheck // ReaderAt implementations must preserve io.EOF.
|
||||
}
|
||||
if n != int(count) {
|
||||
return written, io.ErrUnexpectedEOF
|
||||
}
|
||||
}
|
||||
|
||||
return written, nil
|
||||
}
|
||||
|
||||
func readDyldSlideVersion(mapping dyldCacheMapping) (uint32, error) {
|
||||
if mapping.slideInfoSize < 4 {
|
||||
return 0, fmt.Errorf("shared cache has truncated slide information")
|
||||
}
|
||||
var data [4]byte
|
||||
if _, err := mapping.member.file.ReadAt(data[:], int64(mapping.slideInfoOffset)); err != nil {
|
||||
return 0, fmt.Errorf("read shared-cache slide version: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint32(data[:]), nil
|
||||
}
|
||||
|
||||
func readDyldSlideInfo5(mapping dyldCacheMapping) (*dyldSlideInfo5, error) {
|
||||
if mapping.slideInfoSize < dyldSlideInfo5Size {
|
||||
return nil, fmt.Errorf("shared cache has truncated slide information")
|
||||
}
|
||||
data := make([]byte, dyldSlideInfo5Size)
|
||||
if _, err := mapping.member.file.ReadAt(data, int64(mapping.slideInfoOffset)); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache slide information: %w", err)
|
||||
}
|
||||
if binary.LittleEndian.Uint32(data) != 5 {
|
||||
return nil, fmt.Errorf("unsupported shared-cache slide version %d", binary.LittleEndian.Uint32(data))
|
||||
}
|
||||
slide := &dyldSlideInfo5{
|
||||
pageSize: binary.LittleEndian.Uint32(data[4:]),
|
||||
pageStartsCount: binary.LittleEndian.Uint32(data[8:]),
|
||||
valueAdd: binary.LittleEndian.Uint64(data[16:]),
|
||||
}
|
||||
if slide.pageSize == 0 || uint64(dyldSlideInfo5Size)+uint64(slide.pageStartsCount)*2 > mapping.slideInfoSize {
|
||||
return nil, fmt.Errorf("shared cache has invalid slide information")
|
||||
}
|
||||
|
||||
return slide, nil
|
||||
}
|
||||
|
||||
func (s *dyldSlideInfo5) decode(pointer uint64) uint64 {
|
||||
if pointer == 0 {
|
||||
return 0
|
||||
}
|
||||
target := pointer & ((uint64(1) << 34) - 1)
|
||||
if pointer>>63 == 0 {
|
||||
target |= (pointer >> 34 & 0xff) << 56
|
||||
}
|
||||
|
||||
return s.valueAdd + target
|
||||
}
|
||||
|
||||
func (c *dyldCache) applySlide(path string) error {
|
||||
file, err := os.OpenFile(path, os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open exported image: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
exported, err := macho.NewFile(file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse exported image: %w", err)
|
||||
}
|
||||
defer exported.Close()
|
||||
|
||||
for _, segment := range exported.Segments() {
|
||||
mapping, err := c.mappingForAddress(segment.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mapping.slideInfoOffset == 0 {
|
||||
continue
|
||||
}
|
||||
pageSize, err := c.slidePageSize(*mapping)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
start := (segment.Addr - mapping.address) / pageSize
|
||||
end := (segment.Addr + segment.Memsz - mapping.address + pageSize) / pageSize
|
||||
rebases, err := c.rebases(*mapping, start, end)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, rebase := range rebases {
|
||||
offset, err := exported.GetOffset(rebase.address)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if _, err := file.Seek(int64(offset), io.SeekStart); err != nil {
|
||||
return fmt.Errorf("seek to exported pointer %#x: %w", offset, err)
|
||||
}
|
||||
if err := binary.Write(file, binary.LittleEndian, rebase.target); err != nil {
|
||||
return fmt.Errorf("write exported pointer %#x: %w", rebase.target, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := file.Sync(); err != nil {
|
||||
return fmt.Errorf("sync exported image: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *dyldCache) rebases(mapping dyldCacheMapping, startPage, endPage uint64) ([]dyldRebase, error) {
|
||||
version, err := readDyldSlideVersion(mapping)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if version != 5 {
|
||||
return nil, fmt.Errorf("unsupported shared-cache slide version %d", version)
|
||||
}
|
||||
|
||||
slide, err := readDyldSlideInfo5(mapping)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
starts, err := readDyldSlideArray(mapping, dyldSlideInfo5Size, slide.pageStartsCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if endPage == 0 || endPage > uint64(len(starts)) {
|
||||
endPage = uint64(len(starts))
|
||||
}
|
||||
if startPage > endPage {
|
||||
return nil, fmt.Errorf("invalid shared-cache slide page range")
|
||||
}
|
||||
|
||||
var rebases []dyldRebase
|
||||
|
||||
for page := startPage; page < endPage; page++ {
|
||||
start := starts[page]
|
||||
if start == 0xffff {
|
||||
continue
|
||||
}
|
||||
pageFileOffset := mapping.fileOffset + page*uint64(slide.pageSize)
|
||||
pageAddress := mapping.address + page*uint64(slide.pageSize)
|
||||
offset := uint64(start)
|
||||
for count := 0; count < dyldMaximumSlideChainPointers; count++ {
|
||||
if offset+8 > uint64(slide.pageSize) {
|
||||
return nil, fmt.Errorf("shared-cache slide chain leaves its page")
|
||||
}
|
||||
var data [8]byte
|
||||
if _, err := mapping.member.file.ReadAt(data[:], int64(pageFileOffset+offset)); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache slide pointer: %w", err)
|
||||
}
|
||||
pointer := binary.LittleEndian.Uint64(data[:])
|
||||
rebases = append(rebases, dyldRebase{
|
||||
address: pageAddress + offset,
|
||||
target: slide.decode(pointer),
|
||||
})
|
||||
next := pointer >> 52 & 0x7ff
|
||||
if next == 0 {
|
||||
break
|
||||
}
|
||||
offset += next * 8
|
||||
if count == dyldMaximumSlideChainPointers-1 {
|
||||
return nil, fmt.Errorf("shared-cache slide chain is too long")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rebases, nil
|
||||
}
|
||||
|
||||
func (c *dyldCache) slidePageSize(mapping dyldCacheMapping) (uint64, error) {
|
||||
slide, err := readDyldSlideInfo5(mapping)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return uint64(slide.pageSize), nil
|
||||
}
|
||||
|
||||
func readDyldSlideArray(mapping dyldCacheMapping, offset, count uint32) ([]uint16, error) {
|
||||
if count == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
data := make([]byte, uint64(count)*2)
|
||||
if _, err := mapping.member.file.ReadAt(data, int64(mapping.slideInfoOffset+uint64(offset))); err != nil {
|
||||
return nil, fmt.Errorf("read shared-cache slide table: %w", err)
|
||||
}
|
||||
values := make([]uint16, count)
|
||||
for index := range values {
|
||||
values[index] = binary.LittleEndian.Uint16(data[index*2:])
|
||||
}
|
||||
|
||||
return values, nil
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
machotypes "github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
// imageSymbols restores symbol load commands without allocating the cache-wide string table.
|
||||
// Export needs only this image's nlists and the strings they actually reference.
|
||||
func (c *dyldCache) imageSymbols(image *dyldImage, f *macho.File) error {
|
||||
header := make([]byte, dyldMachHeader64Size)
|
||||
if _, err := image.member.file.ReadAt(header, int64(image.offset)); err != nil {
|
||||
return fmt.Errorf("read image header: %w", err)
|
||||
}
|
||||
|
||||
size := uint64(binary.LittleEndian.Uint32(header[20:]))
|
||||
if size > dyldMaximumLoadCommandsSize {
|
||||
return fmt.Errorf("invalid image load command size")
|
||||
}
|
||||
|
||||
commands := make([]byte, size)
|
||||
if _, err := image.member.file.ReadAt(commands, int64(image.offset)+dyldMachHeader64Size); err != nil {
|
||||
return fmt.Errorf("read image commands: %w", err)
|
||||
}
|
||||
|
||||
address, err := image.linkeditAddress()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mapping, err := c.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
loads := make([]macho.Load, 0, len(f.Loads)+2)
|
||||
index := 0
|
||||
|
||||
for offset := 0; offset < len(commands); {
|
||||
if len(commands)-offset < 8 {
|
||||
return fmt.Errorf("truncated image command")
|
||||
}
|
||||
|
||||
length := int(binary.LittleEndian.Uint32(commands[offset+4:]))
|
||||
if length < 8 || length > len(commands)-offset {
|
||||
return fmt.Errorf("invalid image command size")
|
||||
}
|
||||
|
||||
raw := commands[offset : offset+length]
|
||||
offset += length
|
||||
|
||||
command := machotypes.LoadCmd(binary.LittleEndian.Uint32(raw))
|
||||
switch command {
|
||||
case machotypes.LC_SYMTAB:
|
||||
table, err := readImageSymbols(mapping.member, raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
f.Symtab = table
|
||||
loads = append(loads, table)
|
||||
case machotypes.LC_DYSYMTAB:
|
||||
table := &macho.Dysymtab{LoadBytes: raw}
|
||||
if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &table.DysymtabCmd); err != nil {
|
||||
return fmt.Errorf("decode dynamic symbols: %w", err)
|
||||
}
|
||||
|
||||
if f.Symtab == nil || uint64(table.Iundefsym)+uint64(table.Nundefsym) > uint64(len(f.Symtab.Syms)) || table.Nindirectsyms > 4<<20 {
|
||||
return fmt.Errorf("invalid dynamic symbol table")
|
||||
}
|
||||
|
||||
if !validDyldRange(mapping.member.size, uint64(table.Indirectsymoff), uint64(table.Nindirectsyms)*4) {
|
||||
return fmt.Errorf("indirect symbols exceed cache member")
|
||||
}
|
||||
|
||||
encoded := make([]byte, int(table.Nindirectsyms)*4)
|
||||
if _, err := mapping.member.file.ReadAt(encoded, int64(table.Indirectsymoff)); err != nil {
|
||||
return fmt.Errorf("read indirect symbols: %w", err)
|
||||
}
|
||||
|
||||
table.IndirectSyms = make([]uint32, table.Nindirectsyms)
|
||||
if err := binary.Read(bytes.NewReader(encoded), binary.LittleEndian, table.IndirectSyms); err != nil {
|
||||
return fmt.Errorf("decode indirect symbols: %w", err)
|
||||
}
|
||||
|
||||
f.Dysymtab = table
|
||||
loads = append(loads, table)
|
||||
default:
|
||||
if index >= len(f.Loads) || f.Loads[index].Command() != command {
|
||||
return fmt.Errorf("image load command order changed")
|
||||
}
|
||||
|
||||
loads = append(loads, f.Loads[index])
|
||||
index++
|
||||
}
|
||||
}
|
||||
|
||||
f.Loads = loads
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// readImageSymbols decodes just the referenced names, preserving go-macho's symbol normalization.
|
||||
func readImageSymbols(member *dyldCacheMember, raw []byte) (*macho.Symtab, error) {
|
||||
table := &macho.Symtab{LoadBytes: raw}
|
||||
if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &table.SymtabCmd); err != nil {
|
||||
return nil, fmt.Errorf("decode symbols: %w", err)
|
||||
}
|
||||
|
||||
if table.Nsyms > 4<<20 || !validDyldRange(member.size, uint64(table.Symoff), uint64(table.Nsyms)*16) || !validDyldRange(member.size, uint64(table.Stroff), uint64(table.Strsize)) {
|
||||
return nil, fmt.Errorf("invalid image symbol table")
|
||||
}
|
||||
|
||||
encoded := make([]byte, int(table.Nsyms)*16)
|
||||
if _, err := member.file.ReadAt(encoded, int64(table.Symoff)); err != nil {
|
||||
return nil, fmt.Errorf("read image symbols: %w", err)
|
||||
}
|
||||
|
||||
readName := func(offset uint64) (string, error) {
|
||||
if offset >= uint64(table.Strsize) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
name, err := readDyldCString(member.file, int64(uint64(table.Stroff)+uint64(table.Strsize)), uint64(table.Stroff)+offset)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if strings.HasPrefix(name, "_") && strings.Contains(name, ".") {
|
||||
name = name[1:]
|
||||
}
|
||||
|
||||
return name, nil
|
||||
}
|
||||
reader := bytes.NewReader(encoded)
|
||||
|
||||
table.Syms = make([]macho.Symbol, 0, table.Nsyms)
|
||||
for i := uint32(0); i < table.Nsyms; i++ {
|
||||
var n machotypes.Nlist64
|
||||
if err := binary.Read(reader, binary.LittleEndian, &n); err != nil {
|
||||
return nil, fmt.Errorf("decode image symbol: %w", err)
|
||||
}
|
||||
|
||||
name, err := readName(uint64(n.Name))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
indirect := ""
|
||||
if n.Type.IsIndirectSym() {
|
||||
indirect, err = readName(n.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
table.Syms = append(table.Syms, macho.Symbol{Name: name, IndirectName: indirect, Type: n.Type, Sect: n.Sect, Desc: n.Desc, Value: n.Value})
|
||||
}
|
||||
|
||||
return table, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
|
||||
machotypes "github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
type sparseSymbols struct {
|
||||
data []byte
|
||||
largest int
|
||||
}
|
||||
|
||||
// ReadAt simulates a large sparse cache and records the largest requested allocation.
|
||||
func (s *sparseSymbols) ReadAt(output []byte, offset int64) (int, error) {
|
||||
s.largest = max(s.largest, len(output))
|
||||
|
||||
if offset < 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
clear(output)
|
||||
|
||||
if offset < int64(len(s.data)) {
|
||||
copy(output, s.data[offset:])
|
||||
}
|
||||
|
||||
return len(output), nil
|
||||
}
|
||||
|
||||
var _ = Describe("Shared-cache symbol loading", func() {
|
||||
It("reads only referenced strings from a gigabyte-sized string table", func() {
|
||||
raw := &sparseSymbols{data: make([]byte, 2048)}
|
||||
names := []byte("\x00_regular\x00_Go.symbol\x00_target.symbol\x00")
|
||||
copy(raw.data[1024:], names)
|
||||
entries := []machotypes.Nlist64{{Nlist: machotypes.Nlist{Name: 1, Type: 0x0f}, Value: 0x180001000}, {Nlist: machotypes.Nlist{Name: 10, Type: 0x0b}, Value: 21}}
|
||||
var table bytes.Buffer
|
||||
for _, entry := range entries {
|
||||
Expect(binary.Write(&table, binary.LittleEndian, entry)).To(Succeed())
|
||||
}
|
||||
copy(raw.data[128:], table.Bytes())
|
||||
var command bytes.Buffer
|
||||
header := machotypes.SymtabCmd{LoadCmd: machotypes.LC_SYMTAB, Len: 24, Symoff: 128, Nsyms: 2, Stroff: 1024, Strsize: 1 << 30}
|
||||
Expect(binary.Write(&command, binary.LittleEndian, header)).To(Succeed())
|
||||
result, err := readImageSymbols(&dyldCacheMember{file: raw, size: 2 << 30}, command.Bytes())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(result.Syms).To(HaveLen(2))
|
||||
Expect(result.Syms[0].Name).To(Equal("_regular"))
|
||||
Expect(result.Syms[1].Name).To(Equal("Go.symbol"))
|
||||
Expect(result.Syms[1].IndirectName).To(Equal("target.symbol"))
|
||||
Expect(raw.largest).To(BeNumerically("<=", 4096))
|
||||
})
|
||||
It("rejects symbol data extending beyond the cache member", func() {
|
||||
var command bytes.Buffer
|
||||
Expect(binary.Write(&command, binary.LittleEndian, machotypes.SymtabCmd{LoadCmd: machotypes.LC_SYMTAB, Len: 24, Symoff: 128, Nsyms: 10, Stroff: 256, Strsize: 128})).To(Succeed())
|
||||
_, err := readImageSymbols(&dyldCacheMember{file: bytes.NewReader(make([]byte, 256)), size: 256}, command.Bytes())
|
||||
Expect(err).To(MatchError(ContainSubstring("invalid image symbol table")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Buffered remote ranges", func() {
|
||||
var source []byte
|
||||
var remote *remoteFile
|
||||
var requests []string
|
||||
var mu sync.Mutex
|
||||
BeforeEach(func() {
|
||||
source = make([]byte, 1<<20)
|
||||
for n := range source {
|
||||
source[n] = byte(n % 251)
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
requests = append(requests, r.Header.Get("Range"))
|
||||
mu.Unlock()
|
||||
http.ServeContent(w, r, "image", time.Time{}, bytes.NewReader(source))
|
||||
}))
|
||||
DeferCleanup(server.Close)
|
||||
requests = nil
|
||||
remote = &remoteFile{ctx: context.Background(), client: server.Client(), url: server.URL, size: int64(len(source))}
|
||||
})
|
||||
It("serves a small sequential stream in bounded larger transfers", func() {
|
||||
output := make([]byte, len(source))
|
||||
for offset := 0; offset < len(output); offset += 4096 {
|
||||
count, err := remote.ReadAt(output[offset:offset+4096], int64(offset))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(4096))
|
||||
}
|
||||
Expect(output).To(Equal(source))
|
||||
mu.Lock()
|
||||
count := len(requests)
|
||||
mu.Unlock()
|
||||
Expect(count).To(Equal(5))
|
||||
Expect(len(remote.cache)).To(BeNumerically("<=", remoteReadAheadSize))
|
||||
})
|
||||
It("keeps sparse metadata requests exact", func() {
|
||||
for _, offset := range []int64{0, 500000, 900000} {
|
||||
output := make([]byte, 8)
|
||||
_, err := remote.ReadAt(output, offset)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(output).To(Equal(source[offset : offset+8]))
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
Expect(requests).To(Equal([]string{"bytes=0-7", "bytes=500000-500007", "bytes=900000-900007"}))
|
||||
})
|
||||
It("isolates cached bytes from caller mutation and reports EOF correctly", func() {
|
||||
data := make([]byte, 4096)
|
||||
_, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
clear(data)
|
||||
_, err = remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(data).To(Equal(source[:4096]))
|
||||
tail := make([]byte, 32)
|
||||
count, err := remote.ReadAt(tail, int64(len(source)-16))
|
||||
Expect(err).To(MatchError(io.EOF))
|
||||
Expect(count).To(Equal(16))
|
||||
Expect(tail[:count]).To(Equal(source[len(source)-16:]))
|
||||
})
|
||||
It("honors cancellation even when data is buffered", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
remote.ctx = ctx
|
||||
data := make([]byte, 32)
|
||||
_, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
cancel()
|
||||
_, err = remote.ReadAt(data, 0)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
})
|
||||
It("supports concurrent independent reads", func() {
|
||||
finished := make(chan error, 8)
|
||||
for n := range 8 {
|
||||
go func() {
|
||||
offset := int64(n * 40000)
|
||||
output := make([]byte, 4096)
|
||||
_, err := remote.ReadAt(output, offset)
|
||||
if err == nil && !bytes.Equal(output, source[offset:offset+4096]) {
|
||||
err = errors.New("incorrect concurrent range")
|
||||
}
|
||||
finished <- err
|
||||
}()
|
||||
}
|
||||
for range 8 {
|
||||
Eventually(finished).Should(Receive(BeNil()))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Interrupted remote responses", func() {
|
||||
It("resumes a short response at the first unread byte", func() {
|
||||
var ranges []string
|
||||
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 8, client: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
ranges = append(ranges, r.Header.Get("Range"))
|
||||
if len(ranges) == 1 {
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-7/8"}}, Body: io.NopCloser(strings.NewReader("abcd"))}, nil
|
||||
}
|
||||
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 4-7/8"}}, Body: io.NopCloser(strings.NewReader("efgh"))}, nil
|
||||
})}}
|
||||
data := make([]byte, 8)
|
||||
count, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(8))
|
||||
Expect(string(data)).To(Equal("abcdefgh"))
|
||||
Expect(ranges).To(Equal([]string{"bytes=0-7", "bytes=4-7"}))
|
||||
})
|
||||
It("rejects incorrect response ranges without caching them", func() {
|
||||
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 8, client: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 1-7/8"}}, Body: io.NopCloser(strings.NewReader("1234567"))}, nil
|
||||
})}}
|
||||
_, err := remote.ReadAt(make([]byte, 8), 0)
|
||||
Expect(err).To(MatchError(ContainSubstring("server returned bytes")))
|
||||
Expect(remote.cache).To(BeEmpty())
|
||||
})
|
||||
It("does not fail a completed requested prefix when speculative tail reads fail", func() {
|
||||
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 1 << 20}
|
||||
calls := 0
|
||||
remote.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
switch calls {
|
||||
case 1:
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-3/1048576"}}, Body: io.NopCloser(strings.NewReader("abcd"))}, nil
|
||||
case 2:
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{fmt.Sprintf("bytes 4-%d/1048576", 4+remoteReadAheadSize-1)}}, Body: io.NopCloser(strings.NewReader("efgh"))}, nil
|
||||
default:
|
||||
return nil, errors.New("connection interrupted")
|
||||
}
|
||||
})}
|
||||
data := make([]byte, 4)
|
||||
_, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
count, err := remote.ReadAt(data, 4)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(4))
|
||||
Expect(string(data)).To(Equal("efgh"))
|
||||
Expect(remote.cacheOffset).To(BeZero())
|
||||
Expect(remote.cache).To(HaveLen(4))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Remote image size probes", func() {
|
||||
DescribeTable("requires exactly the requested byte", func(body string, valid bool) {
|
||||
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-0/123"}}, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
remote, err := openRemoteFile(context.Background(), client)
|
||||
if valid {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(remote.size).To(Equal(int64(123)))
|
||||
} else {
|
||||
Expect(err).To(MatchError(ContainSubstring("probe has an invalid length")))
|
||||
}
|
||||
}, Entry("one byte", "x", true), Entry("empty body", "", false), Entry("too much data", "xx", false))
|
||||
})
|
||||
@@ -0,0 +1,238 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
remoteReadAttempts = 3
|
||||
restoreImageUserAgent = "Mozilla/5.0"
|
||||
remoteSmallReadSize = 32 << 10
|
||||
remoteReadAheadSize = 256 << 10
|
||||
)
|
||||
|
||||
type remoteFile struct {
|
||||
ctx context.Context
|
||||
client *http.Client
|
||||
url string
|
||||
size int64
|
||||
mu sync.Mutex
|
||||
cache []byte
|
||||
cacheOffset int64
|
||||
previous bool
|
||||
lastEnd int64
|
||||
}
|
||||
|
||||
//nolint:wsl // Request construction and validation are clearer in protocol order.
|
||||
func openRemoteFile(ctx context.Context, client *http.Client) (*remoteFile, error) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, macOSRestoreURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create remote image request: %w", err)
|
||||
}
|
||||
|
||||
request.Header.Set("User-Agent", restoreImageUserAgent)
|
||||
request.Header.Set("Range", "bytes=0-0")
|
||||
response, err := client.Do(request)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open remote image: %w", err)
|
||||
}
|
||||
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusPartialContent {
|
||||
return nil, fmt.Errorf("open remote image: server returned %s without byte-range support", response.Status)
|
||||
}
|
||||
|
||||
start, end, size, err := parseContentRange(response.Header.Get("Content-Range"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open remote image: %w", err)
|
||||
}
|
||||
if start != 0 || end != 0 {
|
||||
return nil, fmt.Errorf("open remote image: server returned unexpected byte range %d-%d", start, end)
|
||||
}
|
||||
|
||||
probe, err := io.ReadAll(io.LimitReader(response.Body, 2))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read remote image probe: %w", err)
|
||||
}
|
||||
if len(probe) != 1 {
|
||||
return nil, errors.New("remote image probe has an invalid length")
|
||||
}
|
||||
|
||||
return &remoteFile{ctx: ctx, client: client, url: macOSRestoreURL, size: size}, nil
|
||||
}
|
||||
|
||||
//nolint:wsl // Parsing checks are clearer in wire-format order.
|
||||
func parseContentRange(value string) (int64, int64, int64, error) {
|
||||
unitAndRange, total, ok := strings.Cut(value, "/")
|
||||
if !ok || total == "" || total == "*" {
|
||||
return 0, 0, 0, fmt.Errorf("invalid Content-Range %q", value)
|
||||
}
|
||||
size, err := strconv.ParseInt(total, 10, 64)
|
||||
if err != nil || size <= 0 {
|
||||
return 0, 0, 0, fmt.Errorf("invalid Content-Range %q", value)
|
||||
}
|
||||
rangeValue, ok := strings.CutPrefix(unitAndRange, "bytes ")
|
||||
if !ok {
|
||||
return 0, 0, 0, fmt.Errorf("invalid Content-Range %q", value)
|
||||
}
|
||||
|
||||
startValue, endValue, ok := strings.Cut(rangeValue, "-")
|
||||
if !ok {
|
||||
return 0, 0, 0, fmt.Errorf("invalid Content-Range %q", value)
|
||||
}
|
||||
start, startErr := strconv.ParseInt(startValue, 10, 64)
|
||||
end, endErr := strconv.ParseInt(endValue, 10, 64)
|
||||
if startErr != nil || endErr != nil || start < 0 || end < start || end >= size {
|
||||
return 0, 0, 0, fmt.Errorf("invalid Content-Range %q", value)
|
||||
}
|
||||
|
||||
return start, end, size, nil
|
||||
}
|
||||
|
||||
//nolint:wsl // Range request validation is clearer in protocol order.
|
||||
func (r *remoteFile) ReadAt(data []byte, offset int64) (int, error) {
|
||||
if len(data) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if offset < 0 {
|
||||
return 0, errors.New("negative remote image offset")
|
||||
}
|
||||
|
||||
if offset >= r.size {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
wanted := len(data)
|
||||
if remaining := r.size - offset; int64(wanted) > remaining {
|
||||
wanted = int(remaining)
|
||||
}
|
||||
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, fmt.Errorf("read remote image: %w", err)
|
||||
}
|
||||
r.mu.Lock()
|
||||
if offset >= r.cacheOffset && offset+int64(wanted) <= r.cacheOffset+int64(len(r.cache)) {
|
||||
copy(data[:wanted], r.cache[offset-r.cacheOffset:offset-r.cacheOffset+int64(wanted)])
|
||||
r.previous, r.lastEnd = true, offset+int64(wanted)
|
||||
r.mu.Unlock()
|
||||
if wanted != len(data) {
|
||||
return wanted, io.EOF
|
||||
}
|
||||
|
||||
return wanted, nil
|
||||
}
|
||||
// Sparse metadata reads stay exact; only a sequential small-read stream
|
||||
// earns read-ahead. This avoids fetching large unused image regions.
|
||||
ahead := r.previous && offset == r.lastEnd && wanted <= remoteSmallReadSize
|
||||
r.previous, r.lastEnd = true, offset+int64(wanted)
|
||||
r.mu.Unlock()
|
||||
fetchSize := wanted
|
||||
if ahead {
|
||||
fetchSize = int(min(int64(remoteReadAheadSize), r.size-offset))
|
||||
}
|
||||
buffer := data[:wanted]
|
||||
if fetchSize > wanted {
|
||||
buffer = make([]byte, fetchSize)
|
||||
}
|
||||
count, err := r.readRange(buffer, offset)
|
||||
if count == fetchSize && err == nil && fetchSize <= remoteReadAheadSize {
|
||||
cached := buffer
|
||||
if fetchSize == wanted {
|
||||
cached = bytes.Clone(buffer)
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.cacheOffset, r.cache = offset, cached
|
||||
r.mu.Unlock()
|
||||
}
|
||||
if fetchSize > wanted {
|
||||
copy(data[:wanted], buffer[:min(count, wanted)])
|
||||
}
|
||||
if count < wanted {
|
||||
return count, err
|
||||
}
|
||||
if wanted != len(data) {
|
||||
return wanted, io.EOF
|
||||
}
|
||||
|
||||
return wanted, nil
|
||||
}
|
||||
|
||||
// Read and validate one wire range, resuming interrupted bodies as needed.
|
||||
func (r *remoteFile) readRange(data []byte, offset int64) (int, error) {
|
||||
wanted := len(data)
|
||||
|
||||
total := 0
|
||||
|
||||
var lastErr error
|
||||
|
||||
for attempt := 0; attempt < remoteReadAttempts && total < wanted; attempt++ {
|
||||
start := offset + int64(total)
|
||||
end := offset + int64(wanted) - 1
|
||||
|
||||
request, err := http.NewRequestWithContext(r.ctx, http.MethodGet, r.url, nil)
|
||||
if err != nil {
|
||||
return total, fmt.Errorf("create remote range request: %w", err)
|
||||
}
|
||||
|
||||
request.Header.Set("User-Agent", restoreImageUserAgent)
|
||||
request.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end))
|
||||
|
||||
response, err := r.client.Do(request)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if response.StatusCode != http.StatusPartialContent {
|
||||
response.Body.Close()
|
||||
|
||||
return total, fmt.Errorf("read remote image range: server returned %s", response.Status)
|
||||
}
|
||||
|
||||
actualStart, actualEnd, actualSize, err := parseContentRange(response.Header.Get("Content-Range"))
|
||||
|
||||
if err != nil || actualStart != start || actualEnd != end || actualSize != r.size {
|
||||
response.Body.Close()
|
||||
|
||||
if err != nil {
|
||||
return total, fmt.Errorf("read remote image range: %w", err)
|
||||
}
|
||||
|
||||
return total, fmt.Errorf("read remote image range: server returned bytes %d-%d/%d, expected %d-%d/%d", actualStart, actualEnd, actualSize, start, end, r.size)
|
||||
}
|
||||
|
||||
count, readErr := io.ReadFull(response.Body, data[total:wanted])
|
||||
closeErr := response.Body.Close()
|
||||
total += count
|
||||
|
||||
if readErr == nil {
|
||||
lastErr = closeErr
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
lastErr = readErr
|
||||
}
|
||||
|
||||
if total != wanted {
|
||||
if lastErr == nil {
|
||||
lastErr = io.ErrUnexpectedEOF
|
||||
}
|
||||
|
||||
return total, fmt.Errorf("read remote image at offset %d: %w", offset+int64(total), lastErr)
|
||||
}
|
||||
|
||||
return total, nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
return function(request)
|
||||
}
|
||||
|
||||
var _ = Describe("remote image HTTP requests", func() {
|
||||
It("reads image ranges from a server requiring a browser-compatible user agent", func() {
|
||||
const content = "restore image"
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
if request.UserAgent() != "Mozilla/5.0" {
|
||||
http.Error(response, "unsupported user agent", http.StatusForbidden)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
http.ServeContent(response, request, "restore.ipsw", time.Time{}, strings.NewReader(content))
|
||||
}))
|
||||
DeferCleanup(server.Close)
|
||||
|
||||
transport := &http.Transport{}
|
||||
DeferCleanup(transport.CloseIdleConnections)
|
||||
|
||||
client := &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
request = request.Clone(request.Context())
|
||||
request.URL.Scheme = "http"
|
||||
request.URL.Host = server.Listener.Addr().String()
|
||||
|
||||
return transport.RoundTrip(request)
|
||||
})}
|
||||
|
||||
remote, err := openRemoteFile(context.Background(), client)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(remote.size).To(Equal(int64(len(content))))
|
||||
|
||||
data := make([]byte, len(content)-1)
|
||||
count, err := remote.ReadAt(data, 1)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(len(data)))
|
||||
Expect(string(data)).To(Equal(content[1:]))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/asn1"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
"github.com/blacktop/go-macho/pkg/fixupchains"
|
||||
"github.com/blacktop/go-macho/types"
|
||||
"github.com/go-compressions/lzfse"
|
||||
)
|
||||
|
||||
const (
|
||||
kernelCacheName = "kernelcache.release.mac13j"
|
||||
kernelCacheCompressedSize = 33043908
|
||||
kernelCacheArchiveSize = 33096787
|
||||
kernelCachePayloadSize = 33096384
|
||||
kernelCacheImageSize = 124354560
|
||||
fairPlayKextIdentifier = "com.apple.driver.FairPlayIOKit"
|
||||
maximumKernelCacheSymbols = 1 << 20
|
||||
)
|
||||
|
||||
func extractFairPlayKext(archive *zip.Reader, destination string) error {
|
||||
entry, err := pinnedZipEntry(archive, kernelCacheName, kernelCacheCompressedSize, kernelCacheArchiveSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
reader, err := entry.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("open pinned kernel collection: %w", err)
|
||||
}
|
||||
|
||||
data, readErr := io.ReadAll(io.LimitReader(reader, kernelCacheArchiveSize+1))
|
||||
closeErr := reader.Close()
|
||||
|
||||
if readErr != nil || closeErr != nil {
|
||||
return fmt.Errorf("read pinned kernel collection: %w", errors.Join(readErr, closeErr))
|
||||
}
|
||||
|
||||
if len(data) != kernelCacheArchiveSize {
|
||||
return fmt.Errorf("pinned kernel collection has size %d, expected %d", len(data), kernelCacheArchiveSize)
|
||||
}
|
||||
|
||||
payload, err := im4pPayload(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode pinned kernel collection: %w", err)
|
||||
}
|
||||
|
||||
if len(payload) != kernelCachePayloadSize {
|
||||
return fmt.Errorf("pinned kernel payload has size %d, expected %d", len(payload), kernelCachePayloadSize)
|
||||
}
|
||||
|
||||
image, err := lzfse.Decompress(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decompress pinned kernel collection: %w", err)
|
||||
}
|
||||
|
||||
if len(image) != kernelCacheImageSize {
|
||||
return fmt.Errorf("pinned kernel image has size %d, expected %d", len(image), kernelCacheImageSize)
|
||||
}
|
||||
|
||||
collection, err := macho.NewFile(bytes.NewReader(image))
|
||||
if err != nil {
|
||||
return fmt.Errorf("open pinned kernel collection Mach-O: %w", err)
|
||||
}
|
||||
|
||||
defer collection.Close()
|
||||
|
||||
if collection.Type != types.MH_FILESET {
|
||||
return errors.New("pinned kernel collection is not a fileset")
|
||||
}
|
||||
|
||||
var fixups *fixupchains.DyldChainedFixups
|
||||
if collection.HasFixups() {
|
||||
fixups, err = collection.DyldChainedFixups()
|
||||
if err != nil {
|
||||
return fmt.Errorf("read pinned kernel fixups: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
symbols := make(map[string]macho.Symbol)
|
||||
|
||||
for _, entry := range collection.FileSets() {
|
||||
member, openErr := collection.GetFileSetFileByName(entry.EntryID)
|
||||
if openErr != nil || member.Symtab == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, symbol := range member.Symtab.Syms {
|
||||
if symbol.Type.IsExternalSym() && !symbol.Type.IsUndefinedSym() && symbol.Value != 0 {
|
||||
symbols[symbol.Name] = symbol
|
||||
if len(symbols) > maximumKernelCacheSymbols {
|
||||
return errors.New("pinned kernel symbol table exceeds the limit")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
member, err := collection.GetFileSetFileByName(fairPlayKextIdentifier)
|
||||
if err != nil {
|
||||
return fmt.Errorf("find FairPlayIOKit in pinned kernel collection: %w", err)
|
||||
}
|
||||
|
||||
var resolved []macho.Symbol
|
||||
|
||||
if member.Symtab != nil {
|
||||
for _, symbol := range member.Symtab.Syms {
|
||||
if !symbol.Type.IsUndefinedSym() || symbol.Name == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if target, ok := symbols[symbol.Name]; ok {
|
||||
resolved = append(resolved, macho.Symbol{
|
||||
Name: symbol.Name,
|
||||
Type: types.N_ABS | types.N_EXT,
|
||||
Desc: symbol.Desc,
|
||||
Value: target.Value,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := member.Export(destination, fixups, collection.GetBaseAddress(), resolved); err != nil {
|
||||
return fmt.Errorf("export FairPlayIOKit from pinned kernel collection: %w", err)
|
||||
}
|
||||
|
||||
info, err := os.Stat(destination)
|
||||
if err != nil {
|
||||
return fmt.Errorf("inspect exported FairPlayIOKit: %w", err)
|
||||
}
|
||||
|
||||
if !info.Mode().IsRegular() {
|
||||
return errors.New("exported FairPlayIOKit is not a regular file")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func im4pPayload(data []byte) ([]byte, error) {
|
||||
var container asn1.RawValue
|
||||
|
||||
rest, err := asn1.Unmarshal(data, &container)
|
||||
if err != nil || len(rest) != 0 || container.Tag != asn1.TagSequence || !container.IsCompound {
|
||||
return nil, errors.New("invalid IM4P container")
|
||||
}
|
||||
|
||||
contents := container.Bytes
|
||||
fields := make([]asn1.RawValue, 0, 4)
|
||||
|
||||
for len(contents) != 0 && len(fields) < 4 {
|
||||
var field asn1.RawValue
|
||||
|
||||
contents, err = asn1.Unmarshal(contents, &field)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode IM4P field: %w", err)
|
||||
}
|
||||
|
||||
fields = append(fields, field)
|
||||
}
|
||||
|
||||
if len(fields) != 4 || fields[0].Tag != asn1.TagIA5String || string(fields[0].Bytes) != "IM4P" || fields[1].Tag != asn1.TagIA5String || string(fields[1].Bytes) != "krnl" || fields[3].Tag != asn1.TagOctetString {
|
||||
return nil, errors.New("invalid IM4P kernel payload")
|
||||
}
|
||||
|
||||
return append([]byte(nil), fields[3].Bytes...), nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// padLZFSEStreams supplies unused low accumulator bytes for short FSE streams.
|
||||
// Apple's decoder can read those bytes before the payload; the pure Go decoder
|
||||
// bounds each stream separately and otherwise rejects valid short payloads.
|
||||
// This is only used on authenticated AEA data, whose decoded SHA-256 is checked.
|
||||
func padLZFSEStreams(src []byte) ([]byte, error) {
|
||||
var out []byte
|
||||
|
||||
for len(src) >= 4 {
|
||||
magic := binary.LittleEndian.Uint32(src)
|
||||
if magic == 0x24787662 {
|
||||
return append(out, src...), nil
|
||||
}
|
||||
|
||||
if len(src) < 12 {
|
||||
return nil, errors.New("short LZFSE block")
|
||||
}
|
||||
|
||||
if magic == 0x2d787662 || magic == 0x6e787662 {
|
||||
size := 8 + int(binary.LittleEndian.Uint32(src[4:]))
|
||||
if magic == 0x6e787662 {
|
||||
size = 12 + int(binary.LittleEndian.Uint32(src[8:]))
|
||||
}
|
||||
|
||||
if size > len(src) {
|
||||
return nil, errors.New("truncated LZFSE block")
|
||||
}
|
||||
|
||||
out = append(out, src[:size]...)
|
||||
src = src[size:]
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var header, literals, matches int
|
||||
|
||||
var v0, v1 uint64
|
||||
|
||||
switch magic {
|
||||
case 0x32787662:
|
||||
if len(src) < 32 {
|
||||
return nil, errors.New("short LZFSE V2 header")
|
||||
}
|
||||
|
||||
v0 = binary.LittleEndian.Uint64(src[8:])
|
||||
v1 = binary.LittleEndian.Uint64(src[16:])
|
||||
header = int(binary.LittleEndian.Uint32(src[24:]))
|
||||
literals = int(v0 >> 20 & 0xfffff)
|
||||
matches = int(v1 >> 40 & 0xfffff)
|
||||
|
||||
if header < 32 {
|
||||
return nil, errors.New("invalid LZFSE V2 header")
|
||||
}
|
||||
case 0x31787662:
|
||||
header = 772
|
||||
if len(src) < header {
|
||||
return nil, errors.New("short LZFSE V1 header")
|
||||
}
|
||||
|
||||
literals = int(binary.LittleEndian.Uint32(src[20:]))
|
||||
matches = int(binary.LittleEndian.Uint32(src[24:]))
|
||||
default:
|
||||
return nil, errors.New("unknown LZFSE block")
|
||||
}
|
||||
|
||||
if header > len(src) || literals > len(src)-header || matches > len(src)-header-literals {
|
||||
return nil, errors.New("truncated LZFSE payload")
|
||||
}
|
||||
|
||||
lp, mp := max(0, 8-literals), max(0, 8-matches)
|
||||
|
||||
h := append([]byte(nil), src[:header]...)
|
||||
|
||||
if magic == 0x32787662 {
|
||||
binary.LittleEndian.PutUint64(h[8:], v0&^(uint64(0xfffff)<<20)|uint64(literals+lp)<<20)
|
||||
binary.LittleEndian.PutUint64(h[16:], v1&^(uint64(0xfffff)<<40)|uint64(matches+mp)<<40)
|
||||
} else {
|
||||
binary.LittleEndian.PutUint32(h[8:], uint32(literals+lp+matches+mp))
|
||||
binary.LittleEndian.PutUint32(h[20:], uint32(literals+lp))
|
||||
binary.LittleEndian.PutUint32(h[24:], uint32(matches+mp))
|
||||
}
|
||||
|
||||
out = append(out, h...)
|
||||
out = append(out, make([]byte, lp)...)
|
||||
out = append(out, src[header:header+literals]...)
|
||||
out = append(out, make([]byte, mp)...)
|
||||
out = append(out, src[header+literals:header+literals+matches]...)
|
||||
src = src[header+literals+matches:]
|
||||
}
|
||||
|
||||
return nil, errors.New("missing LZFSE end marker")
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
|
||||
"github.com/go-compressions/lzfse"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Short LZFSE entropy streams", func() {
|
||||
It("decodes a valid short literal payload without changing its output", func() {
|
||||
original := make([]byte, 65536)
|
||||
encoded, err := lzfse.Compress(original)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(binary.LittleEndian.Uint32(encoded)).To(Equal(uint32(0x32787662)))
|
||||
word := binary.LittleEndian.Uint64(encoded[8:])
|
||||
Expect(word >> 20 & 0xfffff).To(BeZero())
|
||||
header := int(binary.LittleEndian.Uint32(encoded[24:]))
|
||||
short := append([]byte(nil), encoded[:header]...)
|
||||
short = append(short, make([]byte, 4)...)
|
||||
short = append(short, encoded[header:]...)
|
||||
binary.LittleEndian.PutUint64(short[8:], word|4<<20)
|
||||
_, err = lzfse.Decompress(short)
|
||||
Expect(err).To(MatchError(ContainSubstring("stream too short")))
|
||||
padded, err := padLZFSEStreams(short)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
decoded, err := lzfse.Decompress(padded)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(decoded).To(Equal(original))
|
||||
})
|
||||
It("rejects truncated block payloads", func() { _, err := padLZFSEStreams([]byte{'b', 'v', 'x', '2'}); Expect(err).To(HaveOccurred()) })
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Compact asset cache migration", func() {
|
||||
var directory, legacyDirectory string
|
||||
var source, selected []byte
|
||||
BeforeEach(func() {
|
||||
root := GinkgoT().TempDir()
|
||||
directory = filepath.Join(root, assetCacheDirectory)
|
||||
legacyDirectory = filepath.Join(root, legacyAssetCacheDirectory)
|
||||
source = make([]byte, 40)
|
||||
for n, v := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
|
||||
binary.BigEndian.PutUint32(source[n*4:], v)
|
||||
}
|
||||
copy(source[28:], "arm!unused!")
|
||||
selected = []byte("arm!")
|
||||
originalRequired, originalLegacy := requiredFiles, legacyFiles
|
||||
DeferCleanup(func() { requiredFiles, legacyFiles = originalRequired, originalLegacy })
|
||||
requiredFiles = []fileSpec{{name: "CoreFP", size: len(selected), digest: sha256.Sum256(selected)}}
|
||||
legacyFiles = []fileSpec{{name: "CoreFP", size: len(source), digest: sha256.Sum256(source)}}
|
||||
Expect(os.MkdirAll(legacyDirectory, 0o700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(legacyDirectory, "CoreFP"), source, 0o600)).To(Succeed())
|
||||
})
|
||||
It("verifies legacy files and writes only the selected architecture", func() {
|
||||
bundle, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(bundle.CoreFP).To(Equal(selected))
|
||||
migrated, err := os.ReadFile(filepath.Join(directory, "CoreFP"))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(migrated).To(Equal(selected))
|
||||
old, err := os.ReadFile(filepath.Join(legacyDirectory, "CoreFP"))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(old).To(Equal(source))
|
||||
})
|
||||
It("uses a compact cache without requiring the old files", func() {
|
||||
Expect(writeCache(directory, Bundle{CoreFP: selected})).To(Succeed())
|
||||
Expect(os.RemoveAll(legacyDirectory)).To(Succeed())
|
||||
bundle, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(bundle.CoreFP).To(Equal(selected))
|
||||
})
|
||||
It("rejects corrupt discarded legacy bytes", func() {
|
||||
corrupt := bytes.Clone(source)
|
||||
corrupt[len(corrupt)-1] ^= 0xff
|
||||
Expect(os.WriteFile(filepath.Join(legacyDirectory, "CoreFP"), corrupt, 0o600)).To(Succeed())
|
||||
_, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeFalse())
|
||||
})
|
||||
It("repairs corrupt compact data from a valid old cache", func() {
|
||||
Expect(os.MkdirAll(directory, 0o700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(directory, "CoreFP"), []byte("bad!"), 0o600)).To(Succeed())
|
||||
bundle, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(bundle.CoreFP).To(Equal(selected))
|
||||
})
|
||||
It("keeps valid legacy data usable when the compact cache cannot be written", func() {
|
||||
Expect(os.WriteFile(directory, []byte("not a directory"), 0o600)).To(Succeed())
|
||||
bundle, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(bundle.CoreFP).To(Equal(selected))
|
||||
})
|
||||
It("rejects a legacy slice that does not match the new pin", func() {
|
||||
requiredFiles[0].digest = sha256.Sum256([]byte("bad!"))
|
||||
_, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeFalse())
|
||||
})
|
||||
|
||||
})
|
||||
@@ -0,0 +1,183 @@
|
||||
//nolint:wsl // Archive extraction is clearer when resource setup remains adjacent.
|
||||
package assets
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const (
|
||||
appleMediaServicesImage = "/System/Library/PrivateFrameworks/AppleMediaServices.framework/Versions/A/AppleMediaServices"
|
||||
fileSystemImageName = "043-70867-640.dmg.aea"
|
||||
systemOSImageName = "043-70701-651.dmg.aea"
|
||||
fileSystemArchiveSize = 11274289152
|
||||
fileSystemImageSize = 14189330432
|
||||
systemOSArchiveSize = 2415919104
|
||||
systemOSImageSize = 2879389696
|
||||
arm64CachePath = "/System/Library/dyld/dyld_shared_cache_arm64e"
|
||||
)
|
||||
|
||||
var frameworkImagePaths = []string{
|
||||
"/System/Library/PrivateFrameworks/CoreADI.framework/Versions/A/adid",
|
||||
"/System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Resources/commerce",
|
||||
"/System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/CoreFP",
|
||||
"/System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/Resources/CoreFP.icxs",
|
||||
"/System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/fairplayd",
|
||||
}
|
||||
|
||||
func resolveRemoteImage(ctx context.Context) (Bundle, error) {
|
||||
client := &http.Client{}
|
||||
remote, err := openRemoteFile(ctx, client)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("resolve macOS %s (%s) frameworks: %w", macOSVersion, macOSBuild, err)
|
||||
}
|
||||
|
||||
archive, err := zip.NewReader(remote, remote.size)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read macOS %s (%s) restore image: %w", macOSVersion, macOSBuild, err)
|
||||
}
|
||||
|
||||
fileSystemEntry, err := pinnedZipEntry(archive, fileSystemImageName, fileSystemArchiveSize, fileSystemArchiveSize)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
systemOSEntry, err := pinnedZipEntry(archive, systemOSImageName, systemOSArchiveSize, systemOSArchiveSize)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
workspace, err := os.MkdirTemp("", "ipatool-macos-27-*")
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("create macOS image workspace: %w", err)
|
||||
}
|
||||
defer os.RemoveAll(workspace)
|
||||
|
||||
frameworkDirectory := filepath.Join(workspace, "frameworks")
|
||||
if err := extractFrameworkFiles(ctx, client, remote, fileSystemEntry, frameworkDirectory); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
appleMediaServicesPath := filepath.Join(frameworkDirectory, "AppleMediaServices")
|
||||
if err := extractAppleMediaServices(ctx, client, remote, systemOSEntry, appleMediaServicesPath); err != nil {
|
||||
return Bundle{}, fmt.Errorf("extract AppleMediaServices from macOS %s (%s): %w", macOSVersion, macOSBuild, err)
|
||||
}
|
||||
if err := extractFairPlayKext(archive, filepath.Join(frameworkDirectory, "FairPlayIOKit")); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
files := make(map[string][]byte, len(requiredFiles))
|
||||
|
||||
for _, spec := range requiredFiles {
|
||||
data, err := os.ReadFile(filepath.Join(frameworkDirectory, spec.name))
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read extracted %s: %w", spec.name, err)
|
||||
}
|
||||
|
||||
files[spec.name] = data
|
||||
}
|
||||
|
||||
bundle, err := compactBundle(bundleFrom(files))
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func extractAppleMediaServices(ctx context.Context, client *http.Client, remote *remoteFile, entry *zip.File, destination string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return fmt.Errorf("extract AppleMediaServices: %w", err)
|
||||
}
|
||||
|
||||
offset, err := entry.DataOffset()
|
||||
if err != nil {
|
||||
return fmt.Errorf("locate encrypted SystemOS cryptex: %w", err)
|
||||
}
|
||||
encryptedImage := io.NewSectionReader(remote, offset, int64(entry.CompressedSize64))
|
||||
image, err := newAEAReader(ctx, client, encryptedImage, int64(entry.CompressedSize64))
|
||||
if err != nil {
|
||||
return fmt.Errorf("open encrypted SystemOS cryptex: %w", err)
|
||||
}
|
||||
|
||||
if image.size != systemOSImageSize {
|
||||
return fmt.Errorf("SystemOS cryptex has size %d, expected %d", image.size, systemOSImageSize)
|
||||
}
|
||||
|
||||
extractor, closeExtractor, err := newAPFSExtractor(image, image.size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() { _ = closeExtractor() }()
|
||||
|
||||
opener := func(suffix string) (*dyldCacheFile, error) {
|
||||
file, err := extractor.openFile(ctx, arm64CachePath+suffix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open arm64e shared-cache member %q: %w", suffix, err)
|
||||
}
|
||||
|
||||
return &dyldCacheFile{reader: file, size: file.size, close: func() error { return nil }}, nil
|
||||
}
|
||||
if err := extractDyldImageFromFiles(opener, appleMediaServicesImage, destination); err != nil {
|
||||
return fmt.Errorf("export AppleMediaServices from arm64e shared cache: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func pinnedZipEntry(archive *zip.Reader, name string, compressedSize, uncompressedSize uint64) (*zip.File, error) {
|
||||
expectedMethod := zip.Store
|
||||
if compressedSize != uncompressedSize {
|
||||
expectedMethod = zip.Deflate
|
||||
}
|
||||
|
||||
for _, entry := range archive.File {
|
||||
if entry.Name != name {
|
||||
continue
|
||||
}
|
||||
|
||||
if entry.Method != expectedMethod || entry.CompressedSize64 != compressedSize || entry.UncompressedSize64 != uncompressedSize {
|
||||
return nil, fmt.Errorf("macOS %s (%s) restore member %s does not match the pinned image", macOSVersion, macOSBuild, name)
|
||||
}
|
||||
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("macOS %s (%s) restore image does not contain %s", macOSVersion, macOSBuild, name)
|
||||
}
|
||||
|
||||
func extractFrameworkFiles(ctx context.Context, client *http.Client, remote *remoteFile, entry *zip.File, destination string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return fmt.Errorf("extract framework files: %w", err)
|
||||
}
|
||||
|
||||
offset, err := entry.DataOffset()
|
||||
if err != nil {
|
||||
return fmt.Errorf("locate encrypted macOS filesystem: %w", err)
|
||||
}
|
||||
|
||||
encryptedImage := io.NewSectionReader(remote, offset, int64(entry.CompressedSize64))
|
||||
image, err := newAEAReader(ctx, client, encryptedImage, int64(entry.CompressedSize64))
|
||||
if err != nil {
|
||||
return fmt.Errorf("open encrypted macOS filesystem: %w", err)
|
||||
}
|
||||
|
||||
if image.size != fileSystemImageSize {
|
||||
return fmt.Errorf("macOS filesystem has size %d, expected %d", image.size, fileSystemImageSize)
|
||||
}
|
||||
|
||||
if err := extractAPFSFiles(ctx, image, image.size, frameworkImagePaths, destination); err != nil {
|
||||
return fmt.Errorf("extract frameworks from macOS %s (%s): %w", macOSVersion, macOSBuild, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("native remote image reader", func() {
|
||||
DescribeTable("parses complete Content-Range values",
|
||||
func(value string, expectedStart, expectedEnd, expectedSize int64) {
|
||||
start, end, size, err := parseContentRange(value)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(start).To(Equal(expectedStart))
|
||||
Expect(end).To(Equal(expectedEnd))
|
||||
Expect(size).To(Equal(expectedSize))
|
||||
},
|
||||
Entry("single byte", "bytes 0-0/26637307067", int64(0), int64(0), int64(26637307067)),
|
||||
Entry("middle range", "bytes 100-199/1000", int64(100), int64(199), int64(1000)),
|
||||
)
|
||||
|
||||
DescribeTable("rejects incomplete Content-Range values",
|
||||
func(value string) {
|
||||
_, _, _, err := parseContentRange(value)
|
||||
Expect(err).To(HaveOccurred())
|
||||
},
|
||||
Entry("missing total", "bytes 0-0/*"),
|
||||
Entry("missing separator", "bytes 0-0"),
|
||||
Entry("zero length", "bytes 0-0/0"),
|
||||
Entry("wrong unit", "items 0-0/1"),
|
||||
Entry("range beyond total", "bytes 0-1/1"),
|
||||
Entry("backwards range", "bytes 2-1/3"),
|
||||
)
|
||||
|
||||
It("parses bounded AEA metadata records", func() {
|
||||
var data bytes.Buffer
|
||||
for key, value := range map[string]string{"first": "value", "second": "another"} {
|
||||
record := append(append([]byte(key), 0), value...)
|
||||
Expect(binary.Write(&data, binary.LittleEndian, uint32(len(record)+4))).To(Succeed())
|
||||
_, err := data.Write(record)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
}
|
||||
|
||||
metadata, err := parseAEAMetadata(data.Bytes())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(metadata).To(HaveKeyWithValue("first", []byte("value")))
|
||||
Expect(metadata).To(HaveKeyWithValue("second", []byte("another")))
|
||||
})
|
||||
|
||||
It("rejects an AEA metadata record outside the authentication block", func() {
|
||||
data := make([]byte, 8)
|
||||
binary.LittleEndian.PutUint32(data, 32)
|
||||
_, err := parseAEAMetadata(data)
|
||||
Expect(err).To(MatchError(ContainSubstring("invalid AEA metadata record length")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,267 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
const authenticationPluginImage = "/System/Library/Accounts/Authentication/AMSAccountAuthenticationPlugin.bundle/Contents/MacOS/AMSAccountAuthenticationPlugin"
|
||||
|
||||
// StoreCache reads the pinned shared-cache data without loading host frameworks.
|
||||
// It is used both by the profile generator and the portable asset installer.
|
||||
type StoreCache struct {
|
||||
cache *dyldCache
|
||||
ctx context.Context
|
||||
opener dyldCacheOpener
|
||||
cleanup func() error
|
||||
slides map[uint64]map[uint64]uint64
|
||||
images map[string]uint64
|
||||
readSystemFile func(string) ([]byte, error)
|
||||
}
|
||||
|
||||
// OpenLocalStoreCache opens shared-cache files for offline profile generation.
|
||||
func OpenLocalStoreCache(ctx context.Context, path string) (*StoreCache, error) {
|
||||
opener := func(suffix string) (*dyldCacheFile, error) {
|
||||
file, err := os.Open(path + suffix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open Store cache member: %w", err)
|
||||
}
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
_ = file.Close()
|
||||
|
||||
return nil, fmt.Errorf("inspect Store cache member: %w", err)
|
||||
}
|
||||
|
||||
return &dyldCacheFile{reader: file, size: info.Size(), close: file.Close}, nil
|
||||
}
|
||||
|
||||
s, err := newStoreCache(ctx, opener, func() error { return nil })
|
||||
if err == nil {
|
||||
s.readSystemFile = os.ReadFile
|
||||
}
|
||||
|
||||
return s, err
|
||||
}
|
||||
|
||||
// OpenRemoteStoreCache obtains data directly from Apple's pinned restore image.
|
||||
func OpenRemoteStoreCache(ctx context.Context) (*StoreCache, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("store asset context is nil")
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
|
||||
remote, err := openRemoteFile(ctx, client)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open Store restore image: %w", err)
|
||||
}
|
||||
|
||||
archive, err := zip.NewReader(remote, remote.size)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read Store restore archive: %w", err)
|
||||
}
|
||||
|
||||
entry, err := pinnedZipEntry(archive, systemOSImageName, systemOSArchiveSize, systemOSArchiveSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
offset, err := entry.DataOffset()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("locate Store cryptex: %w", err)
|
||||
}
|
||||
|
||||
image, err := newAEAReader(ctx, client, io.NewSectionReader(remote, offset, int64(entry.CompressedSize64)), int64(entry.CompressedSize64))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open Store cryptex: %w", err)
|
||||
}
|
||||
|
||||
if image.size != systemOSImageSize {
|
||||
return nil, errors.New("store cryptex does not match the pinned image")
|
||||
}
|
||||
|
||||
extractor, closeExtractor, err := newAPFSExtractor(image, image.size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
opener := func(suffix string) (*dyldCacheFile, error) {
|
||||
file, err := extractor.openFile(ctx, arm64CachePath+suffix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open Store cache member: %w", err)
|
||||
}
|
||||
|
||||
return &dyldCacheFile{reader: file, size: file.size, close: func() error { return nil }}, nil
|
||||
}
|
||||
|
||||
var systemExtractor *apfsExtractor
|
||||
|
||||
var closeSystem func() error
|
||||
|
||||
cleanup := func() error {
|
||||
err := closeExtractor()
|
||||
if closeSystem != nil {
|
||||
err = errors.Join(err, closeSystem())
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
s, err := newStoreCache(ctx, opener, cleanup)
|
||||
if err == nil {
|
||||
s.readSystemFile = func(path string) ([]byte, error) {
|
||||
if systemExtractor == nil {
|
||||
entry, e := pinnedZipEntry(archive, fileSystemImageName, fileSystemArchiveSize, fileSystemArchiveSize)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
offset, e := entry.DataOffset()
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("locate Store filesystem: %w", e)
|
||||
}
|
||||
|
||||
image, e := newAEAReader(ctx, client, io.NewSectionReader(remote, offset, int64(entry.CompressedSize64)), int64(entry.CompressedSize64))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
if image.size != fileSystemImageSize {
|
||||
return nil, errors.New("store filesystem does not match pinned image")
|
||||
}
|
||||
|
||||
systemExtractor, closeSystem, e = newAPFSExtractor(image, image.size)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
|
||||
f, e := systemExtractor.openFile(ctx, path)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
if f.size > 4<<20 {
|
||||
return nil, errors.New("store system file exceeds size limit")
|
||||
}
|
||||
|
||||
return io.ReadAll(io.NewSectionReader(f, 0, f.size))
|
||||
}
|
||||
}
|
||||
|
||||
return s, err
|
||||
}
|
||||
|
||||
func newStoreCache(ctx context.Context, opener dyldCacheOpener, cleanup func() error) (*StoreCache, error) {
|
||||
if ctx == nil {
|
||||
_ = cleanup()
|
||||
|
||||
return nil, errors.New("store asset context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
_ = cleanup()
|
||||
|
||||
return nil, fmt.Errorf("open Store cache: %w", err)
|
||||
}
|
||||
|
||||
cache, err := openDyldCache(opener)
|
||||
if err != nil {
|
||||
_ = cleanup()
|
||||
|
||||
return nil, fmt.Errorf("open Store shared cache: %w", err)
|
||||
}
|
||||
|
||||
return &StoreCache{cache: cache, ctx: ctx, opener: opener, cleanup: cleanup, slides: make(map[uint64]map[uint64]uint64)}, nil
|
||||
}
|
||||
|
||||
func (s *StoreCache) Close() error {
|
||||
return errors.Join(s.cache.Close(), s.cleanup())
|
||||
}
|
||||
|
||||
// Page returns one unslid 4 KiB data page. Runtime-initialized metadata is applied
|
||||
// separately by the versioned Store profile; these bytes always come from Apple.
|
||||
func (s *StoreCache) Page(address uint64) ([]byte, error) {
|
||||
if err := s.ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("read Store page: %w", err)
|
||||
}
|
||||
|
||||
if address&4095 != 0 {
|
||||
return nil, errors.New("unaligned Store page")
|
||||
}
|
||||
|
||||
mapping, err := s.cache.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data := make([]byte, 4096)
|
||||
reader := &dyldCacheReader{cache: s.cache}
|
||||
|
||||
if _, err = reader.ReadAtAddr(data, address); err != nil {
|
||||
return nil, fmt.Errorf("read Store page: %w", err)
|
||||
}
|
||||
|
||||
if mapping.slideInfoSize == 0 {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
pageSize, err := s.cache.slidePageSize(*mapping)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
index := (address - mapping.address) / pageSize
|
||||
base := mapping.address + index*pageSize
|
||||
|
||||
rebases, ok := s.slides[base]
|
||||
if !ok {
|
||||
values, err := s.cache.rebases(*mapping, index, index+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rebases = make(map[uint64]uint64, len(values))
|
||||
for _, value := range values {
|
||||
rebases[value.address] = value.target
|
||||
}
|
||||
|
||||
s.slides[base] = rebases
|
||||
}
|
||||
|
||||
for location, target := range rebases {
|
||||
if location >= address && location+8 <= address+4096 {
|
||||
binary.LittleEndian.PutUint64(data[location-address:], target)
|
||||
}
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// ExtractAuthenticationPlugin exports the same image on every host platform.
|
||||
func (s *StoreCache) ExtractAuthenticationPlugin(destination string) error {
|
||||
if err := s.ctx.Err(); err != nil {
|
||||
return fmt.Errorf("extract authentication plugin: %w", err)
|
||||
}
|
||||
|
||||
return extractDyldImageFromFiles(s.opener, authenticationPluginImage, destination)
|
||||
}
|
||||
|
||||
// FeatureFlags reads the pinned operating system defaults used by Store metadata.
|
||||
func (s *StoreCache) FeatureFlags(domain string) ([]byte, error) {
|
||||
switch domain {
|
||||
case "AppleMediaServices", "Foundation", "CFNetwork":
|
||||
default:
|
||||
return nil, errors.New("unsupported Store feature domain")
|
||||
}
|
||||
|
||||
return s.readSystemFile("/System/Library/FeatureFlags/Domain/" + domain + ".plist")
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
machotypes "github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
// AddressRange reports the unslid virtual range occupied by cache mappings.
|
||||
func (s *StoreCache) AddressRange() (uint64, uint64) {
|
||||
start, end := ^uint64(0), uint64(0)
|
||||
|
||||
for _, member := range s.cache.members {
|
||||
for _, mapping := range member.mappings {
|
||||
start = min(start, mapping.address)
|
||||
end = max(end, mapping.address+mapping.size)
|
||||
}
|
||||
}
|
||||
|
||||
return start, end - start
|
||||
}
|
||||
|
||||
// Images lists the image install names recorded in the downloaded shared cache.
|
||||
func (s *StoreCache) Images() (map[string]uint64, error) {
|
||||
if s.images != nil {
|
||||
return s.images, nil
|
||||
}
|
||||
|
||||
header := make([]byte, dyldHeaderSize)
|
||||
if _, err := s.cache.primary.file.ReadAt(header, 0); err != nil {
|
||||
return nil, fmt.Errorf("read Store cache header: %w", err)
|
||||
}
|
||||
|
||||
offset := uint64(binary.LittleEndian.Uint32(header[448:]))
|
||||
count := uint64(binary.LittleEndian.Uint32(header[452:]))
|
||||
|
||||
if count == 0 || count > dyldMaximumImages || !validDyldRange(s.cache.primary.size, offset, count*dyldImageInfoSize) {
|
||||
return nil, fmt.Errorf("invalid Store image table")
|
||||
}
|
||||
|
||||
data := make([]byte, count*dyldImageInfoSize)
|
||||
if _, err := s.cache.primary.file.ReadAt(data, int64(offset)); err != nil {
|
||||
return nil, fmt.Errorf("read Store image table: %w", err)
|
||||
}
|
||||
|
||||
images := make(map[string]uint64, count)
|
||||
|
||||
for index := uint64(0); index < count; index++ {
|
||||
entry := data[index*dyldImageInfoSize:]
|
||||
|
||||
name, err := readDyldCString(s.cache.primary.file, s.cache.primary.size, uint64(binary.LittleEndian.Uint32(entry[24:])))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
images[name] = binary.LittleEndian.Uint64(entry)
|
||||
}
|
||||
|
||||
s.images = images
|
||||
|
||||
return images, nil
|
||||
}
|
||||
|
||||
// OpenImage exposes Mach-O metadata directly from the cache; no host image is loaded.
|
||||
func (s *StoreCache) OpenImage(name string) (*macho.File, error) {
|
||||
if s.cache.relativeSelectorBase == 0 {
|
||||
objc, err := s.cache.image("/usr/lib/libobjc.A.dylib")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
f, err := s.cache.openImage(objc, machotypes.LC_SYMTAB, machotypes.LC_DYSYMTAB)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer f.Close()
|
||||
|
||||
for _, section := range f.Sections {
|
||||
if section.Name == "__objc_opt_ro" {
|
||||
page, err := s.Page(section.Addr &^ 4095)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
off := section.Addr & 4095
|
||||
if off+48 > uint64(len(page)) || section.Size < 48 {
|
||||
return nil, fmt.Errorf("invalid ObjC optimization header")
|
||||
}
|
||||
|
||||
if binary.LittleEndian.Uint32(page[off:]) != 16 {
|
||||
return nil, fmt.Errorf("unsupported ObjC optimization version")
|
||||
}
|
||||
|
||||
s.cache.relativeSelectorBase = section.Addr + binary.LittleEndian.Uint64(page[off+40:])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
images, err := s.Images()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
address, ok := images[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("image %s was not found", name)
|
||||
}
|
||||
|
||||
mapping, err := s.cache.mappingForAddress(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.cache.openImage(&dyldImage{member: mapping.member, address: address, offset: mapping.fileOffset + address - mapping.address}, machotypes.LC_SYMTAB, machotypes.LC_DYSYMTAB)
|
||||
}
|
||||
|
||||
// Contains reports whether a range is backed by one shared-cache mapping.
|
||||
func (s *StoreCache) Contains(address, size uint64) bool {
|
||||
for _, member := range s.cache.members {
|
||||
for _, m := range member.mappings {
|
||||
if address >= m.address && address-m.address <= m.size && size <= m.size-(address-m.address) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("macOS 27 asset profile", func() {
|
||||
It("pins the Apple restore image and cache namespace", func() {
|
||||
Expect(macOSVersion).To(Equal("27.0.1"))
|
||||
Expect(macOSBuild).To(Equal("26A434"))
|
||||
Expect(macOSRestoreURL).To(Equal("https://updates.cdn-apple.com/2026FallFCS/59241290-5d51-4ca8-9df4-31624b9a4eac/UniversalMac_27.0.1_26A434_Restore.ipsw"))
|
||||
Expect(assetCacheDirectory).To(ContainSubstring("macos-27-26A434"))
|
||||
})
|
||||
|
||||
It("preserves the pinned legacy artifacts for migration", func() {
|
||||
Expect(legacyFiles).To(ConsistOf(
|
||||
fileSpec{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
|
||||
fileSpec{name: "commerce", size: 8092640, digest: mustDigest("76de40a4a32f691947cb926ce3b128d2fc446f7cac9755f831c406cf5a316ac9")},
|
||||
fileSpec{name: "adid", size: 9797952, digest: mustDigest("1fec225b6917206e3d9b00fe636c04878f82bfd06a87a4b6941711de60efab5b")},
|
||||
fileSpec{name: "CoreFP", size: 94842464, digest: mustDigest("2c30fa2b5f695fd66c0360dce72f54757d03ddb7107549715c12cb359a003b46")},
|
||||
fileSpec{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
|
||||
fileSpec{name: "fairplayd", size: 37689264, digest: mustDigest("28b4c7b2a5a0409c5020da55fc3984713a8e2b0eec8557076c8717f7166d003e")},
|
||||
fileSpec{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
|
||||
))
|
||||
})
|
||||
|
||||
It("pins compact runtime artifacts by size and digest", func() {
|
||||
Expect(requiredFiles).To(ConsistOf(
|
||||
fileSpec{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
|
||||
fileSpec{name: "commerce", size: 2735088, digest: mustDigest("c4b2088dd39aeb353f59cb57597902e8317aec66ae7da0414b03c5f932771343")},
|
||||
fileSpec{name: "adid", size: 3047808, digest: mustDigest("43419a206c28bc93ecb8884256088d18306a0a462350f83adbced8e60a94e390")},
|
||||
fileSpec{name: "CoreFP", size: 30764976, digest: mustDigest("afbc123e688a822d980d5816cc2b52f69fde669d1dca92cf85627e1cbee587f6")},
|
||||
fileSpec{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
|
||||
fileSpec{name: "fairplayd", size: 17389744, digest: mustDigest("1e58d37e9602dd0ca5e24b14762063b6c310248b4d3a94272771d815e4ea1784")},
|
||||
fileSpec{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
|
||||
))
|
||||
})
|
||||
|
||||
It("pins the CoreADI path and deflated kernel entry", func() {
|
||||
Expect(frameworkImagePaths).To(ContainElement("/System/Library/PrivateFrameworks/CoreADI.framework/Versions/A/adid"))
|
||||
archive := &zip.Reader{File: []*zip.File{{FileHeader: zip.FileHeader{
|
||||
Name: kernelCacheName, Method: zip.Deflate,
|
||||
CompressedSize64: kernelCacheCompressedSize, UncompressedSize64: kernelCacheArchiveSize,
|
||||
}}}}
|
||||
_, err := pinnedZipEntry(archive, kernelCacheName, kernelCacheCompressedSize, kernelCacheArchiveSize)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
})
|
||||
|
||||
It("rejects an incomplete bundle", func() {
|
||||
Expect(validate(Bundle{})).To(MatchError(ContainSubstring("AppleMediaServices has size 0")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,821 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"sort"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
"github.com/blacktop/go-macho/pkg/fixupchains"
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
const (
|
||||
pageSize = uint64(0x1000)
|
||||
maxImageSpan = uint64(1 << 30)
|
||||
pointerSize = uint64(8)
|
||||
)
|
||||
|
||||
type Memory interface {
|
||||
MemMap(address, size uint64) error
|
||||
MemWrite(address uint64, data []byte) error
|
||||
}
|
||||
|
||||
type segment struct {
|
||||
name string
|
||||
address uint64
|
||||
size uint64
|
||||
fileOff uint64
|
||||
fileSize uint64
|
||||
}
|
||||
|
||||
type Image struct {
|
||||
name string
|
||||
data []byte
|
||||
modified map[uint64][]byte
|
||||
instructions map[uint64][]instructionPatch
|
||||
file *macho.File
|
||||
base uint64
|
||||
segments []segment
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
chained *fixupchains.DyldChainedFixups
|
||||
fixups []chainedRelocation
|
||||
relocated bool
|
||||
loadedBase uint64
|
||||
}
|
||||
|
||||
func (i *Image) Base() uint64 {
|
||||
return i.base
|
||||
}
|
||||
|
||||
//nolint:wsl // Image validation and fixup discovery are clearer in execution order.
|
||||
func Open(name string, input []byte) (*Image, error) {
|
||||
data, err := arm64Slice(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s: %w", name, err)
|
||||
}
|
||||
|
||||
return openImage(name, data, nil)
|
||||
}
|
||||
|
||||
func openImage(name string, data []byte, modified map[uint64][]byte) (*Image, error) {
|
||||
image := &Image{name: name, data: data, modified: modified}
|
||||
|
||||
var reader io.ReaderAt = bytes.NewReader(data)
|
||||
|
||||
if modified != nil {
|
||||
reader = imageInput{image}
|
||||
}
|
||||
|
||||
var key [sha256.Size]byte
|
||||
|
||||
var preparation imagePreparation
|
||||
|
||||
var cached bool
|
||||
|
||||
if modified != nil {
|
||||
key = sha256.Sum256(data)
|
||||
preparation, cached = imagePreparations.get(key)
|
||||
}
|
||||
|
||||
var file *macho.File
|
||||
|
||||
var err error
|
||||
if cached {
|
||||
file, err = macho.NewFile(reader, macho.FileConfig{LoadExcluding: []types.LoadCmd{types.LC_SYMTAB, types.LC_DYSYMTAB, types.LC_CODE_SIGNATURE}})
|
||||
if err == nil {
|
||||
file.Symtab, file.Dysymtab = preparation.symtab, preparation.dysymtab
|
||||
}
|
||||
} else {
|
||||
file, err = macho.NewFile(reader)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s Mach-O: %w", name, err)
|
||||
}
|
||||
|
||||
if file.CPU != types.CPUArm64 {
|
||||
return nil, fmt.Errorf("open %s: expected arm64 Mach-O, found %s", name, file.CPU)
|
||||
}
|
||||
|
||||
image.file = file
|
||||
image.base = file.GetBaseAddress()
|
||||
|
||||
for _, item := range file.Segments() {
|
||||
image.segments = append(image.segments, segment{
|
||||
name: item.Name,
|
||||
address: item.Addr,
|
||||
size: item.Memsz,
|
||||
fileOff: item.Offset,
|
||||
fileSize: item.Filesz,
|
||||
})
|
||||
}
|
||||
|
||||
if err := image.validateSegments(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cached {
|
||||
image.instructions, image.fixups = preparation.instructions, preparation.fixups
|
||||
image.binds, image.rebases = preparation.binds, preparation.rebases
|
||||
|
||||
return image, nil
|
||||
}
|
||||
|
||||
if err := image.removePointerAuthentication(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if file.HasDyldChainedFixups() {
|
||||
image.chained, err = file.DyldChainedFixups()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s chained fixups: %w", name, err)
|
||||
}
|
||||
|
||||
if _, err := image.chained.Parse(); err != nil {
|
||||
return nil, fmt.Errorf("parse %s chained fixups: %w", name, err)
|
||||
}
|
||||
} else {
|
||||
image.binds, err = file.GetBindInfo()
|
||||
if err != nil && !errors.Is(err, macho.ErrMachODyldInfoNotFound) {
|
||||
return nil, fmt.Errorf("read %s bindings: %w", name, err)
|
||||
}
|
||||
|
||||
image.rebases, err = file.GetRebaseInfo()
|
||||
if err != nil && !errors.Is(err, macho.ErrMachODyldInfoNotFound) {
|
||||
return nil, fmt.Errorf("read %s rebases: %w", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
if modified != nil {
|
||||
if image.chained != nil {
|
||||
image.fixups, err = image.decodeChainedRelocations()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
image.chained = nil
|
||||
}
|
||||
|
||||
imagePreparations.put(key, imagePreparation{instructions: image.instructions, fixups: image.fixups, binds: image.binds, rebases: image.rebases, symtab: file.Symtab, dysymtab: file.Dysymtab})
|
||||
}
|
||||
|
||||
return image, nil
|
||||
}
|
||||
|
||||
func (i *Image) removePointerAuthentication() error {
|
||||
var ranges [][2]uint64
|
||||
|
||||
for _, section := range i.file.Sections {
|
||||
if !section.Flags.IsPureInstructions() && !section.Flags.IsSomeInstructions() {
|
||||
continue
|
||||
}
|
||||
|
||||
start := uint64(section.Offset)
|
||||
|
||||
end, overflow := add(start, section.Size)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("instruction section %s exceeds %s", section.Name, i.name)
|
||||
}
|
||||
|
||||
ranges = append(ranges, [2]uint64{start, end})
|
||||
}
|
||||
|
||||
for _, region := range ranges {
|
||||
for offset := region[0]; offset+4 <= region[1]; offset += 4 {
|
||||
instruction := binary.LittleEndian.Uint32(i.data[offset:])
|
||||
replacement := WithoutPointerAuthentication(instruction)
|
||||
|
||||
if replacement == instruction {
|
||||
continue
|
||||
}
|
||||
|
||||
i.writeInstruction(offset, replacement)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// WithoutPointerAuthentication rewrites ARM64e authentication operations for a
|
||||
// VM with canonical, unsigned pointers. Other instructions are unchanged.
|
||||
func WithoutPointerAuthentication(instruction uint32) uint32 {
|
||||
const nop = uint32(0xd503201f)
|
||||
|
||||
var replacement uint32
|
||||
|
||||
switch instruction & 0xfffffc00 {
|
||||
case 0xd71f0800, 0xd71f0c00, 0xd61f0800, 0xd61f0c00:
|
||||
replacement = 0xd61f0000 | (instruction & 0x3e0) // br xN
|
||||
case 0xd73f0800, 0xd73f0c00, 0xd63f0800, 0xd63f0c00:
|
||||
replacement = 0xd63f0000 | (instruction & 0x3e0) // blr xN
|
||||
case 0xdac10000, 0xdac10400, 0xdac10800, 0xdac10c00,
|
||||
0xdac11000, 0xdac11400, 0xdac11800, 0xdac11c00:
|
||||
replacement = nop
|
||||
default:
|
||||
switch instruction {
|
||||
case 0xd65f0bff, 0xd65f0fff:
|
||||
replacement = 0xd65f03c0 // ret
|
||||
case 0xd503211f, 0xd503215f, 0xd503219f, 0xd50321df,
|
||||
0xd503233f, 0xd503237f, 0xd50323bf, 0xd50323ff,
|
||||
0xd50320ff:
|
||||
replacement = nop
|
||||
default:
|
||||
opcode := instruction & 0xffffffe0
|
||||
if opcode == 0xdac123e0 || opcode == 0xdac127e0 ||
|
||||
opcode == 0xdac12be0 || opcode == 0xdac12fe0 ||
|
||||
opcode == 0xdac133e0 || opcode == 0xdac137e0 ||
|
||||
opcode == 0xdac13be0 || opcode == 0xdac13fe0 ||
|
||||
opcode == 0xdac143e0 || opcode == 0xdac147e0 {
|
||||
replacement = nop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if replacement == 0 {
|
||||
return instruction
|
||||
}
|
||||
|
||||
return replacement
|
||||
}
|
||||
|
||||
// ARM64Slice selects the arm64e image without parsing the other architectures.
|
||||
// The returned view aliases input and must not be modified by the caller.
|
||||
func ARM64Slice(input []byte) ([]byte, error) {
|
||||
if len(input) < 4 || binary.BigEndian.Uint32(input) != types.MagicFat.Int() {
|
||||
return input, nil
|
||||
}
|
||||
|
||||
const headerSize, architectureSize = 8, 20
|
||||
if len(input) < headerSize {
|
||||
return nil, errors.New("truncated universal binary header")
|
||||
}
|
||||
|
||||
count := uint64(binary.BigEndian.Uint32(input[4:]))
|
||||
if count == 0 || count > uint64(len(input)-headerSize)/architectureSize {
|
||||
return nil, errors.New("invalid universal binary architecture count")
|
||||
}
|
||||
|
||||
for index := uint64(0); index < count; index++ {
|
||||
header := input[headerSize+index*architectureSize:]
|
||||
cpu := types.CPU(binary.BigEndian.Uint32(header))
|
||||
subtype := types.CPUSubtype(binary.BigEndian.Uint32(header[4:]))
|
||||
|
||||
if cpu != types.CPUArm64 || subtype&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
|
||||
continue
|
||||
}
|
||||
|
||||
offset := uint64(binary.BigEndian.Uint32(header[8:]))
|
||||
size := uint64(binary.BigEndian.Uint32(header[12:]))
|
||||
end, overflow := add(offset, size)
|
||||
|
||||
if size == 0 || offset < headerSize+count*architectureSize || overflow || end > uint64(len(input)) {
|
||||
return nil, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
|
||||
}
|
||||
|
||||
return input[offset:end], nil
|
||||
}
|
||||
|
||||
return nil, errors.New("universal binary has no arm64e slice")
|
||||
}
|
||||
|
||||
func arm64Slice(input []byte) ([]byte, error) {
|
||||
data, err := ARM64Slice(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return bytes.Clone(data), nil
|
||||
}
|
||||
|
||||
func (i *Image) Export(name string, loadBase uint64) (uint64, error) {
|
||||
address, err := i.file.FindSymbolAddress(name)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("find %s in %s: %w", name, i.name, err)
|
||||
}
|
||||
|
||||
if address < i.base {
|
||||
return 0, fmt.Errorf("symbol %s in %s precedes image base", name, i.name)
|
||||
}
|
||||
|
||||
result, overflow := add(loadBase, address-i.base)
|
||||
if overflow {
|
||||
return 0, fmt.Errorf("symbol %s address overflows in %s", name, i.name)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (i *Image) Relocate(loadBase uint64, resolve func(string) (uint64, error)) error {
|
||||
if i.relocated {
|
||||
return fmt.Errorf("%s is already relocated", i.name)
|
||||
}
|
||||
|
||||
for _, relocation := range i.rebases {
|
||||
if relocation.Type != types.REBASE_TYPE_POINTER {
|
||||
return fmt.Errorf("%s uses unsupported rebase type %d", i.name, relocation.Type)
|
||||
}
|
||||
|
||||
if relocation.Value < i.base {
|
||||
return fmt.Errorf("%s contains a rebase below its image base", i.name)
|
||||
}
|
||||
|
||||
offset, err := i.segmentFileOffset(relocation.Segment, relocation.Offset, pointerSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
address, overflow := add(loadBase, relocation.Value-i.base)
|
||||
if overflow {
|
||||
return fmt.Errorf("rebase address overflows in %s", i.name)
|
||||
}
|
||||
|
||||
if err := i.putPointer(offset, address); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, binding := range i.binds {
|
||||
// Lazy bind streams may omit SET_TYPE; dyld's default is a pointer bind.
|
||||
if binding.Type != 0 && binding.Type != types.BIND_TYPE_POINTER {
|
||||
return fmt.Errorf("%s uses unsupported bind type %d for %s", i.name, binding.Type, binding.Name)
|
||||
}
|
||||
|
||||
offset, err := i.segmentFileOffset(binding.Segment, binding.SegOffset, pointerSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
address, err := resolve(binding.Name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve %s for %s: %w", binding.Name, i.name, err)
|
||||
}
|
||||
|
||||
address, err = addSigned(address, binding.Addend)
|
||||
if err != nil {
|
||||
return fmt.Errorf("apply addend for %s in %s: %w", binding.Name, i.name, err)
|
||||
}
|
||||
|
||||
if err := i.putPointer(offset, address); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := i.relocateChained(loadBase, resolve); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
i.relocated = true
|
||||
i.loadedBase = loadBase
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RelocateKernelCachePointers decodes authenticated pointers embedded in an
|
||||
// executable extracted from a kernel collection. These are already fixed up
|
||||
// for the collection and are not described by the image's standalone Mach-O
|
||||
// bind/rebase streams.
|
||||
func (i *Image) RelocateKernelCachePointers(loadBase, kernelBase uint64, resolve func(string) (uint64, error)) error {
|
||||
externalSymbols := make(map[uint64]string)
|
||||
|
||||
if i.file.Symtab != nil {
|
||||
for _, symbol := range i.file.Symtab.Syms {
|
||||
if symbol.Value == 0 || i.containsAddress(symbol.Value) {
|
||||
continue
|
||||
}
|
||||
|
||||
externalSymbols[symbol.Value] = symbol.Name
|
||||
}
|
||||
}
|
||||
|
||||
for _, item := range i.segments {
|
||||
if item.name == "__TEXT" || item.name == "__TEXT_EXEC" || item.name == "__LINKEDIT" || item.fileSize < pointerSize {
|
||||
continue
|
||||
}
|
||||
|
||||
const kernelFixupStride = uint64(4)
|
||||
|
||||
start := item.fileOff
|
||||
if remainder := item.address % kernelFixupStride; remainder != 0 {
|
||||
start += kernelFixupStride - remainder
|
||||
}
|
||||
|
||||
end := item.fileOff + item.fileSize
|
||||
for offset := start; offset <= end-pointerSize; offset += kernelFixupStride {
|
||||
raw := i.pointerAt(offset)
|
||||
|
||||
pointer := fixupchains.DyldChainedPtr64KernelCacheRebase{Pointer: raw}
|
||||
if pointer.CacheLevel() != 0 || pointer.Target() == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
original, overflow := add(kernelBase, pointer.Target())
|
||||
if overflow {
|
||||
continue
|
||||
}
|
||||
|
||||
var relocated uint64
|
||||
if i.containsAddress(original) {
|
||||
relocated, overflow = add(loadBase, original-i.base)
|
||||
if overflow {
|
||||
return fmt.Errorf("kernel-cache pointer at %#x overflows in %s", offset, i.name)
|
||||
}
|
||||
} else if name, ok := externalSymbols[original]; ok {
|
||||
var err error
|
||||
|
||||
relocated, err = resolve(name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve kernel-cache pointer %s at %#x in %s: %w", name, offset, i.name, err)
|
||||
}
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := i.putPointer(offset, relocated); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Image) containsAddress(address uint64) bool {
|
||||
for _, item := range i.segments {
|
||||
if address >= item.address && address-item.address < item.size {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
//nolint:wsl // Chained-fixup decoding is clearer when related operations stay together.
|
||||
func (i *Image) decodeChainedRelocations() ([]chainedRelocation, error) {
|
||||
if i.chained == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var relocations []chainedRelocation
|
||||
for _, start := range i.chained.Starts {
|
||||
for _, fixup := range start.Fixups {
|
||||
offset := fixup.Offset()
|
||||
if offset > uint64(len(i.data)) || pointerSize > uint64(len(i.data))-offset {
|
||||
return nil, fmt.Errorf("chained fixup at %#x exceeds %s", offset, i.name)
|
||||
}
|
||||
|
||||
relocation := chainedRelocation{offset: offset}
|
||||
|
||||
switch {
|
||||
case fixup.IsRebase():
|
||||
var target uint64
|
||||
switch rebase := fixup.(type) {
|
||||
case fixupchains.DyldChainedPtr64RebaseOffset:
|
||||
// DYLD_CHAINED_PTR_64_OFFSET encodes an image-relative
|
||||
// target. go-macho's Rebase currently subtracts the
|
||||
// preferred address from that offset a second time.
|
||||
target = rebase.UnpackedTarget()
|
||||
case fixupchains.DyldChainedPtrArm64eRebase:
|
||||
target = rebase.Target()
|
||||
|
||||
if i.chained.PointerFormat == fixupchains.DYLD_CHAINED_PTR_ARM64E {
|
||||
absolute := rebase.UnpackTarget() & 0x00ffffffffffffff
|
||||
if absolute < i.base {
|
||||
return nil, fmt.Errorf("chained rebase at %#x precedes the base of %s", offset, i.name)
|
||||
}
|
||||
target = absolute - i.base
|
||||
}
|
||||
case fixupchains.DyldChainedPtrArm64eAuthRebase:
|
||||
target = rebase.Target()
|
||||
default:
|
||||
var err error
|
||||
|
||||
target, err = i.chained.Rebase(offset, i.base)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode chained rebase at %#x in %s: %w", offset, i.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
relocation.target = target
|
||||
case fixup.IsBind():
|
||||
binding, ok := fixup.(fixupchains.Bind)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid chained bind at %#x in %s", offset, i.name)
|
||||
}
|
||||
|
||||
relocation.isBind = true
|
||||
relocation.symbol = binding.Name()
|
||||
|
||||
addend := int64(binding.Addend())
|
||||
switch arm64e := fixup.(type) {
|
||||
case fixupchains.DyldChainedPtrArm64eBind:
|
||||
addend = arm64e.SignExtendedAddend()
|
||||
case fixupchains.DyldChainedPtrArm64eBind24:
|
||||
addend = arm64e.SignExtendedAddend()
|
||||
}
|
||||
if ordinal := binding.Ordinal(); ordinal < uint64(len(i.chained.Imports)) {
|
||||
addend += int64(i.chained.Imports[ordinal].Addend())
|
||||
}
|
||||
|
||||
relocation.addend = addend
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown chained fixup at %#x in %s", offset, i.name)
|
||||
}
|
||||
|
||||
relocations = append(relocations, relocation)
|
||||
}
|
||||
}
|
||||
|
||||
return relocations, nil
|
||||
}
|
||||
|
||||
func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, error)) error {
|
||||
relocations := i.fixups
|
||||
|
||||
if i.chained != nil {
|
||||
var err error
|
||||
|
||||
relocations, err = i.decodeChainedRelocations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, relocation := range relocations {
|
||||
var address uint64
|
||||
|
||||
if relocation.isBind {
|
||||
value, err := resolve(relocation.symbol)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve %s for %s: %w", relocation.symbol, i.name, err)
|
||||
}
|
||||
|
||||
address, err = addSigned(value, relocation.addend)
|
||||
if err != nil {
|
||||
return fmt.Errorf("apply chained addend for %s in %s: %w", relocation.symbol, i.name, err)
|
||||
}
|
||||
} else {
|
||||
var overflow bool
|
||||
|
||||
address, overflow = add(loadBase, relocation.target)
|
||||
if overflow {
|
||||
return fmt.Errorf("chained rebase at %#x with target %#x overflows in %s", relocation.offset, relocation.target, i.name)
|
||||
}
|
||||
}
|
||||
|
||||
if err := i.putPointer(relocation.offset, address); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// PreparePrelinked prepares an image extracted from a dyld shared cache. Such
|
||||
// images have already had their cache slide information applied, so they must
|
||||
// remain at their preferred addresses. external maps cache symbol addresses to
|
||||
// the import names implemented by the emulator.
|
||||
func (i *Image) PreparePrelinked(external map[uint64]string, resolve func(string) (uint64, error)) error {
|
||||
if i.relocated {
|
||||
return fmt.Errorf("%s is already relocated", i.name)
|
||||
}
|
||||
|
||||
patched := make(map[uint64]uint64, len(external))
|
||||
|
||||
for address, name := range external {
|
||||
value, err := resolve(name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve %s for %s: %w", name, i.name, err)
|
||||
}
|
||||
|
||||
patched[address] = value
|
||||
}
|
||||
|
||||
if len(patched) == 0 {
|
||||
i.relocated = true
|
||||
i.loadedBase = i.base
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, item := range i.segments {
|
||||
if item.name == "__TEXT" || item.name == "__LINKEDIT" || item.fileSize < pointerSize {
|
||||
continue
|
||||
}
|
||||
|
||||
start := item.fileOff
|
||||
if remainder := item.address % pointerSize; remainder != 0 {
|
||||
start += pointerSize - remainder
|
||||
}
|
||||
|
||||
end := item.fileOff + item.fileSize
|
||||
for offset := start; offset <= end-pointerSize; offset += pointerSize {
|
||||
current := i.pointerAt(offset)
|
||||
|
||||
value, ok := patched[current]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := i.putPointer(offset, value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
i.relocated = true
|
||||
i.loadedBase = i.base
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Image) Load(memory Memory) error {
|
||||
if !i.relocated {
|
||||
return fmt.Errorf("%s must be relocated before loading", i.name)
|
||||
}
|
||||
|
||||
type memoryRange struct {
|
||||
start uint64
|
||||
end uint64
|
||||
}
|
||||
|
||||
ranges := make([]memoryRange, 0, len(i.segments))
|
||||
|
||||
for _, item := range i.segments {
|
||||
if item.name == "__PAGEZERO" || item.size == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if item.address < i.base {
|
||||
return fmt.Errorf("segment %s in %s precedes image base", item.name, i.name)
|
||||
}
|
||||
|
||||
address, overflow := add(i.loadedBase, item.address-i.base)
|
||||
if overflow {
|
||||
return fmt.Errorf("segment %s address overflows in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
end, overflow := add(address, item.size)
|
||||
if overflow {
|
||||
return fmt.Errorf("segment %s range overflows in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
ranges = append(ranges, memoryRange{start: address - address%pageSize, end: align(end, pageSize)})
|
||||
}
|
||||
|
||||
if len(ranges) == 0 {
|
||||
return fmt.Errorf("%s has no loadable segments", i.name)
|
||||
}
|
||||
|
||||
sort.Slice(ranges, func(left, right int) bool { return ranges[left].start < ranges[right].start })
|
||||
merged := ranges[:0]
|
||||
|
||||
for _, current := range ranges {
|
||||
last := len(merged) - 1
|
||||
if last >= 0 && current.start <= merged[last].end {
|
||||
merged[last].end = max(merged[last].end, current.end)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
merged = append(merged, current)
|
||||
}
|
||||
|
||||
var mapped uint64
|
||||
|
||||
for _, item := range merged {
|
||||
size := item.end - item.start
|
||||
|
||||
mapped, _ = add(mapped, size)
|
||||
if mapped > maxImageSpan {
|
||||
return fmt.Errorf("mapped segments make %s too large", i.name)
|
||||
}
|
||||
|
||||
if err := memory.MemMap(item.start, size); err != nil {
|
||||
return fmt.Errorf("map %s: %w", i.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
var buffer []byte
|
||||
if len(i.modified) > 0 || len(i.instructions) > 0 {
|
||||
buffer = make([]byte, min(128<<10, len(i.data)))
|
||||
}
|
||||
|
||||
for _, item := range i.segments {
|
||||
if item.name == "__PAGEZERO" || item.fileSize == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
end, overflow := add(item.fileOff, item.fileSize)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("segment %s data exceeds %s", item.name, i.name)
|
||||
}
|
||||
|
||||
address, overflow := add(i.loadedBase, item.address-i.base)
|
||||
if overflow {
|
||||
return fmt.Errorf("segment %s address overflows in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
if err := i.writeSegment(memory, address, item.fileOff, end, buffer); err != nil {
|
||||
return fmt.Errorf("write segment %s from %s: %w", item.name, i.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Image) validateSegments() error {
|
||||
for _, item := range i.segments {
|
||||
if item.fileSize > item.size {
|
||||
return fmt.Errorf("segment %s file data exceeds its memory size in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
if _, overflow := add(item.address, item.size); overflow {
|
||||
return fmt.Errorf("segment %s address range overflows in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
end, overflow := add(item.fileOff, item.fileSize)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("segment %s data exceeds %s", item.name, i.name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Image) segmentFileOffset(name string, offset, size uint64) (uint64, error) {
|
||||
for _, item := range i.segments {
|
||||
if item.name != name {
|
||||
continue
|
||||
}
|
||||
|
||||
segmentEnd, overflow := add(offset, size)
|
||||
if overflow || segmentEnd > item.size {
|
||||
return 0, fmt.Errorf("fixup at %#x exceeds segment %s in %s", offset, name, i.name)
|
||||
}
|
||||
|
||||
if segmentEnd > item.fileSize {
|
||||
return 0, fmt.Errorf("fixup at %#x exceeds file data for segment %s in %s", offset, name, i.name)
|
||||
}
|
||||
|
||||
result, overflow := add(item.fileOff, offset)
|
||||
if overflow {
|
||||
return 0, fmt.Errorf("fixup offset overflows in %s", i.name)
|
||||
}
|
||||
|
||||
end, overflow := add(result, size)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return 0, fmt.Errorf("fixup at %#x exceeds %s", result, i.name)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("fixup references unknown segment %s in %s", name, i.name)
|
||||
}
|
||||
|
||||
func (i *Image) putPointer(offset, value uint64) error {
|
||||
end, overflow := add(offset, 8)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("fixup at %#x exceeds %s", offset, i.name)
|
||||
}
|
||||
|
||||
var data [8]byte
|
||||
|
||||
binary.LittleEndian.PutUint64(data[:], value)
|
||||
i.writeAt(offset, data[:])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func addSigned(value uint64, delta int64) (uint64, error) {
|
||||
if delta >= 0 {
|
||||
result, overflow := add(value, uint64(delta))
|
||||
if overflow {
|
||||
return 0, errors.New("address overflow")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
magnitude := uint64(-(delta + 1)) + 1
|
||||
if magnitude > value {
|
||||
return 0, errors.New("address underflow")
|
||||
}
|
||||
|
||||
return value - magnitude, nil
|
||||
}
|
||||
|
||||
func add(left, right uint64) (uint64, bool) {
|
||||
return left + right, right > math.MaxUint64-left
|
||||
}
|
||||
|
||||
func align(value, alignment uint64) uint64 {
|
||||
return (value + alignment - 1) &^ (alignment - 1)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
func TestValidateSegments(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dataLen int
|
||||
segment segment
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "valid",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: 8, fileSize: 16},
|
||||
},
|
||||
{
|
||||
name: "file data exceeds memory",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 8, fileOff: 8, fileSize: 16},
|
||||
wantErr: "file data exceeds its memory size",
|
||||
},
|
||||
{
|
||||
name: "file data exceeds image",
|
||||
dataLen: 16,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: 8, fileSize: 16},
|
||||
wantErr: "data exceeds",
|
||||
},
|
||||
{
|
||||
name: "file range overflows",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: math.MaxUint64 - 7, fileSize: 16},
|
||||
wantErr: "data exceeds",
|
||||
},
|
||||
{
|
||||
name: "address range overflows",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: math.MaxUint64 - 7, size: 16},
|
||||
wantErr: "address range overflows",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
image := Image{name: "test", data: make([]byte, test.dataLen), segments: []segment{test.segment}}
|
||||
|
||||
err := image.validateSegments()
|
||||
if test.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("validateSegments() error = %v", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||||
t.Fatalf("validateSegments() error = %v, want error containing %q", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSegmentFileOffsetBounds(t *testing.T) {
|
||||
image := Image{
|
||||
name: "test",
|
||||
data: make([]byte, 64),
|
||||
segments: []segment{
|
||||
{name: "__DATA", address: 0x1000, size: 24, fileOff: 16, fileSize: 16},
|
||||
{name: "__SHORT", address: 0x2000, size: 16, fileOff: 56, fileSize: 16},
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
segment string
|
||||
offset uint64
|
||||
want uint64
|
||||
wantErr string
|
||||
}{
|
||||
{name: "valid at end", segment: "__DATA", offset: 8, want: 24},
|
||||
{name: "past file data", segment: "__DATA", offset: 9, wantErr: "exceeds file data"},
|
||||
{name: "past memory", segment: "__DATA", offset: 17, wantErr: "exceeds segment"},
|
||||
{name: "past image", segment: "__SHORT", offset: 8, wantErr: "exceeds test"},
|
||||
{name: "offset overflow", segment: "__DATA", offset: math.MaxUint64 - 3, wantErr: "exceeds segment"},
|
||||
{name: "unknown segment", segment: "__MISSING", wantErr: "unknown segment"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := image.segmentFileOffset(test.segment, test.offset, pointerSize)
|
||||
if test.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("segmentFileOffset() error = %v", err)
|
||||
}
|
||||
|
||||
if got != test.want {
|
||||
t.Fatalf("segmentFileOffset() = %#x, want %#x", got, test.want)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||||
t.Fatalf("segmentFileOffset() error = %v, want error containing %q", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelocateRejectsFixupsOutsideTheirSegments(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
}{
|
||||
{
|
||||
name: "bind",
|
||||
binds: []types.Bind{{Name: "symbol", Segment: "__DATA", SegOffset: 9}},
|
||||
},
|
||||
{
|
||||
name: "rebase",
|
||||
rebases: []types.Rebase{{Type: types.REBASE_TYPE_POINTER, Segment: "__DATA", Offset: 9, Value: 0x1000}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
image := Image{
|
||||
name: "test",
|
||||
data: make([]byte, 64),
|
||||
base: 0x1000,
|
||||
segments: []segment{{name: "__DATA", address: 0x1000, size: 32, fileOff: 16, fileSize: 16}},
|
||||
binds: test.binds,
|
||||
rebases: test.rebases,
|
||||
}
|
||||
|
||||
err := image.Relocate(0x2000, func(string) (uint64, error) { return 0x3000, nil })
|
||||
if err == nil || !strings.Contains(err.Error(), "exceeds file data") {
|
||||
t.Fatalf("Relocate() error = %v, want file-data bounds error", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package machimage
|
||||
|
||||
import "github.com/blacktop/go-macho"
|
||||
|
||||
// Symbols returns the immutable symbol table used for guest exports and ivars.
|
||||
// Callers must not modify the returned slice.
|
||||
func (i *Image) Symbols() []macho.Symbol {
|
||||
if i.file.Symtab == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return i.file.Symtab.Syms
|
||||
}
|
||||
|
||||
// InstructionRanges returns the guest's executable section address ranges.
|
||||
func (i *Image) InstructionRanges() [][2]uint64 {
|
||||
var ranges [][2]uint64
|
||||
|
||||
for _, section := range i.file.Sections {
|
||||
if section.Flags.IsPureInstructions() || section.Flags.IsSomeInstructions() {
|
||||
ranges = append(ranges, [2]uint64{section.Addr, section.Addr + section.Size})
|
||||
}
|
||||
}
|
||||
|
||||
return ranges
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
const (
|
||||
maxImagePreparations = 8
|
||||
maxPreparationBytes = 64 << 20
|
||||
)
|
||||
|
||||
type chainedRelocation struct {
|
||||
offset, target uint64
|
||||
addend int64
|
||||
symbol string
|
||||
isBind bool
|
||||
}
|
||||
|
||||
type instructionPatch struct {
|
||||
offset uint64
|
||||
value uint32
|
||||
}
|
||||
|
||||
type imagePreparation struct {
|
||||
instructions map[uint64][]instructionPatch
|
||||
fixups []chainedRelocation
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
symtab *macho.Symtab
|
||||
dysymtab *macho.Dysymtab
|
||||
}
|
||||
|
||||
func (p imagePreparation) size() int {
|
||||
size := cap(p.fixups)*int(unsafe.Sizeof(chainedRelocation{})) + cap(p.binds)*int(unsafe.Sizeof(types.Bind{})) + cap(p.rebases)*int(unsafe.Sizeof(types.Rebase{}))
|
||||
for _, patches := range p.instructions {
|
||||
size += cap(patches) * int(unsafe.Sizeof(instructionPatch{}))
|
||||
}
|
||||
|
||||
for _, fixup := range p.fixups {
|
||||
size += len(fixup.symbol)
|
||||
}
|
||||
|
||||
for _, bind := range p.binds {
|
||||
size += len(bind.Name)
|
||||
}
|
||||
|
||||
if p.symtab != nil {
|
||||
size += cap(p.symtab.Syms)*int(unsafe.Sizeof(macho.Symbol{})) + cap(p.symtab.LoadBytes)
|
||||
for _, symbol := range p.symtab.Syms {
|
||||
size += len(symbol.Name) + len(symbol.IndirectName)
|
||||
}
|
||||
}
|
||||
|
||||
if p.dysymtab != nil {
|
||||
size += cap(p.dysymtab.IndirectSyms)*4 + cap(p.dysymtab.LoadBytes)
|
||||
}
|
||||
|
||||
return size
|
||||
}
|
||||
|
||||
type imagePreparationCache struct {
|
||||
mu sync.Mutex
|
||||
entries map[[sha256.Size]byte]imagePreparation
|
||||
order [][sha256.Size]byte
|
||||
bytes int
|
||||
}
|
||||
|
||||
// Cache only immutable instruction patches, symbol tables and decoded relocations. Every guest
|
||||
// supplies its own load bases, import addresses and mutable memory.
|
||||
var imagePreparations imagePreparationCache
|
||||
|
||||
func (c *imagePreparationCache) get(key [sha256.Size]byte) (imagePreparation, bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
prepared, ok := c.entries[key]
|
||||
|
||||
return prepared, ok
|
||||
}
|
||||
|
||||
func (c *imagePreparationCache) put(key [sha256.Size]byte, prepared imagePreparation) {
|
||||
size := prepared.size()
|
||||
if size > maxPreparationBytes {
|
||||
return
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if _, exists := c.entries[key]; exists {
|
||||
return
|
||||
}
|
||||
|
||||
if c.entries == nil {
|
||||
c.entries = make(map[[sha256.Size]byte]imagePreparation)
|
||||
}
|
||||
|
||||
for len(c.order) >= maxImagePreparations || c.bytes+size > maxPreparationBytes {
|
||||
oldest := c.order[0]
|
||||
c.bytes -= c.entries[oldest].size()
|
||||
delete(c.entries, oldest)
|
||||
c.order = c.order[1:]
|
||||
}
|
||||
|
||||
c.order = append(c.order, key)
|
||||
c.entries[key] = prepared
|
||||
c.bytes += size
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
// ARM64Range locates a thin image or the arm64e slice using only its headers.
|
||||
// It leaves unselected architectures unread for range-backed remote sources.
|
||||
func ARM64Range(source io.ReaderAt, size int64) (int64, int64, error) {
|
||||
if size < 0 {
|
||||
return 0, 0, errors.New("invalid image size")
|
||||
}
|
||||
|
||||
var header [8]byte
|
||||
|
||||
if size < 4 {
|
||||
return 0, size, nil
|
||||
}
|
||||
|
||||
if _, err := source.ReadAt(header[:4], 0); err != nil {
|
||||
return 0, 0, fmt.Errorf("read image magic: %w", err)
|
||||
}
|
||||
|
||||
if binary.BigEndian.Uint32(header[:]) != types.MagicFat.Int() {
|
||||
return 0, size, nil
|
||||
}
|
||||
|
||||
if size < 8 {
|
||||
return 0, 0, errors.New("truncated universal binary header")
|
||||
}
|
||||
|
||||
if _, err := source.ReadAt(header[4:], 4); err != nil {
|
||||
return 0, 0, fmt.Errorf("read universal binary header: %w", err)
|
||||
}
|
||||
|
||||
count := int64(binary.BigEndian.Uint32(header[4:]))
|
||||
if count == 0 || count > (size-8)/20 {
|
||||
return 0, 0, errors.New("invalid universal binary architecture count")
|
||||
}
|
||||
|
||||
var architecture [20]byte
|
||||
for index := int64(0); index < count; index++ {
|
||||
if _, err := source.ReadAt(architecture[:], 8+index*20); err != nil {
|
||||
return 0, 0, fmt.Errorf("read universal binary architecture: %w", err)
|
||||
}
|
||||
|
||||
cpu := types.CPU(binary.BigEndian.Uint32(architecture[:]))
|
||||
subtype := types.CPUSubtype(binary.BigEndian.Uint32(architecture[4:]))
|
||||
|
||||
if cpu != types.CPUArm64 || subtype&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
|
||||
continue
|
||||
}
|
||||
|
||||
offset, length := int64(binary.BigEndian.Uint32(architecture[8:])), int64(binary.BigEndian.Uint32(architecture[12:]))
|
||||
if length == 0 || offset < 8+count*20 || offset > size || length > size-offset {
|
||||
return 0, 0, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
|
||||
}
|
||||
|
||||
return offset, length, nil
|
||||
}
|
||||
|
||||
return 0, 0, errors.New("universal binary has no arm64e slice")
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
type headerReader struct {
|
||||
input []byte
|
||||
read int
|
||||
end int64
|
||||
}
|
||||
|
||||
func (r *headerReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||
r.read += len(data)
|
||||
r.end = max(r.end, offset+int64(len(data)))
|
||||
|
||||
return bytes.NewReader(r.input).ReadAt(data, offset) //nolint:wrapcheck // ReaderAt adapters preserve io.EOF.
|
||||
}
|
||||
|
||||
var _ = Describe("Remote architecture selection", func() {
|
||||
It("reads only the architecture headers", func() {
|
||||
input := universalImage()
|
||||
reader := &headerReader{input: input}
|
||||
offset, size, err := ARM64Range(reader, int64(len(input)))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(offset).To(Equal(int64(52)))
|
||||
Expect(size).To(Equal(int64(4)))
|
||||
Expect(reader.end).To(BeNumerically("<=", 48))
|
||||
Expect(reader.read).To(BeNumerically("<=", 48))
|
||||
})
|
||||
It("keeps thin images whole", func() {
|
||||
data := []byte("thin image")
|
||||
reader := &headerReader{input: data}
|
||||
offset, size, err := ARM64Range(reader, int64(len(data)))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(offset).To(BeZero())
|
||||
Expect(size).To(Equal(int64(len(data))))
|
||||
Expect(reader.read).To(Equal(4))
|
||||
})
|
||||
It("rejects invalid counts and out-of-bounds slices", func() {
|
||||
for _, index := range []int{4, 36, 40} {
|
||||
data := universalImage()
|
||||
binary.BigEndian.PutUint32(data[index:], ^uint32(0))
|
||||
_, _, err := ARM64Range(bytes.NewReader(data), int64(len(data)))
|
||||
Expect(err).To(HaveOccurred())
|
||||
}
|
||||
})
|
||||
It("reports truncated headers and missing arm64e slices", func() {
|
||||
data := universalImage()
|
||||
_, _, err := ARM64Range(bytes.NewReader(data[:10]), int64(len(data)))
|
||||
Expect(err).To(HaveOccurred())
|
||||
binary.BigEndian.PutUint32(data[32:], 0)
|
||||
_, _, err = ARM64Range(bytes.NewReader(data), int64(len(data)))
|
||||
Expect(err).To(MatchError(ContainSubstring("no arm64e slice")))
|
||||
})
|
||||
It("handles tiny files and rejects a negative declared size", func() {
|
||||
_, size, err := ARM64Range(bytes.NewReader([]byte{1}), 1)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(size).To(Equal(int64(1)))
|
||||
_, _, err = ARM64Range(bytes.NewReader(nil), -1)
|
||||
Expect(err).To(HaveOccurred())
|
||||
_, _, err = ARM64Range(io.NewSectionReader(bytes.NewReader(nil), 0, 4), 4)
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,103 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
// ReadARM64 consumes exactly size bytes, retaining only the arm64e image of a
|
||||
// universal binary. A caller can hash the entire input with an io.TeeReader.
|
||||
func ReadARM64(input io.Reader, size int) ([]byte, error) {
|
||||
if size < 0 {
|
||||
return nil, errors.New("invalid image size")
|
||||
}
|
||||
|
||||
var header [8]byte
|
||||
|
||||
prefix := min(size, 4)
|
||||
if _, err := io.ReadFull(input, header[:prefix]); err != nil {
|
||||
return nil, fmt.Errorf("read image magic: %w", err)
|
||||
}
|
||||
|
||||
if prefix < 4 || binary.BigEndian.Uint32(header[:]) != types.MagicFat.Int() {
|
||||
data := make([]byte, size)
|
||||
copy(data, header[:prefix])
|
||||
|
||||
if _, err := io.ReadFull(input, data[prefix:]); err != nil {
|
||||
return nil, fmt.Errorf("read thin image: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
if size < 8 {
|
||||
return nil, errors.New("truncated universal binary header")
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(input, header[4:]); err != nil {
|
||||
return nil, fmt.Errorf("read universal binary header: %w", err)
|
||||
}
|
||||
|
||||
count := uint64(binary.BigEndian.Uint32(header[4:]))
|
||||
if count == 0 || count > uint64(size-8)/20 {
|
||||
return nil, errors.New("invalid universal binary architecture count")
|
||||
}
|
||||
|
||||
var offset, length uint64
|
||||
|
||||
var arch [20]byte
|
||||
for range count {
|
||||
if _, err := io.ReadFull(input, arch[:]); err != nil {
|
||||
return nil, fmt.Errorf("read universal binary architecture: %w", err)
|
||||
}
|
||||
|
||||
cpu := types.CPU(binary.BigEndian.Uint32(arch[:]))
|
||||
subtype := types.CPUSubtype(binary.BigEndian.Uint32(arch[4:]))
|
||||
|
||||
if length == 0 && cpu == types.CPUArm64 && subtype&types.CpuSubtypeMask == types.CPUSubtypeArm64E {
|
||||
offset = uint64(binary.BigEndian.Uint32(arch[8:]))
|
||||
length = uint64(binary.BigEndian.Uint32(arch[12:]))
|
||||
|
||||
if length == 0 || offset < 8+count*20 || offset+length > uint64(size) {
|
||||
return nil, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if length == 0 {
|
||||
return nil, errors.New("universal binary has no arm64e slice")
|
||||
}
|
||||
|
||||
buffer := make([]byte, 256<<10)
|
||||
if err := discardImageBytes(input, offset-(8+count*20), buffer); err != nil {
|
||||
return nil, fmt.Errorf("read universal binary prefix: %w", err)
|
||||
}
|
||||
|
||||
data := make([]byte, int(length))
|
||||
if _, err := io.ReadFull(input, data); err != nil {
|
||||
return nil, fmt.Errorf("read arm64e image: %w", err)
|
||||
}
|
||||
|
||||
if err := discardImageBytes(input, uint64(size)-offset-length, buffer); err != nil {
|
||||
return nil, fmt.Errorf("read universal binary suffix: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func discardImageBytes(input io.Reader, count uint64, buffer []byte) error {
|
||||
for count > 0 {
|
||||
size := min(count, uint64(len(buffer)))
|
||||
if _, err := io.ReadFull(input, buffer[:size]); err != nil {
|
||||
return fmt.Errorf("consume image bytes: %w", err)
|
||||
}
|
||||
|
||||
count -= size
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Streaming ARM64 extraction", func() {
|
||||
It("hashes discarded bytes and stops at the declared size", func() {
|
||||
fat := append(universalImage(), []byte("unused suffix")...)
|
||||
reader := bytes.NewReader(append(bytes.Clone(fat), []byte("trailer")...))
|
||||
digest := sha256.New()
|
||||
data, err := ReadARM64(io.TeeReader(reader, digest), len(fat))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).To(Equal("arm!"))
|
||||
expected := sha256.Sum256(fat)
|
||||
Expect(digest.Sum(nil)).To(Equal(expected[:]))
|
||||
trailing, err := io.ReadAll(reader)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(trailing)).To(Equal("trailer"))
|
||||
})
|
||||
It("preserves thin and short input", func() {
|
||||
for _, input := range [][]byte{nil, {1}, {1, 2, 3}, []byte("thin image")} {
|
||||
data, err := ReadARM64(bytes.NewReader(input), len(input))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(bytes.Equal(data, input)).To(BeTrue())
|
||||
}
|
||||
})
|
||||
It("rejects a negative size", func() {
|
||||
_, err := ReadARM64(bytes.NewReader(nil), -1)
|
||||
Expect(err).To(MatchError(ContainSubstring("invalid image size")))
|
||||
})
|
||||
It("rejects truncation before, inside, and after the selected slice", func() {
|
||||
input := append(universalImage(), []byte("suffix")...)
|
||||
for _, length := range []int{0, 4, 7, 20, 48, 53, 55, 59} {
|
||||
_, err := ReadARM64(bytes.NewReader(input[:length]), len(input))
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)).To(BeTrue())
|
||||
}
|
||||
})
|
||||
It("rejects invalid architecture ranges before allocating their data", func() {
|
||||
input := universalImage()
|
||||
input[40] = 0xff
|
||||
_, err := ReadARM64(bytes.NewReader(input), len(input))
|
||||
Expect(err).To(MatchError(ContainSubstring("exceeds input size")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,159 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// OpenShared borrows immutable image bytes and copies only pages changed by
|
||||
// relocation. Instruction patches are applied while loading into guest memory.
|
||||
// Input must remain unchanged while the Image is used.
|
||||
func OpenShared(name string, input []byte) (*Image, error) {
|
||||
data, err := ARM64Slice(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s: %w", name, err)
|
||||
}
|
||||
|
||||
return openImage(name, data, make(map[uint64][]byte))
|
||||
}
|
||||
|
||||
func (i *Image) writeAt(offset uint64, data []byte) {
|
||||
if i.modified == nil {
|
||||
copy(i.data[offset:], data)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for len(data) > 0 {
|
||||
page := offset &^ (pageSize - 1)
|
||||
buffer := i.modified[page]
|
||||
|
||||
if buffer == nil {
|
||||
buffer = bytes.Clone(i.data[page:min(page+pageSize, uint64(len(i.data)))])
|
||||
i.overlay(buffer, page)
|
||||
i.modified[page] = buffer
|
||||
}
|
||||
|
||||
count := copy(buffer[offset-page:], data)
|
||||
offset += uint64(count)
|
||||
data = data[count:]
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Image) pointerAt(offset uint64) uint64 {
|
||||
pageStart := offset &^ (pageSize - 1)
|
||||
if offset+pointerSize <= pageStart+pageSize {
|
||||
if page := i.modified[pageStart]; page != nil {
|
||||
return binary.LittleEndian.Uint64(page[offset-pageStart:])
|
||||
}
|
||||
|
||||
if len(i.instructions[pageStart]) == 0 {
|
||||
return binary.LittleEndian.Uint64(i.data[offset:])
|
||||
}
|
||||
}
|
||||
|
||||
var value [8]byte
|
||||
|
||||
copy(value[:], i.data[offset:offset+8])
|
||||
i.overlay(value[:], offset)
|
||||
|
||||
return binary.LittleEndian.Uint64(value[:])
|
||||
}
|
||||
|
||||
func (i *Image) writeInstruction(offset uint64, value uint32) {
|
||||
if i.modified != nil {
|
||||
if i.instructions == nil {
|
||||
i.instructions = make(map[uint64][]instructionPatch)
|
||||
}
|
||||
|
||||
for page := offset &^ (pageSize - 1); page < offset+4; page += pageSize {
|
||||
i.instructions[page] = append(i.instructions[page], instructionPatch{offset, value})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var data [4]byte
|
||||
|
||||
binary.LittleEndian.PutUint32(data[:], value)
|
||||
i.writeAt(offset, data[:])
|
||||
}
|
||||
|
||||
// Overlay private relocations and immutable instruction patches. Clip each page
|
||||
// and patch to the destination, including unaligned segment and chunk boundaries.
|
||||
func (i *Image) overlay(data []byte, offset uint64) {
|
||||
end := offset + uint64(len(data))
|
||||
for page := offset &^ (pageSize - 1); page < end; page += pageSize {
|
||||
first, last := max(page, offset), min(page+pageSize, end)
|
||||
if modified := i.modified[page]; modified != nil {
|
||||
copy(data[first-offset:last-offset], modified[first-page:last-page])
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
for _, patch := range i.instructions[page] {
|
||||
start, stop := max(first, patch.offset), min(last, patch.offset+4)
|
||||
if start >= stop {
|
||||
continue
|
||||
}
|
||||
|
||||
var encoded [4]byte
|
||||
|
||||
binary.LittleEndian.PutUint32(encoded[:], patch.value)
|
||||
copy(data[start-offset:stop-offset], encoded[start-patch.offset:stop-patch.offset])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep staging memory bounded regardless of image size and guest count.
|
||||
func (i *Image) writeSegment(memory Memory, address, start, end uint64, buffer []byte) error {
|
||||
if len(i.modified) == 0 && len(i.instructions) == 0 {
|
||||
if err := memory.MemWrite(address, i.data[start:end]); err != nil {
|
||||
return fmt.Errorf("write image data: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
for position := start; position < end; {
|
||||
stop := min(position+uint64(len(buffer)), end)
|
||||
data := buffer[:stop-position]
|
||||
copy(data, i.data[position:stop])
|
||||
i.overlay(data, position)
|
||||
|
||||
if err := memory.MemWrite(address+position-start, data); err != nil {
|
||||
return fmt.Errorf("write image chunk: %w", err)
|
||||
}
|
||||
|
||||
position = stop
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Mach-O fixup parsing must observe the same rewritten bytes that will be loaded
|
||||
// into the guest, including instruction patches in mixed code/data sections.
|
||||
type imageInput struct{ image *Image }
|
||||
|
||||
func (r imageInput) ReadAt(data []byte, offset int64) (int, error) {
|
||||
if offset < 0 {
|
||||
return 0, fmt.Errorf("invalid image offset %d", offset)
|
||||
}
|
||||
|
||||
if offset >= int64(len(r.image.data)) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
count := copy(data, r.image.data[offset:])
|
||||
if len(r.image.instructions) > 0 || len(r.image.modified) > 0 {
|
||||
r.image.overlay(data[:count], uint64(offset))
|
||||
}
|
||||
|
||||
if count < len(data) {
|
||||
return count, io.EOF
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
// One instruction page and one data page following the Mach-O headers.
|
||||
func sharedFixture() []byte {
|
||||
data := make([]byte, 3*pageSize)
|
||||
for n, v := range []uint32{0xfeedfacf, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 6, 2, 176, 0, 0} {
|
||||
binary.LittleEndian.PutUint32(data[n*4:], v)
|
||||
}
|
||||
|
||||
binary.LittleEndian.PutUint32(data[32:], 25)
|
||||
binary.LittleEndian.PutUint32(data[36:], 152)
|
||||
copy(data[40:], "__TEXT")
|
||||
|
||||
for n, v := range []uint64{0x100000000, uint64(len(data)), 0, uint64(len(data))} {
|
||||
binary.LittleEndian.PutUint64(data[56+n*8:], v)
|
||||
}
|
||||
|
||||
for n, v := range []uint32{7, 7, 1, 0} {
|
||||
binary.LittleEndian.PutUint32(data[88+n*4:], v)
|
||||
}
|
||||
|
||||
copy(data[104:], "__text")
|
||||
copy(data[120:], "__TEXT")
|
||||
binary.LittleEndian.PutUint64(data[136:], 0x100001000)
|
||||
binary.LittleEndian.PutUint64(data[144:], pageSize)
|
||||
binary.LittleEndian.PutUint32(data[152:], uint32(pageSize))
|
||||
binary.LittleEndian.PutUint32(data[156:], 2)
|
||||
binary.LittleEndian.PutUint32(data[168:], 0x80000400)
|
||||
|
||||
for n, v := range []uint32{2, 24, 512, 1, 528, 8} {
|
||||
binary.LittleEndian.PutUint32(data[184+n*4:], v)
|
||||
}
|
||||
|
||||
binary.LittleEndian.PutUint32(data[512:], 1)
|
||||
data[516], data[517] = 0x0f, 1
|
||||
binary.LittleEndian.PutUint64(data[520:], 0x100001000)
|
||||
copy(data[528:], []byte{0, 't', 'a', 'r', 'g', 'e', 't', 0})
|
||||
binary.LittleEndian.PutUint32(data[4096:], 0xd503233f)
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
type imageMemory struct {
|
||||
data []byte
|
||||
base uint64
|
||||
fail error
|
||||
}
|
||||
|
||||
func (m *imageMemory) MemMap(uint64, uint64) error { return nil }
|
||||
func (m *imageMemory) MemWrite(address uint64, data []byte) error {
|
||||
if m.fail != nil {
|
||||
return m.fail
|
||||
}
|
||||
|
||||
copy(m.data[address-m.base:], data)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ = Describe("Shared image preparation", func() {
|
||||
It("shares instruction patches and isolates relocation and source bytes", func() {
|
||||
source := sharedFixture()
|
||||
original := bytes.Clone(source)
|
||||
first, err := OpenShared("first", source)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
second, err := OpenShared("second", source)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(&first.data[0]).To(BeIdenticalTo(&source[0]))
|
||||
Expect(&first.instructions[4096][0]).To(BeIdenticalTo(&second.instructions[4096][0]))
|
||||
Expect(first.modified).To(BeEmpty())
|
||||
Expect(first.file.Symtab).To(BeIdenticalTo(second.file.Symtab))
|
||||
exported, err := second.Export("target", 0x300000000)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(exported).To(Equal(uint64(0x300001000)))
|
||||
Expect(second.InstructionRanges()).To(Equal([][2]uint64{{0x100001000, 0x100002000}}))
|
||||
Expect(second.Symbols()).To(HaveLen(1))
|
||||
first.binds = []types.Bind{{Name: "target", Segment: "__TEXT", SegOffset: 8192, Type: types.BIND_TYPE_POINTER}}
|
||||
second.binds = first.binds
|
||||
Expect(first.Relocate(0x200000000, func(string) (uint64, error) { return 0x1111, nil })).To(Succeed())
|
||||
Expect(second.Relocate(0x300000000, func(string) (uint64, error) { return 0x2222, nil })).To(Succeed())
|
||||
Expect(second.putPointer(4092, 0x8877665544332211)).To(Succeed())
|
||||
Expect(second.pointerAt(4092)).To(Equal(uint64(0x8877665544332211)))
|
||||
Expect(first.pointerAt(4092)).To(Equal(uint64(0xd503201f00000000)))
|
||||
for _, test := range []struct {
|
||||
image *Image
|
||||
base, value uint64
|
||||
}{{first, 0x200000000, 0x1111}, {second, 0x300000000, 0x2222}} {
|
||||
memory := &imageMemory{base: test.base, data: make([]byte, len(source))}
|
||||
Expect(test.image.Load(memory)).To(Succeed())
|
||||
Expect(binary.LittleEndian.Uint64(memory.data[8192:])).To(Equal(test.value))
|
||||
if test.image == first {
|
||||
Expect(binary.LittleEndian.Uint32(memory.data[4096:])).To(Equal(uint32(0xd503201f)))
|
||||
}
|
||||
}
|
||||
Expect(source).To(Equal(original))
|
||||
})
|
||||
It("keeps concurrent guests independent while sharing preparation", func() {
|
||||
source := sharedFixture()
|
||||
source[len(source)-2] = 77
|
||||
finished := make(chan error, 8)
|
||||
for n := range 8 {
|
||||
go func() {
|
||||
image, err := OpenShared("concurrent", source)
|
||||
if err == nil {
|
||||
image.binds = []types.Bind{{Name: "target", Segment: "__TEXT", SegOffset: 8192, Type: types.BIND_TYPE_POINTER}}
|
||||
expected := uint64(n+1) * 4096
|
||||
err = image.Relocate(uint64(n+1)<<32, func(string) (uint64, error) { return expected, nil })
|
||||
if err == nil && image.pointerAt(8192) != expected {
|
||||
err = fmt.Errorf("guest %d has another guest's binding", n)
|
||||
}
|
||||
}
|
||||
finished <- err
|
||||
}()
|
||||
}
|
||||
for range 8 {
|
||||
Eventually(finished).Should(Receive(BeNil()))
|
||||
}
|
||||
})
|
||||
|
||||
It("applies cached chained relocations with each guest's own addresses", func() {
|
||||
source := make([]byte, 4096)
|
||||
plan := []chainedRelocation{{offset: 0, target: 0x80}, {offset: 8, isBind: true, symbol: "target", addend: -4}}
|
||||
for _, base := range []uint64{0x1000, 0x2000} {
|
||||
image := &Image{data: source, modified: map[uint64][]byte{}, fixups: plan}
|
||||
Expect(image.relocateChained(base, func(string) (uint64, error) { return base + 0x404, nil })).To(Succeed())
|
||||
Expect(image.pointerAt(0)).To(Equal(base + 0x80))
|
||||
Expect(image.pointerAt(8)).To(Equal(base + 0x400))
|
||||
}
|
||||
Expect(source).To(Equal(make([]byte, 4096)))
|
||||
})
|
||||
It("overlays patches across unaligned page, segment, and chunk boundaries", func() {
|
||||
source := make([]byte, 3*pageSize+13)
|
||||
image := &Image{data: source, modified: map[uint64][]byte{}}
|
||||
image.writeInstruction(4094, 0x11223344)
|
||||
Expect(image.pointerAt(4092)).To(Equal(uint64(0x112233440000)))
|
||||
var decoded [8]byte
|
||||
count, err := (imageInput{image}).ReadAt(decoded[:], 4092)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(8))
|
||||
Expect(binary.LittleEndian.Uint64(decoded[:])).To(Equal(uint64(0x112233440000)))
|
||||
Expect(image.putPointer(4095, 0xaabbccddeeff0011)).To(Succeed())
|
||||
expected := bytes.Clone(source)
|
||||
binary.LittleEndian.PutUint32(expected[4094:], 0x11223344)
|
||||
binary.LittleEndian.PutUint64(expected[4095:], 0xaabbccddeeff0011)
|
||||
memory := &imageMemory{data: make([]byte, len(source))}
|
||||
Expect(image.writeSegment(memory, 0, 3, uint64(len(source)), make([]byte, 4093))).To(Succeed())
|
||||
Expect(memory.data[:len(source)-3]).To(Equal(expected[3:]))
|
||||
})
|
||||
It("invalidates preparation when any source byte changes", func() {
|
||||
source := sharedFixture()
|
||||
first, err := OpenShared("first", source)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
changed := bytes.Clone(source)
|
||||
changed[len(changed)-1] = 1
|
||||
second, err := OpenShared("second", changed)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(&first.instructions[4096][0]).NotTo(BeIdenticalTo(&second.instructions[4096][0]))
|
||||
})
|
||||
It("preserves write errors and rejects fixups outside the image", func() {
|
||||
image, err := OpenShared("image", sharedFixture())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(image.Relocate(image.Base(), nil)).To(Succeed())
|
||||
failed := errors.New("write failure")
|
||||
Expect(errors.Is(image.Load(&imageMemory{fail: failed}), failed)).To(BeTrue())
|
||||
Expect(image.putPointer(uint64(len(image.data)-7), 1)).NotTo(Succeed())
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Image preparation cache bounds", func() {
|
||||
It("evicts old preparations when the image count is exceeded", func() {
|
||||
var cache imagePreparationCache
|
||||
first := sha256.Sum256([]byte{0})
|
||||
for n := 0; n <= maxImagePreparations; n++ {
|
||||
cache.put(sha256.Sum256([]byte{byte(n)}), imagePreparation{})
|
||||
}
|
||||
_, ok := cache.get(first)
|
||||
Expect(ok).To(BeFalse())
|
||||
Expect(cache.entries).To(HaveLen(maxImagePreparations))
|
||||
})
|
||||
It("bounds retained patch and fixup storage", func() {
|
||||
var cache imagePreparationCache
|
||||
key := sha256.Sum256([]byte("first"))
|
||||
large := imagePreparation{instructions: map[uint64][]instructionPatch{0: make([]instructionPatch, 0, maxPreparationBytes/16+1)}}
|
||||
cache.put(key, large)
|
||||
_, ok := cache.get(key)
|
||||
Expect(ok).To(BeFalse())
|
||||
half := imagePreparation{instructions: map[uint64][]instructionPatch{0: large.instructions[0][: 0 : maxPreparationBytes/32+1]}}
|
||||
cache.put(key, half)
|
||||
second := sha256.Sum256([]byte("second"))
|
||||
cache.put(second, half)
|
||||
_, ok = cache.get(key)
|
||||
Expect(ok).To(BeFalse())
|
||||
Expect(cache.bytes).To(BeNumerically("<=", maxPreparationBytes))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"testing"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestImageGinkgo(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Mach-O Image Suite")
|
||||
}
|
||||
|
||||
func universalImage() []byte {
|
||||
data := make([]byte, 56)
|
||||
for index, value := range []uint32{
|
||||
types.MagicFat.Int(), 2,
|
||||
uint32(types.CPUAmd64), 3, 48, 4, 0,
|
||||
uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 52, 4, 0,
|
||||
} {
|
||||
binary.BigEndian.PutUint32(data[index*4:], value)
|
||||
}
|
||||
|
||||
copy(data[48:], []byte("x86!arm!"))
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
var _ = Describe("ARM64 image selection", func() {
|
||||
It("selects arm64e without parsing unused architectures", func() {
|
||||
input := universalImage()
|
||||
data, err := ARM64Slice(input)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).To(Equal("arm!"))
|
||||
Expect(&data[0]).To(BeIdenticalTo(&input[52]))
|
||||
})
|
||||
It("preserves thin image data", func() {
|
||||
input := []byte("thin image")
|
||||
data, err := ARM64Slice(input)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(&data[0]).To(BeIdenticalTo(&input[0]))
|
||||
})
|
||||
It("isolates mutable relocation data from the source bundle", func() {
|
||||
for _, input := range [][]byte{universalImage(), []byte("thin image")} {
|
||||
original := bytes.Clone(input)
|
||||
data, err := arm64Slice(input)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
data[0] ^= 0xff
|
||||
Expect(input).To(Equal(original))
|
||||
}
|
||||
})
|
||||
DescribeTable("rejects malformed universal images", func(mutate func([]byte) []byte, message string) {
|
||||
_, err := ARM64Slice(mutate(universalImage()))
|
||||
Expect(err).To(MatchError(ContainSubstring(message)))
|
||||
},
|
||||
Entry("truncated header", func(b []byte) []byte { return b[:4] }, "header"),
|
||||
Entry("truncated architecture table", func(b []byte) []byte { return b[:47] }, "architecture count"),
|
||||
Entry("no architectures", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[4:], 0)
|
||||
|
||||
return b
|
||||
}, "architecture count"),
|
||||
Entry("excessive count", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[4:], ^uint32(0))
|
||||
|
||||
return b
|
||||
}, "architecture count"),
|
||||
Entry("no arm64e image", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[32:], 0)
|
||||
|
||||
return b
|
||||
}, "no arm64e slice"),
|
||||
Entry("slice past the end", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[40:], 5)
|
||||
|
||||
return b
|
||||
}, "exceeds input size"),
|
||||
Entry("empty slice", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[40:], 0)
|
||||
|
||||
return b
|
||||
}, "exceeds input size"),
|
||||
Entry("overlapping header", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[36:], 8)
|
||||
|
||||
return b
|
||||
}, "overlaps"),
|
||||
Entry("large offset", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[36:], ^uint32(0))
|
||||
|
||||
return b
|
||||
}, "exceeds input size"),
|
||||
)
|
||||
})
|
||||
Loaded 100 of 372 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user