You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import base64
  2. import hashlib
  3. import hmac
  4. import os
  5. import time
  6. from configs import dify_config
  7. def sign_tool_file(tool_file_id: str, extension: str) -> str:
  8. """
  9. sign file to get a temporary url for plugin access
  10. """
  11. # Use internal URL for plugin/tool file access in Docker environments
  12. base_url = dify_config.INTERNAL_FILES_URL or dify_config.FILES_URL
  13. file_preview_url = f"{base_url}/files/tools/{tool_file_id}{extension}"
  14. timestamp = str(int(time.time()))
  15. nonce = os.urandom(16).hex()
  16. data_to_sign = f"file-preview|{tool_file_id}|{timestamp}|{nonce}"
  17. secret_key = dify_config.SECRET_KEY.encode() if dify_config.SECRET_KEY else b""
  18. sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  19. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  20. return f"{file_preview_url}?timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"
  21. def verify_tool_file_signature(file_id: str, timestamp: str, nonce: str, sign: str) -> bool:
  22. """
  23. verify signature
  24. """
  25. data_to_sign = f"file-preview|{file_id}|{timestamp}|{nonce}"
  26. secret_key = dify_config.SECRET_KEY.encode() if dify_config.SECRET_KEY else b""
  27. recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  28. recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()
  29. # verify signature
  30. if sign != recalculated_encoded_sign:
  31. return False
  32. current_time = int(time.time())
  33. return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT