Compare commits

...
74 Commits
Author SHA1 Message Date
dependabot[bot]andMajd Alfhaily 779a2e66cb Bump golang.org/x/net from 0.51.0 to 0.55.0 (#508)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.51.0 to 0.55.0.
- [Commits](https://github.com/golang/net/compare/v0.51.0...v0.55.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-version: 0.55.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Majd Alfhaily <majd@alfhaily.me>
2026-07-05 12:46:54 +02:00
Vadim-B52 fd630343bc fix(auth): append trailing slash to native/fast authenticate endpoint (#507)
Apple's account bag now returns the authentication endpoint as
https://auth.itunes.apple.com/auth/v1/native/fast. That endpoint only
responds correctly when the path has a trailing slash; posting to it
without the slash makes Apple's edge return a 301/204 with an empty or
HTML body, so 'ipatool auth login' fails to parse the response and
silently dies (observed as the 'plist: unexpected hex digit' error or a
-5000 with no usable message).

Also improve http client diagnostics: when an XML response body is not a
property list, return 'unexpected response from Apple (HTTP <code>):
<snippet>' instead of the opaque plist parse error.
2026-07-05 12:41:37 +02:00
Rudra Sarkar dcddce4650 Fix 429 rate limit handling and context key type mismatch in login #480 (#481)
fix: handle 429 rate limit and context key type mismatch in login issue #480
2026-05-26 06:21:29 +02:00
Lakr a3fa2f09b3 feat: add tvOS app search and download support (#478) 2026-05-25 13:19:30 +02:00
Majd Alfhaily 85ae82d9c4 chore(repo): delete .github/FUNDING.yml (#475) 2026-05-05 21:23:37 +00:00
Majd Alfhaily 1bee8bc568 chore(repo): remove Patreon funding option (#474) 2026-05-02 16:21:27 +02:00
Majd Alfhaily abaeccefec feat: perform partial zip reads for extracting version and release date (#472) 2026-05-02 12:11:12 +02:00
Majd Alfhailyandliqiang 8c4e037aa3 fix: close ZIP entry readers during replication (#469)
Co-authored-by: liqiang <1573335865@qq.com>
2026-04-16 18:42:55 +00:00
4142ab48ad feat: use auth endpoint from Bag on retries (#468)
* Fix purchase retry to resolve auth endpoint via Bag() before re-login

The retry logic in purchase, download, get-version-metadata, and
list-versions called Login() without an Endpoint when re-authenticating
after a password token expiry. This caused silent failures because the
auth endpoint was empty.

- Add Bag() call before Login() in all retry blocks to resolve the auth
  endpoint dynamically
- Fall back to hardcoded auth endpoint when bag.xml omits
  authenticateAccount
- Detect "Your password has changed." customer message as a token expiry
  trigger alongside failure type 2034
- Increase download retry attempts to 3 to handle license-required then
  token-expired chain

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Address PR review: make auth path constant consistent, add password-changed test

- Rename PrivateAppStoreAPIPathAuthenticate to store only the path
  (consistent with other *APIPath* constants), constructing the full
  URL in the Bag() fallback
- Add test for CustomerMessagePasswordChanged triggering
  ErrPasswordTokenExpired in purchaseWithParams

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix purchase "already purchased" detection for Apple API changes

Apple now returns HTTP 200 with FailureType "5002" for already-purchased
apps instead of HTTP 500. Also treat FailureType "1008" (device
verification failed) as a stale token that triggers re-authentication.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix download retry to handle new Apple failure types (5002, 1008)

Map FailureType "5002" (license already exists) and "1008" (device
verification failed) to ErrPasswordTokenExpired in the download flow,
triggering re-auth retry consistent with the purchase fix in 438e8e8.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix zip corruption on re-download when .ipa already exists

applyPatches opened the destination file with O_CREATE|O_WRONLY but no
O_TRUNC. On re-download, the existing .ipa (which includes sinf data
from ReplicateSinf) is larger than what applyPatches writes (zip entries
+ metadata, no sinf yet). The leftover bytes at the end corrupt the ZIP
end-of-central-directory record, causing ReplicateSinf's zip.OpenReader
to fail with "failed to open zip reader".

Fix: add O_TRUNC to truncate the file before writing, and add a missing
defer dstFile.Close() to prevent file descriptor leaks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Treat "license already exists" as success in purchase and download

When the user already owns an app, purchase should report success
(with alreadyOwned=true) instead of failing with an error. Applied
to both the standalone purchase command and the --purchase flag in
the download command.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove Bag() fallback in retry paths, use DefaultAuthEndpoint directly

The bag response from init.itunes.apple.com/bag.xml does not contain
an authenticateAccount key, so the fallback was firing 100% of the time.
Replace the Bag()+Login() pattern in retry paths with Login() using a
DefaultAuthEndpoint constant directly, avoiding an unnecessary network
round-trip. The cmd/auth.go login flow still uses Bag() as before.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Use bag auth endpoint for retry login

---------

Co-authored-by: Barnabas Birmacher <birmacher@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 18:23:09 +00:00
Majd AlfhailyandBasil 1858ad7a72 chore(deps): update keyring module to maintained fork (#466)
Co-authored-by: Basil <basil@basil.cafe>
2026-04-14 20:39:55 +02:00
gitevedev 2140a26bdf Treating 'iTunes Store Sign-in required' the same way as expired pass (#432) 2026-04-10 18:53:16 +02:00
Majd Alfhaily e914156036 Add repository AGENTS.md guidance 2026-02-16 23:30:01 +01:00
Majd Alfhaily 19ffd1bf6b Use custom pod when applicable in purchase API 2026-02-16 20:12:00 +01:00
Majd Alfhaily 7ffd4bf050 Use custom pod when applicable in download, get-version-metadata and list-versions APIs 2026-02-16 20:12:00 +01:00
Majd Alfhaily 496595a039 Update auth command to retrieve bag and pass custom endpoint to auth API 2026-02-16 20:12:00 +01:00
Majd Alfhaily 7765fd5445 Update auth to use custom endpoint and store pod 2026-02-16 20:12:00 +01:00
Majd Alfhaily 6f63cd4776 Implement AppStore bag retrieval 2026-02-16 20:12:00 +01:00
Majd Alfhaily 65242569b3 Fix decoding Apple Plist envolope 2026-02-16 20:12:00 +01:00
dependabot[bot] 14883b4631 Bump github.com/dvsekhvalnov/jose2go from 1.6.0 to 1.7.0 (#416)
Bumps [github.com/dvsekhvalnov/jose2go](https://github.com/dvsekhvalnov/jose2go) from 1.6.0 to 1.7.0.
- [Commits](https://github.com/dvsekhvalnov/jose2go/compare/v1.6.0...v1.7.0)

---
updated-dependencies:
- dependency-name: github.com/dvsekhvalnov/jose2go
  dependency-version: 1.7.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-23 09:45:46 +01:00
Jens Christian Hillerup 91ae69cc58 Grant binaries exec permissions before packaging with tarball (#389) 2025-09-06 15:14:32 +02:00
GSG 80dbbef6c8 Resume incompleted downloads (#322) 2025-07-13 11:43:24 +02:00
sevenpastzeero e3e604925f Add Iraq storefront code (#383) 2025-07-08 20:38:42 +00:00
Majd Alfhaily cffa279e31 Fix README formatting 2025-06-09 20:44:16 +02:00
Majd Alfhaily 034a0978ab Remove GitHub sponsors from FUNDING.yml 2025-06-09 20:40:45 +02:00
Majd Alfhaily 9657750fc1 Create FUNDING.yml 2025-06-09 20:39:51 +02:00
Majd Alfhaily 9969c18cef Strip 2FA code from whitespaces 2025-06-09 17:23:08 +02:00
Majd Alfhaily f09439ecde Handle disabled account errors on auth 2025-06-09 17:23:08 +02:00
Majd Alfhaily 55ef41fc20 Update README.md 2025-06-09 17:18:53 +02:00
Majd Alfhaily b4bd8d6580 Rename field to external-version-id 2025-06-09 17:18:53 +02:00
Majd Alfhaily 79250ae2a3 Implement GetVersionMetadata command 2025-06-09 17:18:53 +02:00
Majd Alfhaily a3212e0fd2 Use display version in filename 2025-06-09 12:13:32 +02:00
Majd Alfhaily 805678138e Fix running golangci-lint on GitHub Actions 2025-06-09 12:13:32 +02:00
Majd Alfhaily 3a537e7571 Update GitHub Actions to use Go v1.23.0 2025-06-09 12:13:32 +02:00
Majd Alfhaily e686248270 Update README.md 2025-06-09 12:13:32 +02:00
Majd Alfhaily ac081fa19d Use internal version ID in filename of app 2025-06-09 12:13:32 +02:00
Majd Alfhaily 7136f81fd1 Refactor VersionHistory subcommand to ListVersions 2025-06-09 12:13:32 +02:00
SoCuul 34866f5833 Update macOS package manager install instructions (#350) 2025-06-08 13:59:35 +00:00
Chris Lui 46f3369de0 Fix typo on "failed to reoslve the country code" (#367) 2025-06-08 13:48:53 +00:00
koraytutuncu 0bb134e9d7 Add version history and old app version download support (#370) 2025-06-08 15:44:15 +02:00
dependabot[bot] bbf3717456 Bump golang.org/x/net from 0.36.0 to 0.38.0 (#364)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.36.0 to 0.38.0.
- [Commits](https://github.com/golang/net/compare/v0.36.0...v0.38.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-version: 0.38.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-17 23:50:00 +02:00
dependabot[bot] e1eda9f776 Bump golang.org/x/net from 0.33.0 to 0.36.0 (#355)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.33.0 to 0.36.0.
- [Commits](https://github.com/golang/net/compare/v0.33.0...v0.36.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-11 21:33:30 +02:00
Majd Alfhaily c406c36819 Replace Changelog with Releases link 2025-03-01 12:15:22 +01:00
Max e5291ba16b Log if app purchase was required and executed (#339) 2025-02-10 23:33:02 +01:00
AhmedBafkir 37af8f8468 Fix purchase issue (#338)
Fix purchase issue by updating endpoint
2025-02-10 23:25:58 +01:00
MaxandMajd Alfhaily 21cbd596bc Fix initial authentication attempt with 2FA (#331)
I though that the first attempt would not contain the 2fa code,
but I was wrong. This fixes the authentication when using 2fa enabled
accounts.

closes majd/ipatool#326

Co-authored-by: Majd Alfhaily <majd@alfhaily.me>
2025-01-20 00:13:19 +01:00
dependabot[bot]andMajd Alfhaily f3c9076ff0 Bump golang.org/x/net from 0.23.0 to 0.33.0 (#334)
* Bump golang.org/x/net from 0.23.0 to 0.33.0

Bumps [golang.org/x/net](https://github.com/golang/net) from 0.23.0 to 0.33.0.
- [Commits](https://github.com/golang/net/compare/v0.23.0...v0.33.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

* Fix linting errors

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Majd Alfhaily <majd@alfhaily.me>
2025-01-20 00:00:00 +01:00
Majd Alfhaily d147788501 Bump deprecated actions versions 2025-01-19 23:39:03 +01:00
Max 8a23d6fadd Fix authentication (#316)
login: increment 'attempt' while following redirects

Apple has introduced some dynamic GET parameters into their
redirects, forcing us to use the main domain ( no `p71-`
and such prefixes ) to obtain those parameters.

However, when following such redirects, we shall also increment
the `attempt` parameter (something that was hard-coded before).
2024-12-07 23:56:04 +01:00
guangwu 63ee6fc6a4 Fix closing response body (#271) 2024-05-01 01:21:33 +02:00
dependabot[bot] 5b547457f1 Bump golang.org/x/net from 0.20.0 to 0.23.0 (#272)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.20.0 to 0.23.0.
- [Commits](https://github.com/golang/net/compare/v0.20.0...v0.23.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-20 00:53:49 +02:00
Max Foxie 169af4b2ea Add ability to download .ipa by the app ID (#263)
* Add ability to download .ipa by the app ID
* Update `download` command usage in README
* Fix the linter warnings
2024-04-07 16:07:45 +02:00
dleovl f68a119963 Fix auth flag parenthesis (#267) 2024-04-06 18:59:58 +02:00
mike 58e9a18778 Close temporary file (#249) 2024-01-20 10:22:01 +01:00
Majd Alfhaily c8624b26d5 Update Go dependencies (#257)
* Update Go dependencies
* Replace github.com/golang/mock/gomock with go.uber.org/mock/gomock
2024-01-20 00:30:26 +01:00
Majd Alfhaily 3199afc494 Reduce Issues Cleanup workflow frequency to 6 hours 2023-12-21 00:18:16 +01:00
guangwu 6597f5ac77 fix: typo (#234) 2023-10-15 23:20:03 +02:00
双草酸酯 6ccb4a7f0b Hide progress bar in non-interactive mode (#229) 2023-09-23 14:29:49 +02:00
Majd Alfhaily 64c5cc9843 Close zip writer before removing files (#215) 2023-07-16 08:06:36 +00:00
Majd Alfhaily 19e7261713 Update changelog for v2.1.3 release (#204) 2023-06-11 08:43:36 +02:00
Majd Alfhaily b031cd20d1 Make --keychain-passphrase flag persistent (#203) 2023-06-07 22:31:43 +00:00
Majd Alfhaily 9db93c83c0 Close reader file handle (#202) 2023-06-07 22:22:42 +00:00
Majd Alfhaily 90253c336f Update changelog for v2.1.2 release (#198) 2023-06-04 18:03:56 +02:00
Majd Alfhaily e1141bd6d2 Default to FileBackend keyring when other options are not available (#197) 2023-06-03 22:07:32 +00:00
Majd Alfhaily 6a7adabbfa Fix reading config directory (#193) 2023-05-29 17:55:20 +00:00
Majd Alfhaily cfc4a075ae Update changelog for v2.1.0 release (#191) 2023-05-29 13:36:46 +00:00
Majd Alfhaily 74e7588c6d Add v2 suffix to module path (#190) 2023-05-29 13:27:28 +00:00
Majd Alfhaily 67e557e9a7 Add golangci-lint linter (#188) 2023-05-27 21:21:13 +00:00
Majd Alfhaily bf33e0d1c4 Improve tests for http package (#187) 2023-05-27 20:03:29 +00:00
Majd Alfhaily 95c3aa6629 Refactor API interfaces (#185)
- Move logging to command level.
- Simplify and unify interfaces for `appstore` package.
- Move sinf replication from "Download" API to "ReplicateSinf" API.
- Handle retries and command specific logic in the command level.
- Rename "Info" API to "AccountInfo".
2023-05-27 18:48:22 +02:00
Majd Alfhaily cf926d7911 Set build version using linker flags (#183) 2023-05-20 15:54:56 +00:00
Majd Alfhaily 9a361cf7a0 Remove .github/FUNDING.yml (#179) 2023-05-14 08:56:47 +00:00
Majd Alfhaily 574d5b5148 Add storefront code for Georgia (GE) (#177) 2023-05-05 19:49:05 +00:00
Majd Alfhaily 5abc5d1777 Expose Lookup API (#172) 2023-04-09 18:34:46 +00:00
Majd Alfhaily 8762eaf192 Refactor API to return output to caller (#171)
* Refactor auth.info implementation to return output

* Refactor auth.revoke implementation to return output

* Refactor auth.login implementation to return output

* Refactor search implementation to return output

* Refactor purchase implementation to return output

* Refactor download implementation to return output
2023-04-09 18:24:10 +00:00
109 changed files with 5634 additions and 3733 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
github: majd
+20 -19
View File
@@ -12,35 +12,36 @@ jobs:
strategy:
fail-fast: false
matrix:
arch: [ arm64, amd64 ]
arch: [arm64, amd64]
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v3
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.19.3'
go-version: "1.25.0"
cache: true
- run: ./tools/version.sh
- run: go build -o ipatool-$GOOS-$GOARCH.exe
env:
GOOS: windows
GOARCH: ${{ matrix.arch }}
build_linux:
name: Build for Linux
runs-on: macos-latest
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
arch: [ arm64, amd64 ]
include:
- arch: arm64
runner: ubuntu-24.04-arm
- arch: amd64
runner: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v3
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.19.3'
go-version: "1.25.0"
cache: true
- run: ./tools/version.sh
- run: go build -o ipatool-$GOOS-$GOARCH
- run: go build -o ipatool-linux-$GOARCH
env:
GOOS: linux
GOARCH: ${{ matrix.arch }}
build_macos:
name: Build for macOS
@@ -48,17 +49,17 @@ jobs:
strategy:
fail-fast: false
matrix:
arch: [ arm64, amd64 ]
arch: [arm64, amd64]
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v3
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.19.3'
go-version: "1.25.0"
cache: true
- run: ./tools/version.sh
- 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
CGO_LDFLAGS: -mmacosx-version-min=10.15
+6 -9
View File
@@ -9,20 +9,17 @@ jobs:
build:
name: Build
runs-on: macos-latest
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v3
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.19.3'
go-version: "1.25.0"
cache: true
- run: ./tools/version.sh
- run: go build -o ipatool
env:
CGO_CFLAGS: -mmacosx-version-min=10.15
CGO_LDFLAGS: -mmacosx-version-min=10.15
- uses: actions/upload-artifact@v2
- uses: actions/upload-artifact@v4
with:
name: ipatool
path: ipatool
@@ -36,9 +33,9 @@ jobs:
matrix:
command: [auth, download, purchase, search]
steps:
- uses: actions/download-artifact@v2
- uses: actions/download-artifact@v4
with:
name: ipatool
path: build
- run: chmod +x ./build/ipatool
- run: ./build/ipatool ${{ matrix.command }} --help
- run: ./build/ipatool ${{ matrix.command }} --help
-18
View File
@@ -1,18 +0,0 @@
name: Issues Cleanup
on:
issue_comment:
types: [created]
schedule:
- cron: "0 * * * *" # Every hour, every day
jobs:
scan-issues:
runs-on: ubuntu-latest
steps:
- uses: lee-dohm/no-response@v0.5.0
with:
token: ${{ github.token }}
daysUntilClose: 7
closeComment: This issue has been automatically closed because there has been no response from the original author.
responseRequiredLabel: auto-close
+21
View File
@@ -0,0 +1,21 @@
name: Lint
on:
pull_request:
branches:
- main
jobs:
lint:
name: Lint
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
cache: true
- run: go generate github.com/majd/ipatool/...
- uses: golangci/golangci-lint-action@v8
with:
version: v2.9
+62 -50
View File
@@ -18,84 +18,96 @@ jobs:
name: Run tests
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v3
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.19.3'
go-version: "1.25.0"
cache: true
- run: ./tools/version.sh
- run: go generate github.com/majd/ipatool/...
- run: go test -v github.com/majd/ipatool/...
build:
name: Build
runs-on: macos-latest
needs: [get_version, test]
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v3
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.19.3'
go-version: "1.25.0"
cache: true
- run: ./tools/version.sh
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-arm64.exe
env:
GOOS: windows
GOARCH: arm64
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
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
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-linux-arm64
env:
GOOS: linux
GOARCH: arm64
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-linux-amd64
env:
GOOS: linux
GOARCH: amd64
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
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 -o ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
- 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@v2
- 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@v2
- 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@v2
with:
name: ipatool-${{ needs.get_version.outputs.version }}-linux-arm64
path: ipatool-${{ needs.get_version.outputs.version }}-linux-arm64
if-no-files-found: error
- uses: actions/upload-artifact@v2
with:
name: ipatool-${{ needs.get_version.outputs.version }}-linux-amd64
path: ipatool-${{ needs.get_version.outputs.version }}-linux-amd64
if-no-files-found: error
- uses: actions/upload-artifact@v2
- 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@v2
- uses: actions/upload-artifact@v4
with:
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
path: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
if-no-files-found: error
build_linux:
name: Build for Linux
runs-on: ${{ matrix.runner }}
needs: [get_version, test]
strategy:
fail-fast: false
matrix:
include:
- arch: arm64
runner: ubuntu-24.04-arm
- arch: amd64
runner: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.25.0"
cache: true
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-linux-$GOARCH
env:
GOARCH: ${{ matrix.arch }}
VERSION: ${{ needs.get_version.outputs.version }}
- uses: actions/upload-artifact@v4
with:
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
path: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
if-no-files-found: error
release_windows:
name: Release for Windows
runs-on: ubuntu-latest
@@ -103,10 +115,10 @@ jobs:
strategy:
fail-fast: false
matrix:
arch: [ arm64, amd64 ]
arch: [arm64, amd64]
steps:
- uses: actions/checkout@v2
- uses: actions/download-artifact@v2
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.exe
path: bin
@@ -126,18 +138,18 @@ jobs:
release_linux:
name: Release for Linux
runs-on: ubuntu-latest
needs: [get_version, build, release_windows]
needs: [get_version, build_linux, release_windows]
strategy:
fail-fast: false
matrix:
arch: [ arm64, amd64 ]
arch: [arm64, amd64]
steps:
- uses: actions/checkout@v2
- uses: actions/download-artifact@v2
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
path: bin
- run: tar -czvf $FILE.tar.gz bin/$FILE
- 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
@@ -153,23 +165,23 @@ jobs:
release_macos:
name: Release for macOS
runs-on: ubuntu-latest
needs: [get_version, build, release_windows, release_linux]
needs: [get_version, build, build_linux, release_windows, release_linux]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
with:
path: ./ipatool
- uses: actions/download-artifact@v2
- uses: actions/download-artifact@v4
with:
name: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
path: bin
- run: tar -czvf $BIN.tar.gz bin/$BIN && rm -rf 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@v2
- uses: actions/download-artifact@v4
with:
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
path: bin
- run: tar -czvf $FILE.tar.gz bin/$FILE && rm -rf 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
@@ -187,7 +199,7 @@ jobs:
tag: ${{ github.ref }}
overwrite: false
file_glob: true
- uses: actions/checkout@v2
- uses: actions/checkout@v4
with:
repository: ${{ secrets.HOMEBREW_REPO }}
ref: main
@@ -209,4 +221,4 @@ jobs:
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 }}
SHA256_AMD64: ${{ steps.sha256.outputs.sha256_amd64 }}
+5 -5
View File
@@ -8,12 +8,12 @@ on:
jobs:
run_tests:
name: Run tests
runs-on: macos-latest
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v3
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.19.3'
go-version: "1.25.0"
cache: true
- run: ./tools/version.sh
- run: go generate github.com/majd/ipatool/...
- run: go test -v github.com/majd/ipatool/...
+2 -1
View File
@@ -3,4 +3,5 @@
.LSOverride
.vscode/
.idea/
cmd/version.go
**/*_mock.go
exp/
+38
View File
@@ -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$
+34
View File
@@ -0,0 +1,34 @@
# AGENTS.md
This file provides guidance for coding agents working in this repository.
## Repository overview
- Project: `ipatool`
- Language: Go
- Entry point: `main.go`
- CLI command implementations: `cmd/`
## Development workflow
1. Keep changes focused and minimal.
2. Prefer idiomatic Go and keep command behavior consistent with existing commands in `cmd/`.
3. Run formatting and tests before finalizing changes.
## Local checks
Use these commands from the repository root:
```bash
go generate ./...
go test ./...
go build ./...
```
## Coding conventions
- Follow standard Go formatting (`gofmt`).
- Avoid introducing new dependencies unless necessary.
- Keep user-facing text consistent with existing CLI help/output tone.
- Preserve backward compatibility for CLI flags and output formats unless explicitly asked to change them.
## Commit/PR guidance
- Write clear, scoped commit messages.
- Summarize what changed and why in PR descriptions.
- Include test/build results in your handoff.
-107
View File
@@ -1,107 +0,0 @@
## Changelog
### Version [2.0.3](https://github.com/majd/ipatool/releases/tag/v2.0.3)
- Added support for downloading Apple Arcade games.
- Fixed windows builds not having exe extension.
### Version [2.0.2](https://github.com/majd/ipatool/releases/tag/v2.0.2)
- Fixed Sinf patches when the app contains an Apple Watch app.
- Added storefront code for Albania.
- Fixed default output path to be current working directory.
### Version [2.0.1](https://github.com/majd/ipatool/releases/tag/v2.0.1)
- Linux & Windows releases now include the sha256 hash.
- Added storefront code for Mongolia.
### Version [2.0.0](https://github.com/majd/ipatool/releases/tag/v2.0.0)
- Added support for Windows.
- Added support for Linux.
- Added support for generating autocompletion script using the `completion` command.
- Implemented new `auth info` command.
- Implemented `--verbose` flag that replaces the `--debug-level` flag to enable verbose logging.
- Implemented `--format` which allows specifying logs output format to either text or json (default: text).
- Implemented `--non-interactive` flag to disable running the tool in an interactive session.
- The relevant command (i.e. purchase) will now automatically determine the country and the device family from the authenticated account. The following flags have been deprecated.
- `--country`
- `--device-family`
- Improved structured logging.
- Improved error handling.
- Improved support for automated systems.
- Added unit tests to cover the majority of the private App Store API logic.
### Version [1.1.4](https://github.com/majd/ipatool/releases/tag/v1.1.4)
- Add support for patching old code signature revisions as a fallback mechanism.
### Version [1.1.3](https://github.com/majd/ipatool/releases/tag/v1.1.3)
- Fixed keychain access on iOS.
### Version [1.1.2](https://github.com/majd/ipatool/releases/tag/v1.1.2)
- Improved error message for expired token.
- Disabled print buffering and output errors to stderr.
- Added linter.
- Add support for running on iOS.
### Version [1.1.1](https://github.com/majd/ipatool/releases/tag/v1.1.1)
- Update swift-argument-parser dependency.
- Remove usage of Swift concurrency.
- Add backward-compatibility for macOS 10.11+.
### Version [1.1.0](https://github.com/majd/ipatool/releases/tag/v1.1.0)
- Added support for purchasing apps.
- Implemented auth command.
- Implemented purchase command.
- Implemented --purchase flag in download command.
- Added price checks for purchase flow.
### Version [1.0.9](https://github.com/majd/ipatool/releases/tag/v1.0.9)
- Fixed building for older macOS versions.
- Fixed 2FA code not being requested.
### Version [1.0.8](https://github.com/majd/ipatool/releases/tag/v1.0.8)
- Added --output option to the download command for specifying the destination path for the downloaded app package.
### Version [1.0.7](https://github.com/majd/ipatool/releases/tag/v1.0.7)
- Fixed login requests to the store API when the 2FA code is required.
### Version [1.0.6](https://github.com/majd/ipatool/releases/tag/v1.0.6)
- Added support for supplying 2FA code in non-interactive sessions.
### Version [1.0.5](https://github.com/majd/ipatool/releases/tag/v1.0.5)
- Added support for specifying device family.
### Version [1.0.4](https://github.com/majd/ipatool/releases/tag/v1.0.4)
- Added support for specifying the iTunes Store region.
### Version [1.0.3](https://github.com/majd/ipatool/releases/tag/v1.0.3)
- Improved console logging.
### Version [1.0.2](https://github.com/majd/ipatool/releases/tag/v1.0.2)
- Improved error messages.
### Version [1.0.1](https://github.com/majd/ipatool/releases/tag/v1.0.1)
- Grammatical fixes.
### Version [1.0.0](https://github.com/majd/ipatool/releases/tag/v1.0.0)
- Initial release.
+62 -15
View File
@@ -5,7 +5,7 @@
`ipatool` is a command line tool that allows you to search for iOS apps on the [App Store](https://apps.apple.com) and download a copy of the app package, known as an _ipa_ file.
![Demo](./demo.gif)
![Demo](./resources/demo.gif)
- [Requirements](#requirements)
- [Installation](#installation)
@@ -14,10 +14,11 @@
- [Usage](#usage)
- [Compiling](#compiling)
- [License](#license)
- [Changelog](https://github.com/majd/ipatool/blob/main/CHANGELOG.md)
- [Releases](https://github.com/majd/ipatool/releases)
- [FAQ](https://github.com/majd/ipatool/wiki/FAQ)
## Requirements
- Supported operating system (Windows, Linux or macOS).
- Apple ID set up to use the App Store.
@@ -32,7 +33,6 @@ You can grab the latest version of `ipatool` from [GitHub releases](https://gith
You can install `ipatool` using [Homebrew](https://brew.sh).
```shell
$ brew tap majd/repo
$ brew install ipatool
```
@@ -65,14 +65,15 @@ Use "ipatool auth [command] --help" for more information about a command.
To search for apps on the App Store, use the `search` command.
```
Search for iOS apps available on the App Store
Search for iOS and tvOS apps available on the App Store
Usage:
ipatool search <term> [flags]
Flags:
-h, --help help for search
-l, --limit int maximum amount of search results to retrieve (default 5)
-h, --help help for search
-l, --limit int maximum amount of search results to retrieve (default 5)
--platform string Platform to search: iphone, ipad, or appletv
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
@@ -98,24 +99,69 @@ Global Flags:
--verbose enables verbose logs
```
To obtain a list of availble app versions to download, use the `list-versions` command.
```
List the available versions of an iOS app
Usage:
ipatool list-versions [flags]
Flags:
-i, --app-id int ID of the target iOS app (required)
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
-h, --help help for list-versions
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
--keychain-passphrase string passphrase for unlocking keychain
--non-interactive run in non-interactive session
--verbose enables verbose logs
```
To download a copy of the ipa file, use the `download` command.
```
Download (encrypted) iOS app packages from the App Store
Download (encrypted) iOS and tvOS app packages from the App Store
Usage:
ipatool download [flags]
Flags:
-b, --bundle-identifier string The bundle identifier of the target iOS app (required)
-h, --help help for download
-o, --output string The destination path of the downloaded app package
--purchase Obtain a license for the app if needed
-i, --app-id int ID of the target iOS app (required)
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
--external-version-id string External version identifier of the target iOS app (defaults to latest version when not specified)
-h, --help help for download
-o, --output string The destination path of the downloaded app package
--platform string Platform to download for: iphone, ipad, or appletv
--purchase Obtain a license for the app if needed
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
--non-interactive run in non-interactive session
--verbose enables verbose logs
--format format sets output format for command; can be 'text', 'json' (default text)
--keychain-passphrase string passphrase for unlocking keychain
--non-interactive run in non-interactive session
--verbose enables verbose logs
```
To resolve an external version identifier, returned by the `list-versions` command, use the `get-version-metadata` command.
```
Retrieves the metadata for a specific version of an app
Usage:
ipatool get-version-metadata [flags]
Flags:
-i, --app-id int ID of the target iOS app (required)
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
--external-version-id string External version identifier of the target iOS app (required)
-h, --help help for get-version-metadata
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
--keychain-passphrase string passphrase for unlocking keychain
--non-interactive run in non-interactive session
--verbose enables verbose logs
```
**Note:** the tool runs in interactive mode by default. Use the `--non-interactive` flag
@@ -129,9 +175,10 @@ The tool can be compiled using the Go toolchain.
$ go build -o ipatool
```
Unit tests can be executed with the following command.
Unit tests can be executed with the following commands.
```shell
$ go generate github.com/majd/ipatool/...
$ go test -v github.com/majd/ipatool/...
```
+115 -23
View File
@@ -1,12 +1,19 @@
package cmd
import (
"github.com/99designs/keyring"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
"bufio"
"errors"
"fmt"
"os"
"strings"
"time"
var keychainPassphrase string
"github.com/avast/retry-go"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/majd/ipatool/v2/pkg/util"
"github.com/spf13/cobra"
"golang.org/x/term"
)
func authCmd() *cobra.Command {
cmd := &cobra.Command{
@@ -14,10 +21,6 @@ func authCmd() *cobra.Command {
Short: "Authenticate with the App Store",
}
if keyringBackendType() == keyring.FileBackend {
cmd.PersistentFlags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
}
cmd.AddCommand(loginCmd())
cmd.AddCommand(infoCmd())
cmd.AddCommand(revokeCmd())
@@ -26,25 +29,104 @@ func authCmd() *cobra.Command {
}
func loginCmd() *cobra.Command {
var email string
var password string
var authCode string
promptForAuthCode := func() (string, error) {
authCode, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return "", fmt.Errorf("failed to read string: %w", err)
}
authCode = strings.Trim(authCode, "\n")
authCode = strings.Trim(authCode, "\r")
return authCode, nil
}
var email, password, authCode string
cmd := &cobra.Command{
Use: "login",
Short: "Login to the App Store",
RunE: func(cmd *cobra.Command, args []string) error {
appstore, err := newAppStore(cmd, keychainPassphrase)
if err != nil {
return errors.Wrap(err, "failed to create appstore client")
interactive := cmd.Context().Value(interactiveKey).(bool)
if password == "" && !interactive {
return errors.New("password is required when not running in interactive mode; use the \"--password\" flag")
}
return appstore.Login(email, password, authCode)
if password == "" && interactive {
dependencies.Logger.Log().Msg("enter password:")
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return fmt.Errorf("failed to read password: %w", err)
}
password = string(bytes)
}
var lastErr error
// nolint:wrapcheck
return retry.Do(func() error {
if errors.Is(lastErr, appstore.ErrAuthCodeRequired) && interactive {
dependencies.Logger.Log().Msg("enter 2FA code:")
var err error
authCode, err = promptForAuthCode()
if err != nil {
return fmt.Errorf("failed to read auth code: %w", err)
}
}
dependencies.Logger.Verbose().
Str("password", password).
Str("email", email).
Str("authCode", util.IfEmpty(authCode, "<nil>")).
Msg("logging in")
bag, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
output, err := dependencies.AppStore.Login(appstore.LoginInput{
Email: email,
Password: password,
AuthCode: authCode,
Endpoint: bag.AuthEndpoint,
})
if err != nil {
if errors.Is(err, appstore.ErrAuthCodeRequired) && !interactive {
dependencies.Logger.Log().Msg("2FA code is required; run the command again and supply a code using the `--auth-code` flag")
return nil
}
return err
}
dependencies.Logger.Log().
Str("name", output.Account.Name).
Str("email", output.Account.Email).
Bool("success", true).
Send()
return nil
},
retry.LastErrorOnly(true),
retry.DelayType(retry.FixedDelay),
retry.Delay(time.Millisecond),
retry.Attempts(2),
retry.RetryIf(func(err error) bool {
lastErr = err
return errors.Is(err, appstore.ErrAuthCodeRequired)
}),
)
},
}
cmd.Flags().StringVarP(&email, "email", "e", "", "email address for the Apple ID (required)")
cmd.Flags().StringVarP(&password, "password", "p", "", "password for the Apple ID (required")
cmd.Flags().StringVarP(&password, "password", "p", "", "password for the Apple ID (required)")
cmd.Flags().StringVar(&authCode, "auth-code", "", "2FA code for the Apple ID")
_ = cmd.MarkFlagRequired("email")
@@ -52,32 +134,42 @@ func loginCmd() *cobra.Command {
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 {
appstore, err := newAppStore(cmd, keychainPassphrase)
output, err := dependencies.AppStore.AccountInfo()
if err != nil {
return errors.Wrap(err, "failed to create appstore client")
return err
}
return appstore.Info()
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 {
appstore, err := newAppStore(cmd, keychainPassphrase)
err := dependencies.AppStore.Revoke()
if err != nil {
return errors.Wrap(err, "failed to create appstore client")
return err
}
return appstore.Revoke()
dependencies.Logger.Log().Bool("success", true).Send()
return nil
},
}
}
+104 -138
View File
@@ -1,124 +1,40 @@
package cmd
import (
"github.com/99designs/keyring"
"github.com/juju/persistent-cookiejar"
"github.com/majd/ipatool/pkg/appstore"
"github.com/majd/ipatool/pkg/keychain"
"github.com/majd/ipatool/pkg/log"
"github.com/majd/ipatool/pkg/util"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
"golang.org/x/exp/slices"
"golang.org/x/term"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/byteness/keyring"
cookiejar "github.com/juju/persistent-cookiejar"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/keychain"
"github.com/majd/ipatool/v2/pkg/log"
"github.com/majd/ipatool/v2/pkg/util"
"github.com/majd/ipatool/v2/pkg/util/machine"
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
"golang.org/x/term"
)
func newCookieJar() (*cookiejar.Jar, error) {
machine := util.NewMachine(util.MachineArgs{
OperatingSystem: util.NewOperatingSystem(),
})
jar, err := cookiejar.New(&cookiejar.Options{
Filename: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName, CookieJarFileName),
})
if err != nil {
return nil, errors.Wrap(err, "failed to create cookie jar")
}
var dependencies = Dependencies{}
var keychainPassphrase string
return jar, nil
}
func keyringBackendType() keyring.BackendType {
allowedBackends := []keyring.BackendType{
keyring.KeychainBackend,
keyring.SecretServiceBackend,
}
for _, backend := range allowedBackends {
if slices.Contains(keyring.AvailableBackends(), backend) {
return backend
}
}
return keyring.FileBackend
}
func newKeyring(logger log.Logger, passphrase string, interactive bool) (keyring.Keyring, error) {
machine := util.NewMachine(util.MachineArgs{
OperatingSystem: util.NewOperatingSystem(),
})
ring, err := keyring.Open(keyring.Config{
AllowedBackends: []keyring.BackendType{
keyringBackendType(),
},
ServiceName: KeychainServiceName,
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
FilePasswordFunc: func(s string) (string, error) {
if passphrase == "" && !interactive {
return "", errors.New("keychain passphrase is required when not running in interactive mode; use the \"--keychain-passphrase\" flag")
}
if passphrase != "" {
return passphrase, nil
}
path := strings.Split(s, " unlock ")[1]
logger.Log().Msgf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path)
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return "", errors.Wrap(err, "failed to read password")
}
password := string(bytes)
password = strings.Trim(password, "\n")
password = strings.Trim(password, "\r")
return password, nil
},
})
if err != nil {
return nil, errors.Wrap(err, "failed to open keyring")
}
return ring, nil
}
func configureConfigDirectory() error {
os := util.NewOperatingSystem()
machine := util.NewMachine(util.MachineArgs{
OperatingSystem: os,
})
configDirectoryPath := filepath.Join(machine.HomeDirectory(), ConfigDirectoryName)
_, err := os.Stat(configDirectoryPath)
if err != nil && os.IsNotExist(err) {
err = os.MkdirAll(configDirectoryPath, 0700)
if err != nil {
return errors.Wrap(err, "failed to create config directory")
}
} else if err != nil {
return errors.Wrap(err, "could not read metadata")
}
return nil
}
func parseOutputFormat(value string) (OutputFormat, error) {
switch value {
case "json":
return OutputFormatJSON, nil
case "text":
return OutputFormatText, nil
default:
return OutputFormatJSON, errors.Errorf("invalid output format: %s", value)
}
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
@@ -129,41 +45,91 @@ func newLogger(format OutputFormat, verbose bool) log.Logger {
writer = log.NewWriter()
}
return log.NewLogger(log.LoggerArgs{
return log.NewLogger(log.Args{
Verbose: verbose,
Writer: writer,
},
)
}
// newCookieJar returns a new cookie jar instance.
func newCookieJar(machine machine.Machine) http.CookieJar {
return util.Must(cookiejar.New(&cookiejar.Options{
Filename: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName, CookieJarFileName),
}))
}
// newKeychain returns a new keychain instance.
func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) keychain.Keychain {
ring := util.Must(keyring.Open(keyring.Config{
AllowedBackends: []keyring.BackendType{
keyring.KeychainBackend,
keyring.SecretServiceBackend,
keyring.FileBackend,
},
ServiceName: KeychainServiceName,
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
FilePasswordFunc: func(s string) (string, error) {
if keychainPassphrase == "" && !interactive {
return "", errors.New("keychain passphrase is required when not running in interactive mode; use the \"--keychain-passphrase\" flag")
}
if keychainPassphrase != "" {
return keychainPassphrase, nil
}
path := strings.Split(s, " unlock ")[1]
logger.Log().Msgf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path)
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return "", fmt.Errorf("failed to read password: %w", err)
}
password := string(bytes)
password = strings.Trim(password, "\n")
password = strings.Trim(password, "\r")
return password, nil
},
}))
return keychain.New(keychain.Args{Keyring: ring})
}
// initWithCommand initializes the dependencies of the command.
func initWithCommand(cmd *cobra.Command) {
verbose := cmd.Flag("verbose").Value.String() == "true"
interactive, _ := cmd.Context().Value(interactiveKey).(bool)
format := util.Must(OutputFormatFromString(cmd.Flag("format").Value.String()))
dependencies.Logger = newLogger(format, verbose)
dependencies.OS = operatingsystem.New()
dependencies.Machine = machine.New(machine.Args{OS: dependencies.OS})
dependencies.CookieJar = newCookieJar(dependencies.Machine)
dependencies.Keychain = newKeychain(dependencies.Machine, dependencies.Logger, interactive)
dependencies.AppStore = appstore.NewAppStore(appstore.Args{
CookieJar: dependencies.CookieJar,
OperatingSystem: dependencies.OS,
Keychain: dependencies.Keychain,
Machine: dependencies.Machine,
})
util.Must("", createConfigDirectory(dependencies.OS, dependencies.Machine))
}
func newAppStore(
cmd *cobra.Command,
keychainPassphrase string,
) (appstore.AppStore, error) {
logger := cmd.Context().Value("logger").(log.Logger)
interactive := cmd.Context().Value("interactive").(bool)
// createConfigDirectory creates the configuration directory for the CLI tool, if needed.
func createConfigDirectory(os operatingsystem.OperatingSystem, machine machine.Machine) error {
configDirectoryPath := filepath.Join(machine.HomeDirectory(), ConfigDirectoryName)
_, err := os.Stat(configDirectoryPath)
cookieJar, err := newCookieJar()
if err != nil {
return nil, errors.Wrap(err, "failed to create cookie jar")
if err != nil && os.IsNotExist(err) {
err = os.MkdirAll(configDirectoryPath, 0700)
if err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
} else if err != nil {
return fmt.Errorf("could not read metadata: %w", err)
}
os := util.NewOperatingSystem()
keyring, err := newKeyring(logger, keychainPassphrase, interactive)
if err != nil {
return nil, errors.Wrap(err, "failed to create keyring")
}
return appstore.NewAppStore(appstore.AppStoreArgs{
Logger: logger,
CookieJar: cookieJar,
Keychain: keychain.NewKeychain(keychain.KeychainArgs{
Keyring: keyring,
}),
Interactive: interactive,
Machine: util.NewMachine(util.MachineArgs{
OperatingSystem: os,
}),
OperatingSystem: os,
}), nil
return nil
}
-9
View File
@@ -1,14 +1,5 @@
package cmd
import "github.com/thediveo/enumflag/v2"
type OutputFormat enumflag.Flag
const (
OutputFormatText OutputFormat = iota
OutputFormatJSON
)
const (
ConfigDirectoryName = ".ipatool"
CookieJarFileName = "cookies"
+146 -18
View File
@@ -1,39 +1,167 @@
package cmd
import (
"github.com/99designs/keyring"
"github.com/pkg/errors"
"errors"
"fmt"
"os"
"time"
"github.com/avast/retry-go"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/schollz/progressbar/v3"
"github.com/spf13/cobra"
)
// nolint:wrapcheck
func downloadCmd() *cobra.Command {
var keychainPassphrase string
var acquireLicense bool
var outputPath string
var bundleID string
var (
acquireLicense bool
outputPath string
appID int64
bundleID string
externalVersionID string
platformValue string
)
cmd := &cobra.Command{
Use: "download",
Short: "Download (encrypted) iOS app packages from the App Store",
Short: "Download (encrypted) iOS and tvOS app packages from the App Store",
RunE: func(cmd *cobra.Command, args []string) error {
appstore, err := newAppStore(cmd, keychainPassphrase)
if err != nil {
return errors.Wrap(err, "failed to create appstore client")
if appID == 0 && bundleID == "" {
return errors.New("either the app ID or the bundle identifier must be specified")
}
return appstore.Download(bundleID, outputPath, acquireLicense)
var lastErr error
var acc appstore.Account
purchased := false
return retry.Do(func() error {
infoResult, err := dependencies.AppStore.AccountInfo()
if err != nil {
return err
}
acc = infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
Email: acc.Email,
Password: acc.Password,
Endpoint: bagOutput.AuthEndpoint,
})
if err != nil {
return err
}
acc = loginResult.Account
}
app := appstore.App{ID: appID}
platform, err := appstore.ParsePlatform(platformValue)
if err != nil {
return err
}
if bundleID != "" {
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{
Account: acc,
BundleID: bundleID,
Platform: platform,
})
if err != nil {
return err
}
app = lookupResult.App
}
if errors.Is(lastErr, appstore.ErrLicenseRequired) {
err := dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: app})
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
return err
}
purchased = true
dependencies.Logger.Verbose().
Bool("success", true).
Msg("purchase")
}
interactive, _ := cmd.Context().Value(interactiveKey).(bool)
var progress *progressbar.ProgressBar
if interactive {
progress = progressbar.NewOptions64(1,
progressbar.OptionSetDescription("downloading"),
progressbar.OptionSetWriter(os.Stdout),
progressbar.OptionShowBytes(true),
progressbar.OptionSetWidth(20),
progressbar.OptionFullWidth(),
progressbar.OptionThrottle(65*time.Millisecond),
progressbar.OptionShowCount(),
progressbar.OptionClearOnFinish(),
progressbar.OptionSpinnerType(14),
progressbar.OptionSetRenderBlankState(true),
progressbar.OptionSetElapsedTime(false),
progressbar.OptionSetPredictTime(false),
)
}
out, err := dependencies.AppStore.Download(appstore.DownloadInput{
Account: acc,
App: app,
OutputPath: outputPath,
Progress: progress,
ExternalVersionID: externalVersionID,
Platform: platform,
})
if err != nil {
return err
}
err = dependencies.AppStore.ReplicateSinf(appstore.ReplicateSinfInput{Sinfs: out.Sinfs, PackagePath: out.DestinationPath})
if err != nil {
return err
}
dependencies.Logger.Log().
Str("output", out.DestinationPath).
Bool("purchased", purchased).
Bool("success", true).
Send()
return nil
},
retry.LastErrorOnly(true),
retry.DelayType(retry.FixedDelay),
retry.Delay(time.Millisecond),
retry.Attempts(3),
retry.RetryIf(func(err error) bool {
lastErr = err
if errors.Is(err, appstore.ErrPasswordTokenExpired) {
return true
}
if errors.Is(err, appstore.ErrLicenseRequired) && acquireLicense {
return true
}
return false
}),
)
},
}
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (required)")
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
cmd.Flags().StringVarP(&outputPath, "output", "o", "", "The destination path of the downloaded app package")
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target iOS app (defaults to latest version when not specified)")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone, ipad, or appletv")
cmd.Flags().BoolVar(&acquireLicense, "purchase", false, "Obtain a license for the app if needed")
if keyringBackendType() == keyring.FileBackend {
cmd.Flags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
}
_ = cmd.MarkFlagRequired("bundle-identifier")
return cmd
}
+106
View File
@@ -0,0 +1,106 @@
package cmd
import (
"errors"
"fmt"
"time"
"github.com/avast/retry-go"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/spf13/cobra"
)
// nolint:wrapcheck
func getVersionMetadataCmd() *cobra.Command {
var (
appID int64
bundleID string
externalVersionID string
)
cmd := &cobra.Command{
Use: "get-version-metadata",
Short: "Retrieves the metadata for a specific version of an app",
RunE: func(cmd *cobra.Command, args []string) error {
if appID == 0 && bundleID == "" {
return errors.New("either the app ID or the bundle identifier must be specified")
}
var lastErr error
var acc appstore.Account
return retry.Do(func() error {
infoResult, err := dependencies.AppStore.AccountInfo()
if err != nil {
return err
}
acc = infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
Email: acc.Email,
Password: acc.Password,
Endpoint: bagOutput.AuthEndpoint,
})
if err != nil {
return err
}
acc = loginResult.Account
}
app := appstore.App{ID: appID}
if bundleID != "" {
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
if err != nil {
return err
}
app = lookupResult.App
}
out, err := dependencies.AppStore.GetVersionMetadata(appstore.GetVersionMetadataInput{
Account: acc,
App: app,
VersionID: externalVersionID,
})
if err != nil {
return err
}
dependencies.Logger.Log().
Str("externalVersionID", externalVersionID).
Str("displayVersion", out.DisplayVersion).
Time("releaseDate", out.ReleaseDate).
Bool("success", true).
Send()
return nil
},
retry.LastErrorOnly(true),
retry.DelayType(retry.FixedDelay),
retry.Delay(time.Millisecond),
retry.Attempts(2),
retry.RetryIf(func(err error) bool {
lastErr = err
return errors.Is(err, appstore.ErrPasswordTokenExpired)
}),
)
},
}
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target iOS app (required)")
_ = cmd.MarkFlagRequired("external-version-id")
return cmd
}
+97
View File
@@ -0,0 +1,97 @@
package cmd
import (
"errors"
"fmt"
"time"
"github.com/avast/retry-go"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/spf13/cobra"
)
// nolint:wrapcheck
func ListVersionsCmd() *cobra.Command {
var (
appID int64
bundleID string
)
cmd := &cobra.Command{
Use: "list-versions",
Short: "List the available versions of an iOS app",
RunE: func(cmd *cobra.Command, args []string) error {
if appID == 0 && bundleID == "" {
return errors.New("either the app ID or the bundle identifier must be specified")
}
var lastErr error
var acc appstore.Account
return retry.Do(func() error {
infoResult, err := dependencies.AppStore.AccountInfo()
if err != nil {
return err
}
acc = infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
Email: acc.Email,
Password: acc.Password,
Endpoint: bagOutput.AuthEndpoint,
})
if err != nil {
return err
}
acc = loginResult.Account
}
app := appstore.App{ID: appID}
if bundleID != "" {
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
if err != nil {
return err
}
app = lookupResult.App
}
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Account: acc, App: app})
if err != nil {
return err
}
dependencies.Logger.Log().
Interface("externalVersionIdentifiers", out.ExternalVersionIdentifiers).
Str("bundleID", app.BundleID).
Bool("success", true).
Send()
return nil
},
retry.LastErrorOnly(true),
retry.DelayType(retry.FixedDelay),
retry.Delay(time.Millisecond),
retry.Attempts(2),
retry.RetryIf(func(err error) bool {
lastErr = err
return errors.Is(err, appstore.ErrPasswordTokenExpired)
}),
)
},
}
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
return cmd
}
+25
View File
@@ -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)
}
}
+62 -13
View File
@@ -1,34 +1,83 @@
package cmd
import (
"github.com/99designs/keyring"
"github.com/pkg/errors"
"errors"
"fmt"
"time"
"github.com/avast/retry-go"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/spf13/cobra"
)
// nolint:wrapcheck
func purchaseCmd() *cobra.Command {
var keychainPassphrase string
var bundleID string
cmd := &cobra.Command{
Use: "purchase",
Short: "Obtain a license for the app from the App Store",
RunE: func(cmd *cobra.Command, args []string) error {
appstore, err := newAppStore(cmd, keychainPassphrase)
if err != nil {
return errors.Wrap(err, "failed to create appstore client")
}
var lastErr error
var acc appstore.Account
return appstore.Purchase(bundleID)
return retry.Do(func() error {
infoResult, err := dependencies.AppStore.AccountInfo()
if err != nil {
return err
}
acc = infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
Email: acc.Email,
Password: acc.Password,
Endpoint: bagOutput.AuthEndpoint,
})
if err != nil {
return err
}
acc = loginResult.Account
}
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
if err != nil {
return err
}
err = dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: lookupResult.App})
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
return err
}
dependencies.Logger.Log().
Bool("alreadyOwned", errors.Is(err, appstore.ErrLicenseAlreadyExists)).
Bool("success", true).
Send()
return nil
},
retry.LastErrorOnly(true),
retry.DelayType(retry.FixedDelay),
retry.Delay(time.Millisecond),
retry.Attempts(2),
retry.RetryIf(func(err error) bool {
lastErr = err
return errors.Is(err, appstore.ErrPasswordTokenExpired)
}),
)
},
}
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "Bundle identifier of the target iOS app (required)")
if keyringBackendType() == keyring.FileBackend {
cmd.Flags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
}
_ = cmd.MarkFlagRequired("bundle-identifier")
return cmd
+40 -28
View File
@@ -1,16 +1,27 @@
package cmd
import (
"github.com/pkg/errors"
"context"
"errors"
"reflect"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/spf13/cobra"
"github.com/thediveo/enumflag/v2"
"golang.org/x/net/context"
)
var version = "dev"
type contextKey string
const interactiveKey contextKey = "interactive"
func rootCmd() *cobra.Command {
var verbose bool
var nonInteractive bool
var format OutputFormat
var (
verbose bool
nonInteractive bool
format OutputFormat
)
cmd := &cobra.Command{
Use: "ipatool",
@@ -18,17 +29,10 @@ func rootCmd() *cobra.Command {
SilenceErrors: true,
SilenceUsage: true,
Version: version,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
ctx := context.WithValue(context.Background(), "logger", newLogger(format, verbose))
ctx = context.WithValue(ctx, "interactive", nonInteractive == false)
PersistentPreRun: func(cmd *cobra.Command, args []string) {
ctx := context.WithValue(context.Background(), interactiveKey, !nonInteractive)
cmd.SetContext(ctx)
err := configureConfigDirectory()
if err != nil {
return errors.Wrap(err, "failed to configure config directory")
}
return nil
initWithCommand(cmd)
},
}
@@ -39,37 +43,45 @@ func rootCmd() *cobra.Command {
}, enumflag.EnumCaseSensitive), "format", "", "sets output format for command; can be 'text', 'json'")
cmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "enables verbose logs")
cmd.PersistentFlags().BoolVarP(&nonInteractive, "non-interactive", "", false, "run in non-interactive session")
cmd.PersistentFlags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
cmd.AddCommand(authCmd())
cmd.AddCommand(downloadCmd())
cmd.AddCommand(purchaseCmd())
cmd.AddCommand(searchCmd())
cmd.AddCommand(ListVersionsCmd())
cmd.AddCommand(getVersionMetadataCmd())
return cmd
}
// Execute runs the program and returns the approperiate exit status code.
func Execute() (exitCode int) {
// Execute runs the program and returns the appropriate exit status code.
func Execute() int {
cmd := rootCmd()
err := cmd.Execute()
if err != nil {
exitCode = 1
logger := newLogger(OutputFormatText, false)
outputFormat, parseErr := parseOutputFormat(cmd.Flag("format").Value.String())
if parseErr != nil {
logger.Error().Err(parseErr).Send()
return
if err != nil {
if reflect.ValueOf(dependencies).IsZero() {
initWithCommand(cmd)
}
logger = newLogger(outputFormat, cmd.Flag("verbose").Value.String() == "true")
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()
}
logger.Verbose().Stack().Err(err).Send()
logger.Error().
dependencies.Logger.Error().
Err(err).
Bool("success", false).
Send()
return 1
}
return
return 0
}
+31 -12
View File
@@ -1,34 +1,53 @@
package cmd
import (
"github.com/99designs/keyring"
"github.com/pkg/errors"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/spf13/cobra"
)
// nolint:wrapcheck
func searchCmd() *cobra.Command {
var keychainPassphrase string
var limit int64
var (
limit int64
platformValue string
)
cmd := &cobra.Command{
Use: "search <term>",
Short: "Search for iOS apps available on the App Store",
Short: "Search for iOS and tvOS apps available on the App Store",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
appstore, err := newAppStore(cmd, keychainPassphrase)
infoResult, err := dependencies.AppStore.AccountInfo()
if err != nil {
return errors.Wrap(err, "failed to create appstore client")
return err
}
return appstore.Search(args[0], limit)
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")
if keyringBackendType() == keyring.FileBackend {
cmd.PersistentFlags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
}
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone, ipad, or appletv")
return cmd
}
+41 -21
View File
@@ -1,43 +1,63 @@
module github.com/majd/ipatool
module github.com/majd/ipatool/v2
go 1.19
go 1.25.0
require (
github.com/99designs/keyring v1.2.1
github.com/golang/mock v1.6.0
github.com/avast/retry-go v3.0.0+incompatible
github.com/byteness/keyring v1.9.0
github.com/juju/persistent-cookiejar v1.0.0
github.com/onsi/ginkgo/v2 v2.5.0
github.com/onsi/gomega v1.24.0
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.28.0
github.com/schollz/progressbar/v3 v3.13.1
github.com/spf13/cobra v1.6.1
github.com/thediveo/enumflag/v2 v2.0.1
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
golang.org/x/net v0.8.0
golang.org/x/term v0.6.0
go.uber.org/mock v0.4.0
golang.org/x/term v0.43.0
howett.net/plist v1.0.0
)
require (
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
github.com/danieljoos/wincred v1.1.2 // indirect
github.com/dvsekhvalnov/jose2go v1.5.0 // indirect
github.com/go-logr/logr v1.2.3 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b // indirect
github.com/1password/onepassword-sdk-go v0.4.1-beta.1 // indirect
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 // indirect
github.com/byteness/percent v0.2.2 // indirect
github.com/danieljoos/wincred v1.2.3 // indirect
github.com/dvsekhvalnov/jose2go v1.8.0 // indirect
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 // indirect
github.com/extism/go-sdk v1.7.1 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/godbus/dbus/v5 v5.2.2 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f // indirect
github.com/inconshreveable/mousetrap v1.0.1 // indirect
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/rivo/uniseg v0.4.3 // indirect
github.com/schollz/progressbar/v3 v3.12.1 // indirect
github.com/noamcohen97/touchid-go v0.3.0 // indirect
github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/text v0.8.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
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/crypto v0.51.0 // indirect
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
golang.org/x/mod v0.35.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
golang.org/x/tools v0.44.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/errgo.v1 v1.0.1 // indirect
gopkg.in/retry.v1 v1.0.3 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
+84 -75
View File
@@ -1,31 +1,50 @@
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs=
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4=
github.com/99designs/keyring v1.2.1 h1:tYLp1ULvO7i3fI5vE21ReQuj99QFSs7lGm0xWyJo87o=
github.com/99designs/keyring v1.2.1/go.mod h1:fc+wB5KTk9wQ9sDx0kFXB3A0MaeGHM9AwRStKOQ5vOA=
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b h1:sVddTkAGVmDXJbZKgp+W1zC7hN4lLz9Nus1XmjbY7eo=
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b/go.mod h1:5rSymY4oIYtS4G3t0oMkGAXBeoYiukV3vkqlnEjIDJs=
github.com/1password/onepassword-sdk-go v0.4.1-beta.1 h1:b/tt+bAXFXR5f3/irmPAaytfmsN6+5Nj6pbsx5nmKZA=
github.com/1password/onepassword-sdk-go v0.4.1-beta.1/go.mod h1:j/CbzhucTywjlYrd6SE6k0LcQaFZ2l8OLBsAsOYtvD0=
github.com/HdrHistogram/hdrhistogram-go v1.1.2 h1:5IcZpTvzydCQeHzK4Ef/D5rrSqwxob0t8PQPMybUNFM=
github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo=
github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0=
github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY=
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:HFl8GFmwK19hYuXB8OQ0rTO9WOCgZY9JUy964zaYawY=
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:9HlL8SWBRtCZE7sCNq+c3//H/oHywgSwtocmPTdOij8=
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 h1:j59wGsxaBk6aFBuuYofk2oznMGZYyzFovjDqavlJHM8=
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0/go.mod h1:3FrDGTXj08zj6qtqlIvt0vS8eWNrrYpnXOEbcQgFmvM=
github.com/byteness/keyring v1.9.0 h1:9m+7pru+JkMJ8wxma5id5m6pSt2Zx/xPj77kyM+yAVE=
github.com/byteness/keyring v1.9.0/go.mod h1:a6CV8t/qfEUERPTP+dqeVfKgib2wz3PIYbMWRfmvmes=
github.com/byteness/percent v0.2.2 h1:vnIFh8WBR1xoC+U2etz0EMB1cgp+vsK6vynqTCeDziU=
github.com/byteness/percent v0.2.2/go.mod h1:nwavge92FhIyfnldz4YWZD8uxPVvdh8NlzLRd1VYRDs=
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0=
github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0=
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dvsekhvalnov/jose2go v1.5.0 h1:3j8ya4Z4kMCwT5nXIKFSV84YS+HdqSSO0VsTQxaLAeM=
github.com/dvsekhvalnov/jose2go v1.5.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU=
github.com/dvsekhvalnov/jose2go v1.8.0 h1:LqkkVKAlHFfH9LOEl5fe4p/zL02OhWE7pCufMBG2jLA=
github.com/dvsekhvalnov/jose2go v1.8.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU=
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 h1:idfl8M8rPW93NehFw5H1qqH8yG158t5POr+LX9avbJY=
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA=
github.com/frankban/quicktest v1.2.2 h1:xfmOhhoH5fGPgbEAlhLpJH9p0z/0Qizio9osmvn9IUY=
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0=
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU=
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f h1:Fnl4pzx8SR7k7JuzyW8lEtSFH6EQ8xgcypgIn8pcGIE=
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
@@ -43,99 +62,90 @@ github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs=
github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/noamcohen97/touchid-go v0.3.0 h1:fcXxVCizysD7KHRR6hrURt3nyNIs5JBGSbOIidD/3wo=
github.com/noamcohen97/touchid-go v0.3.0/go.mod h1:X9MRNIBGEmPqwpDm1G3fQOAQX7fwBlhzUbnkDTxuta0=
github.com/onsi/ginkgo/v2 v2.5.0 h1:TRtrvv2vdQqzkwrQ1ke6vtXf7IK34RBUJafIy1wMwls=
github.com/onsi/ginkgo/v2 v2.5.0/go.mod h1:Luc4sArBICYCS8THh8v3i3i5CuSZO+RaQRaJoeNwomw=
github.com/onsi/gomega v1.24.0 h1:+0glovB9Jd6z3VR+ScSwQqXVTIfJcGA9UBM8yzQxhqg=
github.com/onsi/gomega v1.24.0/go.mod h1:Z/NWtiqwBrwUt4/2loMmHL63EDLnYHmVbuBpDr2vQAg=
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.2/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=
github.com/rivo/uniseg v0.4.3/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/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.12.1 h1:JAhtIrLWAn6/p7i82SrpSG3fgAwlAxi+Sy12r4AzBvQ=
github.com/schollz/progressbar/v3 v3.12.1/go.mod h1:g7QSuwyGpqCjVQPFZXA31MSxtrhka9Y9LMdF+XT77/Y=
github.com/schollz/progressbar/v3 v3.13.1 h1:o8rySDYiQ59Mwzy2FELeHY5ZARXZTVJC7iHD6PEFUiE=
github.com/schollz/progressbar/v3 v3.13.1/go.mod h1:xvrbki8kfT1fzWzBT/UZd9L6GA+jdL7HAgq2RFnO6fQ=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.3.0 h1:NGXK3lHquSN08v5vWalVI/L8XU9hdzE/G6xsrze47As=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
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/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o=
github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVKhn2Um6rjCsSsg=
github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
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.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
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.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.1.0 h1:hZ/3BUoy5aId7sCpA/Tc5lt8DkFgdVS2onTpJsZ/fl0=
golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/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-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210819135213-f52c844e1c1c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0 h1:ljd4t30dBnAvMZaQCevtY0xLLD0A+bRZXbgLMLU1F/A=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.2.0 h1:z85xZCsEl7bi/KwbNADeBYoOP0++7W1ipu+aGnpwzRM=
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -144,7 +154,6 @@ gopkg.in/errgo.v1 v1.0.1/go.mod h1:3NjfXwocQRYAPTq4/fzX+CwUhPRcR/azYRhj8G+LqMo=
gopkg.in/retry.v1 v1.0.3 h1:a9CArYczAVv6Qs6VGoLMio99GEs7kY9UzSF9+LD+iGs=
gopkg.in/retry.v1 v1.0.3/go.mod h1:FJkXmWiMaAo7xB+xhvDF59zhfjDWyzmyAxiT4dB688g=
gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM=
+2 -1
View File
@@ -1,8 +1,9 @@
package main
import (
"github.com/majd/ipatool/cmd"
"os"
"github.com/majd/ipatool/v2/cmd"
)
func main() {
+1
View File
@@ -7,4 +7,5 @@ type Account struct {
Name string `json:"name,omitempty"`
StoreFront string `json:"storeFront,omitempty"`
Password string `json:"password,omitempty"`
Pod string `json:"pod,omitempty"`
}
+13
View File
@@ -12,6 +12,19 @@ type App struct {
Price float64 `json:"price,omitempty"`
}
type VersionHistoryInfo struct {
App App
LatestVersion string
VersionIdentifiers []string
}
type VersionDetails struct {
VersionID string
VersionString string
Success bool
Error string
}
type Apps []App
func (apps Apps) MarshalZerologArray(a *zerolog.Array) {
+2 -1
View File
@@ -3,6 +3,7 @@ package appstore
import (
"bytes"
"encoding/json"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/rs/zerolog"
@@ -73,6 +74,6 @@ var _ = Describe("App", func() {
Price: 0,
}
Expect(fileName(app)).To(Equal("app.bundle-id1_42_1.0.ipa"))
Expect(fileName(app, "1.0")).To(Equal("app.bundle-id1_42_1.0.ipa"))
})
})
+45 -34
View File
@@ -1,62 +1,73 @@
package appstore
import (
"github.com/majd/ipatool/pkg/http"
"github.com/majd/ipatool/pkg/keychain"
"github.com/majd/ipatool/pkg/log"
"github.com/majd/ipatool/pkg/util"
"io"
"os"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/keychain"
"github.com/majd/ipatool/v2/pkg/util/machine"
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
)
type AppStore interface {
Login(email, password, authCode string) error
Info() error
// Login authenticates with the App Store.
Login(input LoginInput) (LoginOutput, error)
// AccountInfo returns the information of the authenticated account.
AccountInfo() (AccountInfoOutput, error)
// Revoke revokes the active credentials.
Revoke() error
Search(term string, limit int64) error
Purchase(bundleID string) error
Download(bundleID string, outputPath string, acquireLicense bool) error
// Lookup looks apps up based on the specified bundle identifier.
Lookup(input LookupInput) (LookupOutput, error)
// Search searches the App Store for apps matching the specified term.
Search(input SearchInput) (SearchOutput, error)
// Purchase acquires a license for the desired app.
// Note: only free apps are supported.
Purchase(input PurchaseInput) error
// Download downloads the IPA package from the App Store to the desired location.
Download(input DownloadInput) (DownloadOutput, error)
// ReplicateSinf replicates the sinf for the IPA package.
ReplicateSinf(input ReplicateSinfInput) error
// VersionHistory lists the available versions of the specified app.
ListVersions(input ListVersionsInput) (ListVersionsOutput, error)
// GetVersionMetadata returns the metadata for the specified version.
GetVersionMetadata(input GetVersionMetadataInput) (GetVersionMetadataOutput, error)
// Bag fetches the bag which contains endpoint definitions.
Bag(input BagInput) (BagOutput, error)
}
type appstore struct {
keychain keychain.Keychain
loginClient http.Client[LoginResult]
searchClient http.Client[SearchResult]
purchaseClient http.Client[PurchaseResult]
downloadClient http.Client[DownloadResult]
loginClient http.Client[loginResult]
searchClient http.Client[searchResult]
purchaseClient http.Client[purchaseResult]
downloadClient http.Client[downloadResult]
platformClient http.Client[platformVersionLookupResult]
bagClient http.Client[bagResult]
httpClient http.Client[interface{}]
ioReader io.Reader
machine util.Machine
os util.OperatingSystem
logger log.Logger
interactive bool
machine machine.Machine
os operatingsystem.OperatingSystem
}
type AppStoreArgs struct {
type Args struct {
Keychain keychain.Keychain
CookieJar http.CookieJar
Logger log.Logger
OperatingSystem util.OperatingSystem
Machine util.Machine
Interactive bool
OperatingSystem operatingsystem.OperatingSystem
Machine machine.Machine
}
func NewAppStore(args AppStoreArgs) AppStore {
clientArgs := http.ClientArgs{
func NewAppStore(args Args) AppStore {
clientArgs := http.Args{
CookieJar: args.CookieJar,
}
return &appstore{
keychain: args.Keychain,
loginClient: http.NewClient[LoginResult](clientArgs),
searchClient: http.NewClient[SearchResult](clientArgs),
purchaseClient: http.NewClient[PurchaseResult](clientArgs),
downloadClient: http.NewClient[DownloadResult](clientArgs),
loginClient: http.NewClient[loginResult](clientArgs),
searchClient: http.NewClient[searchResult](clientArgs),
purchaseClient: http.NewClient[purchaseResult](clientArgs),
downloadClient: http.NewClient[downloadResult](clientArgs),
platformClient: http.NewClient[platformVersionLookupResult](clientArgs),
bagClient: http.NewClient[bagResult](clientArgs),
httpClient: http.NewClient[interface{}](clientArgs),
ioReader: os.Stdin,
machine: args.Machine,
os: args.OperatingSystem,
logger: args.Logger,
interactive: args.Interactive,
}
}
+28
View File
@@ -0,0 +1,28 @@
package appstore
import (
"encoding/json"
"fmt"
)
type AccountInfoOutput struct {
Account Account
}
func (t *appstore) AccountInfo() (AccountInfoOutput, error) {
data, err := t.keychain.Get("account")
if err != nil {
return AccountInfoOutput{}, fmt.Errorf("failed to get account: %w", err)
}
var acc Account
err = json.Unmarshal(data, &acc)
if err != nil {
return AccountInfoOutput{}, fmt.Errorf("failed to unmarshal json: %w", err)
}
return AccountInfoOutput{
Account: acc,
}, nil
}
@@ -1,29 +1,27 @@
package appstore
import (
"github.com/golang/mock/gomock"
"github.com/majd/ipatool/pkg/keychain"
"github.com/majd/ipatool/pkg/log"
"errors"
"fmt"
"github.com/majd/ipatool/v2/pkg/keychain"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"go.uber.org/mock/gomock"
)
var _ = Describe("AppStore (Info)", func() {
var _ = Describe("AppStore (AccountInfo)", func() {
var (
ctrl *gomock.Controller
appstore AppStore
mockKeychain *keychain.MockKeychain
mockLogger *log.MockLogger
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockKeychain = keychain.NewMockKeychain(ctrl)
mockLogger = log.NewMockLogger(ctrl)
appstore = NewAppStore(AppStoreArgs{
appstore = NewAppStore(Args{
Keychain: mockKeychain,
Logger: mockLogger,
})
})
@@ -31,19 +29,36 @@ var _ = Describe("AppStore (Info)", func() {
ctrl.Finish()
})
When("keychain returns error", func() {
var testErr = errors.New("test error")
When("keychain returns valid data", func() {
const (
testEmail = "test-email"
testName = "test-name"
)
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte{}, testErr)
Return([]byte(fmt.Sprintf("{\"email\": \"%s\", \"name\": \"%s\"}", testEmail, testName)), nil)
})
It("returns output", func() {
out, err := appstore.AccountInfo()
Expect(err).ToNot(HaveOccurred())
Expect(out.Account.Email).To(Equal(testEmail))
Expect(out.Account.Name).To(Equal(testName))
})
})
When("keychain returns error", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte{}, errors.New(""))
})
It("returns wrapped error", func() {
err := appstore.Info()
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
Expect(err).To(MatchError(ContainSubstring(ErrGetAccount.Error())))
_, err := appstore.AccountInfo()
Expect(err).To(HaveOccurred())
})
})
@@ -55,25 +70,8 @@ var _ = Describe("AppStore (Info)", func() {
})
It("fails to unmarshall JSON data", func() {
err := appstore.Info()
Expect(err).To(MatchError(ContainSubstring(ErrUnmarshal.Error())))
})
})
When("keychain returns valid data", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Log().
Return(nil)
mockKeychain.EXPECT().
Get("account").
Return([]byte("{}"), nil)
})
It("returns nil", func() {
err := appstore.Info()
Expect(err).ToNot(HaveOccurred())
_, err := appstore.AccountInfo()
Expect(err).To(HaveOccurred())
})
})
})
+57
View File
@@ -0,0 +1,57 @@
package appstore
import (
"fmt"
gohttp "net/http"
"strings"
"github.com/majd/ipatool/v2/pkg/http"
)
type BagInput struct{}
type BagOutput struct {
AuthEndpoint string
}
func (t *appstore) Bag(input BagInput) (BagOutput, error) {
macAddr, err := t.machine.MacAddress()
if err != nil {
return BagOutput{}, fmt.Errorf("failed to get mac address: %w", err)
}
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
req := t.bagRequest(guid)
res, err := t.bagClient.Send(req)
if err != nil {
return BagOutput{}, fmt.Errorf("failed to send http request: %w", err)
}
if res.StatusCode != gohttp.StatusOK {
return BagOutput{}, fmt.Errorf("received unexpected status code: %d", res.StatusCode)
}
return BagOutput{
AuthEndpoint: res.Data.URLBag.AuthEndpoint,
}, nil
}
type bagResult struct {
URLBag urlBag `plist:"urlBag,omitempty"`
}
type urlBag struct {
AuthEndpoint string `plist:"authenticateAccount,omitempty"`
}
func (*appstore) bagRequest(guid string) http.Request {
return http.Request{
URL: fmt.Sprintf("https://%s%s?guid=%s", PrivateInitDomain, PrivateInitPath, guid),
Method: http.MethodGET,
ResponseFormat: http.ResponseFormatXML,
Headers: map[string]string{
"Accept": "application/xml",
},
}
}
+141
View File
@@ -0,0 +1,141 @@
package appstore
import (
"errors"
gohttp "net/http"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/util/machine"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
)
var _ = Describe("AppStore (Bag)", func() {
var (
ctrl *gomock.Controller
mockBagClient *http.MockClient[bagResult]
mockMachine *machine.MockMachine
as AppStore
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockBagClient = http.NewMockClient[bagResult](ctrl)
mockMachine = machine.NewMockMachine(ctrl)
as = &appstore{
bagClient: mockBagClient,
machine: mockMachine,
}
})
AfterEach(func() {
ctrl.Finish()
})
When("fails to read machine MAC address", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("", errors.New("mac error"))
})
It("returns error", func() {
_, err := as.Bag(BagInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to get mac address"))
})
})
When("request fails", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockBagClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[bagResult]{}, errors.New("request error"))
})
It("returns wrapped error", func() {
_, err := as.Bag(BagInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to send http request"))
})
})
When("request returns non-200 status code", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockBagClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[bagResult]{
StatusCode: gohttp.StatusForbidden,
}, nil)
})
It("returns error", func() {
_, err := as.Bag(BagInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("received unexpected status code"))
})
})
When("request is successful with authenticateAccount in urlBag", func() {
const testAuthEndpoint = "https://example.com"
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("aa:bb:cc:dd:ee:ff", nil)
mockBagClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
Expect(req.Method).To(Equal(http.MethodGET))
Expect(req.URL).To(Equal("https://init.itunes.apple.com/bag.xml?guid=AABBCCDDEEFF"))
Expect(req.ResponseFormat).To(Equal(http.ResponseFormatXML))
Expect(req.Headers).To(HaveKeyWithValue("Accept", "application/xml"))
}).
Return(http.Result[bagResult]{
StatusCode: gohttp.StatusOK,
Data: bagResult{
URLBag: urlBag{
AuthEndpoint: testAuthEndpoint,
},
},
}, nil)
})
It("returns output", func() {
out, err := as.Bag(BagInput{})
Expect(err).ToNot(HaveOccurred())
Expect(out.AuthEndpoint).To(Equal(testAuthEndpoint))
})
})
When("request is successful but authenticateAccount is empty", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("aa:bb:cc:dd:ee:ff", nil)
mockBagClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[bagResult]{
StatusCode: gohttp.StatusOK,
Data: bagResult{},
}, nil)
})
It("returns empty auth endpoint", func() {
out, err := as.Bag(BagInput{})
Expect(err).ToNot(HaveOccurred())
Expect(out.AuthEndpoint).To(BeEmpty())
})
})
})
+232 -314
View File
@@ -2,219 +2,261 @@ package appstore
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"github.com/majd/ipatool/pkg/http"
"github.com/majd/ipatool/pkg/util"
"github.com/pkg/errors"
"github.com/schollz/progressbar/v3"
"howett.net/plist"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/schollz/progressbar/v3"
"howett.net/plist"
)
type DownloadSinfResult struct {
ID int64 `plist:"id,omitempty"`
Data []byte `plist:"sinf,omitempty"`
var (
ErrLicenseRequired = errors.New("license is required")
)
type DownloadInput struct {
Account Account
App App
OutputPath string
Progress *progressbar.ProgressBar
ExternalVersionID string
Platform Platform
}
type DownloadItemResult struct {
HashMD5 string `plist:"md5,omitempty"`
URL string `plist:"URL,omitempty"`
Sinfs []DownloadSinfResult `plist:"sinfs,omitempty"`
Metadata map[string]interface{} `plist:"metadata,omitempty"`
type DownloadOutput struct {
DestinationPath string
Sinfs []Sinf
}
type DownloadResult struct {
FailureType string `plist:"failureType,omitempty"`
CustomerMessage string `plist:"customerMessage,omitempty"`
Items []DownloadItemResult `plist:"songList,omitempty"`
}
type PackageManifest struct {
SinfPaths []string `plist:"SinfPaths,omitempty"`
}
type PackageInfo struct {
BundleExecutable string `plist:"CFBundleExecutable,omitempty"`
}
func (a *appstore) Download(bundleID string, outputPath string, acquireLicense bool) error {
acc, err := a.account()
func (t *appstore) Download(input DownloadInput) (DownloadOutput, error) {
macAddr, err := t.machine.MacAddress()
if err != nil {
return errors.Wrap(err, ErrGetAccount.Error())
}
countryCode, err := a.countryCodeFromStoreFront(acc.StoreFront)
if err != nil {
return errors.Wrap(err, ErrInvalidCountryCode.Error())
}
app, err := a.lookup(bundleID, countryCode)
if err != nil {
return errors.Wrap(err, ErrAppLookup.Error())
}
destination, err := a.resolveDestinationPath(app, outputPath)
if err != nil {
return errors.Wrap(err, ErrResolveDestinationPath.Error())
}
macAddr, err := a.machine.MacAddress()
if err != nil {
return errors.Wrap(err, ErrGetMAC.Error())
return DownloadOutput{}, fmt.Errorf("failed to get mac address: %w", err)
}
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
a.logger.Verbose().Str("mac", macAddr).Str("guid", guid).Send()
err = a.download(acc, app, destination, guid, acquireLicense, true)
if err != nil {
return errors.Wrap(err, ErrDownloadFile.Error())
}
a.logger.Log().Str("output", destination).Bool("success", true).Send()
return nil
}
func (a *appstore) download(acc Account, app App, dst, guid string, acquireLicense, attemptToRenewCredentials bool) error {
req := a.downloadRequest(acc, app, guid)
res, err := a.downloadClient.Send(req)
if err != nil {
return errors.Wrap(err, ErrRequest.Error())
}
if res.Data.FailureType == FailureTypePasswordTokenExpired {
if attemptToRenewCredentials {
a.logger.Verbose().Msg("retrieving new password token")
acc, err = a.login(acc.Email, acc.Password, "", guid, 0, true)
if err != nil {
return errors.Wrap(err, ErrPasswordTokenExpired.Error())
}
return a.download(acc, app, dst, guid, acquireLicense, false)
}
return ErrPasswordTokenExpired
}
if res.Data.FailureType == FailureTypeLicenseNotFound && acquireLicense {
a.logger.Verbose().Msg("attempting to acquire license")
err = a.purchase(app.BundleID, guid, true)
externalVersionID := input.ExternalVersionID
if externalVersionID == "" && input.Platform == PlatformAppleTV {
externalVersionID, err = t.lookupLatestExternalVersionID(input.Account, input.App, input.Platform)
if err != nil {
return errors.Wrap(err, ErrPurchase.Error())
return DownloadOutput{}, fmt.Errorf("failed to resolve platform version: %w", err)
}
}
return a.download(acc, app, dst, guid, false, attemptToRenewCredentials)
req := t.downloadRequest(input.Account, input.App, guid, externalVersionID)
res, err := t.downloadClient.Send(req)
if err != nil {
return DownloadOutput{}, fmt.Errorf("failed to send http request: %w", err)
}
if res.Data.FailureType == FailureTypePasswordTokenExpired ||
res.Data.FailureType == FailureTypeSignInRequired ||
res.Data.FailureType == FailureTypeDeviceVerificationFailed ||
res.Data.FailureType == FailureTypeLicenseAlreadyExists {
return DownloadOutput{}, ErrPasswordTokenExpired
}
if res.Data.FailureType == FailureTypeLicenseNotFound {
return ErrLicenseRequired
return DownloadOutput{}, ErrLicenseRequired
}
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
a.logger.Verbose().Interface("response", res).Send()
return errors.New(res.Data.CustomerMessage)
return DownloadOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
}
if res.Data.FailureType != "" {
a.logger.Verbose().Interface("response", res).Send()
return ErrGeneric
return DownloadOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.FailureType), res)
}
if len(res.Data.Items) == 0 {
a.logger.Verbose().Interface("response", res).Send()
return ErrInvalidResponse
return DownloadOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
}
item := res.Data.Items[0]
err = a.downloadFile(fmt.Sprintf("%s.tmp", dst), item.URL)
if err != nil {
return errors.Wrap(err, ErrDownloadFile.Error())
version := "unknown"
// Read the version from the item metadata
if itemVersion, ok := item.Metadata["bundleShortVersionString"]; ok {
version = fmt.Sprintf("%v", itemVersion)
}
err = a.applyPatches(item, acc, fmt.Sprintf("%s.tmp", dst), dst)
destination, err := t.resolveDestinationPath(input.App, version, input.OutputPath)
if err != nil {
return errors.Wrap(err, ErrPatchApp.Error())
return DownloadOutput{}, fmt.Errorf("failed to resolve destination path: %w", err)
}
err = a.os.Remove(fmt.Sprintf("%s.tmp", dst))
tmpPath := fmt.Sprintf("%s.tmp", destination)
err = t.downloadFile(item.URL, tmpPath, input.Progress)
if err != nil {
return errors.Wrap(err, ErrRemoveTempFile.Error())
return DownloadOutput{}, fmt.Errorf("failed to download file: %w", err)
}
return nil
err = t.applyPatches(item, input.Account, tmpPath, destination)
if err != nil {
return DownloadOutput{}, fmt.Errorf("failed to apply patches: %w", err)
}
err = t.validatePackagePlatform(destination, input.Platform)
if err != nil {
return DownloadOutput{}, fmt.Errorf("failed to validate package platform: %w", err)
}
err = t.os.Remove(fmt.Sprintf("%s.tmp", destination))
if err != nil {
return DownloadOutput{}, fmt.Errorf("failed to remove file: %w", err)
}
return DownloadOutput{
DestinationPath: destination,
Sinfs: item.Sinfs,
}, nil
}
func (a *appstore) downloadFile(dst, sourceURL string) (err error) {
req, err := a.httpClient.NewRequest("GET", sourceURL, nil)
if err != nil {
return errors.Wrap(err, ErrCreateRequest.Error())
type platformPackageInfo struct {
SupportedPlatforms []string `plist:"CFBundleSupportedPlatforms,omitempty"`
}
func (*appstore) validatePackagePlatform(path string, platform Platform) error {
if platform != PlatformAppleTV {
return nil
}
res, err := a.httpClient.Do(req)
reader, err := zip.OpenReader(path)
if err != nil {
return errors.Wrap(err, ErrRequest.Error())
return fmt.Errorf("failed to open zip reader: %w", err)
}
defer reader.Close()
defer func() {
if closeErr := res.Body.Close(); closeErr != err && err == nil {
err = closeErr
for _, file := range reader.File {
if !strings.HasPrefix(file.Name, "Payload/") || !strings.HasSuffix(file.Name, ".app/Info.plist") {
continue
}
}()
file, err := a.os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return errors.Wrap(err, ErrOpenFile.Error())
infoFile, err := file.Open()
if err != nil {
return fmt.Errorf("failed to open info plist: %w", err)
}
data, readErr := io.ReadAll(infoFile)
closeErr := infoFile.Close()
if readErr != nil {
return fmt.Errorf("failed to read info plist: %w", readErr)
}
if closeErr != nil {
return fmt.Errorf("failed to close info plist: %w", closeErr)
}
var info platformPackageInfo
_, err = plist.Unmarshal(data, &info)
if err != nil {
return fmt.Errorf("failed to decode info plist: %w", err)
}
for _, supportedPlatform := range info.SupportedPlatforms {
if supportedPlatform == "AppleTVOS" {
return nil
}
}
}
defer func() {
if closeErr := file.Close(); closeErr != err && err == nil {
err = closeErr
return errors.New("downloaded package does not declare AppleTVOS support")
}
type downloadItemResult struct {
HashMD5 string `plist:"md5,omitempty"`
URL string `plist:"URL,omitempty"`
Sinfs []Sinf `plist:"sinfs,omitempty"`
Metadata map[string]interface{} `plist:"metadata,omitempty"`
}
type downloadResult struct {
FailureType string `plist:"failureType,omitempty"`
CustomerMessage string `plist:"customerMessage,omitempty"`
Items []downloadItemResult `plist:"songList,omitempty"`
}
func (t *appstore) downloadFile(src, dst string, progress *progressbar.ProgressBar) error {
req, err := t.httpClient.NewRequest("GET", src, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
file, err := t.os.OpenFile(dst, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
stat, err := t.os.Stat(dst)
if err != nil {
return fmt.Errorf("failed to get file info: %w", err)
}
if req != nil && stat != nil {
req.Header.Add("range", fmt.Sprintf("bytes=%d-", stat.Size()))
}
res, err := t.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer res.Body.Close()
if progress != nil {
progress.ChangeMax64(res.ContentLength + stat.Size())
err = progress.Set64(stat.Size())
if err != nil {
return fmt.Errorf("can not set bar progress: %w", err)
}
}()
sizeMB := float64(res.ContentLength) / (1 << 20)
a.logger.Verbose().Str("size", fmt.Sprintf("%.2fMB", sizeMB)).Msg("downloading")
_, err = file.Seek(0, io.SeekEnd)
if err != nil {
return fmt.Errorf("can not seek file: %w", err)
}
if a.interactive {
bar := progressbar.NewOptions64(res.ContentLength,
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),
)
_, err = io.Copy(io.MultiWriter(file, bar), res.Body)
_, err = io.Copy(io.MultiWriter(file, progress), res.Body)
} else {
_, err = io.Copy(file, res.Body)
}
if err != nil {
return errors.Wrap(err, ErrFileWrite.Error())
return fmt.Errorf("failed to write file: %w", err)
}
return nil
}
func (*appstore) downloadRequest(acc Account, app App, guid string) http.Request {
host := fmt.Sprintf("%s-%s", PriavteAppStoreAPIDomainPrefixWithoutAuthCode, PrivateAppStoreAPIDomain)
func (*appstore) downloadRequest(acc Account, app App, guid string, externalVersionID string) http.Request {
payload := map[string]interface{}{
"creditDisplay": "",
"guid": guid,
"salableAdamId": app.ID,
}
if externalVersionID != "" {
payload["externalVersionId"] = externalVersionID
}
podPrefix := ""
if acc.Pod != "" {
podPrefix = "p" + acc.Pod + "-"
}
return http.Request{
URL: fmt.Sprintf("https://%s%s?guid=%s", host, PrivateAppStoreAPIPathDownload, guid),
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
Method: http.MethodPOST,
ResponseFormat: http.ResponseFormatXML,
Headers: map[string]string{
@@ -223,37 +265,44 @@ func (*appstore) downloadRequest(acc Account, app App, guid string) http.Request
"X-Dsid": acc.DirectoryServicesID,
},
Payload: &http.XMLPayload{
Content: map[string]interface{}{
"creditDisplay": "",
"guid": guid,
"salableAdamId": app.ID,
},
Content: payload,
},
}
}
func fileName(app App) string {
return fmt.Sprintf("%s_%d_%s.ipa",
app.BundleID,
app.ID,
app.Version)
func fileName(app App, version string) string {
var parts []string
if app.BundleID != "" {
parts = append(parts, app.BundleID)
}
if app.ID != 0 {
parts = append(parts, strconv.FormatInt(app.ID, 10))
}
if version != "" {
parts = append(parts, version)
}
return fmt.Sprintf("%s.ipa", strings.Join(parts, "_"))
}
func (a *appstore) resolveDestinationPath(app App, path string) (string, error) {
file := fileName(app)
func (t *appstore) resolveDestinationPath(app App, version string, path string) (string, error) {
file := fileName(app, version)
if path == "" {
workdir, err := a.os.Getwd()
workdir, err := t.os.Getwd()
if err != nil {
return "", errors.Wrap(err, ErrGetCurrentDirectory.Error())
return "", fmt.Errorf("failed to get current directory: %w", err)
}
return fmt.Sprintf("%s/%s", workdir, file), nil
}
isDir, err := a.isDirectory(path)
isDir, err := t.isDirectory(path)
if err != nil {
return "", errors.Wrap(err, ErrCheckDirectory.Error())
return "", fmt.Errorf("failed to determine whether path is a directory: %w", err)
}
if isDir {
@@ -263,10 +312,10 @@ func (a *appstore) resolveDestinationPath(app App, path string) (string, error)
return path, nil
}
func (a *appstore) isDirectory(path string) (bool, error) {
info, err := a.os.Stat(path)
func (t *appstore) isDirectory(path string) (bool, error) {
info, err := t.os.Stat(path)
if err != nil && !os.IsNotExist(err) {
return false, errors.Wrap(err, ErrGetFileMetadata.Error())
return false, fmt.Errorf("failed to read file metadata: %w", err)
}
if info == nil {
@@ -276,183 +325,52 @@ func (a *appstore) isDirectory(path string) (bool, error) {
return info.IsDir(), nil
}
func (a *appstore) applyPatches(item DownloadItemResult, acc Account, src, dst string) (err error) {
dstFile, err := a.os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return errors.Wrap(err, ErrOpenFile.Error())
}
func (t *appstore) applyPatches(item downloadItemResult, acc Account, src, dst string) error {
srcZip, err := zip.OpenReader(src)
if err != nil {
return errors.Wrap(err, ErrOpenZipFile.Error())
return fmt.Errorf("failed to open zip reader: %w", err)
}
defer func() {
if closeErr := srcZip.Close(); closeErr != err && err == nil {
err = closeErr
}
}()
defer srcZip.Close()
dstFile, err := t.os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer dstFile.Close()
dstZip := zip.NewWriter(dstFile)
defer func() {
if closeErr := dstZip.Close(); closeErr != err && err == nil {
err = closeErr
}
}()
defer dstZip.Close()
manifestData := new(bytes.Buffer)
infoData := new(bytes.Buffer)
appBundle, err := a.replicateZip(srcZip, dstZip, infoData, manifestData)
err = t.replicateZip(srcZip, dstZip)
if err != nil {
return errors.Wrap(err, ErrReplicateZip.Error())
return fmt.Errorf("failed to replicate zip: %w", err)
}
err = a.writeMetadata(item.Metadata, acc, dstZip)
err = t.writeMetadata(item.Metadata, acc, dstZip)
if err != nil {
return errors.Wrap(err, ErrWriteMetadataFile.Error())
}
if manifestData.Len() > 0 {
err = a.applySinfPatches(item, dstZip, manifestData.Bytes(), appBundle)
if err != nil {
return errors.Wrap(err, ErrApplyPatches.Error())
}
} else {
err = a.applyLegacySinfPatches(item, dstZip, infoData.Bytes(), appBundle)
if err != nil {
return errors.Wrap(err, ErrApplyLegacyPatches.Error())
}
return fmt.Errorf("failed to write metadata: %w", err)
}
return nil
}
func (a *appstore) writeMetadata(metadata map[string]interface{}, acc Account, zip *zip.Writer) error {
func (t *appstore) writeMetadata(metadata map[string]interface{}, acc Account, zip *zip.Writer) error {
metadata["apple-id"] = acc.Email
metadata["userName"] = acc.Email
metadataFile, err := zip.Create("iTunesMetadata.plist")
if err != nil {
return errors.Wrap(err, ErrCreateMetadataFile.Error())
return fmt.Errorf("failed to create file: %w", err)
}
data, err := plist.Marshal(metadata, plist.BinaryFormat)
if err != nil {
return errors.Wrap(err, ErrEncodeMetadataFile.Error())
return fmt.Errorf("failed to marshal data: %w", err)
}
_, err = metadataFile.Write(data)
if err != nil {
return errors.Wrap(err, ErrWriteMetadataFile.Error())
}
return nil
}
func (a *appstore) replicateZip(src *zip.ReadCloser, dst *zip.Writer, info *bytes.Buffer, manifest *bytes.Buffer) (appBundle string, err error) {
for _, file := range src.File {
srcFile, err := file.OpenRaw()
if err != nil {
return "", errors.Wrap(err, ErrOpenFile.Error())
}
if strings.HasSuffix(file.Name, ".app/SC_Info/Manifest.plist") {
srcFileD, err := file.Open()
if err != nil {
return "", errors.Wrap(err, ErrDecompressManifestFile.Error())
}
_, err = io.Copy(manifest, srcFileD)
if err != nil {
return "", errors.Wrap(err, ErrGetManifestFile.Error())
}
}
if strings.Contains(file.Name, ".app/Info.plist") {
srcFileD, err := file.Open()
if err != nil {
return "", errors.Wrap(err, ErrDecompressInfoFile.Error())
}
if !strings.Contains(file.Name, "/Watch/") {
appBundle = filepath.Base(strings.TrimSuffix(file.Name, ".app/Info.plist"))
}
_, err = io.Copy(info, srcFileD)
if err != nil {
return "", errors.Wrap(err, ErrGetInfoFile.Error())
}
}
header := file.FileHeader
dstFile, err := dst.CreateRaw(&header)
if err != nil {
return "", errors.Wrap(err, ErrCreateDestinationFile.Error())
}
_, err = io.Copy(dstFile, srcFile)
if err != nil {
return "", errors.Wrap(err, ErrFileWrite.Error())
}
}
if appBundle == "" {
return "", ErrGetBundleName
}
return appBundle, nil
}
func (a *appstore) applySinfPatches(item DownloadItemResult, zip *zip.Writer, manifestData []byte, appBundle string) error {
var manifest PackageManifest
_, err := plist.Unmarshal(manifestData, &manifest)
if err != nil {
return errors.Wrap(err, ErrUnmarshal.Error())
}
zipped, err := util.Zip(item.Sinfs, manifest.SinfPaths)
if err != nil {
return errors.Wrap(err, ErrZipSinfs.Error())
}
for _, pair := range zipped {
sp := fmt.Sprintf("Payload/%s.app/%s", appBundle, pair.Second)
a.logger.Verbose().Str("path", sp).Msg("writing sinf data")
file, err := zip.Create(sp)
if err != nil {
return errors.Wrap(err, ErrCreateSinfFile.Error())
}
_, err = file.Write(pair.First.Data)
if err != nil {
return errors.Wrap(err, ErrWriteSinfData.Error())
}
}
return nil
}
func (a *appstore) applyLegacySinfPatches(item DownloadItemResult, zip *zip.Writer, infoData []byte, appBundle string) error {
a.logger.Verbose().Msg("applying legacy sinf patches")
var info PackageInfo
_, err := plist.Unmarshal(infoData, &info)
if err != nil {
return errors.Wrap(err, ErrUnmarshal.Error())
}
sp := fmt.Sprintf("Payload/%s.app/SC_Info/%s.sinf", appBundle, info.BundleExecutable)
a.logger.Verbose().Str("path", sp).Msg("writing sinf data")
file, err := zip.Create(sp)
if err != nil {
return errors.Wrap(err, ErrCreateSinfFile.Error())
}
_, err = file.Write(item.Sinfs[0].Data)
if err != nil {
return errors.Wrap(err, ErrWriteSinfData.Error())
return fmt.Errorf("failed to write data: %w", err)
}
return nil
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,97 @@
package appstore
import (
"errors"
"fmt"
"strings"
"time"
"github.com/majd/ipatool/v2/pkg/http"
)
type GetVersionMetadataInput struct {
Account Account
App App
VersionID string
}
type GetVersionMetadataOutput struct {
DisplayVersion string
ReleaseDate time.Time
}
func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersionMetadataOutput, error) {
macAddr, err := t.machine.MacAddress()
if err != nil {
return GetVersionMetadataOutput{}, fmt.Errorf("failed to get mac address: %w", err)
}
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
req := t.getVersionMetadataRequest(input.Account, input.App, guid, input.VersionID)
res, err := t.downloadClient.Send(req)
if err != nil {
return GetVersionMetadataOutput{}, fmt.Errorf("failed to send http request: %w", err)
}
if res.Data.FailureType == FailureTypePasswordTokenExpired || res.Data.FailureType == FailureTypeSignInRequired {
return GetVersionMetadataOutput{}, ErrPasswordTokenExpired
}
if res.Data.FailureType == FailureTypeLicenseNotFound {
return GetVersionMetadataOutput{}, ErrLicenseRequired
}
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
return GetVersionMetadataOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
}
if res.Data.FailureType != "" {
return GetVersionMetadataOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.FailureType), res)
}
if len(res.Data.Items) == 0 {
return GetVersionMetadataOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
}
item := res.Data.Items[0]
// Do not fall back to item.Metadata here. The App Store download API can
// return stale version and release date values, so the IPA Info.plist is the
// source of truth and failures should be visible to callers.
metadata, err := t.readVersionMetadataFromIPA(item.URL)
if err != nil {
return GetVersionMetadataOutput{}, fmt.Errorf("failed to read version metadata: %w", err)
}
return GetVersionMetadataOutput(metadata), nil
}
func (t *appstore) getVersionMetadataRequest(acc Account, app App, guid string, version string) http.Request {
payload := map[string]interface{}{
"creditDisplay": "",
"guid": guid,
"salableAdamId": app.ID,
"externalVersionId": version,
}
podPrefix := ""
if acc.Pod != "" {
podPrefix = "p" + acc.Pod + "-"
}
return http.Request{
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
Method: http.MethodPOST,
ResponseFormat: http.ResponseFormatXML,
Headers: map[string]string{
"Content-Type": "application/x-apple-plist",
"iCloud-DSID": acc.DirectoryServicesID,
"X-Dsid": acc.DirectoryServicesID,
},
Payload: &http.XMLPayload{
Content: payload,
},
}
}
@@ -0,0 +1,524 @@
package appstore
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
gohttp "net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/util/machine"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
"howett.net/plist"
)
func testIPA(displayVersion string, releaseDate interface{}, modified time.Time) []byte {
buffer := new(bytes.Buffer)
zipWriter := zip.NewWriter(buffer)
fillerHeader := &zip.FileHeader{
Name: "Payload/Test.app/Filler.bin",
Method: zip.Store,
}
filler, err := zipWriter.CreateHeader(fillerHeader)
Expect(err).ToNot(HaveOccurred())
_, err = filler.Write(make([]byte, 1024*1024))
Expect(err).ToNot(HaveOccurred())
infoHeader := &zip.FileHeader{
Name: "Payload/Test.app/Info.plist",
Method: zip.Deflate,
Modified: modified,
}
infoFile, err := zipWriter.CreateHeader(infoHeader)
Expect(err).ToNot(HaveOccurred())
info := map[string]interface{}{
"CFBundleExecutable": "Test",
"CFBundleShortVersionString": displayVersion,
}
if releaseDate != nil {
info["releaseDate"] = releaseDate
}
infoData, err := plist.Marshal(info, plist.BinaryFormat)
Expect(err).ToNot(HaveOccurred())
_, err = infoFile.Write(infoData)
Expect(err).ToNot(HaveOccurred())
err = zipWriter.Close()
Expect(err).ToNot(HaveOccurred())
return buffer.Bytes()
}
func testIPAServer(data []byte) (*httptest.Server, *int64, *int64) {
return testIPAServerWithRangeLog(data, nil)
}
func testIPAServerWithRangeLog(data []byte, rangeLog *[]string) (*httptest.Server, *int64, *int64) {
var (
servedBytes int64
wholeGetCount int64
)
server := httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, r *gohttp.Request) {
if r.Method != gohttp.MethodGet {
w.WriteHeader(gohttp.StatusMethodNotAllowed)
return
}
rangeHeader := r.Header.Get("Range")
if rangeLog != nil {
*rangeLog = append(*rangeLog, rangeHeader)
}
if rangeHeader == "" {
atomic.AddInt64(&wholeGetCount, 1)
w.WriteHeader(gohttp.StatusOK)
_, _ = w.Write(data)
return
}
start, end, err := testRangeBounds(rangeHeader, len(data))
if err != nil {
w.WriteHeader(gohttp.StatusRequestedRangeNotSatisfiable)
return
}
w.Header().Set("Accept-Ranges", "bytes")
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(data)))
w.Header().Set("Content-Length", strconv.Itoa(end-start+1))
w.WriteHeader(gohttp.StatusPartialContent)
n, _ := w.Write(data[start : end+1])
atomic.AddInt64(&servedBytes, int64(n))
}))
return server, &servedBytes, &wholeGetCount
}
func testRangeBounds(header string, size int) (int, int, error) {
if !strings.HasPrefix(header, "bytes=") {
return 0, 0, fmt.Errorf("invalid range header: %s", header)
}
parts := strings.Split(strings.TrimPrefix(header, "bytes="), "-")
if len(parts) != 2 {
return 0, 0, fmt.Errorf("invalid range header: %s", header)
}
start, err := strconv.Atoi(parts[0])
if err != nil {
return 0, 0, fmt.Errorf("failed to parse range start: %w", err)
}
end := size - 1
if parts[1] != "" {
end, err = strconv.Atoi(parts[1])
if err != nil {
return 0, 0, fmt.Errorf("failed to parse range end: %w", err)
}
}
if start < 0 || start >= size || end < start {
return 0, 0, fmt.Errorf("invalid range bounds: %s", header)
}
if end >= size {
end = size - 1
}
return start, end, nil
}
var _ = Describe("HTTPRangeReaderAt", func() {
It("clamps reads that cross EOF", func() {
data := []byte("abcdef")
rangeLog := []string{}
server, _, _ := testIPAServerWithRangeLog(data, &rangeLog)
defer server.Close()
reader, size, err := newHTTPRangeReaderAt(http.NewClient[interface{}](http.Args{}), server.URL)
Expect(err).NotTo(HaveOccurred())
Expect(size).To(Equal(int64(len(data))))
buf := make([]byte, 4)
n, err := reader.ReadAt(buf, 4)
Expect(n).To(Equal(2))
Expect(err).To(Equal(io.EOF))
Expect(string(buf[:n])).To(Equal("ef"))
Expect(rangeLog).To(ContainElement("bytes=4-5"))
})
})
var _ = Describe("AppStore (GetVersionMetadata)", func() {
var (
ctrl *gomock.Controller
mockMachine *machine.MockMachine
mockDownloadClient *http.MockClient[downloadResult]
as AppStore
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockMachine = machine.NewMockMachine(ctrl)
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
as = &appstore{
machine: mockMachine,
downloadClient: mockDownloadClient,
httpClient: http.NewClient[interface{}](http.Args{}),
}
})
AfterEach(func() {
ctrl.Finish()
})
When("fails to get MAC address", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("", errors.New("mac error"))
})
It("returns error", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to get mac address"))
})
})
When("request fails", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{}, errors.New("request error"))
})
It("returns error", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to send http request"))
})
})
When("request uses a custom pod", func() {
const (
testPod = "42"
testGUID = "001122334455"
)
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
expectedURL := "https://p" + testPod + "-" + PrivateAppStoreAPIDomain + PrivateAppStoreAPIPathDownload + "?guid=" + testGUID
Expect(req.URL).To(Equal(expectedURL))
}).
Return(http.Result[downloadResult]{}, errors.New("request error"))
})
It("sends the request to the pod-specific host", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{
Account: Account{
Pod: testPod,
},
})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to send http request"))
})
})
When("password token is expired", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
FailureType: FailureTypePasswordTokenExpired,
},
}, nil)
})
It("returns error", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
Expect(err).To(Equal(ErrPasswordTokenExpired))
})
})
When("Sign In to the iTunes Store", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
FailureType: FailureTypeSignInRequired,
},
}, nil)
})
It("returns error", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
Expect(err).To(Equal(ErrPasswordTokenExpired))
})
})
When("license is missing", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
FailureType: FailureTypeLicenseNotFound,
},
}, nil)
})
It("returns error", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
Expect(err).To(Equal(ErrLicenseRequired))
})
})
When("store API returns error", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
})
When("response contains customer message", func() {
BeforeEach(func() {
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
FailureType: "SOME_ERROR",
CustomerMessage: "Customer error message",
},
}, nil)
})
It("returns customer message as error", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Customer error message"))
})
})
When("response does not contain customer message", func() {
BeforeEach(func() {
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
FailureType: "SOME_ERROR",
},
}, nil)
})
It("returns generic error", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("SOME_ERROR"))
})
})
})
When("store API returns no items", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
Items: []downloadItemResult{},
},
}, nil)
})
It("returns error", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("invalid response"))
})
})
When("fails to parse release date", func() {
var server *httptest.Server
BeforeEach(func() {
ipa := testIPA("1.0.0", "invalid-date", time.Date(2024, 3, 19, 12, 0, 0, 0, time.UTC))
server, _, _ = testIPAServer(ipa)
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
Items: []downloadItemResult{
{
URL: server.URL,
Metadata: map[string]interface{}{
"bundleShortVersionString": "1.0.0",
"releaseDate": "invalid-date",
},
},
},
},
}, nil)
})
AfterEach(func() {
server.Close()
})
It("returns error", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to parse release date"))
})
})
When("IPA metadata cannot be read", func() {
var server *httptest.Server
BeforeEach(func() {
server = httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, r *gohttp.Request) {
w.WriteHeader(gohttp.StatusOK)
}))
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
Items: []downloadItemResult{
{
URL: server.URL,
Metadata: map[string]interface{}{
"bundleShortVersionString": "1.0.0",
"releaseDate": "2024-03-20T12:00:00Z",
},
},
},
},
}, nil)
})
AfterEach(func() {
server.Close()
})
It("returns error instead of falling back to API metadata", func() {
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to read version metadata"))
})
})
When("successfully gets version metadata", func() {
var (
server *httptest.Server
ipa []byte
servedBytes *int64
wholeGetCount *int64
releaseDate time.Time
displayVersion string
)
BeforeEach(func() {
releaseDate = time.Date(2024, 4, 2, 12, 0, 0, 0, time.UTC)
displayVersion = "2.0.0"
ipa = testIPA(displayVersion, fmt.Sprintf(" \n%s\t", releaseDate.Format(time.RFC3339)), time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC))
server, servedBytes, wholeGetCount = testIPAServer(ipa)
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
Items: []downloadItemResult{
{
URL: server.URL,
Metadata: map[string]interface{}{
"releaseDate": "2020-01-01T00:00:00Z",
"bundleShortVersionString": "1.0.0",
},
},
},
},
}, nil)
})
AfterEach(func() {
server.Close()
})
It("returns version metadata", func() {
output, err := as.GetVersionMetadata(GetVersionMetadataInput{
Account: Account{
DirectoryServicesID: "test-dsid",
},
App: App{
ID: 1234567890,
},
VersionID: "test-version",
})
Expect(err).NotTo(HaveOccurred())
Expect(output.DisplayVersion).To(Equal(displayVersion))
Expect(output.ReleaseDate).To(Equal(releaseDate))
Expect(atomic.LoadInt64(wholeGetCount)).To(BeZero())
Expect(atomic.LoadInt64(servedBytes)).To(BeNumerically("<", int64(len(ipa)/2)))
})
})
})
-36
View File
@@ -1,36 +0,0 @@
package appstore
import (
"encoding/json"
"github.com/pkg/errors"
)
func (a *appstore) Info() error {
acc, err := a.account()
if err != nil {
return errors.Wrap(err, ErrGetAccount.Error())
}
a.logger.Log().
Str("name", acc.Name).
Str("email", acc.Email).
Bool("success", true).
Send()
return nil
}
func (a *appstore) account() (Account, error) {
data, err := a.keychain.Get("account")
if err != nil {
return Account{}, errors.Wrap(err, ErrGetKeychainItem.Error())
}
var acc Account
err = json.Unmarshal(data, &acc)
if err != nil {
return Account{}, errors.Wrap(err, ErrUnmarshal.Error())
}
return acc, err
}
+104
View File
@@ -0,0 +1,104 @@
package appstore
import (
"errors"
"fmt"
"strings"
"github.com/majd/ipatool/v2/pkg/http"
)
type ListVersionsInput struct {
Account Account
App App
}
type ListVersionsOutput struct {
ExternalVersionIdentifiers []string
LatestExternalVersionID string
}
func (t *appstore) ListVersions(input ListVersionsInput) (ListVersionsOutput, error) {
macAddr, err := t.machine.MacAddress()
if err != nil {
return ListVersionsOutput{}, fmt.Errorf("failed to get mac address: %w", err)
}
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
req := t.listVersionsRequest(input.Account, input.App, guid)
res, err := t.downloadClient.Send(req)
if err != nil {
return ListVersionsOutput{}, fmt.Errorf("failed to send http request: %w", err)
}
if res.Data.FailureType == FailureTypePasswordTokenExpired || res.Data.FailureType == FailureTypeSignInRequired {
return ListVersionsOutput{}, ErrPasswordTokenExpired
}
if res.Data.FailureType == FailureTypeLicenseNotFound {
return ListVersionsOutput{}, ErrLicenseRequired
}
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
}
if res.Data.FailureType != "" {
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.FailureType), res)
}
if len(res.Data.Items) == 0 {
return ListVersionsOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
}
item := res.Data.Items[0]
rawIdentifiers, ok := item.Metadata["softwareVersionExternalIdentifiers"].([]interface{})
if !ok {
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("failed to get version identifiers from item metadata"), item.Metadata)
}
externalVersionIdentifiers := make([]string, len(rawIdentifiers))
for i, val := range rawIdentifiers {
externalVersionIdentifiers[i] = fmt.Sprintf("%v", val)
}
latestExternalVersionID := item.Metadata["softwareVersionExternalIdentifier"]
if latestExternalVersionID == nil {
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("failed to get latest version from item metadata"), item.Metadata)
}
return ListVersionsOutput{
ExternalVersionIdentifiers: externalVersionIdentifiers,
LatestExternalVersionID: fmt.Sprintf("%v", latestExternalVersionID),
}, nil
}
func (t *appstore) listVersionsRequest(acc Account, app App, guid string) http.Request {
payload := map[string]interface{}{
"creditDisplay": "",
"guid": guid,
"salableAdamId": app.ID,
}
podPrefix := ""
if acc.Pod != "" {
podPrefix = "p" + acc.Pod + "-"
}
return http.Request{
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
Method: http.MethodPOST,
ResponseFormat: http.ResponseFormatXML,
Headers: map[string]string{
"Content-Type": "application/x-apple-plist",
"iCloud-DSID": acc.DirectoryServicesID,
"X-Dsid": acc.DirectoryServicesID,
},
Payload: &http.XMLPayload{
Content: payload,
},
}
}
+315
View File
@@ -0,0 +1,315 @@
package appstore
import (
"errors"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/util/machine"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
)
var _ = Describe("AppStore (ListVersions)", func() {
var (
ctrl *gomock.Controller
mockDownloadClient *http.MockClient[downloadResult]
mockMachine *machine.MockMachine
as AppStore
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
mockMachine = machine.NewMockMachine(ctrl)
as = &appstore{
downloadClient: mockDownloadClient,
machine: mockMachine,
}
})
AfterEach(func() {
ctrl.Finish()
})
When("fails to get MAC address", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("", errors.New(""))
})
It("returns error", func() {
_, err := as.ListVersions(ListVersionsInput{})
Expect(err).To(HaveOccurred())
})
})
When("request fails", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{}, errors.New(""))
})
It("returns error", func() {
_, err := as.ListVersions(ListVersionsInput{})
Expect(err).To(HaveOccurred())
})
})
When("request uses a custom pod", func() {
const (
testPod = "42"
testGUID = "001122334455"
)
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
expectedURL := "https://p" + testPod + "-" + PrivateAppStoreAPIDomain + PrivateAppStoreAPIPathDownload + "?guid=" + testGUID
Expect(req.URL).To(Equal(expectedURL))
}).
Return(http.Result[downloadResult]{}, errors.New(""))
})
It("sends the request to the pod-specific host", func() {
_, err := as.ListVersions(ListVersionsInput{
Account: Account{
Pod: testPod,
},
})
Expect(err).To(HaveOccurred())
})
})
When("password token is expired", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
FailureType: FailureTypePasswordTokenExpired,
},
}, nil)
})
It("returns error", func() {
_, err := as.ListVersions(ListVersionsInput{})
Expect(err).To(HaveOccurred())
})
})
When("Sign In to the iTunes Store", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
FailureType: FailureTypeSignInRequired,
},
}, nil)
})
It("returns error", func() {
_, err := as.ListVersions(ListVersionsInput{})
Expect(err).To(HaveOccurred())
})
})
When("license is required", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
FailureType: FailureTypeLicenseNotFound,
},
}, nil)
})
It("returns error", func() {
_, err := as.ListVersions(ListVersionsInput{})
Expect(err).To(HaveOccurred())
})
})
When("store API returns error with customer message", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
FailureType: "test-failure",
CustomerMessage: "test error message",
},
}, nil)
})
It("returns error with customer message", func() {
_, err := as.ListVersions(ListVersionsInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("test error message"))
})
})
When("store API returns error without customer message", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
FailureType: "test-failure",
},
}, nil)
})
It("returns error with failure type", func() {
_, err := as.ListVersions(ListVersionsInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("test-failure"))
})
})
When("store API returns no items", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
Items: []downloadItemResult{},
},
}, nil)
})
It("returns error", func() {
_, err := as.ListVersions(ListVersionsInput{})
Expect(err).To(HaveOccurred())
})
})
When("version identifiers not found in metadata", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
Items: []downloadItemResult{
{
Metadata: map[string]interface{}{
"someOtherKey": "someValue",
},
},
},
},
}, nil)
})
It("returns error", func() {
_, err := as.ListVersions(ListVersionsInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to get version identifiers from item metadata"))
})
})
When("latest version not found in metadata", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
Items: []downloadItemResult{
{
Metadata: map[string]interface{}{
"softwareVersionExternalIdentifiers": []interface{}{"12345678", "87654321"},
},
},
},
},
}, nil)
})
It("returns error", func() {
_, err := as.ListVersions(ListVersionsInput{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to get latest version from item metadata"))
})
})
When("successfully lists versions", func() {
const (
testVersion1 = "12345678"
testVersion2 = "87654321"
testLatest = "87654321"
)
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockDownloadClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[downloadResult]{
Data: downloadResult{
Items: []downloadItemResult{
{
Metadata: map[string]interface{}{
"softwareVersionExternalIdentifiers": []interface{}{testVersion1, testVersion2},
"softwareVersionExternalIdentifier": testLatest,
},
},
},
},
}, nil)
})
It("returns versions", func() {
out, err := as.ListVersions(ListVersionsInput{})
Expect(err).ToNot(HaveOccurred())
Expect(out.ExternalVersionIdentifiers).To(Equal([]string{testVersion1, testVersion2}))
Expect(out.LatestExternalVersionID).To(Equal(testLatest))
})
})
})
+125 -125
View File
@@ -1,116 +1,104 @@
package appstore
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"github.com/majd/ipatool/pkg/http"
"github.com/majd/ipatool/pkg/util"
"github.com/pkg/errors"
"os"
gohttp "net/http"
"strconv"
"strings"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/util"
)
type LoginAddressResult struct {
var (
ErrAuthCodeRequired = errors.New("auth code is required")
)
type LoginInput struct {
Email string
Password string
AuthCode string
Endpoint string
}
type LoginOutput struct {
Account Account
}
func (t *appstore) Login(input LoginInput) (LoginOutput, error) {
macAddr, err := t.machine.MacAddress()
if err != nil {
return LoginOutput{}, fmt.Errorf("failed to get mac address: %w", err)
}
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
acc, err := t.login(input.Email, input.Password, input.AuthCode, guid, input.Endpoint)
if err != nil {
return LoginOutput{}, err
}
return LoginOutput{
Account: acc,
}, nil
}
type loginAddressResult struct {
FirstName string `plist:"firstName,omitempty"`
LastName string `plist:"lastName,omitempty"`
}
type LoginAccountResult struct {
type loginAccountResult struct {
Email string `plist:"appleId,omitempty"`
Address LoginAddressResult `plist:"address,omitempty"`
Address loginAddressResult `plist:"address,omitempty"`
}
type LoginResult struct {
type loginResult struct {
FailureType string `plist:"failureType,omitempty"`
CustomerMessage string `plist:"customerMessage,omitempty"`
Account LoginAccountResult `plist:"accountInfo,omitempty"`
Account loginAccountResult `plist:"accountInfo,omitempty"`
DirectoryServicesID string `plist:"dsPersonId,omitempty"`
PasswordToken string `plist:"passwordToken,omitempty"`
}
func (a *appstore) Login(email, password, authCode string) error {
if password == "" && !a.interactive {
return ErrPasswordRequired
}
func (t *appstore) login(email, password, authCode, guid, endpoint string) (Account, error) {
redirect := ""
if password == "" && a.interactive {
a.logger.Log().Msg("enter password:")
var (
err error
res http.Result[loginResult]
)
retry := true
for attempt := 1; retry && attempt <= 4; attempt++ {
request := t.loginRequest(email, password, authCode, guid, endpoint, attempt)
request.URL, _ = util.IfEmpty(redirect, request.URL), ""
res, err = t.loginClient.Send(request)
var err error
password, err = a.promptForPassword()
if err != nil {
return errors.Wrap(err, ErrGetData.Error())
return Account{}, fmt.Errorf("request failed: %w", err)
}
if retry, redirect, err = t.parseLoginResponse(&res, attempt, authCode); err != nil {
return Account{}, err
}
}
macAddr, err := a.machine.MacAddress()
if retry {
return Account{}, NewErrorWithMetadata(errors.New("too many attempts"), res)
}
sf, err := res.GetHeader(HTTPHeaderStoreFront)
if err != nil {
return errors.Wrap(err, ErrGetMAC.Error())
return Account{}, NewErrorWithMetadata(fmt.Errorf("failed to get storefront header: %w", err), res)
}
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
a.logger.Verbose().Str("mac", macAddr).Str("guid", guid).Send()
acc, err := a.login(email, password, authCode, guid, 0, false)
if err != nil {
return errors.Wrap(err, ErrLogin.Error())
}
a.logger.Log().
Str("name", acc.Name).
Str("email", acc.Email).
Bool("success", true).
Send()
return nil
}
func (a *appstore) login(email, password, authCode, guid string, attempt int, failOnAuthCodeRequirement bool) (Account, error) {
a.logger.Verbose().
Int("attempt", attempt).
Str("password", password).
Str("email", email).
Str("authCode", util.IfEmpty(authCode, "<nil>")).
Msg("sending login request")
request := a.loginRequest(email, password, authCode, guid)
res, err := a.loginClient.Send(request)
if err != nil {
return Account{}, errors.Wrap(err, ErrRequest.Error())
}
if attempt == 0 && res.Data.FailureType == FailureTypeInvalidCredentials {
return a.login(email, password, authCode, guid, 1, failOnAuthCodeRequirement)
}
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
a.logger.Verbose().Interface("response", res).Send()
return Account{}, errors.New(res.Data.CustomerMessage)
}
if res.Data.FailureType != "" {
a.logger.Verbose().Interface("response", res).Send()
return Account{}, ErrGeneric
}
if res.Data.FailureType == "" && authCode == "" && res.Data.CustomerMessage == CustomerMessageBadLogin {
if failOnAuthCodeRequirement {
return Account{}, ErrAuthCodeRequired
}
if a.interactive {
a.logger.Log().Msg("enter 2FA code:")
authCode, err = a.promptForAuthCode()
if err != nil {
return Account{}, errors.Wrap(err, ErrGetData.Error())
}
return a.login(email, password, authCode, guid, 0, failOnAuthCodeRequirement)
} else {
a.logger.Log().Msg("2FA code is required; run the command again and supply a code using the `--auth-code` flag")
return Account{}, nil
}
pod, err := res.GetHeader(HTTPHeaderPod)
if err != nil && !errors.Is(err, http.ErrHeaderNotFound) {
return Account{}, NewErrorWithMetadata(fmt.Errorf("failed to get pod header: %w", err), res)
}
addr := res.Data.Account.Address
@@ -119,78 +107,90 @@ func (a *appstore) login(email, password, authCode, guid string, attempt int, fa
Email: res.Data.Account.Email,
PasswordToken: res.Data.PasswordToken,
DirectoryServicesID: res.Data.DirectoryServicesID,
StoreFront: res.Headers[HTTPHeaderStoreFront],
StoreFront: sf,
Password: password,
Pod: pod,
}
data, err := json.Marshal(acc)
if err != nil {
return Account{}, errors.Wrap(err, ErrMarshal.Error())
return Account{}, fmt.Errorf("failed to marshal json: %w", err)
}
err = a.keychain.Set("account", data)
err = t.keychain.Set("account", data)
if err != nil {
return Account{}, errors.Wrap(err, ErrSetKeychainItem.Error())
return Account{}, fmt.Errorf("failed to save account in keychain: %w", err)
}
return acc, nil
}
func (a *appstore) loginRequest(email, password, authCode, guid string) http.Request {
attempt := "4"
if authCode != "" {
attempt = "2"
func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int, authCode string) (bool, string, error) {
var (
retry bool
redirect string
err error
)
if res.StatusCode == gohttp.StatusFound {
if redirect, err = res.GetHeader("location"); err != nil {
err = fmt.Errorf("failed to retrieve redirect location: %w", err)
} else {
retry = true
}
} else if attempt == 1 && res.Data.FailureType == FailureTypeInvalidCredentials {
retry = true
} else if res.Data.FailureType == "" && authCode == "" && res.Data.CustomerMessage == CustomerMessageBadLogin {
err = ErrAuthCodeRequired
} else if res.Data.FailureType == "" && res.Data.CustomerMessage == CustomerMessageAccountDisabled {
err = NewErrorWithMetadata(errors.New("account is disabled"), res)
} else if res.Data.FailureType != "" {
if res.Data.CustomerMessage != "" {
err = NewErrorWithMetadata(errors.New(res.Data.CustomerMessage), res)
} else {
err = NewErrorWithMetadata(errors.New("something went wrong"), res)
}
} else if res.StatusCode != gohttp.StatusOK || res.Data.PasswordToken == "" || res.Data.DirectoryServicesID == "" {
err = NewErrorWithMetadata(errors.New("something went wrong"), res)
}
return retry, redirect, err
}
func (t *appstore) loginRequest(email, password, authCode, guid, endpoint string, attempt int) http.Request {
return http.Request{
Method: http.MethodPOST,
URL: a.authDomain(authCode, guid),
URL: authenticateURL(endpoint),
ResponseFormat: http.ResponseFormatXML,
Headers: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
},
Payload: &http.XMLPayload{
Content: map[string]interface{}{
"appleId": email,
"attempt": attempt,
"createSession": "true",
"guid": guid,
"password": fmt.Sprintf("%s%s", password, authCode),
"rmp": "0",
"why": "signIn",
"appleId": email,
"attempt": strconv.Itoa(attempt),
"guid": guid,
"password": fmt.Sprintf("%s%s", password, strings.ReplaceAll(authCode, " ", "")),
"rmp": "0",
"why": "signIn",
},
},
}
}
func (a *appstore) promptForAuthCode() (string, error) {
reader := bufio.NewReader(a.ioReader)
authCode, err := reader.ReadString('\n')
if err != nil {
return "", errors.Wrap(err, ErrGetData.Error())
// authenticateURL normalizes the bag-provided authentication endpoint. Apple's
// current endpoint (https://auth.itunes.apple.com/auth/v1/native/fast) only
// responds correctly when the path has a trailing slash; without it the request
// is redirected/dropped and the login silently fails. The legacy MZFinance
// authenticate endpoint is left untouched.
func authenticateURL(endpoint string) string {
if endpoint == "" {
return endpoint
}
authCode = strings.Trim(authCode, "\n")
authCode = strings.Trim(authCode, "\r")
return authCode, nil
}
func (*appstore) authDomain(authCode, guid string) string {
prefix := PriavteAppStoreAPIDomainPrefixWithoutAuthCode
if authCode != "" {
prefix = PriavteAppStoreAPIDomainPrefixWithAuthCode
if strings.Contains(endpoint, "/native/") && !strings.HasSuffix(endpoint, "/") {
return endpoint + "/"
}
return fmt.Sprintf(
"https://%s-%s%s?guid=%s", prefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathAuthenticate, guid)
}
func (a *appstore) promptForPassword() (string, error) {
password, err := a.machine.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return "", errors.Wrap(err, ErrGetData.Error())
}
return string(password), nil
return endpoint
}
+146 -209
View File
@@ -2,124 +2,67 @@ package appstore
import (
"encoding/json"
"errors"
"fmt"
"github.com/golang/mock/gomock"
"github.com/majd/ipatool/pkg/http"
"github.com/majd/ipatool/pkg/keychain"
"github.com/majd/ipatool/pkg/log"
"github.com/majd/ipatool/pkg/util"
"strings"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/keychain"
"github.com/majd/ipatool/v2/pkg/util/machine"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"os"
"strings"
"syscall"
"go.uber.org/mock/gomock"
)
var _ = Describe("AppStore (Login)", func() {
const (
testPassword = "test-password"
testPassword = "test-password"
testEmail = "test-email"
testFirstName = "test-first-name"
testLastName = "test-last-name"
testPod = "42"
)
var (
ctrl *gomock.Controller
as AppStore
mockKeychain *keychain.MockKeychain
mockClient *http.MockClient[LoginResult]
mockMachine *util.MockMachine
mockLogger *log.MockLogger
testErr = errors.New("test")
mockClient *http.MockClient[loginResult]
mockMachine *machine.MockMachine
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockKeychain = keychain.NewMockKeychain(ctrl)
mockClient = http.NewMockClient[LoginResult](ctrl)
mockMachine = util.NewMockMachine(ctrl)
mockLogger = log.NewMockLogger(ctrl)
mockClient = http.NewMockClient[loginResult](ctrl)
mockMachine = machine.NewMockMachine(ctrl)
as = &appstore{
keychain: mockKeychain,
loginClient: mockClient,
ioReader: os.Stdin,
machine: mockMachine,
logger: mockLogger,
interactive: true,
}
mockLogger.EXPECT().
Verbose().
Return(nil).
MaxTimes(4)
})
AfterEach(func() {
ctrl.Finish()
})
When("not running in interactive mode and password is not supplied", func() {
BeforeEach(func() {
as.(*appstore).interactive = false
})
It("returns error", func() {
err := as.Login("", "", "")
Expect(err).To(MatchError(ContainSubstring("password is required")))
})
})
When("prompts user for password", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Log().
Return(nil)
})
When("user enters password", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("", errors.New("success"))
mockMachine.EXPECT().
ReadPassword(syscall.Stdin).
Return([]byte(testPassword), nil)
})
It("succeeds", func() {
err := as.Login("", "", "")
Expect(err).To(MatchError(ContainSubstring("success")))
})
})
When("fails to read password from stdin", func() {
BeforeEach(func() {
mockMachine.EXPECT().
ReadPassword(syscall.Stdin).
Return(nil, testErr)
})
It("returns error", func() {
err := as.Login("", "", "")
Expect(err).To(MatchError(ContainSubstring(ErrGetData.Error())))
})
})
})
When("fails to read Machine's MAC address", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("", testErr)
Return("", errors.New(""))
})
It("returns error", func() {
err := as.Login("", testPassword, "")
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
Expect(err).To(MatchError(ContainSubstring(ErrGetMAC.Error())))
_, err := as.Login(LoginInput{
Password: testPassword,
})
Expect(err).To(HaveOccurred())
})
})
When("sucessfully reads Machine's MAC address", func() {
When("successfully reads machine's MAC address", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
@@ -130,33 +73,53 @@ var _ = Describe("AppStore (Login)", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[LoginResult]{}, testErr)
Return(http.Result[loginResult]{}, errors.New(""))
})
It("returns wrapped error", func() {
err := as.Login("", testPassword, "")
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
_, err := as.Login(LoginInput{
Password: testPassword,
})
Expect(err).To(HaveOccurred())
})
})
When("store API returns invalid first response", func() {
const testCustomerMessage = "test"
When("normalizes the native authentication endpoint", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[LoginResult]{
Data: LoginResult{
FailureType: FailureTypeInvalidCredentials,
CustomerMessage: "test",
Do(func(req http.Request) {
Expect(req.URL).To(Equal("https://auth.itunes.apple.com/auth/v1/native/fast/"))
}).
Return(http.Result[loginResult]{}, errors.New("stop"))
})
It("appends the trailing slash", func() {
_, err := as.Login(LoginInput{
Password: testPassword,
Endpoint: "https://auth.itunes.apple.com/auth/v1/native/fast",
})
Expect(err).To(HaveOccurred())
})
})
When("store API returns invalid credentials on first attempt", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[loginResult]{
Data: loginResult{
FailureType: FailureTypeInvalidCredentials,
},
}, nil).
Times(2)
})
It("retries one more time", func() {
err := as.Login("", testPassword, "")
Expect(err).To(MatchError(ContainSubstring(testCustomerMessage)))
It("retries once then returns an error", func() {
_, err := as.Login(LoginInput{
Password: testPassword,
})
Expect(err).To(HaveOccurred())
})
})
@@ -164,119 +127,120 @@ var _ = Describe("AppStore (Login)", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[LoginResult]{
Data: LoginResult{
Return(http.Result[loginResult]{
Data: loginResult{
FailureType: "random-error",
},
}, nil)
})
It("returns error", func() {
err := as.Login("", testPassword, "")
Expect(err).To(MatchError(ContainSubstring(ErrGeneric.Error())))
_, err := as.Login(LoginInput{
Password: testPassword,
})
Expect(err).To(HaveOccurred())
})
})
When("store API indicates account is disabled", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[loginResult]{
Data: loginResult{
CustomerMessage: CustomerMessageAccountDisabled,
},
}, nil)
})
It("returns account disabled error", func() {
_, err := as.Login(LoginInput{
Password: testPassword,
})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("account is disabled"))
})
})
When("store API requires 2FA code", func() {
When("not running in interactive mode", func() {
BeforeEach(func() {
as.(*appstore).interactive = false
mockLogger.EXPECT().
Log().
Return(nil).
Times(2)
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[LoginResult]{
Data: LoginResult{
FailureType: "",
CustomerMessage: CustomerMessageBadLogin,
},
}, nil)
})
It("prints message", func() {
err := as.Login("", testPassword, "")
Expect(err).ToNot(HaveOccurred())
})
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[loginResult]{
Data: loginResult{
FailureType: "",
CustomerMessage: CustomerMessageBadLogin,
},
}, nil)
})
When("user enters 2FA code", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Log().
Return(nil).
Times(2)
mockKeychain.EXPECT().
Set("account", gomock.Any()).
Return(nil)
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[LoginResult]{
Data: LoginResult{
FailureType: "",
CustomerMessage: CustomerMessageBadLogin,
},
}, nil).
Times(2)
as.(*appstore).ioReader = strings.NewReader("123456\n")
It("returns ErrAuthCodeRequired error", func() {
_, err := as.Login(LoginInput{
Password: testPassword,
})
Expect(err).To(Equal(ErrAuthCodeRequired))
})
})
It("successfully authenticates", func() {
err := as.Login("", testPassword, "")
Expect(err).ToNot(HaveOccurred())
})
When("store API redirects", func() {
const (
testRedirectLocation = "https://test-redirect-url.com"
)
BeforeEach(func() {
firstCall := mockClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
x := req.Payload.(*http.XMLPayload)
Expect(x.Content).To(HaveKeyWithValue("attempt", "1"))
}).
Return(http.Result[loginResult]{
StatusCode: 302,
Headers: map[string]string{"Location": testRedirectLocation},
}, nil)
secondCall := mockClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
Expect(req.URL).To(Equal(testRedirectLocation))
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
x := req.Payload.(*http.XMLPayload)
Expect(x.Content).To(HaveKeyWithValue("attempt", "2"))
}).
Return(http.Result[loginResult]{}, errors.New("test complete"))
gomock.InOrder(firstCall, secondCall)
})
When("prompts user for 2FA code", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Log().
Return(nil)
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[LoginResult]{
Data: LoginResult{
FailureType: "",
CustomerMessage: CustomerMessageBadLogin,
},
}, nil)
as.(*appstore).ioReader = strings.NewReader("123456")
})
It("fails to read 2FA code from stdin", func() {
err := as.Login("", testPassword, "")
Expect(err).To(MatchError(ContainSubstring(ErrGetData.Error())))
It("follows the redirect and increments attempt", func() {
_, err := as.Login(LoginInput{
Password: testPassword,
})
Expect(err).To(MatchError("request failed: test complete"))
})
})
When("store API returns valid response", func() {
const (
testEmail = "test-email"
testFirstName = "test-first-name"
testLastName = "test-last-name"
testPasswordToken = "test-password-token"
testDirectoryServicesID = "directory-services-id"
testStoreFront = "test-storefront"
)
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[LoginResult]{
Data: LoginResult{
Return(http.Result[loginResult]{
StatusCode: 200,
Headers: map[string]string{
HTTPHeaderStoreFront: testStoreFront,
HTTPHeaderPod: testPod,
},
Data: loginResult{
PasswordToken: testPasswordToken,
DirectoryServicesID: testDirectoryServicesID,
Account: LoginAccountResult{
Account: loginAccountResult{
Email: testEmail,
Address: LoginAddressResult{
Address: loginAddressResult{
FirstName: testFirstName,
LastName: testLastName,
},
@@ -285,7 +249,7 @@ var _ = Describe("AppStore (Login)", func() {
}, nil)
})
When("fails to save account in keychain", func() {
When("successfully saves account in keychain", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Set("account", gomock.Any()).
@@ -296,51 +260,24 @@ var _ = Describe("AppStore (Login)", func() {
PasswordToken: testPasswordToken,
Password: testPassword,
DirectoryServicesID: testDirectoryServicesID,
StoreFront: testStoreFront,
Pod: testPod,
}
var got Account
err := json.Unmarshal(data, &got)
Expect(err).ToNot(HaveOccurred())
Expect(got).To(Equal(want))
}).
Return(testErr)
})
It("returns error", func() {
err := as.Login("", testPassword, "")
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
Expect(err).To(MatchError(ContainSubstring(ErrSetKeychainItem.Error())))
})
})
When("sucessfully saves account in keychain", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Log().
Return(nil)
mockKeychain.EXPECT().
Set("account", gomock.Any()).
Do(func(key string, data []byte) {
want := Account{
Name: fmt.Sprintf("%s %s", testFirstName, testLastName),
Email: testEmail,
PasswordToken: testPasswordToken,
Password: testPassword,
DirectoryServicesID: testDirectoryServicesID,
}
var got Account
err := json.Unmarshal(data, &got)
Expect(err).ToNot(HaveOccurred())
Expect(json.Unmarshal(data, &got)).To(Succeed())
Expect(got).To(Equal(want))
}).
Return(nil)
})
It("returns nil", func() {
err := as.Login("", testPassword, "")
out, err := as.Login(LoginInput{
Password: testPassword,
})
Expect(err).ToNot(HaveOccurred())
Expect(out.Account.Email).To(Equal(testEmail))
Expect(out.Account.Name).To(Equal(strings.Join([]string{testFirstName, testLastName}, " ")))
})
})
})
+47 -20
View File
@@ -1,51 +1,78 @@
package appstore
import (
"errors"
"fmt"
"github.com/majd/ipatool/pkg/http"
"github.com/pkg/errors"
gohttp "net/http"
"net/url"
"github.com/majd/ipatool/v2/pkg/http"
)
func (a *appstore) lookup(bundleID, countryCode string) (App, error) {
if StoreFronts[countryCode] == "" {
return App{}, ErrInvalidCountryCode
}
type LookupInput struct {
Account Account
BundleID string
Platform Platform
}
request := a.lookupRequest(bundleID, countryCode)
type LookupOutput struct {
App App
}
res, err := a.searchClient.Send(request)
func (t *appstore) Lookup(input LookupInput) (LookupOutput, error) {
countryCode, err := countryCodeFromStoreFront(input.Account.StoreFront)
if err != nil {
return App{}, errors.Wrap(err, ErrRequest.Error())
return LookupOutput{}, fmt.Errorf("failed to resolve the country code: %w", err)
}
if res.StatusCode != 200 {
a.logger.Verbose().Interface("data", res.Data).Int("status", res.StatusCode).Send()
return App{}, ErrRequest
request, err := t.lookupRequest(input.BundleID, countryCode, input.Platform)
if err != nil {
return LookupOutput{}, fmt.Errorf("failed to create lookup request: %w", err)
}
res, err := t.searchClient.Send(request)
if err != nil {
return LookupOutput{}, fmt.Errorf("request failed: %w", err)
}
if res.StatusCode != gohttp.StatusOK {
return LookupOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
}
if len(res.Data.Results) == 0 {
return App{}, ErrAppNotFound
return LookupOutput{}, errors.New("app not found")
}
return res.Data.Results[0], nil
return LookupOutput{
App: res.Data.Results[0],
}, nil
}
func (a *appstore) lookupRequest(bundleID, countryCode string) http.Request {
func (t *appstore) lookupRequest(bundleID, countryCode string, platform Platform) (http.Request, error) {
url, err := t.lookupURL(bundleID, countryCode, platform)
if err != nil {
return http.Request{}, err
}
return http.Request{
URL: a.lookupURL(bundleID, countryCode),
URL: url,
Method: http.MethodGET,
ResponseFormat: http.ResponseFormatJSON,
}
}, nil
}
func (a *appstore) lookupURL(bundleID, countryCode string) string {
func (t *appstore) lookupURL(bundleID, countryCode string, platform Platform) (string, error) {
entity, err := platform.lookupEntity()
if err != nil {
return "", err
}
params := url.Values{}
params.Add("entity", "software,iPadSoftware")
params.Add("entity", entity)
params.Add("limit", "1")
params.Add("media", "software")
params.Add("bundleId", bundleID)
params.Add("country", countryCode)
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathLookup, params.Encode())
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathLookup, params.Encode()), nil
}
+94 -62
View File
@@ -1,31 +1,27 @@
package appstore
import (
"github.com/golang/mock/gomock"
"github.com/majd/ipatool/pkg/http"
"github.com/majd/ipatool/pkg/log"
"errors"
"net/url"
"github.com/majd/ipatool/v2/pkg/http"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"os"
"go.uber.org/mock/gomock"
)
var _ = Describe("AppStore (Lookup)", func() {
var (
ctrl *gomock.Controller
mockClient *http.MockClient[SearchResult]
mockLogger *log.MockLogger
as *appstore
mockClient *http.MockClient[searchResult]
as AppStore
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockClient = http.NewMockClient[SearchResult](ctrl)
mockLogger = log.NewMockLogger(ctrl)
mockClient = http.NewMockClient[searchResult](ctrl)
as = &appstore{
searchClient: mockClient,
ioReader: os.Stdin,
logger: mockLogger,
}
})
@@ -33,56 +29,14 @@ var _ = Describe("AppStore (Lookup)", func() {
ctrl.Finish()
})
When("country code is invalid", func() {
It("returns error", func() {
_, err := as.lookup("", "XYZ")
Expect(err).To(MatchError(ContainSubstring(ErrInvalidCountryCode.Error())))
})
})
When("request fails", func() {
var testErr = errors.New("test")
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{}, testErr)
})
It("returns error", func() {
_, err := as.lookup("", "US")
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
})
})
When("request returns bad status code", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Verbose().
Return(nil)
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 400,
}, nil)
})
It("returns error", func() {
_, err := as.lookup("", "US")
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
})
})
When("request is successful", func() {
When("does not find app", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
Return(http.Result[searchResult]{
StatusCode: 200,
Data: SearchResult{
Data: searchResult{
Count: 0,
Results: []App{},
},
@@ -90,8 +44,12 @@ var _ = Describe("AppStore (Lookup)", func() {
})
It("returns error", func() {
_, err := as.lookup("", "US")
Expect(err).To(MatchError(ContainSubstring(ErrAppNotFound.Error())))
_, err := as.Lookup(LookupInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
@@ -107,9 +65,9 @@ var _ = Describe("AppStore (Lookup)", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
Return(http.Result[searchResult]{
StatusCode: 200,
Data: SearchResult{
Data: searchResult{
Count: 1,
Results: []App{testApp},
},
@@ -117,10 +75,84 @@ var _ = Describe("AppStore (Lookup)", func() {
})
It("returns app", func() {
app, err := as.lookup("", "US")
app, err := as.Lookup(LookupInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).ToNot(HaveOccurred())
Expect(app).To(Equal(testApp))
Expect(app).To(Equal(LookupOutput{App: testApp}))
})
})
})
When("platform is AppleTV", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
parsedURL, err := url.Parse(req.URL)
Expect(err).ToNot(HaveOccurred())
Expect(parsedURL.Query().Get("entity")).To(Equal("tvSoftware"))
}).
Return(http.Result[searchResult]{}, errors.New("request error"))
})
It("uses the tvOS lookup entity", func() {
_, err := as.Lookup(LookupInput{
Account: Account{
StoreFront: "143441",
},
Platform: PlatformAppleTV,
})
Expect(err).To(HaveOccurred())
})
})
When("store front is invalid", func() {
It("returns error", func() {
_, err := as.Lookup(LookupInput{
Account: Account{
StoreFront: "xyz",
},
})
Expect(err).To(HaveOccurred())
})
})
When("request fails", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[searchResult]{}, errors.New(""))
})
It("returns error", func() {
_, err := as.Lookup(LookupInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
When("request returns bad status code", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[searchResult]{
StatusCode: 400,
}, nil)
})
It("returns error", func() {
_, err := as.Lookup(LookupInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
})
+318
View File
@@ -0,0 +1,318 @@
package appstore
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"math"
"net/http"
"strconv"
"strings"
"time"
apphttp "github.com/majd/ipatool/v2/pkg/http"
"howett.net/plist"
)
var infoPlistReleaseDateKeys = []string{
"releaseDate",
"ReleaseDate",
}
var infoPlistDisplayVersionKeys = []string{
"CFBundleShortVersionString",
"bundleShortVersionString",
}
type versionMetadata struct {
DisplayVersion string
ReleaseDate time.Time
}
type httpRangeReaderAt struct {
client apphttp.Client[interface{}]
url string
size int64
}
func newHTTPRangeReaderAt(client apphttp.Client[interface{}], url string) (*httpRangeReaderAt, int64, error) {
if url == "" {
return nil, 0, errors.New("url is empty")
}
size, err := remoteFileSize(client, url)
if err != nil {
return nil, 0, fmt.Errorf("failed to read remote file size: %w", err)
}
return &httpRangeReaderAt{
client: client,
url: url,
size: size,
}, size, nil
}
func remoteFileSize(client apphttp.Client[interface{}], url string) (int64, error) {
req, err := client.NewRequest("GET", url, nil)
if err != nil {
return 0, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Accept-Encoding", "identity")
req.Header.Set("Range", "bytes=0-0")
res, err := client.Do(req)
if err != nil {
return 0, fmt.Errorf("request failed: %w", err)
}
if res != nil && res.Body != nil {
defer res.Body.Close()
}
if res.StatusCode != http.StatusPartialContent {
return 0, fmt.Errorf("expected partial content response, got status %d", res.StatusCode)
}
size, err := parseContentRangeSize(res.Header.Get("Content-Range"))
if err != nil {
return 0, err
}
return size, nil
}
func parseContentRangeSize(header string) (int64, error) {
if header == "" {
return 0, errors.New("content range is empty")
}
slash := strings.LastIndex(header, "/")
if slash == -1 || slash == len(header)-1 {
return 0, fmt.Errorf("invalid content range: %s", header)
}
sizeText := header[slash+1:]
if sizeText == "*" {
return 0, fmt.Errorf("invalid content range size: %s", sizeText)
}
size, err := strconv.ParseInt(sizeText, 10, 64)
if err != nil {
return 0, fmt.Errorf("failed to parse content range size: %w", err)
}
return size, nil
}
func (r *httpRangeReaderAt) ReadAt(p []byte, off int64) (int, error) {
if len(p) == 0 {
return 0, nil
}
if off < 0 {
return 0, errors.New("offset is negative")
}
if off >= r.size {
return 0, io.EOF
}
requestEnd := off + int64(len(p)) - 1
rangeEnd := requestEnd
if rangeEnd >= r.size {
rangeEnd = r.size - 1
}
req, err := r.client.NewRequest("GET", r.url, nil)
if err != nil {
return 0, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Accept-Encoding", "identity")
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", off, rangeEnd))
res, err := r.client.Do(req)
if err != nil {
return 0, fmt.Errorf("request failed: %w", err)
}
if res != nil && res.Body != nil {
defer res.Body.Close()
}
if res.StatusCode != http.StatusPartialContent {
return 0, fmt.Errorf("expected partial content response, got status %d", res.StatusCode)
}
readLength := int(rangeEnd-off) + 1
n, err := io.ReadFull(res.Body, p[:readLength])
if err == io.ErrUnexpectedEOF || err == io.EOF {
return n, io.EOF
}
if err != nil {
return n, fmt.Errorf("failed to read response body: %w", err)
}
if requestEnd >= r.size {
return n, io.EOF
}
return n, nil
}
func (t *appstore) readVersionMetadataFromIPA(url string) (versionMetadata, error) {
reader, size, err := newHTTPRangeReaderAt(t.httpClient, url)
if err != nil {
return versionMetadata{}, err
}
zipReader, err := zip.NewReader(reader, size)
if err != nil {
return versionMetadata{}, fmt.Errorf("failed to open zip reader: %w", err)
}
for _, file := range zipReader.File {
if !isMainAppInfoPlist(file.Name) {
continue
}
metadata, err := readVersionMetadataFromInfoPlist(file)
if err != nil {
return versionMetadata{}, err
}
return metadata, nil
}
return versionMetadata{}, errors.New("could not find Info.plist")
}
func isMainAppInfoPlist(name string) bool {
parts := strings.Split(name, "/")
return len(parts) == 3 && parts[0] == "Payload" && strings.HasSuffix(parts[1], ".app") && parts[2] == "Info.plist"
}
func readVersionMetadataFromInfoPlist(file *zip.File) (versionMetadata, error) {
src, err := file.Open()
if err != nil {
return versionMetadata{}, fmt.Errorf("failed to open Info.plist: %w", err)
}
defer src.Close()
data := new(bytes.Buffer)
_, err = io.Copy(data, src)
if err != nil {
return versionMetadata{}, fmt.Errorf("failed to read Info.plist: %w", err)
}
metadata := map[string]interface{}{}
_, err = plist.Unmarshal(data.Bytes(), &metadata)
if err != nil {
return versionMetadata{}, fmt.Errorf("failed to unmarshal Info.plist: %w", err)
}
displayVersion, err := readDisplayVersionFromMetadata(metadata)
if err != nil {
return versionMetadata{}, err
}
releaseDate, err := readReleaseDateFromInfoPlist(metadata, file.Modified)
if err != nil {
return versionMetadata{}, err
}
return versionMetadata{
DisplayVersion: displayVersion,
ReleaseDate: releaseDate,
}, nil
}
func readDisplayVersionFromMetadata(metadata map[string]interface{}) (string, error) {
for _, key := range infoPlistDisplayVersionKeys {
value, ok := metadata[key]
if !ok {
continue
}
displayVersion := strings.TrimSpace(fmt.Sprintf("%v", value))
if displayVersion == "" || displayVersion == "<nil>" {
return "", fmt.Errorf("%s is empty", key)
}
return displayVersion, nil
}
return "", errors.New("info plist does not contain a display version")
}
func readReleaseDateFromInfoPlist(metadata map[string]interface{}, modified time.Time) (time.Time, error) {
for _, key := range infoPlistReleaseDateKeys {
value, ok := metadata[key]
if !ok {
continue
}
releaseDate, err := parseReleaseDateValue(value)
if err != nil {
return time.Time{}, fmt.Errorf("failed to parse release date: %w", err)
}
return releaseDate, nil
}
if modified.IsZero() {
return time.Time{}, errors.New("info plist does not contain a release date")
}
return modified.UTC(), nil
}
func parseReleaseDateValue(value interface{}) (time.Time, error) {
switch val := value.(type) {
case time.Time:
return val.UTC(), nil
case string:
return parseReleaseDateString(val)
case int:
return time.Unix(int64(val), 0).UTC(), nil
case int64:
return time.Unix(val, 0).UTC(), nil
case uint64:
if val > math.MaxInt64 {
return time.Time{}, fmt.Errorf("timestamp is too large: %d", val)
}
return time.Unix(int64(val), 0).UTC(), nil
case float64:
return time.Unix(int64(val), 0).UTC(), nil
default:
return time.Time{}, fmt.Errorf("unsupported release date type %T", value)
}
}
func parseReleaseDateString(value string) (time.Time, error) {
value = strings.TrimSpace(value)
for _, layout := range []string{
time.RFC3339,
time.RFC3339Nano,
"Monday, January 2, 2006",
"2006-01-02",
} {
parsed, err := time.Parse(layout, value)
if err == nil {
return parsed.UTC(), nil
}
}
return time.Time{}, fmt.Errorf("invalid release date: %s", value)
}
@@ -0,0 +1,142 @@
package appstore
import (
"encoding/json"
"errors"
"fmt"
gohttp "net/http"
"net/url"
"strconv"
"strings"
"github.com/majd/ipatool/v2/pkg/http"
)
type platformVersionLookupResult struct {
Results map[string]platformVersionLookupItem `json:"results,omitempty"`
}
type platformVersionLookupItem struct {
BundleID string `json:"bundleId,omitempty"`
Name string `json:"name,omitempty"`
Offers []platformVersionLookupOffer `json:"offers,omitempty"`
}
type platformVersionLookupOffer struct {
BuyParams string `json:"buyParams,omitempty"`
Version platformVersionLookupVersion `json:"version,omitempty"`
}
type platformVersionLookupVersion struct {
Display string `json:"display,omitempty"`
ExternalID platformVersionExternalID `json:"externalId,omitempty"`
}
type platformVersionExternalID string
func (id *platformVersionExternalID) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}
var stringID string
if err := json.Unmarshal(data, &stringID); err == nil {
*id = platformVersionExternalID(stringID)
return nil
}
var numberID json.Number
if err := json.Unmarshal(data, &numberID); err == nil {
*id = platformVersionExternalID(numberID.String())
return nil
}
return fmt.Errorf("invalid external version id %s", string(data))
}
func (t *appstore) lookupLatestExternalVersionID(acc Account, app App, platform Platform) (string, error) {
if app.ID == 0 {
return "", errors.New("app ID is required for platform version lookup")
}
countryCode, err := countryCodeFromStoreFront(acc.StoreFront)
if err != nil {
return "", fmt.Errorf("failed to resolve the country code: %w", err)
}
request, err := t.platformVersionLookupRequest(app.ID, countryCode, platform)
if err != nil {
return "", fmt.Errorf("failed to create platform version lookup request: %w", err)
}
res, err := t.platformClient.Send(request)
if err != nil {
return "", fmt.Errorf("platform version lookup request failed: %w", err)
}
if res.StatusCode != gohttp.StatusOK {
return "", NewErrorWithMetadata(errors.New("platform version lookup request failed"), res)
}
item, ok := res.Data.Results[strconv.FormatInt(app.ID, 10)]
if !ok {
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no app"), res)
}
if len(item.Offers) == 0 {
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no offers"), res)
}
offer := item.Offers[0]
externalVersionID := string(offer.Version.ExternalID)
if externalVersionID == "" {
externalVersionID, err = externalVersionIDFromBuyParams(offer.BuyParams)
if err != nil {
return "", fmt.Errorf("failed to parse buy params: %w", err)
}
}
if externalVersionID == "" {
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no external version id"), res)
}
return externalVersionID, nil
}
func (*appstore) platformVersionLookupRequest(appID int64, countryCode string, platform Platform) (http.Request, error) {
metadataPlatform, err := platform.metadataPlatform()
if err != nil {
return http.Request{}, err
}
params := url.Values{}
params.Add("version", "2")
params.Add("id", strconv.FormatInt(appID, 10))
params.Add("p", "mdm-lockup")
params.Add("caller", "MDM")
params.Add("platform", metadataPlatform)
params.Add("cc", strings.ToLower(countryCode))
params.Add("l", "en")
return http.Request{
URL: fmt.Sprintf("https://uclient-api.itunes.apple.com/WebObjects/MZStorePlatform.woa/wa/lookup?%s", params.Encode()),
Method: http.MethodGET,
ResponseFormat: http.ResponseFormatJSON,
}, nil
}
func externalVersionIDFromBuyParams(buyParams string) (string, error) {
if buyParams == "" {
return "", nil
}
values, err := url.ParseQuery(buyParams)
if err != nil {
return "", fmt.Errorf("failed to parse query: %w", err)
}
return values.Get("appExtVrsId"), nil
}
+69 -92
View File
@@ -1,77 +1,68 @@
package appstore
import (
"errors"
"fmt"
"github.com/majd/ipatool/pkg/http"
"github.com/pkg/errors"
gohttp "net/http"
"strings"
"github.com/majd/ipatool/v2/pkg/http"
)
type PurchaseResult struct {
var (
ErrPasswordTokenExpired = errors.New("password token is expired")
ErrLicenseAlreadyExists = errors.New("license already exists")
ErrSubscriptionRequired = errors.New("subscription required")
ErrTemporarilyUnavailable = errors.New("item is temporarily unavailable")
)
type PurchaseInput struct {
Account Account
App App
}
func (t *appstore) Purchase(input PurchaseInput) error {
macAddr, err := t.machine.MacAddress()
if err != nil {
return fmt.Errorf("failed to get mac address: %w", err)
}
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
if input.App.Price > 0 {
return errors.New("purchasing paid apps is not supported")
}
err = t.purchaseWithParams(input.Account, input.App, guid, PricingParameterAppStore)
if err != nil {
if err == ErrTemporarilyUnavailable {
err = t.purchaseWithParams(input.Account, input.App, guid, PricingParameterAppleArcade)
if err != nil {
return fmt.Errorf("failed to purchase item with param '%s': %w", PricingParameterAppleArcade, err)
}
return nil
}
return fmt.Errorf("failed to purchase item with param '%s': %w", PricingParameterAppStore, err)
}
return nil
}
type purchaseResult struct {
FailureType string `plist:"failureType,omitempty"`
CustomerMessage string `plist:"customerMessage,omitempty"`
JingleDocType string `plist:"jingleDocType,omitempty"`
Status int `plist:"status,omitempty"`
}
func (a *appstore) Purchase(bundleID string) error {
macAddr, err := a.machine.MacAddress()
func (t *appstore) purchaseWithParams(acc Account, app App, guid string, pricingParameters string) error {
req := t.purchaseRequest(acc, app, acc.StoreFront, guid, pricingParameters)
res, err := t.purchaseClient.Send(req)
if err != nil {
return errors.Wrap(err, ErrGetMAC.Error())
}
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
a.logger.Verbose().Str("mac", macAddr).Str("guid", guid).Send()
err = a.purchase(bundleID, guid, true)
if err != nil {
return errors.Wrap(err, ErrPurchase.Error())
}
a.logger.Log().Bool("success", true).Send()
return nil
}
func (a *appstore) purchase(bundleID string, guid string, attemptToRenewCredentials bool) error {
acc, err := a.account()
if err != nil {
return errors.Wrap(err, ErrGetAccount.Error())
}
countryCode, err := a.countryCodeFromStoreFront(acc.StoreFront)
if err != nil {
return errors.Wrap(err, ErrInvalidCountryCode.Error())
}
app, err := a.lookup(bundleID, countryCode)
if err != nil {
return errors.Wrap(err, ErrAppLookup.Error())
}
if app.Price > 0 {
return ErrPaidApp
}
err = a.purchaseWithParams(acc, app, bundleID, guid, attemptToRenewCredentials, PricingParameterAppStore)
if err != nil {
if err == ErrTemporarilyUnavailable {
err = a.purchaseWithParams(acc, app, bundleID, guid, attemptToRenewCredentials, PricingParameterAppleArcade)
if err != nil {
return errors.Wrapf(err, "failed to purchase item with param '%s'", PricingParameterAppleArcade)
}
}
return errors.Wrapf(err, "failed to purchase item with param '%s'", PricingParameterAppStore)
}
return nil
}
func (a *appstore) purchaseWithParams(acc Account, app App, bundleID string, guid string, attemptToRenewCredentials bool, pricingParameters string) error {
req := a.purchaseRequest(acc, app, acc.StoreFront, guid, pricingParameters)
res, err := a.purchaseClient.Send(req)
if err != nil {
return errors.Wrap(err, ErrRequest.Error())
return fmt.Errorf("request failed: %w", err)
}
if res.Data.FailureType == FailureTypeTemporarilyUnavailable {
@@ -79,61 +70,47 @@ func (a *appstore) purchaseWithParams(acc Account, app App, bundleID string, gui
}
if res.Data.CustomerMessage == CustomerMessageSubscriptionRequired {
a.logger.Verbose().Interface("response", res).Send()
return ErrSubscriptionRequired
}
if res.Data.FailureType == FailureTypePasswordTokenExpired {
if attemptToRenewCredentials {
a.logger.Verbose().Msg("retrieving new password token")
acc, err = a.login(acc.Email, acc.Password, "", guid, 0, true)
if err != nil {
return errors.Wrap(err, ErrPasswordTokenExpired.Error())
}
return a.purchaseWithParams(acc, app, bundleID, guid, false, pricingParameters)
}
if res.Data.FailureType == FailureTypePasswordTokenExpired ||
res.Data.FailureType == FailureTypeSignInRequired ||
res.Data.FailureType == FailureTypeDeviceVerificationFailed ||
res.Data.CustomerMessage == CustomerMessagePasswordChanged {
return ErrPasswordTokenExpired
}
if res.Data.FailureType == FailureTypeLicenseAlreadyExists {
return ErrLicenseAlreadyExists
}
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
a.logger.Verbose().Interface("response", res).Send()
return errors.New(res.Data.CustomerMessage)
return NewErrorWithMetadata(errors.New(res.Data.CustomerMessage), res)
}
if res.Data.FailureType != "" {
a.logger.Verbose().Interface("response", res).Send()
return ErrGeneric
return NewErrorWithMetadata(errors.New("something went wrong"), res)
}
if res.StatusCode == 500 {
return ErrLicenseExists
if res.StatusCode == gohttp.StatusInternalServerError {
return ErrLicenseAlreadyExists
}
if res.Data.JingleDocType != "purchaseSuccess" || res.Data.Status != 0 {
a.logger.Verbose().Interface("response", res).Send()
return errors.New(ErrPurchase.Error())
return NewErrorWithMetadata(errors.New("failed to purchase app"), res)
}
return nil
}
func (*appstore) countryCodeFromStoreFront(storeFront string) (string, error) {
for key, val := range StoreFronts {
parts := strings.Split(storeFront, "-")
if len(parts) >= 1 && parts[0] == val {
return key, nil
}
func (t *appstore) purchaseRequest(acc Account, app App, storeFront, guid string, pricingParameters string) http.Request {
podPrefix := ""
if acc.Pod != "" {
podPrefix = "p" + acc.Pod + "-"
}
return "", errors.New(ErrInvalidStoreFront.Error())
}
func (a *appstore) purchaseRequest(acc Account, app App, storeFront, guid string, pricingParameters string) http.Request {
return http.Request{
URL: fmt.Sprintf("https://%s%s", PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathPurchase),
URL: fmt.Sprintf("https://%s%s%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathPurchase),
Method: http.MethodPOST,
ResponseFormat: http.ResponseFormatXML,
Headers: map[string]string{
+227 -412
View File
@@ -1,42 +1,37 @@
package appstore
import (
"github.com/golang/mock/gomock"
"github.com/majd/ipatool/pkg/http"
"github.com/majd/ipatool/pkg/keychain"
"github.com/majd/ipatool/pkg/log"
"github.com/majd/ipatool/pkg/util"
"errors"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/keychain"
"github.com/majd/ipatool/v2/pkg/util/machine"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
)
var _ = Describe("AppStore (Purchase)", func() {
var (
ctrl *gomock.Controller
mockKeychain *keychain.MockKeychain
mockMachine *util.MockMachine
mockLogger *log.MockLogger
mockPurchaseClient *http.MockClient[PurchaseResult]
mockSearchClient *http.MockClient[SearchResult]
mockLoginClient *http.MockClient[LoginResult]
mockMachine *machine.MockMachine
mockPurchaseClient *http.MockClient[purchaseResult]
mockLoginClient *http.MockClient[loginResult]
as *appstore
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockPurchaseClient = http.NewMockClient[purchaseResult](ctrl)
mockLoginClient = http.NewMockClient[loginResult](ctrl)
mockKeychain = keychain.NewMockKeychain(ctrl)
mockPurchaseClient = http.NewMockClient[PurchaseResult](ctrl)
mockSearchClient = http.NewMockClient[SearchResult](ctrl)
mockLoginClient = http.NewMockClient[LoginResult](ctrl)
mockMachine = util.NewMockMachine(ctrl)
mockLogger = log.NewMockLogger(ctrl)
mockMachine = machine.NewMockMachine(ctrl)
as = &appstore{
keychain: mockKeychain,
purchaseClient: mockPurchaseClient,
searchClient: mockSearchClient,
loginClient: mockLoginClient,
machine: mockMachine,
logger: mockLogger,
}
})
@@ -48,435 +43,306 @@ var _ = Describe("AppStore (Purchase)", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("", ErrGetMAC)
Return("", errors.New(""))
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrGetMAC.Error())))
})
})
When("not logged in", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockLogger.EXPECT().
Verbose().
Return(nil)
mockKeychain.EXPECT().
Get("account").
Return(nil, ErrGetKeychainItem)
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrGetKeychainItem.Error())))
Expect(err).To(MatchError(ContainSubstring(ErrGetAccount.Error())))
})
})
When("country code is invalid", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Verbose().
Return(nil)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockKeychain.EXPECT().
Get("account").
Return([]byte("{}"), nil)
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrInvalidCountryCode.Error())))
})
})
When("app lookup fails", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockSearchClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{}, ErrRequest)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockLogger.EXPECT().
Verbose().
Return(nil)
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrAppLookup.Error())))
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
err := as.Purchase(PurchaseInput{})
Expect(err).To(HaveOccurred())
})
})
When("app is paid", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Verbose().
Return(nil)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockSearchClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 200,
Data: SearchResult{
Count: 1,
Results: []App{
{
Price: 0.99,
},
},
},
}, nil)
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrPaidApp.Error())))
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
App: App{
Price: 0.99,
},
})
Expect(err).To(HaveOccurred())
})
})
When("purchase request fails", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockSearchClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 200,
Data: SearchResult{
Count: 1,
Results: []App{
{
ID: 0,
BundleID: "",
Name: "",
Version: "",
Price: 0,
},
},
},
}, nil)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[PurchaseResult]{}, ErrRequest)
mockLogger.EXPECT().
Verbose().
Return(nil)
Return(http.Result[purchaseResult]{}, errors.New(""))
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
When("request uses a custom pod", func() {
const (
testPod = "42"
testGUID = "001122334455"
)
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:11:22:33:44:55", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
expectedURL := "https://p" + testPod + "-" + PrivateAppStoreAPIDomain + PrivateAppStoreAPIPathPurchase
Expect(req.URL).To(Equal(expectedURL))
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
payload := req.Payload.(*http.XMLPayload)
Expect(payload.Content["guid"]).To(Equal(testGUID))
}).
Return(http.Result[purchaseResult]{}, errors.New(""))
})
It("sends the request to the pod-specific host", func() {
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
Pod: testPod,
},
})
Expect(err).To(HaveOccurred())
})
})
When("password token is expired", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockSearchClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 200,
Data: SearchResult{
Count: 1,
Results: []App{
{
ID: 0,
BundleID: "",
Name: "",
Version: "",
Price: 0,
},
},
},
}, nil)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[PurchaseResult]{
Data: PurchaseResult{
Return(http.Result[purchaseResult]{
Data: purchaseResult{
FailureType: FailureTypePasswordTokenExpired,
},
}, nil)
mockLogger.EXPECT().
Verbose().
Return(nil)
})
When("renewing credentials fails", func() {
BeforeEach(func() {
mockLoginClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[LoginResult]{
Data: LoginResult{
FailureType: "",
CustomerMessage: CustomerMessageBadLogin,
},
}, nil)
mockLogger.EXPECT().
Verbose().
Return(nil).
Times(2)
It("returns error", func() {
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrPasswordTokenExpired.Error())))
})
When("Sign In to the iTunes Store", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[purchaseResult]{
Data: purchaseResult{
FailureType: FailureTypeSignInRequired,
},
}, nil)
})
When("renewing credentials succeeds", func() {
BeforeEach(func() {
mockLoginClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[LoginResult]{
Data: LoginResult{},
}, nil)
mockLogger.EXPECT().
Verbose().
Return(nil).
Times(2)
mockKeychain.EXPECT().
Set("account", gomock.Any()).
Return(nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[PurchaseResult]{
Data: PurchaseResult{
FailureType: FailureTypePasswordTokenExpired,
},
}, nil)
It("returns error", func() {
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
It("attempts to purchase app", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrPasswordTokenExpired.Error())))
When("customer message indicates password has changed", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[purchaseResult]{
Data: purchaseResult{
FailureType: "some_other_failure",
CustomerMessage: CustomerMessagePasswordChanged,
},
}, nil)
})
It("returns password token expired error", func() {
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(MatchError(ErrPasswordTokenExpired))
})
})
When("store API returns customer error message", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockSearchClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 200,
Data: SearchResult{
Count: 1,
Results: []App{
{
ID: 0,
BundleID: "",
Name: "",
Version: "",
Price: 0,
},
},
},
}, nil)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[PurchaseResult]{
Data: PurchaseResult{
Return(http.Result[purchaseResult]{
Data: purchaseResult{
FailureType: "failure",
CustomerMessage: CustomerMessageBadLogin,
},
}, nil)
mockLogger.EXPECT().
Verbose().
Return(nil).
Times(2)
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(CustomerMessageBadLogin)))
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
When("store API returns unknown error", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockSearchClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 200,
Data: SearchResult{
Count: 1,
Results: []App{
{
ID: 0,
BundleID: "",
Name: "",
Version: "",
Price: 0,
},
},
},
}, nil)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[PurchaseResult]{
Data: PurchaseResult{
Return(http.Result[purchaseResult]{
Data: purchaseResult{
FailureType: "failure",
},
}, nil)
mockLogger.EXPECT().
Verbose().
Return(nil).
Times(2)
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrGeneric.Error())))
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
When("account already has a license for the app", func() {
When("account already has a license for the app (failure type)", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockSearchClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 200,
Data: SearchResult{
Count: 1,
Results: []App{
{
ID: 0,
BundleID: "",
Name: "",
Version: "",
Price: 0,
},
},
},
}, nil)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[PurchaseResult]{
StatusCode: 500,
Data: PurchaseResult{},
Return(http.Result[purchaseResult]{
StatusCode: 200,
Data: purchaseResult{
FailureType: FailureTypeLicenseAlreadyExists,
CustomerMessage: "An unknown error has occurred",
},
}, nil)
mockLogger.EXPECT().
Verbose().
Return(nil)
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrLicenseExists.Error())))
It("returns license already exists error", func() {
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(MatchError(ErrLicenseAlreadyExists))
})
})
When("account already has a license for the app (HTTP 500 legacy)", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[purchaseResult]{
StatusCode: 500,
Data: purchaseResult{},
}, nil)
})
It("returns license already exists error", func() {
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(MatchError(ErrLicenseAlreadyExists))
})
})
When("device verification fails", func() {
BeforeEach(func() {
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[purchaseResult]{
StatusCode: 200,
Data: purchaseResult{
FailureType: FailureTypeDeviceVerificationFailed,
CustomerMessage: "Your device or computer could not be verified. Contact support for assistance.",
},
}, nil)
})
It("returns password token expired error", func() {
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(MatchError(ErrPasswordTokenExpired))
})
})
When("subscription is required", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockSearchClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 200,
Data: SearchResult{
Count: 1,
Results: []App{
{
ID: 0,
BundleID: "",
Name: "",
Version: "",
Price: 0,
},
},
},
}, nil)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(pricingParametersMatcher{"STDQ"}).
Return(http.Result[PurchaseResult]{
Return(http.Result[purchaseResult]{
StatusCode: 200,
Data: PurchaseResult{
Data: purchaseResult{
CustomerMessage: "This item is temporarily unavailable.",
FailureType: FailureTypeTemporarilyUnavailable,
},
@@ -484,58 +350,35 @@ var _ = Describe("AppStore (Purchase)", func() {
mockPurchaseClient.EXPECT().
Send(pricingParametersMatcher{"GAME"}).
Return(http.Result[PurchaseResult]{
Return(http.Result[purchaseResult]{
StatusCode: 200,
Data: PurchaseResult{
Data: purchaseResult{
CustomerMessage: CustomerMessageSubscriptionRequired,
},
}, nil)
mockLogger.EXPECT().
Verbose().
Return(nil).
Times(2)
})
It("returns error", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrSubscriptionRequired.Error())))
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
When("successfully purchases the app", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockSearchClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 200,
Data: SearchResult{
Count: 1,
Results: []App{
{
ID: 0,
BundleID: "",
Name: "",
Version: "",
Price: 0,
},
},
},
}, nil)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(pricingParametersMatcher{"STDQ"}).
Return(http.Result[PurchaseResult]{
Return(http.Result[purchaseResult]{
StatusCode: 200,
Data: PurchaseResult{
Data: purchaseResult{
CustomerMessage: "This item is temporarily unavailable.",
FailureType: FailureTypeTemporarilyUnavailable,
},
@@ -543,76 +386,49 @@ var _ = Describe("AppStore (Purchase)", func() {
mockPurchaseClient.EXPECT().
Send(pricingParametersMatcher{"GAME"}).
Return(http.Result[PurchaseResult]{
Return(http.Result[purchaseResult]{
StatusCode: 200,
Data: PurchaseResult{
Data: purchaseResult{
JingleDocType: "purchaseSuccess",
Status: 0,
},
}, nil)
mockLogger.EXPECT().
Verbose().
Return(nil)
mockLogger.EXPECT().
Log().
Return(nil)
})
It("returns nil", func() {
err := as.Purchase("")
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).ToNot(HaveOccurred())
})
})
When("purchasing the app fails", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockSearchClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 200,
Data: SearchResult{
Count: 1,
Results: []App{
{
ID: 0,
BundleID: "",
Name: "",
Version: "",
Price: 0,
},
},
},
}, nil)
mockMachine.EXPECT().
MacAddress().
Return("00:00:00:00:00:00", nil)
mockPurchaseClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[PurchaseResult]{
Return(http.Result[purchaseResult]{
StatusCode: 200,
Data: PurchaseResult{
Data: purchaseResult{
JingleDocType: "failure",
Status: -1,
},
}, nil)
mockLogger.EXPECT().
Verbose().
Return(nil).
Times(2)
})
It("returns nil", func() {
err := as.Purchase("")
Expect(err).To(MatchError(ContainSubstring(ErrPurchase.Error())))
err := as.Purchase(PurchaseInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
})
@@ -622,8 +438,7 @@ type pricingParametersMatcher struct {
}
func (p pricingParametersMatcher) Matches(in interface{}) bool {
request := in.(http.Request)
return request.Payload.(*http.XMLPayload).Content["pricingParameters"] == p.pricingParameters
return in.(http.Request).Payload.(*http.XMLPayload).Content["pricingParameters"] == p.pricingParameters
}
func (p pricingParametersMatcher) String() string {
+241
View File
@@ -0,0 +1,241 @@
package appstore
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/majd/ipatool/v2/pkg/util"
"howett.net/plist"
)
type Sinf struct {
ID int64 `plist:"id,omitempty"`
Data []byte `plist:"sinf,omitempty"`
}
type ReplicateSinfInput struct {
Sinfs []Sinf
PackagePath string
}
func (t *appstore) ReplicateSinf(input ReplicateSinfInput) error {
zipReader, err := zip.OpenReader(input.PackagePath)
if err != nil {
return errors.New("failed to open zip reader")
}
tmpPath := fmt.Sprintf("%s.tmp", input.PackagePath)
tmpFile, err := t.os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
zipWriter := zip.NewWriter(tmpFile)
err = t.replicateZip(zipReader, zipWriter)
if err != nil {
return fmt.Errorf("failed to replicate zip: %w", err)
}
bundleName, err := t.readBundleName(zipReader)
if err != nil {
return fmt.Errorf("failed to read bundle name: %w", err)
}
manifest, err := t.readManifestPlist(zipReader)
if err != nil {
return fmt.Errorf("failed to read manifest plist: %w", err)
}
info, err := t.readInfoPlist(zipReader)
if err != nil {
return fmt.Errorf("failed to read info plist: %w", err)
}
if manifest != nil {
err = t.replicateSinfFromManifest(*manifest, zipWriter, input.Sinfs, bundleName)
} else {
err = t.replicateSinfFromInfo(*info, zipWriter, input.Sinfs, bundleName)
}
if err != nil {
return fmt.Errorf("failed to replicate sinf: %w", err)
}
zipReader.Close()
zipWriter.Close()
tmpFile.Close()
err = t.os.Remove(input.PackagePath)
if err != nil {
return fmt.Errorf("failed to remove original file: %w", err)
}
err = t.os.Rename(tmpPath, input.PackagePath)
if err != nil {
return fmt.Errorf("failed to remove original file: %w", err)
}
return nil
}
type packageManifest struct {
SinfPaths []string `plist:"SinfPaths,omitempty"`
}
type packageInfo struct {
BundleExecutable string `plist:"CFBundleExecutable,omitempty"`
}
func (*appstore) replicateSinfFromManifest(manifest packageManifest, zip *zip.Writer, sinfs []Sinf, bundleName string) error {
zipped, err := util.Zip(sinfs, manifest.SinfPaths)
if err != nil {
return fmt.Errorf("failed to zip sinfs: %w", err)
}
for _, pair := range zipped {
sp := fmt.Sprintf("Payload/%s.app/%s", bundleName, pair.Second)
file, err := zip.Create(sp)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
_, err = file.Write(pair.First.Data)
if err != nil {
return fmt.Errorf("failed to write data: %w", err)
}
}
return nil
}
func (t *appstore) replicateSinfFromInfo(info packageInfo, zip *zip.Writer, sinfs []Sinf, bundleName string) error {
sp := fmt.Sprintf("Payload/%s.app/SC_Info/%s.sinf", bundleName, info.BundleExecutable)
file, err := zip.Create(sp)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
_, err = file.Write(sinfs[0].Data)
if err != nil {
return fmt.Errorf("failed to write data: %w", err)
}
return nil
}
func (t *appstore) replicateZip(src *zip.ReadCloser, dst *zip.Writer) error {
for _, file := range src.File {
err := func() error {
srcFile, err := file.Open()
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer srcFile.Close()
header := file.FileHeader
dstFile, err := dst.CreateHeader(&header)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
_, err = io.Copy(dstFile, srcFile)
if err != nil {
return fmt.Errorf("failed to copy file: %w", err)
}
return nil
}()
if err != nil {
return err
}
}
return nil
}
func (*appstore) readInfoPlist(reader *zip.ReadCloser) (*packageInfo, error) {
for _, file := range reader.File {
if strings.Contains(file.Name, ".app/Info.plist") {
src, err := file.Open()
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
}
data := new(bytes.Buffer)
_, err = io.Copy(data, src)
if err != nil {
return nil, fmt.Errorf("failed to copy data: %w", err)
}
var info packageInfo
_, err = plist.Unmarshal(data.Bytes(), &info)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal data: %w", err)
}
return &info, nil
}
}
return nil, nil
}
func (*appstore) readManifestPlist(reader *zip.ReadCloser) (*packageManifest, error) {
for _, file := range reader.File {
if strings.HasSuffix(file.Name, ".app/SC_Info/Manifest.plist") {
src, err := file.Open()
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
}
data := new(bytes.Buffer)
_, err = io.Copy(data, src)
if err != nil {
return nil, fmt.Errorf("failed to copy data: %w", err)
}
var manifest packageManifest
_, err = plist.Unmarshal(data.Bytes(), &manifest)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal data: %w", err)
}
return &manifest, nil
}
}
return nil, nil
}
func (*appstore) readBundleName(reader *zip.ReadCloser) (string, error) {
var bundleName string
for _, file := range reader.File {
if strings.Contains(file.Name, ".app/Info.plist") && !strings.Contains(file.Name, "/Watch/") {
bundleName = filepath.Base(strings.TrimSuffix(file.Name, ".app/Info.plist"))
break
}
}
if bundleName == "" {
return "", errors.New("could not read bundle name")
}
return bundleName, nil
}
@@ -0,0 +1,200 @@
package appstore
import (
"archive/zip"
"errors"
"fmt"
"os"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/keychain"
"github.com/majd/ipatool/v2/pkg/util/machine"
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
"howett.net/plist"
)
var _ = Describe("AppStore (ReplicateSinf)", func() {
var (
ctrl *gomock.Controller
mockKeychain *keychain.MockKeychain
mockDownloadClient *http.MockClient[downloadResult]
mockPurchaseClient *http.MockClient[purchaseResult]
mockLoginClient *http.MockClient[loginResult]
mockHTTPClient *http.MockClient[interface{}]
mockOS *operatingsystem.MockOperatingSystem
mockMachine *machine.MockMachine
as AppStore
testFile *os.File
testZip *zip.Writer
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockKeychain = keychain.NewMockKeychain(ctrl)
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
mockLoginClient = http.NewMockClient[loginResult](ctrl)
mockPurchaseClient = http.NewMockClient[purchaseResult](ctrl)
mockHTTPClient = http.NewMockClient[interface{}](ctrl)
mockOS = operatingsystem.NewMockOperatingSystem(ctrl)
mockMachine = machine.NewMockMachine(ctrl)
as = &appstore{
keychain: mockKeychain,
loginClient: mockLoginClient,
purchaseClient: mockPurchaseClient,
downloadClient: mockDownloadClient,
httpClient: mockHTTPClient,
machine: mockMachine,
os: mockOS,
}
var err error
testFile, err = os.CreateTemp("", "test_file")
Expect(err).ToNot(HaveOccurred())
testZip = zip.NewWriter(testFile)
})
JustBeforeEach(func() {
testZip.Close()
})
AfterEach(func() {
err := os.Remove(testFile.Name())
Expect(err).ToNot(HaveOccurred())
ctrl.Finish()
})
When("app includes codesign manifest", func() {
BeforeEach(func() {
mockOS.EXPECT().
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
DoAndReturn(os.OpenFile)
mockOS.EXPECT().
Remove(testFile.Name()).
Return(nil)
mockOS.EXPECT().
Rename(fmt.Sprintf("%s.tmp", testFile.Name()), testFile.Name()).
Return(nil)
manifest, err := plist.Marshal(packageManifest{
SinfPaths: []string{
"SC_Info/TestApp.sinf",
},
}, plist.BinaryFormat)
Expect(err).ToNot(HaveOccurred())
w, err := testZip.Create("Payload/Test.app/SC_Info/Manifest.plist")
Expect(err).ToNot(HaveOccurred())
_, err = w.Write(manifest)
Expect(err).ToNot(HaveOccurred())
w, err = testZip.Create("Payload/Test.app/Info.plist")
Expect(err).ToNot(HaveOccurred())
info, err := plist.Marshal(map[string]interface{}{
"CFBundleExecutable": "Test",
}, plist.BinaryFormat)
Expect(err).ToNot(HaveOccurred())
_, err = w.Write(info)
Expect(err).ToNot(HaveOccurred())
w, err = testZip.Create("Payload/Test.app/Watch/Test.app/Info.plist")
Expect(err).ToNot(HaveOccurred())
watchInfo, err := plist.Marshal(map[string]interface{}{
"WKWatchKitApp": true,
}, plist.BinaryFormat)
Expect(err).ToNot(HaveOccurred())
_, err = w.Write(watchInfo)
Expect(err).ToNot(HaveOccurred())
})
It("replicates sinf from manifest plist", func() {
err := as.ReplicateSinf(ReplicateSinfInput{
PackagePath: testFile.Name(),
Sinfs: []Sinf{
{
ID: 0,
Data: []byte(""),
},
},
})
Expect(err).ToNot(HaveOccurred())
})
})
When("app does not include codesign manifest", func() {
BeforeEach(func() {
mockOS.EXPECT().
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
DoAndReturn(os.OpenFile)
mockOS.EXPECT().
Remove(testFile.Name()).
Return(nil)
mockOS.EXPECT().
Rename(fmt.Sprintf("%s.tmp", testFile.Name()), testFile.Name()).
Return(nil)
w, err := testZip.Create("Payload/Test.app/Info.plist")
Expect(err).ToNot(HaveOccurred())
info, err := plist.Marshal(map[string]interface{}{
"CFBundleExecutable": "Test",
}, plist.BinaryFormat)
Expect(err).ToNot(HaveOccurred())
_, err = w.Write(info)
Expect(err).ToNot(HaveOccurred())
w, err = testZip.Create("Payload/Test.app/Watch/Test.app/Info.plist")
Expect(err).ToNot(HaveOccurred())
watchInfo, err := plist.Marshal(map[string]interface{}{
"WKWatchKitApp": true,
}, plist.BinaryFormat)
Expect(err).ToNot(HaveOccurred())
_, err = w.Write(watchInfo)
Expect(err).ToNot(HaveOccurred())
})
It("replicates sinf", func() {
err := as.ReplicateSinf(ReplicateSinfInput{
PackagePath: testFile.Name(),
Sinfs: []Sinf{
{
ID: 0,
Data: []byte(""),
},
},
})
Expect(err).ToNot(HaveOccurred())
})
})
When("fails to open file", func() {
BeforeEach(func() {
mockOS.EXPECT().
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
Return(nil, errors.New(""))
})
It("returns error", func() {
err := as.ReplicateSinf(ReplicateSinfInput{
PackagePath: testFile.Name(),
})
Expect(err).To(HaveOccurred())
})
})
})
+4 -5
View File
@@ -1,15 +1,14 @@
package appstore
import (
"github.com/pkg/errors"
"fmt"
)
func (a *appstore) Revoke() error {
err := a.keychain.Remove("account")
func (t *appstore) Revoke() error {
err := t.keychain.Remove("account")
if err != nil {
return errors.Wrap(err, ErrRemoveKeychainItem.Error())
return fmt.Errorf("failed to remove account from keychain: %w", err)
}
a.logger.Log().Bool("success", true).Send()
return nil
}
+18 -28
View File
@@ -1,12 +1,12 @@
package appstore
import (
"github.com/golang/mock/gomock"
"github.com/majd/ipatool/pkg/keychain"
"github.com/majd/ipatool/pkg/log"
"errors"
"github.com/majd/ipatool/v2/pkg/keychain"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"go.uber.org/mock/gomock"
)
var _ = Describe("AppStore (Revoke)", func() {
@@ -14,16 +14,13 @@ var _ = Describe("AppStore (Revoke)", func() {
ctrl *gomock.Controller
appstore AppStore
mockKeychain *keychain.MockKeychain
mockLogger *log.MockLogger
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockKeychain = keychain.NewMockKeychain(ctrl)
mockLogger = log.NewMockLogger(ctrl)
appstore = NewAppStore(AppStoreArgs{
appstore = NewAppStore(Args{
Keychain: mockKeychain,
Logger: mockLogger,
})
})
@@ -31,28 +28,8 @@ var _ = Describe("AppStore (Revoke)", func() {
ctrl.Finish()
})
When("keychain returns error", func() {
var testErr = errors.New("test error")
BeforeEach(func() {
mockKeychain.EXPECT().
Remove("account").
Return(testErr)
})
It("returns wrapped error", func() {
err := appstore.Revoke()
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
Expect(err).To(MatchError(ContainSubstring(ErrRemoveKeychainItem.Error())))
})
})
When("keychain removes item", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Log().
Return(nil)
mockKeychain.EXPECT().
Remove("account").
Return(nil)
@@ -63,4 +40,17 @@ var _ = Describe("AppStore (Revoke)", func() {
Expect(err).ToNot(HaveOccurred())
})
})
When("keychain returns error", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Remove("account").
Return(errors.New(""))
})
It("returns wrapped error", func() {
err := appstore.Revoke()
Expect(err).To(HaveOccurred())
})
})
})
+56 -33
View File
@@ -1,60 +1,83 @@
package appstore
import (
"errors"
"fmt"
"github.com/majd/ipatool/pkg/http"
"github.com/pkg/errors"
gohttp "net/http"
"net/url"
"strconv"
"github.com/majd/ipatool/v2/pkg/http"
)
type SearchResult struct {
type SearchInput struct {
Account Account
Term string
Limit int64
Platform Platform
}
type SearchOutput struct {
Count int
Results []App
}
func (t *appstore) Search(input SearchInput) (SearchOutput, error) {
countryCode, err := countryCodeFromStoreFront(input.Account.StoreFront)
if err != nil {
return SearchOutput{}, fmt.Errorf("country code is invalid: %w", err)
}
request, err := t.searchRequest(input.Term, countryCode, input.Limit, input.Platform)
if err != nil {
return SearchOutput{}, fmt.Errorf("failed to create search request: %w", err)
}
res, err := t.searchClient.Send(request)
if err != nil {
return SearchOutput{}, fmt.Errorf("request failed: %w", err)
}
if res.StatusCode != gohttp.StatusOK {
return SearchOutput{}, NewErrorWithMetadata(errors.New("request failed"), res)
}
return SearchOutput{
Count: res.Data.Count,
Results: res.Data.Results,
}, nil
}
type searchResult struct {
Count int `json:"resultCount,omitempty"`
Results []App `json:"results,omitempty"`
}
func (a *appstore) Search(term string, limit int64) error {
acc, err := a.account()
func (t *appstore) searchRequest(term, countryCode string, limit int64, platform Platform) (http.Request, error) {
url, err := t.searchURL(term, countryCode, limit, platform)
if err != nil {
return errors.Wrap(err, ErrGetAccount.Error())
return http.Request{}, err
}
countryCode, err := a.countryCodeFromStoreFront(acc.StoreFront)
if err != nil {
return errors.Wrap(err, ErrInvalidCountryCode.Error())
}
request := a.searchRequest(term, countryCode, limit)
res, err := a.searchClient.Send(request)
if err != nil {
return errors.Wrap(err, ErrRequest.Error())
}
if res.StatusCode != 200 {
a.logger.Verbose().Interface("data", res.Data).Int("status", res.StatusCode).Send()
return ErrRequest
}
a.logger.Log().Int("count", res.Data.Count).Array("apps", Apps(res.Data.Results)).Send()
return nil
}
func (a *appstore) searchRequest(term, countryCode string, limit int64) http.Request {
return http.Request{
URL: a.searchURL(term, countryCode, limit),
URL: url,
Method: http.MethodGET,
ResponseFormat: http.ResponseFormatJSON,
}
}, nil
}
func (a *appstore) searchURL(term, countryCode string, limit int64) string {
func (t *appstore) searchURL(term, countryCode string, limit int64, platform Platform) (string, error) {
entity, err := platform.searchEntity()
if err != nil {
return "", err
}
params := url.Values{}
params.Add("entity", "software,iPadSoftware")
params.Add("entity", entity)
params.Add("limit", strconv.Itoa(int(limit)))
params.Add("media", "software")
params.Add("term", term)
params.Add("country", countryCode)
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathSearch, params.Encode())
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathSearch, params.Encode()), nil
}
+92 -78
View File
@@ -1,35 +1,27 @@
package appstore
import (
"github.com/golang/mock/gomock"
"github.com/majd/ipatool/pkg/http"
"github.com/majd/ipatool/pkg/keychain"
"github.com/majd/ipatool/pkg/log"
"errors"
"net/url"
"github.com/majd/ipatool/v2/pkg/http"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"os"
"go.uber.org/mock/gomock"
)
var _ = Describe("AppStore (Search)", func() {
var (
ctrl *gomock.Controller
mockClient *http.MockClient[SearchResult]
mockLogger *log.MockLogger
mockKeychain *keychain.MockKeychain
as AppStore
ctrl *gomock.Controller
mockClient *http.MockClient[searchResult]
as AppStore
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockClient = http.NewMockClient[SearchResult](ctrl)
mockLogger = log.NewMockLogger(ctrl)
mockKeychain = keychain.NewMockKeychain(ctrl)
mockClient = http.NewMockClient[searchResult](ctrl)
as = &appstore{
searchClient: mockClient,
ioReader: os.Stdin,
logger: mockLogger,
keychain: mockKeychain,
}
})
@@ -37,99 +29,121 @@ var _ = Describe("AppStore (Search)", func() {
ctrl.Finish()
})
When("user is not logged in", func() {
When("request is successful", func() {
const (
testID = 0
testBundleID = "test-bundle-id"
testName = "test-name"
testVersion = "test-version"
testPrice = 0.0
)
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return(nil, ErrGetKeychainItem)
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[searchResult]{
StatusCode: 200,
Data: searchResult{
Count: 1,
Results: []App{
{
ID: testID,
BundleID: testBundleID,
Name: testName,
Version: testVersion,
Price: testPrice,
},
},
},
}, nil)
})
It("returns error", func() {
err := as.Search("", 0)
Expect(err).To(MatchError(ContainSubstring(ErrGetAccount.Error())))
It("returns output", func() {
out, err := as.Search(SearchInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).ToNot(HaveOccurred())
Expect(out.Count).To(Equal(1))
Expect(out.Results).To(HaveLen(1))
Expect(out.Results[0]).To(Equal(App{
ID: testID,
BundleID: testBundleID,
Name: testName,
Version: testVersion,
Price: testPrice,
}))
})
})
When("country code is invalid", func() {
When("platform is AppleTV", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{}"), nil)
mockClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
parsedURL, err := url.Parse(req.URL)
Expect(err).ToNot(HaveOccurred())
Expect(parsedURL.Query().Get("entity")).To(Equal("software,tvSoftware"))
}).
Return(http.Result[searchResult]{}, errors.New("request error"))
})
It("uses the tvOS search entity", func() {
_, err := as.Search(SearchInput{
Account: Account{
StoreFront: "143441",
},
Platform: PlatformAppleTV,
})
Expect(err).To(HaveOccurred())
})
})
When("store front is invalid", func() {
It("returns error", func() {
err := as.Search("", 0)
Expect(err).To(MatchError(ContainSubstring(ErrInvalidCountryCode.Error())))
_, err := as.Search(SearchInput{
Account: Account{
StoreFront: "xyz",
},
})
Expect(err).To(HaveOccurred())
})
})
When("request fails", func() {
var testErr = errors.New("test")
BeforeEach(func() {
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{}, testErr)
Return(http.Result[searchResult]{}, errors.New(""))
})
It("returns error", func() {
err := as.Search("", 0)
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
_, err := as.Search(SearchInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
When("request returns bad status code", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Verbose().
Return(nil)
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
Return(http.Result[searchResult]{
StatusCode: 400,
}, nil)
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
})
It("returns error", func() {
err := as.Search("", 0)
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
})
})
When("request is successful", func() {
BeforeEach(func() {
mockLogger.EXPECT().
Log().
Return(nil)
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[SearchResult]{
StatusCode: 200,
Data: SearchResult{
Count: 0,
Results: []App{},
},
}, nil)
mockKeychain.EXPECT().
Get("account").
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
})
It("returns nil", func() {
err := as.Search("", 0)
Expect(err).ToNot(HaveOccurred())
_, err := as.Search(SearchInput{
Account: Account{
StoreFront: "143441",
},
})
Expect(err).To(HaveOccurred())
})
})
})
+2 -1
View File
@@ -1,9 +1,10 @@
package appstore
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"testing"
)
func TestAppStore(t *testing.T) {
+16 -10
View File
@@ -1,26 +1,32 @@
package appstore
const (
FailureTypeInvalidCredentials = "-5000"
FailureTypePasswordTokenExpired = "2034"
FailureTypeLicenseNotFound = "9610"
FailureTypeTemporarilyUnavailable = "2059"
FailureTypeInvalidCredentials = "-5000"
FailureTypePasswordTokenExpired = "2034"
FailureTypeSignInRequired = "2042"
FailureTypeLicenseNotFound = "9610"
FailureTypeTemporarilyUnavailable = "2059"
FailureTypeLicenseAlreadyExists = "5002"
FailureTypeDeviceVerificationFailed = "1008"
CustomerMessageBadLogin = "MZFinance.BadLogin.Configurator_message"
CustomerMessageAccountDisabled = "Your account is disabled."
CustomerMessageSubscriptionRequired = "Subscription Required"
CustomerMessagePasswordChanged = "Your password has changed."
iTunesAPIDomain = "itunes.apple.com"
iTunesAPIPathSearch = "/search"
iTunesAPIPathLookup = "/lookup"
PriavteAppStoreAPIDomainPrefixWithoutAuthCode = "p25"
PriavteAppStoreAPIDomainPrefixWithAuthCode = "p71"
PrivateAppStoreAPIDomain = "buy." + iTunesAPIDomain
PrivateAppStoreAPIPathAuthenticate = "/WebObjects/MZFinance.woa/wa/authenticate"
PrivateAppStoreAPIPathPurchase = "/WebObjects/MZBuy.woa/wa/buyProduct"
PrivateAppStoreAPIPathDownload = "/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct"
PrivateInitDomain = "init." + iTunesAPIDomain
PrivateInitPath = "/bag.xml"
PrivateAppStoreAPIDomain = "buy." + iTunesAPIDomain
PrivateAppStoreAPIPathPurchase = "/WebObjects/MZFinance.woa/wa/buyProduct"
PrivateAppStoreAPIPathDownload = "/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct"
HTTPHeaderStoreFront = "X-Set-Apple-Store-Front"
HTTPHeaderPod = "pod"
PricingParameterAppStore = "STDQ"
PricingParameterAppleArcade = "GAME"
+17
View File
@@ -0,0 +1,17 @@
package appstore
type Error struct {
Metadata interface{}
underlyingError error
}
func (t Error) Error() string {
return t.underlyingError.Error()
}
func NewErrorWithMetadata(err error, metadata interface{}) *Error {
return &Error{
underlyingError: err,
Metadata: metadata,
}
}
-58
View File
@@ -1,58 +0,0 @@
package appstore
import "errors"
var (
ErrAppLookup = errors.New("failed to find app")
ErrAppNotFound = errors.New("failed to find app on the App Store")
ErrApplyLegacyPatches = errors.New("failed to apply legacy patches")
ErrApplyPatches = errors.New("failed to apply patches")
ErrAuthCodeRequired = errors.New("auth code is required")
ErrCheckDirectory = errors.New("failed to determine if the supplied path is a directory")
ErrCreateDestinationFile = errors.New("failed to create destination file")
ErrCreateMetadataFile = errors.New("failed to create metadata file")
ErrCreateRequest = errors.New("failed to create HTTP request")
ErrCreateSinfFile = errors.New("failed to create sinf file")
ErrDecompressInfoFile = errors.New("failed to open decompressed info file")
ErrDecompressManifestFile = errors.New("failed to open decompressed manifest file")
ErrDownloadFile = errors.New("failed to download file")
ErrEncodeMetadataFile = errors.New("failed to encode metadata")
ErrFileWrite = errors.New("failed to write file")
ErrGeneric = errors.New("failed due to an unknown error")
ErrGetAccount = errors.New("failed to get account")
ErrGetBundleName = errors.New("failed to determine name of app bundle")
ErrGetCurrentDirectory = errors.New("failed to get current directory path")
ErrGetData = errors.New("failed to get data")
ErrGetExecutablePath = errors.New("failed to get executable path")
ErrGetFileMetadata = errors.New("failed to get file metadata")
ErrGetInfoFile = errors.New("failed to read info file")
ErrGetKeychainItem = errors.New("failed to read item from keychain")
ErrGetMAC = errors.New("failed to get MAC address")
ErrGetManifestFile = errors.New("failed to read manifest file")
ErrInvalidCountryCode = errors.New("invalid country code")
ErrInvalidResponse = errors.New("received 0 items from the App Store; expected 1 or more")
ErrInvalidStoreFront = errors.New("could not infer country code from store front")
ErrLicenseExists = errors.New("account already has a license for this app")
ErrLicenseRequired = errors.New("license is required")
ErrLogin = errors.New("failed to log in")
ErrMarshal = errors.New("failed to marshal data")
ErrOpenFile = errors.New("failed to open file")
ErrOpenZipFile = errors.New("failed to open zip file")
ErrPaidApp = errors.New("paid apps cannot be purchased")
ErrPasswordRequired = errors.New("password is required when not running in interactive mode; use the \"--password\" flag")
ErrPasswordTokenExpired = errors.New("password token is expired")
ErrPatchApp = errors.New("failed to patch app package")
ErrPurchase = errors.New("failed to purchase app")
ErrRemoveKeychainItem = errors.New("failed to remove item from keychain")
ErrRemoveTempFile = errors.New("failed to remove temporary file")
ErrReplicateZip = errors.New("failed to replicate zip")
ErrRequest = errors.New("failed to send request")
ErrResolveDestinationPath = errors.New("failed to resolve destination path")
ErrSetKeychainItem = errors.New("failed to save item in keychain")
ErrSubscriptionRequired = errors.New("subscription required")
ErrTemporarilyUnavailable = errors.New("item is temporarily unavailable")
ErrUnmarshal = errors.New("failed to unmarshal data")
ErrWriteMetadataFile = errors.New("failed to write metadata")
ErrWriteSinfData = errors.New("failed to write sinf data")
ErrZipSinfs = errors.New("failed to zip sinfs and sinf paths")
)
+67
View File
@@ -0,0 +1,67 @@
package appstore
import "fmt"
type Platform string
const (
PlatformIPhone Platform = "iphone"
PlatformIPad Platform = "ipad"
PlatformAppleTV Platform = "appletv"
)
func ParsePlatform(value string) (Platform, error) {
switch value {
case "":
return "", nil
case "iphone", "iPhone", "ios", "iOS":
return PlatformIPhone, nil
case "ipad", "iPad":
return PlatformIPad, nil
case "appletv", "AppleTV", "apple-tv", "tvos", "tvOS":
return PlatformAppleTV, nil
default:
return "", fmt.Errorf("invalid platform %q", value)
}
}
func (p Platform) lookupEntity() (string, error) {
switch p {
case "":
return "software,iPadSoftware", nil
case PlatformIPhone:
return "software", nil
case PlatformIPad:
return "iPadSoftware", nil
case PlatformAppleTV:
return "tvSoftware", nil
default:
return "", fmt.Errorf("invalid platform %q", p)
}
}
func (p Platform) searchEntity() (string, error) {
switch p {
case "":
return "software,iPadSoftware", nil
case PlatformIPhone:
return "software", nil
case PlatformIPad:
return "iPadSoftware", nil
case PlatformAppleTV:
return "software,tvSoftware", nil
default:
return "", fmt.Errorf("invalid platform %q", p)
}
}
func (p Platform) metadataPlatform() (string, error) {
switch p {
case PlatformIPhone, PlatformIPad:
return "enterprisestore", nil
case PlatformAppleTV:
return "atv9", nil
default:
return "", fmt.Errorf("invalid platform %q", p)
}
}
+27
View File
@@ -0,0 +1,27 @@
package appstore
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Platform", func() {
DescribeTable("parses aliases",
func(value string, expected Platform) {
platform, err := ParsePlatform(value)
Expect(err).ToNot(HaveOccurred())
Expect(platform).To(Equal(expected))
},
Entry("default", "", Platform("")),
Entry("iPhone", "iphone", PlatformIPhone),
Entry("iOS", "ios", PlatformIPhone),
Entry("iPad", "ipad", PlatformIPad),
Entry("AppleTV", "appletv", PlatformAppleTV),
Entry("tvOS", "tvos", PlatformAppleTV),
)
It("returns an error for invalid platforms", func() {
_, err := ParsePlatform("watch")
Expect(err).To(HaveOccurred())
})
})
@@ -1,6 +1,23 @@
package appstore
var StoreFronts = map[string]string{
import (
"fmt"
"strings"
)
func countryCodeFromStoreFront(storeFront string) (string, error) {
for key, val := range storeFronts {
parts := strings.Split(storeFront, "-")
if len(parts) >= 1 && parts[0] == val {
return key, nil
}
}
return "", fmt.Errorf("country code mapping for store front (%s) was not found", storeFront)
}
var storeFronts = map[string]string{
"AE": "143481",
"AG": "143540",
"AI": "143538",
@@ -46,6 +63,7 @@ var StoreFronts = map[string]string{
"FR": "143442",
"GB": "143444",
"GD": "143546",
"GE": "143615",
"GH": "143573",
"GR": "143448",
"GT": "143504",
@@ -60,6 +78,7 @@ var StoreFronts = map[string]string{
"IN": "143467",
"IS": "143558",
"IT": "143450",
"IQ": "143617",
"JM": "143511",
"JO": "143528",
"JP": "143462",
+182 -23
View File
@@ -3,14 +3,27 @@ package http
import (
"bytes"
"encoding/json"
"github.com/pkg/errors"
"howett.net/plist"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"howett.net/plist"
)
//go:generate mockgen -source=client.go -destination=client_mock.go -package=http
const (
appStoreAuthURL = "https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/authenticate"
)
var (
documentXMLPattern = regexp.MustCompile(`(?is)<Document\b[^>]*>(.*)</Document>`)
plistXMLPattern = regexp.MustCompile(`(?is)<plist\b[^>]*>.*?</plist>`)
dictXMLPattern = regexp.MustCompile(`(?is)<dict\b[^>]*>.*</dict>`)
htmlTagPattern = regexp.MustCompile(`(?is)<[^>]*>`)
)
//go:generate go run go.uber.org/mock/mockgen -source=client.go -destination=client_mock.go -package=http
type Client[R interface{}] interface {
Send(request Request) (Result[R], error)
Do(req *http.Request) (*http.Response, error)
@@ -22,7 +35,7 @@ type client[R interface{}] struct {
cookieJar CookieJar
}
type ClientArgs struct {
type Args struct {
CookieJar CookieJar
}
@@ -30,18 +43,31 @@ type AddHeaderTransport struct {
T http.RoundTripper
}
func (adt *AddHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error) {
func (t *AddHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.Header.Get("User-Agent") == "" {
req.Header.Set("User-Agent", DefaultUserAgent)
}
return adt.T.RoundTrip(req)
res, err := t.T.RoundTrip(req)
if err != nil {
return nil, fmt.Errorf("failed to make round trip: %w", err)
}
return res, nil
}
func NewClient[R interface{}](args ClientArgs) Client[R] {
func NewClient[R interface{}](args Args) Client[R] {
return &client[R]{
internalClient: http.Client{
Timeout: 0,
Jar: args.CookieJar,
Timeout: 0,
Jar: args.CookieJar,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if req.Referer() == appStoreAuthURL {
return http.ErrUseLastResponse
}
return nil
},
Transport: &AddHeaderTransport{http.DefaultTransport},
},
cookieJar: args.CookieJar,
@@ -49,19 +75,21 @@ func NewClient[R interface{}](args ClientArgs) Client[R] {
}
func (c *client[R]) Send(req Request) (Result[R], error) {
var data []byte
var err error
var (
data []byte
err error
)
if req.Payload != nil {
data, err = req.Payload.data()
if err != nil {
return Result[R]{}, errors.Wrap(err, ErrGetPayloadData.Error())
return Result[R]{}, fmt.Errorf("failed to get payload data: %w", err)
}
}
request, err := http.NewRequest(req.Method, req.URL, bytes.NewReader(data))
if err != nil {
return Result[R]{}, errors.Wrap(err, ErrCreateRequest.Error())
return Result[R]{}, fmt.Errorf("failed to create request: %w", err)
}
for key, val := range req.Headers {
@@ -70,42 +98,55 @@ func (c *client[R]) Send(req Request) (Result[R], error) {
res, err := c.internalClient.Do(request)
if err != nil {
return Result[R]{}, errors.Wrap(err, ErrRequest.Error())
return Result[R]{}, fmt.Errorf("request failed: %w", err)
}
defer res.Body.Close()
err = c.cookieJar.Save()
if err != nil {
return Result[R]{}, errors.Wrap(err, ErrSaveCookie.Error())
return Result[R]{}, fmt.Errorf("failed to save cookies: %w", err)
}
if req.ResponseFormat == ResponseFormatJSON {
return c.handleJSONResponse(res)
}
if req.ResponseFormat == ResponseFormatXML {
return c.handleXMLResponse(res)
}
return Result[R]{}, errors.Errorf("%s: %s", ErrUnsupportedContentType.Error(), req.ResponseFormat)
return Result[R]{}, fmt.Errorf("content type is not supported (%s)", req.ResponseFormat)
}
func (c *client[R]) Do(req *http.Request) (*http.Response, error) {
return c.internalClient.Do(req)
res, err := c.internalClient.Do(req)
if err != nil {
return nil, fmt.Errorf("received error: %w", err)
}
return res, nil
}
func (*client[R]) NewRequest(method, url string, body io.Reader) (*http.Request, error) {
return http.NewRequest(method, url, body)
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
return req, nil
}
func (c *client[R]) handleJSONResponse(res *http.Response) (Result[R], error) {
body, err := io.ReadAll(res.Body)
if err != nil {
return Result[R]{}, errors.Wrap(err, ErrGetResponseBody.Error())
return Result[R]{}, fmt.Errorf("failed to read response body: %w", err)
}
var data R
err = json.Unmarshal(body, &data)
if err != nil {
return Result[R]{}, errors.Wrap(err, ErrUnmarshalJSON.Error())
return Result[R]{}, fmt.Errorf("failed to unmarshal json: %w", err)
}
return Result[R]{
@@ -117,13 +158,29 @@ func (c *client[R]) handleJSONResponse(res *http.Response) (Result[R], error) {
func (c *client[R]) handleXMLResponse(res *http.Response) (Result[R], error) {
body, err := io.ReadAll(res.Body)
if err != nil {
return Result[R]{}, errors.Wrap(err, ErrGetResponseBody.Error())
return Result[R]{}, fmt.Errorf("failed to read response body: %w", err)
}
if res.StatusCode == http.StatusTooManyRequests {
return Result[R]{}, fmt.Errorf("rate limited by Apple (HTTP %d): %s", res.StatusCode, strings.TrimSpace(string(body)))
}
var data R
_, err = plist.Unmarshal(body, &data)
normalizedBody := normalizeXMLPlistBody(body)
if !looksLikePropertyList(normalizedBody) {
snippet := bodySnippet(body)
if snippet == "" {
return Result[R]{}, fmt.Errorf("unexpected response from Apple (HTTP %d): empty or non-plist body", res.StatusCode)
}
return Result[R]{}, fmt.Errorf("unexpected response from Apple (HTTP %d): %s", res.StatusCode, snippet)
}
_, err = plist.Unmarshal(normalizedBody, &data)
if err != nil {
return Result[R]{}, errors.Wrap(err, ErrUnmarshalXML.Error())
return Result[R]{}, fmt.Errorf("failed to unmarshal xml: %w", err)
}
headers := map[string]string{}
@@ -137,3 +194,105 @@ func (c *client[R]) handleXMLResponse(res *http.Response) (Result[R], error) {
Data: data,
}, nil
}
func normalizeXMLPlistBody(body []byte) []byte {
normalized := bytes.TrimSpace(body)
if len(normalized) == 0 {
return normalized
}
if documentBody := extractDocumentInnerBody(normalized); len(documentBody) > 0 {
normalized = documentBody
}
if embeddedPlist := extractEmbeddedPlist(normalized); len(embeddedPlist) > 0 {
normalized = embeddedPlist
}
if dictBody := extractEmbeddedDict(normalized); len(dictBody) > 0 {
return dictBody
}
if bytes.Contains(normalized, []byte("<key>")) {
return []byte("<dict>" + string(normalized) + "</dict>")
}
return normalized
}
// looksLikePropertyList reports whether body appears to be a (binary or XML)
// property list. Apple occasionally answers with an HTML error page or a plain
// text message; those must not be handed to plist.Unmarshal, which would
// misinterpret a leading "<h..." as an OpenStep hex-data block and fail with an
// opaque "unexpected hex digit" error instead of surfacing Apple's actual response.
func looksLikePropertyList(body []byte) bool {
trimmed := bytes.TrimSpace(body)
if len(trimmed) == 0 {
return false
}
if bytes.HasPrefix(trimmed, []byte("bplist")) {
return true
}
lower := bytes.ToLower(trimmed)
for _, marker := range [][]byte{
[]byte("<?xml"),
[]byte("<plist"),
[]byte("<dict"),
[]byte("<key"),
} {
if bytes.Contains(lower, marker) {
return true
}
}
return false
}
// bodySnippet returns a compact, single-line excerpt of a non-plist response
// body suitable for embedding in an error message. HTML markup is stripped so
// the underlying message (if any) is readable.
func bodySnippet(body []byte) string {
text := htmlTagPattern.ReplaceAll(body, []byte(" "))
snippet := strings.Join(strings.Fields(string(text)), " ")
const maxLen = 200
if len(snippet) > maxLen {
snippet = snippet[:maxLen] + "…"
}
return snippet
}
func extractEmbeddedPlist(body []byte) []byte {
plistMatch := plistXMLPattern.Find(body)
if len(plistMatch) == 0 {
return nil
}
return bytes.TrimSpace(plistMatch)
}
func extractEmbeddedDict(body []byte) []byte {
dictMatch := dictXMLPattern.Find(body)
if len(dictMatch) == 0 {
return nil
}
return bytes.TrimSpace(dictMatch)
}
func extractDocumentInnerBody(body []byte) []byte {
documentMatch := documentXMLPattern.FindSubmatch(body)
if len(documentMatch) < 2 {
return nil
}
documentBody := bytes.TrimSpace(documentMatch[1])
if len(documentBody) == 0 {
return nil
}
return documentBody
}
-81
View File
@@ -1,81 +0,0 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: client.go
// Package http is a generated GoMock package.
package http
import (
io "io"
http "net/http"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockClient is a mock of Client interface.
type MockClient[R interface{}] struct {
ctrl *gomock.Controller
recorder *MockClientMockRecorder[R]
}
// MockClientMockRecorder is the mock recorder for MockClient.
type MockClientMockRecorder[R interface{}] struct {
mock *MockClient[R]
}
// NewMockClient creates a new mock instance.
func NewMockClient[R interface{}](ctrl *gomock.Controller) *MockClient[R] {
mock := &MockClient[R]{ctrl: ctrl}
mock.recorder = &MockClientMockRecorder[R]{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockClient[R]) EXPECT() *MockClientMockRecorder[R] {
return m.recorder
}
// Do mocks base method.
func (m *MockClient[R]) Do(req *http.Request) (*http.Response, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Do", req)
ret0, _ := ret[0].(*http.Response)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Do indicates an expected call of Do.
func (mr *MockClientMockRecorder[R]) Do(req interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockClient[R])(nil).Do), req)
}
// NewRequest mocks base method.
func (m *MockClient[R]) NewRequest(method, url string, body io.Reader) (*http.Request, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewRequest", method, url, body)
ret0, _ := ret[0].(*http.Request)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NewRequest indicates an expected call of NewRequest.
func (mr *MockClientMockRecorder[R]) NewRequest(method, url, body interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewRequest", reflect.TypeOf((*MockClient[R])(nil).NewRequest), method, url, body)
}
// Send mocks base method.
func (m *MockClient[R]) Send(request Request) (Result[R], error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Send", request)
ret0, _ := ret[0].(Result[R])
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Send indicates an expected call of Send.
func (mr *MockClientMockRecorder[R]) Send(request interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*MockClient[R])(nil).Send), request)
}
+120 -91
View File
@@ -1,72 +1,38 @@
package http
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/golang/mock/gomock"
"net/http"
"net/http/httptest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"math/rand"
"net/http"
"go.uber.org/mock/gomock"
)
type JSONResult struct {
Foo string `json:"foo"`
}
type XMLResult struct {
Foo string `plist:"foo"`
}
var _ = Describe("Client", Ordered, func() {
type jsonResult struct {
Foo string `json:"foo"`
}
type xmlResult struct {
Foo string `plist:"foo"`
}
var (
port int
ctx context.Context
cancel context.CancelFunc
ctrl *gomock.Controller
srv *httptest.Server
mockHandler func(w http.ResponseWriter, r *http.Request)
mockCookieJar *MockCookieJar
)
BeforeAll(func() {
ctrl = gomock.NewController(GinkgoT())
port = rand.Intn(59_999-50_000) + 50_000
ctx, cancel = context.WithCancel(context.Background())
mockCookieJar = NewMockCookieJar(ctrl)
http.HandleFunc("/json", func(w http.ResponseWriter, r *http.Request) {
res := []byte("{\"foo\":\"bar\"}")
w.Header().Add("Content-Type", "application/json")
_, err := w.Write(res)
Expect(err).ToNot(HaveOccurred())
})
http.HandleFunc("/xml", func(w http.ResponseWriter, r *http.Request) {
res := []byte("<dict><key>foo</key><string>bar</string></dict>")
w.Header().Add("Content-Type", "application/xml")
_, err := w.Write(res)
Expect(err).ToNot(HaveOccurred())
})
http.HandleFunc("/error", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/random-type")
})
http.HandleFunc("/headers", func(w http.ResponseWriter, r *http.Request) {
err := json.NewEncoder(w).Encode(r.Header)
Expect(err).ToNot(HaveOccurred())
})
go func() {
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
Expect(err).ToNot(HaveOccurred())
<-ctx.Done()
}()
})
AfterAll(func() {
cancel()
mockHandler = func(w http.ResponseWriter, r *http.Request) {}
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mockHandler(w, r)
}))
})
BeforeEach(func() {
@@ -77,17 +43,22 @@ var _ = Describe("Client", Ordered, func() {
})
It("returns request", func() {
sut := NewClient[XMLResult](ClientArgs{})
sut := NewClient[xmlResult](Args{})
req, err := sut.NewRequest("GET", fmt.Sprintf("http://localhost:%d/json", port), nil)
req, err := sut.NewRequest("GET", srv.URL, nil)
Expect(err).ToNot(HaveOccurred())
Expect(req).ToNot(BeNil())
})
It("returns response", func() {
sut := NewClient[XMLResult](ClientArgs{})
mockHandler = func(_w http.ResponseWriter, r *http.Request) {
defer GinkgoRecover()
Expect(r.Header.Get("User-Agent")).To(Equal(DefaultUserAgent))
}
req, err := sut.NewRequest("GET", fmt.Sprintf("http://localhost:%d/json", port), nil)
sut := NewClient[xmlResult](Args{})
req, err := sut.NewRequest("GET", srv.URL, nil)
Expect(err).ToNot(HaveOccurred())
Expect(req).ToNot(BeNil())
@@ -98,25 +69,22 @@ var _ = Describe("Client", Ordered, func() {
When("payload decodes successfully", func() {
When("cookie jar fails to save", func() {
var testErr = errors.New("test")
BeforeEach(func() {
mockCookieJar.EXPECT().
Save().
Return(testErr)
Return(errors.New(""))
})
It("returns error", func() {
sut := NewClient[JSONResult](ClientArgs{
sut := NewClient[jsonResult](Args{
CookieJar: mockCookieJar,
})
_, err := sut.Send(Request{
URL: fmt.Sprintf("http://localhost:%d/json", port),
URL: srv.URL,
Method: MethodGET,
})
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
Expect(err).To(MatchError(ContainSubstring("failed to save cookies")))
Expect(err).To(HaveOccurred())
})
})
@@ -128,11 +96,17 @@ var _ = Describe("Client", Ordered, func() {
})
It("decodes JSON response", func() {
sut := NewClient[JSONResult](ClientArgs{
mockHandler = func(w http.ResponseWriter, _r *http.Request) {
w.Header().Add("Content-Type", "application/json")
_, err := w.Write([]byte("{\"foo\":\"bar\"}"))
Expect(err).ToNot(HaveOccurred())
}
sut := NewClient[jsonResult](Args{
CookieJar: mockCookieJar,
})
res, err := sut.Send(Request{
URL: fmt.Sprintf("http://localhost:%d/json", port),
URL: srv.URL,
Method: MethodGET,
ResponseFormat: ResponseFormatJSON,
Headers: map[string]string{
@@ -150,11 +124,17 @@ var _ = Describe("Client", Ordered, func() {
})
It("decodes XML response", func() {
sut := NewClient[XMLResult](ClientArgs{
mockHandler = func(w http.ResponseWriter, _r *http.Request) {
w.Header().Add("Content-Type", "application/xml")
_, err := w.Write([]byte("<dict><key>foo</key><string>bar</string></dict>"))
Expect(err).ToNot(HaveOccurred())
}
sut := NewClient[xmlResult](Args{
CookieJar: mockCookieJar,
})
res, err := sut.Send(Request{
URL: fmt.Sprintf("http://localhost:%d/xml", port),
URL: srv.URL,
Method: MethodPOST,
ResponseFormat: ResponseFormatXML,
})
@@ -163,28 +143,94 @@ var _ = Describe("Client", Ordered, func() {
Expect(res.Data.Foo).To(Equal("bar"))
})
It("returns error when content type is not supported", func() {
sut := NewClient[XMLResult](ClientArgs{
It("decodes XML response wrapped in an Apple Document envelope", func() {
mockHandler = func(w http.ResponseWriter, _r *http.Request) {
w.Header().Add("Content-Type", "application/xml")
_, err := w.Write([]byte("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<Document xmlns=\"http://www.apple.com/itms/\"><key>foo</key><string>bar</string></Document>"))
Expect(err).ToNot(HaveOccurred())
}
sut := NewClient[xmlResult](Args{
CookieJar: mockCookieJar,
})
res, err := sut.Send(Request{
URL: srv.URL,
Method: MethodPOST,
ResponseFormat: ResponseFormatXML,
})
Expect(err).ToNot(HaveOccurred())
Expect(res.Data.Foo).To(Equal("bar"))
})
It("decodes XML response wrapped in Document/Protocol/plist with nested dict", func() {
mockHandler = func(w http.ResponseWriter, _r *http.Request) {
w.Header().Add("Content-Type", "application/xml")
_, err := w.Write([]byte("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<Document xmlns=\"http://www.apple.com/itms/\"><Protocol><plist version=\"1.0\"><dict><key>nested</key><dict><key>a</key><string>b</string></dict><key>foo</key><string>bar</string></dict></plist></Protocol></Document>"))
Expect(err).ToNot(HaveOccurred())
}
sut := NewClient[xmlResult](Args{
CookieJar: mockCookieJar,
})
res, err := sut.Send(Request{
URL: srv.URL,
Method: MethodPOST,
ResponseFormat: ResponseFormatXML,
})
Expect(err).ToNot(HaveOccurred())
Expect(res.Data.Foo).To(Equal("bar"))
})
It("returns a readable error when Apple responds with an HTML page instead of a plist", func() {
mockHandler = func(w http.ResponseWriter, _r *http.Request) {
w.Header().Add("Content-Type", "text/html")
w.WriteHeader(http.StatusServiceUnavailable)
_, err := w.Write([]byte("<html><body><h1>Service Unavailable</h1></body></html>"))
Expect(err).ToNot(HaveOccurred())
}
sut := NewClient[xmlResult](Args{
CookieJar: mockCookieJar,
})
_, err := sut.Send(Request{
URL: fmt.Sprintf("http://localhost:%d/error", port),
URL: srv.URL,
Method: MethodPOST,
ResponseFormat: ResponseFormatXML,
})
Expect(err).To(HaveOccurred())
Expect(err.Error()).ToNot(ContainSubstring("hex digit"))
Expect(err.Error()).To(ContainSubstring("Service Unavailable"))
})
It("returns error when content type is not supported", func() {
mockHandler = func(w http.ResponseWriter, _r *http.Request) {
w.Header().Add("Content-Type", "application/xyz")
}
sut := NewClient[xmlResult](Args{
CookieJar: mockCookieJar,
})
_, err := sut.Send(Request{
URL: srv.URL,
Method: MethodPOST,
ResponseFormat: "random",
})
Expect(err).To(MatchError(ContainSubstring("unsupported response body content type: random")))
Expect(err).To(HaveOccurred())
})
})
})
When("payload fails to decode", func() {
It("returns error", func() {
sut := NewClient[XMLResult](ClientArgs{
sut := NewClient[xmlResult](Args{
CookieJar: mockCookieJar,
})
_, err := sut.Send(Request{
URL: fmt.Sprintf("http://localhost:%d/error", port),
URL: srv.URL,
Method: MethodPOST,
ResponseFormat: ResponseFormatXML,
Payload: &URLPayload{
@@ -194,24 +240,7 @@ var _ = Describe("Client", Ordered, func() {
},
})
Expect(err).To(MatchError(ContainSubstring(ErrGetPayloadData.Error())))
Expect(err).To(HaveOccurred())
})
})
It("uses default headers", func() {
sut := NewClient[XMLResult](ClientArgs{})
req, err := sut.NewRequest("GET", fmt.Sprintf("http://localhost:%d/headers", port), nil)
Expect(err).ToNot(HaveOccurred())
Expect(req).ToNot(BeNil())
res, err := sut.Do(req)
Expect(err).ToNot(HaveOccurred())
Expect(res).ToNot(BeNil())
headers := http.Header{}
err = json.NewDecoder(res.Body).Decode(&headers)
Expect(err).ToNot(HaveOccurred())
Expect(headers.Get("User-Agent")).To(Equal(DefaultUserAgent))
})
})
+4 -1
View File
@@ -5,5 +5,8 @@ type ResponseFormat string
const (
ResponseFormatJSON ResponseFormat = "json"
ResponseFormatXML ResponseFormat = "xml"
DefaultUserAgent = "Configurator/2.15 (Macintosh; OperatingSystem X 11.0.0; 16G29) AppleWebKit/2603.3.8"
)
const (
DefaultUserAgent = "Configurator/2.17 (Macintosh; OS X 15.2; 24C5089c) AppleWebKit/0620.1.16.11.6"
)
+1 -1
View File
@@ -2,7 +2,7 @@ package http
import "net/http"
//go:generate mockgen -source=cookiejar.go -destination=cookiejar_mock.go -package=http
//go:generate go run go.uber.org/mock/mockgen -source=cookiejar.go -destination=cookiejar_mock.go -package=http
type CookieJar interface {
http.CookieJar
-76
View File
@@ -1,76 +0,0 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: cookiejar.go
// Package http is a generated GoMock package.
package http
import (
http "net/http"
url "net/url"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockCookieJar is a mock of CookieJar interface.
type MockCookieJar struct {
ctrl *gomock.Controller
recorder *MockCookieJarMockRecorder
}
// MockCookieJarMockRecorder is the mock recorder for MockCookieJar.
type MockCookieJarMockRecorder struct {
mock *MockCookieJar
}
// NewMockCookieJar creates a new mock instance.
func NewMockCookieJar(ctrl *gomock.Controller) *MockCookieJar {
mock := &MockCookieJar{ctrl: ctrl}
mock.recorder = &MockCookieJarMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockCookieJar) EXPECT() *MockCookieJarMockRecorder {
return m.recorder
}
// Cookies mocks base method.
func (m *MockCookieJar) Cookies(u *url.URL) []*http.Cookie {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Cookies", u)
ret0, _ := ret[0].([]*http.Cookie)
return ret0
}
// Cookies indicates an expected call of Cookies.
func (mr *MockCookieJarMockRecorder) Cookies(u interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cookies", reflect.TypeOf((*MockCookieJar)(nil).Cookies), u)
}
// Save mocks base method.
func (m *MockCookieJar) Save() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Save")
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockCookieJarMockRecorder) Save() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockCookieJar)(nil).Save))
}
// SetCookies mocks base method.
func (m *MockCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "SetCookies", u, cookies)
}
// SetCookies indicates an expected call of SetCookies.
func (mr *MockCookieJarMockRecorder) SetCookies(u, cookies interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCookies", reflect.TypeOf((*MockCookieJar)(nil).SetCookies), u, cookies)
}
-16
View File
@@ -1,16 +0,0 @@
package http
import "errors"
var (
ErrCreateRequest = errors.New("failed to create HTTP request")
ErrEncodePayloadXML = errors.New("failed to encode XML object")
ErrGetPayloadData = errors.New("failed to get payload data")
ErrGetResponseBody = errors.New("failed to get response body")
ErrRequest = errors.New("failed to send request")
ErrSaveCookie = errors.New("failed to save cookies")
ErrUnmarshalJSON = errors.New("failed to unmarshal JSON data")
ErrUnmarshalXML = errors.New("failed to unmarshal XML data")
ErrUnsupportedContentType = errors.New("unsupported response body content type")
ErrUnsupportedValueType = errors.New("unsupported value type")
)
+2 -1
View File
@@ -1,9 +1,10 @@
package http
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"testing"
)
func TestHTTP(t *testing.T) {
+5 -4
View File
@@ -2,10 +2,11 @@ package http
import (
"bytes"
"github.com/pkg/errors"
"howett.net/plist"
"fmt"
"net/url"
"strconv"
"howett.net/plist"
)
type Payload interface {
@@ -25,7 +26,7 @@ func (p *XMLPayload) data() ([]byte, error) {
err := plist.NewEncoder(buffer).Encode(p.Content)
if err != nil {
return nil, errors.Wrap(err, ErrEncodePayloadXML.Error())
return nil, fmt.Errorf("failed to encode plist: %w", err)
}
return buffer.Bytes(), nil
@@ -41,7 +42,7 @@ func (p *URLPayload) data() ([]byte, error) {
case int:
params.Add(key, strconv.Itoa(val.(int)))
default:
return nil, errors.Errorf("%s: %s", ErrUnsupportedValueType.Error(), t)
return nil, fmt.Errorf("value type is not supported (%s)", t)
}
}
+2 -2
View File
@@ -30,7 +30,7 @@ var _ = Describe("Payload", func() {
}
data, err := sut.data()
Expect(err).To(MatchError(ContainSubstring(ErrUnsupportedValueType.Error())))
Expect(err).To(HaveOccurred())
Expect(data).To(BeNil())
})
})
@@ -57,7 +57,7 @@ var _ = Describe("Payload", func() {
}
data, err := sut.data()
Expect(err).To(MatchError(ContainSubstring("failed to encode XML object")))
Expect(err).To(HaveOccurred())
Expect(data).To(BeNil())
})
})
+20
View File
@@ -1,7 +1,27 @@
package http
import (
"errors"
"strings"
)
var (
ErrHeaderNotFound = errors.New("header not found")
)
type Result[R interface{}] struct {
StatusCode int
Headers map[string]string
Data R
}
func (c *Result[R]) GetHeader(key string) (string, error) {
key = strings.ToLower(key)
for k, v := range c.Headers {
if strings.ToLower(k) == key {
return v, nil
}
}
return "", ErrHeaderNotFound
}
-9
View File
@@ -1,9 +0,0 @@
package keychain
import "github.com/pkg/errors"
var (
ErrGetKeychainItem = errors.New("failed to get item from keyring")
ErrRemoveKeychainItem = errors.New("failed to remove item from keyring")
ErrSetKeychainItem = errors.New("failed to set item in keyring")
)
+3 -3
View File
@@ -1,6 +1,6 @@
package keychain
//go:generate mockgen -source=keychain.go -destination=keychain_mock.go -package keychain
//go:generate go run go.uber.org/mock/mockgen -source=keychain.go -destination=keychain_mock.go -package keychain
type Keychain interface {
Get(key string) ([]byte, error)
Set(key string, data []byte) error
@@ -11,11 +11,11 @@ type keychain struct {
keyring Keyring
}
type KeychainArgs struct {
type Args struct {
Keyring Keyring
}
func NewKeychain(args KeychainArgs) Keychain {
func New(args Args) Keychain {
return &keychain{
keyring: args.Keyring,
}
+2 -2
View File
@@ -1,13 +1,13 @@
package keychain
import (
"github.com/pkg/errors"
"fmt"
)
func (k *keychain) Get(key string) ([]byte, error) {
item, err := k.keyring.Get(key)
if err != nil {
return nil, errors.Wrap(err, ErrGetKeychainItem.Error())
return nil, fmt.Errorf("failed to get item: %w", err)
}
return item.Data, nil
+7 -8
View File
@@ -1,11 +1,12 @@
package keychain
import (
"github.com/99designs/keyring"
"github.com/golang/mock/gomock"
"errors"
"github.com/byteness/keyring"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"go.uber.org/mock/gomock"
)
var _ = Describe("Keychain (Get)", func() {
@@ -18,7 +19,7 @@ var _ = Describe("Keychain (Get)", func() {
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockKeyring = NewMockKeyring(ctrl)
keychain = NewKeychain(KeychainArgs{
keychain = New(Args{
Keyring: mockKeyring,
})
})
@@ -29,18 +30,16 @@ var _ = Describe("Keychain (Get)", func() {
When("keyring returns error", func() {
const testKey = "test-key"
var testErr = errors.New("test error")
BeforeEach(func() {
mockKeyring.EXPECT().
Get(testKey).
Return(keyring.Item{}, testErr)
Return(keyring.Item{}, errors.New(""))
})
It("returns wrapped error", func() {
data, err := keychain.Get(testKey)
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
Expect(err).To(MatchError(ContainSubstring("failed to get item from keyring")))
Expect(err).To(HaveOccurred())
Expect(data).To(BeNil())
})
})
-77
View File
@@ -1,77 +0,0 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: keychain.go
// Package keychain is a generated GoMock package.
package keychain
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockKeychain is a mock of Keychain interface.
type MockKeychain struct {
ctrl *gomock.Controller
recorder *MockKeychainMockRecorder
}
// MockKeychainMockRecorder is the mock recorder for MockKeychain.
type MockKeychainMockRecorder struct {
mock *MockKeychain
}
// NewMockKeychain creates a new mock instance.
func NewMockKeychain(ctrl *gomock.Controller) *MockKeychain {
mock := &MockKeychain{ctrl: ctrl}
mock.recorder = &MockKeychainMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockKeychain) EXPECT() *MockKeychainMockRecorder {
return m.recorder
}
// Get mocks base method.
func (m *MockKeychain) Get(key string) ([]byte, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Get", key)
ret0, _ := ret[0].([]byte)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Get indicates an expected call of Get.
func (mr *MockKeychainMockRecorder) Get(key interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockKeychain)(nil).Get), key)
}
// Remove mocks base method.
func (m *MockKeychain) Remove(key string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Remove", key)
ret0, _ := ret[0].(error)
return ret0
}
// Remove indicates an expected call of Remove.
func (mr *MockKeychainMockRecorder) Remove(key interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockKeychain)(nil).Remove), key)
}
// Set mocks base method.
func (m *MockKeychain) Set(key string, data []byte) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Set", key, data)
ret0, _ := ret[0].(error)
return ret0
}
// Set indicates an expected call of Set.
func (mr *MockKeychainMockRecorder) Set(key, data interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Set", reflect.TypeOf((*MockKeychain)(nil).Set), key, data)
}
+4 -2
View File
@@ -1,11 +1,13 @@
package keychain
import "github.com/pkg/errors"
import (
"fmt"
)
func (k *keychain) Remove(key string) error {
err := k.keyring.Remove(key)
if err != nil {
return errors.Wrap(err, ErrRemoveKeychainItem.Error())
return fmt.Errorf("failed to remove item: %w", err)
}
return nil
+6 -7
View File
@@ -1,10 +1,11 @@
package keychain
import (
"github.com/golang/mock/gomock"
"errors"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"go.uber.org/mock/gomock"
)
var _ = Describe("Keychain (Remove)", func() {
@@ -17,7 +18,7 @@ var _ = Describe("Keychain (Remove)", func() {
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockKeyring = NewMockKeyring(ctrl)
keychain = NewKeychain(KeychainArgs{
keychain = New(Args{
Keyring: mockKeyring,
})
})
@@ -28,18 +29,16 @@ var _ = Describe("Keychain (Remove)", func() {
When("keyring returns error", func() {
const testKey = "test-key"
var testErr = errors.New("test error")
BeforeEach(func() {
mockKeyring.EXPECT().
Remove(testKey).
Return(testErr)
Return(errors.New(""))
})
It("returns wrapped error", func() {
err := keychain.Remove(testKey)
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
Expect(err).To(MatchError(ContainSubstring("failed to remove item from keyring")))
Expect(err).To(HaveOccurred())
})
})
+4 -3
View File
@@ -1,8 +1,9 @@
package keychain
import (
"github.com/99designs/keyring"
"github.com/pkg/errors"
"fmt"
"github.com/byteness/keyring"
)
func (k *keychain) Set(key string, data []byte) error {
@@ -11,7 +12,7 @@ func (k *keychain) Set(key string, data []byte) error {
Data: data,
})
if err != nil {
return errors.Wrap(err, ErrSetKeychainItem.Error())
return fmt.Errorf("failed to set item: %w", err)
}
return nil
+8 -11
View File
@@ -1,11 +1,12 @@
package keychain
import (
"github.com/99designs/keyring"
"github.com/golang/mock/gomock"
"errors"
"github.com/byteness/keyring"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"go.uber.org/mock/gomock"
)
var _ = Describe("Keychain (Set)", func() {
@@ -18,7 +19,7 @@ var _ = Describe("Keychain (Set)", func() {
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockKeyring = NewMockKeyring(ctrl)
keychain = NewKeychain(KeychainArgs{
keychain = New(Args{
Keyring: mockKeyring,
})
})
@@ -29,10 +30,7 @@ var _ = Describe("Keychain (Set)", func() {
When("keyring returns error", func() {
const testKey = "test-key"
var (
testData = []byte("test")
testErr = errors.New("test error")
)
var testData = []byte("test")
BeforeEach(func() {
mockKeyring.EXPECT().
@@ -40,13 +38,12 @@ var _ = Describe("Keychain (Set)", func() {
Key: testKey,
Data: testData,
}).
Return(testErr)
Return(errors.New(""))
})
It("returns wrapped error", func() {
err := keychain.Set(testKey, testData)
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
Expect(err).To(MatchError(ContainSubstring("failed to set item in keyring")))
Expect(err).To(HaveOccurred())
})
})
+2 -1
View File
@@ -1,9 +1,10 @@
package keychain
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"testing"
)
func TestKeychain(t *testing.T) {
+2 -2
View File
@@ -1,8 +1,8 @@
package keychain
import "github.com/99designs/keyring"
import "github.com/byteness/keyring"
//go:generate mockgen -source=keyring.go -destination=keyring_mock.go -package keychain
//go:generate go run go.uber.org/mock/mockgen -source=keyring.go -destination=keyring_mock.go -package keychain
type Keyring interface {
Get(key string) (keyring.Item, error)
Set(item keyring.Item) error
-78
View File
@@ -1,78 +0,0 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: keyring.go
// Package keychain is a generated GoMock package.
package keychain
import (
reflect "reflect"
keyring "github.com/99designs/keyring"
gomock "github.com/golang/mock/gomock"
)
// MockKeyring is a mock of Keyring interface.
type MockKeyring struct {
ctrl *gomock.Controller
recorder *MockKeyringMockRecorder
}
// MockKeyringMockRecorder is the mock recorder for MockKeyring.
type MockKeyringMockRecorder struct {
mock *MockKeyring
}
// NewMockKeyring creates a new mock instance.
func NewMockKeyring(ctrl *gomock.Controller) *MockKeyring {
mock := &MockKeyring{ctrl: ctrl}
mock.recorder = &MockKeyringMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockKeyring) EXPECT() *MockKeyringMockRecorder {
return m.recorder
}
// Get mocks base method.
func (m *MockKeyring) Get(key string) (keyring.Item, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Get", key)
ret0, _ := ret[0].(keyring.Item)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Get indicates an expected call of Get.
func (mr *MockKeyringMockRecorder) Get(key interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockKeyring)(nil).Get), key)
}
// Remove mocks base method.
func (m *MockKeyring) Remove(key string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Remove", key)
ret0, _ := ret[0].(error)
return ret0
}
// Remove indicates an expected call of Remove.
func (mr *MockKeyringMockRecorder) Remove(key interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockKeyring)(nil).Remove), key)
}
// Set mocks base method.
func (m *MockKeyring) Set(item keyring.Item) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Set", item)
ret0, _ := ret[0].(error)
return ret0
}
// Set indicates an expected call of Set.
func (mr *MockKeyringMockRecorder) Set(item interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Set", reflect.TypeOf((*MockKeyring)(nil).Set), item)
}
+2 -1
View File
@@ -1,9 +1,10 @@
package log
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"testing"
)
func TestLog(t *testing.T) {
+5 -4
View File
@@ -1,13 +1,14 @@
package log
import (
"io"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/rs/zerolog/pkgerrors"
"io"
)
//go:generate mockgen -source=logger.go -destination=logger_mock.go -package log
//go:generate go run go.uber.org/mock/mockgen -source=logger.go -destination=logger_mock.go -package log
type Logger interface {
Verbose() *zerolog.Event
Log() *zerolog.Event
@@ -19,12 +20,12 @@ type logger struct {
verbose bool
}
type LoggerArgs struct {
type Args struct {
Verbose bool
Writer io.Writer
}
func NewLogger(args LoggerArgs) Logger {
func NewLogger(args Args) Logger {
internalLogger := log.Logger
level := zerolog.InfoLevel
-77
View File
@@ -1,77 +0,0 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: logger.go
// Package log is a generated GoMock package.
package log
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
zerolog "github.com/rs/zerolog"
)
// MockLogger is a mock of Logger interface.
type MockLogger struct {
ctrl *gomock.Controller
recorder *MockLoggerMockRecorder
}
// MockLoggerMockRecorder is the mock recorder for MockLogger.
type MockLoggerMockRecorder struct {
mock *MockLogger
}
// NewMockLogger creates a new mock instance.
func NewMockLogger(ctrl *gomock.Controller) *MockLogger {
mock := &MockLogger{ctrl: ctrl}
mock.recorder = &MockLoggerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockLogger) EXPECT() *MockLoggerMockRecorder {
return m.recorder
}
// Error mocks base method.
func (m *MockLogger) Error() *zerolog.Event {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Error")
ret0, _ := ret[0].(*zerolog.Event)
return ret0
}
// Error indicates an expected call of Error.
func (mr *MockLoggerMockRecorder) Error() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockLogger)(nil).Error))
}
// Log mocks base method.
func (m *MockLogger) Log() *zerolog.Event {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Log")
ret0, _ := ret[0].(*zerolog.Event)
return ret0
}
// Log indicates an expected call of Log.
func (mr *MockLoggerMockRecorder) Log() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Log", reflect.TypeOf((*MockLogger)(nil).Log))
}
// Verbose mocks base method.
func (m *MockLogger) Verbose() *zerolog.Event {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Verbose")
ret0, _ := ret[0].(*zerolog.Event)
return ret0
}
// Verbose indicates an expected call of Verbose.
func (mr *MockLoggerMockRecorder) Verbose() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verbose", reflect.TypeOf((*MockLogger)(nil).Verbose))
}
+3 -3
View File
@@ -4,8 +4,8 @@ import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/golang/mock/gomock"
"github.com/rs/zerolog"
"go.uber.org/mock/gomock"
)
var _ = Describe("Logger", func() {
@@ -22,7 +22,7 @@ var _ = Describe("Logger", func() {
Context("Verbose logger", func() {
BeforeEach(func() {
logger = NewLogger(LoggerArgs{
logger = NewLogger(Args{
Verbose: true,
Writer: mockWriter,
})
@@ -44,7 +44,7 @@ var _ = Describe("Logger", func() {
Context("Non-verbose logger", func() {
BeforeEach(func() {
logger = NewLogger(LoggerArgs{
logger = NewLogger(Args{
Verbose: false,
Writer: mockWriter,
})
+24 -7
View File
@@ -1,12 +1,14 @@
package log
import (
"github.com/rs/zerolog"
"fmt"
"io"
"os"
"github.com/rs/zerolog"
)
//go:generate mockgen -source=writer.go -destination=writer_mock.go -package log
//go:generate go run go.uber.org/mock/mockgen -source=writer.go -destination=writer_mock.go -package log
type Writer interface {
Write(p []byte) (n int, err error)
WriteLevel(level zerolog.Level, p []byte) (n int, err error)
@@ -24,16 +26,31 @@ func NewWriter() Writer {
}
}
func (l *writer) Write(p []byte) (n int, err error) {
return l.stdOutWriter.Write(p)
func (l *writer) Write(p []byte) (int, error) {
n, err := l.stdOutWriter.Write(p)
if err != nil {
return 0, fmt.Errorf("failed to write data: %w", err)
}
return n, nil
}
func (l *writer) WriteLevel(level zerolog.Level, p []byte) (n int, err error) {
func (l *writer) WriteLevel(level zerolog.Level, p []byte) (int, error) {
switch level {
case zerolog.DebugLevel, zerolog.InfoLevel, zerolog.WarnLevel:
return l.stdOutWriter.Write(p)
n, err := l.stdOutWriter.Write(p)
if err != nil {
return 0, fmt.Errorf("failed to write data: %w", err)
}
return n, nil
case zerolog.ErrorLevel:
return l.stdErrWriter.Write(p)
n, err := l.stdErrWriter.Write(p)
if err != nil {
return 0, fmt.Errorf("failed to write data: %w", err)
}
return n, nil
default:
return len(p), nil
}
-65
View File
@@ -1,65 +0,0 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: writer.go
// Package log is a generated GoMock package.
package log
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
zerolog "github.com/rs/zerolog"
)
// MockWriter is a mock of Writer interface.
type MockWriter struct {
ctrl *gomock.Controller
recorder *MockWriterMockRecorder
}
// MockWriterMockRecorder is the mock recorder for MockWriter.
type MockWriterMockRecorder struct {
mock *MockWriter
}
// NewMockWriter creates a new mock instance.
func NewMockWriter(ctrl *gomock.Controller) *MockWriter {
mock := &MockWriter{ctrl: ctrl}
mock.recorder = &MockWriterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockWriter) EXPECT() *MockWriterMockRecorder {
return m.recorder
}
// Write mocks base method.
func (m *MockWriter) Write(p []byte) (int, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Write", p)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Write indicates an expected call of Write.
func (mr *MockWriterMockRecorder) Write(p interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockWriter)(nil).Write), p)
}
// WriteLevel mocks base method.
func (m *MockWriter) WriteLevel(level zerolog.Level, p []byte) (int, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "WriteLevel", level, p)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// WriteLevel indicates an expected call of WriteLevel.
func (mr *MockWriterMockRecorder) WriteLevel(level, p interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteLevel", reflect.TypeOf((*MockWriter)(nil).WriteLevel), level, p)
}
+1 -1
View File
@@ -1,10 +1,10 @@
package log
import (
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/rs/zerolog"
"go.uber.org/mock/gomock"
)
var _ = Describe("Writer", func() {
-10
View File
@@ -1,10 +0,0 @@
package util
import "github.com/pkg/errors"
var (
ErrEmptyNetworkInterfaces = errors.New("could not find network interfaces")
ErrGetNetworkInterfaces = errors.New("failed to get network interfaces")
ErrInvalidNetworkInterface = errors.New("could not find network interfaces with a valid MAC address")
ErrSlicesLengthMismatch = errors.New("slices have different lengths")
)
-62
View File
@@ -1,62 +0,0 @@
package util
import (
"github.com/pkg/errors"
"golang.org/x/term"
"net"
"path/filepath"
"runtime"
)
//go:generate mockgen -source=machine.go -destination=machine_mock.go -package util
type Machine interface {
MacAddress() (string, error)
HomeDirectory() string
ReadPassword(fd int) ([]byte, error)
}
type machine struct {
os OperatingSystem
}
type MachineArgs struct {
OperatingSystem OperatingSystem
}
func NewMachine(args MachineArgs) Machine {
return &machine{
os: args.OperatingSystem,
}
}
func (*machine) MacAddress() (string, error) {
ifaces, err := net.Interfaces()
if err != nil {
return "", errors.Wrap(err, ErrGetNetworkInterfaces.Error())
}
if len(ifaces) == 0 {
return "", errors.New(ErrEmptyNetworkInterfaces.Error())
}
for _, iface := range ifaces {
addr := iface.HardwareAddr.String()
if addr != "" {
return addr, nil
}
}
return "", errors.New(ErrInvalidNetworkInterface.Error())
}
func (m *machine) HomeDirectory() string {
if runtime.GOOS == "windows" {
return filepath.Join(m.os.Getenv("HOMEDRIVE"), m.os.Getenv("HOMEPATH"))
}
return m.os.Getenv("HOME")
}
func (*machine) ReadPassword(fd int) ([]byte, error) {
return term.ReadPassword(fd)
}
+69
View File
@@ -0,0 +1,69 @@
package machine
import (
"fmt"
"net"
"path/filepath"
"runtime"
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
"golang.org/x/term"
)
//go:generate go run go.uber.org/mock/mockgen -source=machine.go -destination=machine_mock.go -package machine
type Machine interface {
MacAddress() (string, error)
HomeDirectory() string
ReadPassword(fd int) ([]byte, error)
}
type machine struct {
os operatingsystem.OperatingSystem
}
type Args struct {
OS operatingsystem.OperatingSystem
}
func New(args Args) Machine {
return &machine{
os: args.OS,
}
}
func (*machine) MacAddress() (string, error) {
interfaces, err := net.Interfaces()
if err != nil {
return "", fmt.Errorf("failed to get network interfaces: %w", err)
}
if len(interfaces) == 0 {
return "", fmt.Errorf("could not find network interfaces: %w", err)
}
for _, netInterface := range interfaces {
addr := netInterface.HardwareAddr.String()
if addr != "" {
return addr, nil
}
}
return "", fmt.Errorf("could not find network interfaces with a valid mac address: %w", err)
}
func (m *machine) HomeDirectory() string {
if runtime.GOOS == "windows" {
return filepath.Join(m.os.Getenv("HOMEDRIVE"), m.os.Getenv("HOMEPATH"))
}
return m.os.Getenv("HOME")
}
func (*machine) ReadPassword(fd int) ([]byte, error) {
data, err := term.ReadPassword(fd)
if err != nil {
return nil, fmt.Errorf("failed to read password: %w", err)
}
return data, nil
}
@@ -1,24 +1,32 @@
package util
package machine
import (
"github.com/golang/mock/gomock"
"syscall"
"testing"
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"syscall"
"go.uber.org/mock/gomock"
)
func TestMachine(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Machine Suite")
}
var _ = Describe("Machine", func() {
var (
ctrl *gomock.Controller
machine Machine
mockOS *MockOperatingSystem
mockOS *operatingsystem.MockOperatingSystem
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockOS = NewMockOperatingSystem(ctrl)
machine = NewMachine(MachineArgs{
OperatingSystem: mockOS,
mockOS = operatingsystem.NewMockOperatingSystem(ctrl)
machine = New(Args{
OS: mockOS,
})
})
@@ -46,7 +54,7 @@ var _ = Describe("Machine", func() {
When("reading password from stdout", func() {
It("returns error", func() {
_, err := machine.ReadPassword(syscall.Stdout)
Expect(err).To(MatchError(ContainSubstring("inappropriate ioctl for device")))
Expect(err).To(HaveOccurred())
})
})
})
-78
View File
@@ -1,78 +0,0 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: machine.go
// Package util is a generated GoMock package.
package util
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockMachine is a mock of Machine interface.
type MockMachine struct {
ctrl *gomock.Controller
recorder *MockMachineMockRecorder
}
// MockMachineMockRecorder is the mock recorder for MockMachine.
type MockMachineMockRecorder struct {
mock *MockMachine
}
// NewMockMachine creates a new mock instance.
func NewMockMachine(ctrl *gomock.Controller) *MockMachine {
mock := &MockMachine{ctrl: ctrl}
mock.recorder = &MockMachineMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockMachine) EXPECT() *MockMachineMockRecorder {
return m.recorder
}
// HomeDirectory mocks base method.
func (m *MockMachine) HomeDirectory() string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "HomeDirectory")
ret0, _ := ret[0].(string)
return ret0
}
// HomeDirectory indicates an expected call of HomeDirectory.
func (mr *MockMachineMockRecorder) HomeDirectory() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HomeDirectory", reflect.TypeOf((*MockMachine)(nil).HomeDirectory))
}
// MacAddress mocks base method.
func (m *MockMachine) MacAddress() (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "MacAddress")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// MacAddress indicates an expected call of MacAddress.
func (mr *MockMachineMockRecorder) MacAddress() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MacAddress", reflect.TypeOf((*MockMachine)(nil).MacAddress))
}
// ReadPassword mocks base method.
func (m *MockMachine) ReadPassword(fd int) ([]byte, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ReadPassword", fd)
ret0, _ := ret[0].([]byte)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ReadPassword indicates an expected call of ReadPassword.
func (mr *MockMachineMockRecorder) ReadPassword(fd interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadPassword", reflect.TypeOf((*MockMachine)(nil).ReadPassword), fd)
}
+10
View File
@@ -0,0 +1,10 @@
package util
// Must is a helper that wraps a call to a function returning (T, error) and panics if the error is non-nil.
func Must[T any](val T, err error) T {
if err != nil {
panic(err.Error())
}
return val
}
+24
View File
@@ -0,0 +1,24 @@
package util
import (
"errors"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Must", func() {
It("returns current value", func() {
res := Must("value", nil)
Expect(res).To(Equal("value"))
})
It("panics", func() {
defer func() {
r := recover()
Expect(r).To(Equal("test"))
}()
_ = Must("value", errors.New("test"))
})
})
-48
View File
@@ -1,48 +0,0 @@
package util
import "os"
//go:generate mockgen -source=operating_system.go -destination=operating_system_mock.go -package util
type OperatingSystem interface {
Getenv(key string) string
Stat(name string) (os.FileInfo, error)
Getwd() (string, error)
OpenFile(name string, flag int, perm os.FileMode) (*os.File, error)
Remove(name string) error
IsNotExist(err error) bool
MkdirAll(path string, perm os.FileMode) error
}
type operatingSystem struct{}
func NewOperatingSystem() OperatingSystem {
return &operatingSystem{}
}
func (*operatingSystem) Getenv(key string) string {
return os.Getenv(key)
}
func (*operatingSystem) Stat(name string) (os.FileInfo, error) {
return os.Stat(name)
}
func (*operatingSystem) Getwd() (string, error) {
return os.Getwd()
}
func (*operatingSystem) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
return os.OpenFile(name, flag, perm)
}
func (*operatingSystem) Remove(name string) error {
return os.Remove(name)
}
func (*operatingSystem) IsNotExist(err error) bool {
return os.IsNotExist(err)
}
func (*operatingSystem) MkdirAll(path string, perm os.FileMode) error {
return os.MkdirAll(path, perm)
}
-136
View File
@@ -1,136 +0,0 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: operating_system.go
// Package util is a generated GoMock package.
package util
import (
os "os"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockOperatingSystem is a mock of OperatingSystem interface.
type MockOperatingSystem struct {
ctrl *gomock.Controller
recorder *MockOperatingSystemMockRecorder
}
// MockOperatingSystemMockRecorder is the mock recorder for MockOperatingSystem.
type MockOperatingSystemMockRecorder struct {
mock *MockOperatingSystem
}
// NewMockOperatingSystem creates a new mock instance.
func NewMockOperatingSystem(ctrl *gomock.Controller) *MockOperatingSystem {
mock := &MockOperatingSystem{ctrl: ctrl}
mock.recorder = &MockOperatingSystemMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockOperatingSystem) EXPECT() *MockOperatingSystemMockRecorder {
return m.recorder
}
// Getenv mocks base method.
func (m *MockOperatingSystem) Getenv(key string) string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Getenv", key)
ret0, _ := ret[0].(string)
return ret0
}
// Getenv indicates an expected call of Getenv.
func (mr *MockOperatingSystemMockRecorder) Getenv(key interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Getenv", reflect.TypeOf((*MockOperatingSystem)(nil).Getenv), key)
}
// Getwd mocks base method.
func (m *MockOperatingSystem) Getwd() (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Getwd")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Getwd indicates an expected call of Getwd.
func (mr *MockOperatingSystemMockRecorder) Getwd() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Getwd", reflect.TypeOf((*MockOperatingSystem)(nil).Getwd))
}
// IsNotExist mocks base method.
func (m *MockOperatingSystem) IsNotExist(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNotExist", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNotExist indicates an expected call of IsNotExist.
func (mr *MockOperatingSystemMockRecorder) IsNotExist(err interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNotExist", reflect.TypeOf((*MockOperatingSystem)(nil).IsNotExist), err)
}
// MkdirAll mocks base method.
func (m *MockOperatingSystem) MkdirAll(path string, perm os.FileMode) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "MkdirAll", path, perm)
ret0, _ := ret[0].(error)
return ret0
}
// MkdirAll indicates an expected call of MkdirAll.
func (mr *MockOperatingSystemMockRecorder) MkdirAll(path, perm interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MkdirAll", reflect.TypeOf((*MockOperatingSystem)(nil).MkdirAll), path, perm)
}
// OpenFile mocks base method.
func (m *MockOperatingSystem) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "OpenFile", name, flag, perm)
ret0, _ := ret[0].(*os.File)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// OpenFile indicates an expected call of OpenFile.
func (mr *MockOperatingSystemMockRecorder) OpenFile(name, flag, perm interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenFile", reflect.TypeOf((*MockOperatingSystem)(nil).OpenFile), name, flag, perm)
}
// Remove mocks base method.
func (m *MockOperatingSystem) Remove(name string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Remove", name)
ret0, _ := ret[0].(error)
return ret0
}
// Remove indicates an expected call of Remove.
func (mr *MockOperatingSystemMockRecorder) Remove(name interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockOperatingSystem)(nil).Remove), name)
}
// Stat mocks base method.
func (m *MockOperatingSystem) Stat(name string) (os.FileInfo, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Stat", name)
ret0, _ := ret[0].(os.FileInfo)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Stat indicates an expected call of Stat.
func (mr *MockOperatingSystemMockRecorder) Stat(name interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stat", reflect.TypeOf((*MockOperatingSystem)(nil).Stat), name)
}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more