diff --git a/package.json b/package.json index e2cee12..f2eee85 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@salesforce/lwc-dev-mobile-core", "description": "Core module supporting Salesforce CLI mobile extension plug-ins", - "version": "4.0.0-alpha.3", + "version": "4.0.0-alpha.4", "author": { "name": "Meisam Seyed Aliroteh", "email": "maliroteh@salesforce.com", diff --git a/src/common/CryptoUtils.ts b/src/common/CryptoUtils.ts index 073af4c..e74ec9d 100644 --- a/src/common/CryptoUtils.ts +++ b/src/common/CryptoUtils.ts @@ -4,6 +4,7 @@ * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ +import { randomBytes } from 'node:crypto'; import forge from 'node-forge'; import { Messages } from '@salesforce/core'; @@ -129,4 +130,14 @@ export class CryptoUtils { pemPublicKey: publicKey }; } + + /** + * Generates a cryptographically secure pseudorandom number generator(CSPRNG) token. + * + * @param {number} byteSize the size of the token to be generated. Default is 32(256-bit). + * @returns the generated CSPRNG token expressed in base64. + */ + public static generateIdentityToken(byteSize: number = 32): string { + return randomBytes(byteSize).toString('base64'); + } } diff --git a/test/unit/common/CryptoUtils.test.ts b/test/unit/common/CryptoUtils.test.ts index 2fe3a9f..32674c8 100644 --- a/test/unit/common/CryptoUtils.test.ts +++ b/test/unit/common/CryptoUtils.test.ts @@ -72,4 +72,16 @@ describe('CryptoUtils tests', () => { expect(cert.pemPublicKey.startsWith('-----BEGIN PUBLIC KEY-----')).to.be.true; expect(cert.pemPrivateKey.startsWith('-----BEGIN RSA PRIVATE KEY-----')).to.be.true; }).timeout(10000); // increase timeout for this test + + it('generateIdentityToken succeeds to generate tokens with correct size', async () => { + let token = CryptoUtils.generateIdentityToken(); + let b64string = Buffer.from(token, 'base64'); + let byteSize = b64string.byteLength; + expect(byteSize).to.equal(32); + + token = CryptoUtils.generateIdentityToken(64); + b64string = Buffer.from(token, 'base64'); + byteSize = b64string.byteLength; + expect(byteSize).to.equal(64); + }); });