Shield external portal jumps (keep EXTERNAL_* for later), serve /nav from static build, and proxy /book + /community to vertical Next apps with Caddy notes. Co-authored-by: Cursor <cursoragent@cursor.com>
113 lines
3.5 KiB
Python
113 lines
3.5 KiB
Python
"""微信小程序消息推送:URL 校验 + 可选加解密。"""
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import struct
|
||
from typing import Any
|
||
|
||
import xmltodict
|
||
from Crypto.Cipher import AES
|
||
|
||
from app.config import settings
|
||
|
||
|
||
def check_signature(signature: str, timestamp: str, nonce: str) -> bool:
|
||
token = settings.wx_push_token
|
||
items = sorted([token, timestamp or "", nonce or ""])
|
||
digest = hashlib.sha1("".join(items).encode("utf-8")).hexdigest()
|
||
return digest == (signature or "")
|
||
|
||
|
||
def check_msg_signature(msg_signature: str, timestamp: str, nonce: str, encrypt: str) -> bool:
|
||
token = settings.wx_push_token
|
||
items = sorted([token, timestamp or "", nonce or "", encrypt or ""])
|
||
digest = hashlib.sha1("".join(items).encode("utf-8")).hexdigest()
|
||
return digest == (msg_signature or "")
|
||
|
||
|
||
def _aes_key() -> bytes:
|
||
key = settings.wx_push_encoding_aes_key.strip()
|
||
return base64.b64decode(key + "=")
|
||
|
||
|
||
def _pkcs7_unpad(data: bytes) -> bytes:
|
||
pad = data[-1]
|
||
if pad < 1 or pad > 32:
|
||
pad = 0
|
||
return data[:-pad]
|
||
|
||
|
||
def _pkcs7_pad(data: bytes, block: int = 32) -> bytes:
|
||
amount = block - (len(data) % block)
|
||
if amount == 0:
|
||
amount = block
|
||
return data + bytes([amount] * amount)
|
||
|
||
|
||
def decrypt_message(encrypt_b64: str) -> str:
|
||
aes_key = _aes_key()
|
||
cipher = AES.new(aes_key, AES.MODE_CBC, aes_key[:16])
|
||
plain = _pkcs7_unpad(cipher.decrypt(base64.b64decode(encrypt_b64)))
|
||
msg_len = struct.unpack("!I", plain[16:20])[0]
|
||
msg = plain[20 : 20 + msg_len]
|
||
return msg.decode("utf-8")
|
||
|
||
|
||
def encrypt_message(reply: str) -> str:
|
||
aes_key = _aes_key()
|
||
random16 = os.urandom(16)
|
||
msg = reply.encode("utf-8")
|
||
appid = settings.wx_appid.encode("utf-8")
|
||
packed = random16 + struct.pack("!I", len(msg)) + msg + appid
|
||
cipher = AES.new(aes_key, AES.MODE_CBC, aes_key[:16])
|
||
encrypted = cipher.encrypt(_pkcs7_pad(packed))
|
||
return base64.b64encode(encrypted).decode("utf-8")
|
||
|
||
|
||
def build_encrypted_response(reply: str, nonce: str, timestamp: str) -> str:
|
||
encrypt = encrypt_message(reply)
|
||
items = sorted([settings.wx_push_token, timestamp, nonce, encrypt])
|
||
signature = hashlib.sha1("".join(items).encode("utf-8")).hexdigest()
|
||
return (
|
||
"<xml>"
|
||
f"<Encrypt><![CDATA[{encrypt}]]></Encrypt>"
|
||
f"<MsgSignature><![CDATA[{signature}]]></MsgSignature>"
|
||
f"<TimeStamp>{timestamp}</TimeStamp>"
|
||
f"<Nonce><![CDATA[{nonce}]]></Nonce>"
|
||
"</xml>"
|
||
)
|
||
|
||
|
||
def parse_notify_body(text: str, query: dict[str, str]) -> dict[str, Any]:
|
||
"""解析推送正文;兼容明文 / 兼容 / 安全模式,XML / JSON。"""
|
||
root: dict[str, Any] = {}
|
||
try:
|
||
if text.strip().startswith("{"):
|
||
root = json.loads(text)
|
||
else:
|
||
parsed = xmltodict.parse(text)
|
||
root = parsed.get("xml") or parsed
|
||
except Exception:
|
||
return {}
|
||
|
||
if not isinstance(root, dict):
|
||
return {}
|
||
|
||
enc = root.get("Encrypt") or root.get("encrypt")
|
||
if enc:
|
||
msg_sig = query.get("msg_signature") or query.get("signature") or ""
|
||
if msg_sig and not check_msg_signature(
|
||
msg_sig, query.get("timestamp", ""), query.get("nonce", ""), str(enc)
|
||
):
|
||
# 仍尝试解密,部分环境签名字段名不同
|
||
pass
|
||
plain = decrypt_message(str(enc))
|
||
if plain.strip().startswith("{"):
|
||
return json.loads(plain)
|
||
parsed = xmltodict.parse(plain)
|
||
return parsed.get("xml") or parsed
|
||
return root
|