import hmac
import hashlib
import base64
# Provided Base64-encoded secret from your Deck dashboard.
# IMPORTANT: Replace `<<YOUR_DECK_WEBHOOK_SECRET_FROM_DASHBOARD>>` with your actual secret.
# This secret should be kept confidential.
secret_base64 = "<<YOUR_DECK_WEBHOOK_SECRET_FROM_DASHBOARD>>"
# JSON body payload as a raw string.
# This must match the webhook event body exactly, byte-for-byte, as received.
# This is an EXAMPLE Webhook Event Body.
body = '{"link_token":"link-production-77bd1897-b21b-4eb8-fca6-08dda362f7ed","public_token":"public-production-b7500d0c-920d-46cf-44eb-08dda3634c66","webhook_type":"Link","webhook_code":"ConnectionCreated","environment":"Production"}'
# --- Signature Calculation ---
# Decode the Base64 secret into raw bytes.
# In Python, the hmac module expects a bytes-like object for the key.
key_bytes = base64.b64decode(secret_base64)
# The message body must also be encoded to bytes.
body_bytes = body.encode('utf-8')
# Create the HMAC-SHA256 hash.
# hashlib.sha256 is the hashing algorithm.
# key_bytes is the secret key.
hmac_sha256 = hmac.new(key_bytes, body_bytes, hashlib.sha256)
# Compute the signature digest and encode it to Base64.
# .digest() returns the raw byte hash.
# base64.b64encode() encodes these bytes to Base64.
# .decode('utf-8') converts the resulting bytes to a string for printing.
computed_signature = base64.b64encode(hmac_sha256.digest()).decode('utf-8')
# --- Output ---
# Replace `<<X_SIGNATURE_FROM_HEADER>>` with the signature you receive in the X-Signature header
# from the webhook request. You'll compare your computed signature against this.
print("Expected Signature (from header):", "<<X_SIGNATURE_FROM_HEADER>>")
print("Computed Signature:", computed_signature)
# You would then compare `computed_signature` with the `X-Signature` header value
# received in your webhook request to verify its authenticity.
if computed_signature == "<<X_SIGNATURE_FROM_HEADER>>":
print("\nSignature verification successful! The webhook is authentic.")
else:
print("\nSignature verification FAILED! The webhook may be tampered with or invalid.")