Skip to content

Commit

Permalink
Modified toText and toBase64 helper methods to handle base64 url enco…
Browse files Browse the repository at this point in the history
…ded strings
  • Loading branch information
sacOO7 committed Sep 24, 2024
1 parent 1d69777 commit 3e22022
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
25 changes: 21 additions & 4 deletions src/channel/ably/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(/=+$/, '');

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on
library input
may run slow on strings with many repetitions of '='.
};

const isAbsoluteUrl = (url: string) => (url && url.indexOf('http://') === 0) || url.indexOf('https://') === 0;
Expand Down
2 changes: 1 addition & 1 deletion src/connector/ably-connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
2 changes: 1 addition & 1 deletion src/echo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 3e22022

Please sign in to comment.