Files
discordeno/packages/utils/src/token.ts
Fleny a7d645ec4b feat: Implement OAuth2 endpoints (#3114)
* add OAuth2 routes

* Add oauth2 methods to rest

* Add rest manager methods, Add token params

* Add authorization headers

* Add auth to editUserApplicationRoleConnection

* fix logging header always displaying bot as auth

* Add OAuth2Scope enum

* Start testing ratelimit handling

* Fix now scopes are separated by a space

* move webhook object to DiscordAccessTokenResponse

* convert payload to snake_case

* fix some typings

* more types fixes

* add support for upserting commands with tokens

* handle correctly ratelimit and concurrently

* add guild to DiscordAccessTokenResponse

* Add oauth2 create link function

* Fix removeTokenPrefix to support Bearer tokens

* update jsdoc comment for removeTokenPrefix

* fix removeTokenPrefix unit tests

* fix see link on getMember and getCurrentMember

* add bot helpers and fix some types

* Use objects to pass the bearer tokens

* fix Deno issue with Buffer.from

* Merge 'upstream/main' into feat/oauth2 to fix merge conflict

* Fix debug queue logging

* keep only 1 route for current user

* add Bearer prefixed url to the rest of the logs

---------

Co-authored-by: Skillz4Killz <23035000+Skillz4Killz@users.noreply.github.com>
2023-09-19 16:23:22 +00:00

24 lines
1013 B
TypeScript

import { Buffer } from 'node:buffer'
const validTokenPrefixes = ['Bot', 'Bearer']
/** Removes the Bot/Bearer before the token. */
export function removeTokenPrefix(token?: string, type: 'GATEWAY' | 'REST' = 'REST'): string {
// If no token is provided, throw an error
if (token === undefined) {
throw new Error(`The ${type} was not given a token. Please provide a token and try again.`)
}
const splittedToken = token.split(' ')
// If the token does not have a prefix just return token
if (splittedToken.length < 2 || !validTokenPrefixes.includes(splittedToken[0])) return token
// Remove the prefix and return only the token.
return splittedToken.splice(1).join(' ')
}
/** Get the bot id from the bot token. WARNING: Discord staff has mentioned this may not be stable forever. Use at your own risk. However, note for over 5 years this has never broken. */
export function getBotIdFromToken(token: string): bigint {
return BigInt(Buffer.from(token.split('.')[0], 'base64').toString())
}