Line data Source code
1 4 : (ns matchscore.utils.telegram-auth
2 : (:require
3 : [clojure.string :as str]
4 : [ring.util.codec :as codec]
5 : [taoensso.telemere :as t])
6 : (:import
7 : (java.nio.charset StandardCharsets)
8 : (javax.crypto Mac)
9 : (javax.crypto.spec SecretKeySpec)))
10 :
11 :
12 : ;; https://github.com/tofitaV/TelegramDataValidation/blob/main/src/main/java/org/tg/auth/TelegramAuth.java
13 : ;; https://github.com/nimaxin/init-data-py/tree/master
14 :
15 :
16 4 : (defn hmac-sha256
17 : [key data]
18 6 : (let [algorithm "HmacSHA256"
19 9 : mac (Mac/getInstance algorithm)
20 9 : secret-key (SecretKeySpec. key algorithm)]
21 6 : (.init mac secret-key)
22 6 : (.doFinal mac data)))
23 :
24 :
25 4 : (defn bytes-to-hex
26 : "Convert a byte array to a lowercase hex string."
27 : [bytes]
28 20 : (str/join (map #(format "%02x" %) bytes)))
29 :
30 :
31 4 : (defn valid?
32 : "Validate Telegram Web App init data against a bot token.
33 : Args:
34 : init-data (str): Query string (e.g., 'query_id=abc123&user=...&hash=...').
35 : bot-token (str): Bot token.
36 : Returns:
37 : bool: True if valid, false otherwise."
38 : [init-data bot-token & {:keys [lifetime-ms]}]
39 3 : (try
40 : ;; Log raw input for debugging
41 : ;; Parse query string
42 8 : (let [params (codec/form-decode init-data)
43 6 : hash (get params "hash")
44 6 : auth-date (get params "auth_date")]
45 : ;; Validate required fields
46 34 : (if (or (nil? hash) (nil? auth-date) (not (re-matches #"\d+" auth-date)))
47 : false
48 :
49 : ;; Build data-check-string
50 3 : (let [data-check-string (->>
51 4 : (dissoc params "hash")
52 3 : (sort-by key)
53 2 : (map
54 1 : (fn [[k v]]
55 5 : (str k "=" v)))
56 1 : (str/join "\n"))
57 2 : data-check-bytes (.getBytes data-check-string StandardCharsets/UTF_8)
58 :
59 : ;; Compute secret_key: HMAC-SHA256("WebAppData", bot-token)
60 2 : secret-key-new (hmac-sha256
61 3 : (.getBytes "WebAppData" StandardCharsets/UTF_8)
62 2 : (.getBytes bot-token StandardCharsets/UTF_8))
63 :
64 : ;; Compute hash: HMAC-SHA256(data-check-string, secret-key)
65 6 : computed-hash (bytes-to-hex (hmac-sha256 secret-key-new data-check-bytes))
66 :
67 : ;; Check auth_date (1-hour lifetime)
68 5 : auth-date-ms (* (Long/parseLong auth-date) 1000)]
69 : ;; Return true if hash matches and auth_date is less than lifetime-ms
70 6 : (and
71 3 : (= hash computed-hash)
72 7 : (if lifetime-ms (<= (- (System/currentTimeMillis) auth-date-ms) lifetime-ms) true)))))
73 96 : (catch Exception e (t/log! :error (str "Error:" (.getMessage e))) false)))
|