refactor: move vendor app credentials and signing keys into config

The provider apps' own identifiers and protocol keys were scattered as
constants across six packages. They are not user secrets and stay baked in so
the tool still works out of the box, but they are now mirrored into the config
so that when a provider rotates one, a user can fix their install with a config
edit instead of waiting for a release.

Moved, each with the current value as the default in internal/config:
  qobuz     mobile_app_id, mobile_app_secret
  tidal     app_client_id, app_client_secret
  deezer    api_key, gateway_key, blowfish_secret
  yandex    sign_key, legacy_mp3_sign_salt
  beatport  app_client_id

applyVendorDefaults backfills any empty value, so configs written before these
keys existed keep working and the clients never have to nil-check them. Each
client reads through a small accessor; the package-level signing helpers
(mobileSignRequest, yandexDownloadSign, legacyDirectURL, deriveGatewayAuthToken
and friends, deriveDeezerBlowfishKey) now take the key as a parameter instead
of closing over a constant. The blowfish secret reaches internal/download
through a field on Downloader set by app.New.

The blowfish key derivation XORs 16 bytes of the secret, so a mistyped override
would have panicked; a wrong-length value is now rejected with a warning and
the built-in value is used. Tests pin the length and that the qobuz mobile
secret is valid hex, since the HKDF step requires it.

Also drops soundcloud.client_id and soundcloud.app_version: soundcloud goes
through yt-dlp, which supplies its own, so nothing read them.

config.toml.example documents each new key as "leave empty unless the vendor
rotates theirs".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
JorenandClaude Opus 5 committed 2026-10-03 17:11:41 +02:00
1 parent b3b6a2eb1d
commit 384f32cd67
13 files changed
+323 -61

No files matched your search

+12 -4
View File
@@ -24,7 +24,6 @@ import (
const (
baseURL = "https://api.beatport.com/v4"
clientID = "ryZ8LuyQVPqbK2mBX2Hwt4qSMtnWuTYSqBPO92yQ"
tokenEndpoint = "/auth/o/token/"
authEndpoint = "/auth/o/authorize/"
loginEndpoint = "/auth/login/"
@@ -376,11 +375,11 @@ func (c *Client) loginPasswordFlow(ctx context.Context) error {
if err != nil {
return err
}
return c.issueToken(ctx, map[string]string{"client_id": clientID, "grant_type": "authorization_code", "code": code})
return c.issueToken(ctx, map[string]string{"client_id": c.appClientID(), "grant_type": "authorization_code", "code": code})
}
func (c *Client) authorize(ctx context.Context) (string, error) {
params := url.Values{"client_id": []string{clientID}, "response_type": []string{"code"}}
params := url.Values{"client_id": []string{c.appClientID()}, "response_type": []string{"code"}}
resp, status, err := c.rawRequest(ctx, http.MethodGet, authEndpoint, params, nil, "", false)
if err != nil {
return "", err
@@ -397,7 +396,7 @@ func (c *Client) authorize(ctx context.Context) (string, error) {
func (c *Client) refresh(ctx context.Context) error {
b := &c.cfg.Session.Beatport
return c.issueToken(ctx, map[string]string{"client_id": clientID, "grant_type": "refresh_token", "refresh_token": b.RefreshToken})
return c.issueToken(ctx, map[string]string{"client_id": c.appClientID(), "grant_type": "refresh_token", "refresh_token": b.RefreshToken})
}
func (c *Client) issueToken(ctx context.Context, payload map[string]string) error {
@@ -846,3 +845,12 @@ func cloneValues(in url.Values) url.Values {
}
return out
}
// appClientID reads the vendor OAuth app credential from config, falling back
// to the built-in default.
func (c *Client) appClientID() string {
if v := strings.TrimSpace(c.cfg.Session.Beatport.AppClientID); v != "" {
return v
}
return config.DefaultBeatportAppClientID
}
+31 -15
View File
@@ -33,8 +33,6 @@ var (
mediaURL = "https://media.deezer.com/v1/get_url"
pipeURL = "https://pipe.deezer.com/api"
authURL = "https://auth.deezer.com/login/renew"
apiKey = "4VCYIJUCDLOUELGD1V8WBVYBNVDYOXEWSLLZDONGBBDFVXTZJRXPR29JRLQFO6ZE"
gatewayDec = "VBK1FSUEXHTSDBJJ"
deezerUAPool = []string{
"Deezer/9.0.11.4 (Android; 14; Mobile; us) Xiaomi Redmi Note 7",
"Deezer/9.0.11.4 (Android; 14; Mobile; us) Samsung SM-G991B",
@@ -499,7 +497,7 @@ func (c *Client) loginWithCredentials(ctx context.Context, email, password strin
if err != nil {
return err
}
authToken, err := deriveGatewayAuthToken(mobileToken)
authToken, err := deriveGatewayAuthToken(c.gatewayKey(), mobileToken)
if err != nil {
return err
}
@@ -509,7 +507,7 @@ func (c *Client) loginWithCredentials(ctx context.Context, email, password strin
}
c.sid = jsonutil.FirstNonEmpty(c.sid, sid)
encryptedPassword, err := encryptPassword(mobileToken, password)
encryptedPassword, err := encryptPassword(c.gatewayKey(), mobileToken, password)
if err != nil {
return err
}
@@ -528,7 +526,7 @@ func (c *Client) loginWithCredentials(ctx context.Context, email, password strin
"password": encryptedPassword,
}
params := url.Values{}
params.Set("api_key", apiKey)
params.Set("api_key", c.apiKey())
params.Set("sid", c.sid)
params.Set("method", "mobile_userAuth")
params.Set("output", "3")
@@ -737,7 +735,7 @@ func (c *Client) bootstrapSID(ctx context.Context) (string, error) {
if err != nil {
return "", err
}
authToken, err := deriveGatewayAuthToken(mobileToken)
authToken, err := deriveGatewayAuthToken(c.gatewayKey(), mobileToken)
if err != nil {
return "", err
}
@@ -749,7 +747,7 @@ func (c *Client) mobileAuth(ctx context.Context) (string, error) {
return "", err
}
params := url.Values{}
params.Set("api_key", apiKey)
params.Set("api_key", c.apiKey())
params.Set("output", "3")
params.Set("method", "mobile_auth")
params.Set("network", randomHexN(32))
@@ -802,7 +800,7 @@ func (c *Client) apiCheckToken(ctx context.Context, authToken string) (string, e
return "", err
}
params := url.Values{}
params.Set("api_key", apiKey)
params.Set("api_key", c.apiKey())
params.Set("method", "api_checkToken")
params.Set("auth_token", authToken)
params.Set("output", "3")
@@ -865,7 +863,7 @@ func (c *Client) mobileUserAutolog(ctx context.Context) error {
payload["refresh_token"] = strings.TrimSpace(c.refresh)
}
params := url.Values{}
params.Set("api_key", apiKey)
params.Set("api_key", c.apiKey())
params.Set("sid", c.sid)
params.Set("output", "3")
params.Set("input", "3")
@@ -1075,8 +1073,10 @@ func (c *Client) refreshLicenseFromPipe(ctx context.Context) error {
return nil
}
func deriveGatewayAuthToken(mobileToken string) (string, error) {
dec, err := decryptMobileToken(mobileToken)
// deriveGatewayAuthToken and friends take gatewayKey explicitly so the key
// comes from config rather than a package constant.
func deriveGatewayAuthToken(gatewayKey, mobileToken string) (string, error) {
dec, err := decryptMobileToken(gatewayKey, mobileToken)
if err != nil {
return "", err
}
@@ -1092,19 +1092,19 @@ func deriveGatewayAuthToken(mobileToken string) (string, error) {
return hex.EncodeToString(enc), nil
}
func decryptMobileToken(mobileToken string) ([]byte, error) {
func decryptMobileToken(gatewayKey, mobileToken string) ([]byte, error) {
b, err := hex.DecodeString(strings.TrimSpace(mobileToken))
if err != nil {
return nil, err
}
return aesECBDecrypt([]byte(gatewayDec), b)
return aesECBDecrypt([]byte(gatewayKey), b)
}
func encryptPassword(mobileToken, password string) (string, error) {
func encryptPassword(gatewayKey, mobileToken, password string) (string, error) {
if strings.TrimSpace(password) == "" {
return "", errors.New("missing deezer password")
}
dec, err := decryptMobileToken(mobileToken)
dec, err := decryptMobileToken(gatewayKey, mobileToken)
if err != nil {
return "", err
}
@@ -1513,3 +1513,19 @@ func enrichAlbumImage(meta map[string]any) {
"original": cover,
}
}
// apiKey and gatewayKey read the vendor protocol keys from config, falling
// back to the built-in defaults.
func (c *Client) apiKey() string {
if v := strings.TrimSpace(c.cfg.Session.Deezer.APIKey); v != "" {
return v
}
return config.DefaultDeezerAPIKey
}
func (c *Client) gatewayKey() string {
if v := strings.TrimSpace(c.cfg.Session.Deezer.GatewayKey); v != "" {
return v
}
return config.DefaultDeezerGatewayKey
}
+1 -1
View File
@@ -728,7 +728,7 @@ func TestMobileUserAutologIncludesRefreshToken(t *testing.T) {
func testMobileToken(t *testing.T) string {
t.Helper()
plain := []byte(strings.Repeat("A", 64) + strings.Repeat("B", 16) + strings.Repeat("C", 16))
enc, err := aesECBEncrypt([]byte(gatewayDec), plain)
enc, err := aesECBEncrypt([]byte(config.DefaultDeezerGatewayKey), plain)
if err != nil {
t.Fatalf("aesECBEncrypt() error = %v", err)
}
+28 -12
View File
@@ -40,8 +40,6 @@ import (
const baseURL = "https://www.qobuz.com/api.json/0.2"
const (
mobileAppID = "312369995"
mobileAppSecret = "e79f8b9be485692b0e5f9dd895826368"
mobileUserAgent = "Dalvik/2.1.0 (Linux; U; Android 9; Nexus 6P Build/PQ3A.190801.002) QobuzMobileAndroid/9.7.0.3-b26022717"
mobileAppVersion = "9.7.0.3"
mobileSessionProf = "qbz-1"
@@ -1046,11 +1044,11 @@ func (c *Client) ensureMobileSession(ctx context.Context) error {
func (c *Client) mobileLogin(ctx context.Context, username, password string) error {
ts := time.Now().Unix()
params := url.Values{}
params.Set("app_id", mobileAppID)
params.Set("app_id", c.mobileAppID())
params.Set("username", username)
params.Set("password", password)
params.Set("request_ts", strconv.FormatInt(ts, 10))
params.Set("request_sig", mobileSignRequest("oauth2/login", []kv{{"password", password}, {"username", username}}, ts))
params.Set("request_sig", mobileSignRequest(c.mobileAppSecret(), "oauth2/login", []kv{{"password", password}, {"username", username}}, ts))
reqURL := baseURL + "/oauth2/login?" + params.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
@@ -1088,9 +1086,9 @@ func (c *Client) mobileLogin(ctx context.Context, username, password string) err
func (c *Client) mobileStartSession(ctx context.Context) error {
ts := time.Now().Unix()
params := url.Values{}
params.Set("app_id", mobileAppID)
params.Set("app_id", c.mobileAppID())
params.Set("request_ts", strconv.FormatInt(ts, 10))
params.Set("request_sig", mobileSignRequest("session/start", []kv{{"profile", mobileSessionProf}}, ts))
params.Set("request_sig", mobileSignRequest(c.mobileAppSecret(), "session/start", []kv{{"profile", mobileSessionProf}}, ts))
reqURL := baseURL + "/session/start?" + params.Encode()
form := url.Values{}
@@ -1132,12 +1130,12 @@ func (c *Client) mobileStartSession(ctx context.Context) error {
func (c *Client) mobileGetFileURL(ctx context.Context, trackID string, formatID int) (*mobileFileURL, error) {
ts := time.Now().Unix()
params := url.Values{}
params.Set("app_id", mobileAppID)
params.Set("app_id", c.mobileAppID())
params.Set("track_id", trackID)
params.Set("format_id", strconv.Itoa(formatID))
params.Set("intent", "stream")
params.Set("request_ts", strconv.FormatInt(ts, 10))
params.Set("request_sig", mobileSignRequest("file/url", []kv{{"format_id", strconv.Itoa(formatID)}, {"intent", "stream"}, {"track_id", trackID}}, ts))
params.Set("request_sig", mobileSignRequest(c.mobileAppSecret(), "file/url", []kv{{"format_id", strconv.Itoa(formatID)}, {"intent", "stream"}, {"track_id", trackID}}, ts))
reqURL := baseURL + "/file/url?" + params.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
if err != nil {
@@ -1259,7 +1257,7 @@ func (c *Client) mobileDownloadSegment(ctx context.Context, sourceURL string) ([
func (c *Client) setMobileHeaders(req *http.Request) {
req.Header.Set("User-Agent", mobileUserAgent)
req.Header.Set("X-App-Id", mobileAppID)
req.Header.Set("X-App-Id", c.mobileAppID())
req.Header.Set("X-App-Version", mobileAppVersion)
req.Header.Set("X-Device-Platform", "android")
req.Header.Set("X-Device-Model", "Nexus 6P")
@@ -1272,7 +1270,9 @@ func (c *Client) setMobileHeaders(req *http.Request) {
}
}
func mobileSignRequest(endpoint string, params []kv, ts int64) string {
// mobileSignRequest signs a mobile API request. appSecret comes from config
// (Client.mobileAppSecret) so a rotation can be fixed without a rebuild.
func mobileSignRequest(appSecret, endpoint string, params []kv, ts int64) string {
method := strings.ReplaceAll(endpoint, "/", "")
sortKVs(params)
var sb strings.Builder
@@ -1282,7 +1282,7 @@ func mobileSignRequest(endpoint string, params []kv, ts int64) string {
sb.WriteString(p.Value)
}
sb.WriteString(strconv.FormatInt(ts, 10))
sb.WriteString(mobileAppSecret)
sb.WriteString(appSecret)
h := md5.Sum([]byte(sb.String()))
return hex.EncodeToString(h[:])
}
@@ -1321,7 +1321,7 @@ func (c *Client) mobileDeriveTrackKey(encryptedKey string) ([]byte, error) {
// A non-hex secret used to be swallowed and HKDF keyed on nil, which
// derives a wrong KEK and yields silently corrupt audio rather than an
// error.
secretKey, err := hex.DecodeString(mobileAppSecret)
secretKey, err := hex.DecodeString(c.mobileAppSecret())
if err != nil {
return nil, fmt.Errorf("decode mobile app secret: %w", err)
}
@@ -1491,3 +1491,19 @@ func readU24BE(data []byte, off int) uint32 {
}
return uint32(data[off])<<16 | uint32(data[off+1])<<8 | uint32(data[off+2])
}
// mobileAppID and mobileAppSecret read the vendor mobile app credentials from
// config, falling back to the built-in defaults.
func (c *Client) mobileAppID() string {
if v := strings.TrimSpace(c.cfg.Session.Qobuz.MobileAppID); v != "" {
return v
}
return config.DefaultQobuzMobileAppID
}
func (c *Client) mobileAppSecret() string {
if v := strings.TrimSpace(c.cfg.Session.Qobuz.MobileAppSecret); v != "" {
return v
}
return config.DefaultQobuzMobileAppSecret
}
+19 -4
View File
@@ -28,8 +28,6 @@ const (
lyricsAPIv1 = "https://api.tidal.com/v1"
openAPIV2 = "https://openapi.tidal.com/v2"
authURL = "https://auth.tidal.com/v1/oauth2"
clientID = "fX2JxdmntZWK0ixT"
clientSec = "1Nm5AfDAjxrgJFJbKNWLeAyKGVGmINuXPPLHVXAvxAg="
tidalRequestAttempts = 3
)
@@ -146,7 +144,7 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {
}
form := url.Values{}
form.Set("client_id", clientID)
form.Set("client_id", c.appClientID())
form.Set("refresh_token", refresh)
form.Set("grant_type", "refresh_token")
form.Set("scope", "r_usr+w_usr+w_sub")
@@ -972,7 +970,7 @@ func (c *Client) apiPost(ctx context.Context, endpoint string, form url.Values,
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", "streamrip-go/0.1")
if basicAuth {
auth := base64.StdEncoding.EncodeToString([]byte(clientID + ":" + clientSec))
auth := base64.StdEncoding.EncodeToString([]byte(c.appClientID() + ":" + c.appClientSecret()))
req.Header.Set("Authorization", "Basic "+auth)
}
return req, nil
@@ -1004,3 +1002,20 @@ func tidalImageMap(cover string) map[string]any {
"original": base + "/1280x1280.jpg",
}
}
// appClientID and appClientSecret read the vendor OAuth app credentials from
// config, falling back to the built-in defaults. Config is the source of truth
// so a rotation can be fixed without a rebuild.
func (c *Client) appClientID() string {
if v := strings.TrimSpace(c.cfg.Session.Tidal.AppClientID); v != "" {
return v
}
return config.DefaultTidalAppClientID
}
func (c *Client) appClientSecret() string {
if v := strings.TrimSpace(c.cfg.Session.Tidal.AppClientSecret); v != "" {
return v
}
return config.DefaultTidalAppClientSecret
}
+28 -12
View File
@@ -30,12 +30,10 @@ import (
)
const (
baseURL = "https://api.music.yandex.net"
desktopClientHeader = "YandexMusicDesktopAppWindows/5.13.2"
desktopOrigin = "music-application://desktop"
requestAttempts = 3
desktopWindowsSignKey = "kzqU4XhfCaY6B6JTHODeq5"
legacyMP3SignSalt = "XGRlBW9FXlekgbPrRHuSiA"
baseURL = "https://api.music.yandex.net"
desktopClientHeader = "YandexMusicDesktopAppWindows/5.13.2"
desktopOrigin = "music-application://desktop"
requestAttempts = 3
)
var ErrMissingYandexToken = errors.New("missing yandex access_token")
@@ -345,7 +343,7 @@ func (c *Client) getLegacyDownloadable(ctx context.Context, trackID string) (*pr
if err != nil {
return nil, err
}
directURL, err := legacyDirectURL(xmlInfo)
directURL, err := legacyDirectURL(c.legacyMP3Salt(), xmlInfo)
if err != nil {
return nil, err
}
@@ -366,7 +364,7 @@ func (c *Client) getLegacyDownloadable(ctx context.Context, trackID string) (*pr
func (c *Client) getDesktopDownloadable(ctx context.Context, trackID string, quality int, transport string) (*provider.Downloadable, error) {
qualityParam, codecs := downloadRequestProfile(quality)
sign, ts := yandexDownloadSign(trackID, qualityParam, codecs, transport)
sign, ts := yandexDownloadSign(c.signKey(), trackID, qualityParam, codecs, transport)
params := url.Values{}
params.Set("trackId", trackID)
params.Set("codecs", strings.Join(codecs, ","))
@@ -432,11 +430,11 @@ func (c *Client) fetchLegacyXML(ctx context.Context, xmlURL string) (*legacyDown
return &out, nil
}
func legacyDirectURL(info *legacyDownloadInfoXML) (string, error) {
func legacyDirectURL(salt string, info *legacyDownloadInfoXML) (string, error) {
if info == nil || info.Host == "" || info.Path == "" || info.TS == "" || info.S == "" {
return "", errors.New("invalid yandex legacy xml payload")
}
sum := md5.Sum([]byte(legacyMP3SignSalt + strings.TrimPrefix(info.Path, "/") + info.S))
sum := md5.Sum([]byte(salt + strings.TrimPrefix(info.Path, "/") + info.S))
return "https://" + info.Host + "/get-mp3/" + hex.EncodeToString(sum[:]) + "/" + info.TS + info.Path, nil
}
@@ -944,9 +942,11 @@ func isExplicit(raw map[string]any) bool {
return jsonutil.BoolFromAny(raw["explicit"])
}
func yandexDownloadSign(trackID, quality string, codecs []string, transport string) (string, int64) {
// yandexDownloadSign signs a download request. signKey comes from config
// (Client.signKey) so a rotation can be fixed without a rebuild.
func yandexDownloadSign(signKey, trackID, quality string, codecs []string, transport string) (string, int64) {
ts := time.Now().Unix()
mac := hmac.New(sha256.New, []byte(desktopWindowsSignKey))
mac := hmac.New(sha256.New, []byte(signKey))
_, _ = mac.Write([]byte(strconv.FormatInt(ts, 10) + trackID + quality + strings.Join(codecs, "") + transport))
return strings.TrimRight(base64.StdEncoding.EncodeToString(mac.Sum(nil)), "="), ts
}
@@ -1027,3 +1027,19 @@ func firstPositiveInt(vals ...int) int {
}
return 0
}
// signKey and legacyMP3Salt read the vendor request-signing keys from config,
// falling back to the built-in defaults.
func (c *Client) signKey() string {
if v := strings.TrimSpace(c.cfg.Session.Yandex.SignKey); v != "" {
return v
}
return config.DefaultYandexSignKey
}
func (c *Client) legacyMP3Salt() string {
if v := strings.TrimSpace(c.cfg.Session.Yandex.LegacyMP3SignSalt); v != "" {
return v
}
return config.DefaultYandexLegacyMP3Salt
}
+2 -2
View File
@@ -15,7 +15,7 @@ import (
)
func TestYandexDownloadSignMatchesCapturedFormat(t *testing.T) {
sign, ts := yandexDownloadSign("32038184", "lossless", []string{"flac", "aac", "he-aac", "mp3", "flac-mp4", "aac-mp4", "he-aac-mp4"}, "raw")
sign, ts := yandexDownloadSign(config.DefaultYandexSignKey, "32038184", "lossless", []string{"flac", "aac", "he-aac", "mp3", "flac-mp4", "aac-mp4", "he-aac-mp4"}, "raw")
if ts <= 0 {
t.Fatalf("timestamp = %d", ts)
}
@@ -168,7 +168,7 @@ func TestGetMetadataTrackUsesModernTracksEndpoint(t *testing.T) {
}
func TestLegacyDirectURLBuildsPlayableMP3URL(t *testing.T) {
url, err := legacyDirectURL(&legacyDownloadInfoXML{
url, err := legacyDirectURL(config.DefaultYandexLegacyMP3Salt, &legacyDownloadInfoXML{
Host: "example.test",
Path: "/abc123",
TS: "1234567890",