export const API_KEY_PREFIX = 'create_'; type Client = { clientId: string; clientSecret: string; }; /** * This function will decode the api key supplied by the user. * If the key is invalid, then it will return undefined, otherwise * it will return the clientId and clientSecret. */ export const decodeApiKey = (apiKey: string): Client | undefined => { if (!apiKey.startsWith(API_KEY_PREFIX)) { return; } const nonPrefixedKey = Buffer.from( apiKey.slice(API_KEY_PREFIX.length), 'base64url' ).toString('utf-8'); const clientId = nonPrefixedKey.slice(0, nonPrefixedKey.indexOf('.')); const clientSecret = nonPrefixedKey.slice(nonPrefixedKey.indexOf('.') + 1); if (clientId === '' || clientSecret === '') { return; } return { clientId, clientSecret, }; }; /** * This function will encode the api key in a url safe way. */ export const encodeApiKey = ({ clientId, clientSecret }: Client): string => { const key = Buffer.from(`${clientId}.${clientSecret}`).toString('base64url'); return `${API_KEY_PREFIX}${key}`; };