Files
ipatool/cmd/purchase.go
T
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

85 lines
2.0 KiB
Go

package cmd
import (
"errors"
"fmt"
"time"
"github.com/avast/retry-go"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/spf13/cobra"
)
// nolint:wrapcheck
func purchaseCmd() *cobra.Command {
var bundleID string
cmd := &cobra.Command{
Use: "purchase",
Short: "Obtain a license for the app from the App Store",
RunE: func(cmd *cobra.Command, args []string) error {
var lastErr error
var acc appstore.Account
return retry.Do(func() error {
infoResult, err := dependencies.AppStore.AccountInfo()
if err != nil {
return err
}
acc = infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
bagOutput, err := dependencies.AppStore.Bag(appstore.BagInput{})
if err != nil {
return fmt.Errorf("failed to get bag: %w", err)
}
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
Email: acc.Email,
Password: acc.Password,
Endpoint: bagOutput.AuthEndpoint,
})
if err != nil {
return err
}
acc = loginResult.Account
}
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
if err != nil {
return err
}
err = dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: lookupResult.App})
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
return err
}
dependencies.Logger.Log().
Bool("alreadyOwned", errors.Is(err, appstore.ErrLicenseAlreadyExists)).
Bool("success", true).
Send()
return nil
},
retry.LastErrorOnly(true),
retry.DelayType(retry.FixedDelay),
retry.Delay(time.Millisecond),
retry.Attempts(2),
retry.RetryIf(func(err error) bool {
lastErr = err
return errors.Is(err, appstore.ErrPasswordTokenExpired)
}),
)
},
}
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "Bundle identifier of the target iOS app (required)")
_ = cmd.MarkFlagRequired("bundle-identifier")
return cmd
}