#!/usr/bin/env python3
"""
解密飞书 UAT（用户访问令牌）
"""
import os
import json
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

# 路径
LINUX_UAT_DIR = os.path.expanduser("~/.local/share/openclaw-feishu-uat")
MASTER_KEY_PATH = os.path.join(LINUX_UAT_DIR, "master.key")
ENCRYPTED_FILE = os.path.join(LINUX_UAT_DIR, "cli_a93815b250b9dcb5_ou_86def554b50f91972e2924a605ccf634.enc")

# 常量
IV_BYTES = 12
TAG_BYTES = 16

def decrypt_uat():
    # 读取 master key
    with open(MASTER_KEY_PATH, "rb") as f:
        key = f.read()
    
    # 读取加密文件
    with open(ENCRYPTED_FILE, "rb") as f:
        data = f.read()
    
    # 解析加密数据：[12-byte IV][16-byte tag][ciphertext]
    iv = data[:IV_BYTES]
    tag = data[IV_BYTES:IV_BYTES + TAG_BYTES]
    ciphertext = data[IV_BYTES + TAG_BYTES:]
    
    # 解密
    aesgcm = AESGCM(key)
    plaintext = aesgcm.decrypt(iv, ciphertext + tag, None)
    
    # 解析 JSON
    token_data = json.loads(plaintext.decode('utf-8'))
    return token_data

if __name__ == "__main__":
    token_data = decrypt_uat()
    print("解密成功！")
    print(f"用户 OpenID: {token_data.get('user_open_id')}")
    print(f"访问令牌: {token_data.get('access_token', '')[:20]}...")
    print(f"刷新令牌: {token_data.get('refresh_token', '')[:20]}...")
    print(f"过期时间: {token_data.get('expires_at')}")
    print(f"\n完整数据：")
    print(json.dumps(token_data, indent=2))
