From d99d12e9aa5c00225f53e381ad3bdc935be9347f Mon Sep 17 00:00:00 2001 From: diegosouzapw Date: Fri, 12 Jun 2026 09:04:32 -0300 Subject: [PATCH] fix(qwen-web): migrate to v2 chat API with full cookie-jar replay (#3288) The legacy /api/chat/completions endpoint was retired upstream and now returns 504 HTML from Alibaba's gateway for every request regardless of credentials, so token refresh could never help (#3288, discussion #2768). - Rewrite QwenWebExecutor to the two-step v2 flow: POST /api/v2/chats/new then POST /api/v2/chat/completions?chat_id=, parsing the phase-based SSE (think -> reasoning, answer -> content) into OpenAI chunks. - Replay the full browser cookie jar (cna + ssxmod_itna/itna2 + token) required by Alibaba's baxia WAF instead of only a Bearer token, plus the bx-v/bx-umidtoken/source anti-bot headers (mirrors grok-web). - Map the WAF/expired HTML page to a clear, actionable auth error instead of surfacing raw 504 HTML to the client. - webSessionCredentials: qwen-web becomes a full-cookie provider; browser login (tokenExtractionConfig) now captures the WAF cookies. - Refresh the model catalog to the current upstream ids (qwen3.7-max, qwen3.7-plus, qwen3.6-plus); legacy ids kept as executor aliases. - New helpers buildQwenCookieHeader/extractQwenToken; 17 unit tests. --- CHANGELOG.md | 1 + open-sse/config/freeModelCatalog.data.ts | 11 +- open-sse/config/providerRegistry.ts | 17 +- open-sse/executors/qwen-web.ts | 520 +++++++++++++----- open-sse/services/tokenExtractionConfig.ts | 12 +- src/lib/providers/webCookieAuth.ts | 35 ++ src/shared/providers/webSessionCredentials.ts | 10 +- tests/unit/executor-qwen-web.test.ts | 297 +++++++++- tests/unit/web-cookie-auth.test.ts | 28 + 9 files changed, 754 insertions(+), 177 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 418cc74897b1..658777b198d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - fix(gemini): standard Gemini provider no longer sends tool calls without a thought_signature (falls back to context mode when the signature is unavailable), fixing HTTP 400 on multi-turn thinking-model tool calls (#3688) - fix(antigravity): preserve gemini-3.1-pro High/Low budget tiers (upstream accepts the suffixed ids; stop collapsing to bare gemini-3.1-pro) (#3696) - fix: streaming combos now fail over to the next target when an upstream returns an empty/content-filtered response instead of surfacing a blank reply (#3685) +- fix(qwen-web): migrate the Qwen Web provider to the v2 chat API. The legacy `/api/chat/completions` endpoint was retired upstream and returned `504` HTML from Alibaba's gateway for every request regardless of credentials, so no token refresh could help (#3288, discussion #2768). The executor now uses the two-step v2 flow (`/api/v2/chats/new` → `/api/v2/chat/completions?chat_id=`), replays the full browser cookie jar (cna + ssxmod_itna/itna2 + token) required by Alibaba's WAF instead of only a Bearer token, parses the phase-based SSE (think→reasoning, answer→content), and maps the WAF/expired HTML page to a clear actionable auth error instead of surfacing raw HTML. The credential requirement is now a full Cookie header, browser-login capture grabs the WAF cookies, and the model catalog is refreshed to the current upstream ids (`qwen3.7-max`, `qwen3.7-plus`, `qwen3.6-plus`; legacy ids kept as aliases). 17 unit tests. --- diff --git a/open-sse/config/freeModelCatalog.data.ts b/open-sse/config/freeModelCatalog.data.ts index 5b29278eced3..d7d516091504 100644 --- a/open-sse/config/freeModelCatalog.data.ts +++ b/open-sse/config/freeModelCatalog.data.ts @@ -418,14 +418,9 @@ export const FREE_MODEL_BUDGETS: FreeModelBudget[] = [ { provider: "friendliai", modelId: "meta-llama-3.1-8b-instruct", displayName: "meta-llama-3.1-8b-instruct", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "friendliai", tos: "avoid" }, { provider: "ai21", modelId: "jamba-large-1.7", displayName: "jamba-large-1.7", monthlyTokens: 0, creditTokens: 10000000, freeType: "one-time-initial", poolKey: "ai21", tos: "avoid" }, { provider: "ai21", modelId: "jamba-mini-2", displayName: "jamba-mini-2", monthlyTokens: 0, creditTokens: 10000000, freeType: "one-time-initial", poolKey: "ai21", tos: "avoid" }, - { provider: "qwen-web", modelId: "qwen-plus", displayName: "Qwen Plus", monthlyTokens: 0, creditTokens: 0, freeType: "discontinued", poolKey: "qwen-web", tos: "avoid" }, - { provider: "qwen-web", modelId: "qwen-max", displayName: "Qwen Max", monthlyTokens: 0, creditTokens: 0, freeType: "discontinued", poolKey: "qwen-web", tos: "avoid" }, - { provider: "qwen-web", modelId: "qwen-turbo", displayName: "Qwen Turbo", monthlyTokens: 0, creditTokens: 0, freeType: "discontinued", poolKey: "qwen-web", tos: "avoid" }, - { provider: "qwen-web", modelId: "qwen3-plus", displayName: "Qwen3 Plus", monthlyTokens: 0, creditTokens: 0, freeType: "discontinued", poolKey: "qwen-web", tos: "avoid" }, - { provider: "qwen-web", modelId: "qwen3-max", displayName: "Qwen3 Max", monthlyTokens: 0, creditTokens: 0, freeType: "discontinued", poolKey: "qwen-web", tos: "avoid" }, - { provider: "qwen-web", modelId: "qwen3-flash", displayName: "Qwen3 Flash", monthlyTokens: 0, creditTokens: 0, freeType: "discontinued", poolKey: "qwen-web", tos: "avoid" }, - { provider: "qwen-web", modelId: "qwen3-coder-plus", displayName: "Qwen3 Coder Plus", monthlyTokens: 0, creditTokens: 0, freeType: "discontinued", poolKey: "qwen-web", tos: "avoid" }, - { provider: "qwen-web", modelId: "qwen3-coder-flash", displayName: "Qwen3 Coder Flash", monthlyTokens: 0, creditTokens: 0, freeType: "discontinued", poolKey: "qwen-web", tos: "avoid" }, + { provider: "qwen-web", modelId: "qwen3.7-max", displayName: "Qwen3.7 Max", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "qwen-web", tos: "avoid" }, + { provider: "qwen-web", modelId: "qwen3.7-plus", displayName: "Qwen3.7 Plus", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "qwen-web", tos: "avoid" }, + { provider: "qwen-web", modelId: "qwen3.6-plus", displayName: "Qwen3.6 Plus", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "qwen-web", tos: "avoid" }, { provider: "gitlawb", modelId: "mimo-v2.5-pro", displayName: "MiMo-V2.5-Pro", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "gitlawb", tos: "unknown" }, { provider: "gitlawb", modelId: "mimo-v2.5", displayName: "MiMo-V2.5", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "gitlawb", tos: "unknown" }, { provider: "gitlawb", modelId: "mimo-v2-pro", displayName: "MiMo-V2-Pro", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "gitlawb", tos: "unknown" }, diff --git a/open-sse/config/providerRegistry.ts b/open-sse/config/providerRegistry.ts index d017b25a18cd..27bc46650fd2 100644 --- a/open-sse/config/providerRegistry.ts +++ b/open-sse/config/providerRegistry.ts @@ -4011,18 +4011,17 @@ const _REGISTRY_EAGER: Record = { alias: "qwen-web", format: "openai", executor: "qwen-web", - baseUrl: "https://chat.qwen.ai/api/chat/completions", + // v2 API (the legacy /api/chat/completions endpoint was retired upstream). + baseUrl: "https://chat.qwen.ai/api/v2/chat/completions", authType: "apikey", authHeader: "bearer", + // Current upstream catalog (GET https://chat.qwen.ai/api/models). Legacy + // ids (qwen-plus, qwen3-max, ...) still resolve via the executor's + // MODEL_ALIASES map for backward compatibility. models: [ - { id: "qwen-plus", name: "Qwen Plus" }, - { id: "qwen-max", name: "Qwen Max" }, - { id: "qwen-turbo", name: "Qwen Turbo" }, - { id: "qwen3-plus", name: "Qwen3 Plus" }, - { id: "qwen3-max", name: "Qwen3 Max" }, - { id: "qwen3-flash", name: "Qwen3 Flash" }, - { id: "qwen3-coder-plus", name: "Qwen3 Coder Plus" }, - { id: "qwen3-coder-flash", name: "Qwen3 Coder Flash" }, + { id: "qwen3.7-max", name: "Qwen3.7 Max" }, + { id: "qwen3.7-plus", name: "Qwen3.7 Plus" }, + { id: "qwen3.6-plus", name: "Qwen3.6 Plus" }, ], }, diff --git a/open-sse/executors/qwen-web.ts b/open-sse/executors/qwen-web.ts index 67c7f50c1e01..82db1baebb21 100644 --- a/open-sse/executors/qwen-web.ts +++ b/open-sse/executors/qwen-web.ts @@ -1,173 +1,367 @@ /** - * QwenWebExecutor — Alibaba Tongyi Qwen Chat via chat.qwen.ai + * QwenWebExecutor — Alibaba Tongyi Qwen Chat via chat.qwen.ai (v2 API) * - * Routes requests through Qwen's consumer chat API. - * Chinese market provider with strong vision, coding, and reasoning models. + * Routes requests through Qwen's consumer chat API. The legacy v1 endpoint + * (`/api/chat/completions`) was retired upstream in 2026 and now answers 504 + * HTML from Alibaba's gateway for every request, regardless of credentials + * (#3288 / discussion #2768). The current contract is a two-step v2 flow: * - * Auth: Token from chat.qwen.ai Local Storage or tongyi_sso_ticket cookie - * Endpoint: POST https://chat.qwen.ai/api/chat/completions - * Format: OpenAI-compatible + * 1. POST /api/v2/chats/new → create a chat, returns chat_id + * 2. POST /api/v2/chat/completions?chat_id= → phase-based SSE stream + * + * The v2 endpoints sit behind Alibaba's "baxia" WAF, which requires the full + * browser cookie jar from a real logged-in session (cna, ssxmod_itna, + * ssxmod_itna2, token, ...). We therefore replay the captured/pasted Cookie + * header verbatim plus the bearer token, mirroring how grok-web replays its + * anti-bot cookies. + * + * SSE chunks carry `choices[0].delta` with a `phase` field: `think` / + * `thinking_summary` map to reasoning, `answer` (or a null phase) carries the + * assistant content. + * + * Reference implementations: gpt4free `g4f/Provider/Qwen.py`, + * Chat2API `proxy/adapters/qwen-ai.ts`. + * + * Auth: full Cookie header from chat.qwen.ai + bearer token (localStorage + * `token`, also mirrored to a `token` cookie). + * Format: OpenAI-compatible (translated from Qwen's phase protocol). */ import { BaseExecutor, type ExecuteInput } from "./base.ts"; import { makeExecutorErrorResult as makeErrorResult } from "../utils/error.ts"; import { prepareToolMessages, buildToolAwareResult } from "../translator/webTools.ts"; +import { buildQwenCookieHeader, extractQwenToken } from "@/lib/providers/webCookieAuth"; const BASE_URL = "https://chat.qwen.ai"; -const CHAT_URL = `${BASE_URL}/api/chat/completions`; +const CHATS_NEW_URL = `${BASE_URL}/api/v2/chats/new`; +const CHAT_COMPLETIONS_URL = `${BASE_URL}/api/v2/chat/completions`; const USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"; +// Anti-bot headers the v2 endpoint expects. `bx-umidtoken` is normally minted +// per-session from sg-wum.alibaba.com; a captured value travels with the cookie +// jar, but we also send a static fallback so the header is always present. +const BX_VERSION = "2.5.36"; +const BX_UMIDTOKEN_FALLBACK = "T2gA0000000000000000000000000000000000000000"; + +const MODEL_ALIASES: Record = { + // Legacy OmniRoute ids → current upstream catalog (GET /api/models). + "qwen-plus": "qwen3.7-plus", + "qwen-max": "qwen3.7-max", + "qwen-turbo": "qwen3.6-plus", + "qwen3-plus": "qwen3.7-plus", + "qwen3-max": "qwen3.7-max", + "qwen3-flash": "qwen3.6-plus", + "qwen3-coder-plus": "qwen3.7-max", + "qwen3-coder-flash": "qwen3.6-plus", + qwen: "qwen3.7-max", + qwen3: "qwen3.7-max", +}; + +const DEFAULT_MODEL = "qwen3.7-max"; + +function mapModel(modelId: string): string { + return MODEL_ALIASES[modelId] || modelId; +} + +function uuid(): string { + return crypto.randomUUID(); +} + +/** Detect Alibaba's WAF / retired-v1 gateway page so we never surface raw HTML. */ +function isWafResponse(status: number, contentType: string, bodyText: string): boolean { + if (contentType.includes("text/html")) return true; + if (status === 504) return true; + return /aliyun_waf|baxia| { + const headers: Record = { + "Content-Type": "application/json", + Accept: "*/*", + "User-Agent": USER_AGENT, + Origin: BASE_URL, + Referer: chatId ? `${BASE_URL}/c/${chatId}` : `${BASE_URL}/`, + source: "web", + "x-request-id": uuid(), + "bx-v": BX_VERSION, + "bx-umidtoken": BX_UMIDTOKEN_FALLBACK, + }; + if (token) headers["Authorization"] = `Bearer ${token}`; + if (cookieHeader) headers["Cookie"] = cookieHeader; + return headers; + } + async execute(input: ExecuteInput) { const { body, credentials, signal, stream: wantStream } = input; const bodyObj = (body || {}) as Record; - const rawToken = String(credentials?.apiKey ?? credentials?.accessToken ?? "").trim(); + + const rawCred = String(credentials?.apiKey ?? "").trim(); + const cookieHeader = buildQwenCookieHeader(rawCred); + let token = extractQwenToken(rawCred); + if (!token && credentials?.accessToken) token = String(credentials.accessToken).trim(); const messages = (bodyObj.messages as Array<{ role: string; content: string }>) || []; - const modelId = (bodyObj.model as string) || "qwen-plus"; + const requestedModel = (bodyObj.model as string) || DEFAULT_MODEL; + const modelId = mapModel(requestedModel); const { hasTools, requestedTools, effectiveMessages } = prepareToolMessages(bodyObj, messages); - const reqBody = { - messages: effectiveMessages.map((m) => ({ role: m.role, content: String(m.content ?? "") })), - model: modelId, - stream: wantStream, - max_tokens: (bodyObj.max_tokens as number) || 4096, - }; + // Qwen Web is single-turn: fold the conversation into one user prompt. + const prompt = this.foldMessages(effectiveMessages); - const reqHeaders: Record = { - "Content-Type": "application/json", - "User-Agent": USER_AGENT, - Accept: wantStream ? "text/event-stream" : "application/json", - Referer: `${BASE_URL}/`, - Origin: BASE_URL, - }; - if (rawToken) { - reqHeaders["Authorization"] = `Bearer ${rawToken}`; + // ── Step 1: create a chat ──────────────────────────────────────────────── + let chatId: string; + try { + const newChatRes = await fetch(CHATS_NEW_URL, { + method: "POST", + headers: this.buildHeaders(token, cookieHeader), + body: JSON.stringify({ + title: "New Chat", + models: [modelId], + chat_mode: "normal", + chat_type: "t2t", + timestamp: Date.now(), + }), + signal, + }); + + const ct = newChatRes.headers.get("content-type") || ""; + if (!newChatRes.ok || ct.includes("text/html")) { + const text = await newChatRes.text().catch(() => ""); + if (isWafResponse(newChatRes.status, ct, text)) { + return makeErrorResult(401, WAF_ERROR_MESSAGE, body, CHATS_NEW_URL); + } + return makeErrorResult( + newChatRes.status || 502, + `Qwen create-chat failed: ${text.slice(0, 300)}`, + body, + CHATS_NEW_URL + ); + } + + const data = (await newChatRes.json()) as { data?: { id?: string } }; + chatId = data?.data?.id ?? ""; + if (!chatId) { + return makeErrorResult(502, "Qwen create-chat returned no chat id", body, CHATS_NEW_URL); + } + } catch (err) { + return makeErrorResult( + 502, + `Qwen create-chat error: ${err instanceof Error ? err.message : "unknown"}`, + body, + CHATS_NEW_URL + ); } + // ── Step 2: send the message ───────────────────────────────────────────── + const completionUrl = `${CHAT_COMPLETIONS_URL}?chat_id=${chatId}`; + const msgPayload = this.buildMessagePayload(chatId, modelId, prompt, requestedModel); + let upstream: Response; try { - upstream = await fetch(CHAT_URL, { + upstream = await fetch(completionUrl, { method: "POST", - headers: reqHeaders, - body: JSON.stringify(reqBody), + headers: this.buildHeaders(token, cookieHeader, chatId), + body: JSON.stringify(msgPayload), signal, }); } catch (err) { return makeErrorResult( 502, - `Qwen fetch failed: ${err instanceof Error ? err.message : "unknown"}`, + `Qwen completion fetch failed: ${err instanceof Error ? err.message : "unknown"}`, body, - CHAT_URL + completionUrl ); } - if (!upstream.ok) { + const ct = upstream.headers.get("content-type") || ""; + if (!upstream.ok || ct.includes("text/html")) { const errText = await upstream.text().catch(() => ""); - if (upstream.status === 401) { - return makeErrorResult( - 401, - "Qwen authentication failed. Your token may have expired. " + - "Get a fresh token from chat.qwen.ai (DevTools → Application → Local Storage → token)", - body, - CHAT_URL - ); + if (isWafResponse(upstream.status, ct, errText)) { + return makeErrorResult(401, WAF_ERROR_MESSAGE, body, completionUrl); } - return makeErrorResult(upstream.status, `Qwen error: ${errText}`, body, CHAT_URL); + return makeErrorResult( + upstream.status || 502, + `Qwen error: ${errText.slice(0, 300)}`, + body, + completionUrl + ); } if (!wantStream) { - const data = (await upstream.json()) as Record; - const rawContent = - (data?.choices as Array<{ message?: { content?: string } }>)?.[0]?.message?.content || - (data?.content as string) || - ""; + const { content } = await this.collectStream(upstream); + const finalText = content; if (hasTools) { - const { content, toolCalls, finishReason } = buildToolAwareResult(rawContent, requestedTools, "qwen"); - const message: Record = { role: "assistant", content }; - if (toolCalls) { message.tool_calls = toolCalls; message.content = null; } - return { - response: new Response( - JSON.stringify({ - id: `chatcmpl-qwen-${Date.now()}`, object: "chat.completion", - created: Math.floor(Date.now() / 1000), model: modelId, - choices: [{ index: 0, message, finish_reason: finishReason }], - }), - { headers: { "Content-Type": "application/json" } } - ), - url: CHAT_URL, headers: reqHeaders, transformedBody: reqBody, - }; + const { + content: toolContent, + toolCalls, + finishReason, + } = buildToolAwareResult(finalText, requestedTools, "qwen"); + const message: Record = { role: "assistant", content: toolContent }; + if (toolCalls) { + message.tool_calls = toolCalls; + message.content = null; + } + return this.jsonResponse(modelId, message, finishReason, completionUrl, msgPayload); } - return { - response: new Response( - JSON.stringify({ - id: `chatcmpl-qwen-${Date.now()}`, object: "chat.completion", - created: Math.floor(Date.now() / 1000), model: modelId, - choices: [{ index: 0, message: { role: "assistant", content: rawContent }, finish_reason: "stop" }], - }), - { headers: { "Content-Type": "application/json" } } - ), - url: CHAT_URL, headers: reqHeaders, transformedBody: reqBody, - }; + return this.jsonResponse( + modelId, + { role: "assistant", content: finalText }, + "stop", + completionUrl, + msgPayload + ); } - // Streaming - const encoder = new TextEncoder(); - const decoder = new TextDecoder(); + // Streaming: transform Qwen phase SSE → OpenAI chat.completion.chunk SSE. + const stream = this.buildClientStream(upstream, modelId, hasTools, requestedTools, signal); + return { + response: new Response(stream, { + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }, + }), + url: completionUrl, + headers: this.buildHeaders(token, cookieHeader, chatId), + transformedBody: msgPayload, + }; + } - if (hasTools) { - let fullContent = ""; - const reader = upstream.body?.getReader(); - if (reader) { - let buf = ""; - try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - buf += decoder.decode(value, { stream: true }); - for (const line of buf.split("\n")) { - if (!line.startsWith("data:")) continue; - const d = line.slice(5).trim(); - if (d === "[DONE]") continue; - try { fullContent += JSON.parse(d).choices?.[0]?.delta?.content || ""; } catch {} - } - buf = buf.split("\n").pop() || ""; - } - } catch {} + private foldMessages(messages: Array<{ role: string; content: unknown }>): string { + let systemContent = ""; + let userContent = ""; + for (const m of messages) { + const text = String(m.content ?? ""); + if (m.role === "system") { + systemContent += (systemContent ? "\n\n" : "") + text; + } else if (m.role === "user") { + userContent = text; } + } + return systemContent ? `${systemContent}\n\nUser: ${userContent}` : userContent; + } - const { content, toolCalls, finishReason } = buildToolAwareResult(fullContent, requestedTools, "qwen"); - const stream = new ReadableStream({ - start(controller) { - const id = `chatcmpl-qwen-${Date.now()}`; - const created = Math.floor(Date.now() / 1000); - const delta = toolCalls - ? { role: "assistant", content: null, tool_calls: toolCalls } - : { role: "assistant", content }; - controller.enqueue(encoder.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model: modelId, choices: [{ index: 0, delta, finish_reason: null }] })}\n\n`)); - controller.enqueue(encoder.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model: modelId, choices: [{ index: 0, delta: {}, finish_reason: finishReason }] })}\n\n`)); - controller.enqueue(encoder.encode("data: [DONE]\n\n")); - controller.close(); + private buildMessagePayload( + chatId: string, + modelId: string, + prompt: string, + requestedModel: string + ): Record { + const fid = uuid(); + const enableThinking = /think|reason|r1/i.test(requestedModel); + const featureConfig: Record = { + thinking_enabled: enableThinking, + output_schema: "phase", + auto_thinking: enableThinking, + research_mode: "normal", + auto_search: false, + }; + return { + stream: true, + incremental_output: true, + chat_id: chatId, + chat_mode: "normal", + model: modelId, + parent_id: null, + messages: [ + { + fid, + parentId: null, + childrenIds: [], + role: "user", + content: prompt, + user_action: "chat", + files: [], + timestamp: Math.floor(Date.now() / 1000), + models: [modelId], + chat_type: "t2t", + feature_config: featureConfig, + sub_chat_type: "t2t", + parent_id: null, }, - }); - return { - response: new Response(stream, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" } }), - url: CHAT_URL, headers: reqHeaders, transformedBody: reqBody, - }; + ], + }; + } + + /** Read the whole upstream SSE stream, returning the joined answer + reasoning. */ + private async collectStream(upstream: Response): Promise<{ content: string; reasoning: string }> { + const reader = upstream.body?.getReader(); + const decoder = new TextDecoder(); + let content = ""; + let reasoning = ""; + if (!reader) return { content, reasoning }; + + let buffer = ""; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split("\n"); + buffer = lines.pop() || ""; + for (const line of lines) { + const delta = parseSseDelta(line); + if (!delta) continue; + if (delta.kind === "answer") content += delta.text; + else if (delta.kind === "think") reasoning += delta.text; + } + } + } catch { + /* upstream closed mid-stream — return what we have */ } + return { content, reasoning }; + } + + /** Transform the Qwen phase SSE into OpenAI chat.completion.chunk SSE. */ + private buildClientStream( + upstream: Response, + modelId: string, + hasTools: boolean, + requestedTools: unknown, + signal: AbortSignal | null | undefined + ): ReadableStream { + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + const id = `chatcmpl-qwen-${Date.now()}`; + const created = Math.floor(Date.now() / 1000); + const emitChunk = (delta: Record, finishReason: string | null) => + `data: ${JSON.stringify({ + id, + object: "chat.completion.chunk", + created, + model: modelId, + choices: [{ index: 0, delta, finish_reason: finishReason }], + })}\n\n`; - const stream = new ReadableStream({ + return new ReadableStream({ async start(controller) { const reader = upstream.body?.getReader(); - if (!reader) { controller.close(); return; } + if (!reader) { + controller.enqueue(encoder.encode("data: [DONE]\n\n")); + controller.close(); + return; + } let buffer = ""; + let fullContent = ""; + controller.enqueue(encoder.encode(emitChunk({ role: "assistant", content: "" }, null))); try { while (true) { const { done, value } = await reader.read(); @@ -176,43 +370,95 @@ export class QwenWebExecutor extends BaseExecutor { const lines = buffer.split("\n"); buffer = lines.pop() || ""; for (const line of lines) { - if (!line.startsWith("data:")) continue; - const data = line.slice(5).trim(); - if (data === "[DONE]") { controller.enqueue(encoder.encode("data: [DONE]\n\n")); continue; } - try { - const parsed = JSON.parse(data); - const text = parsed.choices?.[0]?.delta?.content || parsed.choices?.[0]?.text || ""; - if (text) { - const chunk = { - id: `chatcmpl-qwen-${Date.now()}`, - object: "chat.completion.chunk", - created: Math.floor(Date.now() / 1000), - model: modelId, - choices: [{ index: 0, delta: { content: text }, finish_reason: null }], - }; - controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`)); + const delta = parseSseDelta(line); + if (!delta || !delta.text) continue; + if (delta.kind === "answer") { + fullContent += delta.text; + if (!hasTools) { + controller.enqueue(encoder.encode(emitChunk({ content: delta.text }, null))); } - } catch { - /* skip unparseable chunks */ + } else if (delta.kind === "think" && !hasTools) { + controller.enqueue( + encoder.encode(emitChunk({ reasoning_content: delta.text }, null)) + ); } } } } catch (err) { - if (!signal?.aborted) controller.error(err); - } finally { - controller.enqueue(encoder.encode("data: [DONE]\n\n")); - controller.close(); + if (!signal?.aborted) { + controller.error(err); + return; + } } + + if (hasTools) { + const { content, toolCalls, finishReason } = buildToolAwareResult( + fullContent, + requestedTools, + "qwen" + ); + const delta = toolCalls + ? { role: "assistant", content: null, tool_calls: toolCalls } + : { role: "assistant", content }; + controller.enqueue(encoder.encode(emitChunk(delta, null))); + controller.enqueue(encoder.encode(emitChunk({}, finishReason))); + } else { + controller.enqueue(encoder.encode(emitChunk({}, "stop"))); + } + controller.enqueue(encoder.encode("data: [DONE]\n\n")); + controller.close(); }, }); + } + private jsonResponse( + modelId: string, + message: Record, + finishReason: string, + url: string, + transformedBody: unknown + ) { return { - response: new Response(stream, { - headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" }, - }), - url: CHAT_URL, - headers: reqHeaders, - transformedBody: reqBody, + response: new Response( + JSON.stringify({ + id: `chatcmpl-qwen-${Date.now()}`, + object: "chat.completion", + created: Math.floor(Date.now() / 1000), + model: modelId, + choices: [{ index: 0, message, finish_reason: finishReason }], + }), + { headers: { "Content-Type": "application/json" } } + ), + url, + headers: {} as Record, + transformedBody, }; } } + +/** Parse one SSE line into a typed delta, or null if it carries no content. */ +function parseSseDelta(line: string): { kind: "answer" | "think"; text: string } | null { + if (!line.startsWith("data:")) return null; + const payload = line.slice(5).trim(); + if (!payload || payload === "[DONE]") return null; + let parsed: { + choices?: Array<{ delta?: { phase?: string | null; content?: unknown } }>; + }; + try { + parsed = JSON.parse(payload); + } catch { + return null; + } + const delta = parsed?.choices?.[0]?.delta; + if (!delta) return null; + const phase = delta.phase; + const content = typeof delta.content === "string" ? delta.content : ""; + if (phase === "think" || phase === "thinking_summary") { + return { kind: "think", text: content }; + } + // `answer` phase or a null/absent phase both carry assistant content. + if (phase === "answer" || phase === null || phase === undefined) { + return { kind: "answer", text: content }; + } + return null; +} diff --git a/open-sse/services/tokenExtractionConfig.ts b/open-sse/services/tokenExtractionConfig.ts index d9f6f0a86c6d..f82804e2e0d9 100644 --- a/open-sse/services/tokenExtractionConfig.ts +++ b/open-sse/services/tokenExtractionConfig.ts @@ -168,16 +168,24 @@ const RAW_CONFIGS: TokenExtractionConfig[] = [ ), // ── Qwen Web ────────────────────────────────────────────── + // The v2 API sits behind Alibaba's "baxia" WAF, which needs the full browser + // cookie jar (cna + ssxmod_itna/itna2 + token), not just the bearer token. + // Capture the WAF cookies alongside the localStorage token (#3288). config( "qwen-web", "Qwen Web (Tongyi)", "https://chat.qwen.ai/", "https://chat.qwen.ai", [ - { type: "cookie", name: "XSRF_TOKEN", domain: ".chat.qwen.ai" }, { type: "localStorage", key: "token" }, + { type: "cookie", name: "token", domain: ".chat.qwen.ai" }, + { type: "cookie", name: "cna", domain: ".chat.qwen.ai" }, + { type: "cookie", name: "ssxmod_itna", domain: ".chat.qwen.ai" }, + { type: "cookie", name: "ssxmod_itna2", domain: ".chat.qwen.ai" }, + { type: "cookie", name: "XSRF_TOKEN", domain: ".chat.qwen.ai" }, ], - "Log in to Qwen at chat.qwen.ai using your Alibaba account. The session token will be extracted.", + "Log in to Qwen at chat.qwen.ai using your Alibaba account. The session token and the " + + "Alibaba WAF cookies (cna, ssxmod_itna) will be extracted — all are required by the v2 API.", { cookieDomain: ".chat.qwen.ai" } ), diff --git a/src/lib/providers/webCookieAuth.ts b/src/lib/providers/webCookieAuth.ts index 4e9263c5fcac..a7e204efdf8e 100644 --- a/src/lib/providers/webCookieAuth.ts +++ b/src/lib/providers/webCookieAuth.ts @@ -63,6 +63,41 @@ export function buildGrokCookieHeader(rawValue: string): string { return parts.join("; "); } +/** + * Build the `Cookie` header value for chat.qwen.ai (Qwen Web / Tongyi). + * + * The Qwen v2 API sits behind Alibaba's "baxia" WAF, which requires the full + * browser cookie jar from a real logged-in session (`cna`, `ssxmod_itna`, + * `ssxmod_itna2`, `token`, `_bl_uid`, `x-ap`, ...). Unlike grok we cannot + * reconstruct a canonical subset, so we forward the whole pasted/captured blob + * verbatim (minus a leading `Cookie:`/`bearer ` prefix). + * + * A bare token (no cookie pairs, i.e. no `=`) yields "" — there is no jar to + * replay, only a bearer credential (handled by {@link extractQwenToken}). + */ +export function buildQwenCookieHeader(rawValue: string): string { + const trimmed = stripCookieInputPrefix(rawValue); + if (!trimmed || !trimmed.includes("=")) return ""; + return trimmed; +} + +/** + * Extract the Qwen bearer token from whatever the user pasted/captured. + * + * Qwen stores its auth JWT in localStorage as `token`, and chat.qwen.ai also + * mirrors it into a `token` cookie. So: + * - full cookie blob with `token=...` → that value + * - bare token (no cookie pairs) → the value itself + * - cookie blob without a `token` pair → "" (token must come from elsewhere) + */ +export function extractQwenToken(rawValue: string): string { + const trimmed = stripCookieInputPrefix(rawValue); + if (!trimmed) return ""; + if (!trimmed.includes("=")) return trimmed; + const match = trimmed.match(/(?:^|;\s*)token=([^;\s]+)/); + return match ? match[1] : ""; +} + export function normalizeSessionCookieHeaders( rawValues: Array, defaultCookieName: string diff --git a/src/shared/providers/webSessionCredentials.ts b/src/shared/providers/webSessionCredentials.ts index 4f9bfec84c9b..0914d94742d2 100644 --- a/src/shared/providers/webSessionCredentials.ts +++ b/src/shared/providers/webSessionCredentials.ts @@ -158,11 +158,11 @@ export const WEB_SESSION_CREDENTIAL_REQUIREMENTS = { storageKeys: ["cookie", "session"], }, "qwen-web": { - kind: "token", - credentialName: "token", - placeholder: "Paste your Qwen token from chat.qwen.ai (Local Storage → token)", - acceptsFullCookieHeader: false, - storageKeys: ["token", "tongyi_sso_ticket"], + kind: "cookie", + credentialName: "full Cookie header (must include cna, ssxmod_itna, token)", + placeholder: "cna=...; token=...; ssxmod_itna=...; ssxmod_itna2=... (full Cookie header from chat.qwen.ai)", + acceptsFullCookieHeader: true, + storageKeys: ["cookie", "token", "ssxmod_itna", "ssxmod_itna2", "cna", "tongyi_sso_ticket"], }, "duckduckgo-web": { kind: "cookie", diff --git a/tests/unit/executor-qwen-web.test.ts b/tests/unit/executor-qwen-web.test.ts index 2cf4893c852e..a1dff956e373 100644 --- a/tests/unit/executor-qwen-web.test.ts +++ b/tests/unit/executor-qwen-web.test.ts @@ -1,28 +1,293 @@ -import { describe, it } from "node:test"; +import { describe, it, beforeEach, afterEach } from "node:test"; import assert from "node:assert/strict"; const mod = await import("../../open-sse/executors/qwen-web.ts"); +const { REGISTRY } = await import("../../open-sse/config/providerRegistry.ts"); +const { FREE_MODEL_BUDGETS } = await import("../../open-sse/config/freeModelCatalog.data.ts"); -describe("QwenWebExecutor", () => { +type FetchCall = { url: string; init: any }; + +const realFetch = globalThis.fetch; +let calls: FetchCall[] = []; + +/** Build an SSE Response from an array of v2 "phase" delta events. */ +function sseResponse(events: Array>): Response { + const encoder = new TextEncoder(); + const stream = new ReadableStream({ + start(controller) { + for (const ev of events) { + controller.enqueue(encoder.encode(`data: ${JSON.stringify(ev)}\n\n`)); + } + controller.enqueue(encoder.encode("data: [DONE]\n\n")); + controller.close(); + }, + }); + return new Response(stream, { + status: 200, + headers: { "content-type": "text/event-stream" }, + }); +} + +function chatCreatedResponse(id = "chat-abc"): Response { + return new Response(JSON.stringify({ success: true, data: { id } }), { + status: 200, + headers: { "content-type": "application/json" }, + }); +} + +/** The 504 + HTML page Alibaba's gateway returns for the retired v1 endpoint + * and for WAF-blocked requests. */ +function wafHtmlResponse(status = 504): Response { + return new Response( + "\n504 Gateway Time-out\n\n" + + '

504 Gateway Time-out

\n
alibaba-ga
\n' + + '\n\n', + { status, headers: { "content-type": "text/html; charset=utf-8" } } + ); +} + +beforeEach(() => { + calls = []; +}); + +afterEach(() => { + globalThis.fetch = realFetch; +}); + +describe("QwenWebExecutor (v2 migration)", () => { it("can be instantiated", () => { + assert.ok(new mod.QwenWebExecutor()); + }); + + it("uses the v2 two-step flow: chats/new then chat/completions?chat_id=", async () => { + globalThis.fetch = (async (url: any, init: any = {}) => { + calls.push({ url: String(url), init }); + if (String(url).includes("/api/v2/chats/new")) return chatCreatedResponse("chat-xyz"); + return sseResponse([ + { choices: [{ delta: { phase: "answer", content: "Hello", status: "typing" } }] }, + { choices: [{ delta: { phase: "answer", content: " world", status: "finished" } }] }, + ]); + }) as any; + const executor = new mod.QwenWebExecutor(); - assert.ok(executor); + const result = await executor.execute({ + model: "qwen3.7-max", + body: { messages: [{ role: "user", content: "hi" }] }, + stream: false, + credentials: { apiKey: "token=jwt-tok; cna=abc; ssxmod_itna=1-xyz" }, + signal: null, + } as any); + + assert.equal(calls.length, 2, "should make exactly two upstream calls"); + assert.match(calls[0].url, /\/api\/v2\/chats\/new$/); + assert.equal(calls[0].init.method, "POST"); + assert.match(calls[1].url, /\/api\/v2\/chat\/completions\?chat_id=chat-xyz/); + assert.equal(calls[1].init.method, "POST"); + + // chats/new payload shape + const newBody = JSON.parse(calls[0].init.body); + assert.deepEqual(newBody.models, ["qwen3.7-max"]); + assert.equal(newBody.chat_type, "t2t"); + assert.equal(newBody.chat_mode, "normal"); + + // completion payload references the created chat_id + const compBody = JSON.parse(calls[1].init.body); + assert.equal(compBody.chat_id, "chat-xyz"); + assert.equal(compBody.model, "qwen3.7-max"); + assert.equal(compBody.messages[0].role, "user"); + assert.equal(compBody.messages[0].content, "hi"); + + const json = (await result.response.json()) as any; + assert.equal(json.choices[0].message.content, "Hello world"); }); - it("execute returns error on fetch failure", async () => { + it("replays the full cookie jar and the extracted bearer token on every call", async () => { + globalThis.fetch = (async (url: any, init: any = {}) => { + calls.push({ url: String(url), init }); + if (String(url).includes("/api/v2/chats/new")) return chatCreatedResponse(); + return sseResponse([ + { choices: [{ delta: { phase: "answer", content: "ok", status: "finished" } }] }, + ]); + }) as any; + + const cookieBlob = "token=jwt-secret; cna=CNA1; ssxmod_itna=1-AAA; ssxmod_itna2=1-BBB"; const executor = new mod.QwenWebExecutor(); - try { - const result = await executor.execute({ - model: "qwen-plus", - body: { messages: [{ role: "user", content: "hi" }] }, - stream: false, - credentials: { apiKey: "" }, - signal: null, - }); - assert.ok(result.response instanceof Response); - assert.ok(result.url.includes("qwen.ai")); - } catch { - // Network error expected + await executor.execute({ + model: "qwen3.7-plus", + body: { messages: [{ role: "user", content: "hi" }] }, + stream: false, + credentials: { apiKey: cookieBlob }, + signal: null, + } as any); + + for (const call of calls) { + const headers = call.init.headers as Record; + const cookie = headers.Cookie || headers.cookie || ""; + assert.match(cookie, /cna=CNA1/, "full cookie jar must be replayed"); + assert.match(cookie, /ssxmod_itna=1-AAA/, "WAF cookies must be replayed"); + const auth = headers.Authorization || headers.authorization || ""; + assert.equal(auth, "Bearer jwt-secret", "bearer token extracted from token= cookie"); } }); + + it("sends the anti-bot headers required by the v2 endpoint", async () => { + globalThis.fetch = (async (url: any, init: any = {}) => { + calls.push({ url: String(url), init }); + if (String(url).includes("/api/v2/chats/new")) return chatCreatedResponse(); + return sseResponse([ + { choices: [{ delta: { phase: "answer", content: "ok", status: "finished" } }] }, + ]); + }) as any; + + const executor = new mod.QwenWebExecutor(); + await executor.execute({ + model: "qwen3.7-plus", + body: { messages: [{ role: "user", content: "hi" }] }, + stream: false, + credentials: { apiKey: "token=t; cna=c" }, + signal: null, + } as any); + + const headers = calls[0].init.headers as Record; + assert.ok(headers["bx-v"], "bx-v header present"); + assert.ok(headers["bx-umidtoken"], "bx-umidtoken header present"); + assert.equal(headers.source || headers.Source, "web", "source: web header present"); + }); + + it("maps the thinking phase to reasoning_content, not the answer content", async () => { + globalThis.fetch = (async (url: any) => { + if (String(url).includes("/api/v2/chats/new")) return chatCreatedResponse(); + return sseResponse([ + { choices: [{ delta: { phase: "think", content: "let me think", status: "typing" } }] }, + { choices: [{ delta: { phase: "think", content: "...", status: "finished" } }] }, + { choices: [{ delta: { phase: "answer", content: "Final answer", status: "finished" } }] }, + ]); + }) as any; + + const executor = new mod.QwenWebExecutor(); + const result = await executor.execute({ + model: "qwen3.7-max", + body: { messages: [{ role: "user", content: "hi" }] }, + stream: false, + credentials: { apiKey: "token=t; cna=c" }, + signal: null, + } as any); + + const json = (await result.response.json()) as any; + assert.equal(json.choices[0].message.content, "Final answer"); + assert.ok( + !String(json.choices[0].message.content).includes("let me think"), + "thinking content must not leak into the answer" + ); + }); + + it("classifies the retired-v1 / WAF 504 HTML page as a clear auth error (not raw HTML)", async () => { + globalThis.fetch = (async (url: any) => { + if (String(url).includes("/api/v2/chats/new")) return wafHtmlResponse(504); + return chatCreatedResponse(); + }) as any; + + const executor = new mod.QwenWebExecutor(); + const result = await executor.execute({ + model: "qwen3.7-max", + body: { messages: [{ role: "user", content: "hi" }] }, + stream: false, + credentials: { apiKey: "token=stale; cna=c" }, + signal: null, + } as any); + + assert.ok([401, 403].includes(result.response.status), "should map to an auth status"); + const json = (await result.response.json()) as any; + const msg = String(json.error?.message || ""); + assert.ok(!msg.includes(" { + globalThis.fetch = (async (url: any) => { + if (String(url).includes("/api/v2/chats/new")) return chatCreatedResponse(); + return sseResponse([ + { choices: [{ delta: { phase: "answer", content: "Hi", status: "typing" } }] }, + { choices: [{ delta: { phase: "answer", content: " there", status: "finished" } }] }, + ]); + }) as any; + + const executor = new mod.QwenWebExecutor(); + const result = await executor.execute({ + model: "qwen3.7-max", + body: { messages: [{ role: "user", content: "hi" }] }, + stream: true, + credentials: { apiKey: "token=t; cna=c" }, + signal: null, + } as any); + + const text = await result.response.text(); + assert.match(text, /chat\.completion\.chunk/); + assert.match(text, /"content":"Hi"/); + assert.match(text, /"content":" there"/); + assert.match(text, /data: \[DONE\]/); + }); + + it("accepts a bare token (back-compat) without a cookie jar", async () => { + globalThis.fetch = (async (url: any, init: any = {}) => { + calls.push({ url: String(url), init }); + if (String(url).includes("/api/v2/chats/new")) return chatCreatedResponse(); + return sseResponse([ + { choices: [{ delta: { phase: "answer", content: "ok", status: "finished" } }] }, + ]); + }) as any; + + const executor = new mod.QwenWebExecutor(); + await executor.execute({ + model: "qwen3.7-plus", + body: { messages: [{ role: "user", content: "hi" }] }, + stream: false, + credentials: { apiKey: "barejwttoken" }, + signal: null, + } as any); + + const headers = calls[0].init.headers as Record; + assert.equal(headers.Authorization || headers.authorization, "Bearer barejwttoken"); + }); + + it("registry points at the v2 endpoint and the current model catalog", () => { + const provider = (REGISTRY as any)["qwen-web"]; + assert.ok(provider, "qwen-web must be registered"); + assert.match(provider.baseUrl, /\/api\/v2\/chat\/completions$/, "registry must use v2 endpoint"); + const ids = provider.models.map((m: any) => m.id); + assert.deepEqual(ids.sort(), ["qwen3.6-plus", "qwen3.7-max", "qwen3.7-plus"]); + }); + + it("free-model catalog lists the current qwen-web ids (not the retired ones)", () => { + const qwenModels = (FREE_MODEL_BUDGETS as any[]).filter((m) => m.provider === "qwen-web"); + const ids = qwenModels.map((m) => m.modelId); + assert.ok(ids.includes("qwen3.7-max"), "catalog must list qwen3.7-max"); + assert.ok(!ids.includes("qwen-plus"), "retired qwen-plus must be gone"); + assert.ok( + qwenModels.every((m) => m.freeType !== "discontinued"), + "qwen-web is no longer discontinued after the v2 migration" + ); + }); + + it("maps legacy model ids to the current upstream catalog", async () => { + globalThis.fetch = (async (url: any, init: any = {}) => { + calls.push({ url: String(url), init }); + if (String(url).includes("/api/v2/chats/new")) return chatCreatedResponse(); + return sseResponse([ + { choices: [{ delta: { phase: "answer", content: "ok", status: "finished" } }] }, + ]); + }) as any; + + const executor = new mod.QwenWebExecutor(); + await executor.execute({ + model: "qwen3-max", + body: { messages: [{ role: "user", content: "hi" }] }, + stream: false, + credentials: { apiKey: "token=t; cna=c" }, + signal: null, + } as any); + + const newBody = JSON.parse(calls[0].init.body); + assert.match(newBody.models[0], /^qwen3\.[67]-/, "legacy qwen3-max maps to a current model id"); + }); }); diff --git a/tests/unit/web-cookie-auth.test.ts b/tests/unit/web-cookie-auth.test.ts index ba9e158ee3cf..cc3c043b804c 100644 --- a/tests/unit/web-cookie-auth.test.ts +++ b/tests/unit/web-cookie-auth.test.ts @@ -6,6 +6,8 @@ const { normalizeSessionCookieHeader, stripCookieInputPrefix, buildGrokCookieHeader, + buildQwenCookieHeader, + extractQwenToken, } = await import("../../src/lib/providers/webCookieAuth.ts"); test("stripCookieInputPrefix removes 'cookie:' and 'bearer ' prefixes", () => { @@ -87,3 +89,29 @@ test("buildGrokCookieHeader: blob without sso returns empty string", () => { assert.equal(buildGrokCookieHeader("foo=1; sso-rw=CCC.ddd; bar=2"), ""); assert.equal(buildGrokCookieHeader(""), ""); }); + +test("buildQwenCookieHeader: passes through a full DevTools cookie blob", () => { + const blob = "cna=ABC; token=jwt.tok; ssxmod_itna=1-XYZ; ssxmod_itna2=1-QRS"; + assert.equal(buildQwenCookieHeader(blob), blob); +}); + +test("buildQwenCookieHeader: strips a leading 'Cookie:' prefix", () => { + assert.equal(buildQwenCookieHeader("Cookie: cna=ABC; token=jwt"), "cna=ABC; token=jwt"); +}); + +test("buildQwenCookieHeader: a bare token (no cookie pairs) yields no cookie header", () => { + assert.equal(buildQwenCookieHeader("eyJ0eXAi.abc.def"), ""); + assert.equal(buildQwenCookieHeader(""), ""); +}); + +test("extractQwenToken: pulls the token= value out of a cookie blob", () => { + assert.equal(extractQwenToken("cna=ABC; token=jwt.tok; ssxmod_itna=1-XYZ"), "jwt.tok"); +}); + +test("extractQwenToken: returns a bare token unchanged", () => { + assert.equal(extractQwenToken("eyJ0eXAi.abc.def"), "eyJ0eXAi.abc.def"); +}); + +test("extractQwenToken: a cookie blob without a token cookie yields empty string", () => { + assert.equal(extractQwenToken("cna=ABC; ssxmod_itna=1-XYZ"), ""); +});