-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
<script setup> | ||
import { ref, provide } from 'vue'; | ||
import WebApp from '@twa-dev/sdk'; | ||
import hmac from 'js-crypto-hmac'; | ||
const props = defineProps({ | ||
bot_token: { | ||
type: String, | ||
required: true, | ||
} | ||
}); | ||
const clientAuthorized = ref(null); | ||
const ksort = (obj) => { | ||
const sortedKeys = Object.keys(obj).sort(); | ||
const sortedObj = {}; | ||
sortedKeys.forEach(key => { | ||
sortedObj[key] = obj[key]; | ||
}); | ||
return sortedObj; | ||
}; | ||
const buffer2Hex = (buffer) => { | ||
return [...new Uint8Array(buffer)] | ||
.map(x => x.toString(16).padStart(2, '0')) | ||
.join(''); | ||
} | ||
let initDataUnsafe = {...WebApp.initDataUnsafe}; | ||
let initDataHash = initDataUnsafe.hash; | ||
let initDataString = ''; | ||
delete initDataUnsafe['hash']; | ||
initDataUnsafe = ksort(initDataUnsafe); | ||
initDataString = Object.entries(initDataUnsafe) | ||
.map(([key, value]) => { | ||
value = typeof value === 'object' ? JSON.stringify(value, null, 0) : value; | ||
return `${key}=${value}`; | ||
}) | ||
.join('\n'); | ||
hmac.compute(new TextEncoder().encode("WebAppData"), new TextEncoder().encode(props.bot_token), 'SHA-256').then((secret_key) => { | ||
hmac.compute(secret_key, new TextEncoder().encode(initDataString), 'SHA-256').then((result) => { | ||
clientAuthorized.value = buffer2Hex(result) === initDataHash; | ||
}); | ||
}); | ||
</script> | ||
|
||
<template> | ||
<slot v-if="clientAuthorized" /> | ||
<slot v-else name="unauthorized"> | ||
Unauthorized Telegram Client | ||
</slot> | ||
</template> | ||
|
||
<style lang="scss"> | ||
</style> |