Compare commits

..
Author SHA1 Message Date
Vincent Young 0dd935ba7e feat(translate): validate source/target language codes
Previously TranslateByDeepLX silently mapped any caller-supplied code
through toOneshotLang(), falling back to a lowercased pass-through for
unknown codes. The oneshot endpoint accepts unknown codes with a 200
but echoes the source text back untranslated, leaving callers to
distinguish "translated, identical to source" from "language not
supported" without a clear signal.

Validate strictly against the language table the extension bundles in
background.js (array `y` for target-capable codes, `A` for the
source-only EN / PT aliases) and return HTTP 400 with a list of
supported codes on mismatch. This also catches:

  - target_lang = ""        → "target_lang is required"
  - target_lang = "auto"    → "target_lang cannot be \"auto\"; pick one of: ..."
  - source_lang = ""/"auto" → allowed, server autodetects
  - case-insensitive       → strings.ToUpper before lookup

Pick up languages the previous map missed:

  + ES-419 (Latin American Spanish)
  + HE     (Hebrew)
  + VI     (Vietnamese)

Fix the EN / PT source-lang mapping: the extension's `A` array maps
both to the generic langCodeForIta ("en"/"pt"), not the regional
default. As a target they continue to resolve to en-US / pt-BR for
backward compat with callers that historically passed "EN" / "PT".

Verified end-to-end:
  - 5 valid codes (DE, ZH-HANT, HE, VI, ES-419) → 200 + translated text
  - Invalid target "XX"  → 400, message lists 38 supported codes
  - Invalid source "ZZ"  → 400, message lists 38 codes + "auto"
  - target_lang "auto"   → 400
  - source autodetect (empty / "auto") + valid target → 200
  - Lowercase input "de" → 200 (case-insensitive)
2026-05-22 12:12:27 +08:00
2 changed files with 6 additions and 86 deletions
+1 -4
View File
@@ -1,4 +1 @@
DeepLX DeepLX
# macOS Finder metadata
.DS_Store
+5 -82
View File
@@ -15,11 +15,9 @@ package translate
import ( import (
"compress/flate" "compress/flate"
"compress/gzip" "compress/gzip"
"context"
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -29,7 +27,6 @@ import (
"strings" "strings"
"sync" "sync"
"time" "time"
"unicode/utf8"
"github.com/andybalholm/brotli" "github.com/andybalholm/brotli"
"github.com/imroc/req/v3" "github.com/imroc/req/v3"
@@ -60,26 +57,6 @@ const (
impersonatedChromeMajor = "120" impersonatedChromeMajor = "120"
chromeExtensionVersion = "1.86.0" chromeExtensionVersion = "1.86.0"
chromeExtensionID = "cofdbpoegempjloogbagkncekinflcnj" chromeExtensionID = "cofdbpoegempjloogbagkncekinflcnj"
// oneshot enforces a 1500-character hard cap on the total length of
// the `text` array (sum across all items). Source: the extension's
// own `G.notLoggedIn = 1500` constant in background.js. The server
// returns 400 `{"errors":{"text":["text exceeds maximum length"]}}`
// past this; bail early to spare the upstream and give the caller a
// faster, less ambiguous error.
maxFreeTextLength = 1500
// oneshotTimeout caps how long we wait on a single translate request.
// Without an explicit timeout, a hung upstream connection would
// dangle indefinitely and the caller (e.g. browser extension) would
// sit on a spinner forever — observed in the field.
oneshotTimeout = 20 * time.Second
// warmupTimeout caps the initial GET to www.deepl.com that seeds the
// cookie jar. Shorter than oneshotTimeout because warmup typically
// completes in well under a second; we'd rather skip a slow warmup
// (cookies are best-effort anyway) than block the first translation.
warmupTimeout = 5 * time.Second
) )
// instanceID mirrors the UUID the extension persists in chrome.storage on // instanceID mirrors the UUID the extension persists in chrome.storage on
@@ -99,14 +76,6 @@ var (
cookieWarmer sync.Once cookieWarmer sync.Once
) )
// oneshotClients caches one req.Client per proxy URL so all translate
// calls share the underlying TCP / TLS / HTTP/2 connection pool.
// Creating a fresh req.Client per request meant a brand-new TLS
// handshake every time (~200-400ms of overhead on top of DeepL's own
// ~1.5s processing latency). Reusing the client lets keep-alive +
// session tickets cut that to near zero on the warm path.
var oneshotClients sync.Map // map[string]*req.Client
func sharedCookieJar() http.CookieJar { func sharedCookieJar() http.CookieJar {
cookieJarOnce.Do(func() { cookieJarOnce.Do(func() {
j, _ := cookiejar.New(nil) j, _ := cookiejar.New(nil)
@@ -118,15 +87,10 @@ func sharedCookieJar() http.CookieJar {
// warmCookies primes the shared jar by GETting www.deepl.com once. // warmCookies primes the shared jar by GETting www.deepl.com once.
// The Set-Cookie response (userCountry / verifiedBot) lands on .deepl.com, // The Set-Cookie response (userCountry / verifiedBot) lands on .deepl.com,
// which is the eTLD+1 of oneshot-free.www.deepl.com, so subsequent POSTs // which is the eTLD+1 of oneshot-free.www.deepl.com, so subsequent POSTs
// to the oneshot endpoint will carry those cookies automatically. The // to the oneshot endpoint will carry those cookies automatically.
// same request doubles as a TLS-handshake warmup: it leaves a live
// HTTP/2 connection to www.deepl.com in the client pool, which the
// first oneshot POST then resumes via TLS session tickets.
func warmCookies(client *req.Client) { func warmCookies(client *req.Client) {
cookieWarmer.Do(func() { cookieWarmer.Do(func() {
ctx, cancel := context.WithTimeout(context.Background(), warmupTimeout) _, _ = client.R().Get("https://www.deepl.com/translator")
defer cancel()
_, _ = client.R().SetContext(ctx).Get("https://www.deepl.com/translator")
}) })
} }
@@ -275,33 +239,8 @@ type oneshotRequest struct {
// headers (pragma, cache-control, upgrade-insecure-requests, sec-fetch-user) // headers (pragma, cache-control, upgrade-insecure-requests, sec-fetch-user)
// that a fetch() never emits — wipe those so the WAF cannot tell us apart // that a fetch() never emits — wipe those so the WAF cannot tell us apart
// on that axis. // on that axis.
// getOneshotClient returns a process-wide cached client for the given
// proxy URL, creating it on first use. Sharing the client across
// requests is the single biggest latency win we have on the warm path:
// it keeps the TLS / HTTP/2 connection in the pool so subsequent
// requests skip the handshake entirely. Kicks off cookie-jar warmup
// in the background on first creation so that the first real translate
// call lands on an already-established connection.
func getOneshotClient(proxyURL string) (*req.Client, error) {
if c, ok := oneshotClients.Load(proxyURL); ok {
return c.(*req.Client), nil
}
c, err := newOneshotClient(proxyURL)
if err != nil {
return nil, err
}
if actual, loaded := oneshotClients.LoadOrStore(proxyURL, c); loaded {
return actual.(*req.Client), nil
}
// First time we've seen this proxy. Kick warmup off in the
// background so the very first translate call can run in parallel
// with the TLS handshake to www.deepl.com.
go warmCookies(c)
return c, nil
}
func newOneshotClient(proxyURL string) (*req.Client, error) { func newOneshotClient(proxyURL string) (*req.Client, error) {
client := req.C().ImpersonateChrome().SetCookieJar(sharedCookieJar()).SetTimeout(oneshotTimeout) client := req.C().ImpersonateChrome().SetCookieJar(sharedCookieJar())
for _, h := range []string{ for _, h := range []string{
"Pragma", "Pragma",
"Cache-Control", "Cache-Control",
@@ -331,10 +270,11 @@ func newOneshotClient(proxyURL string) (*req.Client, error) {
// exactly. Omitting that header instead would put the request on a // exactly. Omitting that header instead would put the request on a
// different server-side auth branch. // different server-side auth branch.
func callOneshot(endpoint string, body []byte, bearerToken, proxyURL string) (gjson.Result, int, error) { func callOneshot(endpoint string, body []byte, bearerToken, proxyURL string) (gjson.Result, int, error) {
client, err := getOneshotClient(proxyURL) client, err := newOneshotClient(proxyURL)
if err != nil { if err != nil {
return gjson.Result{}, 0, err return gjson.Result{}, 0, err
} }
warmCookies(client) // no-op after the first translation in the process
authValue := "None" authValue := "None"
if bearerToken != "" { if bearerToken != "" {
@@ -409,13 +349,6 @@ func TranslateByDeepLX(sourceLang, targetLang, text string, tagHandling string,
}, nil }, nil
} }
if n := utf8.RuneCountInString(text); n > maxFreeTextLength {
return DeepLXTranslationResult{
Code: http.StatusRequestEntityTooLarge,
Message: fmt.Sprintf("text exceeds maximum length: %d characters (anonymous oneshot limit is %d)", n, maxFreeTextLength),
}, nil
}
reqStruct := oneshotRequest{ reqStruct := oneshotRequest{
Text: []string{text}, Text: []string{text},
TargetLang: resolvedTarget, TargetLang: resolvedTarget,
@@ -439,16 +372,6 @@ func TranslateByDeepLX(sourceLang, targetLang, text string, tagHandling string,
id := time.Now().UnixMilli() id := time.Now().UnixMilli()
result, status, err := callOneshot(endpoint, bodyBytes, dlSession, proxyURL) result, status, err := callOneshot(endpoint, bodyBytes, dlSession, proxyURL)
if err != nil { if err != nil {
// Map upstream timeouts to 504 so callers can distinguish "DeepL
// took too long" from other 503 failure modes (DNS, TLS, etc.).
var ue *url.Error
if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &ue) && ue.Timeout()) {
return DeepLXTranslationResult{
ID: id,
Code: http.StatusGatewayTimeout,
Message: fmt.Sprintf("upstream DeepL request timed out after %s", oneshotTimeout),
}, nil
}
return DeepLXTranslationResult{ return DeepLXTranslationResult{
ID: id, ID: id,
Code: http.StatusServiceUnavailable, Code: http.StatusServiceUnavailable,