Skip to content

Commit 766061a

Browse files
committed
Update zai_provider.py
1 parent 9f1b228 commit 766061a

1 file changed

Lines changed: 41 additions & 30 deletions

File tree

app/providers/zai_provider.py

Lines changed: 41 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def get_zai_dynamic_headers(chat_id: str = "") -> Dict[str, str]:
6969
"Cache-Control": "no-cache",
7070
"User-Agent": user_agent,
7171
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
72-
"X-FE-Version": "prod-fe-1.0.103",
72+
"X-FE-Version": "prod-fe-1.0.104",
7373
"Origin": "https://chat.z.ai",
7474
}
7575

@@ -117,20 +117,21 @@ def _extract_user_id_from_token(token: str) -> str:
117117
return "guest"
118118

119119

120-
def generate_signature(message_text: str, request_id: str, timestamp_ms: int, user_id: str, secret: str = "junjie") -> str:
120+
def generate_signature(message_text: str, request_id: str, timestamp_ms: int, user_id: str = "", secret: str = "") -> str:
121121
"""Dual-layer HMAC-SHA256 signature matching Z.AI's zs function.
122122
123-
- e: requestId,<id>,timestamp,<ts>,user_id,<uid>
123+
New algorithm (2025):
124+
- e: request_id (just the UUID string)
124125
- t: message_text
125-
- s/i: timestamp_ms
126+
- i: timestamp_ms (as string)
126127
- w: base64(utf8_encode(t))
127128
- c: e|w|i
128-
- E: floor(timestamp_ms / 300000)
129+
- E: floor(timestamp_ms / (5 * 60 * 1000))
129130
- A: HMAC_SHA256(secret, E)
130-
- k: HMAC_SHA256(A, c)
131+
- signature: HMAC_SHA256(A, c)
131132
"""
132-
# e = requestId,<id>,timestamp,<ts>,user_id,<uid>
133-
e = f"requestId,{request_id},timestamp,{timestamp_ms},user_id,{user_id}"
133+
# e = request_id (simplified from previous complex format)
134+
e = request_id
134135

135136
# t = message_text, encode to UTF-8 then base64 (matching btoa behavior)
136137
t = message_text or ""
@@ -147,10 +148,10 @@ def generate_signature(message_text: str, request_id: str, timestamp_ms: int, us
147148
window_index = timestamp_ms // (5 * 60 * 1000)
148149

149150
# A = HMAC_SHA256(secret, window_index)
150-
root_key = (secret or "junjie").encode("utf-8")
151+
root_key = secret.encode("utf-8")
151152
derived_hex = hmac.new(root_key, str(window_index).encode("utf-8"), hashlib.sha256).hexdigest()
152153

153-
# k = HMAC_SHA256(A, c)
154+
# signature = HMAC_SHA256(A, c)
154155
signature = hmac.new(derived_hex.encode("utf-8"), c.encode("utf-8"), hashlib.sha256).hexdigest()
155156

156157
return signature
@@ -669,39 +670,49 @@ async def transform_request(self, request: OpenAIRequest) -> Dict[str, Any]:
669670
if request.max_tokens is not None:
670671
body["params"]["max_tokens"] = request.max_tokens
671672

672-
# 构建请求头
673-
headers = {
674-
"Authorization": f"Bearer {token}",
675-
"X-Signature": "",
676-
"Content-Type": "application/json"
677-
}
678-
679673
# Dual-layer HMAC signing metadata and header
680674
user_id = _extract_user_id_from_token(token)
681675
timestamp_ms = int(time.time() * 1000)
682676
request_id = generate_uuid()
683-
secret = os.getenv("ZAI_SIGNING_SECRET", "junjie") or "junjie"
684-
signature = generate_signature(
685-
message_text=last_user_text,
686-
request_id=request_id,
687-
timestamp_ms=timestamp_ms,
688-
user_id=user_id,
689-
secret=secret,
690-
)
691-
677+
secret = os.getenv("ZAI_SIGNING_SECRET", "key-@@@@)))()((9))-xxxx&&&%%%%%") or "key-@@@@)))()((9))-xxxx&&&%%%%%"
678+
679+
try:
680+
signature = generate_signature(
681+
message_text=last_user_text,
682+
request_id=request_id,
683+
timestamp_ms=timestamp_ms,
684+
user_id=user_id,
685+
secret=secret,
686+
)
687+
logger.debug(f"[Z.AI] 生成签名成功: {signature[:16]}... (user_id={user_id}, request_id={request_id})")
688+
except Exception as e:
689+
logger.error(f"[Z.AI] 签名生成失败: {e}")
690+
signature = ""
691+
692+
# 构建请求头 (匹配 X-FE-Version 和 X-Signature)
693+
headers = {
694+
"Authorization": f"Bearer {token}",
695+
"Content-Type": "application/json",
696+
"X-FE-Version": "prod-fe-1.0.104",
697+
"X-Signature": signature,
698+
}
699+
692700
query_params = {
693701
"timestamp": str(timestamp_ms),
694702
"requestId": request_id,
695703
"user_id": user_id,
696-
"token": token or "",
697-
"version": "1.0.103",
704+
"token": token,
705+
"version": "0.0.1",
698706
"platform": "web",
699707
"current_url": f"https://chat.z.ai/c/{chat_id}",
700708
"pathname": f"/c/{chat_id}",
701-
"signature_timestamp": timestamp_ms,
709+
"signature_timestamp": str(timestamp_ms),
702710
}
703711
signed_url = f"{self.config.api_endpoint}?{urlencode(query_params)}"
704-
headers["X-Signature"] = signature
712+
713+
# 记录请求详情用于调试
714+
logger.debug(f"[Z.AI] 请求头: Authorization=Bearer *****, X-Signature={signature[:16] if signature else '(空)'}...")
715+
logger.debug(f"[Z.AI] URL 参数: timestamp={timestamp_ms}, requestId={request_id}, user_id={user_id}")
705716

706717
# 存储当前token用于错误处理
707718
self._current_token = token

0 commit comments

Comments
 (0)