upload.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. #!/usr/bin/env python3
  2. """
  3. Upload an .excalidraw file to excalidraw.com and print a shareable URL.
  4. No account required. The diagram is encrypted client-side (AES-GCM) before
  5. upload -- the encryption key is embedded in the URL fragment, so the server
  6. never sees plaintext.
  7. Requirements:
  8. pip install cryptography
  9. Usage:
  10. python upload.py <path-to-file.excalidraw>
  11. Example:
  12. python upload.py ~/diagrams/architecture.excalidraw
  13. # prints: https://excalidraw.com/#json=abc123,encryptionKeyHere
  14. """
  15. import json
  16. import os
  17. import struct
  18. import sys
  19. import zlib
  20. import base64
  21. import urllib.request
  22. try:
  23. from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  24. except ImportError:
  25. print("Error: 'cryptography' package is required for upload.")
  26. print("Install it with: pip install cryptography")
  27. sys.exit(1)
  28. # Excalidraw public upload endpoint (no auth needed)
  29. UPLOAD_URL = "https://json.excalidraw.com/api/v2/post/"
  30. def concat_buffers(*buffers: bytes) -> bytes:
  31. """
  32. Build the Excalidraw v2 concat-buffers binary format.
  33. Layout: [version=1 (4B big-endian)] then for each buffer:
  34. [length (4B big-endian)] [data bytes]
  35. """
  36. parts = [struct.pack(">I", 1)] # version = 1
  37. for buf in buffers:
  38. parts.append(struct.pack(">I", len(buf)))
  39. parts.append(buf)
  40. return b"".join(parts)
  41. def upload(excalidraw_json: str) -> str:
  42. """
  43. Encrypt and upload Excalidraw JSON to excalidraw.com.
  44. Args:
  45. excalidraw_json: The full .excalidraw file content as a string.
  46. Returns:
  47. Shareable URL string.
  48. """
  49. # 1. Inner payload: concat_buffers(file_metadata, data)
  50. file_metadata = json.dumps({}).encode("utf-8")
  51. data_bytes = excalidraw_json.encode("utf-8")
  52. inner_payload = concat_buffers(file_metadata, data_bytes)
  53. # 2. Compress with zlib
  54. compressed = zlib.compress(inner_payload)
  55. # 3. AES-GCM 128-bit encrypt
  56. raw_key = os.urandom(16) # 128-bit key
  57. iv = os.urandom(12) # 12-byte nonce
  58. aesgcm = AESGCM(raw_key)
  59. encrypted = aesgcm.encrypt(iv, compressed, None)
  60. # 4. Encoding metadata
  61. encoding_meta = json.dumps({
  62. "version": 2,
  63. "compression": "pako@1",
  64. "encryption": "AES-GCM",
  65. }).encode("utf-8")
  66. # 5. Outer payload: concat_buffers(encoding_meta, iv, encrypted)
  67. payload = concat_buffers(encoding_meta, iv, encrypted)
  68. # 6. Upload
  69. req = urllib.request.Request(UPLOAD_URL, data=payload, method="POST")
  70. with urllib.request.urlopen(req, timeout=30) as resp:
  71. if resp.status != 200:
  72. raise RuntimeError(f"Upload failed with HTTP {resp.status}")
  73. result = json.loads(resp.read().decode("utf-8"))
  74. file_id = result.get("id")
  75. if not file_id:
  76. raise RuntimeError(f"Upload returned no file ID. Response: {result}")
  77. # 7. Key as base64url (JWK 'k' format, no padding)
  78. key_b64 = base64.urlsafe_b64encode(raw_key).rstrip(b"=").decode("ascii")
  79. return f"https://excalidraw.com/#json={file_id},{key_b64}"
  80. def main():
  81. if len(sys.argv) < 2:
  82. print("Usage: python upload.py <path-to-file.excalidraw>")
  83. sys.exit(1)
  84. file_path = sys.argv[1]
  85. if not os.path.isfile(file_path):
  86. print(f"Error: File not found: {file_path}")
  87. sys.exit(1)
  88. with open(file_path, "r", encoding="utf-8") as f:
  89. content = f.read()
  90. # Basic validation: should be valid JSON with an "elements" key
  91. try:
  92. doc = json.loads(content)
  93. except json.JSONDecodeError as e:
  94. print(f"Error: File is not valid JSON: {e}")
  95. sys.exit(1)
  96. if "elements" not in doc:
  97. print("Warning: File does not contain an 'elements' key. Uploading anyway.")
  98. url = upload(content)
  99. print(url)
  100. if __name__ == "__main__":
  101. main()