From 3e220228b9971fe9712c65b35fddf5da43084322 Mon Sep 17 00:00:00 2001 From: sacOO7 Date: Tue, 24 Sep 2024 15:51:21 +0530 Subject: [PATCH] Modified toText and toBase64 helper methods to handle base64 url encoded strings --- src/channel/ably/utils.ts | 25 +++++++++++++++++++++---- src/connector/ably-connector.ts | 2 +- src/echo.ts | 2 +- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/channel/ably/utils.ts b/src/channel/ably/utils.ts index 4fa68b9..3717a9c 100644 --- a/src/channel/ably/utils.ts +++ b/src/channel/ably/utils.ts @@ -33,18 +33,35 @@ export const toTokenDetails = (jwtToken: string): TokenDetails | any => { const isBrowser = typeof window === 'object'; +/** + * Helper method to decode base64 url encoded string + * @param base64 base64 url encoded string + * @returns decoded text string + */ export const toText = (base64: string) => { + const base64Encoded = base64.replace(/-/g, '+').replace(/_/g, '/'); + const padding = base64.length % 4 === 0 ? '' : '='.repeat(4 - (base64.length % 4)); + const base64WithPadding = base64Encoded + padding; + if (isBrowser) { - return atob(base64); + return atob(base64WithPadding); } - return Buffer.from(base64, 'base64').toString('binary'); + return Buffer.from(base64WithPadding, 'base64').toString('binary'); }; +/** + * Helper method to encode text into base64 url encoded string + * @param base64 text + * @returns base64 url encoded string + */ export const toBase64 = (text: string) => { + let encoded = '' if (isBrowser) { - return btoa(text); + encoded = btoa(text); + } else { + encoded = Buffer.from(text, 'binary').toString('base64'); } - return Buffer.from(text, 'binary').toString('base64'); + return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }; const isAbsoluteUrl = (url: string) => (url && url.indexOf('http://') === 0) || url.indexOf('https://') === 0; diff --git a/src/connector/ably-connector.ts b/src/connector/ably-connector.ts index 253f8bc..038757e 100644 --- a/src/connector/ably-connector.ts +++ b/src/connector/ably-connector.ts @@ -119,7 +119,7 @@ export class AblyConnector extends Connector { /** * Get the socket ID for the connection. - * For ably, returns base64 encoded json with keys {connectionKey, clientId} + * For ably, returns base64 url encoded json with keys {connectionKey, clientId} */ socketId(): string { let socketIdObject = { diff --git a/src/echo.ts b/src/echo.ts index fd3f492..d646fa3 100644 --- a/src/echo.ts +++ b/src/echo.ts @@ -117,7 +117,7 @@ export default class Echo { /** * Get the Socket ID for the connection. - * For ably, returns base64 encoded json with keys {connectionKey, clientId} + * For ably, returns base64 url encoded json with keys {connectionKey, clientId} */ socketId(): string { return this.connector.socketId();