import hashlib import hmac import secrets as _secrets import time from urllib.parse import quote, urlencode def _hex(secret: str, message: bytes) -> str: return hmac.new(secret.encode(), message, hashlib.sha256).hexdigest() def sign_launch_url(secret, placement, user_id, sub_ids=None, ts=None, nonce=None): """Signed wall launch URL (sdk.md 2.1).""" sub_ids = sub_ids or {} keys = sorted(sub_ids) sub = "&".join(f"{quote(k, safe='')}={quote(sub_ids[k], safe='')}" for k in keys) ts = str(int(time.time()) if ts is None else ts) nonce = nonce or _secrets.token_hex(16) message = "\n".join(["krin-launch-v1", placement, user_id, ts, nonce, sub]) sig = _hex(secret, message.encode()) params = [("placement", placement), ("user_id", user_id), ("ts", ts), ("nonce", nonce), ("sig", sig)] params += [(f"sub_ids[{k}]", sub_ids[k]) for k in keys] return "https://wall.krin.io/w?" + urlencode(params, quote_via=quote) def verify_postback_post(raw_body: bytes, header: str, secrets: list, now=None) -> bool: """POST reward postback: raw_body is the exact bytes KRIN sent.""" now = int(time.time()) if now is None else now t, sigs = None, [] for part in header.split(","): key, _, value = part.strip().partition("=") if key == "t": t = value elif key == "v1": sigs.append(value) if not t or not t.isdigit() or abs(now - int(t)) > 300: return False for secret in secrets: expected = _hex(secret, t.encode() + b"." + raw_body) if any(hmac.compare_digest(expected, v) for v in sigs): return True return False def verify_postback_get(q: dict, secrets: list, now=None) -> bool: """GET reward postback (krin-pb-v2): q holds the decoded query values. A True result with q["test"] == "1" is a test postback: never credit it.""" now = int(time.time()) if now is None else now ts = str(q.get("ts", "")) if not ts.isdigit() or abs(now - int(ts)) > 300: return False test = str(q.get("test", "")) if test not in ("0", "1"): return False message = "\n".join(["krin-pb-v2", ts] + [str(q.get(k, "")) for k in ("conversion_id", "kind", "user_id", "reward", "payout_micros")] + [test]) return any(hmac.compare_digest(_hex(s, message.encode()), str(q.get("sig", ""))) for s in secrets) def sign_inbound(secret, offer_key, click_id, event, txn_id="", ts=None): """Advertiser S2S conversion to t.krin.io (postbacks.md 4.1, signature v2). The signature covers the request exactly as sent: method, host, path and the query without sig.""" host = "t.krin.io" path = "/pb/" + quote(offer_key, safe="") params = [("click_id", click_id), ("event", event)] if txn_id: params.append(("txn_id", txn_id)) params.append(("ts", str(int(time.time()) if ts is None else ts))) query = urlencode(params, quote_via=quote) sig = _hex(secret, "\n".join(["krin-in-v2", "GET", host, path, query]).encode()) return f"https://{host}{path}?{query}&sig={sig}"