diff --git a/translate/appversion.go b/translate/appversion.go new file mode 100644 index 0000000..faa90e2 --- /dev/null +++ b/translate/appversion.go @@ -0,0 +1,193 @@ +/* + * @Author: Vincent Young + * @Date: 2026-10-08 00:00:00 + * @LastEditors: Vincent Yang + * @LastEditTime: 2026-10-08 00:00:00 + * @FilePath: /DLX/translate/appversion.go + * @Telegram: https://t.me/missuo + * @GitHub: https://github.com/missuo + * + * Copyright © 2024 by Vincent, All Rights Reserved. + */ + +package translate + +import ( + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "strings" + "sync" + "time" +) + +// DeepL's iOS app on the US App Store. Apple's public lookup endpoint is +// key-less and returns, in results[0].version, the marketing version the iOS +// client reports as CFBundleShortVersionString in its User-Agent and +// app_information.app_version. +// +// DeepL rate-limits clients whose iOS TLS fingerprint and advertised app +// version are inconsistent (see OwO-Network/DLX#236): once the pinned version +// goes stale, *every* request is answered with HTTP 429. Resolving the version +// at runtime keeps that profile coherent without a rebuild. +const ( + deeplAppStoreTrackID = 1552407475 + deeplAppStoreBundleID = "com.linguee.DeepLMobileTranslator" + deeplAppStoreSeller = "DeepL SE" +) + +// deeplAppStoreLookupURL is a var rather than a const so tests can point it at +// a local server. +var deeplAppStoreLookupURL = fmt.Sprintf( + "https://itunes.apple.com/lookup?id=%d&country=us", deeplAppStoreTrackID, +) + +// Lookup policy, mirroring the approach of tisfeng/Easydict#1341. The App Store +// is only contacted lazily, on the first translation after the cache expires — +// never at startup — so an unreachable App Store cannot delay or prevent the +// process from serving. +const ( + appVersionCacheTTL = 24 * time.Hour + appVersionRetryBackoff = 15 * time.Minute + appVersionLookupTimeout = 3 * time.Second +) + +// appVersionHTTPClient is shared so repeat lookups reuse the connection pool. +// It is separate from the translation client: no TLS fingerprint, no cookies, +// no proxy. +var appVersionHTTPClient = &http.Client{Timeout: appVersionLookupTimeout} + +// appVersionProvider resolves and caches the DeepL iOS version this client +// advertises. The zero value is ready to use. +type appVersionProvider struct { + mu sync.Mutex + version string // last successfully resolved version, "" if none + fetchedAt time.Time // when version was resolved + attemptedAt time.Time // when a lookup was last started +} + +var iosAppVersionProvider appVersionProvider + +// currentIOSAppVersion returns the DeepL iOS marketing version to advertise in +// both the User-Agent and app_information. A successful lookup is cached for +// appVersionCacheTTL; a failed one is not retried for appVersionRetryBackoff. +// Any failure falls back to the last resolved version, or to the pinned +// iosAppVersion if none was ever resolved, so behaviour degrades to the +// previous hardcoded value instead of failing. +func currentIOSAppVersion() string { + p := &iosAppVersionProvider + // The lock is held across the lookup so a burst of cold requests performs + // at most one App Store query; callers block for no longer than + // appVersionLookupTimeout and then share the result. + p.mu.Lock() + defer p.mu.Unlock() + + now := time.Now() + if isValidAppVersion(p.version) && now.Sub(p.fetchedAt) < appVersionCacheTTL { + return p.version + } + if !p.attemptedAt.IsZero() && now.Sub(p.attemptedAt) < appVersionRetryBackoff { + return p.cachedOrFallback() + } + + p.attemptedAt = now + version, err := fetchLatestIOSAppVersion() + if err == nil && !isValidAppVersion(version) { + err = fmt.Errorf("implausible version %q", version) + } + if err != nil { + fallback := p.cachedOrFallback() + log.Printf("DeepL iOS app version lookup failed, falling back to %s: %v", fallback, err) + return fallback + } + p.version = version + p.fetchedAt = now + return version +} + +// cachedOrFallback prefers a previously resolved version over the pinned +// constant: a version that was current recently is a better guess than one +// hardcoded at build time. +func (p *appVersionProvider) cachedOrFallback() string { + if isValidAppVersion(p.version) { + return p.version + } + return iosAppVersion +} + +// appStoreLookup is the subset of Apple's lookup response we consume. +type appStoreLookup struct { + ResultCount int `json:"resultCount"` + Results []appStoreResult `json:"results"` +} + +type appStoreResult struct { + TrackID int64 `json:"trackId"` + BundleID string `json:"bundleId"` + ArtistName string `json:"artistName"` + Version string `json:"version"` +} + +// fetchLatestIOSAppVersion queries Apple's lookup API for the DeepL iOS app. +func fetchLatestIOSAppVersion() (string, error) { + resp, err := appVersionHTTPClient.Get(deeplAppStoreLookupURL) + if err != nil { + return "", err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("app store lookup: unexpected status %d", resp.StatusCode) + } + // Cap the read so a misbehaving endpoint cannot make us allocate without + // bound. + body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return "", err + } + + var lookup appStoreLookup + if err := json.Unmarshal(body, &lookup); err != nil { + return "", fmt.Errorf("app store lookup: %w", err) + } + return lookup.deepLVersion() +} + +// deepLVersion validates that the lookup result really is the DeepL iOS app +// and returns its marketing version. A wrong or unexpected answer is rejected +// rather than advertised, which keeps the fallback path honest. +func (l appStoreLookup) deepLVersion() (string, error) { + if l.ResultCount != 1 || len(l.Results) != 1 { + return "", fmt.Errorf("app store lookup: expected 1 result, got %d", len(l.Results)) + } + r := l.Results[0] + if r.TrackID != deeplAppStoreTrackID || r.BundleID != deeplAppStoreBundleID || r.ArtistName != deeplAppStoreSeller { + return "", fmt.Errorf("app store lookup: unexpected app %d/%q/%q", r.TrackID, r.BundleID, r.ArtistName) + } + if !isValidAppVersion(r.Version) { + return "", fmt.Errorf("app store lookup: implausible version %q", r.Version) + } + return r.Version, nil +} + +// isValidAppVersion accepts the dotted numeric forms DeepL ships ("26.42", +// "26.52.1", "1.2.3.4") and rejects everything else. +func isValidAppVersion(version string) bool { + parts := strings.Split(version, ".") + if len(parts) < 2 || len(parts) > 4 { + return false + } + for _, part := range parts { + if part == "" { + return false + } + for _, r := range part { + if r < '0' || r > '9' { + return false + } + } + } + return true +} diff --git a/translate/appversion_test.go b/translate/appversion_test.go new file mode 100644 index 0000000..a69f097 --- /dev/null +++ b/translate/appversion_test.go @@ -0,0 +1,195 @@ +/* + * @Author: Vincent Young + * @Date: 2026-10-08 00:00:00 + * @LastEditors: Vincent Yang + * @LastEditTime: 2026-10-08 00:00:00 + * @FilePath: /DLX/translate/appversion_test.go + * @Telegram: https://t.me/missuo + * @GitHub: https://github.com/missuo + * + * Copyright © 2024 by Vincent, All Rights Reserved. + */ + +package translate + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "testing" +) + +func TestIsValidAppVersion(t *testing.T) { + tests := []struct { + version string + want bool + }{ + {"26.42", true}, + {"26.53", true}, + {"26.52.1", true}, + {"1.2.3.4", true}, + {"", false}, + {"26", false}, + {"26.42.1.2.3", false}, + {"26..42", false}, + {".26.42", false}, + {"26.42.", false}, + {"26.42-beta", false}, + {"v26.42", false}, + {"26.4 2", false}, + } + for _, tt := range tests { + if got := isValidAppVersion(tt.version); got != tt.want { + t.Errorf("isValidAppVersion(%q) = %v, want %v", tt.version, got, tt.want) + } + } +} + +func TestAppStoreLookupDeepLVersion(t *testing.T) { + result := func(trackID int64, bundleID, artist, version string) appStoreResult { + return appStoreResult{TrackID: trackID, BundleID: bundleID, ArtistName: artist, Version: version} + } + valid := result(deeplAppStoreTrackID, deeplAppStoreBundleID, deeplAppStoreSeller, "26.53") + + tests := []struct { + name string + lookup appStoreLookup + want string + wantErr bool + }{ + {"valid", appStoreLookup{ResultCount: 1, Results: []appStoreResult{valid}}, "26.53", false}, + {"no results", appStoreLookup{ResultCount: 0}, "", true}, + {"two results", appStoreLookup{ResultCount: 2, Results: []appStoreResult{valid, valid}}, "", true}, + {"wrong track id", appStoreLookup{ResultCount: 1, Results: []appStoreResult{result(1, deeplAppStoreBundleID, deeplAppStoreSeller, "26.53")}}, "", true}, + {"wrong bundle", appStoreLookup{ResultCount: 1, Results: []appStoreResult{result(deeplAppStoreTrackID, "com.example.app", deeplAppStoreSeller, "26.53")}}, "", true}, + {"wrong seller", appStoreLookup{ResultCount: 1, Results: []appStoreResult{result(deeplAppStoreTrackID, deeplAppStoreBundleID, "Someone Else", "26.53")}}, "", true}, + {"implausible version", appStoreLookup{ResultCount: 1, Results: []appStoreResult{result(deeplAppStoreTrackID, deeplAppStoreBundleID, deeplAppStoreSeller, "latest")}}, "", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := tt.lookup.deepLVersion() + if (err != nil) != tt.wantErr { + t.Fatalf("deepLVersion() error = %v, wantErr %v", err, tt.wantErr) + } + if got != tt.want { + t.Fatalf("deepLVersion() = %q, want %q", got, tt.want) + } + }) + } +} + +// lookupServer serves an App Store lookup response with the given version and +// counts how many times it was queried. +func lookupServer(t *testing.T, version string, status int) (*httptest.Server, func() int) { + t.Helper() + var ( + mu sync.Mutex + requests int + ) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + requests++ + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if status != http.StatusOK { + return + } + _ = json.NewEncoder(w).Encode(appStoreLookup{ + ResultCount: 1, + Results: []appStoreResult{{ + TrackID: deeplAppStoreTrackID, + BundleID: deeplAppStoreBundleID, + ArtistName: deeplAppStoreSeller, + Version: version, + }}, + }) + })) + t.Cleanup(srv.Close) + count := func() int { + mu.Lock() + defer mu.Unlock() + return requests + } + return srv, count +} + +// resetProvider points the resolver at url and clears its cache for the test. +func resetProvider(t *testing.T, url string) { + t.Helper() + originalURL := deeplAppStoreLookupURL + iosAppVersionProvider = appVersionProvider{} + t.Cleanup(func() { + deeplAppStoreLookupURL = originalURL + iosAppVersionProvider = appVersionProvider{} + }) + deeplAppStoreLookupURL = url +} + +func TestCurrentIOSAppVersionUsesLookupAndCaches(t *testing.T) { + srv, count := lookupServer(t, "26.99", http.StatusOK) + resetProvider(t, srv.URL) + + for i := 0; i < 3; i++ { + if got := currentIOSAppVersion(); got != "26.99" { + t.Fatalf("currentIOSAppVersion() = %q, want %q", got, "26.99") + } + } + if got := count(); got != 1 { + t.Fatalf("lookup served %d requests, want 1 (result must be cached)", got) + } +} + +func TestCurrentIOSAppVersionFallsBackAndBacksOff(t *testing.T) { + srv, count := lookupServer(t, "", http.StatusInternalServerError) + resetProvider(t, srv.URL) + + for i := 0; i < 3; i++ { + if got := currentIOSAppVersion(); got != iosAppVersion { + t.Fatalf("currentIOSAppVersion() = %q, want fallback %q", got, iosAppVersion) + } + } + if got := count(); got != 1 { + t.Fatalf("lookup served %d requests, want 1 (failure must back off)", got) + } +} + +func TestCurrentIOSAppVersionFallsBackOnMalformedBody(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "not json") + })) + t.Cleanup(srv.Close) + resetProvider(t, srv.URL) + + if got := currentIOSAppVersion(); got != iosAppVersion { + t.Fatalf("currentIOSAppVersion() = %q, want fallback %q", got, iosAppVersion) + } +} + +func TestCurrentIOSAppVersionSingleFlight(t *testing.T) { + srv, count := lookupServer(t, "26.99", http.StatusOK) + resetProvider(t, srv.URL) + + const goroutines = 16 + results := make([]string, goroutines) + var wg sync.WaitGroup + for i := 0; i < goroutines; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + results[i] = currentIOSAppVersion() + }(i) + } + wg.Wait() + + for i, got := range results { + if got != "26.99" { + t.Fatalf("goroutine %d got %q, want %q", i, got, "26.99") + } + } + if got := count(); got != 1 { + t.Fatalf("lookup served %d requests, want 1 (concurrent callers must share one lookup)", got) + } +} diff --git a/translate/translate.go b/translate/translate.go index 9aebc0c..549c1e7 100644 --- a/translate/translate.go +++ b/translate/translate.go @@ -42,8 +42,11 @@ import ( // traffic hard; oneshot lives on a separate pool and accepts the literal // header `Authorization: None` for free requests. // -// Request shape reverse-engineered from DeepL iOS 26.42 (build 5443737, -// bundle com.linguee.DeepLMobileTranslator, IPA Info.plist + ItaClient.framework): +// Request shape reverse-engineered from the DeepL iOS client (bundle +// com.linguee.DeepLMobileTranslator, IPA Info.plist + ItaClient.framework). +// The advertised app version is resolved at runtime from the App Store +// (appversion.go) so a DeepL release cannot silently invalidate the profile; +// iosAppVersion below is only the fallback. // // Transport // ItaClient oneshot uses Ktor Darwin engine @@ -73,7 +76,9 @@ const ( oneshotFreeEndpoint = "https://oneshot-free.www.deepl.com/v1/translate" oneshotProEndpoint = "https://oneshot-pro.www.deepl.com/v1/translate" - // Pinned to DeepL iOS IPA (CFBundleShortVersionString / CFBundleVersion). + // Fallback DeepL iOS version, used only when the runtime App Store + // lookup fails (appversion.go). The build number stays pinned because + // Apple's lookup API does not expose CFBundleVersion. iosAppVersion = "26.42" iosAppBuild = "5443737" @@ -305,12 +310,13 @@ func newOneshotClient(proxyURL string) (*req.Client, error) { // - TLS ClientHello ≈ real iOS (utls HelloIOS_Auto) // - Cookie jar shared like URLSession's HTTPCookieStorage // - Common headers = what URLSession attaches by default - // Per-request headers (Authorization, x-app-*) are set in callOneshot. + // Per-request headers (Authorization, User-Agent, x-app-*) are set in + // callOneshot; the client-level User-Agent is only a default. client := req.C(). SetTLSFingerprintIOS(). SetCookieJar(sharedCookieJar()). SetTimeout(oneshotTimeout). - SetUserAgent(iosUserAgent()). + SetUserAgent(iosUserAgent(iosAppVersion)). // URLSession default Accept-Encoding for data tasks. SetCommonHeader("Accept-Encoding", "gzip, deflate, br"). SetCommonHeader("Accept", "*/*"). @@ -332,10 +338,10 @@ func newOneshotClient(proxyURL string) (*req.Client, error) { // Darwin stack emits (CFBundleName/CFBundleShortVersionString + CFNetwork // + Darwin). Do NOT invent alternate formats (e.g. embedding the bundle // ID) — mismatched UA + iOS TLS fingerprint is a cheap ban signal. -func iosUserAgent() string { +func iosUserAgent(appVersion string) string { return fmt.Sprintf( "DeepL/%s CFNetwork/%s Darwin/%s", - iosAppVersion, iosCFNetworkVersion, iosDarwinVersion, + appVersion, iosCFNetworkVersion, iosDarwinVersion, ) } @@ -343,7 +349,9 @@ func iosUserAgent() string { // For anonymous traffic bearerToken is empty and we send the literal // header `Authorization: None` — matching ItaClient.LoginNone. Omitting // that header puts the request on a different server-side auth branch. -func callOneshot(endpoint string, body []byte, bearerToken, proxyURL string) (gjson.Result, int, error) { +// appVersion is the value the request body advertises; the same value is +// echoed in the User-Agent so TLS, UA and app_information stay consistent. +func callOneshot(endpoint string, body []byte, bearerToken, proxyURL, appVersion string) (gjson.Result, int, error) { client, err := getOneshotClient(proxyURL) if err != nil { return gjson.Result{}, 0, err @@ -359,6 +367,7 @@ func callOneshot(endpoint string, body []byte, bearerToken, proxyURL string) (gj DisableAutoReadResponse(). SetHeader("Content-Type", "application/json"). SetHeader("Authorization", authValue). + SetHeader("User-Agent", iosUserAgent(appVersion)). // ClientInfos.appHeaders (Util/ClientInfos.swift) — only these three // x-app-* keys exist in the iOS binary. SetHeader("x-app-os-version", iosOSVersion). @@ -435,6 +444,10 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro // official v2 API does — ignored upstream. _ = tagHandling + // Resolve the advertised version once per request so the User-Agent and + // app_information always agree; the lookup itself is cached (appversion.go). + appVersion := currentIOSAppVersion() + reqStruct := oneshotRequest{ Text: []string{text}, TargetLang: resolvedTarget, @@ -444,7 +457,7 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro AppInformation: appInformation{ OS: "iOS", OSVersion: iosOSVersion, - AppVersion: iosAppVersion, + AppVersion: appVersion, AppBuild: iosAppBuild, InstanceID: instanceID, }, @@ -457,7 +470,7 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro } id := time.Now().UnixMilli() - result, status, err := callOneshot(endpoint, bodyBytes, dlSession, proxyURL) + result, status, err := callOneshot(endpoint, bodyBytes, dlSession, proxyURL, appVersion) if err != nil { // Map upstream timeouts to 504 so callers can distinguish "DeepL // took too long" from other 503 failure modes (DNS, TLS, etc.).