""" 企微群入站「加密 open_userid → 明文 userid」归一。 为什么单独一个文件(2026-11-19 真机问题): - 企微智能机器人回调 `from.userid` 只有在「机器人创建者是超级管理员」时才是明文; 否则是企业主体下的加密 open_userid(`wo` 开头,约 35 位)。 - 群里成交/未成交、航线报价、锁舱、产品报价都要拿这个 ID 跟主账 `sales_wecom_id` 和岗位名单做字符串比较;加密值永远比不上,业务全被判成「不是本人」。 真机日志证据:`sender=woDK6DYQAAQZ...` → `phase=not_sales`,而主账记的是 `LuoXiaoHua`;同一句走会话存档(明文)就能办成。 - 官方提供 `cgi-bin/batch/openuserid_to_userid` 把它换回明文,前提是成员在该 自建应用的可见范围内。这里做的就是「解密同一个入站 ID」,不是事后向企微补身份, 身份来源仍然是入站报文,符合 prompt/06、09 的身份约束。 职责: - `looks_like_open_userid`:只做形态判断,不打网络。 - `resolve_open_userid`:换明文;命中 Redis 缓存不重复打企微。 副作用: - 会打企微 HTTPS(`WECOM_OPENID_NORMALIZE_ENABLED=true` 时),超时默认 3 秒。 - 只写 Redis 短缓存(ID 映射,不是六态、不是 checkpoint)。 - 不写日志正文、不打印密钥。 禁止: - 在回调请求线程调用(会拖慢秒回);只允许在 inbox 工作线程调用。 - 把换不到明文的 ID 当成「不是本人」直接拒绝;调用方必须走「存档兜底」。 """ from __future__ import annotations import logging import threading from typing import Optional import httpx from agent.config import get_settings logger = logging.getLogger(__name__) # 企微开放接口基址;与出站客户端一致,不写死业务域名。 _API_BASE = "https://qyapi.weixin.qq.com" # 换成功一次就够用很久:userid 极少变,7 天足够,过期自动再换一次。 _HIT_TTL_SECONDS = 7 * 24 * 3600 # 换不到(不在应用可见范围)不能一直重试打接口:10 分钟后再试,管理员加权限后能自愈。 _MISS_TTL_SECONDS = 600 _OPENID_PREFIX = "wecom:openid2userid:" _MISS_VALUE = "#miss" # access_token 由同一个进程内客户端缓存;多线程共用一把小锁只保护客户端创建。 _client_lock = threading.Lock() _client_cache: dict[str, object] = {} def looks_like_open_userid(value: str) -> bool: """ 形态判断:是不是企微加密 open_userid。 明文 userid 是 `LuoXiaoHua` 这种短名字;加密值固定 `wo` 前缀且 30 位以上。 这里宁可判宽一点:判错只会多一次接口调用(有缓存),判漏会让业务被判「不是本人」。 """ text = (value or "").strip() return text.startswith("wo") and len(text) >= 20 def _redis_client(): """懒取 Redis 门面;连不上返回 None,归一化退化成每次都打接口。""" try: from agent.redis_coord.runtime import get_redis_runtime return get_redis_runtime().client except Exception: # noqa: BLE001 - 缓存不可用不能阻断业务 logger.warning("open_userid: Redis 不可用,跳过 ID 缓存", exc_info=True) return None def _cache_get(open_userid: str) -> str: """读缓存:返回明文 / 空串(未缓存) / `#miss`(上次换不到)。""" client = _redis_client() if client is None: return "" try: value = client.raw.get(client.key(_OPENID_PREFIX + open_userid)) return str(value or "").strip() except Exception: # noqa: BLE001 logger.warning("open_userid: 读缓存失败", exc_info=True) return "" def _cache_set(open_userid: str, value: str, ttl: int) -> None: """写缓存;失败只记日志,不影响本次结果。""" client = _redis_client() if client is None: return try: client.raw.set(client.key(_OPENID_PREFIX + open_userid), value, ex=ttl) except Exception: # noqa: BLE001 logger.warning("open_userid: 写缓存失败", exc_info=True) def _app_client(): """ 取企微自建应用客户端(只用于 access_token)。 复用模块级实例:每次新建都会重新取 token,群里消息一多就会打爆 gettoken 频控。 """ settings = get_settings() corp_id = str(settings.wecom_corp_id or "").strip() secret = str(settings.wecom_secret or "").strip() if not corp_id or not secret: return None key = f"{corp_id}:{settings.wecom_agent_id}" with _client_lock: cached = _client_cache.get(key) if cached is not None: return cached from agent.channel.outbox.sender import WeComAppClient client = WeComAppClient( corp_id=corp_id, secret=secret, agent_id=int(settings.wecom_agent_id or "0") or 0, ) _client_cache[key] = client return client def _fetch_plain(open_userids: list[str], *, timeout_sec: float) -> dict[str, str]: """ 调 `batch/openuserid_to_userid` 批量换明文。 返回 {open_userid: 明文};换不到的键不会出现在结果里(也不抛异常)。 """ client = _app_client() if client is None: logger.warning("open_userid: 未配置 WECOM_CORP_ID/SECRET,无法换明文") return {} try: token = client.get_access_token() except Exception: # noqa: BLE001 - token 失败等同换不到 logger.warning("open_userid: 取 access_token 失败", exc_info=True) return {} if not token: return {} url = f"{_API_BASE}/cgi-bin/batch/openuserid_to_userid" body = {"open_userid_list": list(open_userids)} try: # httpx 默认 INFO 会打印完整 URL(含 access_token),这里只打异常不打印 URL。 with httpx.Client(timeout=max(0.5, float(timeout_sec))) as http: resp = http.post(url, params={"access_token": token}, json=body) data = resp.json() except Exception: # noqa: BLE001 logger.warning("open_userid: 兑换接口调用失败", exc_info=True) return {} if int(data.get("errcode") or 0) != 0: logger.warning( "open_userid: 兑换失败 errcode=%s errmsg=%s", data.get("errcode"), str(data.get("errmsg") or "")[:120], ) return {} out: dict[str, str] = {} for row in data.get("userid_list") or []: if not isinstance(row, dict): continue src = str(row.get("open_userid") or "").strip() dst = str(row.get("userid") or "").strip() if src and dst: out[src] = dst return out def resolve_open_userid(sender_id: str, *, timeout_sec: Optional[float] = None) -> tuple[str, str]: """ 把群入站发言人的加密 ID 换回明文。 返回 `(明文或原值, 状态)`,状态语义: - `plain` :本来就是明文,调用方按可信处理; - `resolved` :换成了明文,调用方可以把明文当身份用; - `unresolved` :确实是加密 ID 但换不到(没配密钥 / 不在应用可见范围 / 接口失败), 调用方**不得**据此判「不是本人」,要让会话存档那条兜底; - `disabled` :开关关着,按原样返回,行为与改动前完全一致。 只在 inbox 工作线程调用;有缓存,命中不打网络。 """ text = (sender_id or "").strip() if not looks_like_open_userid(text): return text, "plain" settings = get_settings() if not bool(getattr(settings, "wecom_openid_normalize_enabled", False)): return text, "disabled" cached = _cache_get(text) if cached and cached != _MISS_VALUE: return cached, "resolved" if cached == _MISS_VALUE: return text, "unresolved" timeout = ( float(timeout_sec) if timeout_sec is not None else float(getattr(settings, "wecom_openid_normalize_timeout_sec", 3.0) or 3.0) ) found = _fetch_plain([text], timeout_sec=timeout) plain = str(found.get(text) or "").strip() if plain: _cache_set(text, plain, _HIT_TTL_SECONDS) # 不打印完整 ID,只留前 6 位,够对照日志又不泄露身份。 logger.info("open_userid 换明文成功 open=%s… userid=%s", text[:6], plain) return plain, "resolved" _cache_set(text, _MISS_VALUE, _MISS_TTL_SECONDS) logger.warning("open_userid 换不到明文 open=%s…(走存档兜底)", text[:6]) return text, "unresolved"