"""Educational HMAC envelope, not a Stripe SDK or HTTP endpoint."""
import hashlib,hmac,json,re
from pathlib import Path
ROOT=Path(__file__).resolve().parent
KEY=b'public-fixture-key-not-for-deployment'
NOW=1800000000
BODY=b'{"id":"event-1", "value":7}'
def sign(body,ts,key=KEY):
 return hmac.new(key,str(ts).encode('ascii')+b'.'+body,hashlib.sha256).hexdigest()
def verify(body,ts,signature,now=NOW):
 if type(ts) is not int or len(body)>4096:return False
 if not isinstance(signature,str) or not re.fullmatch(r'[0-9a-f]{64}',signature):return False
 if not hmac.compare_digest(sign(body,ts),signature):return False
 return -30 <= now-ts <= 300
signature=sign(BODY,NOW)
rows=[]
def check(name,body,ts,sig,expected,now=NOW):
 actual=verify(body,ts,sig,now);assert actual is expected
 rows.append(dict(case=name,accepted=actual,expected=expected))
check('original bytes',BODY,NOW,signature,True)
reserialized=json.dumps(json.loads(BODY),separators=(',',':')).encode()
assert json.loads(reserialized)==json.loads(BODY) and reserialized!=BODY
check('equivalent JSON different bytes',reserialized,NOW,signature,False)
check('wrong endpoint key',BODY,NOW,sign(BODY,NOW,b'another-public-test-key'),False)
check('modified body',BODY.replace(b'7',b'8'),NOW,signature,False)
check('old timestamp still authentic',BODY,NOW-301,sign(BODY,NOW-301),False)
check('future beyond policy',BODY,NOW+31,sign(BODY,NOW+31),False)
check('malformed signature',BODY,NOW,'zz',False)
check('same delivery again in window',BODY,NOW,signature,True,now=NOW+1)
seen=set();effects=0
for _ in range(2):
 assert verify(BODY,NOW,signature)
 event=json.loads(BODY)
 if event['id'] not in seen:seen.add(event['id']);effects+=1
assert effects==1
(ROOT/'results.json').write_text(json.dumps(dict(checks=rows,checksCount=8,accepted=2,rejected=6,duplicateDeliveryEffects=effects,freshnessPolicySeconds=dict(maxAge=300,maxFuture=30),scope='Exact HMAC input and a local deduplication set. No HTTP parser, SDK conformance, durable ledger or timing benchmark.'),indent=2)+'\n')
print('8 signature checks passed; duplicate example effects:',effects)
