From dd7567f43c658cd03f60784907ca0ad0b18f0be4 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Mon, 18 Apr 2022 17:26:09 +0600 Subject: [PATCH] add checking of data in web app --- .../kotlin/dev/inmo/tgbotapi/webapps/CryptoJSExtensions.kt | 7 +++++++ .../src/jsMain/kotlin/dev/inmo/tgbotapi/webapps/WebApp.kt | 6 ++++++ 2 files changed, 13 insertions(+) create mode 100644 tgbotapi.webapps/src/jsMain/kotlin/dev/inmo/tgbotapi/webapps/CryptoJSExtensions.kt diff --git a/tgbotapi.webapps/src/jsMain/kotlin/dev/inmo/tgbotapi/webapps/CryptoJSExtensions.kt b/tgbotapi.webapps/src/jsMain/kotlin/dev/inmo/tgbotapi/webapps/CryptoJSExtensions.kt new file mode 100644 index 0000000000..4e24f9e9e0 --- /dev/null +++ b/tgbotapi.webapps/src/jsMain/kotlin/dev/inmo/tgbotapi/webapps/CryptoJSExtensions.kt @@ -0,0 +1,7 @@ +package dev.inmo.tgbotapi.webapps + +import dev.inmo.micro_utils.crypto.CryptoJs + +fun CryptoJs.HmacSHA256(text: String, key: String) = this.asDynamic().HmacSHA256(text, key).unsafeCast() + +fun CryptoJs.hex(text: String) = this.asDynamic().format.Hex(text).unsafeCast() diff --git a/tgbotapi.webapps/src/jsMain/kotlin/dev/inmo/tgbotapi/webapps/WebApp.kt b/tgbotapi.webapps/src/jsMain/kotlin/dev/inmo/tgbotapi/webapps/WebApp.kt index 8a21b744a7..fbba60f883 100644 --- a/tgbotapi.webapps/src/jsMain/kotlin/dev/inmo/tgbotapi/webapps/WebApp.kt +++ b/tgbotapi.webapps/src/jsMain/kotlin/dev/inmo/tgbotapi/webapps/WebApp.kt @@ -1,5 +1,7 @@ package dev.inmo.tgbotapi.webapps +import dev.inmo.micro_utils.crypto.CryptoJS + external class WebApp { val initData: String val initDataUnsafe: WebAppInitData @@ -73,3 +75,7 @@ fun WebApp.onMainButtonClicked(eventHandler: EventHandler) = onEvent(EventType.M * @return The callback which should be used in case you want to turn off events handling */ fun WebApp.onViewportChanged(eventHandler: ViewportChangedEventHandler) = onEvent(EventType.ViewportChanged, eventHandler) + +fun WebApp.isInitDataSafe(botToken: String) = CryptoJS.hex( + CryptoJS.HmacSHA256(botToken, "WebAppData") +) == initDataUnsafe.hash