UNPKG

@aws-amplify/auth

Version:
52 lines (50 loc) 2 kB
'use strict'; // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", { value: true }); exports.generateCodeVerifier = void 0; const sha256_js_1 = require("@aws-crypto/sha256-js"); const utils_1 = require("@aws-amplify/core/internals/utils"); const CODE_VERIFIER_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; /** * * @param length Desired length of the code verifier. * * **NOTE:** According to the [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636#section-4.1) * A code verifier must be with a length >= 43 and <= 128. * * @returns An object that contains the generated `codeVerifier` and a method * `toCodeChallenge` to generate the code challenge from the `codeVerifier` * following the spec of [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636#section-4.2). */ const generateCodeVerifier = (length) => { const randomBytes = new Uint8Array(length); (0, utils_1.getCrypto)().getRandomValues(randomBytes); let value = ''; let codeChallenge; for (const byte of randomBytes) { value += CODE_VERIFIER_CHARSET.charAt(byte % CODE_VERIFIER_CHARSET.length); } return { value, method: 'S256', toCodeChallenge() { if (codeChallenge) { return codeChallenge; } codeChallenge = generateCodeChallenge(value); return codeChallenge; }, }; }; exports.generateCodeVerifier = generateCodeVerifier; function generateCodeChallenge(codeVerifier) { const awsCryptoHash = new sha256_js_1.Sha256(); awsCryptoHash.update(codeVerifier); const codeChallenge = removePaddingChar(utils_1.base64Encoder.convert(awsCryptoHash.digestSync(), { urlSafe: true })); return codeChallenge; } function removePaddingChar(base64Encoded) { return base64Encoded.replace(/=/g, ''); } //# sourceMappingURL=generateCodeVerifier.js.map