import asyncio import json import time import httpx class PlatformError(Exception): pass class Feishu: def __init__(self, settings, transport=None): self.settings = settings self.http = httpx.AsyncClient(base_url=settings.feishu_api_base.rstrip("/"), timeout=15, follow_redirects=False, transport=transport, trust_env=False) self._token = None self._expires = 0 self._tenant_token = None self._tenant_expires = 0 self._lock = asyncio.Lock() async def close(self): await self.http.aclose() async def _json(self, method, path, **kwargs): try: response = await self.http.request(method, path, **kwargs) response.raise_for_status() data = response.json() if data.get("code", 0) != 0: raise PlatformError("platform rejected request") return data except (httpx.HTTPError, ValueError, KeyError) as exc: # Never propagate upstream bodies or credentials to caller/logs. raise PlatformError("platform request failed") from None async def app_token(self): async with self._lock: if self._token and self._expires > time.monotonic() + 1800: return self._token data = await self._json("POST", "/open-apis/auth/v3/app_access_token/internal", json={"app_id": self.settings.feishu_app_id, "app_secret": self.settings.feishu_app_secret}) self._token = data["app_access_token"] self._expires = time.monotonic() + int(data.get("expire", 7200)) return self._token async def exchange(self, code): token = await self.app_token() data = await self._json("POST", "/open-apis/authen/v1/oidc/access_token", headers={"Authorization": f"Bearer {token}"}, json={"grant_type": "authorization_code", "code": code}) return self.normalize(data["data"]) async def tenant_token(self): async with self._lock: if self._tenant_token and self._tenant_expires > time.monotonic() + 1800: return self._tenant_token data = await self._json("POST", "/open-apis/auth/v3/tenant_access_token/internal", json={"app_id": self.settings.feishu_app_id, "app_secret": self.settings.feishu_app_secret}) self._tenant_token = data["tenant_access_token"] self._tenant_expires = time.monotonic() + int(data.get("expire", 7200)) return self._tenant_token async def refresh(self, refresh_token): token = await self.app_token() data = await self._json("POST", "/open-apis/authen/v1/oidc/refresh_access_token", headers={"Authorization": f"Bearer {token}"}, json={"grant_type": "refresh_token", "refresh_token": refresh_token}) result = self.normalize(data["data"]) info = await self.user_info(result["user_access_token"]) result["open_id"] = info["open_id"] return result @staticmethod def normalize(data): return {"user_access_token": data["access_token"], "refresh_token": data.get("refresh_token", ""), "expires_in": data.get("expires_in", data.get("expire", 0)), "refresh_expires_in": data.get("refresh_expires_in", 0), "open_id": data.get("open_id", "")} async def user_info(self, token): data = await self._json("GET", "/open-apis/authen/v1/user_info", headers={"Authorization": f"Bearer {token}"}) return data["data"] async def _credential_request(self, grant): """Strict stage-2 adapter; legacy OAuth normalization remains unchanged. Missing rotation fields are not silently defaulted; the Broker validates them and treats an ambiguous refresh as unknown rather than replaying it. """ try: token = await self.app_token() path = ("/open-apis/authen/v1/oidc/access_token" if grant["grant_type"] == "authorization_code" else "/open-apis/authen/v1/oidc/refresh_access_token") response = await self.http.post(path, headers={"Authorization": f"Bearer {token}"}, json=grant) response.raise_for_status() body = response.json() if not isinstance(body, dict) or type(body.get("code")) is not int or body["code"] != 0: raise ValueError() data = body["data"] result = {"user_access_token": data["access_token"], "refresh_token": data["refresh_token"], "expires_in": data.get("expires_in", data.get("expire")), "refresh_expires_in": data.get("refresh_expires_in")} if "scope" in data: result["scope"] = data["scope"] return result except Exception: raise PlatformError("credential platform request failed") from None async def credential_exchange(self, code): return await self._credential_request({"grant_type": "authorization_code", "code": code}) async def credential_refresh(self, refresh_token): return await self._credential_request({"grant_type": "refresh_token", "refresh_token": refresh_token}) async def reply(self, message_id, text): # Reply to the original message only: no caller-controlled recipient. token = await self.tenant_token() await self._json("POST", f"/open-apis/im/v1/messages/{message_id}/reply", headers={"Authorization": f"Bearer {token}"}, json={"msg_type": "text", "content": json.dumps({"text": text}, ensure_ascii=False)}) async def reply_task_card(self,message_id,card,delivery_id,*,token): import re if not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',message_id):raise PlatformError('invalid reply reference') data=await self._json('POST',f'/open-apis/im/v1/messages/{message_id}/reply', headers={'Authorization':'Bearer '+token},json={'msg_type':'interactive', 'content':json.dumps(card,ensure_ascii=False),'uuid':delivery_id}) result=data.get('data',{}).get('message_id') if not isinstance(result,str)or not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',result):raise PlatformError('card receipt invalid') return result async def update_task_card(self,message_id,card,*,token): import re if not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',message_id):raise PlatformError('invalid card reference') await self._json('PATCH',f'/open-apis/im/v1/messages/{message_id}', headers={'Authorization':'Bearer '+token},json={'content':json.dumps(card,ensure_ascii=False)}) async def download_message_file(self,message_id,file_key,max_bytes): import re if not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',message_id)or not re.fullmatch(r'[A-Za-z0-9_-]{1,256}',file_key):raise PlatformError('invalid file reference') token=await self.tenant_token() try: async with self.http.stream('GET',f'/open-apis/im/v1/messages/{message_id}/resources/{file_key}', params={'type':'file'},headers={'Authorization':'Bearer '+token},timeout=60)as response: if response.status_code!=200 or response.headers.get('content-type','').lower().startswith(('application/json','text/html')):raise PlatformError('message file download rejected') raw=bytearray() async for chunk in response.aiter_bytes(): raw.extend(chunk) if len(raw)>max_bytes:raise PlatformError('message file size limit') if not raw:raise PlatformError('empty message file') return bytes(raw) except httpx.HTTPError:raise PlatformError('message file download failed')from None async def upload_file(self,name,content,mime,*,token): data=await self._json('POST','/open-apis/im/v1/files',headers={'Authorization':'Bearer '+token}, data={'file_type':'stream','file_name':name},files={'file':(name,content,mime)},timeout=60) key=data.get('data',{}).get('file_key') import re if not isinstance(key,str)or not re.fullmatch(r'[A-Za-z0-9_-]{1,256}',key):raise PlatformError('file upload receipt invalid') return key async def reply_file(self,message_id,file_key,delivery_id,*,token): import re if not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',message_id):raise PlatformError('invalid reply reference') data=await self._json('POST',f'/open-apis/im/v1/messages/{message_id}/reply', headers={'Authorization':'Bearer '+token},json={'msg_type':'file','content':json.dumps({'file_key':file_key}), 'uuid':delivery_id}) message=data.get('data',{}).get('message_id') if not isinstance(message,str)or not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',message):raise PlatformError('file message receipt invalid') return message async def send(self, owner, msg_type, content, delivery_id, *, token=None): token = token or await self.tenant_token() data = await self._json('POST', '/open-apis/im/v1/messages', params={'receive_id_type': 'open_id'}, headers={'Authorization': 'Bearer ' + token}, json={'receive_id': owner, 'msg_type': msg_type, 'content': json.dumps(content, ensure_ascii=False), 'uuid': delivery_id}) return data.get('data', {})