Files
AppleSync/internal/apple/token.go
T
2026-11-26 15:11:41 +01:00

126 lines
3.0 KiB
Go

package apple
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"regexp"
"strings"
)
const browserUA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0 Safari/537.36"
var (
jsAssetRe = regexp.MustCompile(`/assets/index[^"']+\.js`)
jwtRe = regexp.MustCompile(`eyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+`)
)
// FetchWebToken scrapes a public Apple Music web-player token from the
// music.apple.com JavaScript bundle. The token is required for the catalog API
// but does not identify a user account.
func FetchWebToken(ctx context.Context, client *http.Client) (string, error) {
body, err := fetchText(ctx, client, "https://music.apple.com")
if err != nil {
return "", fmt.Errorf("apple token: %w", err)
}
assets := uniqueStrings(jsAssetRe.FindAllString(body, -1))
if len(assets) == 0 {
return "", fmt.Errorf("apple token: no JavaScript asset found")
}
var best string
bestScore := -1
for i, asset := range assets {
if i >= 8 {
break
}
assetURL := "https://music.apple.com" + asset
script, err := fetchText(ctx, client, assetURL)
if err != nil {
continue
}
for _, candidate := range uniqueStrings(jwtRe.FindAllString(script, -1)) {
score := tokenScore(candidate)
if score > bestScore {
bestScore = score
best = candidate
}
}
if bestScore >= 20 {
break
}
}
if best == "" || bestScore <= 0 {
return "", fmt.Errorf("apple token: no web token found in JavaScript bundle")
}
return best, nil
}
func tokenScore(token string) int {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return 0
}
header := decodeJWTPart(parts[0])
payload := decodeJWTPart(parts[1])
score := 0
if header["kid"] == "WebPlayKid" {
score += 10
}
if payload["iss"] == "AMPWebPlay" {
score += 10
}
return score
}
func decodeJWTPart(part string) map[string]any {
data, err := base64.RawURLEncoding.DecodeString(part)
if err != nil {
// Some tokens may include padding.
data, err = base64.URLEncoding.DecodeString(part)
if err != nil {
return nil
}
}
var out map[string]any
if err := json.Unmarshal(data, &out); err != nil {
return nil
}
return out
}
func fetchText(ctx context.Context, client *http.Client, rawURL string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return "", err
}
req.Header.Set("User-Agent", browserUA)
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return "", fmt.Errorf("%s: status %d", rawURL, resp.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20))
if err != nil {
return "", err
}
return string(data), nil
}
func uniqueStrings(values []string) []string {
seen := make(map[string]bool, len(values))
out := make([]string, 0, len(values))
for _, value := range values {
if !seen[value] {
seen[value] = true
out = append(out, value)
}
}
return out
}