Compare commits

..
7 Commits
Author SHA1 Message Date
Vincent Young 54158cddd5 ci(release): generate release notes with contributor thanks
Build the release body from GitHub's generate-notes API (What's Changed,
New Contributors, Full Changelog) and append a Thanks section naming
each PR author who is not a repository collaborator or a bot. Grant the
Release job contents: write explicitly.
2026-10-08 03:32:57 -07:00
Vincent Young 6ff3cfac2f fix(translate): map Chinese source codes to generic zh
DeepL only accepts the generic "zh" as a source hint; zh-Hans and
zh-Hant are target-only script variants and are silently ignored when
sent as source_lang. Ambiguous mixed-script Chinese therefore fell back
to auto-detection, was detected as English and echoed back untranslated.

ZH, ZH-HANS and ZH-HANT now resolve to "zh" for source_lang while the
target mapping is unchanged. /v2/translate also reads source_lang (JSON
and form) instead of always auto-detecting. Adds resolveSourceLang and
resolveTargetLang tests.

Fixes #239
2026-10-08 03:32:57 -07:00
Vincent Young 11c94403ec build: bump Go toolchain to 1.27
Raise go.mod to 1.27.0 and the Dockerfile builder to golang:1.27. Pin
setup-go in the CI and release workflows to 1.27.1 so they match the
module's minimum instead of lagging behind it (previously 1.24.2 vs
go 1.25.0).
2026-10-08 03:25:28 -07:00
Vincent Young ef3979d915 fix(translate): resolve DeepL iOS app version at runtime (#238)
Merge branch 'pr-238' (JounQin/DLX:feat/dynamic-ios-app-version).

Look up the current DeepL iOS version from Apple's App Store lookup API
lazily, cache it for 24h and fall back to the pinned constant on any
failure. Conflict in translate/translate.go resolved by keeping the PR's
fallback wording and the 26.52 value from #237.

Fixes #236
2026-10-08 03:22:32 -07:00
holtwood 9f76381eb4 fix(translate): bump pinned iOS app version to 26.52 (#237)
DeepL's current iOS release is 26.52. With 26.42 pinned, every request to
oneshot-free returns 429 ("your IP has been blocked by DeepL temporarily"),
regardless of the IP it is sent from.

Built from source, same host, back to back:

  HEAD (26.42) -> 429
  this change  -> 200 with a correct translation

iosAppBuild is left as it was: the A/B above only changes the version string,
and the older build number did not prevent translation. If the 26.52 IPA
reports a different CFBundleVersion, that value should replace it.
2026-10-08 03:20:23 -07:00
JounQin 5e7e2129c0 fix(translate): resolve DeepL iOS app version at runtime
Pinning iosAppVersion made the impersonated iOS client profile go stale as
soon as DeepL shipped an update: an iOS TLS fingerprint paired with a version
DeepL no longer considers current is an inconsistent profile, and every
oneshot request is then answered with HTTP 429 (OwO-Network/DLX#236).

Resolve the version lazily from Apple's public lookup API instead, cache it
for 24h (15m retry backoff, 3s timeout) and fall back to the pinned 26.42 when
the lookup fails, so a failure degrades to the previous behaviour instead of
breaking startup or a request. The User-Agent and app_information.app_version
always carry the same resolved value, since a UA/body mismatch is itself a ban
signal. app_build stays pinned because the lookup API does not expose
CFBundleVersion.

Approach modelled on tisfeng/Easydict#1341. No new dependencies.

Refs: https://github.com/OwO-Network/DLX/issues/236
2026-10-08 10:09:14 +00:00
Vincent Young 66090baa7e fix(translate): align oneshot client with DeepL iOS URLSession profile
Replace the fabricated iOS 27.0 UA/os_version (which DeepL rate-limits and
can temp-ban) with a coherent iOS 26 profile matching the 26.42 IPA: CFNetwork
User-Agent, app_information, and ClientInfos x-app-* headers over HelloIOS TLS.
2026-08-06 10:18:52 +08:00
9 changed files with 630 additions and 37 deletions
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v4 uses: actions/setup-go@v4
with: with:
go-version: '1.24.2' go-version: '1.27.1'
- name: Install golint - name: Install golint
run: go install golang.org/x/lint/golint@latest run: go install golang.org/x/lint/golint@latest
+65 -2
View File
@@ -32,7 +32,7 @@ jobs:
- uses: actions/setup-go@v4 - uses: actions/setup-go@v4
with: with:
go-version: "1.24.2" go-version: "1.27.1"
- name: Build - name: Build
env: env:
@@ -58,16 +58,79 @@ jobs:
needs: Build needs: Build
if: startsWith(github.ref, 'refs/tags/v') if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
contents: write
steps: steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Download artifacts - name: Download artifacts
uses: actions/download-artifact@v4 uses: actions/download-artifact@v4
with: with:
path: dist path: dist
merge-multiple: true merge-multiple: true
# Start from GitHub's auto-generated notes (What's Changed / New
# Contributors / Full Changelog) and add a "Thanks" section naming every
# PR author who is not a repository collaborator or a bot.
- name: Generate release notes
shell: bash
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
prev=$(git describe --tags --abbrev=0 "${TAG}^" 2>/dev/null || true)
args=(-f tag_name="$TAG")
if [ -n "$prev" ]; then
args+=(-f previous_tag_name="$prev")
fi
gh api "repos/${GITHUB_REPOSITORY}/releases/generate-notes" \
"${args[@]}" --jq .body > notes.md
declare -A prs=()
while read -r login num; do
prs["$login"]="${prs[$login]:-}${prs[$login]:+, }#${num}"
done < <(grep -oE 'by @[A-Za-z0-9_-]+ in https://github\.com/[^ ]+/pull/[0-9]+' notes.md \
| sed -E 's#by @([^ ]+) in .*/pull/([0-9]+)#\1 \2#' | sort -u -k1,1 -k2,2n)
thanks=()
for login in "${!prs[@]}"; do
case "$login" in
dependabot*|renovate*|github-actions*|*\[bot\]) continue ;;
esac
perm=$(gh api "repos/${GITHUB_REPOSITORY}/collaborators/${login}/permission" \
--jq .permission 2>/dev/null || echo none)
case "$perm" in
admin|maintain|write) continue ;;
esac
thanks+=("* Thanks @${login} for ${prs[$login]}")
done
if [ "${#thanks[@]}" -gt 0 ]; then
if grep -q '^\*\*Full Changelog' notes.md; then
{
sed '/^\*\*Full Changelog/,$d' notes.md
printf '## Thanks\n'
printf '%s\n' "${thanks[@]}" | sort
printf '\n'
grep '^\*\*Full Changelog' notes.md
} > notes.out
else
{
cat notes.md
printf '\n## Thanks\n'
printf '%s\n' "${thanks[@]}" | sort
} > notes.out
fi
mv notes.out notes.md
fi
echo "::group::Release notes"; cat notes.md; echo "::endgroup::"
- name: Release - name: Release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v1
with: with:
draft: false draft: false
generate_release_notes: true body_path: notes.md
files: dist/* files: dist/*
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.25 AS builder FROM golang:1.27 AS builder
WORKDIR /go/src/github.com/OwO-Network/DLX WORKDIR /go/src/github.com/OwO-Network/DLX
COPY . . COPY . .
RUN go get -d -v ./ RUN go get -d -v ./
+1 -1
View File
@@ -1,6 +1,6 @@
module github.com/OwO-Network/DLX module github.com/OwO-Network/DLX
go 1.25.0 go 1.27.0
require ( require (
github.com/andybalholm/brotli v1.2.2 github.com/andybalholm/brotli v1.2.2
+5 -1
View File
@@ -240,14 +240,17 @@ func Router(cfg *Config) *gin.Engine {
proxyURL := cfg.Proxy proxyURL := cfg.Proxy
var translateText string var translateText string
var sourceLang string
var targetLang string var targetLang string
translateText = c.PostForm("text") translateText = c.PostForm("text")
sourceLang = c.PostForm("source_lang")
targetLang = c.PostForm("target_lang") targetLang = c.PostForm("target_lang")
if translateText == "" || targetLang == "" { if translateText == "" || targetLang == "" {
var jsonData struct { var jsonData struct {
Text []string `json:"text"` Text []string `json:"text"`
SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"` TargetLang string `json:"target_lang"`
} }
@@ -260,10 +263,11 @@ func Router(cfg *Config) *gin.Engine {
} }
translateText = strings.Join(jsonData.Text, "\n") translateText = strings.Join(jsonData.Text, "\n")
sourceLang = jsonData.SourceLang
targetLang = jsonData.TargetLang targetLang = jsonData.TargetLang
} }
result, err := translate.TranslateByDLX("", targetLang, translateText, "", proxyURL, "") result, err := translate.TranslateByDLX(sourceLang, targetLang, translateText, "", proxyURL, "")
if err != nil { if err != nil {
log.Printf("Translation failed: %s", err) log.Printf("Translation failed: %s", err)
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
+193
View File
@@ -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
}
+195
View File
@@ -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)
}
}
+81
View File
@@ -0,0 +1,81 @@
/*
* @Author: Vincent Young
* @Date: 2026-10-08 00:00:00
* @LastEditors: Vincent Yang
* @LastEditTime: 2026-10-08 00:00:00
* @FilePath: /DLX/translate/lang_test.go
* @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo
*
* Copyright © 2024 by Vincent, All Rights Reserved.
*/
package translate
import "testing"
func TestResolveSourceLang(t *testing.T) {
cases := []struct {
in string
want string
}{
{"", ""},
{"auto", ""},
{"AUTO", ""},
{"EN", "en"},
{"en-us", "en-US"},
{"PT", "pt"},
{"PT-BR", "pt-BR"},
// DeepL only accepts the generic "zh" as a source hint; the
// script variants are target-only (#239).
{"ZH", "zh"},
{"zh", "zh"},
{"ZH-HANS", "zh"},
{"zh-hant", "zh"},
{"JA", "ja"},
{"ES-419", "es-419"},
{"DE-CH", "de-CH"},
}
for _, c := range cases {
got, err := resolveSourceLang(c.in)
if err != nil {
t.Errorf("resolveSourceLang(%q) error: %v", c.in, err)
continue
}
if got != c.want {
t.Errorf("resolveSourceLang(%q) = %q, want %q", c.in, got, c.want)
}
}
if _, err := resolveSourceLang("xx"); err == nil {
t.Errorf("resolveSourceLang(%q) expected error", "xx")
}
}
func TestResolveTargetLang(t *testing.T) {
cases := []struct {
in string
want string
}{
{"EN", "en-US"},
{"en-gb", "en-GB"},
{"PT", "pt-BR"},
{"ZH", "zh-Hans"},
{"ZH-HANS", "zh-Hans"},
{"zh-hant", "zh-Hant"},
}
for _, c := range cases {
got, err := resolveTargetLang(c.in)
if err != nil {
t.Errorf("resolveTargetLang(%q) error: %v", c.in, err)
continue
}
if got != c.want {
t.Errorf("resolveTargetLang(%q) = %q, want %q", c.in, got, c.want)
}
}
for _, bad := range []string{"", "auto", "xx"} {
if _, err := resolveTargetLang(bad); err == nil {
t.Errorf("resolveTargetLang(%q) expected error", bad)
}
}
}
+88 -31
View File
@@ -42,28 +42,60 @@ import (
// traffic hard; oneshot lives on a separate pool and accepts the literal // traffic hard; oneshot lives on a separate pool and accepts the literal
// header `Authorization: None` for free requests. // header `Authorization: None` for free requests.
// //
// Request shape below is reverse-engineered from DeepL iOS 26.42 // Request shape reverse-engineered from the DeepL iOS client (bundle
// (build 5443737, bundle com.linguee.DeepLMobileTranslator): // com.linguee.DeepLMobileTranslator, IPA Info.plist + ItaClient.framework).
// - Free URL → https://oneshot-free.www.deepl.com/v1/translate // The advertised app version is resolved at runtime from the App Store
// - Pro URL → https://oneshot-pro.www.deepl.com/v1/translate // (appversion.go) so a DeepL release cannot silently invalidate the profile;
// (iOS also constructs https://oneshot. + .pro.deepl.com/v1/translate) // iosAppVersion below is only the fallback.
// - Body → OneShotTranslator + ItaClient.AppInformation //
// - Headers → ClientInfos.appHeaders (x-app-*) + Authorization // Transport
// - usage_type → ItaClient.OneShotUsageType.translate // ItaClient oneshot uses Ktor Darwin engine
// (io.ktor.client.engine.darwin.KtorNSURLSessionDelegate) → real
// URLSession TLS. We approximate that ClientHello with utls HelloIOS.
//
// Free URL → https://oneshot-free.www.deepl.com/v1/translate
// Pro URL → https://oneshot. + <cell> + .pro.deepl.com/v1/translate
// (we keep oneshot-pro.www as the free-tier Pro fallback)
//
// Headers (ClientInfos.appHeaders + LoginNone):
// Authorization: None (ItaClient.LoginNone)
// x-app-os-version (UIDevice.systemVersion)
// x-app-instance-id (stable install UUID)
// x-app-session-id (session UUID)
// User-Agent (URLSession / CFNetwork product form)
// Accept / Accept-Encoding (URLSession defaults)
//
// Body (ItaClient OneShotTranslationRequestDto + AppInformation):
// text[], target_lang, source_lang?, usage_type, app_information
// usage_type ∈ {translate, ocr, voiceforconversations}
//
// DeepL rate-limits / temporarily bans clients whose TLS + UA + app_information
// story is inconsistent (e.g. iOS TLS fingerprint + "iOS 27.0" in the UA when
// 27 is not a shipping OS). Keep every field on one coherent iOS profile.
const ( const (
oneshotFreeEndpoint = "https://oneshot-free.www.deepl.com/v1/translate" oneshotFreeEndpoint = "https://oneshot-free.www.deepl.com/v1/translate"
oneshotProEndpoint = "https://oneshot-pro.www.deepl.com/v1/translate" oneshotProEndpoint = "https://oneshot-pro.www.deepl.com/v1/translate"
// Pinned to DeepL iOS IPA (Info.plist CFBundleShortVersionString / // Fallback DeepL iOS version, used only when the runtime App Store
// CFBundleVersion). Keep app_information in lockstep with the TLS // lookup fails (appversion.go). Keep it tracking DeepL's current App Store
// fingerprint and User-Agent so the request tells one consistent story. // release: a stale version is answered with HTTP 429 on every request
iosAppVersion = "26.42" // ("your IP has been blocked by DeepL temporarily"), from any IP. The build
// number stays pinned because Apple's lookup API does not expose
// CFBundleVersion.
iosAppVersion = "26.52"
iosAppBuild = "5443737" iosAppBuild = "5443737"
iosBundleID = "com.linguee.DeepLMobileTranslator"
// Stable OS version reported in app_information + x-app-os-version. // Reported OS version for app_information.os_version + x-app-os-version.
// HelloIOS_Auto does not pin a specific iOS minor; pin a fixed value // IPA is built against iphoneos26.5 (DTPlatformVersion). Must be a real
// so UA / x-app-os-version / app_information stay consistent. // shipping major — a future value (e.g. 27.0) combined with an iOS TLS
iosOSVersion = "27.0" // fingerprint is rejected with HTTP 429 and can temp-ban the IP.
iosOSVersion = "26.0"
// CFNetwork / Darwin versions that accompany URLSession User-Agents on
// the same OS generation as DTPlatformVersion 26.x (build machine
// BuildMachineOSBuild 25E246 → Darwin 25).
iosCFNetworkVersion = "3826.600.41"
iosDarwinVersion = "25.0.0"
// oneshot enforces a 1500-character hard cap on the total length of // oneshot enforces a 1500-character hard cap on the total length of
// the `text` array for anonymous traffic (same limit the Chrome // the `text` array for anonymous traffic (same limit the Chrome
@@ -163,7 +195,8 @@ var targetLangMap = map[string]string{
// sourceLangMap is what the API accepts as `source_lang`. It is a // sourceLangMap is what the API accepts as `source_lang`. It is a
// superset of targetLangMap: EN and PT are first-class source codes // superset of targetLangMap: EN and PT are first-class source codes
// mapping to the generic "en"/"pt". // mapping to the generic "en"/"pt", and the Chinese codes all map to the
// generic "zh".
var sourceLangMap = func() map[string]string { var sourceLangMap = func() map[string]string {
m := make(map[string]string, len(targetLangMap)+2) m := make(map[string]string, len(targetLangMap)+2)
for k, v := range targetLangMap { for k, v := range targetLangMap {
@@ -171,6 +204,13 @@ var sourceLangMap = func() map[string]string {
} }
m["EN"] = "en" m["EN"] = "en"
m["PT"] = "pt" m["PT"] = "pt"
// DeepL's source codes are the generic language forms. zh-Hans/zh-Hant
// are target-only script variants: sent as a source hint they are
// silently ignored, so ambiguous mixed-script Chinese fell back to
// auto-detection and came back untranslated (#239).
m["ZH"] = "zh"
m["ZH-HANS"] = "zh"
m["ZH-HANT"] = "zh"
return m return m
}() }()
@@ -277,16 +317,22 @@ func getOneshotClient(proxyURL string) (*req.Client, error) {
} }
func newOneshotClient(proxyURL string) (*req.Client, error) { func newOneshotClient(proxyURL string) (*req.Client, error) {
// iOS TLS ClientHello via utls HelloIOS_Auto. Headers are set per // Match ItaClient's Ktor Darwin / URLSession profile:
// request in callOneshot to match ClientInfos.appHeaders rather than // - TLS ClientHello ≈ real iOS (utls HelloIOS_Auto)
// a browser navigation profile. // - Cookie jar shared like URLSession's HTTPCookieStorage
// - Common headers = what URLSession attaches by default
// Per-request headers (Authorization, User-Agent, x-app-*) are set in
// callOneshot; the client-level User-Agent is only a default.
client := req.C(). client := req.C().
SetTLSFingerprintIOS(). SetTLSFingerprintIOS().
SetCookieJar(sharedCookieJar()). SetCookieJar(sharedCookieJar()).
SetTimeout(oneshotTimeout). SetTimeout(oneshotTimeout).
SetUserAgent(iosUserAgent()). SetUserAgent(iosUserAgent(iosAppVersion)).
// URLSession default Accept-Encoding for data tasks.
SetCommonHeader("Accept-Encoding", "gzip, deflate, br"). SetCommonHeader("Accept-Encoding", "gzip, deflate, br").
SetCommonHeader("Accept", "*/*"). SetCommonHeader("Accept", "*/*").
// Preferred language list — mirrors a US-locale device; DeepL
// does not hard-require a specific value for free oneshot.
SetCommonHeader("Accept-Language", "en-US,en;q=0.9") SetCommonHeader("Accept-Language", "en-US,en;q=0.9")
if proxyURL != "" { if proxyURL != "" {
@@ -299,12 +345,14 @@ func newOneshotClient(proxyURL string) (*req.Client, error) {
return client, nil return client, nil
} }
// iosUserAgent approximates the CFNetwork-style UA the DeepL iOS app // iosUserAgent is the URLSession product-style User-Agent the app's Ktor
// advertises via ClientInfos.userAgent. // Darwin stack emits (CFBundleName/CFBundleShortVersionString + CFNetwork
func iosUserAgent() string { // + Darwin). Do NOT invent alternate formats (e.g. embedding the bundle
// ID) — mismatched UA + iOS TLS fingerprint is a cheap ban signal.
func iosUserAgent(appVersion string) string {
return fmt.Sprintf( return fmt.Sprintf(
"DeepL/%s (%s; build:%s; iOS %s)", "DeepL/%s CFNetwork/%s Darwin/%s",
iosAppVersion, iosBundleID, iosAppBuild, iosOSVersion, appVersion, iosCFNetworkVersion, iosDarwinVersion,
) )
} }
@@ -312,12 +360,15 @@ func iosUserAgent() string {
// For anonymous traffic bearerToken is empty and we send the literal // For anonymous traffic bearerToken is empty and we send the literal
// header `Authorization: None` — matching ItaClient.LoginNone. Omitting // header `Authorization: None` — matching ItaClient.LoginNone. Omitting
// that header puts the request on a different server-side auth branch. // 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) client, err := getOneshotClient(proxyURL)
if err != nil { if err != nil {
return gjson.Result{}, 0, err return gjson.Result{}, 0, err
} }
// LoginNone → literal "None"; LoginPro/Free → "Bearer <access_token>".
authValue := "None" authValue := "None"
if bearerToken != "" { if bearerToken != "" {
authValue = "Bearer " + bearerToken authValue = "Bearer " + bearerToken
@@ -327,7 +378,9 @@ func callOneshot(endpoint string, body []byte, bearerToken, proxyURL string) (gj
DisableAutoReadResponse(). DisableAutoReadResponse().
SetHeader("Content-Type", "application/json"). SetHeader("Content-Type", "application/json").
SetHeader("Authorization", authValue). SetHeader("Authorization", authValue).
// ClientInfos.appHeaders from DeepL iOS (Util/ClientInfos.swift). 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). SetHeader("x-app-os-version", iosOSVersion).
SetHeader("x-app-instance-id", instanceID). SetHeader("x-app-instance-id", instanceID).
SetHeader("x-app-session-id", sessionID). SetHeader("x-app-session-id", sessionID).
@@ -402,6 +455,10 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro
// official v2 API does — ignored upstream. // official v2 API does — ignored upstream.
_ = tagHandling _ = 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{ reqStruct := oneshotRequest{
Text: []string{text}, Text: []string{text},
TargetLang: resolvedTarget, TargetLang: resolvedTarget,
@@ -411,7 +468,7 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro
AppInformation: appInformation{ AppInformation: appInformation{
OS: "iOS", OS: "iOS",
OSVersion: iosOSVersion, OSVersion: iosOSVersion,
AppVersion: iosAppVersion, AppVersion: appVersion,
AppBuild: iosAppBuild, AppBuild: iosAppBuild,
InstanceID: instanceID, InstanceID: instanceID,
}, },
@@ -424,7 +481,7 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro
} }
id := time.Now().UnixMilli() id := time.Now().UnixMilli()
result, status, err := callOneshot(endpoint, bodyBytes, dlSession, proxyURL) result, status, err := callOneshot(endpoint, bodyBytes, dlSession, proxyURL, appVersion)
if err != nil { if err != nil {
// Map upstream timeouts to 504 so callers can distinguish "DeepL // Map upstream timeouts to 504 so callers can distinguish "DeepL
// took too long" from other 503 failure modes (DNS, TLS, etc.). // took too long" from other 503 failure modes (DNS, TLS, etc.).