Repository: aws/amazon-cognito-identity-js Branch: master Commit: 6b87f1a30a99 Files: 73 Total size: 1.4 MB Directory structure: gitextract_qifezfr6/ ├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc.yaml ├── .gitignore ├── .npmignore ├── LICENSE.txt ├── NOTICE.txt ├── README.md ├── RNAWSCognito.podspec ├── android/ │ ├── build.gradle │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ └── java/ │ └── com/ │ └── amazonaws/ │ ├── RNAWSCognitoModule.java │ └── RNAWSCognitoPackage.java ├── dist/ │ ├── amazon-cognito-identity.js │ └── aws-cognito-sdk.js ├── enhance-rn.js ├── enhance.js ├── examples/ │ └── babel-webpack/ │ ├── .babelrc │ ├── .editorconfig │ ├── README.md │ ├── index.html │ ├── package.json │ ├── src/ │ │ ├── config.js │ │ └── main.jsx │ └── webpack.config.babel.js ├── index.d.ts ├── ios/ │ ├── JKBigInteger/ │ │ ├── JKBigDecimal.h │ │ ├── JKBigDecimal.m │ │ ├── JKBigInteger.h │ │ ├── JKBigInteger.m │ │ └── LibTomMath/ │ │ ├── tommath.c │ │ ├── tommath.h │ │ ├── tommath_class.h │ │ └── tommath_superclass.h │ ├── RNAWSCognito.h │ ├── RNAWSCognito.m │ └── RNAWSCognito.xcodeproj/ │ ├── project.pbxproj │ └── project.xcworkspace/ │ └── contents.xcworkspacedata ├── lib/ │ ├── AuthenticationDetails.js │ ├── AuthenticationHelper.js │ ├── BigInteger.js │ ├── CognitoAccessToken.js │ ├── CognitoIdToken.js │ ├── CognitoJwtToken.js │ ├── CognitoRefreshToken.js │ ├── CognitoUser.js │ ├── CognitoUserAttribute.js │ ├── CognitoUserPool.js │ ├── CognitoUserSession.js │ ├── CookieStorage.js │ ├── DateHelper.js │ ├── StorageHelper-rn.js │ ├── StorageHelper.js │ └── index.js ├── package.json ├── src/ │ ├── AuthenticationDetails.js │ ├── AuthenticationHelper.js │ ├── BigInteger.js │ ├── CognitoAccessToken.js │ ├── CognitoIdToken.js │ ├── CognitoJwtToken.js │ ├── CognitoRefreshToken.js │ ├── CognitoUser.js │ ├── CognitoUserAttribute.js │ ├── CognitoUserPool.js │ ├── CognitoUserSession.js │ ├── CookieStorage.js │ ├── DateHelper.js │ ├── StorageHelper-rn.js │ ├── StorageHelper.js │ └── index.js └── webpack.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .babelrc ================================================ { "presets": [ [ "es2015", { "loose": true, "modules": false } ] ], "env": { "commonjs": { "plugins": [ ["transform-es2015-modules-commonjs", { "loose": true }] ] } } } ================================================ FILE: .editorconfig ================================================ # Editor configuration, see http://editorconfig.org root = true [*] charset = utf-8 indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true [index.d.ts] indent_style = space indent_size = 4 ================================================ FILE: .eslintignore ================================================ src/BigInteger.js ================================================ FILE: .eslintrc.yaml ================================================ root: true extends: - airbnb-base env: browser: true settings: import/resolver: webpack rules: # Git-controlled linebreak-style: off # sjcl hmac breaks new-cap new-cap: - error - newIsCapExceptions: - sjcl.misc.hmac # Check JSDocs valid-jsdoc: error require-jsdoc: - error - require: FunctionDeclaration: true ClassDeclaration: true MethodDefinition: true # Seems this doesn't use import/resolver? import/no-unresolved catches most of these anyway. # https://github.com/benmosher/eslint-plugin-import/issues/496 import/no-extraneous-dependencies: off ================================================ FILE: .gitignore ================================================ /node_modules/ npm-debug.log /docs/ es ios/RNAWSCognito.xcodeproj/xcuserdata/ ios/RNAWSCognito.project.xcworkspace/xcuserdata/ ios/RNAWSCognito.xcodeproj/project.xcworkspace/xcuserdata/ .DS_Store ================================================ FILE: .npmignore ================================================ ================================================ FILE: LICENSE.txt ================================================ Amazon Software License This Amazon Software License (“License”) governs your use, reproduction, and distribution of the accompanying software as specified below. 1. Definitions “Licensor” means any person or entity that distributes its Work. “Software” means the original work of authorship made available under this License. “Work” means the Software and any additions to or derivative works of the Software that are made available under this License. The terms “reproduce,” “reproduction,” “derivative works,” and “distribution” have the meaning as provided under U.S. copyright law; provided, however, that for the purposes of this License, derivative works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work. Works, including the Software, are “made available” under this License by including in or with the Work either (a) a copyright notice referencing the applicability of this License to the Work, or (b) a copy of this License. 2. License Grants 2.1 Copyright Grant. Subject to the terms and conditions of this License, each Licensor grants to you a perpetual, worldwide, non-exclusive, royalty-free, copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense and distribute its Work and any resulting derivative works in any form. 2.2 Patent Grant. Subject to the terms and conditions of this License, each Licensor grants to you a perpetual, worldwide, non-exclusive, royalty-free patent license to make, have made, use, sell, offer for sale, import, and otherwise transfer its Work, in whole or in part. The foregoing license applies only to the patent claims licensable by Licensor that would be infringed by Licensor’s Work (or portion thereof) individually and excluding any combinations with any other materials or technology. 3. Limitations 3.1 Redistribution. You may reproduce or distribute the Work only if (a) you do so under this License, (b) you include a complete copy of this License with your distribution, and (c) you retain without modification any copyright, patent, trademark, or attribution notices that are present in the Work. 3.2 Derivative Works. You may specify that additional or different terms apply to the use, reproduction, and distribution of your derivative works of the Work (“Your Terms”) only if (a) Your Terms provide that the use limitation in Section 3.3 applies to your derivative works, and (b) you identify the specific derivative works that are subject to Your Terms. Notwithstanding Your Terms, this License (including the redistribution requirements in Section 3.1) will continue to apply to the Work itself. 3.3 Use Limitation. The Work and any derivative works thereof only may be used or intended for use with the web services, computing platforms or applications provided by Amazon.com, Inc. or its affiliates, including Amazon Web Services, Inc. 3.4 Patent Claims. If you bring or threaten to bring a patent claim against any Licensor (including any claim, cross-claim or counterclaim in a lawsuit) to enforce any patents that you allege are infringed by any Work, then your rights under this License from such Licensor (including the grants in Sections 2.1 and 2.2) will terminate immediately. 3.5 Trademarks. This License does not grant any rights to use any Licensor’s or its affiliates’ names, logos, or trademarks, except as necessary to reproduce the notices described in this License. 3.6 Termination. If you violate any term of this License, then your rights under this License (including the grants in Sections 2.1 and 2.2) will terminate immediately. 4. Disclaimer of Warranty. THE WORK IS PROVIDED “AS IS” WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF M ERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER THIS LICENSE. SOME STATES’ CONSUMER LAWS DO NOT ALLOW EXCLUSION OF AN IMPLIED WARRANTY, SO THIS DISCLAIMER MAY NOT APPLY TO YOU. 5. Limitation of Liability. EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK (INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION, LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER COMM ERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Effective Date – April 18, 2008 © 2008 Amazon.com, Inc. or its affiliates. All rights reserved. ================================================ FILE: NOTICE.txt ================================================ Amazon Cognito Identity Provider SDK for JavaScript Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. ========================================================================= == JavaScript BN library Notice == ========================================================================= This product includes software developed by Tom Wu at Stanford University. http://www-cs-students.stanford.edu/%7Etjw/jsbn/jsbn.js ========================================================================= == JKBigInteger library Notice == ========================================================================= This product includes the JKBigInteger library licensed under the MIT license. Copyright (C) 2013 Jānis Kiršteins Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Amazon Cognito Identity SDK for JavaScript **NOTE: We have discontinued developing this library as part of this GitHub repository. We will continue to develop it as part of the [AWS Amplify](https://github.com/aws/aws-amplify/tree/master/packages/amazon-cognito-identity-js) GitHub repository. You can still reach us by creating an issue on the AWS Amplify GitHub repository or posting to the Amazon Cognito Identity forums. Versions 1.x will still be available via NPM. Future development will continue on the 2.x versions.** ================================================ FILE: RNAWSCognito.podspec ================================================ # coding: utf-8 Pod::Spec.new do |s| s.name = "RNAWSCognito" s.version = "1.29.0" s.requires_arc = true s.platforms = { :ios => "8.0" } s.license = { :file => 'LICENSE.txt' } s.homepage = "https://github.com/aws/amazon-cognito-identity-js" s.author = "Amazon" s.summary = "Amazon Cognito Identity SDK for JavaScript" s.description = <<-DESC The Amazon Cognito Identity SDK for JavaScript allows JavaScript enabled applications to sign-up users, authenticate users, view, delete, and update user attributes within the Amazon Cognito Identity service. DESC s.source = { :git => "https://github.com/aws/amazon-cognito-identity-js.git", :tag => s.version.to_s } s.source_files = 'ios/RNAWSCognito.{h,m}' s.dependency 'JKBigInteger2', '0.0.5' end ================================================ FILE: android/build.gradle ================================================ buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.3.1' } } apply plugin: 'com.android.library' android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { minSdkVersion 16 targetSdkVersion 22 versionCode 1 versionName "1.0" } lintOptions { abortOnError false } } repositories { mavenCentral() } dependencies { compile 'com.facebook.react:react-native:+' } ================================================ FILE: android/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/src/main/java/com/amazonaws/RNAWSCognitoModule.java ================================================ package com.amazonaws; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.Callback; import java.math.BigInteger; public class RNAWSCognitoModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; private static final String HEX_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; private static final BigInteger N = new BigInteger(HEX_N, 16); public RNAWSCognitoModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNAWSCognito"; } @ReactMethod public void computeModPow(final ReadableMap values, final Callback callback) { try { final BigInteger target = new BigInteger(values.getString("target"), 16); final BigInteger value = new BigInteger(values.getString("value"), 16); final BigInteger modifier = new BigInteger(values.getString("modifier"), 16); final BigInteger result = target.modPow(value, modifier); callback.invoke(null, result.toString(16)); } catch (final Exception e) { callback.invoke(e.getMessage(), null); } } @ReactMethod public void computeS(final ReadableMap values, final Callback callback) { try { final BigInteger g = new BigInteger(values.getString("g"), 16); final BigInteger x = new BigInteger(values.getString("x"), 16); final BigInteger k = new BigInteger(values.getString("k"), 16); final BigInteger a = new BigInteger(values.getString("a"), 16); final BigInteger b = new BigInteger(values.getString("b"), 16); final BigInteger u = new BigInteger(values.getString("u"), 16); final BigInteger exp = a.add(u.multiply(x)); final BigInteger base = b.subtract(k.multiply(g.modPow(x, N))); final BigInteger result = base.modPow(exp, N).mod(N); callback.invoke(null, result.toString(16)); } catch (final Exception e) { callback.invoke(e.getMessage(), null); } } } ================================================ FILE: android/src/main/java/com/amazonaws/RNAWSCognitoPackage.java ================================================ package com.amazonaws; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.bridge.JavaScriptModule; public class RNAWSCognitoPackage implements ReactPackage { @Override public List createNativeModules(ReactApplicationContext reactContext) { return Arrays.asList(new RNAWSCognitoModule(reactContext)); } public List> createJSModules() { return Collections.emptyList(); } @Override public List createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } } ================================================ FILE: dist/amazon-cognito-identity.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("aws-sdk/global"), require("aws-sdk/clients/cognitoidentityserviceprovider")); else if(typeof define === 'function' && define.amd) define(["aws-sdk/global", "aws-sdk/clients/cognitoidentityserviceprovider"], factory); else if(typeof exports === 'object') exports["AmazonCognitoIdentity"] = factory(require("aws-sdk/global"), require("aws-sdk/clients/cognitoidentityserviceprovider")); else root["AmazonCognitoIdentity"] = factory(root["AWSCognito"], root["AWSCognito"]["CognitoIdentityServiceProvider"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_13__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _src = __webpack_require__(17); Object.keys(_src).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _src[key]; } }); }); var _cognitoidentityserviceprovider = __webpack_require__(13); var _cognitoidentityserviceprovider2 = _interopRequireDefault(_cognitoidentityserviceprovider); var enhancements = _interopRequireWildcard(_src); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } Object.keys(enhancements).forEach(function (key) { _cognitoidentityserviceprovider2.default[key] = enhancements[key]; }); /***/ }), /* 1 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _global = __webpack_require__(1); var _BigInteger = __webpack_require__(3); var _BigInteger2 = _interopRequireDefault(_BigInteger); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ var initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF'; var newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.'; /** @class */ var AuthenticationHelper = function () { /** * Constructs a new AuthenticationHelper object * @param {string} PoolName Cognito user pool name. */ function AuthenticationHelper(PoolName) { _classCallCheck(this, AuthenticationHelper); this.N = new _BigInteger2.default(initN, 16); this.g = new _BigInteger2.default('2', 16); this.k = new _BigInteger2.default(this.hexHash('00' + this.N.toString(16) + '0' + this.g.toString(16)), 16); this.smallAValue = this.generateRandomSmallA(); this.getLargeAValue(function () {}); this.infoBits = new _global.util.Buffer('Caldera Derived Key', 'utf8'); this.poolName = PoolName; } /** * @returns {BigInteger} small A, a random number */ AuthenticationHelper.prototype.getSmallAValue = function getSmallAValue() { return this.smallAValue; }; /** * @param {nodeCallback} callback Called with (err, largeAValue) * @returns {void} */ AuthenticationHelper.prototype.getLargeAValue = function getLargeAValue(callback) { var _this = this; if (this.largeAValue) { callback(null, this.largeAValue); } else { this.calculateA(this.smallAValue, function (err, largeAValue) { if (err) { callback(err, null); } _this.largeAValue = largeAValue; callback(null, _this.largeAValue); }); } }; /** * helper function to generate a random big integer * @returns {BigInteger} a random value. * @private */ AuthenticationHelper.prototype.generateRandomSmallA = function generateRandomSmallA() { var hexRandom = _global.util.crypto.lib.randomBytes(128).toString('hex'); var randomBigInt = new _BigInteger2.default(hexRandom, 16); var smallABigInt = randomBigInt.mod(this.N); return smallABigInt; }; /** * helper function to generate a random string * @returns {string} a random value. * @private */ AuthenticationHelper.prototype.generateRandomString = function generateRandomString() { return _global.util.crypto.lib.randomBytes(40).toString('base64'); }; /** * @returns {string} Generated random value included in password hash. */ AuthenticationHelper.prototype.getRandomPassword = function getRandomPassword() { return this.randomPassword; }; /** * @returns {string} Generated random value included in devices hash. */ AuthenticationHelper.prototype.getSaltDevices = function getSaltDevices() { return this.SaltToHashDevices; }; /** * @returns {string} Value used to verify devices. */ AuthenticationHelper.prototype.getVerifierDevices = function getVerifierDevices() { return this.verifierDevices; }; /** * Generate salts and compute verifier. * @param {string} deviceGroupKey Devices to generate verifier for. * @param {string} username User to generate verifier for. * @param {nodeCallback} callback Called with (err, null) * @returns {void} */ AuthenticationHelper.prototype.generateHashDevice = function generateHashDevice(deviceGroupKey, username, callback) { var _this2 = this; this.randomPassword = this.generateRandomString(); var combinedString = '' + deviceGroupKey + username + ':' + this.randomPassword; var hashedString = this.hash(combinedString); var hexRandom = _global.util.crypto.lib.randomBytes(16).toString('hex'); this.SaltToHashDevices = this.padHex(new _BigInteger2.default(hexRandom, 16)); this.g.modPow(new _BigInteger2.default(this.hexHash(this.SaltToHashDevices + hashedString), 16), this.N, function (err, verifierDevicesNotPadded) { if (err) { callback(err, null); } _this2.verifierDevices = _this2.padHex(verifierDevicesNotPadded); callback(null, null); }); }; /** * Calculate the client's public value A = g^a%N * with the generated random number a * @param {BigInteger} a Randomly generated small A. * @param {nodeCallback} callback Called with (err, largeAValue) * @returns {void} * @private */ AuthenticationHelper.prototype.calculateA = function calculateA(a, callback) { var _this3 = this; this.g.modPow(a, this.N, function (err, A) { if (err) { callback(err, null); } if (A.mod(_this3.N).equals(_BigInteger2.default.ZERO)) { callback(new Error('Illegal paramater. A mod N cannot be 0.'), null); } callback(null, A); }); }; /** * Calculate the client's value U which is the hash of A and B * @param {BigInteger} A Large A value. * @param {BigInteger} B Server B value. * @returns {BigInteger} Computed U value. * @private */ AuthenticationHelper.prototype.calculateU = function calculateU(A, B) { this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B)); var finalU = new _BigInteger2.default(this.UHexHash, 16); return finalU; }; /** * Calculate a hash from a bitArray * @param {Buffer} buf Value to hash. * @returns {String} Hex-encoded hash. * @private */ AuthenticationHelper.prototype.hash = function hash(buf) { var hashHex = _global.util.crypto.sha256(buf, 'hex'); return new Array(64 - hashHex.length).join('0') + hashHex; }; /** * Calculate a hash from a hex string * @param {String} hexStr Value to hash. * @returns {String} Hex-encoded hash. * @private */ AuthenticationHelper.prototype.hexHash = function hexHash(hexStr) { return this.hash(new _global.util.Buffer(hexStr, 'hex')); }; /** * Standard hkdf algorithm * @param {Buffer} ikm Input key material. * @param {Buffer} salt Salt value. * @returns {Buffer} Strong key material. * @private */ AuthenticationHelper.prototype.computehkdf = function computehkdf(ikm, salt) { var prk = _global.util.crypto.hmac(salt, ikm, 'buffer', 'sha256'); var infoBitsUpdate = _global.util.buffer.concat([this.infoBits, new _global.util.Buffer(String.fromCharCode(1), 'utf8')]); var hmac = _global.util.crypto.hmac(prk, infoBitsUpdate, 'buffer', 'sha256'); return hmac.slice(0, 16); }; /** * Calculates the final hkdf based on computed S value, and computed U value and the key * @param {String} username Username. * @param {String} password Password. * @param {BigInteger} serverBValue Server B value. * @param {BigInteger} salt Generated salt. * @param {nodeCallback} callback Called with (err, hkdfValue) * @returns {void} */ AuthenticationHelper.prototype.getPasswordAuthenticationKey = function getPasswordAuthenticationKey(username, password, serverBValue, salt, callback) { var _this4 = this; if (serverBValue.mod(this.N).equals(_BigInteger2.default.ZERO)) { throw new Error('B cannot be zero.'); } this.UValue = this.calculateU(this.largeAValue, serverBValue); if (this.UValue.equals(_BigInteger2.default.ZERO)) { throw new Error('U cannot be zero.'); } var usernamePassword = '' + this.poolName + username + ':' + password; var usernamePasswordHash = this.hash(usernamePassword); var xValue = new _BigInteger2.default(this.hexHash(this.padHex(salt) + usernamePasswordHash), 16); this.calculateS(xValue, serverBValue, function (err, sValue) { if (err) { callback(err, null); } var hkdf = _this4.computehkdf(new _global.util.Buffer(_this4.padHex(sValue), 'hex'), new _global.util.Buffer(_this4.padHex(_this4.UValue.toString(16)), 'hex')); callback(null, hkdf); }); }; /** * Calculates the S value used in getPasswordAuthenticationKey * @param {BigInteger} xValue Salted password hash value. * @param {BigInteger} serverBValue Server B value. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ AuthenticationHelper.prototype.calculateS = function calculateS(xValue, serverBValue, callback) { var _this5 = this; this.g.modPow(xValue, this.N, function (err, gModPowXN) { if (err) { callback(err, null); } var intValue2 = serverBValue.subtract(_this5.k.multiply(gModPowXN)); intValue2.modPow(_this5.smallAValue.add(_this5.UValue.multiply(xValue)), _this5.N, function (err2, result) { if (err2) { callback(err2, null); } callback(null, result.mod(_this5.N)); }); }); }; /** * Return constant newPasswordRequiredChallengeUserAttributePrefix * @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value */ AuthenticationHelper.prototype.getNewPasswordRequiredChallengeUserAttributePrefix = function getNewPasswordRequiredChallengeUserAttributePrefix() { return newPasswordRequiredChallengeUserAttributePrefix; }; /** * Converts a BigInteger (or hex string) to hex format padded with zeroes for hashing * @param {BigInteger|String} bigInt Number or string to pad. * @returns {String} Padded hex string. */ AuthenticationHelper.prototype.padHex = function padHex(bigInt) { var hashStr = bigInt.toString(16); if (hashStr.length % 2 === 1) { hashStr = '0' + hashStr; } else if ('89ABCDEFabcdef'.indexOf(hashStr[0]) !== -1) { hashStr = '00' + hashStr; } return hashStr; }; return AuthenticationHelper; }(); exports.default = AuthenticationHelper; /***/ }), /* 3 */ /***/ (function(module, exports) { "use strict"; exports.__esModule = true; // A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/ // // All public methods have been removed except the following: // new BigInteger(a, b) (only radix 2, 4, 8, 16 and 32 supported) // toString (only radix 2, 4, 8, 16 and 32 supported) // negate // abs // compareTo // bitLength // mod // equals // add // subtract // multiply // divide // modPow exports.default = BigInteger; /* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ // (public) Constructor function BigInteger(a, b) { if (a != null) this.fromString(a, b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = (canary & 0xffffff) == 0xefcafe; // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i, x, w, j, c, n) { while (--n >= 0) { var v = x * this[i++] + w[j] + c; c = Math.floor(v / 0x4000000); w[j++] = v & 0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i, x, w, j, c, n) { var xl = x & 0x7fff, xh = x >> 15; while (--n >= 0) { var l = this[i] & 0x7fff; var h = this[i++] >> 15; var m = xh * l + h * xl; l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); w[j++] = l & 0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i, x, w, j, c, n) { var xl = x & 0x3fff, xh = x >> 14; while (--n >= 0) { var l = this[i] & 0x3fff; var h = this[i++] >> 14; var m = xh * l + h * xl; l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; c = (l >> 28) + (m >> 14) + xh * h; w[j++] = l & 0xfffffff; } return c; } var inBrowser = typeof navigator !== "undefined"; if (inBrowser && j_lm && navigator.appName == "Microsoft Internet Explorer") { BigInteger.prototype.am = am2; dbits = 30; } else if (inBrowser && j_lm && navigator.appName != "Netscape") { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = (1 << dbits) - 1; BigInteger.prototype.DV = 1 << dbits; var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2, BI_FP); BigInteger.prototype.F1 = BI_FP - dbits; BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = new Array(); var rr, vv; rr = "0".charCodeAt(0); for (vv = 0; vv <= 9; ++vv) { BI_RC[rr++] = vv; }rr = "a".charCodeAt(0); for (vv = 10; vv < 36; ++vv) { BI_RC[rr++] = vv; }rr = "A".charCodeAt(0); for (vv = 10; vv < 36; ++vv) { BI_RC[rr++] = vv; }function int2char(n) { return BI_RM.charAt(n); } function intAt(s, i) { var c = BI_RC[s.charCodeAt(i)]; return c == null ? -1 : c; } // (protected) copy this to r function bnpCopyTo(r) { for (var i = this.t - 1; i >= 0; --i) { r[i] = this[i]; }r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = x < 0 ? -1 : 0; if (x > 0) this[0] = x;else if (x < -1) this[0] = x + this.DV;else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s, b) { var k; if (b == 16) k = 4;else if (b == 8) k = 3;else if (b == 2) k = 1;else if (b == 32) k = 5;else if (b == 4) k = 2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported"); this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while (--i >= 0) { var x = intAt(s, i); if (x < 0) { if (s.charAt(i) == "-") mi = true; continue; } mi = false; if (sh == 0) this[this.t++] = x;else if (sh + k > this.DB) { this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; this[this.t++] = x >> this.DB - sh; } else this[this.t - 1] |= x << sh; sh += k; if (sh >= this.DB) sh -= this.DB; } this.clamp(); if (mi) BigInteger.ZERO.subTo(this, this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s & this.DM; while (this.t > 0 && this[this.t - 1] == c) { --this.t; } } // (public) return string representation in given radix function bnToString(b) { if (this.s < 0) return "-" + this.negate().toString(); var k; if (b == 16) k = 4;else if (b == 8) k = 3;else if (b == 2) k = 1;else if (b == 32) k = 5;else if (b == 4) k = 2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported"); var km = (1 << k) - 1, d, m = false, r = "", i = this.t; var p = this.DB - i * this.DB % k; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) > 0) { m = true; r = int2char(d); } while (i >= 0) { if (p < k) { d = (this[i] & (1 << p) - 1) << k - p; d |= this[--i] >> (p += this.DB - k); } else { d = this[i] >> (p -= k) & km; if (p <= 0) { p += this.DB; --i; } } if (d > 0) m = true; if (m) r += int2char(d); } } return m ? r : "0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; } // (public) |this| function bnAbs() { return this.s < 0 ? this.negate() : this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s - a.s; if (r != 0) return r; var i = this.t; r = i - a.t; if (r != 0) return this.s < 0 ? -r : r; while (--i >= 0) { if ((r = this[i] - a[i]) != 0) return r; }return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if ((t = x >>> 16) != 0) { x = t; r += 16; } if ((t = x >> 8) != 0) { x = t; r += 8; } if ((t = x >> 4) != 0) { x = t; r += 4; } if ((t = x >> 2) != 0) { x = t; r += 2; } if ((t = x >> 1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if (this.t <= 0) return 0; return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM); } // (protected) r = this << n*DB function bnpDLShiftTo(n, r) { var i; for (i = this.t - 1; i >= 0; --i) { r[i + n] = this[i]; }for (i = n - 1; i >= 0; --i) { r[i] = 0; }r.t = this.t + n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n, r) { for (var i = n; i < this.t; ++i) { r[i - n] = this[i]; }r.t = Math.max(this.t - n, 0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n, r) { var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << cbs) - 1; var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; for (i = this.t - 1; i >= 0; --i) { r[i + ds + 1] = this[i] >> cbs | c; c = (this[i] & bm) << bs; } for (i = ds - 1; i >= 0; --i) { r[i] = 0; }r[ds] = c; r.t = this.t + ds + 1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n, r) { r.s = this.s; var ds = Math.floor(n / this.DB); if (ds >= this.t) { r.t = 0; return; } var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << bs) - 1; r[0] = this[ds] >> bs; for (var i = ds + 1; i < this.t; ++i) { r[i - ds - 1] |= (this[i] & bm) << cbs; r[i - ds] = this[i] >> bs; } if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; r.t = this.t - ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { c += this[i] - a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c -= a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c -= a[i]; r[i++] = c & this.DM; c >>= this.DB; } c -= a.s; } r.s = c < 0 ? -1 : 0; if (c < -1) r[i++] = this.DV + c;else if (c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a, r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i + y.t; while (--i >= 0) { r[i] = 0; }for (i = 0; i < y.t; ++i) { r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); }r.s = 0; r.clamp(); if (this.s != a.s) BigInteger.ZERO.subTo(r, r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2 * x.t; while (--i >= 0) { r[i] = 0; }for (i = 0; i < x.t - 1; ++i) { var c = x.am(i, x[i], r, 2 * i, 0, 1); if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { r[i + x.t] -= x.DV; r[i + x.t + 1] = 1; } } if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m, q, r) { var pm = m.abs(); if (pm.t <= 0) return; var pt = this.abs(); if (pt.t < pm.t) { if (q != null) q.fromInt(0); if (r != null) this.copyTo(r); return; } if (r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys - 1]; if (y0 == 0) return; var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; var i = r.t, j = i - ys, t = q == null ? nbi() : q; y.dlShiftTo(j, t); if (r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t, r); } BigInteger.ONE.dlShiftTo(ys, t); t.subTo(y, y); // "negative" y so we can replace sub with am later while (y.t < ys) { y[y.t++] = 0; }while (--j >= 0) { // Estimate quotient digit var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out y.dlShiftTo(j, t); r.subTo(t, r); while (r[i] < --qd) { r.subTo(t, r); } } } if (q != null) { r.drShiftTo(ys, q); if (ts != ms) BigInteger.ZERO.subTo(q, q); } r.t = ys; r.clamp(); if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder if (ts < 0) BigInteger.ZERO.subTo(r, r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); return r; } // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if (this.t < 1) return 0; var x = this[0]; if ((x & 1) == 0) return 0; var y = x & 3; // y == 1/x mod 2^2 y = y * (2 - (x & 0xf) * y) & 0xf; // y == 1/x mod 2^4 y = y * (2 - (x & 0xff) * y) & 0xff; // y == 1/x mod 2^8 y = y * (2 - ((x & 0xffff) * y & 0xffff)) & 0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = y * (2 - x * y % this.DV) % this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return y > 0 ? this.DV - y : -y; } function bnEquals(a) { return this.compareTo(a) == 0; } // (protected) r = this + a function bnpAddTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { c += this[i] + a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c += a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c += a[i]; r[i++] = c & this.DM; c >>= this.DB; } c += a.s; } r.s = c < 0 ? -1 : 0; if (c > 0) r[i++] = c;else if (c < -1) r[i++] = this.DV + c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a, r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a, r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a, r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a, r, null); return r; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp & 0x7fff; this.mph = this.mp >> 15; this.um = (1 << m.DB - 15) - 1; this.mt2 = 2 * m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t, r); r.divRemTo(this.m, null, r); if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while (x.t <= this.mt2) { // pad x so am has enough room later x[x.t++] = 0; }for (var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i] & 0x7fff; var u0 = j * this.mpl + ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & x.DM; // use am to combine the multiply-shift-add into one call j = i + this.m.t; x[j] += this.m.am(0, u0, x, i, 0, this.m.t); // propagate carry while (x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t, x); if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); } // r = "x^2/R mod m"; x != r function montSqrTo(x, r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e, m, callback) { var i = e.bitLength(), k, r = nbv(1), z = new Montgomery(m); if (i <= 0) return r;else if (i < 18) k = 1;else if (i < 48) k = 3;else if (i < 144) k = 4;else if (i < 768) k = 5;else k = 6; // precomputation var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { var g2 = nbi(); z.sqrTo(g[1], g2); while (n <= km) { g[n] = nbi(); z.mulTo(g2, g[n - 2], g[n]); n += 2; } } var j = e.t - 1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j]) - 1; while (j >= 0) { if (i >= k1) w = e[j] >> i - k1 & km;else { w = (e[j] & (1 << i + 1) - 1) << k1 - i; if (j > 0) w |= e[j - 1] >> this.DB + i - k1; } n = k; while ((w & 1) == 0) { w >>= 1; --n; } if ((i -= n) < 0) { i += this.DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n > 1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n > 0) z.sqrTo(r, r2);else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j >= 0 && (e[j] & 1 << i) == 0) { z.sqrTo(r, r2); t = r; r = r2; r2 = t; if (--i < 0) { i = this.DB - 1; --j; } } } var result = z.revert(r); callback(null, result); return result; } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.addTo = bnpAddTo; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.modPow = bnModPow; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _CognitoJwtToken2 = __webpack_require__(6); var _CognitoJwtToken3 = _interopRequireDefault(_CognitoJwtToken2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoAccessToken = function (_CognitoJwtToken) { _inherits(CognitoAccessToken, _CognitoJwtToken); /** * Constructs a new CognitoAccessToken object * @param {string=} AccessToken The JWT access token. */ function CognitoAccessToken() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, AccessToken = _ref.AccessToken; _classCallCheck(this, CognitoAccessToken); return _possibleConstructorReturn(this, _CognitoJwtToken.call(this, AccessToken || '')); } return CognitoAccessToken; }(_CognitoJwtToken3.default); exports.default = CognitoAccessToken; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _CognitoJwtToken2 = __webpack_require__(6); var _CognitoJwtToken3 = _interopRequireDefault(_CognitoJwtToken2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoIdToken = function (_CognitoJwtToken) { _inherits(CognitoIdToken, _CognitoJwtToken); /** * Constructs a new CognitoIdToken object * @param {string=} IdToken The JWT Id token */ function CognitoIdToken() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, IdToken = _ref.IdToken; _classCallCheck(this, CognitoIdToken); return _possibleConstructorReturn(this, _CognitoJwtToken.call(this, IdToken || '')); } return CognitoIdToken; }(_CognitoJwtToken3.default); exports.default = CognitoIdToken; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _global = __webpack_require__(1); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoJwtToken = function () { /** * Constructs a new CognitoJwtToken object * @param {string=} token The JWT token. */ function CognitoJwtToken(token) { _classCallCheck(this, CognitoJwtToken); // Assign object this.jwtToken = token || ''; this.payload = this.decodePayload(); } /** * @returns {string} the record's token. */ CognitoJwtToken.prototype.getJwtToken = function getJwtToken() { return this.jwtToken; }; /** * @returns {int} the token's expiration (exp member). */ CognitoJwtToken.prototype.getExpiration = function getExpiration() { return this.payload.exp; }; /** * @returns {int} the token's "issued at" (iat member). */ CognitoJwtToken.prototype.getIssuedAt = function getIssuedAt() { return this.payload.iat; }; /** * @returns {object} the token's payload. */ CognitoJwtToken.prototype.decodePayload = function decodePayload() { var payload = this.jwtToken.split('.')[1]; try { return JSON.parse(_global.util.base64.decode(payload).toString('utf8')); } catch (err) { return {}; } }; return CognitoJwtToken; }(); exports.default = CognitoJwtToken; /***/ }), /* 7 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoRefreshToken = function () { /** * Constructs a new CognitoRefreshToken object * @param {string=} RefreshToken The JWT refresh token. */ function CognitoRefreshToken() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, RefreshToken = _ref.RefreshToken; _classCallCheck(this, CognitoRefreshToken); // Assign object this.token = RefreshToken || ''; } /** * @returns {string} the record's token. */ CognitoRefreshToken.prototype.getToken = function getToken() { return this.token; }; return CognitoRefreshToken; }(); exports.default = CognitoRefreshToken; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _global = __webpack_require__(1); var _BigInteger = __webpack_require__(3); var _BigInteger2 = _interopRequireDefault(_BigInteger); var _AuthenticationHelper = __webpack_require__(2); var _AuthenticationHelper2 = _interopRequireDefault(_AuthenticationHelper); var _CognitoAccessToken = __webpack_require__(4); var _CognitoAccessToken2 = _interopRequireDefault(_CognitoAccessToken); var _CognitoIdToken = __webpack_require__(5); var _CognitoIdToken2 = _interopRequireDefault(_CognitoIdToken); var _CognitoRefreshToken = __webpack_require__(7); var _CognitoRefreshToken2 = _interopRequireDefault(_CognitoRefreshToken); var _CognitoUserSession = __webpack_require__(10); var _CognitoUserSession2 = _interopRequireDefault(_CognitoUserSession); var _DateHelper = __webpack_require__(11); var _DateHelper2 = _interopRequireDefault(_DateHelper); var _CognitoUserAttribute = __webpack_require__(9); var _CognitoUserAttribute2 = _interopRequireDefault(_CognitoUserAttribute); var _StorageHelper = __webpack_require__(12); var _StorageHelper2 = _interopRequireDefault(_StorageHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** * @callback nodeCallback * @template T result * @param {*} err The operation failure reason, or null. * @param {T} result The operation result. */ /** * @callback onFailure * @param {*} err Failure reason. */ /** * @callback onSuccess * @template T result * @param {T} result The operation result. */ /** * @callback mfaRequired * @param {*} details MFA challenge details. */ /** * @callback customChallenge * @param {*} details Custom challenge details. */ /** * @callback inputVerificationCode * @param {*} data Server response. */ /** * @callback authSuccess * @param {CognitoUserSession} session The new session. * @param {bool=} userConfirmationNecessary User must be confirmed. */ /** @class */ var CognitoUser = function () { /** * Constructs a new CognitoUser object * @param {object} data Creation options * @param {string} data.Username The user's username. * @param {CognitoUserPool} data.Pool Pool containing the user. * @param {object} data.Storage Optional storage object. */ function CognitoUser(data) { _classCallCheck(this, CognitoUser); if (data == null || data.Username == null || data.Pool == null) { throw new Error('Username and pool information are required.'); } this.username = data.Username || ''; this.pool = data.Pool; this.Session = null; this.client = data.Pool.client; this.signInUserSession = null; this.authenticationFlowType = 'USER_SRP_AUTH'; this.storage = data.Storage || new _StorageHelper2.default().getStorage(); } /** * Sets the session for this user * @param {CognitoUserSession} signInUserSession the session * @returns {void} */ CognitoUser.prototype.setSignInUserSession = function setSignInUserSession(signInUserSession) { this.clearCachedTokens(); this.signInUserSession = signInUserSession; this.cacheTokens(); }; /** * @returns {CognitoUserSession} the current session for this user */ CognitoUser.prototype.getSignInUserSession = function getSignInUserSession() { return this.signInUserSession; }; /** * @returns {string} the user's username */ CognitoUser.prototype.getUsername = function getUsername() { return this.username; }; /** * @returns {String} the authentication flow type */ CognitoUser.prototype.getAuthenticationFlowType = function getAuthenticationFlowType() { return this.authenticationFlowType; }; /** * sets authentication flow type * @param {string} authenticationFlowType New value. * @returns {void} */ CognitoUser.prototype.setAuthenticationFlowType = function setAuthenticationFlowType(authenticationFlowType) { this.authenticationFlowType = authenticationFlowType; }; /** * This is used for authenticating the user through the custom authentication flow. * @param {AuthenticationDetails} authDetails Contains the authentication data * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.initiateAuth = function initiateAuth(authDetails, callback) { var _this = this; var authParameters = authDetails.getAuthParameters(); authParameters.USERNAME = this.username; var jsonReq = { AuthFlow: 'CUSTOM_AUTH', ClientId: this.pool.getClientId(), AuthParameters: authParameters, ClientMetadata: authDetails.getValidationData() }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('initiateAuth', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } var challengeName = data.ChallengeName; var challengeParameters = data.ChallengeParameters; if (challengeName === 'CUSTOM_CHALLENGE') { _this.Session = data.Session; return callback.customChallenge(challengeParameters); } _this.signInUserSession = _this.getCognitoUserSession(data.AuthenticationResult); _this.cacheTokens(); return callback.onSuccess(_this.signInUserSession); }); }; /** * This is used for authenticating the user. it calls the AuthenticationHelper for SRP related * stuff * @param {AuthenticationDetails} authDetails Contains the authentication data * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {newPasswordRequired} callback.newPasswordRequired new * password and any required attributes are required to continue * @param {mfaRequired} callback.mfaRequired MFA code * required to continue. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.authenticateUser = function authenticateUser(authDetails, callback) { var _this2 = this; var authenticationHelper = new _AuthenticationHelper2.default(this.pool.getUserPoolId().split('_')[1]); var dateHelper = new _DateHelper2.default(); var serverBValue = void 0; var salt = void 0; var authParameters = {}; if (this.deviceKey != null) { authParameters.DEVICE_KEY = this.deviceKey; } authParameters.USERNAME = this.username; authenticationHelper.getLargeAValue(function (errOnAValue, aValue) { // getLargeAValue callback start if (errOnAValue) { callback.onFailure(errOnAValue); } authParameters.SRP_A = aValue.toString(16); if (_this2.authenticationFlowType === 'CUSTOM_AUTH') { authParameters.CHALLENGE_NAME = 'SRP_A'; } var jsonReq = { AuthFlow: _this2.authenticationFlowType, ClientId: _this2.pool.getClientId(), AuthParameters: authParameters, ClientMetadata: authDetails.getValidationData() }; if (_this2.getUserContextData(_this2.username)) { jsonReq.UserContextData = _this2.getUserContextData(_this2.username); } _this2.client.makeUnauthenticatedRequest('initiateAuth', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } var challengeParameters = data.ChallengeParameters; _this2.username = challengeParameters.USER_ID_FOR_SRP; serverBValue = new _BigInteger2.default(challengeParameters.SRP_B, 16); salt = new _BigInteger2.default(challengeParameters.SALT, 16); _this2.getCachedDeviceKeyAndPassword(); authenticationHelper.getPasswordAuthenticationKey(_this2.username, authDetails.getPassword(), serverBValue, salt, function (errOnHkdf, hkdf) { // getPasswordAuthenticationKey callback start if (errOnHkdf) { callback.onFailure(errOnHkdf); } var dateNow = dateHelper.getNowString(); var signatureString = _global.util.crypto.hmac(hkdf, _global.util.buffer.concat([new _global.util.Buffer(_this2.pool.getUserPoolId().split('_')[1], 'utf8'), new _global.util.Buffer(_this2.username, 'utf8'), new _global.util.Buffer(challengeParameters.SECRET_BLOCK, 'base64'), new _global.util.Buffer(dateNow, 'utf8')]), 'base64', 'sha256'); var challengeResponses = {}; challengeResponses.USERNAME = _this2.username; challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK; challengeResponses.TIMESTAMP = dateNow; challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString; if (_this2.deviceKey != null) { challengeResponses.DEVICE_KEY = _this2.deviceKey; } var respondToAuthChallenge = function respondToAuthChallenge(challenge, challengeCallback) { return _this2.client.makeUnauthenticatedRequest('respondToAuthChallenge', challenge, function (errChallenge, dataChallenge) { if (errChallenge && errChallenge.code === 'ResourceNotFoundException' && errChallenge.message.toLowerCase().indexOf('device') !== -1) { challengeResponses.DEVICE_KEY = null; _this2.deviceKey = null; _this2.randomPassword = null; _this2.deviceGroupKey = null; _this2.clearCachedDeviceKeyAndPassword(); return respondToAuthChallenge(challenge, challengeCallback); } return challengeCallback(errChallenge, dataChallenge); }); }; var jsonReqResp = { ChallengeName: 'PASSWORD_VERIFIER', ClientId: _this2.pool.getClientId(), ChallengeResponses: challengeResponses, Session: data.Session }; if (_this2.getUserContextData()) { jsonReqResp.UserContextData = _this2.getUserContextData(); } respondToAuthChallenge(jsonReqResp, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } var challengeName = dataAuthenticate.ChallengeName; if (challengeName === 'NEW_PASSWORD_REQUIRED') { _this2.Session = dataAuthenticate.Session; var userAttributes = null; var rawRequiredAttributes = null; var requiredAttributes = []; var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix(); if (dataAuthenticate.ChallengeParameters) { userAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.userAttributes); rawRequiredAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.requiredAttributes); } if (rawRequiredAttributes) { for (var i = 0; i < rawRequiredAttributes.length; i++) { requiredAttributes[i] = rawRequiredAttributes[i].substr(userAttributesPrefix.length); } } return callback.newPasswordRequired(userAttributes, requiredAttributes); } return _this2.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback); }); return undefined; // getPasswordAuthenticationKey callback end }); return undefined; }); // getLargeAValue callback end }); }; /** * PRIVATE ONLY: This is an internal only method and should not * be directly called by the consumers. * @param {object} dataAuthenticate authentication data * @param {object} authenticationHelper helper created * @param {callback} callback passed on from caller * @returns {void} */ CognitoUser.prototype.authenticateUserInternal = function authenticateUserInternal(dataAuthenticate, authenticationHelper, callback) { var _this3 = this; var challengeName = dataAuthenticate.ChallengeName; var challengeParameters = dataAuthenticate.ChallengeParameters; if (challengeName === 'SMS_MFA') { this.Session = dataAuthenticate.Session; return callback.mfaRequired(challengeName, challengeParameters); } if (challengeName === 'SELECT_MFA_TYPE') { this.Session = dataAuthenticate.Session; return callback.selectMFAType(challengeName, challengeParameters); } if (challengeName === 'MFA_SETUP') { this.Session = dataAuthenticate.Session; return callback.mfaSetup(challengeName, challengeParameters); } if (challengeName === 'SOFTWARE_TOKEN_MFA') { this.Session = dataAuthenticate.Session; return callback.totpRequired(challengeName, challengeParameters); } if (challengeName === 'CUSTOM_CHALLENGE') { this.Session = dataAuthenticate.Session; return callback.customChallenge(challengeParameters); } if (challengeName === 'DEVICE_SRP_AUTH') { this.getDeviceResponse(callback); return undefined; } this.signInUserSession = this.getCognitoUserSession(dataAuthenticate.AuthenticationResult); this.cacheTokens(); var newDeviceMetadata = dataAuthenticate.AuthenticationResult.NewDeviceMetadata; if (newDeviceMetadata == null) { return callback.onSuccess(this.signInUserSession); } authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) { if (errGenHash) { return callback.onFailure(errGenHash); } var deviceSecretVerifierConfig = { Salt: new _global.util.Buffer(authenticationHelper.getSaltDevices(), 'hex').toString('base64'), PasswordVerifier: new _global.util.Buffer(authenticationHelper.getVerifierDevices(), 'hex').toString('base64') }; _this3.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier; _this3.deviceGroupKey = newDeviceMetadata.DeviceGroupKey; _this3.randomPassword = authenticationHelper.getRandomPassword(); _this3.client.makeUnauthenticatedRequest('confirmDevice', { DeviceKey: newDeviceMetadata.DeviceKey, AccessToken: _this3.signInUserSession.getAccessToken().getJwtToken(), DeviceSecretVerifierConfig: deviceSecretVerifierConfig, DeviceName: navigator.userAgent }, function (errConfirm, dataConfirm) { if (errConfirm) { return callback.onFailure(errConfirm); } _this3.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey; _this3.cacheDeviceKeyAndPassword(); if (dataConfirm.UserConfirmationNecessary === true) { return callback.onSuccess(_this3.signInUserSession, dataConfirm.UserConfirmationNecessary); } return callback.onSuccess(_this3.signInUserSession); }); return undefined; }); return undefined; }; /** * This method is user to complete the NEW_PASSWORD_REQUIRED challenge. * Pass the new password with any new user attributes to be updated. * User attribute keys must be of format userAttributes.. * @param {string} newPassword new password for this user * @param {object} requiredAttributeData map with values for all required attributes * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {mfaRequired} callback.mfaRequired MFA code required to continue. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.completeNewPasswordChallenge = function completeNewPasswordChallenge(newPassword, requiredAttributeData, callback) { var _this4 = this; if (!newPassword) { return callback.onFailure(new Error('New password is required.')); } var authenticationHelper = new _AuthenticationHelper2.default(this.pool.getUserPoolId().split('_')[1]); var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix(); var finalUserAttributes = {}; if (requiredAttributeData) { Object.keys(requiredAttributeData).forEach(function (key) { finalUserAttributes[userAttributesPrefix + key] = requiredAttributeData[key]; }); } finalUserAttributes.NEW_PASSWORD = newPassword; finalUserAttributes.USERNAME = this.username; var jsonReq = { ChallengeName: 'NEW_PASSWORD_REQUIRED', ClientId: this.pool.getClientId(), ChallengeResponses: finalUserAttributes, Session: this.Session }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } return _this4.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback); }); return undefined; }; /** * This is used to get a session using device authentication. It is called at the end of user * authentication * * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} * @private */ CognitoUser.prototype.getDeviceResponse = function getDeviceResponse(callback) { var _this5 = this; var authenticationHelper = new _AuthenticationHelper2.default(this.deviceGroupKey); var dateHelper = new _DateHelper2.default(); var authParameters = {}; authParameters.USERNAME = this.username; authParameters.DEVICE_KEY = this.deviceKey; authenticationHelper.getLargeAValue(function (errAValue, aValue) { // getLargeAValue callback start if (errAValue) { callback.onFailure(errAValue); } authParameters.SRP_A = aValue.toString(16); var jsonReq = { ChallengeName: 'DEVICE_SRP_AUTH', ClientId: _this5.pool.getClientId(), ChallengeResponses: authParameters }; if (_this5.getUserContextData()) { jsonReq.UserContextData = _this5.getUserContextData(); } _this5.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } var challengeParameters = data.ChallengeParameters; var serverBValue = new _BigInteger2.default(challengeParameters.SRP_B, 16); var salt = new _BigInteger2.default(challengeParameters.SALT, 16); authenticationHelper.getPasswordAuthenticationKey(_this5.deviceKey, _this5.randomPassword, serverBValue, salt, function (errHkdf, hkdf) { // getPasswordAuthenticationKey callback start if (errHkdf) { return callback.onFailure(errHkdf); } var dateNow = dateHelper.getNowString(); var signatureString = _global.util.crypto.hmac(hkdf, _global.util.buffer.concat([new _global.util.Buffer(_this5.deviceGroupKey, 'utf8'), new _global.util.Buffer(_this5.deviceKey, 'utf8'), new _global.util.Buffer(challengeParameters.SECRET_BLOCK, 'base64'), new _global.util.Buffer(dateNow, 'utf8')]), 'base64', 'sha256'); var challengeResponses = {}; challengeResponses.USERNAME = _this5.username; challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK; challengeResponses.TIMESTAMP = dateNow; challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString; challengeResponses.DEVICE_KEY = _this5.deviceKey; var jsonReqResp = { ChallengeName: 'DEVICE_PASSWORD_VERIFIER', ClientId: _this5.pool.getClientId(), ChallengeResponses: challengeResponses, Session: data.Session }; if (_this5.getUserContextData()) { jsonReqResp.UserContextData = _this5.getUserContextData(); } _this5.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReqResp, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } _this5.signInUserSession = _this5.getCognitoUserSession(dataAuthenticate.AuthenticationResult); _this5.cacheTokens(); return callback.onSuccess(_this5.signInUserSession); }); return undefined; // getPasswordAuthenticationKey callback end }); return undefined; }); // getLargeAValue callback end }); }; /** * This is used for a certain user to confirm the registration by using a confirmation code * @param {string} confirmationCode Code entered by user. * @param {bool} forceAliasCreation Allow migrating from an existing email / phone number. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.confirmRegistration = function confirmRegistration(confirmationCode, forceAliasCreation, callback) { var jsonReq = { ClientId: this.pool.getClientId(), ConfirmationCode: confirmationCode, Username: this.username, ForceAliasCreation: forceAliasCreation }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('confirmSignUp', jsonReq, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); }; /** * This is used by the user once he has the responses to a custom challenge * @param {string} answerChallenge The custom challange answer. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {customChallenge} callback.customChallenge * Custom challenge response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.sendCustomChallengeAnswer = function sendCustomChallengeAnswer(answerChallenge, callback) { var _this6 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.ANSWER = answerChallenge; var authenticationHelper = new _AuthenticationHelper2.default(this.pool.getUserPoolId().split('_')[1]); this.getCachedDeviceKeyAndPassword(); if (this.deviceKey != null) { challengeResponses.DEVICE_KEY = this.deviceKey; } var jsonReq = { ChallengeName: 'CUSTOM_CHALLENGE', ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } return _this6.authenticateUserInternal(data, authenticationHelper, callback); }); }; /** * This is used by the user once he has an MFA code * @param {string} confirmationCode The MFA code entered by the user. * @param {object} callback Result callback map. * @param {string} mfaType The mfa we are replying to. * @param {onFailure} callback.onFailure Called on any error. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.sendMFACode = function sendMFACode(confirmationCode, callback, mfaType) { var _this7 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.SMS_MFA_CODE = confirmationCode; var mfaTypeSelection = mfaType || 'SMS_MFA'; if (mfaTypeSelection === 'SOFTWARE_TOKEN_MFA') { challengeResponses.SOFTWARE_TOKEN_MFA_CODE = confirmationCode; } if (this.deviceKey != null) { challengeResponses.DEVICE_KEY = this.deviceKey; } var jsonReq = { ChallengeName: mfaTypeSelection, ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (err, dataAuthenticate) { if (err) { return callback.onFailure(err); } var challengeName = dataAuthenticate.ChallengeName; if (challengeName === 'DEVICE_SRP_AUTH') { _this7.getDeviceResponse(callback); return undefined; } _this7.signInUserSession = _this7.getCognitoUserSession(dataAuthenticate.AuthenticationResult); _this7.cacheTokens(); if (dataAuthenticate.AuthenticationResult.NewDeviceMetadata == null) { return callback.onSuccess(_this7.signInUserSession); } var authenticationHelper = new _AuthenticationHelper2.default(_this7.pool.getUserPoolId().split('_')[1]); authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) { if (errGenHash) { return callback.onFailure(errGenHash); } var deviceSecretVerifierConfig = { Salt: new _global.util.Buffer(authenticationHelper.getSaltDevices(), 'hex').toString('base64'), PasswordVerifier: new _global.util.Buffer(authenticationHelper.getVerifierDevices(), 'hex').toString('base64') }; _this7.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier; _this7.deviceGroupKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey; _this7.randomPassword = authenticationHelper.getRandomPassword(); _this7.client.makeUnauthenticatedRequest('confirmDevice', { DeviceKey: dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, AccessToken: _this7.signInUserSession.getAccessToken().getJwtToken(), DeviceSecretVerifierConfig: deviceSecretVerifierConfig, DeviceName: navigator.userAgent }, function (errConfirm, dataConfirm) { if (errConfirm) { return callback.onFailure(errConfirm); } _this7.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey; _this7.cacheDeviceKeyAndPassword(); if (dataConfirm.UserConfirmationNecessary === true) { return callback.onSuccess(_this7.signInUserSession, dataConfirm.UserConfirmationNecessary); } return callback.onSuccess(_this7.signInUserSession); }); return undefined; }); return undefined; }); }; /** * This is used by an authenticated user to change the current password * @param {string} oldUserPassword The current password. * @param {string} newUserPassword The requested new password. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.changePassword = function changePassword(oldUserPassword, newUserPassword, callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('changePassword', { PreviousPassword: oldUserPassword, ProposedPassword: newUserPassword, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to enable MFA for himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.enableMFA = function enableMFA(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } var mfaOptions = []; var mfaEnabled = { DeliveryMedium: 'SMS', AttributeName: 'phone_number' }; mfaOptions.push(mfaEnabled); this.client.makeUnauthenticatedRequest('setUserSettings', { MFAOptions: mfaOptions, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to enable MFA for himself * @param {string[]} smsMfaSettings the sms mfa settings * @param {string[]} softwareTokenMfaSettings the software token mfa settings * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.setUserMfaPreference = function setUserMfaPreference(smsMfaSettings, softwareTokenMfaSettings, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('setUserMFAPreference', { SMSMfaSettings: smsMfaSettings, SoftwareTokenMfaSettings: softwareTokenMfaSettings, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to disable MFA for himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.disableMFA = function disableMFA(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } var mfaOptions = []; this.client.makeUnauthenticatedRequest('setUserSettings', { MFAOptions: mfaOptions, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to delete himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.deleteUser = function deleteUser(callback) { var _this8 = this; if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('deleteUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } _this8.clearCachedTokens(); return callback(null, 'SUCCESS'); }); return undefined; }; /** * @typedef {CognitoUserAttribute | { Name:string, Value:string }} AttributeArg */ /** * This is used by an authenticated user to change a list of attributes * @param {AttributeArg[]} attributes A list of the new user attributes. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.updateAttributes = function updateAttributes(attributes, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('updateUserAttributes', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), UserAttributes: attributes }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to get a list of attributes * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.getUserAttributes = function getUserAttributes(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('getUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, userData) { if (err) { return callback(err, null); } var attributeList = []; for (var i = 0; i < userData.UserAttributes.length; i++) { var attribute = { Name: userData.UserAttributes[i].Name, Value: userData.UserAttributes[i].Value }; var userAttribute = new _CognitoUserAttribute2.default(attribute); attributeList.push(userAttribute); } return callback(null, attributeList); }); return undefined; }; /** * This is used by an authenticated user to get the MFAOptions * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.getMFAOptions = function getMFAOptions(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('getUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, userData) { if (err) { return callback(err, null); } return callback(null, userData.MFAOptions); }); return undefined; }; /** * This is used by an authenticated user to delete a list of attributes * @param {string[]} attributeList Names of the attributes to delete. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.deleteAttributes = function deleteAttributes(attributeList, callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('deleteUserAttributes', { UserAttributeNames: attributeList, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by a user to resend a confirmation code * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.resendConfirmationCode = function resendConfirmationCode(callback) { var jsonReq = { ClientId: this.pool.getClientId(), Username: this.username }; this.client.makeUnauthenticatedRequest('resendConfirmationCode', jsonReq, function (err, result) { if (err) { return callback(err, null); } return callback(null, result); }); }; /** * This is used to get a session, either from the session object * or from the local storage, or by using a refresh token * * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.getSession = function getSession(callback) { if (this.username == null) { return callback(new Error('Username is null. Cannot retrieve a new session'), null); } if (this.signInUserSession != null && this.signInUserSession.isValid()) { return callback(null, this.signInUserSession); } var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var idTokenKey = keyPrefix + '.idToken'; var accessTokenKey = keyPrefix + '.accessToken'; var refreshTokenKey = keyPrefix + '.refreshToken'; var clockDriftKey = keyPrefix + '.clockDrift'; if (this.storage.getItem(idTokenKey)) { var idToken = new _CognitoIdToken2.default({ IdToken: this.storage.getItem(idTokenKey) }); var accessToken = new _CognitoAccessToken2.default({ AccessToken: this.storage.getItem(accessTokenKey) }); var refreshToken = new _CognitoRefreshToken2.default({ RefreshToken: this.storage.getItem(refreshTokenKey) }); var clockDrift = parseInt(this.storage.getItem(clockDriftKey), 0) || 0; var sessionData = { IdToken: idToken, AccessToken: accessToken, RefreshToken: refreshToken, ClockDrift: clockDrift }; var cachedSession = new _CognitoUserSession2.default(sessionData); if (cachedSession.isValid()) { this.signInUserSession = cachedSession; return callback(null, this.signInUserSession); } if (refreshToken.getToken() == null) { return callback(new Error('Cannot retrieve a new session. Please authenticate.'), null); } this.refreshSession(refreshToken, callback); } else { callback(new Error('Local storage is missing an ID Token, Please authenticate'), null); } return undefined; }; /** * This uses the refreshToken to retrieve a new session * @param {CognitoRefreshToken} refreshToken A previous session's refresh token. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.refreshSession = function refreshSession(refreshToken, callback) { var _this9 = this; var authParameters = {}; authParameters.REFRESH_TOKEN = refreshToken.getToken(); var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId(); var lastUserKey = keyPrefix + '.LastAuthUser'; if (this.storage.getItem(lastUserKey)) { this.username = this.storage.getItem(lastUserKey); var deviceKeyKey = keyPrefix + '.' + this.username + '.deviceKey'; this.deviceKey = this.storage.getItem(deviceKeyKey); authParameters.DEVICE_KEY = this.deviceKey; } var jsonReq = { ClientId: this.pool.getClientId(), AuthFlow: 'REFRESH_TOKEN_AUTH', AuthParameters: authParameters }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('initiateAuth', jsonReq, function (err, authResult) { if (err) { if (err.code === 'NotAuthorizedException') { _this9.clearCachedTokens(); } return callback(err, null); } if (authResult) { var authenticationResult = authResult.AuthenticationResult; if (!Object.prototype.hasOwnProperty.call(authenticationResult, 'RefreshToken')) { authenticationResult.RefreshToken = refreshToken.getToken(); } _this9.signInUserSession = _this9.getCognitoUserSession(authenticationResult); _this9.cacheTokens(); return callback(null, _this9.signInUserSession); } return undefined; }); }; /** * This is used to save the session tokens to local storage * @returns {void} */ CognitoUser.prototype.cacheTokens = function cacheTokens() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId(); var idTokenKey = keyPrefix + '.' + this.username + '.idToken'; var accessTokenKey = keyPrefix + '.' + this.username + '.accessToken'; var refreshTokenKey = keyPrefix + '.' + this.username + '.refreshToken'; var clockDriftKey = keyPrefix + '.' + this.username + '.clockDrift'; var lastUserKey = keyPrefix + '.LastAuthUser'; this.storage.setItem(idTokenKey, this.signInUserSession.getIdToken().getJwtToken()); this.storage.setItem(accessTokenKey, this.signInUserSession.getAccessToken().getJwtToken()); this.storage.setItem(refreshTokenKey, this.signInUserSession.getRefreshToken().getToken()); this.storage.setItem(clockDriftKey, '' + this.signInUserSession.getClockDrift()); this.storage.setItem(lastUserKey, this.username); }; /** * This is used to cache the device key and device group and device password * @returns {void} */ CognitoUser.prototype.cacheDeviceKeyAndPassword = function cacheDeviceKeyAndPassword() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var deviceKeyKey = keyPrefix + '.deviceKey'; var randomPasswordKey = keyPrefix + '.randomPasswordKey'; var deviceGroupKeyKey = keyPrefix + '.deviceGroupKey'; this.storage.setItem(deviceKeyKey, this.deviceKey); this.storage.setItem(randomPasswordKey, this.randomPassword); this.storage.setItem(deviceGroupKeyKey, this.deviceGroupKey); }; /** * This is used to get current device key and device group and device password * @returns {void} */ CognitoUser.prototype.getCachedDeviceKeyAndPassword = function getCachedDeviceKeyAndPassword() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var deviceKeyKey = keyPrefix + '.deviceKey'; var randomPasswordKey = keyPrefix + '.randomPasswordKey'; var deviceGroupKeyKey = keyPrefix + '.deviceGroupKey'; if (this.storage.getItem(deviceKeyKey)) { this.deviceKey = this.storage.getItem(deviceKeyKey); this.randomPassword = this.storage.getItem(randomPasswordKey); this.deviceGroupKey = this.storage.getItem(deviceGroupKeyKey); } }; /** * This is used to clear the device key info from local storage * @returns {void} */ CognitoUser.prototype.clearCachedDeviceKeyAndPassword = function clearCachedDeviceKeyAndPassword() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var deviceKeyKey = keyPrefix + '.deviceKey'; var randomPasswordKey = keyPrefix + '.randomPasswordKey'; var deviceGroupKeyKey = keyPrefix + '.deviceGroupKey'; this.storage.removeItem(deviceKeyKey); this.storage.removeItem(randomPasswordKey); this.storage.removeItem(deviceGroupKeyKey); }; /** * This is used to clear the session tokens from local storage * @returns {void} */ CognitoUser.prototype.clearCachedTokens = function clearCachedTokens() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId(); var idTokenKey = keyPrefix + '.' + this.username + '.idToken'; var accessTokenKey = keyPrefix + '.' + this.username + '.accessToken'; var refreshTokenKey = keyPrefix + '.' + this.username + '.refreshToken'; var lastUserKey = keyPrefix + '.LastAuthUser'; this.storage.removeItem(idTokenKey); this.storage.removeItem(accessTokenKey); this.storage.removeItem(refreshTokenKey); this.storage.removeItem(lastUserKey); }; /** * This is used to build a user session from tokens retrieved in the authentication result * @param {object} authResult Successful auth response from server. * @returns {CognitoUserSession} The new user session. * @private */ CognitoUser.prototype.getCognitoUserSession = function getCognitoUserSession(authResult) { var idToken = new _CognitoIdToken2.default(authResult); var accessToken = new _CognitoAccessToken2.default(authResult); var refreshToken = new _CognitoRefreshToken2.default(authResult); var sessionData = { IdToken: idToken, AccessToken: accessToken, RefreshToken: refreshToken }; return new _CognitoUserSession2.default(sessionData); }; /** * This is used to initiate a forgot password request * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {inputVerificationCode?} callback.inputVerificationCode * Optional callback raised instead of onSuccess with response data. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.forgotPassword = function forgotPassword(callback) { var jsonReq = { ClientId: this.pool.getClientId(), Username: this.username }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('forgotPassword', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } if (typeof callback.inputVerificationCode === 'function') { return callback.inputVerificationCode(data); } return callback.onSuccess(data); }); }; /** * This is used to confirm a new password using a confirmationCode * @param {string} confirmationCode Code entered by user. * @param {string} newPassword Confirm new password. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.confirmPassword = function confirmPassword(confirmationCode, newPassword, callback) { var jsonReq = { ClientId: this.pool.getClientId(), Username: this.username, ConfirmationCode: confirmationCode, Password: newPassword }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('confirmForgotPassword', jsonReq, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess(); }); }; /** * This is used to initiate an attribute confirmation request * @param {string} attributeName User attribute that needs confirmation. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {inputVerificationCode} callback.inputVerificationCode Called on success. * @returns {void} */ CognitoUser.prototype.getAttributeVerificationCode = function getAttributeVerificationCode(attributeName, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('getUserAttributeVerificationCode', { AttributeName: attributeName, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, data) { if (err) { return callback.onFailure(err); } if (typeof callback.inputVerificationCode === 'function') { return callback.inputVerificationCode(data); } return callback.onSuccess(); }); return undefined; }; /** * This is used to confirm an attribute using a confirmation code * @param {string} attributeName Attribute being confirmed. * @param {string} confirmationCode Code entered by user. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.verifyAttribute = function verifyAttribute(attributeName, confirmationCode, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('verifyUserAttribute', { AttributeName: attributeName, Code: confirmationCode, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to get the device information using the current device key * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess<*>} callback.onSuccess Called on success with device data. * @returns {void} */ CognitoUser.prototype.getDevice = function getDevice(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('getDevice', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey }, function (err, data) { if (err) { return callback.onFailure(err); } return callback.onSuccess(data); }); return undefined; }; /** * This is used to forget a specific device * @param {string} deviceKey Device key. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.forgetSpecificDevice = function forgetSpecificDevice(deviceKey, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('forgetDevice', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: deviceKey }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to forget the current device * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.forgetDevice = function forgetDevice(callback) { var _this10 = this; this.forgetSpecificDevice(this.deviceKey, { onFailure: callback.onFailure, onSuccess: function onSuccess(result) { _this10.deviceKey = null; _this10.deviceGroupKey = null; _this10.randomPassword = null; _this10.clearCachedDeviceKeyAndPassword(); return callback.onSuccess(result); } }); }; /** * This is used to set the device status as remembered * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.setDeviceStatusRemembered = function setDeviceStatusRemembered(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('updateDeviceStatus', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey, DeviceRememberedStatus: 'remembered' }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to set the device status as not remembered * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.setDeviceStatusNotRemembered = function setDeviceStatusNotRemembered(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('updateDeviceStatus', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey, DeviceRememberedStatus: 'not_remembered' }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to list all devices for a user * * @param {int} limit the number of devices returned in a call * @param {string} paginationToken the pagination token in case any was returned before * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess<*>} callback.onSuccess Called on success with device list. * @returns {void} */ CognitoUser.prototype.listDevices = function listDevices(limit, paginationToken, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('listDevices', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), Limit: limit, PaginationToken: paginationToken }, function (err, data) { if (err) { return callback.onFailure(err); } return callback.onSuccess(data); }); return undefined; }; /** * This is used to globally revoke all tokens issued to a user * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.globalSignOut = function globalSignOut(callback) { var _this11 = this; if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('globalSignOut', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback.onFailure(err); } _this11.clearCachedTokens(); return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used for the user to signOut of the application and clear the cached tokens. * @returns {void} */ CognitoUser.prototype.signOut = function signOut() { this.signInUserSession = null; this.clearCachedTokens(); }; /** * This is used by a user trying to select a given MFA * @param {string} answerChallenge the mfa the user wants * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.sendMFASelectionAnswer = function sendMFASelectionAnswer(answerChallenge, callback) { var _this12 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.ANSWER = answerChallenge; var jsonReq = { ChallengeName: 'SELECT_MFA_TYPE', ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } _this12.Session = data.Session; if (answerChallenge === 'SMS_MFA') { return callback.mfaRequired(data.challengeName, data.challengeParameters); } if (answerChallenge === 'SOFTWARE_TOKEN_MFA') { return callback.totpRequired(data.challengeName, data.challengeParameters); } return undefined; }); }; /** * This returns the user context data for advanced security feature. * @returns {void} */ CognitoUser.prototype.getUserContextData = function getUserContextData() { var pool = this.pool; return pool.getUserContextData(this.username); }; /** * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.associateSoftwareToken = function associateSoftwareToken(callback) { var _this13 = this; if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { this.client.makeUnauthenticatedRequest('associateSoftwareToken', { Session: this.Session }, function (err, data) { if (err) { return callback.onFailure(err); } _this13.Session = data.Session; return callback.associateSecretCode(data.SecretCode); }); } else { this.client.makeUnauthenticatedRequest('associateSoftwareToken', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, data) { if (err) { return callback.onFailure(err); } return callback.associateSecretCode(data.SecretCode); }); } }; /** * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA * @param {string} totpCode The MFA code entered by the user. * @param {string} friendlyDeviceName The device name we are assigning to the device. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.verifySoftwareToken = function verifySoftwareToken(totpCode, friendlyDeviceName, callback) { var _this14 = this; if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { this.client.makeUnauthenticatedRequest('verifySoftwareToken', { Session: this.Session, UserCode: totpCode, FriendlyDeviceName: friendlyDeviceName }, function (err, data) { if (err) { return callback.onFailure(err); } _this14.Session = data.Session; var challengeResponses = {}; challengeResponses.USERNAME = _this14.username; var jsonReq = { ChallengeName: 'MFA_SETUP', ClientId: _this14.pool.getClientId(), ChallengeResponses: challengeResponses, Session: _this14.Session }; if (_this14.getUserContextData()) { jsonReq.UserContextData = _this14.getUserContextData(); } _this14.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (errRespond, dataRespond) { if (errRespond) { return callback.onFailure(errRespond); } _this14.signInUserSession = _this14.getCognitoUserSession(dataRespond.AuthenticationResult); _this14.cacheTokens(); return callback.onSuccess(_this14.signInUserSession); }); return undefined; }); } else { this.client.makeUnauthenticatedRequest('verifySoftwareToken', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), UserCode: totpCode, FriendlyDeviceName: friendlyDeviceName }, function (err, data) { if (err) { return callback.onFailure(err); } return callback(null, data); }); } }; return CognitoUser; }(); exports.default = CognitoUser; /***/ }), /* 9 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoUserAttribute = function () { /** * Constructs a new CognitoUserAttribute object * @param {string=} Name The record's name * @param {string=} Value The record's value */ function CognitoUserAttribute() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, Name = _ref.Name, Value = _ref.Value; _classCallCheck(this, CognitoUserAttribute); this.Name = Name || ''; this.Value = Value || ''; } /** * @returns {string} the record's value. */ CognitoUserAttribute.prototype.getValue = function getValue() { return this.Value; }; /** * Sets the record's value. * @param {string} value The new value. * @returns {CognitoUserAttribute} The record for method chaining. */ CognitoUserAttribute.prototype.setValue = function setValue(value) { this.Value = value; return this; }; /** * @returns {string} the record's name. */ CognitoUserAttribute.prototype.getName = function getName() { return this.Name; }; /** * Sets the record's name * @param {string} name The new name. * @returns {CognitoUserAttribute} The record for method chaining. */ CognitoUserAttribute.prototype.setName = function setName(name) { this.Name = name; return this; }; /** * @returns {string} a string representation of the record. */ CognitoUserAttribute.prototype.toString = function toString() { return JSON.stringify(this); }; /** * @returns {object} a flat object representing the record. */ CognitoUserAttribute.prototype.toJSON = function toJSON() { return { Name: this.Name, Value: this.Value }; }; return CognitoUserAttribute; }(); exports.default = CognitoUserAttribute; /***/ }), /* 10 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoUserSession = function () { /** * Constructs a new CognitoUserSession object * @param {CognitoIdToken} IdToken The session's Id token. * @param {CognitoRefreshToken=} RefreshToken The session's refresh token. * @param {CognitoAccessToken} AccessToken The session's access token. * @param {int} ClockDrift The saved computer's clock drift or undefined to force calculation. */ function CognitoUserSession() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, IdToken = _ref.IdToken, RefreshToken = _ref.RefreshToken, AccessToken = _ref.AccessToken, ClockDrift = _ref.ClockDrift; _classCallCheck(this, CognitoUserSession); if (AccessToken == null || IdToken == null) { throw new Error('Id token and Access Token must be present.'); } this.idToken = IdToken; this.refreshToken = RefreshToken; this.accessToken = AccessToken; this.clockDrift = ClockDrift === undefined ? this.calculateClockDrift() : ClockDrift; } /** * @returns {CognitoIdToken} the session's Id token */ CognitoUserSession.prototype.getIdToken = function getIdToken() { return this.idToken; }; /** * @returns {CognitoRefreshToken} the session's refresh token */ CognitoUserSession.prototype.getRefreshToken = function getRefreshToken() { return this.refreshToken; }; /** * @returns {CognitoAccessToken} the session's access token */ CognitoUserSession.prototype.getAccessToken = function getAccessToken() { return this.accessToken; }; /** * @returns {int} the session's clock drift */ CognitoUserSession.prototype.getClockDrift = function getClockDrift() { return this.clockDrift; }; /** * @returns {int} the computer's clock drift */ CognitoUserSession.prototype.calculateClockDrift = function calculateClockDrift() { var now = Math.floor(new Date() / 1000); var iat = Math.min(this.accessToken.getIssuedAt(), this.idToken.getIssuedAt()); return now - iat; }; /** * Checks to see if the session is still valid based on session expiry information found * in tokens and the current time (adjusted with clock drift) * @returns {boolean} if the session is still valid */ CognitoUserSession.prototype.isValid = function isValid() { var now = Math.floor(new Date() / 1000); var adjusted = now - this.clockDrift; return adjusted < this.accessToken.getExpiration() && adjusted < this.idToken.getExpiration(); }; return CognitoUserSession; }(); exports.default = CognitoUserSession; /***/ }), /* 11 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var weekNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; /** @class */ var DateHelper = function () { function DateHelper() { _classCallCheck(this, DateHelper); } /** * @returns {string} The current time in "ddd MMM D HH:mm:ss UTC YYYY" format. */ DateHelper.prototype.getNowString = function getNowString() { var now = new Date(); var weekDay = weekNames[now.getUTCDay()]; var month = monthNames[now.getUTCMonth()]; var day = now.getUTCDate(); var hours = now.getUTCHours(); if (hours < 10) { hours = '0' + hours; } var minutes = now.getUTCMinutes(); if (minutes < 10) { minutes = '0' + minutes; } var seconds = now.getUTCSeconds(); if (seconds < 10) { seconds = '0' + seconds; } var year = now.getUTCFullYear(); // ddd MMM D HH:mm:ss UTC YYYY var dateNow = weekDay + ' ' + month + ' ' + day + ' ' + hours + ':' + minutes + ':' + seconds + ' UTC ' + year; return dateNow; }; return DateHelper; }(); exports.default = DateHelper; /***/ }), /* 12 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ var dataMemory = {}; /** @class */ var MemoryStorage = function () { function MemoryStorage() { _classCallCheck(this, MemoryStorage); } /** * This is used to set a specific item in storage * @param {string} key - the key for the item * @param {object} value - the value * @returns {string} value that was set */ MemoryStorage.setItem = function setItem(key, value) { dataMemory[key] = value; return dataMemory[key]; }; /** * This is used to get a specific key from storage * @param {string} key - the key for the item * This is used to clear the storage * @returns {string} the data item */ MemoryStorage.getItem = function getItem(key) { return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined; }; /** * This is used to remove an item from storage * @param {string} key - the key being set * @returns {string} value - value that was deleted */ MemoryStorage.removeItem = function removeItem(key) { return delete dataMemory[key]; }; /** * This is used to clear the storage * @returns {string} nothing */ MemoryStorage.clear = function clear() { dataMemory = {}; return dataMemory; }; return MemoryStorage; }(); /** @class */ var StorageHelper = function () { /** * This is used to get a storage object * @returns {object} the storage */ function StorageHelper() { _classCallCheck(this, StorageHelper); try { this.storageWindow = window.localStorage; this.storageWindow.setItem('aws.cognito.test-ls', 1); this.storageWindow.removeItem('aws.cognito.test-ls'); } catch (exception) { this.storageWindow = MemoryStorage; } } /** * This is used to return the storage * @returns {object} the storage */ StorageHelper.prototype.getStorage = function getStorage() { return this.storageWindow; }; return StorageHelper; }(); exports.default = StorageHelper; /***/ }), /* 13 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_13__; /***/ }), /* 14 */ /***/ (function(module, exports) { "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var AuthenticationDetails = function () { /** * Constructs a new AuthenticationDetails object * @param {object=} data Creation options. * @param {string} data.Username User being authenticated. * @param {string} data.Password Plain-text password to authenticate with. * @param {(AttributeArg[])?} data.ValidationData Application extra metadata. * @param {(AttributeArg[])?} data.AuthParamaters Authentication paramaters for custom auth. */ function AuthenticationDetails(data) { _classCallCheck(this, AuthenticationDetails); var _ref = data || {}, ValidationData = _ref.ValidationData, Username = _ref.Username, Password = _ref.Password, AuthParameters = _ref.AuthParameters; this.validationData = ValidationData || []; this.authParameters = AuthParameters || []; this.username = Username; this.password = Password; } /** * @returns {string} the record's username */ AuthenticationDetails.prototype.getUsername = function getUsername() { return this.username; }; /** * @returns {string} the record's password */ AuthenticationDetails.prototype.getPassword = function getPassword() { return this.password; }; /** * @returns {Array} the record's validationData */ AuthenticationDetails.prototype.getValidationData = function getValidationData() { return this.validationData; }; /** * @returns {Array} the record's authParameters */ AuthenticationDetails.prototype.getAuthParameters = function getAuthParameters() { return this.authParameters; }; return AuthenticationDetails; }(); exports.default = AuthenticationDetails; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _cognitoidentityserviceprovider = __webpack_require__(13); var _cognitoidentityserviceprovider2 = _interopRequireDefault(_cognitoidentityserviceprovider); var _CognitoUser = __webpack_require__(8); var _CognitoUser2 = _interopRequireDefault(_CognitoUser); var _StorageHelper = __webpack_require__(12); var _StorageHelper2 = _interopRequireDefault(_StorageHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoUserPool = function () { /** * Constructs a new CognitoUserPool object * @param {object} data Creation options. * @param {string} data.UserPoolId Cognito user pool id. * @param {string} data.ClientId User pool application client id. * @param {object} data.Storage Optional storage object. * @param {boolean} data.AdvancedSecurityDataCollectionFlag Optional: * boolean flag indicating if the data collection is enabled * to support cognito advanced security features. By default, this * flag is set to true. */ function CognitoUserPool(data) { _classCallCheck(this, CognitoUserPool); var _ref = data || {}, UserPoolId = _ref.UserPoolId, ClientId = _ref.ClientId, endpoint = _ref.endpoint, AdvancedSecurityDataCollectionFlag = _ref.AdvancedSecurityDataCollectionFlag; if (!UserPoolId || !ClientId) { throw new Error('Both UserPoolId and ClientId are required.'); } if (!/^[\w-]+_.+$/.test(UserPoolId)) { throw new Error('Invalid UserPoolId format.'); } var region = UserPoolId.split('_')[0]; this.userPoolId = UserPoolId; this.clientId = ClientId; this.client = new _cognitoidentityserviceprovider2.default({ apiVersion: '2016-04-19', region: region, endpoint: endpoint }); /** * By default, AdvancedSecurityDataCollectionFlag is set to true, * if no input value is provided. */ this.advancedSecurityDataCollectionFlag = AdvancedSecurityDataCollectionFlag !== false; this.storage = data.Storage || new _StorageHelper2.default().getStorage(); } /** * @returns {string} the user pool id */ CognitoUserPool.prototype.getUserPoolId = function getUserPoolId() { return this.userPoolId; }; /** * @returns {string} the client id */ CognitoUserPool.prototype.getClientId = function getClientId() { return this.clientId; }; /** * @typedef {object} SignUpResult * @property {CognitoUser} user New user. * @property {bool} userConfirmed If the user is already confirmed. */ /** * method for signing up a user * @param {string} username User's username. * @param {string} password Plain-text initial password entered by user. * @param {(AttributeArg[])=} userAttributes New user attributes. * @param {(AttributeArg[])=} validationData Application metadata. * @param {nodeCallback} callback Called on error or with the new user. * @returns {void} */ CognitoUserPool.prototype.signUp = function signUp(username, password, userAttributes, validationData, callback) { var _this = this; var jsonReq = { ClientId: this.clientId, Username: username, Password: password, UserAttributes: userAttributes, ValidationData: validationData }; if (this.getUserContextData(username)) { jsonReq.UserContextData = this.getUserContextData(username); } this.client.makeUnauthenticatedRequest('signUp', jsonReq, function (err, data) { if (err) { return callback(err, null); } var cognitoUser = { Username: username, Pool: _this, Storage: _this.storage }; var returnData = { user: new _CognitoUser2.default(cognitoUser), userConfirmed: data.UserConfirmed, userSub: data.UserSub }; return callback(null, returnData); }); }; /** * method for getting the current user of the application from the local storage * * @returns {CognitoUser} the user retrieved from storage */ CognitoUserPool.prototype.getCurrentUser = function getCurrentUser() { var lastUserKey = 'CognitoIdentityServiceProvider.' + this.clientId + '.LastAuthUser'; var lastAuthUser = this.storage.getItem(lastUserKey); if (lastAuthUser) { var cognitoUser = { Username: lastAuthUser, Pool: this, Storage: this.storage }; return new _CognitoUser2.default(cognitoUser); } return null; }; /** * This method returns the encoded data string used for cognito advanced security feature. * This would be generated only when developer has included the JS used for collecting the * data on their client. Please refer to documentation to know more about using AdvancedSecurity * features * @param {string} username the username for the context data * @returns {string} the user context data **/ CognitoUserPool.prototype.getUserContextData = function getUserContextData(username) { if (typeof AmazonCognitoAdvancedSecurityData === 'undefined') { return undefined; } /* eslint-disable */ var amazonCognitoAdvancedSecurityDataConst = AmazonCognitoAdvancedSecurityData; /* eslint-enable */ if (this.advancedSecurityDataCollectionFlag) { var advancedSecurityData = amazonCognitoAdvancedSecurityDataConst.getData(username, this.userPoolId, this.clientId); if (advancedSecurityData) { var userContextData = { EncodedData: advancedSecurityData }; return userContextData; } } return {}; }; return CognitoUserPool; }(); exports.default = CognitoUserPool; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _jsCookie = __webpack_require__(18); var Cookies = _interopRequireWildcard(_jsCookie); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** @class */ var CookieStorage = function () { /** * Constructs a new CookieStorage object * @param {object} data Creation options. * @param {string} data.domain Cookies domain (mandatory). * @param {string} data.path Cookies path (default: '/') * @param {integer} data.expires Cookie expiration (in days, default: 365) * @param {boolean} data.secure Cookie secure flag (default: true) */ function CookieStorage(data) { _classCallCheck(this, CookieStorage); this.domain = data.domain; if (data.path) { this.path = data.path; } else { this.path = '/'; } if (Object.prototype.hasOwnProperty.call(data, 'expires')) { this.expires = data.expires; } else { this.expires = 365; } if (Object.prototype.hasOwnProperty.call(data, 'secure')) { this.secure = data.secure; } else { this.secure = true; } } /** * This is used to set a specific item in storage * @param {string} key - the key for the item * @param {object} value - the value * @returns {string} value that was set */ CookieStorage.prototype.setItem = function setItem(key, value) { Cookies.set(key, value, { path: this.path, expires: this.expires, domain: this.domain, secure: this.secure }); return Cookies.get(key); }; /** * This is used to get a specific key from storage * @param {string} key - the key for the item * This is used to clear the storage * @returns {string} the data item */ CookieStorage.prototype.getItem = function getItem(key) { return Cookies.get(key); }; /** * This is used to remove an item from storage * @param {string} key - the key being set * @returns {string} value - value that was deleted */ CookieStorage.prototype.removeItem = function removeItem(key) { return Cookies.remove(key, { path: this.path, domain: this.domain, secure: this.secure }); }; /** * This is used to clear the storage * @returns {string} nothing */ CookieStorage.prototype.clear = function clear() { var cookies = Cookies.get(); var index = void 0; for (index = 0; index < cookies.length; ++index) { Cookies.remove(cookies[index]); } return {}; }; return CookieStorage; }(); exports.default = CookieStorage; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _AuthenticationDetails = __webpack_require__(14); Object.defineProperty(exports, 'AuthenticationDetails', { enumerable: true, get: function get() { return _interopRequireDefault(_AuthenticationDetails).default; } }); var _AuthenticationHelper = __webpack_require__(2); Object.defineProperty(exports, 'AuthenticationHelper', { enumerable: true, get: function get() { return _interopRequireDefault(_AuthenticationHelper).default; } }); var _CognitoAccessToken = __webpack_require__(4); Object.defineProperty(exports, 'CognitoAccessToken', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoAccessToken).default; } }); var _CognitoIdToken = __webpack_require__(5); Object.defineProperty(exports, 'CognitoIdToken', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoIdToken).default; } }); var _CognitoRefreshToken = __webpack_require__(7); Object.defineProperty(exports, 'CognitoRefreshToken', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoRefreshToken).default; } }); var _CognitoUser = __webpack_require__(8); Object.defineProperty(exports, 'CognitoUser', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoUser).default; } }); var _CognitoUserAttribute = __webpack_require__(9); Object.defineProperty(exports, 'CognitoUserAttribute', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoUserAttribute).default; } }); var _CognitoUserPool = __webpack_require__(15); Object.defineProperty(exports, 'CognitoUserPool', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoUserPool).default; } }); var _CognitoUserSession = __webpack_require__(10); Object.defineProperty(exports, 'CognitoUserSession', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoUserSession).default; } }); var _CookieStorage = __webpack_require__(16); Object.defineProperty(exports, 'CookieStorage', { enumerable: true, get: function get() { return _interopRequireDefault(_CookieStorage).default; } }); var _DateHelper = __webpack_require__(11); Object.defineProperty(exports, 'DateHelper', { enumerable: true, get: function get() { return _interopRequireDefault(_DateHelper).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // The version of crypto-browserify included by aws-sdk only // checks for window.crypto, not window.msCrypto as used by // IE 11 – so we set it explicitly here if (typeof window !== 'undefined' && !window.crypto && window.msCrypto) { window.crypto = window.msCrypto; } /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! * JavaScript Cookie v2.2.0 * https://github.com/js-cookie/js-cookie * * Copyright 2006, 2015 Klaus Hartl & Fagner Brack * Released under the MIT license */ ;(function (factory) { var registeredInModuleLoader = false; if (true) { !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); registeredInModuleLoader = true; } if (true) { module.exports = factory(); registeredInModuleLoader = true; } if (!registeredInModuleLoader) { var OldCookies = window.Cookies; var api = window.Cookies = factory(); api.noConflict = function () { window.Cookies = OldCookies; return api; }; } }(function () { function extend () { var i = 0; var result = {}; for (; i < arguments.length; i++) { var attributes = arguments[ i ]; for (var key in attributes) { result[key] = attributes[key]; } } return result; } function init (converter) { function api (key, value, attributes) { var result; if (typeof document === 'undefined') { return; } // Write if (arguments.length > 1) { attributes = extend({ path: '/' }, api.defaults, attributes); if (typeof attributes.expires === 'number') { var expires = new Date(); expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5); attributes.expires = expires; } // We're using "expires" because "max-age" is not supported by IE attributes.expires = attributes.expires ? attributes.expires.toUTCString() : ''; try { result = JSON.stringify(value); if (/^[\{\[]/.test(result)) { value = result; } } catch (e) {} if (!converter.write) { value = encodeURIComponent(String(value)) .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent); } else { value = converter.write(value, key); } key = encodeURIComponent(String(key)); key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent); key = key.replace(/[\(\)]/g, escape); var stringifiedAttributes = ''; for (var attributeName in attributes) { if (!attributes[attributeName]) { continue; } stringifiedAttributes += '; ' + attributeName; if (attributes[attributeName] === true) { continue; } stringifiedAttributes += '=' + attributes[attributeName]; } return (document.cookie = key + '=' + value + stringifiedAttributes); } // Read if (!key) { result = {}; } // To prevent the for loop in the first place assign an empty array // in case there are no cookies at all. Also prevents odd result when // calling "get()" var cookies = document.cookie ? document.cookie.split('; ') : []; var rdecode = /(%[0-9A-Z]{2})+/g; var i = 0; for (; i < cookies.length; i++) { var parts = cookies[i].split('='); var cookie = parts.slice(1).join('='); if (!this.json && cookie.charAt(0) === '"') { cookie = cookie.slice(1, -1); } try { var name = parts[0].replace(rdecode, decodeURIComponent); cookie = converter.read ? converter.read(cookie, name) : converter(cookie, name) || cookie.replace(rdecode, decodeURIComponent); if (this.json) { try { cookie = JSON.parse(cookie); } catch (e) {} } if (key === name) { result = cookie; break; } if (!key) { result[name] = cookie; } } catch (e) {} } return result; } api.set = api; api.get = function (key) { return api.call(api, key); }; api.getJSON = function () { return api.apply({ json: true }, [].slice.call(arguments)); }; api.defaults = {}; api.remove = function (key, attributes) { api(key, '', extend(attributes, { expires: -1 })); }; api.withConverter = init; return api; } return init(function () {}); })); /***/ }) /******/ ]) }); ; ================================================ FILE: dist/aws-cognito-sdk.js ================================================ // AWS SDK for JavaScript v2.6.4 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // License at https://sdk.amazonaws.com/js/BUNDLE_LICENSE.txt (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;oAdds additional user attributes to the user pool schema.

" }, "AdminAddUserToGroup":{ "name":"AdminAddUserToGroup", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminAddUserToGroupRequest"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Adds the specified user to the specified group.

Requires developer credentials.

" }, "AdminConfirmSignUp":{ "name":"AdminConfirmSignUp", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminConfirmSignUpRequest"}, "output":{"shape":"AdminConfirmSignUpResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyFailedAttemptsException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Confirms user registration as an admin without using a confirmation code. Works on any user.

Requires developer credentials.

" }, "AdminCreateUser":{ "name":"AdminCreateUser", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminCreateUserRequest"}, "output":{"shape":"AdminCreateUserResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"UserNotFoundException"}, {"shape":"UsernameExistsException"}, {"shape":"InvalidPasswordException"}, {"shape":"CodeDeliveryFailureException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"PreconditionNotMetException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UnsupportedUserStateException"}, {"shape":"InternalErrorException"} ], "documentation":"

Creates a new user in the specified user pool and sends a welcome message via email or phone (SMS). This message is based on a template that you configured in your call to CreateUserPool or UpdateUserPool. This template includes your custom sign-up instructions and placeholders for user name and temporary password.

Requires developer credentials.

" }, "AdminDeleteUser":{ "name":"AdminDeleteUser", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminDeleteUserRequest"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Deletes a user as an administrator. Works on any user.

Requires developer credentials.

" }, "AdminDeleteUserAttributes":{ "name":"AdminDeleteUserAttributes", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminDeleteUserAttributesRequest"}, "output":{"shape":"AdminDeleteUserAttributesResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Deletes the user attributes in a user pool as an administrator. Works on any user.

Requires developer credentials.

" }, "AdminDisableProviderForUser":{ "name":"AdminDisableProviderForUser", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminDisableProviderForUserRequest"}, "output":{"shape":"AdminDisableProviderForUserResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"AliasExistsException"}, {"shape":"InternalErrorException"} ] }, "AdminDisableUser":{ "name":"AdminDisableUser", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminDisableUserRequest"}, "output":{"shape":"AdminDisableUserResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Disables the specified user as an administrator. Works on any user.

Requires developer credentials.

" }, "AdminEnableUser":{ "name":"AdminEnableUser", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminEnableUserRequest"}, "output":{"shape":"AdminEnableUserResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Enables the specified user as an administrator. Works on any user.

Requires developer credentials.

" }, "AdminForgetDevice":{ "name":"AdminForgetDevice", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminForgetDeviceRequest"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Forgets the device, as an administrator.

Requires developer credentials.

" }, "AdminGetDevice":{ "name":"AdminGetDevice", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminGetDeviceRequest"}, "output":{"shape":"AdminGetDeviceResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"}, {"shape":"NotAuthorizedException"} ], "documentation":"

Gets the device, as an administrator.

Requires developer credentials.

" }, "AdminGetUser":{ "name":"AdminGetUser", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminGetUserRequest"}, "output":{"shape":"AdminGetUserResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Gets the specified user by user name in a user pool as an administrator. Works on any user.

Requires developer credentials.

" }, "AdminInitiateAuth":{ "name":"AdminInitiateAuth", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminInitiateAuthRequest"}, "output":{"shape":"AdminInitiateAuthResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"MFAMethodNotFoundException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"} ], "documentation":"

Initiates the authentication flow, as an administrator.

Requires developer credentials.

" }, "AdminLinkProviderForUser":{ "name":"AdminLinkProviderForUser", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminLinkProviderForUserRequest"}, "output":{"shape":"AdminLinkProviderForUserResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"AliasExistsException"}, {"shape":"InternalErrorException"} ] }, "AdminListDevices":{ "name":"AdminListDevices", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminListDevicesRequest"}, "output":{"shape":"AdminListDevicesResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"}, {"shape":"NotAuthorizedException"} ], "documentation":"

Lists devices, as an administrator.

Requires developer credentials.

" }, "AdminListGroupsForUser":{ "name":"AdminListGroupsForUser", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminListGroupsForUserRequest"}, "output":{"shape":"AdminListGroupsForUserResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Lists the groups that the user belongs to.

Requires developer credentials.

" }, "AdminListUserAuthEvents":{ "name":"AdminListUserAuthEvents", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminListUserAuthEventsRequest"}, "output":{"shape":"AdminListUserAuthEventsResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"UserPoolAddOnNotEnabledException"}, {"shape":"InternalErrorException"} ] }, "AdminRemoveUserFromGroup":{ "name":"AdminRemoveUserFromGroup", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminRemoveUserFromGroupRequest"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Removes the specified user from the specified group.

Requires developer credentials.

" }, "AdminResetUserPassword":{ "name":"AdminResetUserPassword", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminResetUserPasswordRequest"}, "output":{"shape":"AdminResetUserPasswordResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"NotAuthorizedException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"UserNotFoundException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidEmailRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"InternalErrorException"} ], "documentation":"

Resets the specified user's password in a user pool as an administrator. Works on any user.

When a developer calls this API, the current password is invalidated, so it must be changed. If a user tries to sign in after the API is called, the app will get a PasswordResetRequiredException exception back and should direct the user down the flow to reset the password, which is the same as the forgot password flow. In addition, if the user pool has phone verification selected and a verified phone number exists for the user, or if email verification is selected and a verified email exists for the user, calling this API will also result in sending a message to the end user with the code to change their password.

Requires developer credentials.

" }, "AdminRespondToAuthChallenge":{ "name":"AdminRespondToAuthChallenge", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminRespondToAuthChallengeRequest"}, "output":{"shape":"AdminRespondToAuthChallengeResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"CodeMismatchException"}, {"shape":"ExpiredCodeException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"InvalidPasswordException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"TooManyRequestsException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"InternalErrorException"}, {"shape":"MFAMethodNotFoundException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"AliasExistsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"SoftwareTokenMFANotFoundException"} ], "documentation":"

Responds to an authentication challenge, as an administrator.

Requires developer credentials.

" }, "AdminSetUserMFAPreference":{ "name":"AdminSetUserMFAPreference", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminSetUserMFAPreferenceRequest"}, "output":{"shape":"AdminSetUserMFAPreferenceResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ] }, "AdminSetUserSettings":{ "name":"AdminSetUserSettings", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminSetUserSettingsRequest"}, "output":{"shape":"AdminSetUserSettingsResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Sets all the user settings for a specified user name. Works on any user.

Requires developer credentials.

" }, "AdminUpdateAuthEventFeedback":{ "name":"AdminUpdateAuthEventFeedback", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminUpdateAuthEventFeedbackRequest"}, "output":{"shape":"AdminUpdateAuthEventFeedbackResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"UserPoolAddOnNotEnabledException"}, {"shape":"InternalErrorException"} ] }, "AdminUpdateDeviceStatus":{ "name":"AdminUpdateDeviceStatus", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminUpdateDeviceStatusRequest"}, "output":{"shape":"AdminUpdateDeviceStatusResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Updates the device status as an administrator.

Requires developer credentials.

" }, "AdminUpdateUserAttributes":{ "name":"AdminUpdateUserAttributes", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminUpdateUserAttributesRequest"}, "output":{"shape":"AdminUpdateUserAttributesResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"AliasExistsException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Updates the specified user's attributes, including developer attributes, as an administrator. Works on any user.

In addition to updating user attributes, this API can also be used to mark phone and email as verified.

Requires developer credentials.

" }, "AdminUserGlobalSignOut":{ "name":"AdminUserGlobalSignOut", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AdminUserGlobalSignOutRequest"}, "output":{"shape":"AdminUserGlobalSignOutResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Signs out users from all devices, as an administrator.

Requires developer credentials.

" }, "AssociateSoftwareToken":{ "name":"AssociateSoftwareToken", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AssociateSoftwareTokenRequest"}, "output":{"shape":"AssociateSoftwareTokenResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"InternalErrorException"}, {"shape":"SoftwareTokenMFANotFoundException"} ] }, "Authenticate":{ "name":"Authenticate", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"AuthenticateRequest"}, "output":{"shape":"AuthenticateResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"MFAMethodNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"InvalidEmailRoleAccessPolicyException"}, {"shape":"CodeDeliveryFailureException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"InternalErrorException"} ], "documentation":"

The second step in the authentication flow of Secure Remote Password protocol (SRP) for authenticating a user to get ID, access and refresh tokens. To learn more about the first step, see GetAuthenticationDetails.

", "authtype":"none" }, "ChangePassword":{ "name":"ChangePassword", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ChangePasswordRequest"}, "output":{"shape":"ChangePasswordResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"InvalidPasswordException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Changes the password for a specified user in a user pool.

", "authtype":"none" }, "ConfirmDevice":{ "name":"ConfirmDevice", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ConfirmDeviceRequest"}, "output":{"shape":"ConfirmDeviceResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"InvalidPasswordException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"UsernameExistsException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Confirms tracking of the device. This API call is the call that begins device tracking.

" }, "ConfirmForgotPassword":{ "name":"ConfirmForgotPassword", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ConfirmForgotPasswordRequest"}, "output":{"shape":"ConfirmForgotPasswordResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidParameterException"}, {"shape":"InvalidPasswordException"}, {"shape":"NotAuthorizedException"}, {"shape":"CodeMismatchException"}, {"shape":"ExpiredCodeException"}, {"shape":"TooManyFailedAttemptsException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Allows a user to enter a confirmation code to reset a forgotten password.

", "authtype":"none" }, "ConfirmSignUp":{ "name":"ConfirmSignUp", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ConfirmSignUpRequest"}, "output":{"shape":"ConfirmSignUpResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyFailedAttemptsException"}, {"shape":"CodeMismatchException"}, {"shape":"ExpiredCodeException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"AliasExistsException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Confirms registration of a user and handles the existing alias from a previous user.

", "authtype":"none" }, "CreateGroup":{ "name":"CreateGroup", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"CreateGroupRequest"}, "output":{"shape":"CreateGroupResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"GroupExistsException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Creates a new group in the specified user pool.

Requires developer credentials.

" }, "CreateIdentityProvider":{ "name":"CreateIdentityProvider", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"CreateIdentityProviderRequest"}, "output":{"shape":"CreateIdentityProviderResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"DuplicateProviderException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"InternalErrorException"} ] }, "CreateResourceServer":{ "name":"CreateResourceServer", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"CreateResourceServerRequest"}, "output":{"shape":"CreateResourceServerResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"InternalErrorException"} ] }, "CreateUserImportJob":{ "name":"CreateUserImportJob", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"CreateUserImportJobRequest"}, "output":{"shape":"CreateUserImportJobResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"PreconditionNotMetException"}, {"shape":"NotAuthorizedException"}, {"shape":"LimitExceededException"}, {"shape":"InternalErrorException"} ], "documentation":"

Creates the user import job.

" }, "CreateUserPool":{ "name":"CreateUserPool", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"CreateUserPoolRequest"}, "output":{"shape":"CreateUserPoolResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"InvalidEmailRoleAccessPolicyException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserPoolTaggingException"}, {"shape":"InternalErrorException"} ], "documentation":"

Creates a new Amazon Cognito user pool and sets the password policy for the pool.

" }, "CreateUserPoolClient":{ "name":"CreateUserPoolClient", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"CreateUserPoolClientRequest"}, "output":{"shape":"CreateUserPoolClientResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"NotAuthorizedException"}, {"shape":"ScopeDoesNotExistException"}, {"shape":"InvalidOAuthFlowException"}, {"shape":"InternalErrorException"} ], "documentation":"

Creates the user pool client.

" }, "CreateUserPoolDomain":{ "name":"CreateUserPoolDomain", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"CreateUserPoolDomainRequest"}, "output":{"shape":"CreateUserPoolDomainResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"ResourceNotFoundException"}, {"shape":"InternalErrorException"} ] }, "DeleteGroup":{ "name":"DeleteGroup", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DeleteGroupRequest"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Deletes a group. Currently only groups with no members can be deleted.

Requires developer credentials.

" }, "DeleteIdentityProvider":{ "name":"DeleteIdentityProvider", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DeleteIdentityProviderRequest"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"UnsupportedIdentityProviderException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "DeleteResourceServer":{ "name":"DeleteResourceServer", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DeleteResourceServerRequest"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "DeleteUser":{ "name":"DeleteUser", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DeleteUserRequest"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Allows a user to delete one's self.

", "authtype":"none" }, "DeleteUserAttributes":{ "name":"DeleteUserAttributes", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DeleteUserAttributesRequest"}, "output":{"shape":"DeleteUserAttributesResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Deletes the attributes for a user.

", "authtype":"none" }, "DeleteUserPool":{ "name":"DeleteUserPool", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DeleteUserPoolRequest"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserImportInProgressException"}, {"shape":"InternalErrorException"} ], "documentation":"

Deletes the specified Amazon Cognito user pool.

" }, "DeleteUserPoolClient":{ "name":"DeleteUserPoolClient", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DeleteUserPoolClientRequest"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Allows the developer to delete the user pool client.

" }, "DeleteUserPoolDomain":{ "name":"DeleteUserPoolDomain", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DeleteUserPoolDomainRequest"}, "output":{"shape":"DeleteUserPoolDomainResponse"}, "errors":[ {"shape":"NotAuthorizedException"}, {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"InternalErrorException"} ] }, "DescribeIdentityProvider":{ "name":"DescribeIdentityProvider", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DescribeIdentityProviderRequest"}, "output":{"shape":"DescribeIdentityProviderResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "DescribeResourceServer":{ "name":"DescribeResourceServer", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DescribeResourceServerRequest"}, "output":{"shape":"DescribeResourceServerResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "DescribeRiskConfiguration":{ "name":"DescribeRiskConfiguration", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DescribeRiskConfigurationRequest"}, "output":{"shape":"DescribeRiskConfigurationResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserPoolAddOnNotEnabledException"}, {"shape":"InternalErrorException"} ] }, "DescribeUserImportJob":{ "name":"DescribeUserImportJob", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DescribeUserImportJobRequest"}, "output":{"shape":"DescribeUserImportJobResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Describes the user import job.

" }, "DescribeUserPool":{ "name":"DescribeUserPool", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DescribeUserPoolRequest"}, "output":{"shape":"DescribeUserPoolResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserPoolTaggingException"}, {"shape":"InternalErrorException"} ], "documentation":"

Returns the configuration information and metadata of the specified user pool.

" }, "DescribeUserPoolClient":{ "name":"DescribeUserPoolClient", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DescribeUserPoolClientRequest"}, "output":{"shape":"DescribeUserPoolClientResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Client method for returning the configuration information and metadata of the specified user pool client.

" }, "DescribeUserPoolDomain":{ "name":"DescribeUserPoolDomain", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"DescribeUserPoolDomainRequest"}, "output":{"shape":"DescribeUserPoolDomainResponse"}, "errors":[ {"shape":"NotAuthorizedException"}, {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"InternalErrorException"} ] }, "EnhanceAuth":{ "name":"EnhanceAuth", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"EnhanceAuthRequest"}, "output":{"shape":"EnhanceAuthResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"CodeMismatchException"}, {"shape":"ExpiredCodeException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"TooManyRequestsException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"InternalErrorException"} ], "documentation":"

Grants the ability to supply a multi-factor authentication (MFA) token for an MFA-enabled user to get the ID, access, and refresh tokens.

", "authtype":"none" }, "ForgetDevice":{ "name":"ForgetDevice", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ForgetDeviceRequest"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Forgets the specified device.

" }, "ForgotPassword":{ "name":"ForgotPassword", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ForgotPasswordRequest"}, "output":{"shape":"ForgotPasswordResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"NotAuthorizedException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"InvalidEmailRoleAccessPolicyException"}, {"shape":"CodeDeliveryFailureException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Calling this API causes a message to be sent to the end user with a confirmation code that is required to change the user's password. For the Username parameter, you can use the username or user alias. If a verified phone number exists for the user, the confirmation code is sent to the phone number. Otherwise, if a verified email exists, the confirmation code is sent to the email. If neither a verified phone number nor a verified email exists, InvalidParameterException is thrown. To use the confirmation code for resetting the password, call ConfirmForgotPassword.

", "authtype":"none" }, "GetAuthenticationDetails":{ "name":"GetAuthenticationDetails", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetAuthenticationDetailsRequest"}, "output":{"shape":"GetAuthenticationDetailsResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

First step of the Secure Remote Password protocol (SRP) auth flow to authenticate a user. To learn about the second step, see Authenticate.

", "authtype":"none" }, "GetCSVHeader":{ "name":"GetCSVHeader", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetCSVHeaderRequest"}, "output":{"shape":"GetCSVHeaderResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Gets the header information for the .csv file to be used as input for the user import job.

" }, "GetDevice":{ "name":"GetDevice", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetDeviceRequest"}, "output":{"shape":"GetDeviceResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Gets the device.

" }, "GetGroup":{ "name":"GetGroup", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetGroupRequest"}, "output":{"shape":"GetGroupResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Gets a group.

Requires developer credentials.

" }, "GetIdentityProviderByIdentifier":{ "name":"GetIdentityProviderByIdentifier", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetIdentityProviderByIdentifierRequest"}, "output":{"shape":"GetIdentityProviderByIdentifierResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "GetJWKS":{ "name":"GetJWKS", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetJWKSRequest"}, "output":{"shape":"GetJWKSResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"InvalidParameterException"}, {"shape":"InternalErrorException"} ], "documentation":"

Gets the JSON Web keys for the specified user pool.

", "authtype":"none" }, "GetOpenIdConfiguration":{ "name":"GetOpenIdConfiguration", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetOpenIdConfigurationRequest"}, "output":{"shape":"GetOpenIdConfigurationResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"InvalidParameterException"}, {"shape":"InternalErrorException"} ], "documentation":"

Gets the OpenId configuration information for the specified user pool.

", "authtype":"none" }, "GetSigningCertificate":{ "name":"GetSigningCertificate", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetSigningCertificateRequest"}, "output":{"shape":"GetSigningCertificateResponse"}, "errors":[ {"shape":"InternalErrorException"}, {"shape":"ResourceNotFoundException"} ] }, "GetUICustomization":{ "name":"GetUICustomization", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetUICustomizationRequest"}, "output":{"shape":"GetUICustomizationResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "GetUser":{ "name":"GetUser", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetUserRequest"}, "output":{"shape":"GetUserResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Gets the user attributes and metadata for a user.

", "authtype":"none" }, "GetUserAttributeVerificationCode":{ "name":"GetUserAttributeVerificationCode", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetUserAttributeVerificationCodeRequest"}, "output":{"shape":"GetUserAttributeVerificationCodeResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"InvalidEmailRoleAccessPolicyException"}, {"shape":"CodeDeliveryFailureException"}, {"shape":"LimitExceededException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Gets the user attribute verification code for the specified attribute name.

", "authtype":"none" }, "GetUserPoolMfaConfig":{ "name":"GetUserPoolMfaConfig", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetUserPoolMfaConfigRequest"}, "output":{"shape":"GetUserPoolMfaConfigResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ] }, "GetUserPoolUIConfiguration":{ "name":"GetUserPoolUIConfiguration", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GetUserPoolUIConfigurationRequest"}, "output":{"shape":"GetUserPoolUIConfigurationResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "GlobalSignOut":{ "name":"GlobalSignOut", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"GlobalSignOutRequest"}, "output":{"shape":"GlobalSignOutResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Signs out users from all devices.

" }, "InitiateAuth":{ "name":"InitiateAuth", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"InitiateAuthRequest"}, "output":{"shape":"InitiateAuthResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Initiates the authentication flow.

" }, "ListDevices":{ "name":"ListDevices", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ListDevicesRequest"}, "output":{"shape":"ListDevicesResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Lists the devices.

" }, "ListGroups":{ "name":"ListGroups", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ListGroupsRequest"}, "output":{"shape":"ListGroupsResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Lists the groups associated with a user pool.

Requires developer credentials.

" }, "ListIdentityProviders":{ "name":"ListIdentityProviders", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ListIdentityProvidersRequest"}, "output":{"shape":"ListIdentityProvidersResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "ListResourceServers":{ "name":"ListResourceServers", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ListResourceServersRequest"}, "output":{"shape":"ListResourceServersResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "ListUserImportJobs":{ "name":"ListUserImportJobs", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ListUserImportJobsRequest"}, "output":{"shape":"ListUserImportJobsResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Lists the user import jobs.

" }, "ListUserPoolClients":{ "name":"ListUserPoolClients", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ListUserPoolClientsRequest"}, "output":{"shape":"ListUserPoolClientsResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Lists the clients that have been created for the specified user pool.

" }, "ListUserPools":{ "name":"ListUserPools", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ListUserPoolsRequest"}, "output":{"shape":"ListUserPoolsResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Lists the user pools associated with an AWS account.

" }, "ListUsers":{ "name":"ListUsers", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ListUsersRequest"}, "output":{"shape":"ListUsersResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Lists the users in the Amazon Cognito user pool.

" }, "ListUsersInGroup":{ "name":"ListUsersInGroup", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ListUsersInGroupRequest"}, "output":{"shape":"ListUsersInGroupResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Lists the users in the specified group.

Requires developer credentials.

" }, "RefreshTokens":{ "name":"RefreshTokens", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"RefreshTokensRequest"}, "output":{"shape":"RefreshTokensResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"InternalErrorException"} ], "documentation":"

Refreshes the tokens for the specified client ID.

", "authtype":"none" }, "ResendConfirmationCode":{ "name":"ResendConfirmationCode", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"ResendConfirmationCodeRequest"}, "output":{"shape":"ResendConfirmationCodeResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"NotAuthorizedException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"InvalidEmailRoleAccessPolicyException"}, {"shape":"CodeDeliveryFailureException"}, {"shape":"UserNotFoundException"}, {"shape":"InternalErrorException"} ], "documentation":"

Resends the confirmation (for confirmation of registration) to a specific user in the user pool.

", "authtype":"none" }, "RespondToAuthChallenge":{ "name":"RespondToAuthChallenge", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"RespondToAuthChallengeRequest"}, "output":{"shape":"RespondToAuthChallengeResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"CodeMismatchException"}, {"shape":"ExpiredCodeException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidPasswordException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"TooManyRequestsException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"MFAMethodNotFoundException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"AliasExistsException"}, {"shape":"InternalErrorException"}, {"shape":"SoftwareTokenMFANotFoundException"} ], "documentation":"

Responds to the authentication challenge.

" }, "SetRiskConfiguration":{ "name":"SetRiskConfiguration", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"SetRiskConfigurationRequest"}, "output":{"shape":"SetRiskConfigurationResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserPoolAddOnNotEnabledException"}, {"shape":"InternalErrorException"} ] }, "SetUICustomization":{ "name":"SetUICustomization", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"SetUICustomizationRequest"}, "output":{"shape":"SetUICustomizationResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "SetUserMFAPreference":{ "name":"SetUserMFAPreference", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"SetUserMFAPreferenceRequest"}, "output":{"shape":"SetUserMFAPreferenceResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ] }, "SetUserPoolMfaConfig":{ "name":"SetUserPoolMfaConfig", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"SetUserPoolMfaConfigRequest"}, "output":{"shape":"SetUserPoolMfaConfigResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"ResourceNotFoundException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ] }, "SetUserPoolUIConfiguration":{ "name":"SetUserPoolUIConfiguration", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"SetUserPoolUIConfigurationRequest"}, "output":{"shape":"SetUserPoolUIConfigurationResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "SetUserSettings":{ "name":"SetUserSettings", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"SetUserSettingsRequest"}, "output":{"shape":"SetUserSettingsResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"NotAuthorizedException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Sets the user settings like multi-factor authentication (MFA). If MFA is to be removed for a particular attribute pass the attribute with code delivery as null. If null list is passed, all MFA options are removed.

", "authtype":"none" }, "SignUp":{ "name":"SignUp", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"SignUpRequest"}, "output":{"shape":"SignUpResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"NotAuthorizedException"}, {"shape":"InvalidPasswordException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"UsernameExistsException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"InvalidEmailRoleAccessPolicyException"}, {"shape":"CodeDeliveryFailureException"} ], "documentation":"

Registers the user in the specified user pool and creates a user name, password, and user attributes.

", "authtype":"none" }, "StartUserImportJob":{ "name":"StartUserImportJob", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"StartUserImportJobRequest"}, "output":{"shape":"StartUserImportJobResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"}, {"shape":"PreconditionNotMetException"}, {"shape":"NotAuthorizedException"} ], "documentation":"

Starts the user import.

" }, "StopUserImportJob":{ "name":"StopUserImportJob", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"StopUserImportJobRequest"}, "output":{"shape":"StopUserImportJobResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"}, {"shape":"PreconditionNotMetException"}, {"shape":"NotAuthorizedException"} ], "documentation":"

Stops the user import job.

" }, "UpdateAuthEventFeedback":{ "name":"UpdateAuthEventFeedback", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"UpdateAuthEventFeedbackRequest"}, "output":{"shape":"UpdateAuthEventFeedbackResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserNotFoundException"}, {"shape":"UserPoolAddOnNotEnabledException"}, {"shape":"InternalErrorException"} ] }, "UpdateDeviceStatus":{ "name":"UpdateDeviceStatus", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"UpdateDeviceStatusRequest"}, "output":{"shape":"UpdateDeviceStatusResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Updates the device status.

" }, "UpdateGroup":{ "name":"UpdateGroup", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"UpdateGroupRequest"}, "output":{"shape":"UpdateGroupResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Updates the specified group with the specified attributes.

Requires developer credentials.

" }, "UpdateIdentityProvider":{ "name":"UpdateIdentityProvider", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"UpdateIdentityProviderRequest"}, "output":{"shape":"UpdateIdentityProviderResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"UnsupportedIdentityProviderException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "UpdateResourceServer":{ "name":"UpdateResourceServer", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"UpdateResourceServerRequest"}, "output":{"shape":"UpdateResourceServerResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"InternalErrorException"} ] }, "UpdateUserAttributes":{ "name":"UpdateUserAttributes", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"UpdateUserAttributesRequest"}, "output":{"shape":"UpdateUserAttributesResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"CodeMismatchException"}, {"shape":"ExpiredCodeException"}, {"shape":"NotAuthorizedException"}, {"shape":"UnexpectedLambdaException"}, {"shape":"UserLambdaValidationException"}, {"shape":"InvalidLambdaResponseException"}, {"shape":"TooManyRequestsException"}, {"shape":"AliasExistsException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"InvalidEmailRoleAccessPolicyException"}, {"shape":"CodeDeliveryFailureException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Allows a user to update a specific attribute (one at a time).

", "authtype":"none" }, "UpdateUserPool":{ "name":"UpdateUserPool", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"UpdateUserPoolRequest"}, "output":{"shape":"UpdateUserPoolResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"ConcurrentModificationException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"UserImportInProgressException"}, {"shape":"InternalErrorException"}, {"shape":"InvalidSmsRoleAccessPolicyException"}, {"shape":"InvalidSmsRoleTrustRelationshipException"}, {"shape":"UserPoolTaggingException"}, {"shape":"InvalidEmailRoleAccessPolicyException"} ], "documentation":"

Updates the specified user pool with the specified attributes.

" }, "UpdateUserPoolClient":{ "name":"UpdateUserPoolClient", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"UpdateUserPoolClientRequest"}, "output":{"shape":"UpdateUserPoolClientResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"TooManyRequestsException"}, {"shape":"NotAuthorizedException"}, {"shape":"ScopeDoesNotExistException"}, {"shape":"InvalidOAuthFlowException"}, {"shape":"InternalErrorException"} ], "documentation":"

Allows the developer to update the specified user pool client and password policy.

" }, "VerifySoftwareToken":{ "name":"VerifySoftwareToken", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"VerifySoftwareTokenRequest"}, "output":{"shape":"VerifySoftwareTokenResponse"}, "errors":[ {"shape":"InvalidParameterException"}, {"shape":"ResourceNotFoundException"}, {"shape":"InvalidUserPoolConfigurationException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"}, {"shape":"EnableSoftwareTokenMFAException"}, {"shape":"SoftwareTokenMFANotFoundException"}, {"shape":"CodeMismatchException"} ] }, "VerifyUserAttribute":{ "name":"VerifyUserAttribute", "http":{ "method":"POST", "requestUri":"/" }, "input":{"shape":"VerifyUserAttributeRequest"}, "output":{"shape":"VerifyUserAttributeResponse"}, "errors":[ {"shape":"ResourceNotFoundException"}, {"shape":"InvalidParameterException"}, {"shape":"CodeMismatchException"}, {"shape":"ExpiredCodeException"}, {"shape":"NotAuthorizedException"}, {"shape":"TooManyRequestsException"}, {"shape":"LimitExceededException"}, {"shape":"PasswordResetRequiredException"}, {"shape":"UserNotFoundException"}, {"shape":"UserNotConfirmedException"}, {"shape":"InternalErrorException"} ], "documentation":"

Verifies the specified user attributes in the user pool.

", "authtype":"none" } }, "shapes":{ "AValueHexStringType":{ "type":"string", "max":1024, "min":1, "pattern":"^[0-9a-fA-F]+$" }, "AWSAccountIdType":{"type":"string"}, "AccountTakeoverActionNotifyType":{"type":"boolean"}, "AccountTakeoverActionType":{ "type":"structure", "required":[ "Notify", "EventAction" ], "members":{ "Notify":{"shape":"AccountTakeoverActionNotifyType"}, "EventAction":{"shape":"AccountTakeoverEventActionType"} } }, "AccountTakeoverActionsType":{ "type":"structure", "members":{ "LowAction":{"shape":"AccountTakeoverActionType"}, "MediumAction":{"shape":"AccountTakeoverActionType"}, "HighAction":{"shape":"AccountTakeoverActionType"} } }, "AccountTakeoverEventActionType":{ "type":"string", "enum":[ "BLOCK", "MFA_IF_CONFIGURED", "MFA_REQUIRED", "NO_ACTION" ] }, "AccountTakeoverRiskConfigurationType":{ "type":"structure", "required":["Actions"], "members":{ "NotifyConfiguration":{"shape":"NotifyConfigurationType"}, "Actions":{"shape":"AccountTakeoverActionsType"} } }, "AddCustomAttributesRequest":{ "type":"structure", "required":[ "UserPoolId", "CustomAttributes" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to add custom attributes.

" }, "CustomAttributes":{ "shape":"CustomAttributesListType", "documentation":"

An array of custom attributes, such as Mutable and Name.

" } }, "documentation":"

Represents the request to add custom attributes.

" }, "AddCustomAttributesResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response from the server for the request to add custom attributes.

" }, "AdminAddUserToGroupRequest":{ "type":"structure", "required":[ "UserPoolId", "Username", "GroupName" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The username for the user.

" }, "GroupName":{ "shape":"GroupNameType", "documentation":"

The group name.

" } } }, "AdminConfirmSignUpRequest":{ "type":"structure", "required":[ "UserPoolId", "Username" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for which you want to confirm user registration.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name for which you want to confirm user registration.

" } }, "documentation":"

Represents the request to confirm user registration.

" }, "AdminConfirmSignUpResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response from the server for the request to confirm registration.

" }, "AdminCreateUserConfigType":{ "type":"structure", "members":{ "AllowAdminCreateUserOnly":{ "shape":"BooleanType", "documentation":"

Set to True if only the administrator is allowed to create user profiles. Set to False if users can sign themselves up via an app.

" }, "UnusedAccountValidityDays":{ "shape":"AdminCreateUserUnusedAccountValidityDaysType", "documentation":"

The user account expiration limit, in days, after which the account is no longer usable. To reset the account after that time limit, you must call AdminCreateUser again, specifying \"RESEND\" for the MessageAction parameter. The default value for this parameter is 7.

" }, "InviteMessageTemplate":{ "shape":"MessageTemplateType", "documentation":"

The message template to be used for the welcome message to new users.

" } }, "documentation":"

The type of configuration for creating a new user profile.

" }, "AdminCreateUserRequest":{ "type":"structure", "required":[ "UserPoolId", "Username" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where the user will be created.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The username for the user. Must be unique within the user pool. Must be a UTF-8 string between 1 and 128 characters. After the user is created, the username cannot be changed.

" }, "UserAttributes":{ "shape":"AttributeListType", "documentation":"

An array of name-value pairs that contain user attributes and attribute values to be set for the user to be created. You can create a user without specifying any attributes other than Username. However, any attributes that you specify as required (in CreateUserPool or in the Attributes tab of the console) must be supplied either by you (in your call to AdminCreateUser) or by the user (when he or she signs up in response to your welcome message).

To send a message inviting the user to sign up, you must specify the user's email address or phone number. This can be done in your call to AdminCreateUser or in the Users tab of the Amazon Cognito console for managing your user pools.

In your call to AdminCreateUser, you can set the email_verified attribute to True, and you can set the phone_number_verified attribute to True. (You also do this by calling AdminUpdateUserAttributes.)

  • email: The email address of the user to whom the message that contains the code and username will be sent. Required if the email_verified attribute is set to True, or if \"EMAIL\" is specified in the DesiredDeliveryMediums parameter.

  • phone_number: The phone number of the user to whom the message that contains the code and username will be sent. Required if the phone_number_verified attribute is set to True, or if \"SMS\" is specified in the DesiredDeliveryMediums parameter.

" }, "ValidationData":{ "shape":"AttributeListType", "documentation":"

The user's validation data. This is an array of name-value pairs that contain user attributes and attribute values that you can use for custom validation, such as restricting the types of user accounts that can be registered. For example, you might choose to allow or disallow user sign-up based on the user's domain.

To configure custom validation, you must create a Pre Sign-up Lambda trigger for the user pool as described in the Amazon Cognito Developer Guide. The Lambda trigger receives the validation data and uses it in the validation process.

The user's validation data is not persisted.

" }, "TemporaryPassword":{ "shape":"PasswordType", "documentation":"

The user's temporary password. This password must conform to the password policy that you specified when you created the user pool.

The temporary password is valid only once. To complete the Admin Create User flow, the user must enter the temporary password in the sign-in page along with a new password to be used in all future sign-ins.

This parameter is not required. If you do not specify a value, Amazon Cognito generates one for you.

The temporary password can only be used until the user account expiration limit that you specified when you created the user pool. To reset the account after that time limit, you must call AdminCreateUser again, specifying \"RESEND\" for the MessageAction parameter.

" }, "ForceAliasCreation":{ "shape":"ForceAliasCreation", "documentation":"

This parameter is only used if the phone_number_verified or email_verified attribute is set to True. Otherwise, it is ignored.

If this parameter is set to True and the phone number or email address specified in the UserAttributes parameter already exists as an alias with a different user, the API call will migrate the alias from the previous user to the newly created user. The previous user will no longer be able to log in using that alias.

If this parameter is set to False, the API throws an AliasExistsException error if the alias already exists. The default value is False.

" }, "MessageAction":{ "shape":"MessageActionType", "documentation":"

Set to \"RESEND\" to resend the invitation message to a user that already exists and reset the expiration limit on the user's account. Set to \"SUPPRESS\" to suppress sending the message. Only one value can be specified.

" }, "DesiredDeliveryMediums":{ "shape":"DeliveryMediumListType", "documentation":"

Specify \"EMAIL\" if email will be used to send the welcome message. Specify \"SMS\" if the phone number will be used. The default value is \"SMS\". More than one value can be specified.

" } }, "documentation":"

Represents the request to create a user in the specified user pool.

" }, "AdminCreateUserResponse":{ "type":"structure", "members":{ "User":{ "shape":"UserType", "documentation":"

The user returned in the request to create a new user.

" } }, "documentation":"

Represents the response from the server to the request to create the user.

" }, "AdminCreateUserUnusedAccountValidityDaysType":{ "type":"integer", "max":365, "min":0 }, "AdminDeleteUserAttributesRequest":{ "type":"structure", "required":[ "UserPoolId", "Username", "UserAttributeNames" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to delete user attributes.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user from which you would like to delete attributes.

" }, "UserAttributeNames":{ "shape":"AttributeNameListType", "documentation":"

An array of strings representing the user attribute names you wish to delete.

" } }, "documentation":"

Represents the request to delete user attributes as an administrator.

" }, "AdminDeleteUserAttributesResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response received from the server for a request to delete user attributes.

" }, "AdminDeleteUserRequest":{ "type":"structure", "required":[ "UserPoolId", "Username" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to delete the user.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user you wish to delete.

" } }, "documentation":"

Represents the request to delete a user as an administrator.

" }, "AdminDisableProviderForUserRequest":{ "type":"structure", "required":[ "UserPoolId", "User" ], "members":{ "UserPoolId":{"shape":"StringType"}, "User":{"shape":"ProviderUserIdentifierType"} } }, "AdminDisableProviderForUserResponse":{ "type":"structure", "members":{ } }, "AdminDisableUserRequest":{ "type":"structure", "required":[ "UserPoolId", "Username" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to disable the user.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user you wish to disable.

" } }, "documentation":"

Represents the request to disable any user as an administrator.

" }, "AdminDisableUserResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response received from the server to disable the user as an administrator.

" }, "AdminEnableUserRequest":{ "type":"structure", "required":[ "UserPoolId", "Username" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to enable the user.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user you wish to enable.

" } }, "documentation":"

Represents the request that enables the user as an administrator.

" }, "AdminEnableUserResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response from the server for the request to enable a user as an administrator.

" }, "AdminForgetDeviceRequest":{ "type":"structure", "required":[ "UserPoolId", "Username", "DeviceKey" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name.

" }, "DeviceKey":{ "shape":"DeviceKeyType", "documentation":"

The device key.

" } }, "documentation":"

Sends the forgot device request, as an administrator.

" }, "AdminGetDeviceRequest":{ "type":"structure", "required":[ "DeviceKey", "UserPoolId", "Username" ], "members":{ "DeviceKey":{ "shape":"DeviceKeyType", "documentation":"

The device key.

" }, "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name.

" } }, "documentation":"

Represents the request to get the device, as an administrator.

" }, "AdminGetDeviceResponse":{ "type":"structure", "required":["Device"], "members":{ "Device":{ "shape":"DeviceType", "documentation":"

The device.

" } }, "documentation":"

Gets the device response, as an administrator.

" }, "AdminGetUserRequest":{ "type":"structure", "required":[ "UserPoolId", "Username" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to get information about the user.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user you wish to retrieve.

" } }, "documentation":"

Represents the request to get the specified user as an administrator.

" }, "AdminGetUserResponse":{ "type":"structure", "required":["Username"], "members":{ "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user about whom you are receiving information.

" }, "UserAttributes":{ "shape":"AttributeListType", "documentation":"

An array of name-value pairs representing user attributes.

" }, "UserCreateDate":{ "shape":"DateType", "documentation":"

The date the user was created.

" }, "UserLastModifiedDate":{ "shape":"DateType", "documentation":"

The date the user was last modified.

" }, "Enabled":{ "shape":"BooleanType", "documentation":"

Indicates that the status is enabled.

" }, "UserStatus":{ "shape":"UserStatusType", "documentation":"

The user status. Can be one of the following:

  • UNCONFIRMED - User has been created but not confirmed.

  • CONFIRMED - User has been confirmed.

  • ARCHIVED - User is no longer active.

  • COMPROMISED - User is disabled due to a potential security threat.

  • UNKNOWN - User status is not known.

" }, "MFAOptions":{ "shape":"MFAOptionListType", "documentation":"

Specifies the options for MFA (e.g., email or phone number).

" } }, "documentation":"

Represents the response from the server from the request to get the specified user as an administrator.

" }, "AdminInitiateAuthRequest":{ "type":"structure", "required":[ "UserPoolId", "ClientId", "AuthFlow" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The ID of the Amazon Cognito user pool.

" }, "ClientId":{ "shape":"ClientIdType", "documentation":"

The app client ID.

" }, "AuthFlow":{ "shape":"AuthFlowType", "documentation":"

The authentication flow for this call to execute. The API action will depend on this value. For example:

  • REFRESH_TOKEN_AUTH will take in a valid refresh token and return new tokens.

  • USER_SRP_AUTH will take in USERNAME and SRPA and return the SRP variables to be used for next challenge execution.

Valid values include:

  • USER_SRP_AUTH: Authentication flow for the Secure Remote Password (SRP) protocol.

  • REFRESH_TOKEN_AUTH/REFRESH_TOKEN: Authentication flow for refreshing the access token and ID token by supplying a valid refresh token.

  • CUSTOM_AUTH: Custom authentication flow.

  • ADMIN_NO_SRP_AUTH: Non-SRP authentication flow; you can pass in the USERNAME and PASSWORD directly if the flow is enabled for calling the app client.

" }, "AuthParameters":{ "shape":"AuthParametersType", "documentation":"

The authentication parameters. These are inputs corresponding to the AuthFlow that you are invoking. The required values depend on the value of AuthFlow:

  • For USER_SRP_AUTH: USERNAME (required), SRPA (required), SECRET_HASH (required if the app client is configured with a client secret), DEVICE_KEY

  • For REFRESH_TOKEN_AUTH/REFRESH_TOKEN: USERNAME (required), SECRET_HASH (required if the app client is configured with a client secret), REFRESH_TOKEN (required), DEVICE_KEY

  • For ADMIN_NO_SRP_AUTH: USERNAME (required), SECRET_HASH (if app client is configured with client secret), PASSWORD (required), DEVICE_KEY

  • For CUSTOM_AUTH: USERNAME (required), SECRET_HASH (if app client is configured with client secret), DEVICE_KEY

" }, "ClientMetadata":{ "shape":"ClientMetadataType", "documentation":"

This is a random key-value pair map which can contain any key and will be passed to your PreAuthentication Lambda trigger as-is. It can be used to implement additional validations around authentication.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"}, "ContextData":{"shape":"ContextDataType"} }, "documentation":"

Initiates the authorization request, as an administrator.

" }, "AdminInitiateAuthResponse":{ "type":"structure", "members":{ "ChallengeName":{ "shape":"ChallengeNameType", "documentation":"

The name of the challenge which you are responding to with this call. This is returned to you in the AdminInitiateAuth response if you need to pass another challenge.

  • SMS_MFA: Next challenge is to supply an SMS_MFA_CODE, delivered via SMS.

  • PASSWORD_VERIFIER: Next challenge is to supply PASSWORD_CLAIM_SIGNATURE, PASSWORD_CLAIM_SECRET_BLOCK, and TIMESTAMP after the client-side SRP calculations.

  • CUSTOM_CHALLENGE: This is returned if your custom authentication flow determines that the user should pass another challenge before tokens are issued.

  • DEVICE_SRP_AUTH: If device tracking was enabled on your user pool and the previous challenges were passed, this challenge is returned so that Amazon Cognito can start tracking this device.

  • DEVICE_PASSWORD_VERIFIER: Similar to PASSWORD_VERIFIER, but for devices only.

  • ADMIN_NO_SRP_AUTH: This is returned if you need to authenticate with USERNAME and PASSWORD directly. An app client must be enabled to use this flow.

  • NEW_PASSWORD_REQUIRED: For users which are required to change their passwords after successful first login. This challenge should be passed with NEW_PASSWORD and any other required attributes.

" }, "Session":{ "shape":"SessionType", "documentation":"

The session which should be passed both ways in challenge-response calls to the service. If AdminInitiateAuth or AdminRespondToAuthChallenge API call determines that the caller needs to go through another challenge, they return a session with other challenge parameters. This session should be passed as it is to the next AdminRespondToAuthChallenge API call.

" }, "ChallengeParameters":{ "shape":"ChallengeParametersType", "documentation":"

The challenge parameters. These are returned to you in the AdminInitiateAuth response if you need to pass another challenge. The responses in this parameter should be used to compute inputs to the next call (AdminRespondToAuthChallenge).

All challenges require USERNAME and SECRET_HASH (if applicable).

The value of the USER_IF_FOR_SRP attribute will be the user's actual username, not an alias (such as email address or phone number), even if you specified an alias in your call to AdminInitiateAuth. This is because, in the AdminRespondToAuthChallenge API ChallengeResponses, the USERNAME attribute cannot be an alias.

" }, "AuthenticationResult":{ "shape":"AuthenticationResultType", "documentation":"

The result of the authentication response. This is only returned if the caller does not need to pass another challenge. If the caller does need to pass another challenge before it gets tokens, ChallengeName, ChallengeParameters, and Session are returned.

" } }, "documentation":"

Initiates the authentication response, as an administrator.

" }, "AdminLinkProviderForUserRequest":{ "type":"structure", "required":[ "UserPoolId", "DestinationUser", "SourceUser" ], "members":{ "UserPoolId":{"shape":"StringType"}, "DestinationUser":{"shape":"ProviderUserIdentifierType"}, "SourceUser":{"shape":"ProviderUserIdentifierType"} } }, "AdminLinkProviderForUserResponse":{ "type":"structure", "members":{ } }, "AdminListDevicesRequest":{ "type":"structure", "required":[ "UserPoolId", "Username" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name.

" }, "Limit":{ "shape":"QueryLimitType", "documentation":"

The limit of the devices request.

" }, "PaginationToken":{ "shape":"SearchPaginationTokenType", "documentation":"

The pagination token.

" } }, "documentation":"

Represents the request to list devices, as an administrator.

" }, "AdminListDevicesResponse":{ "type":"structure", "members":{ "Devices":{ "shape":"DeviceListType", "documentation":"

The devices in the list of devices response.

" }, "PaginationToken":{ "shape":"SearchPaginationTokenType", "documentation":"

The pagination token.

" } }, "documentation":"

Lists the device's response, as an administrator.

" }, "AdminListGroupsForUserRequest":{ "type":"structure", "required":[ "Username", "UserPoolId" ], "members":{ "Username":{ "shape":"UsernameType", "documentation":"

The username for the user.

" }, "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool.

" }, "Limit":{ "shape":"QueryLimitType", "documentation":"

The limit of the request to list groups.

" }, "NextToken":{ "shape":"PaginationKey", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" } } }, "AdminListGroupsForUserResponse":{ "type":"structure", "members":{ "Groups":{ "shape":"GroupListType", "documentation":"

The groups that the user belongs to.

" }, "NextToken":{ "shape":"PaginationKey", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" } } }, "AdminListUserAuthEventsRequest":{ "type":"structure", "required":[ "UserPoolId", "Username" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "Username":{"shape":"UsernameType"}, "MaxResults":{"shape":"QueryLimitType"}, "NextToken":{"shape":"PaginationKey"} } }, "AdminListUserAuthEventsResponse":{ "type":"structure", "members":{ "AuthEvents":{"shape":"AuthEventsType"}, "NextToken":{"shape":"PaginationKey"} } }, "AdminRemoveUserFromGroupRequest":{ "type":"structure", "required":[ "UserPoolId", "Username", "GroupName" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The username for the user.

" }, "GroupName":{ "shape":"GroupNameType", "documentation":"

The group name.

" } } }, "AdminResetUserPasswordRequest":{ "type":"structure", "required":[ "UserPoolId", "Username" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to reset the user's password.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user whose password you wish to reset.

" } }, "documentation":"

Represents the request to reset a user's password as an administrator.

" }, "AdminResetUserPasswordResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response from the server to reset a user password as an administrator.

" }, "AdminRespondToAuthChallengeRequest":{ "type":"structure", "required":[ "UserPoolId", "ClientId", "ChallengeName" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The ID of the Amazon Cognito user pool.

" }, "ClientId":{ "shape":"ClientIdType", "documentation":"

The app client ID.

" }, "ChallengeName":{ "shape":"ChallengeNameType", "documentation":"

The challenge name. For more information, see AdminInitiateAuth.

" }, "ChallengeResponses":{ "shape":"ChallengeResponsesType", "documentation":"

The challenge responses. These are inputs corresponding to the value of ChallengeName, for example:

  • SMS_MFA: SMS_MFA_CODE, USERNAME, SECRET_HASH (if app client is configured with client secret).

  • PASSWORD_VERIFIER: PASSWORD_CLAIM_SIGNATURE, PASSWORD_CLAIM_SECRET_BLOCK, TIMESTAMP, USERNAME, SECRET_HASH (if app client is configured with client secret).

  • ADMIN_NO_SRP_AUTH: PASSWORD, USERNAME, SECRET_HASH (if app client is configured with client secret).

  • NEW_PASSWORD_REQUIRED: NEW_PASSWORD, any other required attributes, USERNAME, SECRET_HASH (if app client is configured with client secret).

The value of the USERNAME attribute must be the user's actual username, not an alias (such as email address or phone number). To make this easier, the AdminInitiateAuth response includes the actual username value in the USERNAMEUSER_ID_FOR_SRP attribute, even if you specified an alias in your call to AdminInitiateAuth.

" }, "Session":{ "shape":"SessionType", "documentation":"

The session which should be passed both ways in challenge-response calls to the service. If InitiateAuth or RespondToAuthChallenge API call determines that the caller needs to go through another challenge, they return a session with other challenge parameters. This session should be passed as it is to the next RespondToAuthChallenge API call.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"}, "ContextData":{"shape":"ContextDataType"} }, "documentation":"

The request to respond to the authentication challenge, as an administrator.

" }, "AdminRespondToAuthChallengeResponse":{ "type":"structure", "members":{ "ChallengeName":{ "shape":"ChallengeNameType", "documentation":"

The name of the challenge. For more information, see AdminInitiateAuth.

" }, "Session":{ "shape":"SessionType", "documentation":"

The session which should be passed both ways in challenge-response calls to the service. If InitiateAuth or RespondToAuthChallenge API call determines that the caller needs to go through another challenge, they return a session with other challenge parameters. This session should be passed as it is to the next RespondToAuthChallenge API call.

" }, "ChallengeParameters":{ "shape":"ChallengeParametersType", "documentation":"

The challenge parameters. For more information, see AdminInitiateAuth.

" }, "AuthenticationResult":{ "shape":"AuthenticationResultType", "documentation":"

The result returned by the server in response to the authentication request.

" } }, "documentation":"

Responds to the authentication challenge, as an administrator.

" }, "AdminSetUserMFAPreferenceRequest":{ "type":"structure", "required":[ "Username", "UserPoolId" ], "members":{ "SMSMfaSettings":{"shape":"SMSMfaSettingsType"}, "SoftwareTokenMfaSettings":{"shape":"SoftwareTokenMfaSettingsType"}, "Username":{"shape":"UsernameType"}, "UserPoolId":{"shape":"UserPoolIdType"} } }, "AdminSetUserMFAPreferenceResponse":{ "type":"structure", "members":{ } }, "AdminSetUserSettingsRequest":{ "type":"structure", "required":[ "UserPoolId", "Username", "MFAOptions" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to set the user's settings, such as MFA options.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user for whom you wish to set user settings.

" }, "MFAOptions":{ "shape":"MFAOptionListType", "documentation":"

Specifies the options for MFA (e.g., email or phone number).

" } }, "documentation":"

Represents the request to set user settings as an administrator.

" }, "AdminSetUserSettingsResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response from the server to set user settings as an administrator.

" }, "AdminUpdateAuthEventFeedbackRequest":{ "type":"structure", "required":[ "UserPoolId", "Username", "EventId", "FeedbackValue" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "Username":{"shape":"UsernameType"}, "EventId":{"shape":"EventIdType"}, "FeedbackValue":{"shape":"FeedbackValueType"} } }, "AdminUpdateAuthEventFeedbackResponse":{ "type":"structure", "members":{ } }, "AdminUpdateDeviceStatusRequest":{ "type":"structure", "required":[ "UserPoolId", "Username", "DeviceKey" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID>

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name.

" }, "DeviceKey":{ "shape":"DeviceKeyType", "documentation":"

The device key.

" }, "DeviceRememberedStatus":{ "shape":"DeviceRememberedStatusType", "documentation":"

The status indicating whether a device has been remembered or not.

" } }, "documentation":"

The request to update the device status, as an administrator.

" }, "AdminUpdateDeviceStatusResponse":{ "type":"structure", "members":{ }, "documentation":"

The status response from the request to update the device, as an administrator.

" }, "AdminUpdateUserAttributesRequest":{ "type":"structure", "required":[ "UserPoolId", "Username", "UserAttributes" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to update user attributes.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user for whom you want to update user attributes.

" }, "UserAttributes":{ "shape":"AttributeListType", "documentation":"

An array of name-value pairs representing user attributes.

" } }, "documentation":"

Represents the request to update the user's attributes as an administrator.

" }, "AdminUpdateUserAttributesResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response from the server for the request to update user attributes as an administrator.

" }, "AdminUserGlobalSignOutRequest":{ "type":"structure", "required":[ "UserPoolId", "Username" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name.

" } }, "documentation":"

The request to sign out of all devices, as an administrator.

" }, "AdminUserGlobalSignOutResponse":{ "type":"structure", "members":{ }, "documentation":"

The global sign-out response, as an administrator.

" }, "AdvancedSecurityModeType":{ "type":"string", "enum":[ "OFF", "AUDIT", "ENFORCED" ] }, "AliasAttributeType":{ "type":"string", "enum":[ "phone_number", "email", "preferred_username" ] }, "AliasAttributesListType":{ "type":"list", "member":{"shape":"AliasAttributeType"} }, "AliasExistsException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message sent to the user when an alias exists.

" } }, "documentation":"

This exception is thrown when a user tries to confirm the account with an email or phone number that has already been supplied as an alias from a different account. This exception tells user that an account with this email or phone already exists.

", "exception":true }, "AnalyticsConfigurationType":{ "type":"structure", "required":[ "ApplicationId", "RoleArn", "ExternalId" ], "members":{ "ApplicationId":{"shape":"HexStringType"}, "RoleArn":{"shape":"ArnType"}, "ExternalId":{"shape":"StringType"}, "UserDataShared":{"shape":"BooleanType"} } }, "AnalyticsMetadataType":{ "type":"structure", "members":{ "AnalyticsEndpointId":{"shape":"StringType"} } }, "ArnType":{ "type":"string", "max":2048, "min":20, "pattern":"arn:[\\w+=/,.@-]+:[\\w+=/,.@-]+:([\\w+=/,.@-]*)?:[0-9]+:[\\w+=/,.@-]+(:[\\w+=/,.@-]+)?(:[\\w+=/,.@-]+)?" }, "AssociateSoftwareTokenRequest":{ "type":"structure", "members":{ "AccessToken":{"shape":"TokenModelType"}, "Session":{"shape":"SessionType"} } }, "AssociateSoftwareTokenResponse":{ "type":"structure", "members":{ "SecretCode":{"shape":"SecretCodeType"}, "Session":{"shape":"SessionType"} } }, "AttributeDataType":{ "type":"string", "enum":[ "String", "Number", "DateTime", "Boolean" ] }, "AttributeListType":{ "type":"list", "member":{"shape":"AttributeType"} }, "AttributeMappingKeyType":{ "type":"string", "max":32, "min":1 }, "AttributeMappingType":{ "type":"map", "key":{"shape":"AttributeMappingKeyType"}, "value":{"shape":"StringType"} }, "AttributeNameListType":{ "type":"list", "member":{"shape":"AttributeNameType"} }, "AttributeNameType":{ "type":"string", "max":32, "min":1, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+" }, "AttributeType":{ "type":"structure", "required":["Name"], "members":{ "Name":{ "shape":"AttributeNameType", "documentation":"

The name of the attribute.

" }, "Value":{ "shape":"AttributeValueType", "documentation":"

The value of the attribute.

" } }, "documentation":"

Specifies whether the attribute is standard or custom.

" }, "AttributeValueType":{ "type":"string", "max":2048, "sensitive":true }, "AuthEventType":{ "type":"structure", "members":{ "EventId":{"shape":"StringType"}, "EventType":{"shape":"EventType"}, "CreationDate":{"shape":"DateType"}, "EventResponse":{"shape":"EventResponseType"}, "EventRisk":{"shape":"EventRiskType"}, "ChallengeResponses":{"shape":"ChallengeResponseListType"}, "EventContextData":{"shape":"EventContextDataType"}, "EventFeedback":{"shape":"EventFeedbackType"} } }, "AuthEventsType":{ "type":"list", "member":{"shape":"AuthEventType"} }, "AuthFlowType":{ "type":"string", "enum":[ "USER_SRP_AUTH", "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN", "CUSTOM_AUTH", "ADMIN_NO_SRP_AUTH" ] }, "AuthParametersType":{ "type":"map", "key":{"shape":"StringType"}, "value":{"shape":"StringType"} }, "AuthStateType":{ "type":"string", "pattern":"[A-Za-z0-9-_+/=]+", "sensitive":true }, "AuthenticateRequest":{ "type":"structure", "required":[ "ClientId", "Username", "PasswordClaim" ], "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "SecretHash":{ "shape":"SecretHashType", "documentation":"

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user you wish to authenticate.

" }, "PasswordClaim":{ "shape":"PasswordClaimType", "documentation":"

The password claim of the authentication request.

" }, "Timestamp":{ "shape":"DateType", "documentation":"

The timestamp of the authentication request.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"} }, "documentation":"

Represents the request to authenticate.

" }, "AuthenticateResponse":{ "type":"structure", "members":{ "AuthenticationResult":{ "shape":"AuthenticationResultType", "documentation":"

The result of the authentication response.

" }, "AuthState":{ "shape":"AuthStateType", "documentation":"

The authorization state of the authentication response.

" }, "CodeDeliveryDetails":{ "shape":"CodeDeliveryDetailsType", "documentation":"

The code delivery details returned by the server in the response to the authentication request.

" } }, "documentation":"

Represents the authentication response.

" }, "AuthenticationResultType":{ "type":"structure", "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token of the authentication result.

" }, "ExpiresIn":{ "shape":"IntegerType", "documentation":"

The expiration period of the authentication result.

" }, "TokenType":{ "shape":"StringType", "documentation":"

The token type of the authentication result.

" }, "RefreshToken":{ "shape":"TokenModelType", "documentation":"

The refresh token of the authentication result.

" }, "IdToken":{ "shape":"TokenModelType", "documentation":"

The ID token of the authentication result.

" }, "NewDeviceMetadata":{ "shape":"NewDeviceMetadataType", "documentation":"

The new device metadata from an authentication result.

" } }, "documentation":"

The result type of the authentication result.

" }, "BlobType":{"type":"blob"}, "BlockedIPRangeListType":{ "type":"list", "member":{"shape":"StringType"}, "max":20 }, "BooleanType":{"type":"boolean"}, "BotActionType":{ "type":"structure", "required":["EventAction"], "members":{ "EventAction":{"shape":"BotEventActionType"} } }, "BotActionsType":{ "type":"structure", "members":{ "LowAction":{"shape":"BotActionType"}, "MediumAction":{"shape":"BotActionType"}, "HighAction":{"shape":"BotActionType"} } }, "BotEventActionType":{ "type":"string", "enum":[ "BLOCK", "NO_ACTION" ] }, "BotRiskConfigurationType":{ "type":"structure", "required":["Actions"], "members":{ "EventFilter":{"shape":"EventFiltersType"}, "Actions":{"shape":"BotActionsType"} } }, "CSSType":{"type":"string"}, "CSSVersionType":{"type":"string"}, "CallbackURLsListType":{ "type":"list", "member":{"shape":"RedirectUrlType"}, "max":100, "min":0 }, "ChallengeName":{ "type":"string", "enum":[ "Password", "Mfa" ] }, "ChallengeNameType":{ "type":"string", "enum":[ "SMS_MFA", "SOFTWARE_TOKEN_MFA", "SELECT_MFA_TYPE", "MFA_SETUP", "PASSWORD_VERIFIER", "CUSTOM_CHALLENGE", "DEVICE_SRP_AUTH", "DEVICE_PASSWORD_VERIFIER", "ADMIN_NO_SRP_AUTH", "NEW_PASSWORD_REQUIRED" ] }, "ChallengeParametersType":{ "type":"map", "key":{"shape":"StringType"}, "value":{"shape":"StringType"} }, "ChallengeResponse":{ "type":"string", "enum":[ "Success", "Failure" ] }, "ChallengeResponseListType":{ "type":"list", "member":{"shape":"ChallengeResponseType"} }, "ChallengeResponseType":{ "type":"structure", "members":{ "ChallengeName":{"shape":"ChallengeName"}, "ChallengeResponse":{"shape":"ChallengeResponse"} } }, "ChallengeResponsesType":{ "type":"map", "key":{"shape":"StringType"}, "value":{"shape":"StringType"} }, "ChangePasswordRequest":{ "type":"structure", "required":[ "PreviousPassword", "ProposedPassword", "AccessToken" ], "members":{ "PreviousPassword":{ "shape":"PasswordType", "documentation":"

The old password in the change password request.

" }, "ProposedPassword":{ "shape":"PasswordType", "documentation":"

The new password in the change password request.

" }, "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token in the change password request.

" } }, "documentation":"

Represents the request to change a user password.

" }, "ChangePasswordResponse":{ "type":"structure", "members":{ }, "documentation":"

The response from the server to the change password request.

" }, "ClientIdType":{ "type":"string", "max":128, "min":1, "pattern":"[\\w+]+", "sensitive":true }, "ClientMetadataType":{ "type":"map", "key":{"shape":"StringType"}, "value":{"shape":"StringType"} }, "ClientNameType":{ "type":"string", "max":128, "min":1, "pattern":"[\\w\\s+=,.@-]+" }, "ClientPermissionListType":{ "type":"list", "member":{"shape":"ClientPermissionType"} }, "ClientPermissionType":{ "type":"string", "max":2048, "min":1 }, "ClientSecretType":{ "type":"string", "max":64, "min":1, "pattern":"[\\w+]+", "sensitive":true }, "CodeDeliveryDetailsListType":{ "type":"list", "member":{"shape":"CodeDeliveryDetailsType"} }, "CodeDeliveryDetailsType":{ "type":"structure", "members":{ "Destination":{ "shape":"StringType", "documentation":"

The destination for the code delivery details.

" }, "DeliveryMedium":{ "shape":"DeliveryMediumType", "documentation":"

The delivery medium (email message or phone number).

" }, "AttributeName":{ "shape":"AttributeNameType", "documentation":"

The name of the attribute in the code delivery details type.

" } }, "documentation":"

The type of code delivery details being returned from the server.

" }, "CodeDeliveryFailureException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message sent when a verification code fails to deliver successfully.

" } }, "documentation":"

This exception is thrown when a verification code fails to deliver successfully.

", "exception":true }, "CodeMismatchException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message provided when the code mismatch exception is thrown.

" } }, "documentation":"

This exception is thrown if the provided code does not match what the server was expecting.

", "exception":true }, "CompletionMessageType":{ "type":"string", "max":128, "min":1, "pattern":"[\\w]+" }, "CompromisedCredentialsActionsType":{ "type":"structure", "required":["EventAction"], "members":{ "EventAction":{"shape":"CompromisedCredentialsEventActionType"} } }, "CompromisedCredentialsEventActionType":{ "type":"string", "enum":[ "BLOCK", "NO_ACTION" ] }, "CompromisedCredentialsRiskConfigurationType":{ "type":"structure", "required":["Actions"], "members":{ "EventFilter":{"shape":"EventFiltersType"}, "Actions":{"shape":"CompromisedCredentialsActionsType"} } }, "ConcurrentModificationException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message provided when the concurrent exception is thrown.

" } }, "documentation":"

This exception is thrown if two or more modifications are happening concurrently.

", "exception":true }, "ConfirmDeviceRequest":{ "type":"structure", "required":[ "AccessToken", "DeviceKey" ], "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token.

" }, "DeviceKey":{ "shape":"DeviceKeyType", "documentation":"

The device key.

" }, "DeviceSecretVerifierConfig":{ "shape":"DeviceSecretVerifierConfigType", "documentation":"

The configuration of the device secret verifier.

" }, "DeviceName":{ "shape":"DeviceNameType", "documentation":"

The device name.

" } }, "documentation":"

Confirms the device request.

" }, "ConfirmDeviceResponse":{ "type":"structure", "members":{ "UserConfirmationNecessary":{ "shape":"BooleanType", "documentation":"

Indicates whether the user confirmation is necessary to confirm the device response.

" } }, "documentation":"

Confirms the device response.

" }, "ConfirmForgotPasswordRequest":{ "type":"structure", "required":[ "ClientId", "Username", "ConfirmationCode", "Password" ], "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "SecretHash":{ "shape":"SecretHashType", "documentation":"

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user for whom you want to enter a code to retrieve a forgotten password.

" }, "ConfirmationCode":{ "shape":"ConfirmationCodeType", "documentation":"

The confirmation code sent by a user's request to retrieve a forgotten password. For more information, see ForgotPassword

" }, "Password":{ "shape":"PasswordType", "documentation":"

The password sent by a user's request to retrieve a forgotten password.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"}, "UserContextData":{"shape":"UserContextDataType"} }, "documentation":"

The request representing the confirmation for a password reset.

" }, "ConfirmForgotPasswordResponse":{ "type":"structure", "members":{ }, "documentation":"

The response from the server that results from a user's request to retrieve a forgotten password.

" }, "ConfirmSignUpRequest":{ "type":"structure", "required":[ "ClientId", "Username", "ConfirmationCode" ], "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "SecretHash":{ "shape":"SecretHashType", "documentation":"

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user whose registration you wish to confirm.

" }, "ConfirmationCode":{ "shape":"ConfirmationCodeType", "documentation":"

The confirmation code sent by a user's request to confirm registration.

" }, "ForceAliasCreation":{ "shape":"ForceAliasCreation", "documentation":"

Boolean to be specified to force user confirmation irrespective of existing alias. By default set to False. If this parameter is set to True and the phone number/email used for sign up confirmation already exists as an alias with a different user, the API call will migrate the alias from the previous user to the newly created user being confirmed. If set to False, the API will throw an AliasExistsException error.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"}, "UserContextData":{"shape":"UserContextDataType"} }, "documentation":"

Represents the request to confirm registration of a user.

" }, "ConfirmSignUpResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response from the server for the registration confirmation.

" }, "ConfirmationCodeType":{ "type":"string", "max":2048, "min":1, "pattern":"[\\S]+" }, "ContextDataType":{ "type":"structure", "required":[ "IpAddress", "ServerName", "ServerPath", "HttpHeaders", "EncodedData" ], "members":{ "IpAddress":{"shape":"StringType"}, "ServerName":{"shape":"StringType"}, "ServerPath":{"shape":"StringType"}, "HttpHeaders":{"shape":"HttpHeaderList"}, "EncodedData":{"shape":"StringType"} } }, "CreateGroupRequest":{ "type":"structure", "required":[ "GroupName", "UserPoolId" ], "members":{ "GroupName":{ "shape":"GroupNameType", "documentation":"

The name of the group. Must be unique.

" }, "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool.

" }, "Description":{ "shape":"DescriptionType", "documentation":"

A string containing the description of the group.

" }, "RoleArn":{ "shape":"ArnType", "documentation":"

The role ARN for the group.

" }, "Precedence":{ "shape":"PrecedenceType", "documentation":"

A nonnegative integer value that specifies the precedence of this group relative to the other groups that a user can belong to in the user pool. Zero is the highest precedence value. Groups with lower Precedence values take precedence over groups with higher or null Precedence values. If a user belongs to two or more groups, it is the group with the lowest precedence value whose role ARN will be used in the cognito:roles and cognito:preferred_role claims in the user's tokens.

Two groups can have the same Precedence value. If this happens, neither group takes precedence over the other. If two groups with the same Precedence have the same role ARN, that role is used in the cognito:preferred_role claim in tokens for users in each group. If the two groups have different role ARNs, the cognito:preferred_role claim is not set in users' tokens.

The default Precedence value is null.

" } } }, "CreateGroupResponse":{ "type":"structure", "members":{ "Group":{ "shape":"GroupType", "documentation":"

The group object for the group.

" } } }, "CreateIdentityProviderRequest":{ "type":"structure", "required":[ "UserPoolId", "ProviderName", "ProviderType", "ProviderDetails" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ProviderName":{"shape":"ProviderNameTypeV1"}, "ProviderType":{"shape":"IdentityProviderTypeType"}, "ProviderDetails":{"shape":"ProviderDetailsType"}, "AttributeMapping":{"shape":"AttributeMappingType"}, "IdpIdentifiers":{"shape":"IdpIdentifiersListType"} } }, "CreateIdentityProviderResponse":{ "type":"structure", "required":["IdentityProvider"], "members":{ "IdentityProvider":{"shape":"IdentityProviderType"} } }, "CreateResourceServerRequest":{ "type":"structure", "required":[ "UserPoolId", "Identifier", "Name" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "Identifier":{"shape":"ResourceServerIdentifierType"}, "Name":{"shape":"ResourceServerNameType"}, "Scopes":{"shape":"ResourceServerScopeListType"} } }, "CreateResourceServerResponse":{ "type":"structure", "required":["ResourceServer"], "members":{ "ResourceServer":{"shape":"ResourceServerType"} } }, "CreateUserImportJobRequest":{ "type":"structure", "required":[ "JobName", "UserPoolId", "CloudWatchLogsRoleArn" ], "members":{ "JobName":{ "shape":"UserImportJobNameType", "documentation":"

The job name for the user import job.

" }, "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool that the users are being imported into.

" }, "CloudWatchLogsRoleArn":{ "shape":"ArnType", "documentation":"

The role ARN for the Amazon CloudWatch Logging role for the user import job.

" } }, "documentation":"

Represents the request to create the user import job.

" }, "CreateUserImportJobResponse":{ "type":"structure", "members":{ "UserImportJob":{ "shape":"UserImportJobType", "documentation":"

The job object that represents the user import job.

" } }, "documentation":"

Represents the response from the server to the request to create the user import job.

" }, "CreateUserPoolClientRequest":{ "type":"structure", "required":[ "UserPoolId", "ClientName" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to create a user pool client.

" }, "ClientName":{ "shape":"ClientNameType", "documentation":"

The client name for the user pool client you would like to create.

" }, "GenerateSecret":{ "shape":"GenerateSecret", "documentation":"

Boolean to specify whether you want to generate a secret for the user pool client being created.

" }, "RefreshTokenValidity":{ "shape":"RefreshTokenValidityType", "documentation":"

The time limit, in days, after which the refresh token is no longer valid and cannot be used.

" }, "ReadAttributes":{ "shape":"ClientPermissionListType", "documentation":"

The read attributes.

" }, "WriteAttributes":{ "shape":"ClientPermissionListType", "documentation":"

The write attributes.

" }, "ExplicitAuthFlows":{ "shape":"ExplicitAuthFlowsListType", "documentation":"

The explicit authentication flows.

" }, "SupportedIdentityProviders":{"shape":"SupportedIdentityProvidersListType"}, "CallbackURLs":{"shape":"CallbackURLsListType"}, "LogoutURLs":{"shape":"LogoutURLsListType"}, "DefaultRedirectURI":{"shape":"RedirectUrlType"}, "AllowedOAuthFlows":{"shape":"OAuthFlowsType"}, "AllowedOAuthScopes":{"shape":"ScopeListType"}, "AllowedOAuthFlowsUserPoolClient":{"shape":"BooleanType"}, "AnalyticsConfiguration":{"shape":"AnalyticsConfigurationType"} }, "documentation":"

Represents the request to create a user pool client.

" }, "CreateUserPoolClientResponse":{ "type":"structure", "members":{ "UserPoolClient":{ "shape":"UserPoolClientType", "documentation":"

The user pool client that was just created.

" } }, "documentation":"

Represents the response from the server to create a user pool client.

" }, "CreateUserPoolDomainRequest":{ "type":"structure", "required":[ "Domain", "UserPoolId" ], "members":{ "Domain":{"shape":"DomainType"}, "UserPoolId":{"shape":"UserPoolIdType"} } }, "CreateUserPoolDomainResponse":{ "type":"structure", "members":{ } }, "CreateUserPoolRequest":{ "type":"structure", "required":["PoolName"], "members":{ "PoolName":{ "shape":"UserPoolNameType", "documentation":"

A string used to name the user pool.

" }, "Policies":{ "shape":"UserPoolPolicyType", "documentation":"

The policies associated with the new user pool.

" }, "LambdaConfig":{ "shape":"LambdaConfigType", "documentation":"

The Lambda trigger configuration information for the new user pool.

" }, "AutoVerifiedAttributes":{ "shape":"VerifiedAttributesListType", "documentation":"

The attributes to be auto-verified. Possible values: email, phone_number.

" }, "AliasAttributes":{ "shape":"AliasAttributesListType", "documentation":"

Attributes supported as an alias for this user pool. Possible values: phone_number, email, or preferred_username.

" }, "UsernameAttributes":{"shape":"UsernameAttributesListType"}, "SmsVerificationMessage":{ "shape":"SmsVerificationMessageType", "documentation":"

A string representing the SMS verification message.

" }, "EmailVerificationMessage":{ "shape":"EmailVerificationMessageType", "documentation":"

A string representing the email verification message.

" }, "EmailVerificationSubject":{ "shape":"EmailVerificationSubjectType", "documentation":"

A string representing the email verification subject.

" }, "VerificationMessageTemplate":{"shape":"VerificationMessageTemplateType"}, "SmsAuthenticationMessage":{ "shape":"SmsVerificationMessageType", "documentation":"

A string representing the SMS authentication message.

" }, "MfaConfiguration":{ "shape":"UserPoolMfaType", "documentation":"

Specifies MFA configuration details.

" }, "DeviceConfiguration":{ "shape":"DeviceConfigurationType", "documentation":"

The device configuration.

" }, "EmailConfiguration":{ "shape":"EmailConfigurationType", "documentation":"

The email configuration.

" }, "SmsConfiguration":{ "shape":"SmsConfigurationType", "documentation":"

The SMS configuration.

" }, "UserPoolTags":{ "shape":"UserPoolTagsType", "documentation":"

The cost allocation tags for the user pool. For more information, see Adding Cost Allocation Tags to Your User Pool

" }, "AdminCreateUserConfig":{ "shape":"AdminCreateUserConfigType", "documentation":"

The configuration for AdminCreateUser requests.

" }, "Schema":{ "shape":"SchemaAttributesListType", "documentation":"

An array of schema attributes for the new user pool. These attributes can be standard or custom attributes.

" }, "UserPoolAddOns":{"shape":"UserPoolAddOnsType"} }, "documentation":"

Represents the request to create a user pool.

" }, "CreateUserPoolResponse":{ "type":"structure", "members":{ "UserPool":{ "shape":"UserPoolType", "documentation":"

A container for the user pool details.

" } }, "documentation":"

Represents the response from the server for the request to create a user pool.

" }, "CustomAttributeNameType":{ "type":"string", "max":20, "min":1, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+" }, "CustomAttributesListType":{ "type":"list", "member":{"shape":"SchemaAttributeType"}, "max":25, "min":1 }, "DateType":{"type":"timestamp"}, "DefaultEmailOptionType":{ "type":"string", "enum":[ "CONFIRM_WITH_LINK", "CONFIRM_WITH_CODE" ] }, "DeleteGroupRequest":{ "type":"structure", "required":[ "GroupName", "UserPoolId" ], "members":{ "GroupName":{ "shape":"GroupNameType", "documentation":"

The name of the group.

" }, "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool.

" } } }, "DeleteIdentityProviderRequest":{ "type":"structure", "required":[ "UserPoolId", "ProviderName" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ProviderName":{"shape":"ProviderNameType"} } }, "DeleteResourceServerRequest":{ "type":"structure", "required":[ "UserPoolId", "Identifier" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "Identifier":{"shape":"ResourceServerIdentifierType"} } }, "DeleteUserAttributesRequest":{ "type":"structure", "required":[ "UserAttributeNames", "AccessToken" ], "members":{ "UserAttributeNames":{ "shape":"AttributeNameListType", "documentation":"

An array of strings representing the user attribute names you wish to delete.

" }, "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token used in the request to delete user attributes.

" } }, "documentation":"

Represents the request to delete user attributes.

" }, "DeleteUserAttributesResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response from the server to delete user attributes.

" }, "DeleteUserPoolClientRequest":{ "type":"structure", "required":[ "UserPoolId", "ClientId" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to delete the client.

" }, "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" } }, "documentation":"

Represents the request to delete a user pool client.

" }, "DeleteUserPoolDomainRequest":{ "type":"structure", "required":[ "Domain", "UserPoolId" ], "members":{ "Domain":{"shape":"DomainType"}, "UserPoolId":{"shape":"UserPoolIdType"} } }, "DeleteUserPoolDomainResponse":{ "type":"structure", "members":{ } }, "DeleteUserPoolRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool you want to delete.

" } }, "documentation":"

Represents the request to delete a user pool.

" }, "DeleteUserRequest":{ "type":"structure", "required":["AccessToken"], "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token from a request to delete a user.

" } }, "documentation":"

Represents the request to delete a user.

" }, "DeliveryMediumListType":{ "type":"list", "member":{"shape":"DeliveryMediumType"} }, "DeliveryMediumType":{ "type":"string", "enum":[ "SMS", "EMAIL" ] }, "DescribeIdentityProviderRequest":{ "type":"structure", "required":[ "UserPoolId", "ProviderName" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ProviderName":{"shape":"ProviderNameType"} } }, "DescribeIdentityProviderResponse":{ "type":"structure", "required":["IdentityProvider"], "members":{ "IdentityProvider":{"shape":"IdentityProviderType"} } }, "DescribeResourceServerRequest":{ "type":"structure", "required":[ "UserPoolId", "Identifier" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "Identifier":{"shape":"ResourceServerIdentifierType"} } }, "DescribeResourceServerResponse":{ "type":"structure", "required":["ResourceServer"], "members":{ "ResourceServer":{"shape":"ResourceServerType"} } }, "DescribeRiskConfigurationRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ClientId":{"shape":"ClientIdType"} } }, "DescribeRiskConfigurationResponse":{ "type":"structure", "required":["RiskConfiguration"], "members":{ "RiskConfiguration":{"shape":"RiskConfigurationType"} } }, "DescribeUserImportJobRequest":{ "type":"structure", "required":[ "UserPoolId", "JobId" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool that the users are being imported into.

" }, "JobId":{ "shape":"UserImportJobIdType", "documentation":"

The job ID for the user import job.

" } }, "documentation":"

Represents the request to describe the user import job.

" }, "DescribeUserImportJobResponse":{ "type":"structure", "members":{ "UserImportJob":{ "shape":"UserImportJobType", "documentation":"

The job object that represents the user import job.

" } }, "documentation":"

Represents the response from the server to the request to describe the user import job.

" }, "DescribeUserPoolClientRequest":{ "type":"structure", "required":[ "UserPoolId", "ClientId" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool you want to describe.

" }, "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" } }, "documentation":"

Represents the request to describe a user pool client.

" }, "DescribeUserPoolClientResponse":{ "type":"structure", "members":{ "UserPoolClient":{ "shape":"UserPoolClientType", "documentation":"

The user pool client from a server response to describe the user pool client.

" } }, "documentation":"

Represents the response from the server from a request to describe the user pool client.

" }, "DescribeUserPoolDomainRequest":{ "type":"structure", "required":["Domain"], "members":{ "Domain":{"shape":"DomainType"} } }, "DescribeUserPoolDomainResponse":{ "type":"structure", "members":{ "DomainDescription":{"shape":"DomainDescriptionType"} } }, "DescribeUserPoolRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool you want to describe.

" } }, "documentation":"

Represents the request to describe the user pool.

" }, "DescribeUserPoolResponse":{ "type":"structure", "members":{ "UserPool":{ "shape":"UserPoolType", "documentation":"

The container of metadata returned by the server to describe the pool.

" } }, "documentation":"

Represents the response to describe the user pool.

" }, "DescriptionType":{ "type":"string", "max":2048 }, "DeviceConfigurationType":{ "type":"structure", "members":{ "ChallengeRequiredOnNewDevice":{ "shape":"BooleanType", "documentation":"

Indicates whether a challenge is required on a new device. Only applicable to a new device.

" }, "DeviceOnlyRememberedOnUserPrompt":{ "shape":"BooleanType", "documentation":"

If true, a device is only remembered on user prompt.

" } }, "documentation":"

The type of configuration for the user pool's device tracking.

" }, "DeviceKeyType":{ "type":"string", "max":55, "min":1, "pattern":"[\\w-]+_[0-9a-f-]+" }, "DeviceListType":{ "type":"list", "member":{"shape":"DeviceType"} }, "DeviceNameType":{ "type":"string", "max":1024, "min":1 }, "DeviceRememberedStatusType":{ "type":"string", "enum":[ "remembered", "not_remembered" ] }, "DeviceSecretVerifierConfigType":{ "type":"structure", "members":{ "PasswordVerifier":{ "shape":"StringType", "documentation":"

The password verifier.

" }, "Salt":{ "shape":"StringType", "documentation":"

The salt.

" } }, "documentation":"

The device verifier against which it will be authenticated.

" }, "DeviceType":{ "type":"structure", "members":{ "DeviceKey":{ "shape":"DeviceKeyType", "documentation":"

The device key.

" }, "DeviceAttributes":{ "shape":"AttributeListType", "documentation":"

The device attributes.

" }, "DeviceCreateDate":{ "shape":"DateType", "documentation":"

The creation date of the device.

" }, "DeviceLastModifiedDate":{ "shape":"DateType", "documentation":"

The last modified date of the device.

" }, "DeviceLastAuthenticatedDate":{ "shape":"DateType", "documentation":"

The date in which the device was last authenticated.

" } }, "documentation":"

The device type.

" }, "DomainDescriptionType":{ "type":"structure", "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "AWSAccountId":{"shape":"AWSAccountIdType"}, "Domain":{"shape":"DomainType"}, "S3Bucket":{"shape":"S3BucketType"}, "CloudFrontDistribution":{"shape":"ArnType"}, "Version":{"shape":"DomainVersionType"}, "Status":{"shape":"DomainStatusType"} } }, "DomainStatusType":{ "type":"string", "enum":[ "CREATING", "DELETING", "UPDATING", "ACTIVE", "FAILED" ] }, "DomainType":{ "type":"string", "max":63, "min":1, "pattern":"^[a-z0-9](?:[a-z0-9\\-]{0,61}[a-z0-9])?$" }, "DomainVersionType":{ "type":"string", "max":20, "min":1 }, "DuplicateProviderException":{ "type":"structure", "members":{ "message":{"shape":"MessageType"} }, "exception":true }, "EmailAddressType":{ "type":"string", "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+@[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+" }, "EmailConfigurationType":{ "type":"structure", "members":{ "SourceArn":{ "shape":"ArnType", "documentation":"

The Amazon Resource Name (ARN) of the email source.

" }, "ReplyToEmailAddress":{ "shape":"EmailAddressType", "documentation":"

The REPLY-TO email address.

" } }, "documentation":"

The email configuration type.

" }, "EmailNotificationBodyType":{ "type":"string", "max":20000, "min":6, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]+" }, "EmailNotificationSubjectType":{ "type":"string", "max":140, "min":1, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s]+" }, "EmailVerificationMessageByLinkType":{ "type":"string", "max":20000, "min":6, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*\\{##[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*##\\}[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*" }, "EmailVerificationMessageType":{ "type":"string", "max":20000, "min":6, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*\\{####\\}[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*" }, "EmailVerificationSubjectByLinkType":{ "type":"string", "max":140, "min":1, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s]+" }, "EmailVerificationSubjectType":{ "type":"string", "max":140, "min":1, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s]+" }, "EnableSoftwareTokenMFAException":{ "type":"structure", "members":{ "message":{"shape":"MessageType"} }, "exception":true }, "EnhanceAuthRequest":{ "type":"structure", "required":[ "ClientId", "Username", "AuthState", "Code" ], "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "SecretHash":{ "shape":"SecretHashType", "documentation":"

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user for whom you wish to enhance authentication.

" }, "AuthState":{ "shape":"AuthStateType", "documentation":"

The authentication state.

" }, "Code":{ "shape":"StringType", "documentation":"

The code returned from the enhanced authentication request.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"} }, "documentation":"

Represents the request by the developer to enhance the authentication on a user pool.

" }, "EnhanceAuthResponse":{ "type":"structure", "members":{ "AuthenticationResult":{ "shape":"AuthenticationResultType", "documentation":"

The authentication result from the enhanced authentication response.

" } }, "documentation":"

Represents the response from the enhanced authentication request.

" }, "EventContextDataType":{ "type":"structure", "members":{ "IpAddress":{"shape":"StringType"}, "DeviceName":{"shape":"StringType"}, "Timezone":{"shape":"StringType"}, "City":{"shape":"StringType"}, "Country":{"shape":"StringType"} } }, "EventFeedbackType":{ "type":"structure", "required":[ "FeedbackValue", "Provider" ], "members":{ "FeedbackValue":{"shape":"FeedbackValueType"}, "Provider":{"shape":"StringType"}, "FeedbackDate":{"shape":"DateType"} } }, "EventFilterType":{ "type":"string", "enum":[ "SIGN_IN", "FORGOT_PASSWORD", "ALL" ] }, "EventFiltersType":{ "type":"list", "member":{"shape":"EventFilterType"} }, "EventIdType":{ "type":"string", "max":50, "min":1, "pattern":"[\\w+-]+" }, "EventResponseType":{ "type":"string", "enum":[ "Success", "Failure" ] }, "EventRiskType":{ "type":"structure", "members":{ "RiskDecision":{"shape":"RiskDecisionType"}, "RiskLevel":{"shape":"RiskLevelType"} } }, "EventType":{ "type":"string", "enum":[ "SignIn", "SignUp", "ForgotPassword" ] }, "ExpiredCodeException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the expired code exception is thrown.

" } }, "documentation":"

This exception is thrown if a code has expired.

", "exception":true }, "ExplicitAuthFlowsListType":{ "type":"list", "member":{"shape":"ExplicitAuthFlowsType"} }, "ExplicitAuthFlowsType":{ "type":"string", "enum":[ "ADMIN_NO_SRP_AUTH", "CUSTOM_AUTH_FLOW_ONLY" ] }, "FeedbackValueType":{ "type":"string", "enum":[ "Bad", "Good" ] }, "ForceAliasCreation":{"type":"boolean"}, "ForgetDeviceRequest":{ "type":"structure", "required":["DeviceKey"], "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token for the forgotten device request.

" }, "DeviceKey":{ "shape":"DeviceKeyType", "documentation":"

The device key.

" } }, "documentation":"

Represents the request to forget the device.

" }, "ForgotPasswordRequest":{ "type":"structure", "required":[ "ClientId", "Username" ], "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "SecretHash":{ "shape":"SecretHashType", "documentation":"

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

" }, "UserContextData":{"shape":"UserContextDataType"}, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user for whom you want to enter a code to reset a forgotten password.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"} }, "documentation":"

Represents the request to reset a user's password.

" }, "ForgotPasswordResponse":{ "type":"structure", "members":{ "CodeDeliveryDetails":{ "shape":"CodeDeliveryDetailsType", "documentation":"

The code delivery details returned by the server in response to the request to reset a password.

" } }, "documentation":"

Respresents the response from the server regarding the request to reset a password.

" }, "GenerateSecret":{"type":"boolean"}, "GetAuthenticationDetailsRequest":{ "type":"structure", "required":[ "ClientId", "Username", "SrpA" ], "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "SecretHash":{ "shape":"SecretHashType", "documentation":"

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user for whom you wish to retrieve authentication details.

" }, "SrpA":{ "shape":"AValueHexStringType", "documentation":"

The Secure Remote Password protocol (SRP) key. For more information, see Secure Remote Password Protocol.

" }, "ValidationData":{ "shape":"AttributeListType", "documentation":"

The validation data of the request to get authentication details.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"} }, "documentation":"

Represents the user's request to get authentication details.

" }, "GetAuthenticationDetailsResponse":{ "type":"structure", "required":[ "Salt", "SrpB", "SecretBlock" ], "members":{ "Salt":{ "shape":"HexStringType", "documentation":"

A salt that gets returned by the response from the server to get authentication details. For more information, see Salt cryptography.

" }, "SrpB":{ "shape":"HexStringType", "documentation":"

The Secure Remote Password protocol (SRP) key. For more information, see Secure Remote Password Protocol.

" }, "SecretBlock":{ "shape":"BlobType", "documentation":"

A blob that blocks the secret hash in the get authentication details response.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The resolved username for a possible alias in the input username parameter.

" } }, "documentation":"

Represents the response from the server to get authentication details.

" }, "GetCSVHeaderRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool that the users are to be imported into.

" } }, "documentation":"

Represents the request to get the header information for the .csv file for the user import job.

" }, "GetCSVHeaderResponse":{ "type":"structure", "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool that the users are to be imported into.

" }, "CSVHeader":{ "shape":"ListOfStringTypes", "documentation":"

The header information for the .csv file for the user import job.

" } }, "documentation":"

Represents the response from the server to the request to get the header information for the .csv file for the user import job.

" }, "GetDeviceRequest":{ "type":"structure", "required":["DeviceKey"], "members":{ "DeviceKey":{ "shape":"DeviceKeyType", "documentation":"

The device key.

" }, "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token.

" } }, "documentation":"

Represents the request to get the device.

" }, "GetDeviceResponse":{ "type":"structure", "required":["Device"], "members":{ "Device":{ "shape":"DeviceType", "documentation":"

The device.

" } }, "documentation":"

Gets the device response.

" }, "GetGroupRequest":{ "type":"structure", "required":[ "GroupName", "UserPoolId" ], "members":{ "GroupName":{ "shape":"GroupNameType", "documentation":"

The name of the group.

" }, "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool.

" } } }, "GetGroupResponse":{ "type":"structure", "members":{ "Group":{ "shape":"GroupType", "documentation":"

The group object for the group.

" } } }, "GetIdentityProviderByIdentifierRequest":{ "type":"structure", "required":[ "UserPoolId", "IdpIdentifier" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "IdpIdentifier":{"shape":"IdpIdentifierType"} } }, "GetIdentityProviderByIdentifierResponse":{ "type":"structure", "required":["IdentityProvider"], "members":{ "IdentityProvider":{"shape":"IdentityProviderType"} } }, "GetJWKSRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to get JSON Web keys.

" } }, "documentation":"

Represents the request to get JSON Web keys.

" }, "GetJWKSResponse":{ "type":"structure", "members":{ "keys":{ "shape":"KeyListType", "documentation":"

The keys in a get JSON Web keys response.

" }, "cacheControl":{ "shape":"StringType", "documentation":"

The value of the Cache-Control HTTP header field for the JSON Web keys response. For more information on cacheControl, see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.

" } }, "documentation":"

Represents the response from the server to get JSON Web keys.

" }, "GetOpenIdConfigurationRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to get Open ID configuration information.

" } }, "documentation":"

Represents the request to get the Open ID configuration.

" }, "GetOpenIdConfigurationResponse":{ "type":"structure", "members":{ "issuer":{ "shape":"openIdUrlType", "documentation":"

The issuer of the Open ID configuration response.

" }, "jwks_uri":{ "shape":"openIdUrlType", "documentation":"

The URI of the JSON Web keys in the server response to get Open ID configuration information.

" }, "authorization_endpoint":{ "shape":"openIdUrlType", "documentation":"

The authorization endpoint returned by the server response to get the Open ID configuration information.

" }, "subject_types_supported":{ "shape":"openIdListType", "documentation":"

The subject types supported returned by the server response to get the Open ID configuration information.

" }, "response_types_supported":{ "shape":"openIdListType", "documentation":"

The response types supported returned by the server response to get the Open ID configuration information.

" }, "id_token_signing_alg_values_supported":{ "shape":"openIdListType", "documentation":"

The token-signing algorithm values supported returned by the server response to get the Open ID configuration information.

" } }, "documentation":"

Represents the response from the server to get the Open ID configuration information.

" }, "GetSigningCertificateRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"} } }, "GetSigningCertificateResponse":{ "type":"structure", "members":{ "Certificate":{"shape":"StringType"} } }, "GetUICustomizationRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ClientId":{"shape":"ClientIdType"} } }, "GetUICustomizationResponse":{ "type":"structure", "required":["UICustomization"], "members":{ "UICustomization":{"shape":"UICustomizationType"} } }, "GetUserAttributeVerificationCodeRequest":{ "type":"structure", "required":[ "AccessToken", "AttributeName" ], "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token returned by the server response to get the user attribute verification code.

" }, "AttributeName":{ "shape":"AttributeNameType", "documentation":"

The attribute name returned by the server response to get the user attribute verification code.

" } }, "documentation":"

Represents the request to get user attribute verification.

" }, "GetUserAttributeVerificationCodeResponse":{ "type":"structure", "members":{ "CodeDeliveryDetails":{ "shape":"CodeDeliveryDetailsType", "documentation":"

The code delivery details returned by the server in response to the request to get the user attribute verification code.

" } }, "documentation":"

The verification code response returned by the server response to get the user attribute verification code.

" }, "GetUserPoolMfaConfigRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"} } }, "GetUserPoolMfaConfigResponse":{ "type":"structure", "members":{ "SmsMfaConfiguration":{"shape":"SmsMfaConfigType"}, "SoftwareTokenMfaConfiguration":{"shape":"SoftwareTokenMfaConfigType"}, "MfaConfiguration":{"shape":"UserPoolMfaType"} } }, "GetUserPoolUIConfigurationRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"} } }, "GetUserPoolUIConfigurationResponse":{ "type":"structure", "required":["UserPoolUIConfiguration"], "members":{ "UserPoolUIConfiguration":{"shape":"UserPoolUIConfigurationType"} } }, "GetUserRequest":{ "type":"structure", "required":["AccessToken"], "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token returned by the server response to get information about the user.

" } }, "documentation":"

Represents the request to get information about the user.

" }, "GetUserResponse":{ "type":"structure", "required":[ "Username", "UserAttributes" ], "members":{ "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user you wish to retrieve from the get user request.

" }, "UserAttributes":{ "shape":"AttributeListType", "documentation":"

An array of name-value pairs representing user attributes.

" }, "MFAOptions":{ "shape":"MFAOptionListType", "documentation":"

Specifies the options for MFA (e.g., email or phone number).

" } }, "documentation":"

Represents the response from the server from the request to get information about the user.

" }, "GlobalSignOutRequest":{ "type":"structure", "required":["AccessToken"], "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token.

" } }, "documentation":"

Represents the request to sign out all devices.

" }, "GlobalSignOutResponse":{ "type":"structure", "members":{ }, "documentation":"

The response to the request to sign out all devices.

" }, "GroupExistsException":{ "type":"structure", "members":{ "message":{"shape":"MessageType"} }, "documentation":"

This exception is thrown when Amazon Cognito encounters a group that already exists in the user pool.

", "exception":true }, "GroupListType":{ "type":"list", "member":{"shape":"GroupType"} }, "GroupNameType":{ "type":"string", "max":128, "min":1, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+" }, "GroupType":{ "type":"structure", "members":{ "GroupName":{ "shape":"GroupNameType", "documentation":"

The name of the group.

" }, "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool.

" }, "Description":{ "shape":"DescriptionType", "documentation":"

A string containing the description of the group.

" }, "RoleArn":{ "shape":"ArnType", "documentation":"

The role ARN for the group.

" }, "Precedence":{ "shape":"PrecedenceType", "documentation":"

A nonnegative integer value that specifies the precedence of this group relative to the other groups that a user can belong to in the user pool. If a user belongs to two or more groups, it is the group with the highest precedence whose role ARN will be used in the cognito:roles and cognito:preferred_role claims in the user's tokens. Groups with higher Precedence values take precedence over groups with lower Precedence values or with null Precedence values.

Two groups can have the same Precedence value. If this happens, neither group takes precedence over the other. If two groups with the same Precedence have the same role ARN, that role is used in the cognito:preferred_role claim in tokens for users in each group. If the two groups have different role ARNs, the cognito:preferred_role claim is not set in users' tokens.

The default Precedence value is null.

" }, "LastModifiedDate":{ "shape":"DateType", "documentation":"

The date the group was last modified.

" }, "CreationDate":{ "shape":"DateType", "documentation":"

The date the group was created.

" } }, "documentation":"

The group type.

" }, "HexStringType":{ "type":"string", "pattern":"^[0-9a-fA-F]+$" }, "HttpHeader":{ "type":"structure", "members":{ "headerName":{"shape":"StringType"}, "headerValue":{"shape":"StringType"} } }, "HttpHeaderList":{ "type":"list", "member":{"shape":"HttpHeader"} }, "IdentityProviderType":{ "type":"structure", "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ProviderName":{"shape":"ProviderNameType"}, "ProviderType":{"shape":"IdentityProviderTypeType"}, "ProviderDetails":{"shape":"ProviderDetailsType"}, "AttributeMapping":{"shape":"AttributeMappingType"}, "IdpIdentifiers":{"shape":"IdpIdentifiersListType"}, "LastModifiedDate":{"shape":"DateType"}, "CreationDate":{"shape":"DateType"} } }, "IdentityProviderTypeType":{ "type":"string", "enum":[ "SAML", "Facebook", "Google", "LoginWithAmazon", "ActiveDirectory" ] }, "IdpIdentifierType":{ "type":"string", "max":40, "min":1, "pattern":"[\\w\\s+=.@-]+" }, "IdpIdentifiersListType":{ "type":"list", "member":{"shape":"IdpIdentifierType"}, "max":50, "min":0 }, "ImageFileType":{"type":"blob"}, "ImageUrlType":{"type":"string"}, "InitiateAuthRequest":{ "type":"structure", "required":[ "AuthFlow", "ClientId" ], "members":{ "AuthFlow":{ "shape":"AuthFlowType", "documentation":"

The authentication flow for this call to execute. The API action will depend on this value. For example:

  • REFRESH_TOKEN_AUTH will take in a valid refresh token and return new tokens.

  • USER_SRP_AUTH will take in USERNAME and SRPA and return the SRP variables to be used for next challenge execution.

Valid values include:

  • USER_SRP_AUTH: Authentication flow for the Secure Remote Password (SRP) protocol.

  • REFRESH_TOKEN_AUTH/REFRESH_TOKEN: Authentication flow for refreshing the access token and ID token by supplying a valid refresh token.

  • CUSTOM_AUTH: Custom authentication flow.

ADMIN_NO_SRP_AUTH is not a valid value.

" }, "AuthParameters":{ "shape":"AuthParametersType", "documentation":"

The authentication parameters. These are inputs corresponding to the AuthFlow that you are invoking. The required values depend on the value of AuthFlow:

  • For USER_SRP_AUTH: USERNAME (required), SRPA (required), SECRET_HASH (required if the app client is configured with a client secret), DEVICE_KEY

  • For REFRESH_TOKEN_AUTH/REFRESH_TOKEN: USERNAME (required), SECRET_HASH (required if the app client is configured with a client secret), REFRESH_TOKEN (required), DEVICE_KEY

  • For CUSTOM_AUTH: USERNAME (required), SECRET_HASH (if app client is configured with client secret), DEVICE_KEY

" }, "ClientMetadata":{ "shape":"ClientMetadataType", "documentation":"

This is a random key-value pair map which can contain any key and will be passed to your PreAuthentication Lambda trigger as-is. It can be used to implement additional validations around authentication.

" }, "ClientId":{ "shape":"ClientIdType", "documentation":"

The app client ID.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"}, "UserContextData":{"shape":"UserContextDataType"} }, "documentation":"

Initiates the authentication request.

" }, "InitiateAuthResponse":{ "type":"structure", "members":{ "ChallengeName":{ "shape":"ChallengeNameType", "documentation":"

The name of the challenge which you are responding to with this call. This is returned to you in the AdminInitiateAuth response if you need to pass another challenge.

Valid values include the following. Note that all of these challenges require USERNAME and SECRET_HASH (if applicable) in the parameters.

  • SMS_MFA: Next challenge is to supply an SMS_MFA_CODE, delivered via SMS.

  • PASSWORD_VERIFIER: Next challenge is to supply PASSWORD_CLAIM_SIGNATURE, PASSWORD_CLAIM_SECRET_BLOCK, and TIMESTAMP after the client-side SRP calculations.

  • CUSTOM_CHALLENGE: This is returned if your custom authentication flow determines that the user should pass another challenge before tokens are issued.

  • DEVICE_SRP_AUTH: If device tracking was enabled on your user pool and the previous challenges were passed, this challenge is returned so that Amazon Cognito can start tracking this device.

  • DEVICE_PASSWORD_VERIFIER: Similar to PASSWORD_VERIFIER, but for devices only.

  • NEW_PASSWORD_REQUIRED: For users which are required to change their passwords after successful first login. This challenge should be passed with NEW_PASSWORD and any other required attributes.

" }, "Session":{ "shape":"SessionType", "documentation":"

The session which should be passed both ways in challenge-response calls to the service. If InitiateAuth or RespondToAuthChallenge API call determines that the caller needs to go through another challenge, they return a session with other challenge parameters. This session should be passed as it is to the next RespondToAuthChallenge API call.

" }, "ChallengeParameters":{ "shape":"ChallengeParametersType", "documentation":"

The challenge parameters. These are returned to you in the InitiateAuth response if you need to pass another challenge. The responses in this parameter should be used to compute inputs to the next call (RespondToAuthChallenge).

All challenges require USERNAME and SECRET_HASH (if applicable).

" }, "AuthenticationResult":{ "shape":"AuthenticationResultType", "documentation":"

The result of the authentication response. This is only returned if the caller does not need to pass another challenge. If the caller does need to pass another challenge before it gets tokens, ChallengeName, ChallengeParameters, and Session are returned.

" } }, "documentation":"

Initiates the authentication response.

" }, "IntegerType":{"type":"integer"}, "InternalErrorException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when Amazon Cognito throws an internal error exception.

" } }, "documentation":"

This exception is thrown when Amazon Cognito encounters an internal error.

", "exception":true, "fault":true }, "InvalidEmailRoleAccessPolicyException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when you have an unverified email address or the identity policy is not set on an email address that Amazon Cognito can access.

" } }, "documentation":"

This exception is thrown when Amazon Cognito is not allowed to use your email identity. HTTP status code: 400.

", "exception":true }, "InvalidLambdaResponseException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the Amazon Cognito service throws an invalid AWS Lambda response exception.

" } }, "documentation":"

This exception is thrown when the Amazon Cognito service encounters an invalid AWS Lambda response.

", "exception":true }, "InvalidOAuthFlowException":{ "type":"structure", "members":{ "message":{"shape":"MessageType"} }, "exception":true }, "InvalidParameterException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the Amazon Cognito service throws an invalid parameter exception.

" } }, "documentation":"

This exception is thrown when the Amazon Cognito service encounters an invalid parameter.

", "exception":true }, "InvalidPasswordException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the Amazon Cognito service throws an invalid user password exception.

" } }, "documentation":"

This exception is thrown when the Amazon Cognito service encounters an invalid password.

", "exception":true }, "InvalidSmsRoleAccessPolicyException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message retuned when the invalid SMS role access policy exception is thrown.

" } }, "documentation":"

This exception is returned when the role provided for SMS configuration does not have permission to publish using Amazon SNS.

", "exception":true }, "InvalidSmsRoleTrustRelationshipException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the role trust relationship for the SMS message is invalid.

" } }, "documentation":"

This exception is thrown when the trust relationship is invalid for the role provided for SMS configuration. This can happen if you do not trust cognito-idp.amazonaws.com or the external ID provided in the role does not match what is provided in the SMS configuration for the user pool.

", "exception":true }, "InvalidUserPoolConfigurationException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the user pool configuration is invalid.

" } }, "documentation":"

This exception is thrown when the user pool configuration is invalid.

", "exception":true }, "KeyListType":{ "type":"list", "member":{"shape":"KeyType"} }, "KeyType":{ "type":"structure", "members":{ "kty":{ "shape":"StringType", "documentation":"

A \"kty\" key type parameter. For more information, see JSON Web Key (JWK) Format.

" }, "alg":{ "shape":"StringType", "documentation":"

A \"kty\" (Key Type) parameter. For more information, see \"kty\" (Key Type) Parameter.

" }, "use":{ "shape":"StringType", "documentation":"

A \"use\" (Public Key Use) parameter. For more information, see \"use\" (Public Key Use) Parameter.

" }, "kid":{ "shape":"StringType", "documentation":"

A \"kid\" (Key ID) parameter. For more information, see \"kid\" (Key ID) Parameter.

" }, "n":{ "shape":"StringType", "documentation":"

An \"n\" parameter.

" }, "e":{ "shape":"StringType", "documentation":"

An \"e\" parameter.

" } }, "documentation":"

A JSON Web Key key type in JSON Web Key (JWK) Format.

" }, "LambdaConfigType":{ "type":"structure", "members":{ "PreSignUp":{ "shape":"ArnType", "documentation":"

A pre-registration AWS Lambda trigger.

" }, "CustomMessage":{ "shape":"ArnType", "documentation":"

A custom Message AWS Lambda trigger.

" }, "PostConfirmation":{ "shape":"ArnType", "documentation":"

A post-confirmation AWS Lambda trigger.

" }, "PreAuthentication":{ "shape":"ArnType", "documentation":"

A pre-authentication AWS Lambda trigger.

" }, "PostAuthentication":{ "shape":"ArnType", "documentation":"

A post-authentication AWS Lambda trigger.

" }, "DefineAuthChallenge":{ "shape":"ArnType", "documentation":"

Defines the authentication challenge.

" }, "CreateAuthChallenge":{ "shape":"ArnType", "documentation":"

Creates an authentication challenge.

" }, "VerifyAuthChallengeResponse":{ "shape":"ArnType", "documentation":"

Verifies the authentication challenge response.

" }, "PreTokenGeneration":{"shape":"ArnType"} }, "documentation":"

Specifies the type of configuration for AWS Lambda triggers.

" }, "LimitExceededException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when Amazon Cognito throws a limit exceeded exception.

" } }, "documentation":"

This exception is thrown when a user exceeds the limit for a requested AWS resource.

", "exception":true }, "ListDevicesRequest":{ "type":"structure", "required":["AccessToken"], "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access tokens for the request to list devices.

" }, "Limit":{ "shape":"QueryLimitType", "documentation":"

The limit of the device request.

" }, "PaginationToken":{ "shape":"SearchPaginationTokenType", "documentation":"

The pagination token for the list request.

" } }, "documentation":"

Represents the request to list the devices.

" }, "ListDevicesResponse":{ "type":"structure", "members":{ "Devices":{ "shape":"DeviceListType", "documentation":"

The devices returned in the list devices response.

" }, "PaginationToken":{ "shape":"SearchPaginationTokenType", "documentation":"

The pagination token for the list device response.

" } }, "documentation":"

Represents the response to list devices.

" }, "ListGroupsRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool.

" }, "Limit":{ "shape":"QueryLimitType", "documentation":"

The limit of the request to list groups.

" }, "NextToken":{ "shape":"PaginationKey", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" } } }, "ListGroupsResponse":{ "type":"structure", "members":{ "Groups":{ "shape":"GroupListType", "documentation":"

The group objects for the groups.

" }, "NextToken":{ "shape":"PaginationKey", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" } } }, "ListIdentityProvidersRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "MaxResults":{"shape":"ListProvidersLimitType"}, "NextToken":{"shape":"PaginationKeyType"} } }, "ListIdentityProvidersResponse":{ "type":"structure", "required":["Providers"], "members":{ "Providers":{"shape":"ProvidersListType"}, "NextToken":{"shape":"PaginationKeyType"} } }, "ListOfStringTypes":{ "type":"list", "member":{"shape":"StringType"} }, "ListProvidersLimitType":{ "type":"integer", "max":60, "min":1 }, "ListResourceServersLimitType":{ "type":"integer", "max":50, "min":1 }, "ListResourceServersRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "MaxResults":{"shape":"ListResourceServersLimitType"}, "NextToken":{"shape":"PaginationKeyType"} } }, "ListResourceServersResponse":{ "type":"structure", "required":["ResourceServers"], "members":{ "ResourceServers":{"shape":"ResourceServersListType"}, "NextToken":{"shape":"PaginationKeyType"} } }, "ListUserImportJobsRequest":{ "type":"structure", "required":[ "UserPoolId", "MaxResults" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool that the users are being imported into.

" }, "MaxResults":{ "shape":"PoolQueryLimitType", "documentation":"

The maximum number of import jobs you want the request to return.

" }, "PaginationToken":{ "shape":"PaginationKeyType", "documentation":"

An identifier that was returned from the previous call to ListUserImportJobs, which can be used to return the next set of import jobs in the list.

" } }, "documentation":"

Represents the request to list the user import jobs.

" }, "ListUserImportJobsResponse":{ "type":"structure", "members":{ "UserImportJobs":{ "shape":"UserImportJobsListType", "documentation":"

The user import jobs.

" }, "PaginationToken":{ "shape":"PaginationKeyType", "documentation":"

An identifier that can be used to return the next set of user import jobs in the list.

" } }, "documentation":"

Represents the response from the server to the request to list the user import jobs.

" }, "ListUserPoolClientsRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to list user pool clients.

" }, "MaxResults":{ "shape":"QueryLimit", "documentation":"

The maximum number of results you want the request to return when listing the user pool clients.

" }, "NextToken":{ "shape":"PaginationKey", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" } }, "documentation":"

Represents the request to list the user pool clients.

" }, "ListUserPoolClientsResponse":{ "type":"structure", "members":{ "UserPoolClients":{ "shape":"UserPoolClientListType", "documentation":"

The user pool clients in the response that lists user pool clients.

" }, "NextToken":{ "shape":"PaginationKey", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" } }, "documentation":"

Represents the response from the server that lists user pool clients.

" }, "ListUserPoolsRequest":{ "type":"structure", "required":["MaxResults"], "members":{ "NextToken":{ "shape":"PaginationKeyType", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" }, "MaxResults":{ "shape":"PoolQueryLimitType", "documentation":"

The maximum number of results you want the request to return when listing the user pools.

" } }, "documentation":"

Represents the request to list user pools.

" }, "ListUserPoolsResponse":{ "type":"structure", "members":{ "UserPools":{ "shape":"UserPoolListType", "documentation":"

The user pools from the response to list users.

" }, "NextToken":{ "shape":"PaginationKeyType", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" } }, "documentation":"

Represents the response to list user pools.

" }, "ListUsersInGroupRequest":{ "type":"structure", "required":[ "UserPoolId", "GroupName" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool.

" }, "GroupName":{ "shape":"GroupNameType", "documentation":"

The name of the group.

" }, "Limit":{ "shape":"QueryLimitType", "documentation":"

The limit of the request to list users.

" }, "NextToken":{ "shape":"PaginationKey", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" } } }, "ListUsersInGroupResponse":{ "type":"structure", "members":{ "Users":{ "shape":"UsersListType", "documentation":"

The users returned in the request to list users.

" }, "NextToken":{ "shape":"PaginationKey", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" } } }, "ListUsersRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool on which the search should be performed.

" }, "AttributesToGet":{ "shape":"SearchedAttributeNamesListType", "documentation":"

An array of strings, where each string is the name of a user attribute to be returned for each user in the search results. If the array is empty, all attributes are returned.

" }, "Limit":{ "shape":"QueryLimitType", "documentation":"

Maximum number of users to be returned.

" }, "PaginationToken":{ "shape":"SearchPaginationTokenType", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" }, "Filter":{ "shape":"UserFilterType", "documentation":"

A filter string of the form \"AttributeName Filter-Type \"AttributeValue\"\". Quotation marks within the filter string must be escaped using the backslash (\\) character. For example, \"family_name = \\\"Reddy\\\"\".

  • AttributeName: The name of the attribute to search for. You can only search for one attribute at a time.

  • Filter-Type: For an exact match, use =, for example, \"given_name = \\\"Jon\\\"\". For a prefix (\"starts with\") match, use ^=, for example, \"given_name ^= \\\"Jon\\\"\".

  • AttributeValue: The attribute value that must be matched for each user.

If the filter string is empty, ListUsers returns all users in the user pool.

You can only search for the following standard attributes:

  • username (case-sensitive)

  • email

  • phone_number

  • name

  • given_name

  • family_name

  • preferred_username

  • cognito:user_status (called Enabled in the Console) (case-sensitive)

  • status (case-insensitive)

Custom attributes are not searchable.

For more information, see Searching for Users Using the ListUsers API and Examples of Using the ListUsers API in the Amazon Cognito Developer Guide.

" } }, "documentation":"

Represents the request to list users.

" }, "ListUsersResponse":{ "type":"structure", "members":{ "Users":{ "shape":"UsersListType", "documentation":"

The users returned in the request to list users.

" }, "PaginationToken":{ "shape":"SearchPaginationTokenType", "documentation":"

An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

" } }, "documentation":"

The response from the request to list users.

" }, "LogoutURLsListType":{ "type":"list", "member":{"shape":"RedirectUrlType"}, "max":100, "min":0 }, "LongType":{"type":"long"}, "MFAMethodNotFoundException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when Amazon Cognito throws an MFA method not found exception.

" } }, "documentation":"

This exception is thrown when Amazon Cognito cannot find a multi-factor authentication (MFA) method.

", "exception":true }, "MFAOptionListType":{ "type":"list", "member":{"shape":"MFAOptionType"} }, "MFAOptionType":{ "type":"structure", "members":{ "DeliveryMedium":{ "shape":"DeliveryMediumType", "documentation":"

The delivery medium (email message or SMS message) to send the MFA code.

" }, "AttributeName":{ "shape":"AttributeNameType", "documentation":"

The attribute name of the MFA option type.

" } }, "documentation":"

Specifies the different settings for multi-factor authentication (MFA).

" }, "MessageActionType":{ "type":"string", "enum":[ "RESEND", "SUPPRESS" ] }, "MessageTemplateType":{ "type":"structure", "members":{ "SMSMessage":{ "shape":"SmsVerificationMessageType", "documentation":"

The message template for SMS messages.

" }, "EmailMessage":{ "shape":"EmailVerificationMessageType", "documentation":"

The message template for email messages.

" }, "EmailSubject":{ "shape":"EmailVerificationSubjectType", "documentation":"

The subject line for email messages.

" } }, "documentation":"

The message template structure.

" }, "MessageType":{"type":"string"}, "NewDeviceMetadataType":{ "type":"structure", "members":{ "DeviceKey":{ "shape":"DeviceKeyType", "documentation":"

The device key.

" }, "DeviceGroupKey":{ "shape":"StringType", "documentation":"

The device group key.

" } }, "documentation":"

The new device metadata type.

" }, "NotAuthorizedException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the Amazon Cognito service returns a not authorized exception.

" } }, "documentation":"

This exception gets thrown when a user is not authorized.

", "exception":true }, "NotifyConfigurationType":{ "type":"structure", "required":["SourceArn"], "members":{ "From":{"shape":"StringType"}, "ReplyTo":{"shape":"StringType"}, "SourceArn":{"shape":"ArnType"}, "BlockEmail":{"shape":"NotifyEmailType"}, "NoActionEmail":{"shape":"NotifyEmailType"}, "MfaEmail":{"shape":"NotifyEmailType"} } }, "NotifyEmailType":{ "type":"structure", "required":["Subject"], "members":{ "Subject":{"shape":"EmailNotificationSubjectType"}, "HtmlBody":{"shape":"EmailNotificationBodyType"}, "TextBody":{"shape":"EmailNotificationBodyType"} } }, "NumberAttributeConstraintsType":{ "type":"structure", "members":{ "MinValue":{ "shape":"StringType", "documentation":"

The minimum value of an attribute that is of the number data type.

" }, "MaxValue":{ "shape":"StringType", "documentation":"

The maximum value of an attribute that is of the number data type.

" } }, "documentation":"

The minimum and maximum value of an attribute that is of the number data type.

" }, "OAuthFlowType":{ "type":"string", "enum":[ "code", "implicit", "client_credentials" ] }, "OAuthFlowsType":{ "type":"list", "member":{"shape":"OAuthFlowType"}, "max":3, "min":0 }, "PaginationKey":{ "type":"string", "min":1, "pattern":"[\\S]+" }, "PaginationKeyType":{ "type":"string", "min":1, "pattern":"[\\S]+" }, "PasswordClaimType":{ "type":"structure", "members":{ "SecretBlock":{ "shape":"BlobType", "documentation":"

A secret block claim type for a password.

" }, "Signature":{ "shape":"BlobType", "documentation":"

A signature claim type for a password.

" } }, "documentation":"

The claim type of a password.

", "sensitive":true }, "PasswordPolicyMinLengthType":{ "type":"integer", "max":99, "min":6 }, "PasswordPolicyType":{ "type":"structure", "members":{ "MinimumLength":{ "shape":"PasswordPolicyMinLengthType", "documentation":"

The minimum length of the password policy that you have set. Cannot be less than 6.

" }, "RequireUppercase":{ "shape":"BooleanType", "documentation":"

In the password policy that you have set, refers to whether you have required users to use at least one uppercase letter in their password.

" }, "RequireLowercase":{ "shape":"BooleanType", "documentation":"

In the password policy that you have set, refers to whether you have required users to use at least one lowercase letter in their password.

" }, "RequireNumbers":{ "shape":"BooleanType", "documentation":"

In the password policy that you have set, refers to whether you have required users to use at least one number in their password.

" }, "RequireSymbols":{ "shape":"BooleanType", "documentation":"

In the password policy that you have set, refers to whether you have required users to use at least one symbol in their password.

" } }, "documentation":"

The password policy type.

" }, "PasswordResetRequiredException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when a password reset is required.

" } }, "documentation":"

This exception is thrown when a password reset is required.

", "exception":true }, "PasswordType":{ "type":"string", "max":256, "min":6, "pattern":"[\\S]+", "sensitive":true }, "PoolQueryLimitType":{ "type":"integer", "max":60, "min":1 }, "PreSignedUrlType":{ "type":"string", "max":2048, "min":0 }, "PrecedenceType":{ "type":"integer", "min":0 }, "PreconditionNotMetException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when a precondition is not met.

" } }, "documentation":"

This exception is thrown when a precondition is not met.

", "exception":true }, "ProviderDescription":{ "type":"structure", "members":{ "ProviderName":{"shape":"ProviderNameType"}, "ProviderType":{"shape":"IdentityProviderTypeType"}, "LastModifiedDate":{"shape":"DateType"}, "CreationDate":{"shape":"DateType"} } }, "ProviderDetailsType":{ "type":"map", "key":{"shape":"StringType"}, "value":{"shape":"StringType"} }, "ProviderNameType":{ "type":"string", "max":32, "min":1, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+" }, "ProviderNameTypeV1":{ "type":"string", "max":32, "min":1, "pattern":"[^_][\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}][^_]+" }, "ProviderUserIdentifierType":{ "type":"structure", "members":{ "ProviderName":{"shape":"ProviderNameType"}, "ProviderAttributeName":{"shape":"StringType"}, "ProviderAttributeValue":{"shape":"StringType"} } }, "ProvidersListType":{ "type":"list", "member":{"shape":"ProviderDescription"}, "max":50, "min":0 }, "QueryLimit":{ "type":"integer", "max":60, "min":1 }, "QueryLimitType":{ "type":"integer", "max":60, "min":0 }, "RedirectUrlType":{ "type":"string", "max":1024, "min":1, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+" }, "RefreshTokenValidityType":{ "type":"integer", "max":3650, "min":0 }, "RefreshTokensRequest":{ "type":"structure", "required":[ "ClientId", "RefreshToken" ], "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "ClientSecret":{ "shape":"ClientSecretType", "documentation":"

The client secret for a user's request to refresh tokens.

" }, "RefreshToken":{ "shape":"TokenModelType", "documentation":"

The refresh token for a user's request to refresh tokens.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"} }, "documentation":"

Represents the request to refresh tokens.

" }, "RefreshTokensResponse":{ "type":"structure", "members":{ "AuthenticationResult":{ "shape":"AuthenticationResultType", "documentation":"

The authentication result from the server's response to the request to refresh tokens.

" } }, "documentation":"

Represents the response from the server when the user wants to refresh tokens.

" }, "ResendConfirmationCodeRequest":{ "type":"structure", "required":[ "ClientId", "Username" ], "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "SecretHash":{ "shape":"SecretHashType", "documentation":"

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

" }, "UserContextData":{"shape":"UserContextDataType"}, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user to whom you wish to resend a confirmation code.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"} }, "documentation":"

Represents the request to resend the confirmation code.

" }, "ResendConfirmationCodeResponse":{ "type":"structure", "members":{ "CodeDeliveryDetails":{ "shape":"CodeDeliveryDetailsType", "documentation":"

The code delivery details returned by the server in response to the request to resend the confirmation code.

" } }, "documentation":"

The response from the server when the Amazon Cognito Your User Pools service makes the request to resend a confirmation code.

" }, "ResourceNotFoundException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the Amazon Cognito service returns a resource not found exception.

" } }, "documentation":"

This exception is thrown when the Amazon Cognito service cannot find the requested resource.

", "exception":true }, "ResourceServerIdentifierType":{ "type":"string", "max":256, "min":1, "pattern":"[\\x21\\x23-\\x5B\\x5D-\\x7E]+" }, "ResourceServerNameType":{ "type":"string", "max":256, "min":1, "pattern":"[\\w\\s+=,.@-]+" }, "ResourceServerScopeDescriptionType":{ "type":"string", "max":256, "min":1 }, "ResourceServerScopeListType":{ "type":"list", "member":{"shape":"ResourceServerScopeType"}, "max":25 }, "ResourceServerScopeNameType":{ "type":"string", "max":256, "min":1, "pattern":"[\\x21\\x23-\\x2E\\x30-\\x5B\\x5D-\\x7E]+" }, "ResourceServerScopeType":{ "type":"structure", "required":[ "ScopeName", "ScopeDescription" ], "members":{ "ScopeName":{"shape":"ResourceServerScopeNameType"}, "ScopeDescription":{"shape":"ResourceServerScopeDescriptionType"} } }, "ResourceServerType":{ "type":"structure", "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "Identifier":{"shape":"ResourceServerIdentifierType"}, "Name":{"shape":"ResourceServerNameType"}, "Scopes":{"shape":"ResourceServerScopeListType"} } }, "ResourceServersListType":{ "type":"list", "member":{"shape":"ResourceServerType"} }, "RespondToAuthChallengeRequest":{ "type":"structure", "required":[ "ClientId", "ChallengeName" ], "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The app client ID.

" }, "ChallengeName":{ "shape":"ChallengeNameType", "documentation":"

The challenge name. For more information, see InitiateAuth.

ADMIN_NO_SRP_AUTH is not a valid value.

" }, "Session":{ "shape":"SessionType", "documentation":"

The session which should be passed both ways in challenge-response calls to the service. If InitiateAuth or RespondToAuthChallenge API call determines that the caller needs to go through another challenge, they return a session with other challenge parameters. This session should be passed as it is to the next RespondToAuthChallenge API call.

" }, "ChallengeResponses":{ "shape":"ChallengeResponsesType", "documentation":"

The challenge responses. These are inputs corresponding to the value of ChallengeName, for example:

  • SMS_MFA: SMS_MFA_CODE, USERNAME, SECRET_HASH (if app client is configured with client secret).

  • PASSWORD_VERIFIER: PASSWORD_CLAIM_SIGNATURE, PASSWORD_CLAIM_SECRET_BLOCK, TIMESTAMP, USERNAME, SECRET_HASH (if app client is configured with client secret).

  • NEW_PASSWORD_REQUIRED: NEW_PASSWORD, any other required attributes, USERNAME, SECRET_HASH (if app client is configured with client secret).

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"}, "UserContextData":{"shape":"UserContextDataType"} }, "documentation":"

The request to respond to an authentication challenge.

" }, "RespondToAuthChallengeResponse":{ "type":"structure", "members":{ "ChallengeName":{ "shape":"ChallengeNameType", "documentation":"

The challenge name. For more information, see InitiateAuth.

" }, "Session":{ "shape":"SessionType", "documentation":"

The session which should be passed both ways in challenge-response calls to the service. If InitiateAuth or RespondToAuthChallenge API call determines that the caller needs to go through another challenge, they return a session with other challenge parameters. This session should be passed as it is to the next RespondToAuthChallenge API call.

" }, "ChallengeParameters":{ "shape":"ChallengeParametersType", "documentation":"

The challenge parameters. For more information, see InitiateAuth.

" }, "AuthenticationResult":{ "shape":"AuthenticationResultType", "documentation":"

The result returned by the server in response to the request to respond to the authentication challenge.

" } }, "documentation":"

The response to respond to the authentication challenge.

" }, "RiskConfigurationType":{ "type":"structure", "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ClientId":{"shape":"ClientIdType"}, "CompromisedCredentialsRiskConfiguration":{"shape":"CompromisedCredentialsRiskConfigurationType"}, "BotRiskConfiguration":{"shape":"BotRiskConfigurationType"}, "AccountTakeoverRiskConfiguration":{"shape":"AccountTakeoverRiskConfigurationType"}, "RiskExceptionConfiguration":{"shape":"RiskExceptionConfigurationType"}, "LastModifiedDate":{"shape":"DateType"} } }, "RiskDecisionType":{ "type":"string", "enum":[ "NoRisk", "Bot", "AccountTakeover" ] }, "RiskExceptionConfigurationType":{ "type":"structure", "members":{ "BlockedIPRangeList":{"shape":"BlockedIPRangeListType"}, "SkippedIPRangeList":{"shape":"SkippedIPRangeListType"} } }, "RiskLevelType":{ "type":"string", "enum":[ "Low", "Medium", "High" ] }, "S3BucketType":{ "type":"string", "max":1024, "min":3, "pattern":"^[0-9A-Za-z\\.\\-_]*(?A schema attribute of the name type.

" }, "AttributeDataType":{ "shape":"AttributeDataType", "documentation":"

The attribute data type.

" }, "DeveloperOnlyAttribute":{ "shape":"BooleanType", "documentation":"

Specifies whether the attribute type is developer only.

", "box":true }, "Mutable":{ "shape":"BooleanType", "documentation":"

Specifies whether the attribute can be changed once it has been created.

", "box":true }, "Required":{ "shape":"BooleanType", "documentation":"

Specifies whether a user pool attribute is required. If the attribute is required and the user does not provide a value, registration or sign-in will fail.

", "box":true }, "NumberAttributeConstraints":{ "shape":"NumberAttributeConstraintsType", "documentation":"

Specifies the constraints for an attribute of the number type.

" }, "StringAttributeConstraints":{ "shape":"StringAttributeConstraintsType", "documentation":"

Specifies the constraints for an attribute of the string type.

" } }, "documentation":"

Contains information about the schema attribute.

" }, "SchemaAttributesListType":{ "type":"list", "member":{"shape":"SchemaAttributeType"}, "max":50, "min":1 }, "ScopeDoesNotExistException":{ "type":"structure", "members":{ "message":{"shape":"MessageType"} }, "exception":true }, "ScopeListType":{ "type":"list", "member":{"shape":"ScopeType"}, "max":25 }, "ScopeType":{ "type":"string", "max":256, "min":1, "pattern":"[\\x21\\x23-\\x5B\\x5D-\\x7E]+" }, "SearchPaginationTokenType":{ "type":"string", "min":1, "pattern":"[\\S]+" }, "SearchedAttributeNamesListType":{ "type":"list", "member":{"shape":"AttributeNameType"} }, "SecretCodeType":{ "type":"string", "min":16, "pattern":"[A-Za-z0-9]+", "sensitive":true }, "SecretHashType":{ "type":"string", "max":128, "min":1, "pattern":"[\\w+=/]+", "sensitive":true }, "SessionType":{ "type":"string", "max":2048, "min":20 }, "SetRiskConfigurationRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ClientId":{"shape":"ClientIdType"}, "CompromisedCredentialsRiskConfiguration":{"shape":"CompromisedCredentialsRiskConfigurationType"}, "BotRiskConfiguration":{"shape":"BotRiskConfigurationType"}, "AccountTakeoverRiskConfiguration":{"shape":"AccountTakeoverRiskConfigurationType"}, "RiskExceptionConfiguration":{"shape":"RiskExceptionConfigurationType"} } }, "SetRiskConfigurationResponse":{ "type":"structure", "required":["RiskConfiguration"], "members":{ "RiskConfiguration":{"shape":"RiskConfigurationType"} } }, "SetUICustomizationRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ClientId":{"shape":"ClientIdType"}, "CSS":{"shape":"CSSType"}, "ImageFile":{"shape":"ImageFileType"} } }, "SetUICustomizationResponse":{ "type":"structure", "required":["UICustomization"], "members":{ "UICustomization":{"shape":"UICustomizationType"} } }, "SetUserMFAPreferenceRequest":{ "type":"structure", "required":["AccessToken"], "members":{ "SMSMfaSettings":{"shape":"SMSMfaSettingsType"}, "SoftwareTokenMfaSettings":{"shape":"SoftwareTokenMfaSettingsType"}, "AccessToken":{"shape":"TokenModelType"} } }, "SetUserMFAPreferenceResponse":{ "type":"structure", "members":{ } }, "SetUserPoolMfaConfigRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "SmsMfaConfiguration":{"shape":"SmsMfaConfigType"}, "SoftwareTokenMfaConfiguration":{"shape":"SoftwareTokenMfaConfigType"}, "MfaConfiguration":{"shape":"UserPoolMfaType"} } }, "SetUserPoolMfaConfigResponse":{ "type":"structure", "members":{ "SmsMfaConfiguration":{"shape":"SmsMfaConfigType"}, "SoftwareTokenMfaConfiguration":{"shape":"SoftwareTokenMfaConfigType"}, "MfaConfiguration":{"shape":"UserPoolMfaType"} } }, "SetUserPoolUIConfigurationRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "Details":{"shape":"UIDetailsMapType"} } }, "SetUserPoolUIConfigurationResponse":{ "type":"structure", "required":["UserPoolUIConfiguration"], "members":{ "UserPoolUIConfiguration":{"shape":"UserPoolUIConfigurationType"} } }, "SetUserSettingsRequest":{ "type":"structure", "required":[ "AccessToken", "MFAOptions" ], "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token for the set user settings request.

" }, "MFAOptions":{ "shape":"MFAOptionListType", "documentation":"

Specifies the options for MFA (e.g., email or phone number).

" } }, "documentation":"

Represents the request to set user settings.

" }, "SetUserSettingsResponse":{ "type":"structure", "members":{ }, "documentation":"

The response from the server for a set user settings request.

" }, "SignUpRequest":{ "type":"structure", "required":[ "ClientId", "Username", "Password" ], "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "SecretHash":{ "shape":"SecretHashType", "documentation":"

A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message.

" }, "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user you wish to register.

" }, "Password":{ "shape":"PasswordType", "documentation":"

The password of the user you wish to register.

" }, "UserAttributes":{ "shape":"AttributeListType", "documentation":"

An array of name-value pairs representing user attributes.

" }, "ValidationData":{ "shape":"AttributeListType", "documentation":"

The validation data in the request to register a user.

" }, "AnalyticsMetadata":{"shape":"AnalyticsMetadataType"}, "UserContextData":{"shape":"UserContextDataType"} }, "documentation":"

Represents the request to register a user.

" }, "SignUpResponse":{ "type":"structure", "required":[ "UserConfirmed", "UserSub" ], "members":{ "UserConfirmed":{ "shape":"BooleanType", "documentation":"

A response from the server indicating that a user registration has been confirmed.

" }, "CodeDeliveryDetails":{ "shape":"CodeDeliveryDetailsType", "documentation":"

The code delivery details returned by the server response to the user registration request.

" }, "UserSub":{"shape":"StringType"} }, "documentation":"

The response from the server for a registration request.

" }, "SkippedIPRangeListType":{ "type":"list", "member":{"shape":"StringType"}, "max":20 }, "SmsConfigurationType":{ "type":"structure", "required":["SnsCallerArn"], "members":{ "SnsCallerArn":{ "shape":"ArnType", "documentation":"

The Amazon Resource Name (ARN) of the Amazon Simple Notification Service (SNS) caller.

" }, "ExternalId":{ "shape":"StringType", "documentation":"

The external ID.

" } }, "documentation":"

The SMS configuration type.

" }, "SmsMfaConfigType":{ "type":"structure", "members":{ "SmsAuthenticationMessage":{"shape":"SmsVerificationMessageType"}, "SmsConfiguration":{"shape":"SmsConfigurationType"} } }, "SmsVerificationMessageType":{ "type":"string", "max":140, "min":6, "pattern":".*\\{####\\}.*" }, "SoftwareTokenMFANotFoundException":{ "type":"structure", "members":{ "message":{"shape":"MessageType"} }, "exception":true }, "SoftwareTokenMFAUserCodeType":{ "type":"string", "max":6, "min":6, "pattern":"[0-9]+" }, "SoftwareTokenMfaConfigType":{ "type":"structure", "members":{ "Enabled":{"shape":"BooleanType"} } }, "SoftwareTokenMfaSettingsType":{ "type":"structure", "members":{ "Enabled":{"shape":"BooleanType"}, "PreferredMfa":{"shape":"BooleanType"} } }, "StartUserImportJobRequest":{ "type":"structure", "required":[ "UserPoolId", "JobId" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool that the users are being imported into.

" }, "JobId":{ "shape":"UserImportJobIdType", "documentation":"

The job ID for the user import job.

" } }, "documentation":"

Represents the request to start the user import job.

" }, "StartUserImportJobResponse":{ "type":"structure", "members":{ "UserImportJob":{ "shape":"UserImportJobType", "documentation":"

The job object that represents the user import job.

" } }, "documentation":"

Represents the response from the server to the request to start the user import job.

" }, "StatusType":{ "type":"string", "enum":[ "Enabled", "Disabled" ] }, "StopUserImportJobRequest":{ "type":"structure", "required":[ "UserPoolId", "JobId" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool that the users are being imported into.

" }, "JobId":{ "shape":"UserImportJobIdType", "documentation":"

The job ID for the user import job.

" } }, "documentation":"

Represents the request to stop the user import job.

" }, "StopUserImportJobResponse":{ "type":"structure", "members":{ "UserImportJob":{ "shape":"UserImportJobType", "documentation":"

The job object that represents the user import job.

" } }, "documentation":"

Represents the response from the server to the request to stop the user import job.

" }, "StringAttributeConstraintsType":{ "type":"structure", "members":{ "MinLength":{ "shape":"StringType", "documentation":"

The minimum length of an attribute value of the string type.

" }, "MaxLength":{ "shape":"StringType", "documentation":"

The maximum length of an attribute value of the string type.

" } }, "documentation":"

The type of constraints associated with an attribute of the string type.

" }, "StringType":{"type":"string"}, "SupportedIdentityProvidersListType":{ "type":"list", "member":{"shape":"ProviderNameType"} }, "TokenModelType":{ "type":"string", "pattern":"[A-Za-z0-9-_=.]+", "sensitive":true }, "TooManyFailedAttemptsException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the Amazon Cognito service returns a too many failed attempts exception.

" } }, "documentation":"

This exception gets thrown when the user has made too many failed attempts for a given action (e.g., sign in).

", "exception":true }, "TooManyRequestsException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the Amazon Cognito service returns a too many requests exception.

" } }, "documentation":"

This exception gets thrown when the user has made too many requests for a given operation.

", "exception":true }, "UICustomizationType":{ "type":"structure", "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ClientId":{"shape":"ClientIdType"}, "ImageUrl":{"shape":"ImageUrlType"}, "CSS":{"shape":"CSSType"}, "CSSVersion":{"shape":"CSSVersionType"}, "LastModifiedDate":{"shape":"DateType"}, "CreationDate":{"shape":"DateType"} } }, "UIDetailsMapType":{ "type":"map", "key":{"shape":"StringType"}, "value":{"shape":"StringType"} }, "UnexpectedLambdaException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the Amazon Cognito service returns an unexpected AWS Lambda exception.

" } }, "documentation":"

This exception gets thrown when the Amazon Cognito service encounters an unexpected exception with the AWS Lambda service.

", "exception":true }, "UnsupportedIdentityProviderException":{ "type":"structure", "members":{ "message":{"shape":"MessageType"} }, "exception":true }, "UnsupportedUserStateException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the user is in an unsupported state.

" } }, "documentation":"

The request failed because the user is in an unsupported state.

", "exception":true }, "UpdateAuthEventFeedbackRequest":{ "type":"structure", "required":[ "UserPoolId", "Username", "EventId", "FeedbackToken", "FeedbackValue" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "Username":{"shape":"UsernameType"}, "EventId":{"shape":"EventIdType"}, "FeedbackToken":{"shape":"TokenModelType"}, "FeedbackValue":{"shape":"FeedbackValueType"} } }, "UpdateAuthEventFeedbackResponse":{ "type":"structure", "members":{ } }, "UpdateDeviceStatusRequest":{ "type":"structure", "required":[ "AccessToken", "DeviceKey" ], "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token.

" }, "DeviceKey":{ "shape":"DeviceKeyType", "documentation":"

The device key.

" }, "DeviceRememberedStatus":{ "shape":"DeviceRememberedStatusType", "documentation":"

The status of whether a device is remembered.

" } }, "documentation":"

Represents the request to update the device status.

" }, "UpdateDeviceStatusResponse":{ "type":"structure", "members":{ }, "documentation":"

The response to the request to update the device status.

" }, "UpdateGroupRequest":{ "type":"structure", "required":[ "GroupName", "UserPoolId" ], "members":{ "GroupName":{ "shape":"GroupNameType", "documentation":"

The name of the group.

" }, "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool.

" }, "Description":{ "shape":"DescriptionType", "documentation":"

A string containing the new description of the group.

" }, "RoleArn":{ "shape":"ArnType", "documentation":"

The new role ARN for the group. This is used for setting the cognito:roles and cognito:preferred_role claims in the token.

" }, "Precedence":{ "shape":"PrecedenceType", "documentation":"

The new precedence value for the group. For more information about this parameter, see CreateGroup.

" } } }, "UpdateGroupResponse":{ "type":"structure", "members":{ "Group":{ "shape":"GroupType", "documentation":"

The group object for the group.

" } } }, "UpdateIdentityProviderRequest":{ "type":"structure", "required":[ "UserPoolId", "ProviderName" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "ProviderName":{"shape":"ProviderNameType"}, "ProviderDetails":{"shape":"ProviderDetailsType"}, "AttributeMapping":{"shape":"AttributeMappingType"}, "IdpIdentifiers":{"shape":"IdpIdentifiersListType"} } }, "UpdateIdentityProviderResponse":{ "type":"structure", "required":["IdentityProvider"], "members":{ "IdentityProvider":{"shape":"IdentityProviderType"} } }, "UpdateResourceServerRequest":{ "type":"structure", "required":[ "UserPoolId", "Identifier", "Name" ], "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "Identifier":{"shape":"ResourceServerIdentifierType"}, "Name":{"shape":"ResourceServerNameType"}, "Scopes":{"shape":"ResourceServerScopeListType"} } }, "UpdateResourceServerResponse":{ "type":"structure", "required":["ResourceServer"], "members":{ "ResourceServer":{"shape":"ResourceServerType"} } }, "UpdateUserAttributesRequest":{ "type":"structure", "required":[ "UserAttributes", "AccessToken" ], "members":{ "UserAttributes":{ "shape":"AttributeListType", "documentation":"

An array of name-value pairs representing user attributes.

" }, "AccessToken":{ "shape":"TokenModelType", "documentation":"

The access token for the request to update user attributes.

" } }, "documentation":"

Represents the request to update user attributes.

" }, "UpdateUserAttributesResponse":{ "type":"structure", "members":{ "CodeDeliveryDetailsList":{ "shape":"CodeDeliveryDetailsListType", "documentation":"

The code delivery details list from the server for the request to update user attributes.

" } }, "documentation":"

Represents the response from the server for the request to update user attributes.

" }, "UpdateUserPoolClientRequest":{ "type":"structure", "required":[ "UserPoolId", "ClientId" ], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to update the user pool client.

" }, "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "ClientName":{ "shape":"ClientNameType", "documentation":"

The client name from the update user pool client request.

" }, "RefreshTokenValidity":{ "shape":"RefreshTokenValidityType", "documentation":"

The time limit, in days, after which the refresh token is no longer valid and cannot be used.

" }, "ReadAttributes":{ "shape":"ClientPermissionListType", "documentation":"

The read-only attributes of the user pool.

" }, "WriteAttributes":{ "shape":"ClientPermissionListType", "documentation":"

The writeable attributes of the user pool.

" }, "ExplicitAuthFlows":{ "shape":"ExplicitAuthFlowsListType", "documentation":"

Explicit authentication flows.

" }, "SupportedIdentityProviders":{"shape":"SupportedIdentityProvidersListType"}, "CallbackURLs":{"shape":"CallbackURLsListType"}, "LogoutURLs":{"shape":"LogoutURLsListType"}, "DefaultRedirectURI":{"shape":"RedirectUrlType"}, "AllowedOAuthFlows":{"shape":"OAuthFlowsType"}, "AllowedOAuthScopes":{"shape":"ScopeListType"}, "AllowedOAuthFlowsUserPoolClient":{"shape":"BooleanType"}, "AnalyticsConfiguration":{"shape":"AnalyticsConfigurationType"} }, "documentation":"

Represents the request to update the user pool client.

" }, "UpdateUserPoolClientResponse":{ "type":"structure", "members":{ "UserPoolClient":{ "shape":"UserPoolClientType", "documentation":"

The user pool client value from the response from the server when an update user pool client request is made.

" } }, "documentation":"

Represents the response from the server to the request to update the user pool client.

" }, "UpdateUserPoolRequest":{ "type":"structure", "required":["UserPoolId"], "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool you want to update.

" }, "Policies":{ "shape":"UserPoolPolicyType", "documentation":"

A container with the policies you wish to update in a user pool.

" }, "LambdaConfig":{ "shape":"LambdaConfigType", "documentation":"

The AWS Lambda configuration information from the request to update the user pool.

" }, "AutoVerifiedAttributes":{ "shape":"VerifiedAttributesListType", "documentation":"

The attributes that are automatically verified when the Amazon Cognito service makes a request to update user pools.

" }, "SmsVerificationMessage":{ "shape":"SmsVerificationMessageType", "documentation":"

A container with information about the SMS verification message.

" }, "EmailVerificationMessage":{ "shape":"EmailVerificationMessageType", "documentation":"

The contents of the email verification message.

" }, "EmailVerificationSubject":{ "shape":"EmailVerificationSubjectType", "documentation":"

The subject of the email verification message.

" }, "VerificationMessageTemplate":{"shape":"VerificationMessageTemplateType"}, "SmsAuthenticationMessage":{ "shape":"SmsVerificationMessageType", "documentation":"

The contents of the SMS authentication message.

" }, "MfaConfiguration":{ "shape":"UserPoolMfaType", "documentation":"

Can be one of the following values:

  • OFF - MFA tokens are not required and cannot be specified during user registration.

  • ON - MFA tokens are required for all user registrations. You can only specify required when you are initially creating a user pool.

  • OPTIONAL - Users have the option when registering to create an MFA token.

" }, "DeviceConfiguration":{ "shape":"DeviceConfigurationType", "documentation":"

Device configuration.

" }, "EmailConfiguration":{ "shape":"EmailConfigurationType", "documentation":"

Email configuration.

" }, "SmsConfiguration":{ "shape":"SmsConfigurationType", "documentation":"

SMS configuration.

" }, "UserPoolTags":{ "shape":"UserPoolTagsType", "documentation":"

The cost allocation tags for the user pool. For more information, see Adding Cost Allocation Tags to Your User Pool

" }, "AdminCreateUserConfig":{ "shape":"AdminCreateUserConfigType", "documentation":"

The configuration for AdminCreateUser requests.

" }, "UserPoolAddOns":{"shape":"UserPoolAddOnsType"} }, "documentation":"

Represents the request to update the user pool.

" }, "UpdateUserPoolResponse":{ "type":"structure", "members":{ }, "documentation":"

Represents the response from the server when you make a request to update the user pool.

" }, "UserContextDataType":{ "type":"structure", "members":{ "encodedData":{"shape":"StringType"} } }, "UserFilterType":{ "type":"string", "max":256 }, "UserImportInProgressException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the user pool has an import job running.

" } }, "documentation":"

This exception is thrown when you are trying to modify a user pool while a user import job is in progress for that pool.

", "exception":true }, "UserImportJobIdType":{ "type":"string", "max":55, "min":1, "pattern":"import-[0-9a-zA-Z-]+" }, "UserImportJobNameType":{ "type":"string", "max":128, "min":1, "pattern":"[\\w\\s+=,.@-]+" }, "UserImportJobStatusType":{ "type":"string", "enum":[ "Created", "Pending", "InProgress", "Stopping", "Expired", "Stopped", "Failed", "Succeeded" ] }, "UserImportJobType":{ "type":"structure", "members":{ "JobName":{ "shape":"UserImportJobNameType", "documentation":"

The job name for the user import job.

" }, "JobId":{ "shape":"UserImportJobIdType", "documentation":"

The job ID for the user import job.

" }, "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool that the users are being imported into.

" }, "PreSignedUrl":{ "shape":"PreSignedUrlType", "documentation":"

The pre-signed URL to be used to upload the .csv file.

" }, "CreationDate":{ "shape":"DateType", "documentation":"

The date when the user import job was created.

" }, "StartDate":{ "shape":"DateType", "documentation":"

The date when the user import job was started.

" }, "CompletionDate":{ "shape":"DateType", "documentation":"

The date when the user import job was completed.

" }, "Status":{ "shape":"UserImportJobStatusType", "documentation":"

The status of the user import job. One of the following:

  • Created - The job was created but not started.

  • Pending - A transition state. You have started the job, but it has not begun importing users yet.

  • InProgress - The job has started, and users are being imported.

  • Stopping - You have stopped the job, but the job has not stopped importing users yet.

  • Stopped - You have stopped the job, and the job has stopped importing users.

  • Succeeded - The job has completed successfully.

  • Failed - The job has stopped due to an error.

  • Expired - You created a job, but did not start the job within 24-48 hours. All data associated with the job was deleted, and the job cannot be started.

" }, "CloudWatchLogsRoleArn":{ "shape":"ArnType", "documentation":"

The role ARN for the Amazon CloudWatch Logging role for the user import job. For more information, see \"Creating the CloudWatch Logs IAM Role\" in the Amazon Cognito Developer Guide.

" }, "ImportedUsers":{ "shape":"LongType", "documentation":"

The number of users that were successfully imported.

" }, "SkippedUsers":{ "shape":"LongType", "documentation":"

The number of users that were skipped.

" }, "FailedUsers":{ "shape":"LongType", "documentation":"

The number of users that could not be imported.

" }, "CompletionMessage":{ "shape":"CompletionMessageType", "documentation":"

The message returned when the user import job is completed.

" } }, "documentation":"

The user import job type.

" }, "UserImportJobsListType":{ "type":"list", "member":{"shape":"UserImportJobType"}, "max":50, "min":1 }, "UserLambdaValidationException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when the Amazon Cognito service returns a user validation exception with the AWS Lambda service.

" } }, "documentation":"

This exception gets thrown when the Amazon Cognito service encounters a user validation exception with the AWS Lambda service.

", "exception":true }, "UserNotConfirmedException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when a user is not confirmed successfully.

" } }, "documentation":"

This exception is thrown when a user is not confirmed successfully.

", "exception":true }, "UserNotFoundException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when a user is not found.

" } }, "documentation":"

This exception is thrown when a user is not found.

", "exception":true }, "UserPoolAddOnNotEnabledException":{ "type":"structure", "members":{ "message":{"shape":"MessageType"} }, "exception":true }, "UserPoolAddOnsType":{ "type":"structure", "required":["AdvancedSecurityMode"], "members":{ "AdvancedSecurityMode":{"shape":"AdvancedSecurityModeType"} } }, "UserPoolClientDescription":{ "type":"structure", "members":{ "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool where you want to describe the user pool client.

" }, "ClientName":{ "shape":"ClientNameType", "documentation":"

The client name from the user pool client description.

" } }, "documentation":"

The description of the user pool client.

" }, "UserPoolClientListType":{ "type":"list", "member":{"shape":"UserPoolClientDescription"} }, "UserPoolClientType":{ "type":"structure", "members":{ "UserPoolId":{ "shape":"UserPoolIdType", "documentation":"

The user pool ID for the user pool client.

" }, "ClientName":{ "shape":"ClientNameType", "documentation":"

The client name from the user pool request of the client type.

" }, "ClientId":{ "shape":"ClientIdType", "documentation":"

The ID of the client associated with the user pool.

" }, "ClientSecret":{ "shape":"ClientSecretType", "documentation":"

The client secret from the user pool request of the client type.

" }, "LastModifiedDate":{ "shape":"DateType", "documentation":"

The last modified date from the user pool request of the client type.

" }, "CreationDate":{ "shape":"DateType", "documentation":"

The creation date from the user pool request of the client type.

" }, "RefreshTokenValidity":{ "shape":"RefreshTokenValidityType", "documentation":"

The time limit, in days, after which the refresh token is no longer valid and cannot be used.

" }, "ReadAttributes":{ "shape":"ClientPermissionListType", "documentation":"

The Read-only attributes.

" }, "WriteAttributes":{ "shape":"ClientPermissionListType", "documentation":"

The writeable attributes.

" }, "ExplicitAuthFlows":{ "shape":"ExplicitAuthFlowsListType", "documentation":"

The explicit authentication flows.

" }, "SupportedIdentityProviders":{"shape":"SupportedIdentityProvidersListType"}, "CallbackURLs":{"shape":"CallbackURLsListType"}, "LogoutURLs":{"shape":"LogoutURLsListType"}, "DefaultRedirectURI":{"shape":"RedirectUrlType"}, "AllowedOAuthFlows":{"shape":"OAuthFlowsType"}, "AllowedOAuthScopes":{"shape":"ScopeListType"}, "AllowedOAuthFlowsUserPoolClient":{ "shape":"BooleanType", "box":true }, "AnalyticsConfiguration":{"shape":"AnalyticsConfigurationType"} }, "documentation":"

A user pool of the client type.

" }, "UserPoolDescriptionType":{ "type":"structure", "members":{ "Id":{ "shape":"UserPoolIdType", "documentation":"

The ID in a user pool description.

" }, "Name":{ "shape":"UserPoolNameType", "documentation":"

The name in a user pool description.

" }, "LambdaConfig":{ "shape":"LambdaConfigType", "documentation":"

The AWS Lambda configuration information in a user pool description.

" }, "Status":{ "shape":"StatusType", "documentation":"

The user pool status in a user pool description.

" }, "LastModifiedDate":{ "shape":"DateType", "documentation":"

The last modified date in a user pool description.

" }, "CreationDate":{ "shape":"DateType", "documentation":"

The creation date in a user pool description.

" } }, "documentation":"

A user pool description.

" }, "UserPoolIdType":{ "type":"string", "max":55, "min":1, "pattern":"[\\w-]+_[0-9a-zA-Z]+" }, "UserPoolListType":{ "type":"list", "member":{"shape":"UserPoolDescriptionType"} }, "UserPoolMfaType":{ "type":"string", "enum":[ "OFF", "ON", "OPTIONAL" ] }, "UserPoolNameType":{ "type":"string", "max":128, "min":1, "pattern":"[\\w\\s+=,.@-]+" }, "UserPoolPolicyType":{ "type":"structure", "members":{ "PasswordPolicy":{ "shape":"PasswordPolicyType", "documentation":"

A container with information about the user pool password policy.

" } }, "documentation":"

The type of policy in a user pool.

" }, "UserPoolTaggingException":{ "type":"structure", "members":{ "message":{"shape":"MessageType"} }, "documentation":"

This exception gets thrown when a user pool tag cannot be set or updated.

", "exception":true }, "UserPoolTagsType":{ "type":"map", "key":{"shape":"StringType"}, "value":{"shape":"StringType"} }, "UserPoolType":{ "type":"structure", "members":{ "Id":{ "shape":"UserPoolIdType", "documentation":"

The ID of the user pool.

" }, "Name":{ "shape":"UserPoolNameType", "documentation":"

The name of the user pool.

" }, "Policies":{ "shape":"UserPoolPolicyType", "documentation":"

A container describing the policies associated with a user pool.

" }, "LambdaConfig":{ "shape":"LambdaConfigType", "documentation":"

A container describing the AWS Lambda triggers associated with a user pool.

" }, "Status":{ "shape":"StatusType", "documentation":"

The status of a user pool.

" }, "LastModifiedDate":{ "shape":"DateType", "documentation":"

The last modified date of a user pool.

" }, "CreationDate":{ "shape":"DateType", "documentation":"

The creation date of a user pool.

" }, "SchemaAttributes":{ "shape":"SchemaAttributesListType", "documentation":"

A container with the schema attributes of a user pool.

" }, "AutoVerifiedAttributes":{ "shape":"VerifiedAttributesListType", "documentation":"

Specifies the attributes that are auto-verified in a user pool.

" }, "AliasAttributes":{ "shape":"AliasAttributesListType", "documentation":"

Specifies the attributes that are aliased in a user pool.

" }, "UsernameAttributes":{"shape":"UsernameAttributesListType"}, "SmsVerificationMessage":{ "shape":"SmsVerificationMessageType", "documentation":"

The contents of the SMS verification message.

" }, "EmailVerificationMessage":{ "shape":"EmailVerificationMessageType", "documentation":"

The contents of the email verification message.

" }, "EmailVerificationSubject":{ "shape":"EmailVerificationSubjectType", "documentation":"

The subject of the email verification message.

" }, "VerificationMessageTemplate":{"shape":"VerificationMessageTemplateType"}, "SmsAuthenticationMessage":{ "shape":"SmsVerificationMessageType", "documentation":"

The contents of the SMS authentication message.

" }, "MfaConfiguration":{ "shape":"UserPoolMfaType", "documentation":"

Can be one of the following values:

  • OFF - MFA tokens are not required and cannot be specified during user registration.

  • ON - MFA tokens are required for all user registrations. You can only specify required when you are initially creating a user pool.

  • OPTIONAL - Users have the option when registering to create an MFA token.

" }, "DeviceConfiguration":{ "shape":"DeviceConfigurationType", "documentation":"

The device configuration.

" }, "EstimatedNumberOfUsers":{ "shape":"IntegerType", "documentation":"

A number estimating the size of the user pool.

" }, "EmailConfiguration":{ "shape":"EmailConfigurationType", "documentation":"

The email configuration.

" }, "SmsConfiguration":{ "shape":"SmsConfigurationType", "documentation":"

The SMS configuration.

" }, "UserPoolTags":{ "shape":"UserPoolTagsType", "documentation":"

The cost allocation tags for the user pool. For more information, see Adding Cost Allocation Tags to Your User Pool

" }, "SmsConfigurationFailure":{ "shape":"StringType", "documentation":"

The reason why the SMS configuration cannot send the message(s) to your users.

" }, "EmailConfigurationFailure":{ "shape":"StringType", "documentation":"

The reason why the email configuration cannot send the messages to your users.

" }, "AdminCreateUserConfig":{ "shape":"AdminCreateUserConfigType", "documentation":"

The configuration for AdminCreateUser requests.

" }, "UserPoolAddOns":{"shape":"UserPoolAddOnsType"} }, "documentation":"

A container with information about the user pool type.

" }, "UserPoolUIConfigurationType":{ "type":"structure", "members":{ "UserPoolId":{"shape":"UserPoolIdType"}, "Details":{"shape":"UserPoolUIDetailsType"}, "LastModifiedDate":{"shape":"DateType"}, "CreationDate":{"shape":"DateType"} } }, "UserPoolUIDetailsType":{ "type":"map", "key":{"shape":"StringType"}, "value":{"shape":"UIDetailsMapType"} }, "UserStatusType":{ "type":"string", "enum":[ "UNCONFIRMED", "CONFIRMED", "ARCHIVED", "COMPROMISED", "UNKNOWN", "RESET_REQUIRED", "FORCE_CHANGE_PASSWORD" ] }, "UserType":{ "type":"structure", "members":{ "Username":{ "shape":"UsernameType", "documentation":"

The user name of the user you wish to describe.

" }, "Attributes":{ "shape":"AttributeListType", "documentation":"

A container with information about the user type attributes.

" }, "UserCreateDate":{ "shape":"DateType", "documentation":"

The creation date of the user.

" }, "UserLastModifiedDate":{ "shape":"DateType", "documentation":"

The last modified date of the user.

" }, "Enabled":{ "shape":"BooleanType", "documentation":"

Specifies whether the user is enabled.

" }, "UserStatus":{ "shape":"UserStatusType", "documentation":"

The user status. Can be one of the following:

  • UNCONFIRMED - User has been created but not confirmed.

  • CONFIRMED - User has been confirmed.

  • ARCHIVED - User is no longer active.

  • COMPROMISED - User is disabled due to a potential security threat.

  • UNKNOWN - User status is not known.

" }, "MFAOptions":{ "shape":"MFAOptionListType", "documentation":"

The MFA options for the user.

" } }, "documentation":"

The user type.

" }, "UsernameAttributeType":{ "type":"string", "enum":[ "phone_number", "email" ] }, "UsernameAttributesListType":{ "type":"list", "member":{"shape":"UsernameAttributeType"} }, "UsernameExistsException":{ "type":"structure", "members":{ "message":{ "shape":"MessageType", "documentation":"

The message returned when Amazon Cognito throws a user name exists exception.

" } }, "documentation":"

This exception is thrown when Amazon Cognito encounters a user name that already exists in the user pool.

", "exception":true }, "UsernameType":{ "type":"string", "max":128, "min":1, "pattern":"[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+", "sensitive":true }, "UsersListType":{ "type":"list", "member":{"shape":"UserType"} }, "VerificationMessageTemplateType":{ "type":"structure", "members":{ "SmsMessage":{"shape":"SmsVerificationMessageType"}, "EmailMessage":{"shape":"EmailVerificationMessageType"}, "EmailSubject":{"shape":"EmailVerificationSubjectType"}, "EmailMessageByLink":{"shape":"EmailVerificationMessageByLinkType"}, "EmailSubjectByLink":{"shape":"EmailVerificationSubjectByLinkType"}, "DefaultEmailOption":{"shape":"DefaultEmailOptionType"} } }, "VerifiedAttributeType":{ "type":"string", "enum":[ "phone_number", "email" ] }, "VerifiedAttributesListType":{ "type":"list", "member":{"shape":"VerifiedAttributeType"} }, "VerifySoftwareTokenRequest":{ "type":"structure", "required":["UserCode"], "members":{ "AccessToken":{"shape":"TokenModelType"}, "Session":{"shape":"SessionType"}, "UserCode":{"shape":"SoftwareTokenMFAUserCodeType"}, "FriendlyDeviceName":{"shape":"StringType"} } }, "VerifySoftwareTokenResponse":{ "type":"structure", "members":{ "Status":{"shape":"VerifySoftwareTokenResponseType"}, "Session":{"shape":"SessionType"} } }, "VerifySoftwareTokenResponseType":{ "type":"string", "enum":[ "SUCCESS", "ERROR" ] }, "VerifyUserAttributeRequest":{ "type":"structure", "required":[ "AccessToken", "AttributeName", "Code" ], "members":{ "AccessToken":{ "shape":"TokenModelType", "documentation":"

Represents the access token of the request to verify user attributes.

" }, "AttributeName":{ "shape":"AttributeNameType", "documentation":"

The attribute name in the request to verify user attributes.

" }, "Code":{ "shape":"ConfirmationCodeType", "documentation":"

The verification code in the request to verify user attributes.

" } }, "documentation":"

Represents the request to verify user attributes.

" }, "VerifyUserAttributeResponse":{ "type":"structure", "members":{ }, "documentation":"

A container representing the response from the server from the request to verify user attributes.

" }, "openIdListType":{ "type":"list", "member":{"shape":"StringType"} }, "openIdUrlType":{ "type":"string", "max":150, "min":1, "pattern":"https://cognito-idp\\.amazonaws\\.com/[\\w\\._/-]" } }, "documentation":"

Using the Amazon Cognito Your User Pools API, you can create a user pool to manage directories and users. You can authenticate a user to obtain tokens related to user identity and access policies.

This API reference provides information about user pools in Amazon Cognito Your User Pools.

For more information, see the Amazon Cognito Documentation.

" } },{}],3:[function(require,module,exports){ module.exports={ "acm": { "name": "ACM", "cors": true }, "apigateway": { "name": "APIGateway", "cors": true }, "applicationautoscaling": { "prefix": "application-autoscaling", "name": "ApplicationAutoScaling", "cors": true }, "autoscaling": { "name": "AutoScaling", "cors": true }, "cloudformation": { "name": "CloudFormation", "cors": true }, "cloudfront": { "name": "CloudFront", "versions": ["2013-05-12*", "2013-11-11*", "2014-05-31*", "2014-10-21*", "2014-11-06*", "2015-04-17*", "2015-07-27*", "2015-09-17*", "2016-01-13*", "2016-01-28*", "2016-08-01*", "2016-08-20*"], "cors": true }, "cloudhsm": { "name": "CloudHSM", "cors": true }, "cloudsearch": { "name": "CloudSearch" }, "cloudsearchdomain": { "name": "CloudSearchDomain" }, "cloudtrail": { "name": "CloudTrail", "cors": true }, "cloudwatch": { "prefix": "monitoring", "name": "CloudWatch", "cors": true }, "cloudwatchevents": { "prefix": "events", "name": "CloudWatchEvents", "versions": ["2014-02-03*"], "cors": true }, "cloudwatchlogs": { "prefix": "logs", "name": "CloudWatchLogs", "cors": true }, "codecommit": { "name": "CodeCommit", "cors": true }, "codedeploy": { "name": "CodeDeploy", "cors": true }, "codepipeline": { "name": "CodePipeline", "cors": true }, "cognitoidentity": { "prefix": "cognito-identity", "name": "CognitoIdentity", "cors": true }, "cognitoidentityserviceprovider": { "prefix": "cognito-idp", "name": "CognitoIdentityServiceProvider", "cors": true }, "cognitosync": { "prefix": "cognito-sync", "name": "CognitoSync", "cors": true }, "configservice": { "prefix": "config", "name": "ConfigService", "cors": true }, "datapipeline": { "name": "DataPipeline" }, "devicefarm": { "name": "DeviceFarm", "cors": true }, "directconnect": { "name": "DirectConnect", "cors": true }, "directoryservice": { "prefix": "ds", "name": "DirectoryService" }, "discovery": { "name": "Discovery" }, "dms": { "name": "DMS" }, "dynamodb": { "name": "DynamoDB", "cors": true }, "dynamodbstreams": { "prefix": "streams.dynamodb", "name": "DynamoDBStreams", "cors": true }, "ec2": { "name": "EC2", "versions": ["2013-06-15*", "2013-10-15*", "2014-02-01*", "2014-05-01*", "2014-06-15*", "2014-09-01*", "2014-10-01*", "2015-03-01*", "2015-04-15*", "2015-10-01*"], "cors": true }, "ecr": { "name": "ECR", "cors": true }, "ecs": { "name": "ECS", "cors": true }, "efs": { "prefix": "elasticfilesystem", "name": "EFS" }, "elasticache": { "name": "ElastiCache", "versions": ["2012-11-15*", "2014-03-24*", "2014-07-15*", "2014-09-30*"], "cors": true }, "elasticbeanstalk": { "name": "ElasticBeanstalk", "cors": true }, "elb": { "prefix": "elasticloadbalancing", "name": "ELB", "cors": true }, "elbv2": { "prefix": "elasticloadbalancingv2", "name": "ELBv2", "cors": true }, "emr": { "prefix": "elasticmapreduce", "name": "EMR", "cors": true }, "es": { "name": "ES" }, "elastictranscoder": { "name": "ElasticTranscoder", "cors": true }, "firehose": { "name": "Firehose", "cors": true }, "gamelift": { "name": "GameLift", "cors": true }, "glacier": { "name": "Glacier" }, "iam": { "name": "IAM" }, "importexport": { "name": "ImportExport" }, "inspector": { "name": "Inspector", "versions": ["2015-08-18*"], "cors": true }, "iot": { "name": "Iot", "cors": true }, "iotdata": { "prefix": "iot-data", "name": "IotData", "cors": true }, "kinesis": { "name": "Kinesis", "cors": true }, "kinesisanalytics": { "name": "KinesisAnalytics" }, "kms": { "name": "KMS", "cors": true }, "lambda": { "name": "Lambda", "cors": true }, "machinelearning": { "name": "MachineLearning", "cors": true }, "marketplacecommerceanalytics": { "name": "MarketplaceCommerceAnalytics", "cors": true }, "marketplacemetering": { "prefix": "meteringmarketplace", "name": "MarketplaceMetering" }, "mobileanalytics": { "name": "MobileAnalytics", "cors": true }, "opsworks": { "name": "OpsWorks", "cors": true }, "rds": { "name": "RDS", "versions": ["2014-09-01*"], "cors": true }, "redshift": { "name": "Redshift", "cors": true }, "route53": { "name": "Route53", "cors": true }, "route53domains": { "name": "Route53Domains", "cors": true }, "s3": { "name": "S3", "dualstackAvailable": true, "cors": true }, "servicecatalog": { "name": "ServiceCatalog", "cors": true }, "ses": { "prefix": "email", "name": "SES", "cors": true }, "simpledb": { "prefix": "sdb", "name": "SimpleDB" }, "snowball": { "name": "Snowball" }, "sns": { "name": "SNS", "cors": true }, "sqs": { "name": "SQS", "cors": true }, "ssm": { "name": "SSM", "cors": true }, "storagegateway": { "name": "StorageGateway", "cors": true }, "sts": { "name": "STS", "cors": true }, "support": { "name": "Support" }, "swf": { "name": "SWF" }, "waf": { "name": "WAF", "cors": true }, "workspaces": { "name": "WorkSpaces" } } },{}],4:[function(require,module,exports){ module.exports={ "version": "2.0", "metadata": { "apiVersion": "2011-06-15", "endpointPrefix": "sts", "globalEndpoint": "sts.amazonaws.com", "protocol": "query", "serviceAbbreviation": "AWS STS", "serviceFullName": "AWS Security Token Service", "signatureVersion": "v4", "xmlNamespace": "https://sts.amazonaws.com/doc/2011-06-15/" }, "operations": { "AssumeRole": { "input": { "type": "structure", "required": [ "RoleArn", "RoleSessionName" ], "members": { "RoleArn": {}, "RoleSessionName": {}, "Policy": {}, "DurationSeconds": { "type": "integer" }, "ExternalId": {}, "SerialNumber": {}, "TokenCode": {} } }, "output": { "resultWrapper": "AssumeRoleResult", "type": "structure", "members": { "Credentials": { "shape": "Sa" }, "AssumedRoleUser": { "shape": "Sf" }, "PackedPolicySize": { "type": "integer" } } } }, "AssumeRoleWithSAML": { "input": { "type": "structure", "required": [ "RoleArn", "PrincipalArn", "SAMLAssertion" ], "members": { "RoleArn": {}, "PrincipalArn": {}, "SAMLAssertion": {}, "Policy": {}, "DurationSeconds": { "type": "integer" } } }, "output": { "resultWrapper": "AssumeRoleWithSAMLResult", "type": "structure", "members": { "Credentials": { "shape": "Sa" }, "AssumedRoleUser": { "shape": "Sf" }, "PackedPolicySize": { "type": "integer" }, "Subject": {}, "SubjectType": {}, "Issuer": {}, "Audience": {}, "NameQualifier": {} } } }, "AssumeRoleWithWebIdentity": { "input": { "type": "structure", "required": [ "RoleArn", "RoleSessionName", "WebIdentityToken" ], "members": { "RoleArn": {}, "RoleSessionName": {}, "WebIdentityToken": {}, "ProviderId": {}, "Policy": {}, "DurationSeconds": { "type": "integer" } } }, "output": { "resultWrapper": "AssumeRoleWithWebIdentityResult", "type": "structure", "members": { "Credentials": { "shape": "Sa" }, "SubjectFromWebIdentityToken": {}, "AssumedRoleUser": { "shape": "Sf" }, "PackedPolicySize": { "type": "integer" }, "Provider": {}, "Audience": {} } } }, "DecodeAuthorizationMessage": { "input": { "type": "structure", "required": [ "EncodedMessage" ], "members": { "EncodedMessage": {} } }, "output": { "resultWrapper": "DecodeAuthorizationMessageResult", "type": "structure", "members": { "DecodedMessage": {} } } }, "GetCallerIdentity": { "input": { "type": "structure", "members": {} }, "output": { "resultWrapper": "GetCallerIdentityResult", "type": "structure", "members": { "UserId": {}, "Account": {}, "Arn": {} } } }, "GetFederationToken": { "input": { "type": "structure", "required": [ "Name" ], "members": { "Name": {}, "Policy": {}, "DurationSeconds": { "type": "integer" } } }, "output": { "resultWrapper": "GetFederationTokenResult", "type": "structure", "members": { "Credentials": { "shape": "Sa" }, "FederatedUser": { "type": "structure", "required": [ "FederatedUserId", "Arn" ], "members": { "FederatedUserId": {}, "Arn": {} } }, "PackedPolicySize": { "type": "integer" } } } }, "GetSessionToken": { "input": { "type": "structure", "members": { "DurationSeconds": { "type": "integer" }, "SerialNumber": {}, "TokenCode": {} } }, "output": { "resultWrapper": "GetSessionTokenResult", "type": "structure", "members": { "Credentials": { "shape": "Sa" } } } } }, "shapes": { "Sa": { "type": "structure", "required": [ "AccessKeyId", "SecretAccessKey", "SessionToken", "Expiration" ], "members": { "AccessKeyId": {}, "SecretAccessKey": {}, "SessionToken": {}, "Expiration": { "type": "timestamp" } } }, "Sf": { "type": "structure", "required": [ "AssumedRoleId", "Arn" ], "members": { "AssumedRoleId": {}, "Arn": {} } } } } },{}],5:[function(require,module,exports){ require('../lib/node_loader'); var AWS = require('../lib/core'); var Service = require('../lib/service'); var apiLoader = require('../lib/api_loader'); apiLoader.services['cognitoidentity'] = {}; AWS.CognitoIdentity = Service.defineService('cognitoidentity', ['2014-06-30']); require('../lib/services/cognitoidentity'); Object.defineProperty(apiLoader.services['cognitoidentity'], '2014-06-30', { get: function get() { var model = require('../apis/cognito-identity-2014-06-30.min.json'); return model; }, enumerable: true, configurable: true }); module.exports = AWS.CognitoIdentity; },{"../apis/cognito-identity-2014-06-30.min.json":1,"../lib/api_loader":7,"../lib/core":11,"../lib/node_loader":9,"../lib/service":42,"../lib/services/cognitoidentity":43}],6:[function(require,module,exports){ require('../lib/node_loader'); var AWS = require('../lib/core'); var Service = require('../lib/service'); var apiLoader = require('../lib/api_loader'); apiLoader.services['sts'] = {}; AWS.STS = Service.defineService('sts', ['2011-06-15']); require('../lib/services/sts'); Object.defineProperty(apiLoader.services['sts'], '2011-06-15', { get: function get() { var model = require('../apis/sts-2011-06-15.min.json'); return model; }, enumerable: true, configurable: true }); module.exports = AWS.STS; },{"../apis/sts-2011-06-15.min.json":4,"../lib/api_loader":7,"../lib/core":11,"../lib/node_loader":9,"../lib/service":42,"../lib/services/sts":44}],7:[function(require,module,exports){ var AWS = require('./core'); AWS.apiLoader = function(svc, version) { if (!AWS.apiLoader.services.hasOwnProperty(svc)) { throw new Error('InvalidService: Failed to load api for ' + svc); } return AWS.apiLoader.services[svc][version]; }; AWS.apiLoader.services = {}; module.exports = AWS.apiLoader; },{"./core":11}],8:[function(require,module,exports){ require('./browser_loader'); var AWS = require('./core'); if (typeof window !== 'undefined') window.AWSCognito = AWS; if (typeof module !== 'undefined') module.exports = AWS; if (typeof self !== 'undefined') self.AWSCognito = AWS; if (!Object.prototype.hasOwnProperty.call(AWS, 'CognitoIdentityServiceProvider')) { AWS.apiLoader.services['cognitoidentityserviceprovider'] = {}; AWS.CognitoIdentityServiceProvider = AWS.Service.defineService('cognitoidentityserviceprovider', [ '2016-04-18' ]); } AWS.apiLoader.services['cognitoidentityserviceprovider']['2016-04-18'] = require('../apis/cognito-idp-2016-04-18.min'); if (!Object.prototype.hasOwnProperty.call(AWS, 'STS')) { AWS.apiLoader.services['sts'] = {}; AWS.STS = AWS.Service.defineService('sts', [ '2011-06-15' ]); require('./services/sts'); } AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.min'); },{"../apis/cognito-idp-2016-04-18.min":2,"../apis/sts-2011-06-15.min":4,"./browser_loader":9,"./core":11,"./services/sts":44}],9:[function(require,module,exports){ (function (process){ var util = require('./util'); util.crypto.lib = require('crypto-browserify'); util.Buffer = require('buffer/').Buffer; util.url = require('url/'); util.querystring = require('querystring/'); var AWS = require('./core'); require('./api_loader'); AWS.XML.Parser = require('./xml/browser_parser'); require('./http/xhr'); if (typeof process === 'undefined') { process = { browser: true }; } }).call(this,require("FWaASH")) },{"./api_loader":7,"./core":11,"./http/xhr":20,"./util":53,"./xml/browser_parser":54,"FWaASH":62,"buffer/":69,"crypto-browserify":74,"querystring/":82,"url/":83}],10:[function(require,module,exports){ var AWS = require('./core'); require('./credentials'); require('./credentials/credential_provider_chain'); AWS.Config = AWS.util.inherit({ constructor: function Config(options) { if (options === undefined) options = {}; options = this.extractCredentials(options); AWS.util.each.call(this, this.keys, function (key, value) { this.set(key, options[key], value); }); }, getCredentials: function getCredentials(callback) { var self = this; function finish(err) { callback(err, err ? null : self.credentials); } function credError(msg, err) { return new AWS.util.error(err || new Error(), { code: 'CredentialsError', message: msg }); } function getAsyncCredentials() { self.credentials.get(function(err) { if (err) { var msg = 'Could not load credentials from ' + self.credentials.constructor.name; err = credError(msg, err); } finish(err); }); } function getStaticCredentials() { var err = null; if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) { err = credError('Missing credentials'); } finish(err); } if (self.credentials) { if (typeof self.credentials.get === 'function') { getAsyncCredentials(); } else { // static credentials getStaticCredentials(); } } else if (self.credentialProvider) { self.credentialProvider.resolve(function(err, creds) { if (err) { err = credError('Could not load credentials from any providers', err); } self.credentials = creds; finish(err); }); } else { finish(credError('No credentials to load')); } }, update: function update(options, allowUnknownKeys) { allowUnknownKeys = allowUnknownKeys || false; options = this.extractCredentials(options); AWS.util.each.call(this, options, function (key, value) { if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) || AWS.Service.hasService(key)) { this.set(key, value); } }); }, loadFromPath: function loadFromPath(path) { this.clear(); var options = JSON.parse(AWS.util.readFileSync(path)); var fileSystemCreds = new AWS.FileSystemCredentials(path); var chain = new AWS.CredentialProviderChain(); chain.providers.unshift(fileSystemCreds); chain.resolve(function (err, creds) { if (err) throw err; else options.credentials = creds; }); this.constructor(options); return this; }, clear: function clear() { AWS.util.each.call(this, this.keys, function (key) { delete this[key]; }); this.set('credentials', undefined); this.set('credentialProvider', undefined); }, set: function set(property, value, defaultValue) { if (value === undefined) { if (defaultValue === undefined) { defaultValue = this.keys[property]; } if (typeof defaultValue === 'function') { this[property] = defaultValue.call(this); } else { this[property] = defaultValue; } } else if (property === 'httpOptions' && this[property]) { this[property] = AWS.util.merge(this[property], value); } else { this[property] = value; } }, keys: { credentials: null, credentialProvider: null, region: null, logger: null, apiVersions: {}, apiVersion: null, endpoint: undefined, httpOptions: { timeout: 120000 }, maxRetries: undefined, maxRedirects: 10, paramValidation: true, sslEnabled: true, s3ForcePathStyle: false, s3BucketEndpoint: false, s3DisableBodySigning: true, computeChecksums: true, convertResponseTypes: true, correctClockSkew: false, customUserAgent: null, dynamoDbCrc32: true, systemClockOffset: 0, signatureVersion: null, signatureCache: true, retryDelayOptions: { base: 100 }, useAccelerateEndpoint: false }, extractCredentials: function extractCredentials(options) { if (options.accessKeyId && options.secretAccessKey) { options = AWS.util.copy(options); options.credentials = new AWS.Credentials(options); } return options; }, setPromisesDependency: function setPromisesDependency(dep) { AWS.util.addPromisesToRequests(AWS.Request, dep); } }); AWS.config = new AWS.Config(); },{"./core":11,"./credentials":12,"./credentials/credential_provider_chain":14}],11:[function(require,module,exports){ var AWS = { util: require('./util') }; var _hidden = {}; _hidden.toString(); // hack to parse macro module.exports = AWS; AWS.util.update(AWS, { VERSION: '2.6.4', Signers: {}, Protocol: { Json: require('./protocol/json'), Query: require('./protocol/query'), Rest: require('./protocol/rest'), RestJson: require('./protocol/rest_json'), RestXml: require('./protocol/rest_xml') }, XML: { Builder: require('./xml/builder'), Parser: null // conditionally set based on environment }, JSON: { Builder: require('./json/builder'), Parser: require('./json/parser') }, Model: { Api: require('./model/api'), Operation: require('./model/operation'), Shape: require('./model/shape'), Paginator: require('./model/paginator'), ResourceWaiter: require('./model/resource_waiter') }, util: require('./util'), apiLoader: function() { throw new Error('No API loader set'); } }); require('./service'); require('./credentials'); require('./credentials/credential_provider_chain'); require('./credentials/temporary_credentials'); require('./credentials/web_identity_credentials'); require('./credentials/cognito_identity_credentials'); require('./credentials/saml_credentials'); require('./config'); require('./http'); require('./sequential_executor'); require('./event_listeners'); require('./request'); require('./response'); require('./resource_waiter'); require('./signers/request_signer'); require('./param_validator'); AWS.events = new AWS.SequentialExecutor(); },{"./config":10,"./credentials":12,"./credentials/cognito_identity_credentials":13,"./credentials/credential_provider_chain":14,"./credentials/saml_credentials":15,"./credentials/temporary_credentials":16,"./credentials/web_identity_credentials":17,"./event_listeners":18,"./http":19,"./json/builder":21,"./json/parser":22,"./model/api":23,"./model/operation":25,"./model/paginator":26,"./model/resource_waiter":27,"./model/shape":28,"./param_validator":29,"./protocol/json":30,"./protocol/query":31,"./protocol/rest":32,"./protocol/rest_json":33,"./protocol/rest_xml":34,"./request":38,"./resource_waiter":39,"./response":40,"./sequential_executor":41,"./service":42,"./signers/request_signer":46,"./util":53,"./xml/builder":55}],12:[function(require,module,exports){ var AWS = require('./core'); AWS.Credentials = AWS.util.inherit({ constructor: function Credentials() { AWS.util.hideProperties(this, ['secretAccessKey']); this.expired = false; this.expireTime = null; if (arguments.length === 1 && typeof arguments[0] === 'object') { var creds = arguments[0].credentials || arguments[0]; this.accessKeyId = creds.accessKeyId; this.secretAccessKey = creds.secretAccessKey; this.sessionToken = creds.sessionToken; } else { this.accessKeyId = arguments[0]; this.secretAccessKey = arguments[1]; this.sessionToken = arguments[2]; } }, expiryWindow: 15, needsRefresh: function needsRefresh() { var currentTime = AWS.util.date.getDate().getTime(); var adjustedTime = new Date(currentTime + this.expiryWindow * 1000); if (this.expireTime && adjustedTime > this.expireTime) { return true; } else { return this.expired || !this.accessKeyId || !this.secretAccessKey; } }, get: function get(callback) { var self = this; if (this.needsRefresh()) { this.refresh(function(err) { if (!err) self.expired = false; // reset expired flag if (callback) callback(err); }); } else if (callback) { callback(); } }, refresh: function refresh(callback) { this.expired = false; callback(); } }); },{"./core":11}],13:[function(require,module,exports){ var AWS = require('../core'); var CognitoIdentity = require('../../clients/cognitoidentity'); var STS = require('../../clients/sts'); AWS.CognitoIdentityCredentials = AWS.util.inherit(AWS.Credentials, { localStorageKey: { id: 'aws.cognito.identity-id.', providers: 'aws.cognito.identity-providers.' }, constructor: function CognitoIdentityCredentials(params) { AWS.Credentials.call(this); this.expired = true; this.params = params; this.data = null; this.identityId = null; this.loadCachedId(); }, refresh: function refresh(callback) { var self = this; self.createClients(); self.data = null; self.identityId = null; self.getId(function(err) { if (!err) { if (!self.params.RoleArn) { self.getCredentialsForIdentity(callback); } else { self.getCredentialsFromSTS(callback); } } else { self.clearIdOnNotAuthorized(err); callback(err); } }); }, clearCachedId: function clearCache() { this.identityId = null; delete this.params.IdentityId; var poolId = this.params.IdentityPoolId; var loginId = this.params.LoginId || ''; delete this.storage[this.localStorageKey.id + poolId + loginId]; delete this.storage[this.localStorageKey.providers + poolId + loginId]; }, clearIdOnNotAuthorized: function clearIdOnNotAuthorized(err) { var self = this; if (err.code == 'NotAuthorizedException') { self.clearCachedId(); } }, getId: function getId(callback) { var self = this; if (typeof self.params.IdentityId === 'string') { return callback(null, self.params.IdentityId); } self.cognito.getId(function(err, data) { if (!err && data.IdentityId) { self.params.IdentityId = data.IdentityId; callback(null, data.IdentityId); } else { callback(err); } }); }, loadCredentials: function loadCredentials(data, credentials) { if (!data || !credentials) return; credentials.expired = false; credentials.accessKeyId = data.Credentials.AccessKeyId; credentials.secretAccessKey = data.Credentials.SecretKey; credentials.sessionToken = data.Credentials.SessionToken; credentials.expireTime = data.Credentials.Expiration; }, getCredentialsForIdentity: function getCredentialsForIdentity(callback) { var self = this; self.cognito.getCredentialsForIdentity(function(err, data) { if (!err) { self.cacheId(data); self.data = data; self.loadCredentials(self.data, self); } else { self.clearIdOnNotAuthorized(err); } callback(err); }); }, getCredentialsFromSTS: function getCredentialsFromSTS(callback) { var self = this; self.cognito.getOpenIdToken(function(err, data) { if (!err) { self.cacheId(data); self.params.WebIdentityToken = data.Token; self.webIdentityCredentials.refresh(function(webErr) { if (!webErr) { self.data = self.webIdentityCredentials.data; self.sts.credentialsFrom(self.data, self); } callback(webErr); }); } else { self.clearIdOnNotAuthorized(err); callback(err); } }); }, loadCachedId: function loadCachedId() { var self = this; if (AWS.util.isBrowser() && !self.params.IdentityId) { var id = self.getStorage('id'); if (id && self.params.Logins) { var actualProviders = Object.keys(self.params.Logins); var cachedProviders = (self.getStorage('providers') || '').split(','); var intersect = cachedProviders.filter(function(n) { return actualProviders.indexOf(n) !== -1; }); if (intersect.length !== 0) { self.params.IdentityId = id; } } else if (id) { self.params.IdentityId = id; } } }, createClients: function() { this.webIdentityCredentials = this.webIdentityCredentials || new AWS.WebIdentityCredentials(this.params); this.cognito = this.cognito || new CognitoIdentity({params: this.params}); this.sts = this.sts || new STS(); }, cacheId: function cacheId(data) { this.identityId = data.IdentityId; this.params.IdentityId = this.identityId; if (AWS.util.isBrowser()) { this.setStorage('id', data.IdentityId); if (this.params.Logins) { this.setStorage('providers', Object.keys(this.params.Logins).join(',')); } } }, getStorage: function getStorage(key) { return this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')]; }, setStorage: function setStorage(key, val) { try { this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')] = val; } catch (_) {} }, storage: (function() { try { window.localStorage.setItem('aws.test-storage', 'foobar'); window.localStorage.removeItem('aws.test-storage'); return AWS.util.isBrowser() ? window.localStorage : {}; } catch (_) { return {}; } })() }); },{"../../clients/cognitoidentity":5,"../../clients/sts":6,"../core":11}],14:[function(require,module,exports){ var AWS = require('../core'); AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, { constructor: function CredentialProviderChain(providers) { if (providers) { this.providers = providers; } else { this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0); } }, resolve: function resolve(callback) { if (this.providers.length === 0) { callback(new Error('No providers')); return this; } var index = 0; var providers = this.providers.slice(0); function resolveNext(err, creds) { if ((!err && creds) || index === providers.length) { callback(err, creds); return; } var provider = providers[index++]; if (typeof provider === 'function') { creds = provider.call(); } else { creds = provider; } if (creds.get) { creds.get(function(getErr) { resolveNext(getErr, getErr ? null : creds); }); } else { resolveNext(null, creds); } } resolveNext(); return this; } }); AWS.CredentialProviderChain.defaultProviders = []; },{"../core":11}],15:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); AWS.SAMLCredentials = AWS.util.inherit(AWS.Credentials, { constructor: function SAMLCredentials(params) { AWS.Credentials.call(this); this.expired = true; this.params = params; }, refresh: function refresh(callback) { var self = this; self.createClients(); if (!callback) callback = function(err) { if (err) throw err; }; self.service.assumeRoleWithSAML(function (err, data) { if (!err) { self.service.credentialsFrom(data, self); } callback(err); }); }, createClients: function() { this.service = this.service || new STS({params: this.params}); } }); },{"../../clients/sts":6,"../core":11}],16:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); AWS.TemporaryCredentials = AWS.util.inherit(AWS.Credentials, { constructor: function TemporaryCredentials(params) { AWS.Credentials.call(this); this.loadMasterCredentials(); this.expired = true; this.params = params || {}; if (this.params.RoleArn) { this.params.RoleSessionName = this.params.RoleSessionName || 'temporary-credentials'; } }, refresh: function refresh(callback) { var self = this; self.createClients(); if (!callback) callback = function(err) { if (err) throw err; }; self.service.config.credentials = self.masterCredentials; var operation = self.params.RoleArn ? self.service.assumeRole : self.service.getSessionToken; operation.call(self.service, function (err, data) { if (!err) { self.service.credentialsFrom(data, self); } callback(err); }); }, loadMasterCredentials: function loadMasterCredentials() { this.masterCredentials = AWS.config.credentials; while (this.masterCredentials.masterCredentials) { this.masterCredentials = this.masterCredentials.masterCredentials; } }, createClients: function() { this.service = this.service || new STS({params: this.params}); } }); },{"../../clients/sts":6,"../core":11}],17:[function(require,module,exports){ var AWS = require('../core'); var STS = require('../../clients/sts'); AWS.WebIdentityCredentials = AWS.util.inherit(AWS.Credentials, { constructor: function WebIdentityCredentials(params) { AWS.Credentials.call(this); this.expired = true; this.params = params; this.params.RoleSessionName = this.params.RoleSessionName || 'web-identity'; this.data = null; }, refresh: function refresh(callback) { var self = this; self.createClients(); if (!callback) callback = function(err) { if (err) throw err; }; self.service.assumeRoleWithWebIdentity(function (err, data) { self.data = null; if (!err) { self.data = data; self.service.credentialsFrom(data, self); } callback(err); }); }, createClients: function() { this.service = this.service || new STS({params: this.params}); } }); },{"../../clients/sts":6,"../core":11}],18:[function(require,module,exports){ var AWS = require('./core'); var SequentialExecutor = require('./sequential_executor'); AWS.EventListeners = { Core: {} /* doc hack */ }; AWS.EventListeners = { Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) { addAsync('VALIDATE_CREDENTIALS', 'validate', function VALIDATE_CREDENTIALS(req, done) { if (!req.service.api.signatureVersion) return done(); // none req.service.config.getCredentials(function(err) { if (err) { req.response.error = AWS.util.error(err, {code: 'CredentialsError', message: 'Missing credentials in config'}); } done(); }); }); add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) { if (!req.service.config.region && !req.service.isGlobalEndpoint) { req.response.error = AWS.util.error(new Error(), {code: 'ConfigError', message: 'Missing region in config'}); } }); add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) { var rules = req.service.api.operations[req.operation].input; var validation = req.service.config.paramValidation; new AWS.ParamValidator(validation).validate(rules, req.params); }); addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) { req.haltHandlersOnError(); if (!req.service.api.signatureVersion) return done(); // none if (req.service.getSignerClass(req) === AWS.Signers.V4) { var body = req.httpRequest.body || ''; AWS.util.computeSha256(body, function(err, sha) { if (err) { done(err); } else { req.httpRequest.headers['X-Amz-Content-Sha256'] = sha; done(); } }); } else { done(); } }); add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) { if (req.httpRequest.headers['Content-Length'] === undefined) { var length = AWS.util.string.byteLength(req.httpRequest.body); req.httpRequest.headers['Content-Length'] = length; } }); add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) { req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host; }); add('RESTART', 'restart', function RESTART() { var err = this.response.error; if (!err || !err.retryable) return; this.httpRequest = new AWS.HttpRequest( this.service.endpoint, this.service.region ); if (this.response.retryCount < this.service.config.maxRetries) { this.response.retryCount++; } else { this.response.error = null; } }); addAsync('SIGN', 'sign', function SIGN(req, done) { var service = req.service; if (!service.api.signatureVersion) return done(); // none service.config.getCredentials(function (err, credentials) { if (err) { req.response.error = err; return done(); } try { var date = AWS.util.date.getDate(); var SignerClass = service.getSignerClass(req); var signer = new SignerClass(req.httpRequest, service.api.signingName || service.api.endpointPrefix, service.config.signatureCache); signer.setServiceClientId(service._clientId); delete req.httpRequest.headers['Authorization']; delete req.httpRequest.headers['Date']; delete req.httpRequest.headers['X-Amz-Date']; signer.addAuthorization(credentials, date); req.signedAt = date; } catch (e) { req.response.error = e; } done(); }); }); add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) { if (this.service.successfulResponse(resp, this)) { resp.data = {}; resp.error = null; } else { resp.data = null; resp.error = AWS.util.error(new Error(), {code: 'UnknownError', message: 'An unknown error occurred.'}); } }); addAsync('SEND', 'send', function SEND(resp, done) { resp.httpResponse._abortCallback = done; resp.error = null; resp.data = null; function callback(httpResp) { resp.httpResponse.stream = httpResp; httpResp.on('headers', function onHeaders(statusCode, headers) { resp.request.emit('httpHeaders', [statusCode, headers, resp]); if (!resp.httpResponse.streaming) { if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check httpResp.on('readable', function onReadable() { var data = httpResp.read(); if (data !== null) { resp.request.emit('httpData', [data, resp]); } }); } else { // legacy streams API httpResp.on('data', function onData(data) { resp.request.emit('httpData', [data, resp]); }); } } }); httpResp.on('end', function onEnd() { resp.request.emit('httpDone'); done(); }); } function progress(httpResp) { httpResp.on('sendProgress', function onSendProgress(value) { resp.request.emit('httpUploadProgress', [value, resp]); }); httpResp.on('receiveProgress', function onReceiveProgress(value) { resp.request.emit('httpDownloadProgress', [value, resp]); }); } function error(err) { resp.error = AWS.util.error(err, { code: 'NetworkingError', region: resp.request.httpRequest.region, hostname: resp.request.httpRequest.endpoint.hostname, retryable: true }); resp.request.emit('httpError', [resp.error, resp], function() { done(); }); } function executeSend() { var http = AWS.HttpClient.getInstance(); var httpOptions = resp.request.service.config.httpOptions || {}; try { var stream = http.handleRequest(resp.request.httpRequest, httpOptions, callback, error); progress(stream); } catch (err) { error(err); } } var timeDiff = (AWS.util.date.getDate() - this.signedAt) / 1000; if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign this.emit('sign', [this], function(err) { if (err) done(err); else executeSend(); }); } else { executeSend(); } }); add('HTTP_HEADERS', 'httpHeaders', function HTTP_HEADERS(statusCode, headers, resp) { resp.httpResponse.statusCode = statusCode; resp.httpResponse.headers = headers; resp.httpResponse.body = new AWS.util.Buffer(''); resp.httpResponse.buffers = []; resp.httpResponse.numBytes = 0; var dateHeader = headers.date || headers.Date; if (dateHeader) { var serverTime = Date.parse(dateHeader); if (resp.request.service.config.correctClockSkew && AWS.util.isClockSkewed(serverTime)) { AWS.util.applyClockOffset(serverTime); } } }); add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) { if (chunk) { if (AWS.util.isNode()) { resp.httpResponse.numBytes += chunk.length; var total = resp.httpResponse.headers['content-length']; var progress = { loaded: resp.httpResponse.numBytes, total: total }; resp.request.emit('httpDownloadProgress', [progress, resp]); } resp.httpResponse.buffers.push(new AWS.util.Buffer(chunk)); } }); add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) { if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) { var body = AWS.util.buffer.concat(resp.httpResponse.buffers); resp.httpResponse.body = body; } delete resp.httpResponse.numBytes; delete resp.httpResponse.buffers; }); add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) { if (resp.httpResponse.statusCode) { resp.error.statusCode = resp.httpResponse.statusCode; if (resp.error.retryable === undefined) { resp.error.retryable = this.service.retryableError(resp.error, this); } } }); add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) { if (!resp.error) return; switch (resp.error.code) { case 'RequestExpired': // EC2 only case 'ExpiredTokenException': case 'ExpiredToken': resp.error.retryable = true; resp.request.service.config.credentials.expired = true; } }); add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) { var err = resp.error; if (!err) return; if (typeof err.code === 'string' && typeof err.message === 'string') { if (err.code.match(/Signature/) && err.message.match(/expired/)) { resp.error.retryable = true; } } }); add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) { if (!resp.error) return; if (this.service.clockSkewError(resp.error) && this.service.config.correctClockSkew && AWS.config.isClockSkewed) { resp.error.retryable = true; } }); add('REDIRECT', 'retry', function REDIRECT(resp) { if (resp.error && resp.error.statusCode >= 300 && resp.error.statusCode < 400 && resp.httpResponse.headers['location']) { this.httpRequest.endpoint = new AWS.Endpoint(resp.httpResponse.headers['location']); this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host; resp.error.redirect = true; resp.error.retryable = true; } }); add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) { if (resp.error) { if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) { resp.error.retryDelay = 0; } else if (resp.retryCount < resp.maxRetries) { resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0; } } }); addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) { var delay, willRetry = false; if (resp.error) { delay = resp.error.retryDelay || 0; if (resp.error.retryable && resp.retryCount < resp.maxRetries) { resp.retryCount++; willRetry = true; } else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) { resp.redirectCount++; willRetry = true; } } if (willRetry) { resp.error = null; setTimeout(done, delay); } else { done(); } }); }), CorePost: new SequentialExecutor().addNamedListeners(function(add) { add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId); add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId); add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) { if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') { var message = 'Inaccessible host: `' + err.hostname + '\'. This service may not be available in the `' + err.region + '\' region.'; this.response.error = AWS.util.error(new Error(message), { code: 'UnknownEndpoint', region: err.region, hostname: err.hostname, retryable: true, originalError: err }); } }); }), Logger: new SequentialExecutor().addNamedListeners(function(add) { add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) { var req = resp.request; var logger = req.service.config.logger; if (!logger) return; function buildMessage() { var time = AWS.util.date.getDate().getTime(); var delta = (time - req.startTime.getTime()) / 1000; var ansi = logger.isTTY ? true : false; var status = resp.httpResponse.statusCode; var params = require('util').inspect(req.params, true, null); var message = ''; if (ansi) message += '\x1B[33m'; message += '[AWS ' + req.service.serviceIdentifier + ' ' + status; message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]'; if (ansi) message += '\x1B[0;1m'; message += ' ' + AWS.util.string.lowerFirst(req.operation); message += '(' + params + ')'; if (ansi) message += '\x1B[0m'; return message; } var line = buildMessage(); if (typeof logger.log === 'function') { logger.log(line); } else if (typeof logger.write === 'function') { logger.write(line + '\n'); } }); }), Json: new SequentialExecutor().addNamedListeners(function(add) { var svc = require('./protocol/json'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), Rest: new SequentialExecutor().addNamedListeners(function(add) { var svc = require('./protocol/rest'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), RestJson: new SequentialExecutor().addNamedListeners(function(add) { var svc = require('./protocol/rest_json'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), RestXml: new SequentialExecutor().addNamedListeners(function(add) { var svc = require('./protocol/rest_xml'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), Query: new SequentialExecutor().addNamedListeners(function(add) { var svc = require('./protocol/query'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }) }; },{"./core":11,"./protocol/json":30,"./protocol/query":31,"./protocol/rest":32,"./protocol/rest_json":33,"./protocol/rest_xml":34,"./sequential_executor":41,"util":68}],19:[function(require,module,exports){ var AWS = require('./core'); var inherit = AWS.util.inherit; AWS.Endpoint = inherit({ constructor: function Endpoint(endpoint, config) { AWS.util.hideProperties(this, ['slashes', 'auth', 'hash', 'search', 'query']); if (typeof endpoint === 'undefined' || endpoint === null) { throw new Error('Invalid endpoint: ' + endpoint); } else if (typeof endpoint !== 'string') { return AWS.util.copy(endpoint); } if (!endpoint.match(/^http/)) { var useSSL = config && config.sslEnabled !== undefined ? config.sslEnabled : AWS.config.sslEnabled; endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint; } AWS.util.update(this, AWS.util.urlParse(endpoint)); if (this.port) { this.port = parseInt(this.port, 10); } else { this.port = this.protocol === 'https:' ? 443 : 80; } } }); AWS.HttpRequest = inherit({ constructor: function HttpRequest(endpoint, region, customUserAgent) { endpoint = new AWS.Endpoint(endpoint); this.method = 'POST'; this.path = endpoint.path || '/'; this.headers = {}; this.body = ''; this.endpoint = endpoint; this.region = region; this.setUserAgent(customUserAgent); }, setUserAgent: function setUserAgent(customUserAgent) { var prefix = AWS.util.isBrowser() ? 'X-Amz-' : ''; var customSuffix = ''; if (typeof customUserAgent === 'string' && customUserAgent) { customSuffix += ' ' + customUserAgent; } this.headers[prefix + 'User-Agent'] = AWS.util.userAgent() + customSuffix; }, pathname: function pathname() { return this.path.split('?', 1)[0]; }, search: function search() { var query = this.path.split('?', 2)[1]; if (query) { query = AWS.util.queryStringParse(query); return AWS.util.queryParamsToString(query); } return ''; } }); AWS.HttpResponse = inherit({ constructor: function HttpResponse() { this.statusCode = undefined; this.headers = {}; this.body = undefined; this.streaming = false; this.stream = null; }, createUnbufferedStream: function createUnbufferedStream() { this.streaming = true; return this.stream; } }); AWS.HttpClient = inherit({}); AWS.HttpClient.getInstance = function getInstance() { if (this.singleton === undefined) { this.singleton = new this(); } return this.singleton; }; },{"./core":11}],20:[function(require,module,exports){ var AWS = require('../core'); var EventEmitter = require('events').EventEmitter; require('../http'); AWS.XHRClient = AWS.util.inherit({ handleRequest: function handleRequest(httpRequest, httpOptions, callback, errCallback) { var self = this; var endpoint = httpRequest.endpoint; var emitter = new EventEmitter(); var href = endpoint.protocol + '//' + endpoint.hostname; if (endpoint.port !== 80 && endpoint.port !== 443) { href += ':' + endpoint.port; } href += httpRequest.path; var xhr = new XMLHttpRequest(), headersEmitted = false; httpRequest.stream = xhr; xhr.addEventListener('readystatechange', function() { try { if (xhr.status === 0) return; // 0 code is invalid } catch (e) { return; } if (this.readyState >= this.HEADERS_RECEIVED && !headersEmitted) { try { xhr.responseType = 'arraybuffer'; } catch (e) {} emitter.statusCode = xhr.status; emitter.headers = self.parseHeaders(xhr.getAllResponseHeaders()); emitter.emit('headers', emitter.statusCode, emitter.headers); headersEmitted = true; } if (this.readyState === this.DONE) { self.finishRequest(xhr, emitter); } }, false); xhr.upload.addEventListener('progress', function (evt) { emitter.emit('sendProgress', evt); }); xhr.addEventListener('progress', function (evt) { emitter.emit('receiveProgress', evt); }, false); xhr.addEventListener('timeout', function () { errCallback(AWS.util.error(new Error('Timeout'), {code: 'TimeoutError'})); }, false); xhr.addEventListener('error', function () { errCallback(AWS.util.error(new Error('Network Failure'), { code: 'NetworkingError' })); }, false); callback(emitter); xhr.open(httpRequest.method, href, httpOptions.xhrAsync !== false); AWS.util.each(httpRequest.headers, function (key, value) { if (key !== 'Content-Length' && key !== 'User-Agent' && key !== 'Host') { xhr.setRequestHeader(key, value); } }); if (httpOptions.timeout && httpOptions.xhrAsync !== false) { xhr.timeout = httpOptions.timeout; } if (httpOptions.xhrWithCredentials) { xhr.withCredentials = true; } try { xhr.send(httpRequest.body); } catch (err) { if (httpRequest.body && typeof httpRequest.body.buffer === 'object') { xhr.send(httpRequest.body.buffer); // send ArrayBuffer directly } else { throw err; } } return emitter; }, parseHeaders: function parseHeaders(rawHeaders) { var headers = {}; AWS.util.arrayEach(rawHeaders.split(/\r?\n/), function (line) { var key = line.split(':', 1)[0]; var value = line.substring(key.length + 2); if (key.length > 0) headers[key.toLowerCase()] = value; }); return headers; }, finishRequest: function finishRequest(xhr, emitter) { var buffer; if (xhr.responseType === 'arraybuffer' && xhr.response) { var ab = xhr.response; buffer = new AWS.util.Buffer(ab.byteLength); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } } try { if (!buffer && typeof xhr.responseText === 'string') { buffer = new AWS.util.Buffer(xhr.responseText); } } catch (e) {} if (buffer) emitter.emit('data', buffer); emitter.emit('end'); } }); AWS.HttpClient.prototype = AWS.XHRClient.prototype; AWS.HttpClient.streamsApiVersion = 1; },{"../core":11,"../http":19,"events":60}],21:[function(require,module,exports){ var util = require('../util'); function JsonBuilder() { } JsonBuilder.prototype.build = function(value, shape) { return JSON.stringify(translate(value, shape)); }; function translate(value, shape) { if (!shape || value === undefined || value === null) return undefined; switch (shape.type) { case 'structure': return translateStructure(value, shape); case 'map': return translateMap(value, shape); case 'list': return translateList(value, shape); default: return translateScalar(value, shape); } } function translateStructure(structure, shape) { var struct = {}; util.each(structure, function(name, value) { var memberShape = shape.members[name]; if (memberShape) { if (memberShape.location !== 'body') return; var locationName = memberShape.isLocationName ? memberShape.name : name; var result = translate(value, memberShape); if (result !== undefined) struct[locationName] = result; } }); return struct; } function translateList(list, shape) { var out = []; util.arrayEach(list, function(value) { var result = translate(value, shape.member); if (result !== undefined) out.push(result); }); return out; } function translateMap(map, shape) { var out = {}; util.each(map, function(key, value) { var result = translate(value, shape.value); if (result !== undefined) out[key] = result; }); return out; } function translateScalar(value, shape) { return shape.toWireFormat(value); } module.exports = JsonBuilder; },{"../util":53}],22:[function(require,module,exports){ var util = require('../util'); function JsonParser() { } JsonParser.prototype.parse = function(value, shape) { return translate(JSON.parse(value), shape); }; function translate(value, shape) { if (!shape || value === undefined) return undefined; switch (shape.type) { case 'structure': return translateStructure(value, shape); case 'map': return translateMap(value, shape); case 'list': return translateList(value, shape); default: return translateScalar(value, shape); } } function translateStructure(structure, shape) { if (structure == null) return undefined; var struct = {}; var shapeMembers = shape.members; util.each(shapeMembers, function(name, memberShape) { var locationName = memberShape.isLocationName ? memberShape.name : name; if (Object.prototype.hasOwnProperty.call(structure, locationName)) { var value = structure[locationName]; var result = translate(value, memberShape); if (result !== undefined) struct[name] = result; } }); return struct; } function translateList(list, shape) { if (list == null) return undefined; var out = []; util.arrayEach(list, function(value) { var result = translate(value, shape.member); if (result === undefined) out.push(null); else out.push(result); }); return out; } function translateMap(map, shape) { if (map == null) return undefined; var out = {}; util.each(map, function(key, value) { var result = translate(value, shape.value); if (result === undefined) out[key] = null; else out[key] = result; }); return out; } function translateScalar(value, shape) { return shape.toType(value); } module.exports = JsonParser; },{"../util":53}],23:[function(require,module,exports){ var Collection = require('./collection'); var Operation = require('./operation'); var Shape = require('./shape'); var Paginator = require('./paginator'); var ResourceWaiter = require('./resource_waiter'); var util = require('../util'); var property = util.property; var memoizedProperty = util.memoizedProperty; function Api(api, options) { api = api || {}; options = options || {}; options.api = this; api.metadata = api.metadata || {}; property(this, 'isApi', true, false); property(this, 'apiVersion', api.metadata.apiVersion); property(this, 'endpointPrefix', api.metadata.endpointPrefix); property(this, 'signingName', api.metadata.signingName); property(this, 'globalEndpoint', api.metadata.globalEndpoint); property(this, 'signatureVersion', api.metadata.signatureVersion); property(this, 'jsonVersion', api.metadata.jsonVersion); property(this, 'targetPrefix', api.metadata.targetPrefix); property(this, 'protocol', api.metadata.protocol); property(this, 'timestampFormat', api.metadata.timestampFormat); property(this, 'xmlNamespaceUri', api.metadata.xmlNamespace); property(this, 'abbreviation', api.metadata.serviceAbbreviation); property(this, 'fullName', api.metadata.serviceFullName); memoizedProperty(this, 'className', function() { var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName; if (!name) return null; name = name.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, ''); if (name === 'ElasticLoadBalancing') name = 'ELB'; return name; }); property(this, 'operations', new Collection(api.operations, options, function(name, operation) { return new Operation(name, operation, options); }, util.string.lowerFirst)); property(this, 'shapes', new Collection(api.shapes, options, function(name, shape) { return Shape.create(shape, options); })); property(this, 'paginators', new Collection(api.paginators, options, function(name, paginator) { return new Paginator(name, paginator, options); })); property(this, 'waiters', new Collection(api.waiters, options, function(name, waiter) { return new ResourceWaiter(name, waiter, options); }, util.string.lowerFirst)); if (options.documentation) { property(this, 'documentation', api.documentation); property(this, 'documentationUrl', api.documentationUrl); } } module.exports = Api; },{"../util":53,"./collection":24,"./operation":25,"./paginator":26,"./resource_waiter":27,"./shape":28}],24:[function(require,module,exports){ var memoizedProperty = require('../util').memoizedProperty; function memoize(name, value, fn, nameTr) { memoizedProperty(this, nameTr(name), function() { return fn(name, value); }); } function Collection(iterable, options, fn, nameTr) { nameTr = nameTr || String; var self = this; for (var id in iterable) { if (Object.prototype.hasOwnProperty.call(iterable, id)) { memoize.call(self, id, iterable[id], fn, nameTr); } } } module.exports = Collection; },{"../util":53}],25:[function(require,module,exports){ var Shape = require('./shape'); var util = require('../util'); var property = util.property; var memoizedProperty = util.memoizedProperty; function Operation(name, operation, options) { options = options || {}; property(this, 'name', operation.name || name); property(this, 'api', options.api, false); operation.http = operation.http || {}; property(this, 'httpMethod', operation.http.method || 'POST'); property(this, 'httpPath', operation.http.requestUri || '/'); property(this, 'authtype', operation.authtype || ''); memoizedProperty(this, 'input', function() { if (!operation.input) { return new Shape.create({type: 'structure'}, options); } return Shape.create(operation.input, options); }); memoizedProperty(this, 'output', function() { if (!operation.output) { return new Shape.create({type: 'structure'}, options); } return Shape.create(operation.output, options); }); memoizedProperty(this, 'errors', function() { var list = []; if (!operation.errors) return null; for (var i = 0; i < operation.errors.length; i++) { list.push(Shape.create(operation.errors[i], options)); } return list; }); memoizedProperty(this, 'paginator', function() { return options.api.paginators[name]; }); if (options.documentation) { property(this, 'documentation', operation.documentation); property(this, 'documentationUrl', operation.documentationUrl); } } module.exports = Operation; },{"../util":53,"./shape":28}],26:[function(require,module,exports){ var property = require('../util').property; function Paginator(name, paginator) { property(this, 'inputToken', paginator.input_token); property(this, 'limitKey', paginator.limit_key); property(this, 'moreResults', paginator.more_results); property(this, 'outputToken', paginator.output_token); property(this, 'resultKey', paginator.result_key); } module.exports = Paginator; },{"../util":53}],27:[function(require,module,exports){ var util = require('../util'); var property = util.property; function ResourceWaiter(name, waiter, options) { options = options || {}; property(this, 'name', name); property(this, 'api', options.api, false); if (waiter.operation) { property(this, 'operation', util.string.lowerFirst(waiter.operation)); } var self = this; var keys = [ 'type', 'description', 'delay', 'maxAttempts', 'acceptors' ]; keys.forEach(function(key) { var value = waiter[key]; if (value) { property(self, key, value); } }); } module.exports = ResourceWaiter; },{"../util":53}],28:[function(require,module,exports){ var Collection = require('./collection'); var util = require('../util'); function property(obj, name, value) { if (value !== null && value !== undefined) { util.property.apply(this, arguments); } } function memoizedProperty(obj, name) { if (!obj.constructor.prototype[name]) { util.memoizedProperty.apply(this, arguments); } } function Shape(shape, options, memberName) { options = options || {}; property(this, 'shape', shape.shape); property(this, 'api', options.api, false); property(this, 'type', shape.type); property(this, 'enum', shape.enum); property(this, 'min', shape.min); property(this, 'max', shape.max); property(this, 'pattern', shape.pattern); property(this, 'location', shape.location || this.location || 'body'); property(this, 'name', this.name || shape.xmlName || shape.queryName || shape.locationName || memberName); property(this, 'isStreaming', shape.streaming || this.isStreaming || false); property(this, 'isComposite', shape.isComposite || false); property(this, 'isShape', true, false); property(this, 'isQueryName', shape.queryName ? true : false, false); property(this, 'isLocationName', shape.locationName ? true : false, false); if (options.documentation) { property(this, 'documentation', shape.documentation); property(this, 'documentationUrl', shape.documentationUrl); } if (shape.xmlAttribute) { property(this, 'isXmlAttribute', shape.xmlAttribute || false); } property(this, 'defaultValue', null); this.toWireFormat = function(value) { if (value === null || value === undefined) return ''; return value; }; this.toType = function(value) { return value; }; } Shape.normalizedTypes = { character: 'string', double: 'float', long: 'integer', short: 'integer', biginteger: 'integer', bigdecimal: 'float', blob: 'binary' }; Shape.types = { 'structure': StructureShape, 'list': ListShape, 'map': MapShape, 'boolean': BooleanShape, 'timestamp': TimestampShape, 'float': FloatShape, 'integer': IntegerShape, 'string': StringShape, 'base64': Base64Shape, 'binary': BinaryShape }; Shape.resolve = function resolve(shape, options) { if (shape.shape) { var refShape = options.api.shapes[shape.shape]; if (!refShape) { throw new Error('Cannot find shape reference: ' + shape.shape); } return refShape; } else { return null; } }; Shape.create = function create(shape, options, memberName) { if (shape.isShape) return shape; var refShape = Shape.resolve(shape, options); if (refShape) { var filteredKeys = Object.keys(shape); if (!options.documentation) { filteredKeys = filteredKeys.filter(function(name) { return !name.match(/documentation/); }); } if (filteredKeys === ['shape']) { // no inline customizations return refShape; } var InlineShape = function() { refShape.constructor.call(this, shape, options, memberName); }; InlineShape.prototype = refShape; return new InlineShape(); } else { if (!shape.type) { if (shape.members) shape.type = 'structure'; else if (shape.member) shape.type = 'list'; else if (shape.key) shape.type = 'map'; else shape.type = 'string'; } var origType = shape.type; if (Shape.normalizedTypes[shape.type]) { shape.type = Shape.normalizedTypes[shape.type]; } if (Shape.types[shape.type]) { return new Shape.types[shape.type](shape, options, memberName); } else { throw new Error('Unrecognized shape type: ' + origType); } } }; function CompositeShape(shape) { Shape.apply(this, arguments); property(this, 'isComposite', true); if (shape.flattened) { property(this, 'flattened', shape.flattened || false); } } function StructureShape(shape, options) { var requiredMap = null, firstInit = !this.isShape; CompositeShape.apply(this, arguments); if (firstInit) { property(this, 'defaultValue', function() { return {}; }); property(this, 'members', {}); property(this, 'memberNames', []); property(this, 'required', []); property(this, 'isRequired', function() { return false; }); } if (shape.members) { property(this, 'members', new Collection(shape.members, options, function(name, member) { return Shape.create(member, options, name); })); memoizedProperty(this, 'memberNames', function() { return shape.xmlOrder || Object.keys(shape.members); }); } if (shape.required) { property(this, 'required', shape.required); property(this, 'isRequired', function(name) { if (!requiredMap) { requiredMap = {}; for (var i = 0; i < shape.required.length; i++) { requiredMap[shape.required[i]] = true; } } return requiredMap[name]; }, false, true); } property(this, 'resultWrapper', shape.resultWrapper || null); if (shape.payload) { property(this, 'payload', shape.payload); } if (typeof shape.xmlNamespace === 'string') { property(this, 'xmlNamespaceUri', shape.xmlNamespace); } else if (typeof shape.xmlNamespace === 'object') { property(this, 'xmlNamespacePrefix', shape.xmlNamespace.prefix); property(this, 'xmlNamespaceUri', shape.xmlNamespace.uri); } } function ListShape(shape, options) { var self = this, firstInit = !this.isShape; CompositeShape.apply(this, arguments); if (firstInit) { property(this, 'defaultValue', function() { return []; }); } if (shape.member) { memoizedProperty(this, 'member', function() { return Shape.create(shape.member, options); }); } if (this.flattened) { var oldName = this.name; memoizedProperty(this, 'name', function() { return self.member.name || oldName; }); } } function MapShape(shape, options) { var firstInit = !this.isShape; CompositeShape.apply(this, arguments); if (firstInit) { property(this, 'defaultValue', function() { return {}; }); property(this, 'key', Shape.create({type: 'string'}, options)); property(this, 'value', Shape.create({type: 'string'}, options)); } if (shape.key) { memoizedProperty(this, 'key', function() { return Shape.create(shape.key, options); }); } if (shape.value) { memoizedProperty(this, 'value', function() { return Shape.create(shape.value, options); }); } } function TimestampShape(shape) { var self = this; Shape.apply(this, arguments); if (this.location === 'header') { property(this, 'timestampFormat', 'rfc822'); } else if (shape.timestampFormat) { property(this, 'timestampFormat', shape.timestampFormat); } else if (this.api) { if (this.api.timestampFormat) { property(this, 'timestampFormat', this.api.timestampFormat); } else { switch (this.api.protocol) { case 'json': case 'rest-json': property(this, 'timestampFormat', 'unixTimestamp'); break; case 'rest-xml': case 'query': case 'ec2': property(this, 'timestampFormat', 'iso8601'); break; } } } this.toType = function(value) { if (value === null || value === undefined) return null; if (typeof value.toUTCString === 'function') return value; return typeof value === 'string' || typeof value === 'number' ? util.date.parseTimestamp(value) : null; }; this.toWireFormat = function(value) { return util.date.format(value, self.timestampFormat); }; } function StringShape() { Shape.apply(this, arguments); if (this.api) { switch (this.api.protocol) { case 'rest-xml': case 'query': case 'ec2': this.toType = function(value) { return value || ''; }; } } } function FloatShape() { Shape.apply(this, arguments); this.toType = function(value) { if (value === null || value === undefined) return null; return parseFloat(value); }; this.toWireFormat = this.toType; } function IntegerShape() { Shape.apply(this, arguments); this.toType = function(value) { if (value === null || value === undefined) return null; return parseInt(value, 10); }; this.toWireFormat = this.toType; } function BinaryShape() { Shape.apply(this, arguments); this.toType = util.base64.decode; this.toWireFormat = util.base64.encode; } function Base64Shape() { BinaryShape.apply(this, arguments); } function BooleanShape() { Shape.apply(this, arguments); this.toType = function(value) { if (typeof value === 'boolean') return value; if (value === null || value === undefined) return null; return value === 'true'; }; } Shape.shapes = { StructureShape: StructureShape, ListShape: ListShape, MapShape: MapShape, StringShape: StringShape, BooleanShape: BooleanShape, Base64Shape: Base64Shape }; module.exports = Shape; },{"../util":53,"./collection":24}],29:[function(require,module,exports){ var AWS = require('./core'); AWS.ParamValidator = AWS.util.inherit({ constructor: function ParamValidator(validation) { if (validation === true || validation === undefined) { validation = {'min': true}; } this.validation = validation; }, validate: function validate(shape, params, context) { this.errors = []; this.validateMember(shape, params || {}, context || 'params'); if (this.errors.length > 1) { var msg = this.errors.join('\n* '); msg = 'There were ' + this.errors.length + ' validation errors:\n* ' + msg; throw AWS.util.error(new Error(msg), {code: 'MultipleValidationErrors', errors: this.errors}); } else if (this.errors.length === 1) { throw this.errors[0]; } else { return true; } }, fail: function fail(code, message) { this.errors.push(AWS.util.error(new Error(message), {code: code})); }, validateStructure: function validateStructure(shape, params, context) { this.validateType(params, context, ['object'], 'structure'); var paramName; for (var i = 0; shape.required && i < shape.required.length; i++) { paramName = shape.required[i]; var value = params[paramName]; if (value === undefined || value === null) { this.fail('MissingRequiredParameter', 'Missing required key \'' + paramName + '\' in ' + context); } } for (paramName in params) { if (!Object.prototype.hasOwnProperty.call(params, paramName)) continue; var paramValue = params[paramName], memberShape = shape.members[paramName]; if (memberShape !== undefined) { var memberContext = [context, paramName].join('.'); this.validateMember(memberShape, paramValue, memberContext); } else { this.fail('UnexpectedParameter', 'Unexpected key \'' + paramName + '\' found in ' + context); } } return true; }, validateMember: function validateMember(shape, param, context) { switch (shape.type) { case 'structure': return this.validateStructure(shape, param, context); case 'list': return this.validateList(shape, param, context); case 'map': return this.validateMap(shape, param, context); default: return this.validateScalar(shape, param, context); } }, validateList: function validateList(shape, params, context) { if (this.validateType(params, context, [Array])) { this.validateRange(shape, params.length, context, 'list member count'); for (var i = 0; i < params.length; i++) { this.validateMember(shape.member, params[i], context + '[' + i + ']'); } } }, validateMap: function validateMap(shape, params, context) { if (this.validateType(params, context, ['object'], 'map')) { var mapCount = 0; for (var param in params) { if (!Object.prototype.hasOwnProperty.call(params, param)) continue; this.validateMember(shape.key, param, context + '[key=\'' + param + '\']') this.validateMember(shape.value, params[param], context + '[\'' + param + '\']'); mapCount++; } this.validateRange(shape, mapCount, context, 'map member count'); } }, validateScalar: function validateScalar(shape, value, context) { switch (shape.type) { case null: case undefined: case 'string': return this.validateString(shape, value, context); case 'base64': case 'binary': return this.validatePayload(value, context); case 'integer': case 'float': return this.validateNumber(shape, value, context); case 'boolean': return this.validateType(value, context, ['boolean']); case 'timestamp': return this.validateType(value, context, [Date, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'], 'Date object, ISO-8601 string, or a UNIX timestamp'); default: return this.fail('UnkownType', 'Unhandled type ' + shape.type + ' for ' + context); } }, validateString: function validateString(shape, value, context) { if (this.validateType(value, context, ['string'])) { this.validateEnum(shape, value, context); this.validateRange(shape, value.length, context, 'string length'); this.validatePattern(shape, value, context); } }, validatePattern: function validatePattern(shape, value, context) { if (this.validation['pattern'] && shape['pattern'] !== undefined) { if (!(new RegExp(shape['pattern'])).test(value)) { this.fail('PatternMatchError', 'Provided value "' + value + '" ' + 'does not match regex pattern /' + shape['pattern'] + '/ for ' + context); } } }, validateRange: function validateRange(shape, value, context, descriptor) { if (this.validation['min']) { if (shape['min'] !== undefined && value < shape['min']) { this.fail('MinRangeError', 'Expected ' + descriptor + ' >= ' + shape['min'] + ', but found ' + value + ' for ' + context); } } if (this.validation['max']) { if (shape['max'] !== undefined && value > shape['max']) { this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= ' + shape['max'] + ', but found ' + value + ' for ' + context); } } }, validateEnum: function validateRange(shape, value, context) { if (this.validation['enum'] && shape['enum'] !== undefined) { if (shape['enum'].indexOf(value) === -1) { this.fail('EnumError', 'Found string value of ' + value + ', but ' + 'expected ' + shape['enum'].join('|') + ' for ' + context); } } }, validateType: function validateType(value, context, acceptedTypes, type) { if (value === null || value === undefined) return false; var foundInvalidType = false; for (var i = 0; i < acceptedTypes.length; i++) { if (typeof acceptedTypes[i] === 'string') { if (typeof value === acceptedTypes[i]) return true; } else if (acceptedTypes[i] instanceof RegExp) { if ((value || '').toString().match(acceptedTypes[i])) return true; } else { if (value instanceof acceptedTypes[i]) return true; if (AWS.util.isType(value, acceptedTypes[i])) return true; if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice(); acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]); } foundInvalidType = true; } var acceptedType = type; if (!acceptedType) { acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1'); } var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : ''; this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' + vowel + ' ' + acceptedType); return false; }, validateNumber: function validateNumber(shape, value, context) { if (value === null || value === undefined) return; if (typeof value === 'string') { var castedValue = parseFloat(value); if (castedValue.toString() === value) value = castedValue; } if (this.validateType(value, context, ['number'])) { this.validateRange(shape, value, context, 'numeric value'); } }, validatePayload: function validatePayload(value, context) { if (value === null || value === undefined) return; if (typeof value === 'string') return; if (value && typeof value.byteLength === 'number') return; // typed arrays if (AWS.util.isNode()) { // special check for buffer/stream in Node.js var Stream = AWS.util.stream.Stream; if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return; } var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView']; if (value) { for (var i = 0; i < types.length; i++) { if (AWS.util.isType(value, types[i])) return; if (AWS.util.typeName(value.constructor) === types[i]) return; } } this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' + 'string, Buffer, Stream, Blob, or typed array object'); } }); },{"./core":11}],30:[function(require,module,exports){ var util = require('../util'); var JsonBuilder = require('../json/builder'); var JsonParser = require('../json/parser'); function buildRequest(req) { var httpRequest = req.httpRequest; var api = req.service.api; var target = api.targetPrefix + '.' + api.operations[req.operation].name; var version = api.jsonVersion || '1.0'; var input = api.operations[req.operation].input; var builder = new JsonBuilder(); if (version === 1) version = '1.0'; httpRequest.body = builder.build(req.params || {}, input); httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version; httpRequest.headers['X-Amz-Target'] = target; } function extractError(resp) { var error = {}; var httpResponse = resp.httpResponse; error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError'; if (typeof error.code === 'string') { error.code = error.code.split(':')[0]; } if (httpResponse.body.length > 0) { var e = JSON.parse(httpResponse.body.toString()); if (e.__type || e.code) { error.code = (e.__type || e.code).split('#').pop(); } if (error.code === 'RequestEntityTooLarge') { error.message = 'Request body must be less than 1 MB'; } else { error.message = (e.message || e.Message || null); } } else { error.statusCode = httpResponse.statusCode; error.message = httpResponse.statusCode.toString(); } resp.error = util.error(new Error(), error); } function extractData(resp) { var body = resp.httpResponse.body.toString() || '{}'; if (resp.request.service.config.convertResponseTypes === false) { resp.data = JSON.parse(body); } else { var operation = resp.request.service.api.operations[resp.request.operation]; var shape = operation.output || {}; var parser = new JsonParser(); resp.data = parser.parse(body, shape); } } module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData }; },{"../json/builder":21,"../json/parser":22,"../util":53}],31:[function(require,module,exports){ var AWS = require('../core'); var util = require('../util'); var QueryParamSerializer = require('../query/query_param_serializer'); var Shape = require('../model/shape'); function buildRequest(req) { var operation = req.service.api.operations[req.operation]; var httpRequest = req.httpRequest; httpRequest.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; httpRequest.params = { Version: req.service.api.apiVersion, Action: operation.name }; var builder = new QueryParamSerializer(); builder.serialize(req.params, operation.input, function(name, value) { httpRequest.params[name] = value; }); httpRequest.body = util.queryParamsToString(httpRequest.params); } function extractError(resp) { var data, body = resp.httpResponse.body.toString(); if (body.match('= 0 ? '&' : '?'); var parts = []; util.arrayEach(Object.keys(queryString).sort(), function(key) { if (!Array.isArray(queryString[key])) { queryString[key] = [queryString[key]]; } for (var i = 0; i < queryString[key].length; i++) { parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]); } }); uri += parts.join('&'); } req.httpRequest.path = uri; } function populateHeaders(req) { var operation = req.service.api.operations[req.operation]; util.each(operation.input.members, function (name, member) { var value = req.params[name]; if (value === null || value === undefined) return; if (member.location === 'headers' && member.type === 'map') { util.each(value, function(key, memberValue) { req.httpRequest.headers[member.name + key] = memberValue; }); } else if (member.location === 'header') { value = member.toWireFormat(value).toString(); req.httpRequest.headers[member.name] = value; } }); } function buildRequest(req) { populateMethod(req); populateURI(req); populateHeaders(req); } function extractError() { } function extractData(resp) { var req = resp.request; var data = {}; var r = resp.httpResponse; var operation = req.service.api.operations[req.operation]; var output = operation.output; var headers = {}; util.each(r.headers, function (k, v) { headers[k.toLowerCase()] = v; }); util.each(output.members, function(name, member) { var header = (member.name || name).toLowerCase(); if (member.location === 'headers' && member.type === 'map') { data[name] = {}; var location = member.isLocationName ? member.name : ''; var pattern = new RegExp('^' + location + '(.+)', 'i'); util.each(r.headers, function (k, v) { var result = k.match(pattern); if (result !== null) { data[name][result[1]] = v; } }); } else if (member.location === 'header') { if (headers[header] !== undefined) { data[name] = headers[header]; } } else if (member.location === 'statusCode') { data[name] = parseInt(r.statusCode, 10); } }); resp.data = data; } module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData }; },{"../util":53}],33:[function(require,module,exports){ var util = require('../util'); var Rest = require('./rest'); var Json = require('./json'); var JsonBuilder = require('../json/builder'); var JsonParser = require('../json/parser'); function populateBody(req) { var builder = new JsonBuilder(); var input = req.service.api.operations[req.operation].input; if (input.payload) { var params = {}; var payloadShape = input.members[input.payload]; params = req.params[input.payload]; if (params === undefined) return; if (payloadShape.type === 'structure') { req.httpRequest.body = builder.build(params, payloadShape); } else { // non-JSON payload req.httpRequest.body = params; } } else { req.httpRequest.body = builder.build(req.params, input); } } function buildRequest(req) { Rest.buildRequest(req); if (['GET', 'HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) { populateBody(req); } } function extractError(resp) { Json.extractError(resp); } function extractData(resp) { Rest.extractData(resp); var req = resp.request; var rules = req.service.api.operations[req.operation].output || {}; if (rules.payload) { var payloadMember = rules.members[rules.payload]; var body = resp.httpResponse.body; if (payloadMember.isStreaming) { resp.data[rules.payload] = body; } else if (payloadMember.type === 'structure' || payloadMember.type === 'list') { var parser = new JsonParser(); resp.data[rules.payload] = parser.parse(body, payloadMember); } else { resp.data[rules.payload] = body.toString(); } } else { var data = resp.data; Json.extractData(resp); resp.data = util.merge(data, resp.data); } } module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData }; },{"../json/builder":21,"../json/parser":22,"../util":53,"./json":30,"./rest":32}],34:[function(require,module,exports){ var AWS = require('../core'); var util = require('../util'); var Rest = require('./rest'); function populateBody(req) { var input = req.service.api.operations[req.operation].input; var builder = new AWS.XML.Builder(); var params = req.params; var payload = input.payload; if (payload) { var payloadMember = input.members[payload]; params = params[payload]; if (params === undefined) return; if (payloadMember.type === 'structure') { var rootElement = payloadMember.name; req.httpRequest.body = builder.toXML(params, payloadMember, rootElement, true); } else { // non-xml payload req.httpRequest.body = params; } } else { req.httpRequest.body = builder.toXML(params, input, input.name || input.shape || util.string.upperFirst(req.operation) + 'Request'); } } function buildRequest(req) { Rest.buildRequest(req); if (['GET', 'HEAD'].indexOf(req.httpRequest.method) < 0) { populateBody(req); } } function extractError(resp) { Rest.extractError(resp); var data = new AWS.XML.Parser().parse(resp.httpResponse.body.toString()); if (data.Errors) data = data.Errors; if (data.Error) data = data.Error; if (data.Code) { resp.error = util.error(new Error(), { code: data.Code, message: data.Message }); } else { resp.error = util.error(new Error(), { code: resp.httpResponse.statusCode, message: null }); } } function extractData(resp) { Rest.extractData(resp); var parser; var req = resp.request; var body = resp.httpResponse.body; var operation = req.service.api.operations[req.operation]; var output = operation.output; var payload = output.payload; if (payload) { var payloadMember = output.members[payload]; if (payloadMember.isStreaming) { resp.data[payload] = body; } else if (payloadMember.type === 'structure') { parser = new AWS.XML.Parser(); resp.data[payload] = parser.parse(body.toString(), payloadMember); } else { resp.data[payload] = body.toString(); } } else if (body.length > 0) { parser = new AWS.XML.Parser(); var data = parser.parse(body.toString(), output); util.update(resp.data, data); } } module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData }; },{"../core":11,"../util":53,"./rest":32}],35:[function(require,module,exports){ var util = require('../util'); function QueryParamSerializer() { } QueryParamSerializer.prototype.serialize = function(params, shape, fn) { serializeStructure('', params, shape, fn); }; function ucfirst(shape) { if (shape.isQueryName || shape.api.protocol !== 'ec2') { return shape.name; } else { return shape.name[0].toUpperCase() + shape.name.substr(1); } } function serializeStructure(prefix, struct, rules, fn) { util.each(rules.members, function(name, member) { var value = struct[name]; if (value === null || value === undefined) return; var memberName = ucfirst(member); memberName = prefix ? prefix + '.' + memberName : memberName; serializeMember(memberName, value, member, fn); }); } function serializeMap(name, map, rules, fn) { var i = 1; util.each(map, function (key, value) { var prefix = rules.flattened ? '.' : '.entry.'; var position = prefix + (i++) + '.'; var keyName = position + (rules.key.name || 'key'); var valueName = position + (rules.value.name || 'value'); serializeMember(name + keyName, key, rules.key, fn); serializeMember(name + valueName, value, rules.value, fn); }); } function serializeList(name, list, rules, fn) { var memberRules = rules.member || {}; if (list.length === 0) { fn.call(this, name, null); return; } util.arrayEach(list, function (v, n) { var suffix = '.' + (n + 1); if (rules.api.protocol === 'ec2') { suffix = suffix + ''; // make linter happy } else if (rules.flattened) { if (memberRules.name) { var parts = name.split('.'); parts.pop(); parts.push(ucfirst(memberRules)); name = parts.join('.'); } } else { suffix = '.member' + suffix; } serializeMember(name + suffix, v, memberRules, fn); }); } function serializeMember(name, value, rules, fn) { if (value === null || value === undefined) return; if (rules.type === 'structure') { serializeStructure(name, value, rules, fn); } else if (rules.type === 'list') { serializeList(name, value, rules, fn); } else if (rules.type === 'map') { serializeMap(name, value, rules, fn); } else { fn(name, rules.toWireFormat(value).toString()); } } module.exports = QueryParamSerializer; },{"../util":53}],36:[function(require,module,exports){ var util = require('./util'); var regionConfig = require('./region_config.json'); function generateRegionPrefix(region) { if (!region) return null; var parts = region.split('-'); if (parts.length < 3) return null; return parts.slice(0, parts.length - 2).join('-') + '-*'; } function derivedKeys(service) { var region = service.config.region; var regionPrefix = generateRegionPrefix(region); var endpointPrefix = service.api.endpointPrefix; return [ [region, endpointPrefix], [regionPrefix, endpointPrefix], [region, '*'], [regionPrefix, '*'], ['*', endpointPrefix], ['*', '*'] ].map(function(item) { return item[0] && item[1] ? item.join('/') : null; }); } function applyConfig(service, config) { util.each(config, function(key, value) { if (key === 'globalEndpoint') return; if (service.config[key] === undefined || service.config[key] === null) { service.config[key] = value; } }); } function configureEndpoint(service) { var keys = derivedKeys(service); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!key) continue; if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) { var config = regionConfig.rules[key]; if (typeof config === 'string') { config = regionConfig.patterns[config]; } if (service.config.useDualstack && util.isDualstackAvailable(service)) { config = util.copy(config); config.endpoint = '{service}.dualstack.{region}.amazonaws.com'; } service.isGlobalEndpoint = !!config.globalEndpoint; if (!config.signatureVersion) config.signatureVersion = 'v4'; applyConfig(service, config); return; } } } module.exports = configureEndpoint; },{"./region_config.json":37,"./util":53}],37:[function(require,module,exports){ module.exports={ "rules": { "*/*": { "endpoint": "{service}.{region}.amazonaws.com" }, "cn-*/*": { "endpoint": "{service}.{region}.amazonaws.com.cn" }, "*/cloudfront": "globalSSL", "*/iam": "globalSSL", "*/sts": "globalSSL", "*/importexport": { "endpoint": "{service}.amazonaws.com", "signatureVersion": "v2", "globalEndpoint": true }, "*/route53": { "endpoint": "https://{service}.amazonaws.com", "signatureVersion": "v3https", "globalEndpoint": true }, "*/waf": "globalSSL", "us-gov-*/iam": "globalGovCloud", "us-gov-*/sts": { "endpoint": "{service}.{region}.amazonaws.com" }, "us-gov-west-1/s3": "s3dash", "us-west-1/s3": "s3dash", "us-west-2/s3": "s3dash", "eu-west-1/s3": "s3dash", "ap-southeast-1/s3": "s3dash", "ap-southeast-2/s3": "s3dash", "ap-northeast-1/s3": "s3dash", "sa-east-1/s3": "s3dash", "us-east-1/s3": { "endpoint": "{service}.amazonaws.com", "signatureVersion": "s3" }, "us-east-1/sdb": { "endpoint": "{service}.amazonaws.com", "signatureVersion": "v2" }, "*/sdb": { "endpoint": "{service}.{region}.amazonaws.com", "signatureVersion": "v2" } }, "patterns": { "globalSSL": { "endpoint": "https://{service}.amazonaws.com", "globalEndpoint": true }, "globalGovCloud": { "endpoint": "{service}.us-gov.amazonaws.com" }, "s3dash": { "endpoint": "{service}-{region}.amazonaws.com", "signatureVersion": "s3" } } } },{}],38:[function(require,module,exports){ (function (process){ var AWS = require('./core'); var AcceptorStateMachine = require('./state_machine'); var inherit = AWS.util.inherit; var domain = AWS.util.domain; var jmespath = require('jmespath'); var hardErrorStates = {success: 1, error: 1, complete: 1}; function isTerminalState(machine) { return Object.prototype.hasOwnProperty.call(hardErrorStates, machine._asm.currentState); } var fsm = new AcceptorStateMachine(); fsm.setupStates = function() { var transition = function(_, done) { var self = this; self._haltHandlersOnError = false; self.emit(self._asm.currentState, function(err) { if (err) { if (isTerminalState(self)) { if (domain && self.domain instanceof domain.Domain) { err.domainEmitter = self; err.domain = self.domain; err.domainThrown = false; self.domain.emit('error', err); } else { throw err; } } else { self.response.error = err; done(err); } } else { done(self.response.error); } }); }; this.addState('validate', 'build', 'error', transition); this.addState('build', 'afterBuild', 'restart', transition); this.addState('afterBuild', 'sign', 'restart', transition); this.addState('sign', 'send', 'retry', transition); this.addState('retry', 'afterRetry', 'afterRetry', transition); this.addState('afterRetry', 'sign', 'error', transition); this.addState('send', 'validateResponse', 'retry', transition); this.addState('validateResponse', 'extractData', 'extractError', transition); this.addState('extractError', 'extractData', 'retry', transition); this.addState('extractData', 'success', 'retry', transition); this.addState('restart', 'build', 'error', transition); this.addState('success', 'complete', 'complete', transition); this.addState('error', 'complete', 'complete', transition); this.addState('complete', null, null, transition); }; fsm.setupStates(); AWS.Request = inherit({ constructor: function Request(service, operation, params) { var endpoint = service.endpoint; var region = service.config.region; var customUserAgent = service.config.customUserAgent; if (service.isGlobalEndpoint) region = 'us-east-1'; this.domain = domain && domain.active; this.service = service; this.operation = operation; this.params = params || {}; this.httpRequest = new AWS.HttpRequest(endpoint, region, customUserAgent); this.startTime = AWS.util.date.getDate(); this.response = new AWS.Response(this); this._asm = new AcceptorStateMachine(fsm.states, 'validate'); this._haltHandlersOnError = false; AWS.SequentialExecutor.call(this); this.emit = this.emitEvent; }, send: function send(callback) { if (callback) { this.on('complete', function (resp) { callback.call(resp, resp.error, resp.data); }); } this.runTo(); return this.response; }, build: function build(callback) { return this.runTo('send', callback); }, runTo: function runTo(state, done) { this._asm.runTo(state, done, this); return this; }, abort: function abort() { this.removeAllListeners('validateResponse'); this.removeAllListeners('extractError'); this.on('validateResponse', function addAbortedError(resp) { resp.error = AWS.util.error(new Error('Request aborted by user'), { code: 'RequestAbortedError', retryable: false }); }); if (this.httpRequest.stream) { // abort HTTP stream this.httpRequest.stream.abort(); if (this.httpRequest._abortCallback) { this.httpRequest._abortCallback(); } else { this.removeAllListeners('send'); // haven't sent yet, so let's not } } return this; }, eachPage: function eachPage(callback) { callback = AWS.util.fn.makeAsync(callback, 3); function wrappedCallback(response) { callback.call(response, response.error, response.data, function (result) { if (result === false) return; if (response.hasNextPage()) { response.nextPage().on('complete', wrappedCallback).send(); } else { callback.call(response, null, null, AWS.util.fn.noop); } }); } this.on('complete', wrappedCallback).send(); }, eachItem: function eachItem(callback) { var self = this; function wrappedCallback(err, data) { if (err) return callback(err, null); if (data === null) return callback(null, null); var config = self.service.paginationConfig(self.operation); var resultKey = config.resultKey; if (Array.isArray(resultKey)) resultKey = resultKey[0]; var items = jmespath.search(data, resultKey); var continueIteration = true; AWS.util.arrayEach(items, function(item) { continueIteration = callback(null, item); if (continueIteration === false) { return AWS.util.abort; } }); return continueIteration; } this.eachPage(wrappedCallback); }, isPageable: function isPageable() { return this.service.paginationConfig(this.operation) ? true : false; }, createReadStream: function createReadStream() { var streams = AWS.util.stream; var req = this; var stream = null; if (AWS.HttpClient.streamsApiVersion === 2) { stream = new streams.PassThrough(); req.send(); } else { stream = new streams.Stream(); stream.readable = true; stream.sent = false; stream.on('newListener', function(event) { if (!stream.sent && event === 'data') { stream.sent = true; process.nextTick(function() { req.send(); }); } }); } this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) { if (statusCode < 300) { req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA); req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR); req.on('httpError', function streamHttpError(error) { resp.error = error; resp.error.retryable = false; }); var shouldCheckContentLength = false; var expectedLen; if (req.httpRequest.method !== 'HEAD') { expectedLen = parseInt(headers['content-length'], 10); } if (expectedLen !== undefined && !isNaN(expectedLen) && expectedLen >= 0) { shouldCheckContentLength = true; var receivedLen = 0; } var checkContentLengthAndEmit = function checkContentLengthAndEmit() { if (shouldCheckContentLength && receivedLen !== expectedLen) { stream.emit('error', AWS.util.error( new Error('Stream content length mismatch. Received ' + receivedLen + ' of ' + expectedLen + ' bytes.'), { code: 'StreamContentLengthMismatch' } )); } else if (AWS.HttpClient.streamsApiVersion === 2) { stream.end(); } else { stream.emit('end') } } var httpStream = resp.httpResponse.createUnbufferedStream(); if (AWS.HttpClient.streamsApiVersion === 2) { if (shouldCheckContentLength) { var lengthAccumulator = new streams.PassThrough(); lengthAccumulator._write = function(chunk) { if (chunk && chunk.length) { receivedLen += chunk.length; } return streams.PassThrough.prototype._write.apply(this, arguments); }; lengthAccumulator.on('end', checkContentLengthAndEmit); httpStream.pipe(lengthAccumulator).pipe(stream, { end: false }); } else { httpStream.pipe(stream); } } else { if (shouldCheckContentLength) { httpStream.on('data', function(arg) { if (arg && arg.length) { receivedLen += arg.length; } }); } httpStream.on('data', function(arg) { stream.emit('data', arg); }); httpStream.on('end', checkContentLengthAndEmit); } httpStream.on('error', function(err) { shouldCheckContentLength = false; stream.emit('error', err); }); } }); this.on('error', function(err) { stream.emit('error', err); }); return stream; }, emitEvent: function emit(eventName, args, done) { if (typeof args === 'function') { done = args; args = null; } if (!done) done = function() { }; if (!args) args = this.eventParameters(eventName, this.response); var origEmit = AWS.SequentialExecutor.prototype.emit; origEmit.call(this, eventName, args, function (err) { if (err) this.response.error = err; done.call(this, err); }); }, eventParameters: function eventParameters(eventName) { switch (eventName) { case 'restart': case 'validate': case 'sign': case 'build': case 'afterValidate': case 'afterBuild': return [this]; case 'error': return [this.response.error, this.response]; default: return [this.response]; } }, presign: function presign(expires, callback) { if (!callback && typeof expires === 'function') { callback = expires; expires = null; } return new AWS.Signers.Presign().sign(this.toGet(), expires, callback); }, isPresigned: function isPresigned() { return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, 'presigned-expires'); }, toUnauthenticated: function toUnauthenticated() { this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS); this.removeListener('sign', AWS.EventListeners.Core.SIGN); return this; }, toGet: function toGet() { if (this.service.api.protocol === 'query' || this.service.api.protocol === 'ec2') { this.removeListener('build', this.buildAsGet); this.addListener('build', this.buildAsGet); } return this; }, buildAsGet: function buildAsGet(request) { request.httpRequest.method = 'GET'; request.httpRequest.path = request.service.endpoint.path + '?' + request.httpRequest.body; request.httpRequest.body = ''; delete request.httpRequest.headers['Content-Length']; delete request.httpRequest.headers['Content-Type']; }, haltHandlersOnError: function haltHandlersOnError() { this._haltHandlersOnError = true; } }); AWS.util.addPromisesToRequests(AWS.Request); AWS.util.mixin(AWS.Request, AWS.SequentialExecutor); }).call(this,require("FWaASH")) },{"./core":11,"./state_machine":52,"FWaASH":62,"jmespath":79}],39:[function(require,module,exports){ var AWS = require('./core'); var inherit = AWS.util.inherit; var jmespath = require('jmespath'); function CHECK_ACCEPTORS(resp) { var waiter = resp.request._waiter; var acceptors = waiter.config.acceptors; var acceptorMatched = false; var state = 'retry'; acceptors.forEach(function(acceptor) { if (!acceptorMatched) { var matcher = waiter.matchers[acceptor.matcher]; if (matcher && matcher(resp, acceptor.expected, acceptor.argument)) { acceptorMatched = true; state = acceptor.state; } } }); if (!acceptorMatched && resp.error) state = 'failure'; if (state === 'success') { waiter.setSuccess(resp); } else { waiter.setError(resp, state === 'retry'); } } AWS.ResourceWaiter = inherit({ constructor: function constructor(service, state) { this.service = service; this.state = state; this.loadWaiterConfig(this.state); }, service: null, state: null, config: null, matchers: { path: function(resp, expected, argument) { var result = jmespath.search(resp.data, argument); return jmespath.strictDeepEqual(result,expected); }, pathAll: function(resp, expected, argument) { var results = jmespath.search(resp.data, argument); if (!Array.isArray(results)) results = [results]; var numResults = results.length; if (!numResults) return false; for (var ind = 0 ; ind < numResults; ind++) { if (!jmespath.strictDeepEqual(results[ind], expected)) { return false; } } return true; }, pathAny: function(resp, expected, argument) { var results = jmespath.search(resp.data, argument); if (!Array.isArray(results)) results = [results]; var numResults = results.length; for (var ind = 0 ; ind < numResults; ind++) { if (jmespath.strictDeepEqual(results[ind], expected)) { return true; } } return false; }, status: function(resp, expected) { var statusCode = resp.httpResponse.statusCode; return (typeof statusCode === 'number') && (statusCode === expected); }, error: function(resp, expected) { if (typeof expected === 'string' && resp.error) { return expected === resp.error.code; } return expected === !!resp.error; } }, listeners: new AWS.SequentialExecutor().addNamedListeners(function(add) { add('RETRY_CHECK', 'retry', function(resp) { var waiter = resp.request._waiter; if (resp.error && resp.error.code === 'ResourceNotReady') { resp.error.retryDelay = (waiter.config.delay || 0) * 1000; } }); add('CHECK_OUTPUT', 'extractData', CHECK_ACCEPTORS); add('CHECK_ERROR', 'extractError', CHECK_ACCEPTORS); }), wait: function wait(params, callback) { if (typeof params === 'function') { callback = params; params = undefined; } var request = this.service.makeRequest(this.config.operation, params); request._waiter = this; request.response.maxRetries = this.config.maxAttempts; request.addListeners(this.listeners); if (callback) request.send(callback); return request; }, setSuccess: function setSuccess(resp) { resp.error = null; resp.data = resp.data || {}; resp.request.removeAllListeners('extractData'); }, setError: function setError(resp, retryable) { resp.data = null; resp.error = AWS.util.error(resp.error || new Error(), { code: 'ResourceNotReady', message: 'Resource is not in the state ' + this.state, retryable: retryable }); }, loadWaiterConfig: function loadWaiterConfig(state) { if (!this.service.api.waiters[state]) { throw new AWS.util.error(new Error(), { code: 'StateNotFoundError', message: 'State ' + state + ' not found.' }); } this.config = this.service.api.waiters[state]; } }); },{"./core":11,"jmespath":79}],40:[function(require,module,exports){ var AWS = require('./core'); var inherit = AWS.util.inherit; var jmespath = require('jmespath'); AWS.Response = inherit({ constructor: function Response(request) { this.request = request; this.data = null; this.error = null; this.retryCount = 0; this.redirectCount = 0; this.httpResponse = new AWS.HttpResponse(); if (request) { this.maxRetries = request.service.numRetries(); this.maxRedirects = request.service.config.maxRedirects; } }, nextPage: function nextPage(callback) { var config; var service = this.request.service; var operation = this.request.operation; try { config = service.paginationConfig(operation, true); } catch (e) { this.error = e; } if (!this.hasNextPage()) { if (callback) callback(this.error, null); else if (this.error) throw this.error; return null; } var params = AWS.util.copy(this.request.params); if (!this.nextPageTokens) { return callback ? callback(null, null) : null; } else { var inputTokens = config.inputToken; if (typeof inputTokens === 'string') inputTokens = [inputTokens]; for (var i = 0; i < inputTokens.length; i++) { params[inputTokens[i]] = this.nextPageTokens[i]; } return service.makeRequest(this.request.operation, params, callback); } }, hasNextPage: function hasNextPage() { this.cacheNextPageTokens(); if (this.nextPageTokens) return true; if (this.nextPageTokens === undefined) return undefined; else return false; }, cacheNextPageTokens: function cacheNextPageTokens() { if (Object.prototype.hasOwnProperty.call(this, 'nextPageTokens')) return this.nextPageTokens; this.nextPageTokens = undefined; var config = this.request.service.paginationConfig(this.request.operation); if (!config) return this.nextPageTokens; this.nextPageTokens = null; if (config.moreResults) { if (!jmespath.search(this.data, config.moreResults)) { return this.nextPageTokens; } } var exprs = config.outputToken; if (typeof exprs === 'string') exprs = [exprs]; AWS.util.arrayEach.call(this, exprs, function (expr) { var output = jmespath.search(this.data, expr); if (output) { this.nextPageTokens = this.nextPageTokens || []; this.nextPageTokens.push(output); } }); return this.nextPageTokens; } }); },{"./core":11,"jmespath":79}],41:[function(require,module,exports){ var AWS = require('./core'); AWS.SequentialExecutor = AWS.util.inherit({ constructor: function SequentialExecutor() { this._events = {}; }, listeners: function listeners(eventName) { return this._events[eventName] ? this._events[eventName].slice(0) : []; }, on: function on(eventName, listener) { if (this._events[eventName]) { this._events[eventName].push(listener); } else { this._events[eventName] = [listener]; } return this; }, onAsync: function onAsync(eventName, listener) { listener._isAsync = true; return this.on(eventName, listener); }, removeListener: function removeListener(eventName, listener) { var listeners = this._events[eventName]; if (listeners) { var length = listeners.length; var position = -1; for (var i = 0; i < length; ++i) { if (listeners[i] === listener) { position = i; } } if (position > -1) { listeners.splice(position, 1); } } return this; }, removeAllListeners: function removeAllListeners(eventName) { if (eventName) { delete this._events[eventName]; } else { this._events = {}; } return this; }, emit: function emit(eventName, eventArgs, doneCallback) { if (!doneCallback) doneCallback = function() { }; var listeners = this.listeners(eventName); var count = listeners.length; this.callListeners(listeners, eventArgs, doneCallback); return count > 0; }, callListeners: function callListeners(listeners, args, doneCallback, prevError) { var self = this; var error = prevError || null; function callNextListener(err) { if (err) { error = AWS.util.error(error || new Error(), err); if (self._haltHandlersOnError) { return doneCallback.call(self, error); } } self.callListeners(listeners, args, doneCallback, error); } while (listeners.length > 0) { var listener = listeners.shift(); if (listener._isAsync) { // asynchronous listener listener.apply(self, args.concat([callNextListener])); return; // stop here, callNextListener will continue } else { // synchronous listener try { listener.apply(self, args); } catch (err) { error = AWS.util.error(error || new Error(), err); } if (error && self._haltHandlersOnError) { doneCallback.call(self, error); return; } } } doneCallback.call(self, error); }, addListeners: function addListeners(listeners) { var self = this; if (listeners._events) listeners = listeners._events; AWS.util.each(listeners, function(event, callbacks) { if (typeof callbacks === 'function') callbacks = [callbacks]; AWS.util.arrayEach(callbacks, function(callback) { self.on(event, callback); }); }); return self; }, addNamedListener: function addNamedListener(name, eventName, callback) { this[name] = callback; this.addListener(eventName, callback); return this; }, addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback) { callback._isAsync = true; return this.addNamedListener(name, eventName, callback); }, addNamedListeners: function addNamedListeners(callback) { var self = this; callback( function() { self.addNamedListener.apply(self, arguments); }, function() { self.addNamedAsyncListener.apply(self, arguments); } ); return this; } }); AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on; module.exports = AWS.SequentialExecutor; },{"./core":11}],42:[function(require,module,exports){ var AWS = require('./core'); var Api = require('./model/api'); var regionConfig = require('./region_config'); var inherit = AWS.util.inherit; var clientCount = 0; AWS.Service = inherit({ constructor: function Service(config) { if (!this.loadServiceClass) { throw AWS.util.error(new Error(), 'Service must be constructed with `new\' operator'); } var ServiceClass = this.loadServiceClass(config || {}); if (ServiceClass) { var originalConfig = AWS.util.copy(config); var svc = new ServiceClass(config); Object.defineProperty(svc, '_originalConfig', { get: function() { return originalConfig; }, enumerable: false, configurable: true }); svc._clientId = ++clientCount; return svc; } this.initialize(config); }, initialize: function initialize(config) { var svcConfig = AWS.config[this.serviceIdentifier]; this.config = new AWS.Config(AWS.config); if (svcConfig) this.config.update(svcConfig, true); if (config) this.config.update(config, true); this.validateService(); if (!this.config.endpoint) regionConfig(this); this.config.endpoint = this.endpointFromTemplate(this.config.endpoint); this.setEndpoint(this.config.endpoint); }, validateService: function validateService() { }, loadServiceClass: function loadServiceClass(serviceConfig) { var config = serviceConfig; if (!AWS.util.isEmpty(this.api)) { return null; } else if (config.apiConfig) { return AWS.Service.defineServiceApi(this.constructor, config.apiConfig); } else if (!this.constructor.services) { return null; } else { config = new AWS.Config(AWS.config); config.update(serviceConfig, true); var version = config.apiVersions[this.constructor.serviceIdentifier]; version = version || config.apiVersion; return this.getLatestServiceClass(version); } }, getLatestServiceClass: function getLatestServiceClass(version) { version = this.getLatestServiceVersion(version); if (this.constructor.services[version] === null) { AWS.Service.defineServiceApi(this.constructor, version); } return this.constructor.services[version]; }, getLatestServiceVersion: function getLatestServiceVersion(version) { if (!this.constructor.services || this.constructor.services.length === 0) { throw new Error('No services defined on ' + this.constructor.serviceIdentifier); } if (!version) { version = 'latest'; } else if (AWS.util.isType(version, Date)) { version = AWS.util.date.iso8601(version).split('T')[0]; } if (Object.hasOwnProperty(this.constructor.services, version)) { return version; } var keys = Object.keys(this.constructor.services).sort(); var selectedVersion = null; for (var i = keys.length - 1; i >= 0; i--) { if (keys[i][keys[i].length - 1] !== '*') { selectedVersion = keys[i]; } if (keys[i].substr(0, 10) <= version) { return selectedVersion; } } throw new Error('Could not find ' + this.constructor.serviceIdentifier + ' API to satisfy version constraint `' + version + '\''); }, api: {}, defaultRetryCount: 3, makeRequest: function makeRequest(operation, params, callback) { if (typeof params === 'function') { callback = params; params = null; } params = params || {}; if (this.config.params) { // copy only toplevel bound params var rules = this.api.operations[operation]; if (rules) { params = AWS.util.copy(params); AWS.util.each(this.config.params, function(key, value) { if (rules.input.members[key]) { if (params[key] === undefined || params[key] === null) { params[key] = value; } } }); } } var request = new AWS.Request(this, operation, params); this.addAllRequestListeners(request); if (callback) request.send(callback); return request; }, makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) { if (typeof params === 'function') { callback = params; params = {}; } var request = this.makeRequest(operation, params).toUnauthenticated(); return callback ? request.send(callback) : request; }, waitFor: function waitFor(state, params, callback) { var waiter = new AWS.ResourceWaiter(this, state); return waiter.wait(params, callback); }, addAllRequestListeners: function addAllRequestListeners(request) { var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(), AWS.EventListeners.CorePost]; for (var i = 0; i < list.length; i++) { if (list[i]) request.addListeners(list[i]); } if (!this.config.paramValidation) { request.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS); } if (this.config.logger) { // add logging events request.addListeners(AWS.EventListeners.Logger); } this.setupRequestListeners(request); }, setupRequestListeners: function setupRequestListeners() { }, getSignerClass: function getSignerClass() { var version; if (this.config.signatureVersion) { version = this.config.signatureVersion; } else { version = this.api.signatureVersion; } return AWS.Signers.RequestSigner.getVersion(version); }, serviceInterface: function serviceInterface() { switch (this.api.protocol) { case 'ec2': return AWS.EventListeners.Query; case 'query': return AWS.EventListeners.Query; case 'json': return AWS.EventListeners.Json; case 'rest-json': return AWS.EventListeners.RestJson; case 'rest-xml': return AWS.EventListeners.RestXml; } if (this.api.protocol) { throw new Error('Invalid service `protocol\' ' + this.api.protocol + ' in API config'); } }, successfulResponse: function successfulResponse(resp) { return resp.httpResponse.statusCode < 300; }, numRetries: function numRetries() { if (this.config.maxRetries !== undefined) { return this.config.maxRetries; } else { return this.defaultRetryCount; } }, retryDelays: function retryDelays(retryCount) { return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions); }, retryableError: function retryableError(error) { if (this.networkingError(error)) return true; if (this.expiredCredentialsError(error)) return true; if (this.throttledError(error)) return true; if (error.statusCode >= 500) return true; return false; }, networkingError: function networkingError(error) { return error.code === 'NetworkingError'; }, expiredCredentialsError: function expiredCredentialsError(error) { return (error.code === 'ExpiredTokenException'); }, clockSkewError: function clockSkewError(error) { switch (error.code) { case 'RequestTimeTooSkewed': case 'RequestExpired': case 'InvalidSignatureException': case 'SignatureDoesNotMatch': case 'AuthFailure': case 'RequestInTheFuture': return true; default: return false; } }, throttledError: function throttledError(error) { switch (error.code) { case 'ProvisionedThroughputExceededException': case 'Throttling': case 'ThrottlingException': case 'RequestLimitExceeded': case 'RequestThrottled': return true; default: return false; } }, endpointFromTemplate: function endpointFromTemplate(endpoint) { if (typeof endpoint !== 'string') return endpoint; var e = endpoint; e = e.replace(/\{service\}/g, this.api.endpointPrefix); e = e.replace(/\{region\}/g, this.config.region); e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http'); return e; }, setEndpoint: function setEndpoint(endpoint) { this.endpoint = new AWS.Endpoint(endpoint, this.config); }, paginationConfig: function paginationConfig(operation, throwException) { var paginator = this.api.operations[operation].paginator; if (!paginator) { if (throwException) { var e = new Error(); throw AWS.util.error(e, 'No pagination configuration for ' + operation); } return null; } return paginator; } }); AWS.util.update(AWS.Service, { defineMethods: function defineMethods(svc) { AWS.util.each(svc.prototype.api.operations, function iterator(method) { if (svc.prototype[method]) return; var operation = svc.prototype.api.operations[method]; if (operation.authtype === 'none') { svc.prototype[method] = function (params, callback) { return this.makeUnauthenticatedRequest(method, params, callback); }; } else { svc.prototype[method] = function (params, callback) { return this.makeRequest(method, params, callback); }; } }); }, defineService: function defineService(serviceIdentifier, versions, features) { AWS.Service._serviceMap[serviceIdentifier] = true; if (!Array.isArray(versions)) { features = versions; versions = []; } var svc = inherit(AWS.Service, features || {}); if (typeof serviceIdentifier === 'string') { AWS.Service.addVersions(svc, versions); var identifier = svc.serviceIdentifier || serviceIdentifier; svc.serviceIdentifier = identifier; } else { // defineService called with an API svc.prototype.api = serviceIdentifier; AWS.Service.defineMethods(svc); } return svc; }, addVersions: function addVersions(svc, versions) { if (!Array.isArray(versions)) versions = [versions]; svc.services = svc.services || {}; for (var i = 0; i < versions.length; i++) { if (svc.services[versions[i]] === undefined) { svc.services[versions[i]] = null; } } svc.apiVersions = Object.keys(svc.services).sort(); }, defineServiceApi: function defineServiceApi(superclass, version, apiConfig) { var svc = inherit(superclass, { serviceIdentifier: superclass.serviceIdentifier }); function setApi(api) { if (api.isApi) { svc.prototype.api = api; } else { svc.prototype.api = new Api(api); } } if (typeof version === 'string') { if (apiConfig) { setApi(apiConfig); } else { try { setApi(AWS.apiLoader(superclass.serviceIdentifier, version)); } catch (err) { throw AWS.util.error(err, { message: 'Could not find API configuration ' + superclass.serviceIdentifier + '-' + version }); } } if (!Object.prototype.hasOwnProperty.call(superclass.services, version)) { superclass.apiVersions = superclass.apiVersions.concat(version).sort(); } superclass.services[version] = svc; } else { setApi(version); } AWS.Service.defineMethods(svc); return svc; }, hasService: function(identifier) { return Object.prototype.hasOwnProperty.call(AWS.Service._serviceMap, identifier); }, _serviceMap: {} }); module.exports = AWS.Service; },{"./core":11,"./model/api":23,"./region_config":36}],43:[function(require,module,exports){ var AWS = require('../core'); AWS.util.update(AWS.CognitoIdentity.prototype, { getOpenIdToken: function getOpenIdToken(params, callback) { return this.makeUnauthenticatedRequest('getOpenIdToken', params, callback); }, getId: function getId(params, callback) { return this.makeUnauthenticatedRequest('getId', params, callback); }, getCredentialsForIdentity: function getCredentialsForIdentity(params, callback) { return this.makeUnauthenticatedRequest('getCredentialsForIdentity', params, callback); } }); },{"../core":11}],44:[function(require,module,exports){ var AWS = require('../core'); AWS.util.update(AWS.STS.prototype, { credentialsFrom: function credentialsFrom(data, credentials) { if (!data) return null; if (!credentials) credentials = new AWS.TemporaryCredentials(); credentials.expired = false; credentials.accessKeyId = data.Credentials.AccessKeyId; credentials.secretAccessKey = data.Credentials.SecretAccessKey; credentials.sessionToken = data.Credentials.SessionToken; credentials.expireTime = data.Credentials.Expiration; return credentials; }, assumeRoleWithWebIdentity: function assumeRoleWithWebIdentity(params, callback) { return this.makeUnauthenticatedRequest('assumeRoleWithWebIdentity', params, callback); }, assumeRoleWithSAML: function assumeRoleWithSAML(params, callback) { return this.makeUnauthenticatedRequest('assumeRoleWithSAML', params, callback); } }); },{"../core":11}],45:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; var expiresHeader = 'presigned-expires'; function signedUrlBuilder(request) { var expires = request.httpRequest.headers[expiresHeader]; var signerClass = request.service.getSignerClass(request); delete request.httpRequest.headers['User-Agent']; delete request.httpRequest.headers['X-Amz-User-Agent']; if (signerClass === AWS.Signers.V4) { if (expires > 604800) { // one week expiry is invalid var message = 'Presigning does not support expiry time greater ' + 'than a week with SigV4 signing.'; throw AWS.util.error(new Error(), { code: 'InvalidExpiryTime', message: message, retryable: false }); } request.httpRequest.headers[expiresHeader] = expires; } else if (signerClass === AWS.Signers.S3) { request.httpRequest.headers[expiresHeader] = parseInt( AWS.util.date.unixTimestamp() + expires, 10).toString(); } else { throw AWS.util.error(new Error(), { message: 'Presigning only supports S3 or SigV4 signing.', code: 'UnsupportedSigner', retryable: false }); } } function signedUrlSigner(request) { var endpoint = request.httpRequest.endpoint; var parsedUrl = AWS.util.urlParse(request.httpRequest.path); var queryParams = {}; if (parsedUrl.search) { queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1)); } AWS.util.each(request.httpRequest.headers, function (key, value) { if (key === expiresHeader) key = 'Expires'; if (key.indexOf('x-amz-meta-') === 0) { delete queryParams[key]; key = key.toLowerCase(); } queryParams[key] = value; }); delete request.httpRequest.headers[expiresHeader]; var auth = queryParams['Authorization'].split(' '); if (auth[0] === 'AWS') { auth = auth[1].split(':'); queryParams['AWSAccessKeyId'] = auth[0]; queryParams['Signature'] = auth[1]; } else if (auth[0] === 'AWS4-HMAC-SHA256') { // SigV4 signing auth.shift(); var rest = auth.join(' '); var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1]; queryParams['X-Amz-Signature'] = signature; delete queryParams['Expires']; } delete queryParams['Authorization']; delete queryParams['Host']; endpoint.pathname = parsedUrl.pathname; endpoint.search = AWS.util.queryParamsToString(queryParams); } AWS.Signers.Presign = inherit({ sign: function sign(request, expireTime, callback) { request.httpRequest.headers[expiresHeader] = expireTime || 3600; request.on('build', signedUrlBuilder); request.on('sign', signedUrlSigner); request.removeListener('afterBuild', AWS.EventListeners.Core.SET_CONTENT_LENGTH); request.removeListener('afterBuild', AWS.EventListeners.Core.COMPUTE_SHA256); request.emit('beforePresign', [request]); if (callback) { request.build(function() { if (this.response.error) callback(this.response.error); else { callback(null, AWS.util.urlFormat(request.httpRequest.endpoint)); } }); } else { request.build(); if (request.response.error) throw request.response.error; return AWS.util.urlFormat(request.httpRequest.endpoint); } } }); module.exports = AWS.Signers.Presign; },{"../core":11}],46:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; AWS.Signers.RequestSigner = inherit({ constructor: function RequestSigner(request) { this.request = request; }, setServiceClientId: function setServiceClientId(id) { this.serviceClientId = id; }, getServiceClientId: function getServiceClientId() { return this.serviceClientId; } }); AWS.Signers.RequestSigner.getVersion = function getVersion(version) { switch (version) { case 'v2': return AWS.Signers.V2; case 'v3': return AWS.Signers.V3; case 'v4': return AWS.Signers.V4; case 's3': return AWS.Signers.S3; case 'v3https': return AWS.Signers.V3Https; } throw new Error('Unknown signing version ' + version); }; require('./v2'); require('./v3'); require('./v3https'); require('./v4'); require('./s3'); require('./presign'); },{"../core":11,"./presign":45,"./s3":47,"./v2":48,"./v3":49,"./v3https":50,"./v4":51}],47:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, { subResources: { 'acl': 1, 'accelerate': 1, 'cors': 1, 'lifecycle': 1, 'delete': 1, 'location': 1, 'logging': 1, 'notification': 1, 'partNumber': 1, 'policy': 1, 'requestPayment': 1, 'replication': 1, 'restore': 1, 'tagging': 1, 'torrent': 1, 'uploadId': 1, 'uploads': 1, 'versionId': 1, 'versioning': 1, 'versions': 1, 'website': 1 }, responseHeaders: { 'response-content-type': 1, 'response-content-language': 1, 'response-expires': 1, 'response-cache-control': 1, 'response-content-disposition': 1, 'response-content-encoding': 1 }, addAuthorization: function addAuthorization(credentials, date) { if (!this.request.headers['presigned-expires']) { this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date); } if (credentials.sessionToken) { this.request.headers['x-amz-security-token'] = credentials.sessionToken; } var signature = this.sign(credentials.secretAccessKey, this.stringToSign()); var auth = 'AWS ' + credentials.accessKeyId + ':' + signature; this.request.headers['Authorization'] = auth; }, stringToSign: function stringToSign() { var r = this.request; var parts = []; parts.push(r.method); parts.push(r.headers['Content-MD5'] || ''); parts.push(r.headers['Content-Type'] || ''); parts.push(r.headers['presigned-expires'] || ''); var headers = this.canonicalizedAmzHeaders(); if (headers) parts.push(headers); parts.push(this.canonicalizedResource()); return parts.join('\n'); }, canonicalizedAmzHeaders: function canonicalizedAmzHeaders() { var amzHeaders = []; AWS.util.each(this.request.headers, function (name) { if (name.match(/^x-amz-/i)) amzHeaders.push(name); }); amzHeaders.sort(function (a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1; }); var parts = []; AWS.util.arrayEach.call(this, amzHeaders, function (name) { parts.push(name.toLowerCase() + ':' + String(this.request.headers[name])); }); return parts.join('\n'); }, canonicalizedResource: function canonicalizedResource() { var r = this.request; var parts = r.path.split('?'); var path = parts[0]; var querystring = parts[1]; var resource = ''; if (r.virtualHostedBucket) resource += '/' + r.virtualHostedBucket; resource += path; if (querystring) { var resources = []; AWS.util.arrayEach.call(this, querystring.split('&'), function (param) { var name = param.split('=')[0]; var value = param.split('=')[1]; if (this.subResources[name] || this.responseHeaders[name]) { var subresource = { name: name }; if (value !== undefined) { if (this.subResources[name]) { subresource.value = value; } else { subresource.value = decodeURIComponent(value); } } resources.push(subresource); } }); resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; }); if (resources.length) { querystring = []; AWS.util.arrayEach(resources, function (res) { if (res.value === undefined) { querystring.push(res.name); } else { querystring.push(res.name + '=' + res.value); } }); resource += '?' + querystring.join('&'); } } return resource; }, sign: function sign(secret, string) { return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1'); } }); module.exports = AWS.Signers.S3; },{"../core":11}],48:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, { addAuthorization: function addAuthorization(credentials, date) { if (!date) date = AWS.util.date.getDate(); var r = this.request; r.params.Timestamp = AWS.util.date.iso8601(date); r.params.SignatureVersion = '2'; r.params.SignatureMethod = 'HmacSHA256'; r.params.AWSAccessKeyId = credentials.accessKeyId; if (credentials.sessionToken) { r.params.SecurityToken = credentials.sessionToken; } delete r.params.Signature; // delete old Signature for re-signing r.params.Signature = this.signature(credentials); r.body = AWS.util.queryParamsToString(r.params); r.headers['Content-Length'] = r.body.length; }, signature: function signature(credentials) { return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64'); }, stringToSign: function stringToSign() { var parts = []; parts.push(this.request.method); parts.push(this.request.endpoint.host.toLowerCase()); parts.push(this.request.pathname()); parts.push(AWS.util.queryParamsToString(this.request.params)); return parts.join('\n'); } }); module.exports = AWS.Signers.V2; },{"../core":11}],49:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, { addAuthorization: function addAuthorization(credentials, date) { var datetime = AWS.util.date.rfc822(date); this.request.headers['X-Amz-Date'] = datetime; if (credentials.sessionToken) { this.request.headers['x-amz-security-token'] = credentials.sessionToken; } this.request.headers['X-Amzn-Authorization'] = this.authorization(credentials, datetime); }, authorization: function authorization(credentials) { return 'AWS3 ' + 'AWSAccessKeyId=' + credentials.accessKeyId + ',' + 'Algorithm=HmacSHA256,' + 'SignedHeaders=' + this.signedHeaders() + ',' + 'Signature=' + this.signature(credentials); }, signedHeaders: function signedHeaders() { var headers = []; AWS.util.arrayEach(this.headersToSign(), function iterator(h) { headers.push(h.toLowerCase()); }); return headers.sort().join(';'); }, canonicalHeaders: function canonicalHeaders() { var headers = this.request.headers; var parts = []; AWS.util.arrayEach(this.headersToSign(), function iterator(h) { parts.push(h.toLowerCase().trim() + ':' + String(headers[h]).trim()); }); return parts.sort().join('\n') + '\n'; }, headersToSign: function headersToSign() { var headers = []; AWS.util.each(this.request.headers, function iterator(k) { if (k === 'Host' || k === 'Content-Encoding' || k.match(/^X-Amz/i)) { headers.push(k); } }); return headers; }, signature: function signature(credentials) { return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64'); }, stringToSign: function stringToSign() { var parts = []; parts.push(this.request.method); parts.push('/'); parts.push(''); parts.push(this.canonicalHeaders()); parts.push(this.request.body); return AWS.util.crypto.sha256(parts.join('\n')); } }); module.exports = AWS.Signers.V3; },{"../core":11}],50:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; require('./v3'); AWS.Signers.V3Https = inherit(AWS.Signers.V3, { authorization: function authorization(credentials) { return 'AWS3-HTTPS ' + 'AWSAccessKeyId=' + credentials.accessKeyId + ',' + 'Algorithm=HmacSHA256,' + 'Signature=' + this.signature(credentials); }, stringToSign: function stringToSign() { return this.request.headers['X-Amz-Date']; } }); module.exports = AWS.Signers.V3Https; },{"../core":11,"./v3":49}],51:[function(require,module,exports){ var AWS = require('../core'); var inherit = AWS.util.inherit; var cachedSecret = {}; var cacheQueue = []; var maxCacheEntries = 50; var expiresHeader = 'presigned-expires'; AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, { constructor: function V4(request, serviceName, signatureCache) { AWS.Signers.RequestSigner.call(this, request); this.serviceName = serviceName; this.signatureCache = signatureCache; }, algorithm: 'AWS4-HMAC-SHA256', addAuthorization: function addAuthorization(credentials, date) { var datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, ''); if (this.isPresigned()) { this.updateForPresigned(credentials, datetime); } else { this.addHeaders(credentials, datetime); } this.request.headers['Authorization'] = this.authorization(credentials, datetime); }, addHeaders: function addHeaders(credentials, datetime) { this.request.headers['X-Amz-Date'] = datetime; if (credentials.sessionToken) { this.request.headers['x-amz-security-token'] = credentials.sessionToken; } }, updateForPresigned: function updateForPresigned(credentials, datetime) { var credString = this.credentialString(datetime); var qs = { 'X-Amz-Date': datetime, 'X-Amz-Algorithm': this.algorithm, 'X-Amz-Credential': credentials.accessKeyId + '/' + credString, 'X-Amz-Expires': this.request.headers[expiresHeader], 'X-Amz-SignedHeaders': this.signedHeaders() }; if (credentials.sessionToken) { qs['X-Amz-Security-Token'] = credentials.sessionToken; } if (this.request.headers['Content-Type']) { qs['Content-Type'] = this.request.headers['Content-Type']; } if (this.request.headers['Content-MD5']) { qs['Content-MD5'] = this.request.headers['Content-MD5']; } if (this.request.headers['Cache-Control']) { qs['Cache-Control'] = this.request.headers['Cache-Control']; } AWS.util.each.call(this, this.request.headers, function(key, value) { if (key === expiresHeader) return; if (this.isSignableHeader(key)) { var lowerKey = key.toLowerCase(); if (lowerKey.indexOf('x-amz-meta-') === 0) { qs[lowerKey] = value; } else if (lowerKey.indexOf('x-amz-') === 0) { qs[key] = value; } } }); var sep = this.request.path.indexOf('?') >= 0 ? '&' : '?'; this.request.path += sep + AWS.util.queryParamsToString(qs); }, authorization: function authorization(credentials, datetime) { var parts = []; var credString = this.credentialString(datetime); parts.push(this.algorithm + ' Credential=' + credentials.accessKeyId + '/' + credString); parts.push('SignedHeaders=' + this.signedHeaders()); parts.push('Signature=' + this.signature(credentials, datetime)); return parts.join(', '); }, signature: function signature(credentials, datetime) { var cache = null; var cacheIdentifier = this.serviceName + (this.getServiceClientId() ? '_' + this.getServiceClientId() : ''); if (this.signatureCache) { var cache = cachedSecret[cacheIdentifier]; if (!cache) { cacheQueue.push(cacheIdentifier); if (cacheQueue.length > maxCacheEntries) { delete cachedSecret[cacheQueue.shift()]; } } } var date = datetime.substr(0, 8); if (!cache || cache.akid !== credentials.accessKeyId || cache.region !== this.request.region || cache.date !== date) { var kSecret = credentials.secretAccessKey; var kDate = AWS.util.crypto.hmac('AWS4' + kSecret, date, 'buffer'); var kRegion = AWS.util.crypto.hmac(kDate, this.request.region, 'buffer'); var kService = AWS.util.crypto.hmac(kRegion, this.serviceName, 'buffer'); var kCredentials = AWS.util.crypto.hmac(kService, 'aws4_request', 'buffer'); if (!this.signatureCache) { return AWS.util.crypto.hmac(kCredentials, this.stringToSign(datetime), 'hex'); } cachedSecret[cacheIdentifier] = { region: this.request.region, date: date, key: kCredentials, akid: credentials.accessKeyId }; } var key = cachedSecret[cacheIdentifier].key; return AWS.util.crypto.hmac(key, this.stringToSign(datetime), 'hex'); }, stringToSign: function stringToSign(datetime) { var parts = []; parts.push('AWS4-HMAC-SHA256'); parts.push(datetime); parts.push(this.credentialString(datetime)); parts.push(this.hexEncodedHash(this.canonicalString())); return parts.join('\n'); }, canonicalString: function canonicalString() { var parts = [], pathname = this.request.pathname(); if (this.serviceName !== 's3') pathname = AWS.util.uriEscapePath(pathname); parts.push(this.request.method); parts.push(pathname); parts.push(this.request.search()); parts.push(this.canonicalHeaders() + '\n'); parts.push(this.signedHeaders()); parts.push(this.hexEncodedBodyHash()); return parts.join('\n'); }, canonicalHeaders: function canonicalHeaders() { var headers = []; AWS.util.each.call(this, this.request.headers, function (key, item) { headers.push([key, item]); }); headers.sort(function (a, b) { return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1; }); var parts = []; AWS.util.arrayEach.call(this, headers, function (item) { var key = item[0].toLowerCase(); if (this.isSignableHeader(key)) { parts.push(key + ':' + this.canonicalHeaderValues(item[1].toString())); } }); return parts.join('\n'); }, canonicalHeaderValues: function canonicalHeaderValues(values) { return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, ''); }, signedHeaders: function signedHeaders() { var keys = []; AWS.util.each.call(this, this.request.headers, function (key) { key = key.toLowerCase(); if (this.isSignableHeader(key)) keys.push(key); }); return keys.sort().join(';'); }, credentialString: function credentialString(datetime) { var parts = []; parts.push(datetime.substr(0, 8)); parts.push(this.request.region); parts.push(this.serviceName); parts.push('aws4_request'); return parts.join('/'); }, hexEncodedHash: function hash(string) { return AWS.util.crypto.sha256(string, 'hex'); }, hexEncodedBodyHash: function hexEncodedBodyHash() { if (this.isPresigned() && this.serviceName === 's3' && !this.request.body) { return 'UNSIGNED-PAYLOAD'; } else if (this.request.headers['X-Amz-Content-Sha256']) { return this.request.headers['X-Amz-Content-Sha256']; } else { return this.hexEncodedHash(this.request.body || ''); } }, unsignableHeaders: ['authorization', 'content-type', 'content-length', 'user-agent', expiresHeader, 'expect'], isSignableHeader: function isSignableHeader(key) { if (key.toLowerCase().indexOf('x-amz-') === 0) return true; return this.unsignableHeaders.indexOf(key) < 0; }, isPresigned: function isPresigned() { return this.request.headers[expiresHeader] ? true : false; } }); module.exports = AWS.Signers.V4; },{"../core":11}],52:[function(require,module,exports){ function AcceptorStateMachine(states, state) { this.currentState = state || null; this.states = states || {}; } AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) { if (typeof finalState === 'function') { inputError = bindObject; bindObject = done; done = finalState; finalState = null; } var self = this; var state = self.states[self.currentState]; state.fn.call(bindObject || self, inputError, function(err) { if (err) { if (state.fail) self.currentState = state.fail; else return done ? done.call(bindObject, err) : null; } else { if (state.accept) self.currentState = state.accept; else return done ? done.call(bindObject) : null; } if (self.currentState === finalState) { return done ? done.call(bindObject, err) : null; } self.runTo(finalState, done, bindObject, err); }); }; AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) { if (typeof acceptState === 'function') { fn = acceptState; acceptState = null; failState = null; } else if (typeof failState === 'function') { fn = failState; failState = null; } if (!this.currentState) this.currentState = name; this.states[name] = { accept: acceptState, fail: failState, fn: fn }; return this; }; module.exports = AcceptorStateMachine; },{}],53:[function(require,module,exports){ (function (process){ var AWS; var util = { engine: function engine() { if (util.isBrowser() && typeof navigator !== 'undefined') { return navigator.userAgent; } else { return process.platform + '/' + process.version; } }, userAgent: function userAgent() { var name = util.isBrowser() ? 'js' : 'nodejs'; var agent = 'aws-sdk-' + name + '/' + require('./core').VERSION; if (name === 'nodejs') agent += ' ' + util.engine(); return agent; }, isBrowser: function isBrowser() { return process && process.browser; }, isNode: function isNode() { return !util.isBrowser(); }, uriEscape: function uriEscape(string) { var output = encodeURIComponent(string); output = output.replace(/[^A-Za-z0-9_.~\-%]+/g, escape); output = output.replace(/[*]/g, function(ch) { return '%' + ch.charCodeAt(0).toString(16).toUpperCase(); }); return output; }, uriEscapePath: function uriEscapePath(string) { var parts = []; util.arrayEach(string.split('/'), function (part) { parts.push(util.uriEscape(part)); }); return parts.join('/'); }, urlParse: function urlParse(url) { return util.url.parse(url); }, urlFormat: function urlFormat(url) { return util.url.format(url); }, queryStringParse: function queryStringParse(qs) { return util.querystring.parse(qs); }, queryParamsToString: function queryParamsToString(params) { var items = []; var escape = util.uriEscape; var sortedKeys = Object.keys(params).sort(); util.arrayEach(sortedKeys, function(name) { var value = params[name]; var ename = escape(name); var result = ename + '='; if (Array.isArray(value)) { var vals = []; util.arrayEach(value, function(item) { vals.push(escape(item)); }); result = ename + '=' + vals.sort().join('&' + ename + '='); } else if (value !== undefined && value !== null) { result = ename + '=' + escape(value); } items.push(result); }); return items.join('&'); }, readFileSync: function readFileSync(path) { if (util.isBrowser()) return null; return require('fs').readFileSync(path, 'utf-8'); }, base64: { encode: function encode64(string) { return new util.Buffer(string).toString('base64'); }, decode: function decode64(string) { return new util.Buffer(string, 'base64'); } }, buffer: { toStream: function toStream(buffer) { if (!util.Buffer.isBuffer(buffer)) buffer = new util.Buffer(buffer); var readable = new (util.stream.Readable)(); var pos = 0; readable._read = function(size) { if (pos >= buffer.length) return readable.push(null); var end = pos + size; if (end > buffer.length) end = buffer.length; readable.push(buffer.slice(pos, end)); pos = end; }; return readable; }, concat: function(buffers) { var length = 0, offset = 0, buffer = null, i; for (i = 0; i < buffers.length; i++) { length += buffers[i].length; } buffer = new util.Buffer(length); for (i = 0; i < buffers.length; i++) { buffers[i].copy(buffer, offset); offset += buffers[i].length; } return buffer; } }, string: { byteLength: function byteLength(string) { if (string === null || string === undefined) return 0; if (typeof string === 'string') string = new util.Buffer(string); if (typeof string.byteLength === 'number') { return string.byteLength; } else if (typeof string.length === 'number') { return string.length; } else if (typeof string.size === 'number') { return string.size; } else if (typeof string.path === 'string') { return require('fs').lstatSync(string.path).size; } else { throw util.error(new Error('Cannot determine length of ' + string), { object: string }); } }, upperFirst: function upperFirst(string) { return string[0].toUpperCase() + string.substr(1); }, lowerFirst: function lowerFirst(string) { return string[0].toLowerCase() + string.substr(1); } }, ini: { parse: function string(ini) { var currentSection, map = {}; util.arrayEach(ini.split(/\r?\n/), function(line) { line = line.split(/(^|\s)[;#]/)[0]; // remove comments var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/); if (section) { currentSection = section[1]; } else if (currentSection) { var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/); if (item) { map[currentSection] = map[currentSection] || {}; map[currentSection][item[1]] = item[2]; } } }); return map; } }, fn: { noop: function() {}, makeAsync: function makeAsync(fn, expectedArgs) { if (expectedArgs && expectedArgs <= fn.length) { return fn; } return function() { var args = Array.prototype.slice.call(arguments, 0); var callback = args.pop(); var result = fn.apply(null, args); callback(result); }; } }, date: { getDate: function getDate() { if (!AWS) AWS = require('./core'); if (AWS.config.systemClockOffset) { // use offset when non-zero return new Date(new Date().getTime() + AWS.config.systemClockOffset); } else { return new Date(); } }, iso8601: function iso8601(date) { if (date === undefined) { date = util.date.getDate(); } return date.toISOString().replace(/\.\d{3}Z$/, 'Z'); }, rfc822: function rfc822(date) { if (date === undefined) { date = util.date.getDate(); } return date.toUTCString(); }, unixTimestamp: function unixTimestamp(date) { if (date === undefined) { date = util.date.getDate(); } return date.getTime() / 1000; }, from: function format(date) { if (typeof date === 'number') { return new Date(date * 1000); // unix timestamp } else { return new Date(date); } }, format: function format(date, formatter) { if (!formatter) formatter = 'iso8601'; return util.date[formatter](util.date.from(date)); }, parseTimestamp: function parseTimestamp(value) { if (typeof value === 'number') { // unix timestamp (number) return new Date(value * 1000); } else if (value.match(/^\d+$/)) { // unix timestamp return new Date(value * 1000); } else if (value.match(/^\d{4}/)) { // iso8601 return new Date(value); } else if (value.match(/^\w{3},/)) { // rfc822 return new Date(value); } else { throw util.error( new Error('unhandled timestamp format: ' + value), {code: 'TimestampParserError'}); } } }, crypto: { crc32Table: [ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D], crc32: function crc32(data) { var tbl = util.crypto.crc32Table; var crc = 0 ^ -1; if (typeof data === 'string') { data = new util.Buffer(data); } for (var i = 0; i < data.length; i++) { var code = data.readUInt8(i); crc = (crc >>> 8) ^ tbl[(crc ^ code) & 0xFF]; } return (crc ^ -1) >>> 0; }, hmac: function hmac(key, string, digest, fn) { if (!digest) digest = 'binary'; if (digest === 'buffer') { digest = undefined; } if (!fn) fn = 'sha256'; if (typeof string === 'string') string = new util.Buffer(string); return util.crypto.lib.createHmac(fn, key).update(string).digest(digest); }, md5: function md5(data, digest, callback) { return util.crypto.hash('md5', data, digest, callback); }, sha256: function sha256(data, digest, callback) { return util.crypto.hash('sha256', data, digest, callback); }, hash: function(algorithm, data, digest, callback) { var hash = util.crypto.createHash(algorithm); if (!digest) { digest = 'binary'; } if (digest === 'buffer') { digest = undefined; } if (typeof data === 'string') data = new util.Buffer(data); var sliceFn = util.arraySliceFn(data); var isBuffer = util.Buffer.isBuffer(data); if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true; if (callback && typeof data === 'object' && typeof data.on === 'function' && !isBuffer) { data.on('data', function(chunk) { hash.update(chunk); }); data.on('error', function(err) { callback(err); }); data.on('end', function() { callback(null, hash.digest(digest)); }); } else if (callback && sliceFn && !isBuffer && typeof FileReader !== 'undefined') { var index = 0, size = 1024 * 512; var reader = new FileReader(); reader.onerror = function() { callback(new Error('Failed to read data.')); }; reader.onload = function() { var buf = new util.Buffer(new Uint8Array(reader.result)); hash.update(buf); index += buf.length; reader._continueReading(); }; reader._continueReading = function() { if (index >= data.size) { callback(null, hash.digest(digest)); return; } var back = index + size; if (back > data.size) back = data.size; reader.readAsArrayBuffer(sliceFn.call(data, index, back)); }; reader._continueReading(); } else { if (util.isBrowser() && typeof data === 'object' && !isBuffer) { data = new util.Buffer(new Uint8Array(data)); } var out = hash.update(data).digest(digest); if (callback) callback(null, out); return out; } }, toHex: function toHex(data) { var out = []; for (var i = 0; i < data.length; i++) { out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2)); } return out.join(''); }, createHash: function createHash(algorithm) { return util.crypto.lib.createHash(algorithm); } }, abort: {}, each: function each(object, iterFunction) { for (var key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { var ret = iterFunction.call(this, key, object[key]); if (ret === util.abort) break; } } }, arrayEach: function arrayEach(array, iterFunction) { for (var idx in array) { if (Object.prototype.hasOwnProperty.call(array, idx)) { var ret = iterFunction.call(this, array[idx], parseInt(idx, 10)); if (ret === util.abort) break; } } }, update: function update(obj1, obj2) { util.each(obj2, function iterator(key, item) { obj1[key] = item; }); return obj1; }, merge: function merge(obj1, obj2) { return util.update(util.copy(obj1), obj2); }, copy: function copy(object) { if (object === null || object === undefined) return object; var dupe = {}; for (var key in object) { dupe[key] = object[key]; } return dupe; }, isEmpty: function isEmpty(obj) { for (var prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { return false; } } return true; }, arraySliceFn: function arraySliceFn(obj) { var fn = obj.slice || obj.webkitSlice || obj.mozSlice; return typeof fn === 'function' ? fn : null; }, isType: function isType(obj, type) { if (typeof type === 'function') type = util.typeName(type); return Object.prototype.toString.call(obj) === '[object ' + type + ']'; }, typeName: function typeName(type) { if (Object.prototype.hasOwnProperty.call(type, 'name')) return type.name; var str = type.toString(); var match = str.match(/^\s*function (.+)\(/); return match ? match[1] : str; }, error: function error(err, options) { var originalError = null; if (typeof err.message === 'string' && err.message !== '') { if (typeof options === 'string' || (options && options.message)) { originalError = util.copy(err); originalError.message = err.message; } } err.message = err.message || null; if (typeof options === 'string') { err.message = options; } else if (typeof options === 'object' && options !== null) { util.update(err, options); if (options.message) err.message = options.message; if (options.code || options.name) err.code = options.code || options.name; if (options.stack) err.stack = options.stack; } if (typeof Object.defineProperty === 'function') { Object.defineProperty(err, 'name', {writable: true, enumerable: false}); Object.defineProperty(err, 'message', {enumerable: true}); } err.name = options && options.name || err.name || err.code || 'Error'; err.time = new Date(); if (originalError) err.originalError = originalError; return err; }, inherit: function inherit(klass, features) { var newObject = null; if (features === undefined) { features = klass; klass = Object; newObject = {}; } else { var ctor = function ConstructorWrapper() {}; ctor.prototype = klass.prototype; newObject = new ctor(); } if (features.constructor === Object) { features.constructor = function() { if (klass !== Object) { return klass.apply(this, arguments); } }; } features.constructor.prototype = newObject; util.update(features.constructor.prototype, features); features.constructor.__super__ = klass; return features.constructor; }, mixin: function mixin() { var klass = arguments[0]; for (var i = 1; i < arguments.length; i++) { for (var prop in arguments[i].prototype) { var fn = arguments[i].prototype[prop]; if (prop !== 'constructor') { klass.prototype[prop] = fn; } } } return klass; }, hideProperties: function hideProperties(obj, props) { if (typeof Object.defineProperty !== 'function') return; util.arrayEach(props, function (key) { Object.defineProperty(obj, key, { enumerable: false, writable: true, configurable: true }); }); }, property: function property(obj, name, value, enumerable, isValue) { var opts = { configurable: true, enumerable: enumerable !== undefined ? enumerable : true }; if (typeof value === 'function' && !isValue) { opts.get = value; } else { opts.value = value; opts.writable = true; } Object.defineProperty(obj, name, opts); }, memoizedProperty: function memoizedProperty(obj, name, get, enumerable) { var cachedValue = null; util.property(obj, name, function() { if (cachedValue === null) { cachedValue = get(); } return cachedValue; }, enumerable); }, hoistPayloadMember: function hoistPayloadMember(resp) { var req = resp.request; var operation = req.operation; var output = req.service.api.operations[operation].output; if (output.payload) { var payloadMember = output.members[output.payload]; var responsePayload = resp.data[output.payload]; if (payloadMember.type === 'structure') { util.each(responsePayload, function(key, value) { util.property(resp.data, key, value, false); }); } } }, computeSha256: function computeSha256(body, done) { if (util.isNode()) { var Stream = util.stream.Stream; var fs = require('fs'); if (body instanceof Stream) { if (typeof body.path === 'string') { // assume file object var settings = {}; if (typeof body.start === 'number') { settings.start = body.start; } if (typeof body.end === 'number') { settings.end = body.end; } body = fs.createReadStream(body.path, settings); } else { // TODO support other stream types return done(new Error('Non-file stream objects are ' + 'not supported with SigV4')); } } } util.crypto.sha256(body, 'hex', function(err, sha) { if (err) done(err); else done(null, sha); }); }, isClockSkewed: function isClockSkewed(serverTime) { if (serverTime) { util.property(AWS.config, 'isClockSkewed', Math.abs(new Date().getTime() - serverTime) >= 300000, false); return AWS.config.isClockSkewed; } }, applyClockOffset: function applyClockOffset(serverTime) { if (serverTime) AWS.config.systemClockOffset = serverTime - new Date().getTime(); }, extractRequestId: function extractRequestId(resp) { var requestId = resp.httpResponse.headers['x-amz-request-id'] || resp.httpResponse.headers['x-amzn-requestid']; if (!requestId && resp.data && resp.data.ResponseMetadata) { requestId = resp.data.ResponseMetadata.RequestId; } if (requestId) { resp.requestId = requestId; } if (resp.error) { resp.error.requestId = requestId; } }, addPromisesToRequests: function addPromisesToRequests(constructor, PromiseDependency) { PromiseDependency = PromiseDependency || null; if (!PromiseDependency && typeof Promise !== 'undefined') { PromiseDependency = Promise; } if (typeof PromiseDependency !== 'function') { delete constructor.prototype.promise; return; } constructor.prototype.promise = function promise() { var self = this; return new PromiseDependency(function(resolve, reject) { self.on('complete', function(resp) { if (resp.error) { reject(resp.error); } else { resolve(resp.data); } }); self.runTo(); }); } }, isDualstackAvailable: function isDualstackAvailable(service) { if (!service) return false; var metadata = require('../apis/metadata.json'); if (typeof service !== 'string') service = service.serviceIdentifier; if (typeof service !== 'string' || !metadata.hasOwnProperty(service)) return false; return !!metadata[service].dualstackAvailable; }, calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions) { if (!retryDelayOptions) retryDelayOptions = {}; var customBackoff = retryDelayOptions.customBackoff || null; if (typeof customBackoff === 'function') { return customBackoff(retryCount); } var base = retryDelayOptions.base || 100; var delay = Math.random() * (Math.pow(2, retryCount) * base); return delay; }, handleRequestWithRetries: function handleRequestWithRetries(httpRequest, options, cb) { if (!options) options = {}; var http = AWS.HttpClient.getInstance(); var httpOptions = options.httpOptions || {}; var retryCount = 0; var errCallback = function(err) { var maxRetries = options.maxRetries || 0; if (err && err.code === 'TimeoutError') err.retryable = true; if (err && err.retryable && retryCount < maxRetries) { retryCount++; var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions); setTimeout(sendRequest, delay + (err.retryAfter || 0)); } else { cb(err); } }; var sendRequest = function() { var data = ''; http.handleRequest(httpRequest, httpOptions, function(httpResponse) { httpResponse.on('data', function(chunk) { data += chunk.toString(); }); httpResponse.on('end', function() { var statusCode = httpResponse.statusCode; if (statusCode < 300) { cb(null, data); } else { var retryAfter = parseInt(httpResponse.headers['retry-after'], 10) * 1000 || 0; var err = util.error(new Error(), { retryable: statusCode >= 500 || statusCode === 429 } ); if (retryAfter && err.retryable) err.retryAfter = retryAfter; errCallback(err); } }); }, errCallback); }; process.nextTick(sendRequest); } }; module.exports = util; }).call(this,require("FWaASH")) },{"../apis/metadata.json":3,"./core":11,"FWaASH":62,"fs":56}],54:[function(require,module,exports){ var util = require('../util'); var Shape = require('../model/shape'); function DomXmlParser() { } DomXmlParser.prototype.parse = function(xml, shape) { if (xml.replace(/^\s+/, '') === '') return {}; var result, error; try { if (window.DOMParser) { try { var parser = new DOMParser(); result = parser.parseFromString(xml, 'text/xml'); } catch (syntaxError) { throw util.error(new Error('Parse error in document'), { originalError: syntaxError, code: 'XMLParserError', retryable: true }); } if (result.documentElement === null) { throw util.error(new Error('Cannot parse empty document.'), { code: 'XMLParserError', retryable: true }); } var isError = result.getElementsByTagName('parsererror')[0]; if (isError && (isError.parentNode === result || isError.parentNode.nodeName === 'body' || isError.parentNode.parentNode === result || isError.parentNode.parentNode.nodeName === 'body')) { var errorElement = isError.getElementsByTagName('div')[0] || isError; throw util.error(new Error(errorElement.textContent || 'Parser error in document'), { code: 'XMLParserError', retryable: true }); } } else if (window.ActiveXObject) { result = new window.ActiveXObject('Microsoft.XMLDOM'); result.async = false; if (!result.loadXML(xml)) { throw util.error(new Error('Parse error in document'), { code: 'XMLParserError', retryable: true }); } } else { throw new Error('Cannot load XML parser'); } } catch (e) { error = e; } if (result && result.documentElement && !error) { var data = parseXml(result.documentElement, shape); var metadata = result.getElementsByTagName('ResponseMetadata')[0]; if (metadata) { data.ResponseMetadata = parseXml(metadata, {}); } return data; } else if (error) { throw util.error(error || new Error(), {code: 'XMLParserError', retryable: true}); } else { // empty xml document return {}; } }; function parseXml(xml, shape) { if (!shape) shape = {}; switch (shape.type) { case 'structure': return parseStructure(xml, shape); case 'map': return parseMap(xml, shape); case 'list': return parseList(xml, shape); case undefined: case null: return parseUnknown(xml); default: return parseScalar(xml, shape); } } function parseStructure(xml, shape) { var data = {}; if (xml === null) return data; util.each(shape.members, function(memberName, memberShape) { if (memberShape.isXmlAttribute) { if (Object.prototype.hasOwnProperty.call(xml.attributes, memberShape.name)) { var value = xml.attributes[memberShape.name].value; data[memberName] = parseXml({textContent: value}, memberShape); } } else { var xmlChild = memberShape.flattened ? xml : xml.getElementsByTagName(memberShape.name)[0]; if (xmlChild) { data[memberName] = parseXml(xmlChild, memberShape); } else if (!memberShape.flattened && memberShape.type === 'list') { data[memberName] = memberShape.defaultValue; } } }); return data; } function parseMap(xml, shape) { var data = {}; var xmlKey = shape.key.name || 'key'; var xmlValue = shape.value.name || 'value'; var tagName = shape.flattened ? shape.name : 'entry'; var child = xml.firstElementChild; while (child) { if (child.nodeName === tagName) { var key = child.getElementsByTagName(xmlKey)[0].textContent; var value = child.getElementsByTagName(xmlValue)[0]; data[key] = parseXml(value, shape.value); } child = child.nextElementSibling; } return data; } function parseList(xml, shape) { var data = []; var tagName = shape.flattened ? shape.name : (shape.member.name || 'member'); var child = xml.firstElementChild; while (child) { if (child.nodeName === tagName) { data.push(parseXml(child, shape.member)); } child = child.nextElementSibling; } return data; } function parseScalar(xml, shape) { if (xml.getAttribute) { var encoding = xml.getAttribute('encoding'); if (encoding === 'base64') { shape = new Shape.create({type: encoding}); } } var text = xml.textContent; if (text === '') text = null; if (typeof shape.toType === 'function') { return shape.toType(text); } else { return text; } } function parseUnknown(xml) { if (xml === undefined || xml === null) return ''; if (!xml.firstElementChild) { if (xml.parentNode.parentNode === null) return {}; if (xml.childNodes.length === 0) return ''; else return xml.textContent; } var shape = {type: 'structure', members: {}}; var child = xml.firstElementChild; while (child) { var tag = child.nodeName; if (Object.prototype.hasOwnProperty.call(shape.members, tag)) { shape.members[tag].type = 'list'; } else { shape.members[tag] = {name: tag}; } child = child.nextElementSibling; } return parseStructure(xml, shape); } module.exports = DomXmlParser; },{"../model/shape":28,"../util":53}],55:[function(require,module,exports){ var util = require('../util'); var builder = require('xmlbuilder'); function XmlBuilder() { } XmlBuilder.prototype.toXML = function(params, shape, rootElement, noEmpty) { var xml = builder.create(rootElement); applyNamespaces(xml, shape); serialize(xml, params, shape); return xml.children.length > 0 || noEmpty ? xml.root().toString() : ''; }; function serialize(xml, value, shape) { switch (shape.type) { case 'structure': return serializeStructure(xml, value, shape); case 'map': return serializeMap(xml, value, shape); case 'list': return serializeList(xml, value, shape); default: return serializeScalar(xml, value, shape); } } function serializeStructure(xml, params, shape) { util.arrayEach(shape.memberNames, function(memberName) { var memberShape = shape.members[memberName]; if (memberShape.location !== 'body') return; var value = params[memberName]; var name = memberShape.name; if (value !== undefined && value !== null) { if (memberShape.isXmlAttribute) { xml.att(name, value); } else if (memberShape.flattened) { serialize(xml, value, memberShape); } else { var element = xml.ele(name); applyNamespaces(element, memberShape); serialize(element, value, memberShape); } } }); } function serializeMap(xml, map, shape) { var xmlKey = shape.key.name || 'key'; var xmlValue = shape.value.name || 'value'; util.each(map, function(key, value) { var entry = xml.ele(shape.flattened ? shape.name : 'entry'); serialize(entry.ele(xmlKey), key, shape.key); serialize(entry.ele(xmlValue), value, shape.value); }); } function serializeList(xml, list, shape) { if (shape.flattened) { util.arrayEach(list, function(value) { var name = shape.member.name || shape.name; var element = xml.ele(name); serialize(element, value, shape.member); }); } else { util.arrayEach(list, function(value) { var name = shape.member.name || 'member'; var element = xml.ele(name); serialize(element, value, shape.member); }); } } function serializeScalar(xml, value, shape) { xml.txt(shape.toWireFormat(value)); } function applyNamespaces(xml, shape) { var uri, prefix = 'xmlns'; if (shape.xmlNamespaceUri) { uri = shape.xmlNamespaceUri; if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix; } else if (xml.isRoot && shape.api.xmlNamespaceUri) { uri = shape.api.xmlNamespaceUri; } if (uri) xml.att(prefix, uri); } module.exports = XmlBuilder; },{"../util":53,"xmlbuilder":100}],56:[function(require,module,exports){ },{}],57:[function(require,module,exports){ var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = Buffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 Buffer._useTypedArrays = (function () { try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return 42 === arr.foo() && typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray` } catch (e) { return false } })() function Buffer (subject, encoding, noZero) { if (!(this instanceof Buffer)) return new Buffer(subject, encoding, noZero) var type = typeof subject if (encoding === 'base64' && type === 'string') { subject = stringtrim(subject) while (subject.length % 4 !== 0) { subject = subject + '=' } } var length if (type === 'number') length = coerce(subject) else if (type === 'string') length = Buffer.byteLength(subject, encoding) else if (type === 'object') length = coerce(subject.length) // assume that object is array-like else throw new Error('First argument needs to be a number, array or string.') var buf if (Buffer._useTypedArrays) { buf = Buffer._augment(new Uint8Array(length)) } else { buf = this buf.length = length buf._isBuffer = true } var i if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') { buf._set(subject) } else if (isArrayish(subject)) { for (i = 0; i < length; i++) { if (Buffer.isBuffer(subject)) buf[i] = subject.readUInt8(i) else buf[i] = subject[i] } } else if (type === 'string') { buf.write(subject, 0, encoding) } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) { for (i = 0; i < length; i++) { buf[i] = 0 } } return buf } Buffer.isEncoding = function (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.isBuffer = function (b) { return !!(b !== null && b !== undefined && b._isBuffer) } Buffer.byteLength = function (str, encoding) { var ret str = str + '' switch (encoding || 'utf8') { case 'hex': ret = str.length / 2 break case 'utf8': case 'utf-8': ret = utf8ToBytes(str).length break case 'ascii': case 'binary': case 'raw': ret = str.length break case 'base64': ret = base64ToBytes(str).length break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = str.length * 2 break default: throw new Error('Unknown encoding') } return ret } Buffer.concat = function (list, totalLength) { assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' + 'list should be an Array.') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (typeof totalLength !== 'number') { totalLength = 0 for (i = 0; i < list.length; i++) { totalLength += list[i].length } } var buf = new Buffer(totalLength) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } function _hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } var strLen = string.length assert(strLen % 2 === 0, 'Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var byte = parseInt(string.substr(i * 2, 2), 16) assert(!isNaN(byte), 'Invalid hex string') buf[offset + i] = byte } Buffer._charsWritten = i * 2 return i } function _utf8Write (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) return charsWritten } function _asciiWrite (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) return charsWritten } function _binaryWrite (buf, string, offset, length) { return _asciiWrite(buf, string, offset, length) } function _base64Write (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) return charsWritten } function _utf16leWrite (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length) return charsWritten } Buffer.prototype.write = function (string, offset, length, encoding) { if (isFinite(offset)) { if (!isFinite(length)) { encoding = length length = undefined } } else { // legacy var swap = encoding encoding = offset offset = length length = swap } offset = Number(offset) || 0 var remaining = this.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } encoding = String(encoding || 'utf8').toLowerCase() var ret switch (encoding) { case 'hex': ret = _hexWrite(this, string, offset, length) break case 'utf8': case 'utf-8': ret = _utf8Write(this, string, offset, length) break case 'ascii': ret = _asciiWrite(this, string, offset, length) break case 'binary': ret = _binaryWrite(this, string, offset, length) break case 'base64': ret = _base64Write(this, string, offset, length) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = _utf16leWrite(this, string, offset, length) break default: throw new Error('Unknown encoding') } return ret } Buffer.prototype.toString = function (encoding, start, end) { var self = this encoding = String(encoding || 'utf8').toLowerCase() start = Number(start) || 0 end = (end !== undefined) ? Number(end) : end = self.length if (end === start) return '' var ret switch (encoding) { case 'hex': ret = _hexSlice(self, start, end) break case 'utf8': case 'utf-8': ret = _utf8Slice(self, start, end) break case 'ascii': ret = _asciiSlice(self, start, end) break case 'binary': ret = _binarySlice(self, start, end) break case 'base64': ret = _base64Slice(self, start, end) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = _utf16leSlice(self, start, end) break default: throw new Error('Unknown encoding') } return ret } Buffer.prototype.toJSON = function () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } Buffer.prototype.copy = function (target, target_start, start, end) { var source = this if (!start) start = 0 if (!end && end !== 0) end = this.length if (!target_start) target_start = 0 if (end === start) return if (target.length === 0 || source.length === 0) return assert(end >= start, 'sourceEnd < sourceStart') assert(target_start >= 0 && target_start < target.length, 'targetStart out of bounds') assert(start >= 0 && start < source.length, 'sourceStart out of bounds') assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds') if (end > this.length) end = this.length if (target.length - target_start < end - start) end = target.length - target_start + start var len = end - start if (len < 100 || !Buffer._useTypedArrays) { for (var i = 0; i < len; i++) target[i + target_start] = this[i + start] } else { target._set(this.subarray(start, start + len), target_start) } } function _base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function _utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function _asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) ret += String.fromCharCode(buf[i]) return ret } function _binarySlice (buf, start, end) { return _asciiSlice(buf, start, end) } function _hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function _utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i+1] * 256) } return res } Buffer.prototype.slice = function (start, end) { var len = this.length start = clamp(start, len, 0) end = clamp(end, len, len) if (Buffer._useTypedArrays) { return Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start var newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } return newBuf } } Buffer.prototype.get = function (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } Buffer.prototype.set = function (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } Buffer.prototype.readUInt8 = function (offset, noAssert) { if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to read beyond buffer length') } if (offset >= this.length) return return this[offset] } function _readUInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val if (littleEndian) { val = buf[offset] if (offset + 1 < len) val |= buf[offset + 1] << 8 } else { val = buf[offset] << 8 if (offset + 1 < len) val |= buf[offset + 1] } return val } Buffer.prototype.readUInt16LE = function (offset, noAssert) { return _readUInt16(this, offset, true, noAssert) } Buffer.prototype.readUInt16BE = function (offset, noAssert) { return _readUInt16(this, offset, false, noAssert) } function _readUInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val if (littleEndian) { if (offset + 2 < len) val = buf[offset + 2] << 16 if (offset + 1 < len) val |= buf[offset + 1] << 8 val |= buf[offset] if (offset + 3 < len) val = val + (buf[offset + 3] << 24 >>> 0) } else { if (offset + 1 < len) val = buf[offset + 1] << 16 if (offset + 2 < len) val |= buf[offset + 2] << 8 if (offset + 3 < len) val |= buf[offset + 3] val = val + (buf[offset] << 24 >>> 0) } return val } Buffer.prototype.readUInt32LE = function (offset, noAssert) { return _readUInt32(this, offset, true, noAssert) } Buffer.prototype.readUInt32BE = function (offset, noAssert) { return _readUInt32(this, offset, false, noAssert) } Buffer.prototype.readInt8 = function (offset, noAssert) { if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to read beyond buffer length') } if (offset >= this.length) return var neg = this[offset] & 0x80 if (neg) return (0xff - this[offset] + 1) * -1 else return this[offset] } function _readInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val = _readUInt16(buf, offset, littleEndian, true) var neg = val & 0x8000 if (neg) return (0xffff - val + 1) * -1 else return val } Buffer.prototype.readInt16LE = function (offset, noAssert) { return _readInt16(this, offset, true, noAssert) } Buffer.prototype.readInt16BE = function (offset, noAssert) { return _readInt16(this, offset, false, noAssert) } function _readInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val = _readUInt32(buf, offset, littleEndian, true) var neg = val & 0x80000000 if (neg) return (0xffffffff - val + 1) * -1 else return val } Buffer.prototype.readInt32LE = function (offset, noAssert) { return _readInt32(this, offset, true, noAssert) } Buffer.prototype.readInt32BE = function (offset, noAssert) { return _readInt32(this, offset, false, noAssert) } function _readFloat (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } return ieee754.read(buf, offset, littleEndian, 23, 4) } Buffer.prototype.readFloatLE = function (offset, noAssert) { return _readFloat(this, offset, true, noAssert) } Buffer.prototype.readFloatBE = function (offset, noAssert) { return _readFloat(this, offset, false, noAssert) } function _readDouble (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset + 7 < buf.length, 'Trying to read beyond buffer length') } return ieee754.read(buf, offset, littleEndian, 52, 8) } Buffer.prototype.readDoubleLE = function (offset, noAssert) { return _readDouble(this, offset, true, noAssert) } Buffer.prototype.readDoubleBE = function (offset, noAssert) { return _readDouble(this, offset, false, noAssert) } Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'trying to write beyond buffer length') verifuint(value, 0xff) } if (offset >= this.length) return this[offset] = value } function _writeUInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffff) } var len = buf.length if (offset >= len) return for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { _writeUInt16(this, value, offset, true, noAssert) } Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { _writeUInt16(this, value, offset, false, noAssert) } function _writeUInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffffffff) } var len = buf.length if (offset >= len) return for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { _writeUInt32(this, value, offset, true, noAssert) } Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { _writeUInt32(this, value, offset, false, noAssert) } Buffer.prototype.writeInt8 = function (value, offset, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to write beyond buffer length') verifsint(value, 0x7f, -0x80) } if (offset >= this.length) return if (value >= 0) this.writeUInt8(value, offset, noAssert) else this.writeUInt8(0xff + value + 1, offset, noAssert) } function _writeInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fff, -0x8000) } var len = buf.length if (offset >= len) return if (value >= 0) _writeUInt16(buf, value, offset, littleEndian, noAssert) else _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert) } Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { _writeInt16(this, value, offset, true, noAssert) } Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { _writeInt16(this, value, offset, false, noAssert) } function _writeInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fffffff, -0x80000000) } var len = buf.length if (offset >= len) return if (value >= 0) _writeUInt32(buf, value, offset, littleEndian, noAssert) else _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert) } Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { _writeInt32(this, value, offset, true, noAssert) } Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { _writeInt32(this, value, offset, false, noAssert) } function _writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38) } var len = buf.length if (offset >= len) return ieee754.write(buf, value, offset, littleEndian, 23, 4) } Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { _writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { _writeFloat(this, value, offset, false, noAssert) } function _writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 7 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308) } var len = buf.length if (offset >= len) return ieee754.write(buf, value, offset, littleEndian, 52, 8) } Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { _writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { _writeDouble(this, value, offset, false, noAssert) } Buffer.prototype.fill = function (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (typeof value === 'string') { value = value.charCodeAt(0) } assert(typeof value === 'number' && !isNaN(value), 'value is not a number') assert(end >= start, 'end < start') if (end === start) return if (this.length === 0) return assert(start >= 0 && start < this.length, 'start out of bounds') assert(end >= 0 && end <= this.length, 'end out of bounds') for (var i = start; i < end; i++) { this[i] = value } } Buffer.prototype.inspect = function () { var out = [] var len = this.length for (var i = 0; i < len; i++) { out[i] = toHex(this[i]) if (i === exports.INSPECT_MAX_BYTES) { out[i + 1] = '...' break } } return '' } Buffer.prototype.toArrayBuffer = function () { if (typeof Uint8Array !== 'undefined') { if (Buffer._useTypedArrays) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) buf[i] = this[i] return buf.buffer } } else { throw new Error('Buffer.toArrayBuffer not supported in this browser') } } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } var BP = Buffer.prototype Buffer._augment = function (arr) { arr._isBuffer = true arr._get = arr.get arr._set = arr.set arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.copy = BP.copy arr.slice = BP.slice arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } function clamp (index, len, defaultValue) { if (typeof index !== 'number') return defaultValue index = ~~index; // Coerce to integer. if (index >= len) return len if (index >= 0) return index index += len if (index >= 0) return index return 0 } function coerce (length) { length = ~~Math.ceil(+length) return length < 0 ? 0 : length } function isArray (subject) { return (Array.isArray || function (subject) { return Object.prototype.toString.call(subject) === '[object Array]' })(subject) } function isArrayish (subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number' } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { var b = str.charCodeAt(i) if (b <= 0x7F) byteArray.push(str.charCodeAt(i)) else { var start = i if (b >= 0xD800 && b <= 0xDFFF) i++ var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') for (var j = 0; j < h.length; j++) byteArray.push(parseInt(h[j], 16)) } } return byteArray } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(str) } function blitBuffer (src, dst, offset, length) { var pos for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } function verifuint (value, max) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value >= 0, 'specified a negative value for writing an unsigned value') assert(value <= max, 'value is larger than maximum value for type') assert(Math.floor(value) === value, 'value has a fractional component') } function verifsint (value, max, min) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') assert(Math.floor(value) === value, 'value has a fractional component') } function verifIEEE754 (value, max, min) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') } function assert (test, message) { if (!test) throw new Error(message || 'Failed assertion') } },{"base64-js":58,"ieee754":59}],58:[function(require,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) var PLUS_URL_SAFE = '-'.charCodeAt(0) var SLASH_URL_SAFE = '_'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS || code === PLUS_URL_SAFE) return 62 // '+' if (code === SLASH || code === SLASH_URL_SAFE) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 arr = new Arr(b64.length * 3 / 4 - placeHolders) l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],59:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],60:[function(require,module,exports){ function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; EventEmitter.defaultMaxListeners = 10; EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } throw TypeError('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) this._events[type] = listener; else if (isObject(this._events[type])) this._events[type].push(listener); else this._events[type] = [this._events[type], listener]; if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],61:[function(require,module,exports){ if (typeof Object.create === 'function') { module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],62:[function(require,module,exports){ var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); } process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],63:[function(require,module,exports){ (function (global){ ;(function(root) { var freeExports = typeof exports == 'object' && exports; var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } var punycode, maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' regexPunycode = /^xn--/, regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, key; function error(type) { throw RangeError(errors[type]); } function map(array, fn) { var length = array.length; while (length--) { array[length] = fn(array[length]); } return array; } function mapDomain(string, fn) { return map(string.split(regexSeparators), fn).join('.'); } function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { output.push(value); counter--; } } else { output.push(value); } } return output; } function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } function digitToBasic(digit, flag) { return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } function decode(input) { var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, baseMinusT; basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; output.splice(i++, 0, n); } return ucs2encode(output); } function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], inputLength, handledCPCountPlusOne, baseMinusT, qMinusT; input = ucs2decode(input); inputLength = input.length; n = initialN; delta = 0; bias = initialBias; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; if (basicLength) { output.push(delimiter); } while (handledCPCount < inputLength) { for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } function toUnicode(domain) { return mapDomain(domain, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } function toASCII(domain) { return mapDomain(domain, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } punycode = { 'version': '1.2.4', 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define('punycode', function() { return punycode; }); } else if (freeExports && !freeExports.nodeType) { if (freeModule) { // in Node.js or RingoJS v0.8.0+ freeModule.exports = punycode; } else { // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { // in Rhino or a web browser root.punycode = punycode; } }(this)); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],64:[function(require,module,exports){ 'use strict'; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; },{}],65:[function(require,module,exports){ 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return obj[k].map(function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; },{}],66:[function(require,module,exports){ 'use strict'; exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode'); },{"./decode":64,"./encode":65}],67:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],68:[function(require,module,exports){ (function (process,global){ var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; exports.deprecate = function(fn, msg) { if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; function inspect(obj, opts) { var ctx = { seen: [], stylize: stylizeNoColor }; if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { ctx.showHidden = opts; } else if (opts) { exports._extend(ctx, opts); } if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { if (ctx.customInspect && value && isFunction(value.inspect) && value.inspect !== exports.inspect && !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; if (isArray(value)) { array = true; braces = ['[', ']']; } if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; exports.inherits = require('inherits'); exports._extend = function(origin, add) { if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":67,"FWaASH":62,"inherits":61}],69:[function(require,module,exports){ (function (global){ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() exports.kMaxLength = kMaxLength() function typedArraySupport () { try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { if (that === null) { that = new Buffer(length) } that.length = length } return that } function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true }) } } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) } function allocUnsafe (that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0 } } return that } Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) } Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) var actual = that.write(string, encoding) if (actual !== length) { that = that.slice(0, actual) } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array) } else if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { that = array that.__proto__ = Buffer.prototype } else { that = fromArrayLike(that, array) } return that } function fromObject (that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false if (start === undefined || start < 0) { start = 0 } if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { if (buffer.length === 0) return -1 if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { byteOffset = dir ? 0 : (buffer.length - 1) } if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } if (typeof val === 'string') { val = Buffer.from(val, encoding) } if (Buffer.isBuffer(val)) { if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end) newBuf.__proto__ = Buffer.prototype } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start] } } return newBuf } function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } Buffer.prototype.fill = function fill (val, start, end, encoding) { if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { str = stringtrim(str).replace(INVALID_BASE64_RE, '') if (str.length < 2) return '' while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) if (codePoint > 0xD7FF && codePoint < 0xE000) { if (!leadSurrogate) { if (codePoint > 0xDBFF) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } leadSurrogate = codePoint continue } if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"base64-js":70,"ieee754":71,"isarray":72}],70:[function(require,module,exports){ 'use strict' exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array function init () { var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 } init() function toByteArray (b64) { var i, j, l, tmp, placeHolders, arr var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 arr = new Arr(len * 3 / 4 - placeHolders) l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } },{}],71:[function(require,module,exports){ module.exports=require(59) },{}],72:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],73:[function(require,module,exports){ var Buffer = require('buffer').Buffer; var intSize = 4; var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); var chrsz = 8; function toArray(buf, bigEndian) { if ((buf.length % intSize) !== 0) { var len = buf.length + (intSize - (buf.length % intSize)); buf = Buffer.concat([buf, zeroBuffer], len); } var arr = []; var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; for (var i = 0; i < buf.length; i += intSize) { arr.push(fn.call(buf, i)); } return arr; } function toBuffer(arr, size, bigEndian) { var buf = new Buffer(size); var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; for (var i = 0; i < arr.length; i++) { fn.call(buf, arr[i], i * 4, true); } return buf; } function hash(buf, fn, hashSize, bigEndian) { if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); return toBuffer(arr, hashSize, bigEndian); } module.exports = { hash: hash }; },{"buffer":57}],74:[function(require,module,exports){ var Buffer = require('buffer').Buffer var sha = require('./sha') var sha256 = require('./sha256') var rng = require('./rng') var md5 = require('./md5') var algorithms = { sha1: sha, sha256: sha256, md5: md5 } var blocksize = 64 var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0) function hmac(fn, key, data) { if(!Buffer.isBuffer(key)) key = new Buffer(key) if(!Buffer.isBuffer(data)) data = new Buffer(data) if(key.length > blocksize) { key = fn(key) } else if(key.length < blocksize) { key = Buffer.concat([key, zeroBuffer], blocksize) } var ipad = new Buffer(blocksize), opad = new Buffer(blocksize) for(var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36 opad[i] = key[i] ^ 0x5C } var hash = fn(Buffer.concat([ipad, data])) return fn(Buffer.concat([opad, hash])) } function hash(alg, key) { alg = alg || 'sha1' var fn = algorithms[alg] var bufs = [] var length = 0 if(!fn) error('algorithm:', alg, 'is not yet supported') return { update: function (data) { if(!Buffer.isBuffer(data)) data = new Buffer(data) bufs.push(data) length += data.length return this }, digest: function (enc) { var buf = Buffer.concat(bufs) var r = key ? hmac(fn, key, buf) : fn(buf) bufs = null return enc ? r.toString(enc) : r } } } function error () { var m = [].slice.call(arguments).join(' ') throw new Error([ m, 'we accept pull requests', 'http://github.com/dominictarr/crypto-browserify' ].join('\n')) } exports.createHash = function (alg) { return hash(alg) } exports.createHmac = function (alg, key) { return hash(alg, key) } exports.randomBytes = function(size, callback) { if (callback && callback.call) { try { callback.call(this, undefined, new Buffer(rng(size))) } catch (err) { callback(err) } } else { return new Buffer(rng(size)) } } function each(a, f) { for(var i in a) f(a[i], i) } each(['createCredentials' , 'createCipher' , 'createCipheriv' , 'createDecipher' , 'createDecipheriv' , 'createSign' , 'createVerify' , 'createDiffieHellman' , 'pbkdf2'], function (name) { exports[name] = function () { error('sorry,', name, 'is not implemented yet') } }) },{"./md5":75,"./rng":76,"./sha":77,"./sha256":78,"buffer":57}],75:[function(require,module,exports){ var helpers = require('./helpers'); function md5_vm_test() { return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; } function core_md5(x, len) { x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for(var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return Array(a, b, c, d); } function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } module.exports = function md5(buf) { return helpers.hash(buf, core_md5, 16); }; },{"./helpers":73}],76:[function(require,module,exports){ (function() { var _global = this; var mathRNG, whatwgRNG; mathRNG = function(size) { var bytes = new Array(size); var r; for (var i = 0, r; i < size; i++) { if ((i & 0x03) == 0) r = Math.random() * 0x100000000; bytes[i] = r >>> ((i & 0x03) << 3) & 0xff; } return bytes; } if (_global.crypto && crypto.getRandomValues) { whatwgRNG = function(size) { var bytes = new Uint8Array(size); crypto.getRandomValues(bytes); return bytes; } } module.exports = whatwgRNG || mathRNG; }()) },{}],77:[function(require,module,exports){ var helpers = require('./helpers'); function core_sha1(x, len) { x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; for(var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; var olde = e; for(var j = 0; j < 80; j++) { if(j < 16) w[j] = x[i + j]; else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = rol(b, 30); b = a; a = t; } a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); e = safe_add(e, olde); } return Array(a, b, c, d, e); } function sha1_ft(t, b, c, d) { if(t < 20) return (b & c) | ((~b) & d); if(t < 40) return b ^ c ^ d; if(t < 60) return (b & c) | (b & d) | (c & d); return b ^ c ^ d; } function sha1_kt(t) { return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514; } function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } function rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } module.exports = function sha1(buf) { return helpers.hash(buf, core_sha1, 20, true); }; },{"./helpers":73}],78:[function(require,module,exports){ var helpers = require('./helpers'); var safe_add = function(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }; var S = function(X, n) { return (X >>> n) | (X << (32 - n)); }; var R = function(X, n) { return (X >>> n); }; var Ch = function(x, y, z) { return ((x & y) ^ ((~x) & z)); }; var Maj = function(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)); }; var Sigma0256 = function(x) { return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); }; var Sigma1256 = function(x) { return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); }; var Gamma0256 = function(x) { return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); }; var Gamma1256 = function(x) { return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); }; var core_sha256 = function(m, l) { var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2); var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19); var W = new Array(64); var a, b, c, d, e, f, g, h, i, j; var T1, T2; m[l >> 5] |= 0x80 << (24 - l % 32); m[((l + 64 >> 9) << 4) + 15] = l; for (var i = 0; i < m.length; i += 16) { a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7]; for (var j = 0; j < 64; j++) { if (j < 16) { W[j] = m[j + i]; } else { W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]); } T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]); T2 = safe_add(Sigma0256(a), Maj(a, b, c)); h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2); } HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]); HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]); } return HASH; }; module.exports = function sha256(buf) { return helpers.hash(buf, core_sha256, 32, true); }; },{"./helpers":73}],79:[function(require,module,exports){ (function(exports) { "use strict"; function isArray(obj) { if (obj !== null) { return Object.prototype.toString.call(obj) === "[object Array]"; } else { return false; } } function isObject(obj) { if (obj !== null) { return Object.prototype.toString.call(obj) === "[object Object]"; } else { return false; } } function strictDeepEqual(first, second) { if (first === second) { return true; } var firstType = Object.prototype.toString.call(first); if (firstType !== Object.prototype.toString.call(second)) { return false; } if (isArray(first) === true) { if (first.length !== second.length) { return false; } for (var i = 0; i < first.length; i++) { if (strictDeepEqual(first[i], second[i]) === false) { return false; } } return true; } if (isObject(first) === true) { var keysSeen = {}; for (var key in first) { if (hasOwnProperty.call(first, key)) { if (strictDeepEqual(first[key], second[key]) === false) { return false; } keysSeen[key] = true; } } for (var key2 in second) { if (hasOwnProperty.call(second, key2)) { if (keysSeen[key2] !== true) { return false; } } } return true; } return false; } function isFalse(obj) { if (obj === "" || obj === false || obj === null) { return true; } else if (isArray(obj) && obj.length === 0) { return true; } else if (isObject(obj)) { for (var key in obj) { if (obj.hasOwnProperty(key)) { return false; } } return true; } else { return false; } } function objValues(obj) { var keys = Object.keys(obj); var values = []; for (var i = 0; i < keys.length; i++) { values.push(obj[keys[i]]); } return values; } function merge(a, b) { var merged = {}; for (var key in a) { merged[key] = a[key]; } for (var key2 in b) { merged[key2] = b[key2]; } return merged; } var trimLeft; if (typeof String.prototype.trimLeft === "function") { trimLeft = function(str) { return str.trimLeft(); }; } else { trimLeft = function(str) { return str.match(/^\s*(.*)/)[1]; }; } var TYPE_NUMBER = 0; var TYPE_ANY = 1; var TYPE_STRING = 2; var TYPE_ARRAY = 3; var TYPE_OBJECT = 4; var TYPE_BOOLEAN = 5; var TYPE_EXPREF = 6; var TYPE_NULL = 7; var TYPE_ARRAY_NUMBER = 8; var TYPE_ARRAY_STRING = 9; var TOK_EOF = "EOF"; var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; var TOK_RBRACKET = "Rbracket"; var TOK_RPAREN = "Rparen"; var TOK_COMMA = "Comma"; var TOK_COLON = "Colon"; var TOK_RBRACE = "Rbrace"; var TOK_NUMBER = "Number"; var TOK_CURRENT = "Current"; var TOK_EXPREF = "Expref"; var TOK_PIPE = "Pipe"; var TOK_OR = "Or"; var TOK_AND = "And"; var TOK_EQ = "EQ"; var TOK_GT = "GT"; var TOK_LT = "LT"; var TOK_GTE = "GTE"; var TOK_LTE = "LTE"; var TOK_NE = "NE"; var TOK_FLATTEN = "Flatten"; var TOK_STAR = "Star"; var TOK_FILTER = "Filter"; var TOK_DOT = "Dot"; var TOK_NOT = "Not"; var TOK_LBRACE = "Lbrace"; var TOK_LBRACKET = "Lbracket"; var TOK_LPAREN= "Lparen"; var TOK_LITERAL= "Literal"; var basicTokens = { ".": TOK_DOT, "*": TOK_STAR, ",": TOK_COMMA, ":": TOK_COLON, "{": TOK_LBRACE, "}": TOK_RBRACE, "]": TOK_RBRACKET, "(": TOK_LPAREN, ")": TOK_RPAREN, "@": TOK_CURRENT }; var operatorStartToken = { "<": true, ">": true, "=": true, "!": true }; var skipChars = { " ": true, "\t": true, "\n": true }; function isAlpha(ch) { return (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || ch === "_"; } function isNum(ch) { return (ch >= "0" && ch <= "9") || ch === "-"; } function isAlphaNum(ch) { return (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || (ch >= "0" && ch <= "9") || ch === "_"; } function Lexer() { } Lexer.prototype = { tokenize: function(stream) { var tokens = []; this._current = 0; var start; var identifier; var token; while (this._current < stream.length) { if (isAlpha(stream[this._current])) { start = this._current; identifier = this._consumeUnquotedIdentifier(stream); tokens.push({type: TOK_UNQUOTEDIDENTIFIER, value: identifier, start: start}); } else if (basicTokens[stream[this._current]] !== undefined) { tokens.push({type: basicTokens[stream[this._current]], value: stream[this._current], start: this._current}); this._current++; } else if (isNum(stream[this._current])) { token = this._consumeNumber(stream); tokens.push(token); } else if (stream[this._current] === "[") { token = this._consumeLBracket(stream); tokens.push(token); } else if (stream[this._current] === "\"") { start = this._current; identifier = this._consumeQuotedIdentifier(stream); tokens.push({type: TOK_QUOTEDIDENTIFIER, value: identifier, start: start}); } else if (stream[this._current] === "'") { start = this._current; identifier = this._consumeRawStringLiteral(stream); tokens.push({type: TOK_LITERAL, value: identifier, start: start}); } else if (stream[this._current] === "`") { start = this._current; var literal = this._consumeLiteral(stream); tokens.push({type: TOK_LITERAL, value: literal, start: start}); } else if (operatorStartToken[stream[this._current]] !== undefined) { tokens.push(this._consumeOperator(stream)); } else if (skipChars[stream[this._current]] !== undefined) { this._current++; } else if (stream[this._current] === "&") { start = this._current; this._current++; if (stream[this._current] === "&") { this._current++; tokens.push({type: TOK_AND, value: "&&", start: start}); } else { tokens.push({type: TOK_EXPREF, value: "&", start: start}); } } else if (stream[this._current] === "|") { start = this._current; this._current++; if (stream[this._current] === "|") { this._current++; tokens.push({type: TOK_OR, value: "||", start: start}); } else { tokens.push({type: TOK_PIPE, value: "|", start: start}); } } else { var error = new Error("Unknown character:" + stream[this._current]); error.name = "LexerError"; throw error; } } return tokens; }, _consumeUnquotedIdentifier: function(stream) { var start = this._current; this._current++; while (this._current < stream.length && isAlphaNum(stream[this._current])) { this._current++; } return stream.slice(start, this._current); }, _consumeQuotedIdentifier: function(stream) { var start = this._current; this._current++; var maxLength = stream.length; while (stream[this._current] !== "\"" && this._current < maxLength) { var current = this._current; if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === "\"")) { current += 2; } else { current++; } this._current = current; } this._current++; return JSON.parse(stream.slice(start, this._current)); }, _consumeRawStringLiteral: function(stream) { var start = this._current; this._current++; var maxLength = stream.length; while (stream[this._current] !== "'" && this._current < maxLength) { var current = this._current; if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === "'")) { current += 2; } else { current++; } this._current = current; } this._current++; var literal = stream.slice(start + 1, this._current - 1); return literal.replace("\\'", "'"); }, _consumeNumber: function(stream) { var start = this._current; this._current++; var maxLength = stream.length; while (isNum(stream[this._current]) && this._current < maxLength) { this._current++; } var value = parseInt(stream.slice(start, this._current)); return {type: TOK_NUMBER, value: value, start: start}; }, _consumeLBracket: function(stream) { var start = this._current; this._current++; if (stream[this._current] === "?") { this._current++; return {type: TOK_FILTER, value: "[?", start: start}; } else if (stream[this._current] === "]") { this._current++; return {type: TOK_FLATTEN, value: "[]", start: start}; } else { return {type: TOK_LBRACKET, value: "[", start: start}; } }, _consumeOperator: function(stream) { var start = this._current; var startingChar = stream[start]; this._current++; if (startingChar === "!") { if (stream[this._current] === "=") { this._current++; return {type: TOK_NE, value: "!=", start: start}; } else { return {type: TOK_NOT, value: "!", start: start}; } } else if (startingChar === "<") { if (stream[this._current] === "=") { this._current++; return {type: TOK_LTE, value: "<=", start: start}; } else { return {type: TOK_LT, value: "<", start: start}; } } else if (startingChar === ">") { if (stream[this._current] === "=") { this._current++; return {type: TOK_GTE, value: ">=", start: start}; } else { return {type: TOK_GT, value: ">", start: start}; } } else if (startingChar === "=") { if (stream[this._current] === "=") { this._current++; return {type: TOK_EQ, value: "==", start: start}; } } }, _consumeLiteral: function(stream) { this._current++; var start = this._current; var maxLength = stream.length; var literal; while(stream[this._current] !== "`" && this._current < maxLength) { var current = this._current; if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === "`")) { current += 2; } else { current++; } this._current = current; } var literalString = trimLeft(stream.slice(start, this._current)); literalString = literalString.replace("\\`", "`"); if (this._looksLikeJSON(literalString)) { literal = JSON.parse(literalString); } else { literal = JSON.parse("\"" + literalString + "\""); } this._current++; return literal; }, _looksLikeJSON: function(literalString) { var startingChars = "[{\""; var jsonLiterals = ["true", "false", "null"]; var numberLooking = "-0123456789"; if (literalString === "") { return false; } else if (startingChars.indexOf(literalString[0]) >= 0) { return true; } else if (jsonLiterals.indexOf(literalString) >= 0) { return true; } else if (numberLooking.indexOf(literalString[0]) >= 0) { try { JSON.parse(literalString); return true; } catch (ex) { return false; } } else { return false; } } }; var bindingPower = {}; bindingPower[TOK_EOF] = 0; bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; bindingPower[TOK_QUOTEDIDENTIFIER] = 0; bindingPower[TOK_RBRACKET] = 0; bindingPower[TOK_RPAREN] = 0; bindingPower[TOK_COMMA] = 0; bindingPower[TOK_RBRACE] = 0; bindingPower[TOK_NUMBER] = 0; bindingPower[TOK_CURRENT] = 0; bindingPower[TOK_EXPREF] = 0; bindingPower[TOK_PIPE] = 1; bindingPower[TOK_OR] = 2; bindingPower[TOK_AND] = 3; bindingPower[TOK_EQ] = 5; bindingPower[TOK_GT] = 5; bindingPower[TOK_LT] = 5; bindingPower[TOK_GTE] = 5; bindingPower[TOK_LTE] = 5; bindingPower[TOK_NE] = 5; bindingPower[TOK_FLATTEN] = 9; bindingPower[TOK_STAR] = 20; bindingPower[TOK_FILTER] = 21; bindingPower[TOK_DOT] = 40; bindingPower[TOK_NOT] = 45; bindingPower[TOK_LBRACE] = 50; bindingPower[TOK_LBRACKET] = 55; bindingPower[TOK_LPAREN] = 60; function Parser() { } Parser.prototype = { parse: function(expression) { this._loadTokens(expression); this.index = 0; var ast = this.expression(0); if (this._lookahead(0) !== TOK_EOF) { var t = this._lookaheadToken(0); var error = new Error( "Unexpected token type: " + t.type + ", value: " + t.value); error.name = "ParserError"; throw error; } return ast; }, _loadTokens: function(expression) { var lexer = new Lexer(); var tokens = lexer.tokenize(expression); tokens.push({type: TOK_EOF, value: "", start: expression.length}); this.tokens = tokens; }, expression: function(rbp) { var leftToken = this._lookaheadToken(0); this._advance(); var left = this.nud(leftToken); var currentToken = this._lookahead(0); while (rbp < bindingPower[currentToken]) { this._advance(); left = this.led(currentToken, left); currentToken = this._lookahead(0); } return left; }, _lookahead: function(number) { return this.tokens[this.index + number].type; }, _lookaheadToken: function(number) { return this.tokens[this.index + number]; }, _advance: function() { this.index++; }, nud: function(token) { var left; var right; var expression; switch (token.type) { case TOK_LITERAL: return {type: "Literal", value: token.value}; case TOK_UNQUOTEDIDENTIFIER: return {type: "Field", name: token.value}; case TOK_QUOTEDIDENTIFIER: var node = {type: "Field", name: token.value}; if (this._lookahead(0) === TOK_LPAREN) { throw new Error("Quoted identifier not allowed for function names."); } else { return node; } break; case TOK_NOT: right = this.expression(bindingPower.Not); return {type: "NotExpression", children: [right]}; case TOK_STAR: left = {type: "Identity"}; right = null; if (this._lookahead(0) === TOK_RBRACKET) { right = {type: "Identity"}; } else { right = this._parseProjectionRHS(bindingPower.Star); } return {type: "ValueProjection", children: [left, right]}; case TOK_FILTER: return this.led(token.type, {type: "Identity"}); case TOK_LBRACE: return this._parseMultiselectHash(); case TOK_FLATTEN: left = {type: TOK_FLATTEN, children: [{type: "Identity"}]}; right = this._parseProjectionRHS(bindingPower.Flatten); return {type: "Projection", children: [left, right]}; case TOK_LBRACKET: if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { right = this._parseIndexExpression(); return this._projectIfSlice({type: "Identity"}, right); } else if (this._lookahead(0) === TOK_STAR && this._lookahead(1) === TOK_RBRACKET) { this._advance(); this._advance(); right = this._parseProjectionRHS(bindingPower.Star); return {type: "Projection", children: [{type: "Identity"}, right]}; } else { return this._parseMultiselectList(); } break; case TOK_CURRENT: return {type: TOK_CURRENT}; case TOK_EXPREF: expression = this.expression(bindingPower.Expref); return {type: "ExpressionReference", children: [expression]}; case TOK_LPAREN: var args = []; while (this._lookahead(0) !== TOK_RPAREN) { if (this._lookahead(0) === TOK_CURRENT) { expression = {type: TOK_CURRENT}; this._advance(); } else { expression = this.expression(0); } args.push(expression); } this._match(TOK_RPAREN); return args[0]; default: this._errorToken(token); } }, led: function(tokenName, left) { var right; switch(tokenName) { case TOK_DOT: var rbp = bindingPower.Dot; if (this._lookahead(0) !== TOK_STAR) { right = this._parseDotRHS(rbp); return {type: "Subexpression", children: [left, right]}; } else { this._advance(); right = this._parseProjectionRHS(rbp); return {type: "ValueProjection", children: [left, right]}; } break; case TOK_PIPE: right = this.expression(bindingPower.Pipe); return {type: TOK_PIPE, children: [left, right]}; case TOK_OR: right = this.expression(bindingPower.Or); return {type: "OrExpression", children: [left, right]}; case TOK_AND: right = this.expression(bindingPower.And); return {type: "AndExpression", children: [left, right]}; case TOK_LPAREN: var name = left.name; var args = []; var expression, node; while (this._lookahead(0) !== TOK_RPAREN) { if (this._lookahead(0) === TOK_CURRENT) { expression = {type: TOK_CURRENT}; this._advance(); } else { expression = this.expression(0); } if (this._lookahead(0) === TOK_COMMA) { this._match(TOK_COMMA); } args.push(expression); } this._match(TOK_RPAREN); node = {type: "Function", name: name, children: args}; return node; case TOK_FILTER: var condition = this.expression(0); this._match(TOK_RBRACKET); if (this._lookahead(0) === TOK_FLATTEN) { right = {type: "Identity"}; } else { right = this._parseProjectionRHS(bindingPower.Filter); } return {type: "FilterProjection", children: [left, right, condition]}; case TOK_FLATTEN: var leftNode = {type: TOK_FLATTEN, children: [left]}; var rightNode = this._parseProjectionRHS(bindingPower.Flatten); return {type: "Projection", children: [leftNode, rightNode]}; case TOK_EQ: case TOK_NE: case TOK_GT: case TOK_GTE: case TOK_LT: case TOK_LTE: return this._parseComparator(left, tokenName); case TOK_LBRACKET: var token = this._lookaheadToken(0); if (token.type === TOK_NUMBER || token.type === TOK_COLON) { right = this._parseIndexExpression(); return this._projectIfSlice(left, right); } else { this._match(TOK_STAR); this._match(TOK_RBRACKET); right = this._parseProjectionRHS(bindingPower.Star); return {type: "Projection", children: [left, right]}; } break; default: this._errorToken(this._lookaheadToken(0)); } }, _match: function(tokenType) { if (this._lookahead(0) === tokenType) { this._advance(); } else { var t = this._lookaheadToken(0); var error = new Error("Expected " + tokenType + ", got: " + t.type); error.name = "ParserError"; throw error; } }, _errorToken: function(token) { var error = new Error("Invalid token (" + token.type + "): \"" + token.value + "\""); error.name = "ParserError"; throw error; }, _parseIndexExpression: function() { if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { return this._parseSliceExpression(); } else { var node = { type: "Index", value: this._lookaheadToken(0).value}; this._advance(); this._match(TOK_RBRACKET); return node; } }, _projectIfSlice: function(left, right) { var indexExpr = {type: "IndexExpression", children: [left, right]}; if (right.type === "Slice") { return { type: "Projection", children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] }; } else { return indexExpr; } }, _parseSliceExpression: function() { var parts = [null, null, null]; var index = 0; var currentToken = this._lookahead(0); while (currentToken !== TOK_RBRACKET && index < 3) { if (currentToken === TOK_COLON) { index++; this._advance(); } else if (currentToken === TOK_NUMBER) { parts[index] = this._lookaheadToken(0).value; this._advance(); } else { var t = this._lookahead(0); var error = new Error("Syntax error, unexpected token: " + t.value + "(" + t.type + ")"); error.name = "Parsererror"; throw error; } currentToken = this._lookahead(0); } this._match(TOK_RBRACKET); return { type: "Slice", children: parts }; }, _parseComparator: function(left, comparator) { var right = this.expression(bindingPower[comparator]); return {type: "Comparator", name: comparator, children: [left, right]}; }, _parseDotRHS: function(rbp) { var lookahead = this._lookahead(0); var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; if (exprTokens.indexOf(lookahead) >= 0) { return this.expression(rbp); } else if (lookahead === TOK_LBRACKET) { this._match(TOK_LBRACKET); return this._parseMultiselectList(); } else if (lookahead === TOK_LBRACE) { this._match(TOK_LBRACE); return this._parseMultiselectHash(); } }, _parseProjectionRHS: function(rbp) { var right; if (bindingPower[this._lookahead(0)] < 10) { right = {type: "Identity"}; } else if (this._lookahead(0) === TOK_LBRACKET) { right = this.expression(rbp); } else if (this._lookahead(0) === TOK_FILTER) { right = this.expression(rbp); } else if (this._lookahead(0) === TOK_DOT) { this._match(TOK_DOT); right = this._parseDotRHS(rbp); } else { var t = this._lookaheadToken(0); var error = new Error("Sytanx error, unexpected token: " + t.value + "(" + t.type + ")"); error.name = "ParserError"; throw error; } return right; }, _parseMultiselectList: function() { var expressions = []; while (this._lookahead(0) !== TOK_RBRACKET) { var expression = this.expression(0); expressions.push(expression); if (this._lookahead(0) === TOK_COMMA) { this._match(TOK_COMMA); if (this._lookahead(0) === TOK_RBRACKET) { throw new Error("Unexpected token Rbracket"); } } } this._match(TOK_RBRACKET); return {type: "MultiSelectList", children: expressions}; }, _parseMultiselectHash: function() { var pairs = []; var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; var keyToken, keyName, value, node; for (;;) { keyToken = this._lookaheadToken(0); if (identifierTypes.indexOf(keyToken.type) < 0) { throw new Error("Expecting an identifier token, got: " + keyToken.type); } keyName = keyToken.value; this._advance(); this._match(TOK_COLON); value = this.expression(0); node = {type: "KeyValuePair", name: keyName, value: value}; pairs.push(node); if (this._lookahead(0) === TOK_COMMA) { this._match(TOK_COMMA); } else if (this._lookahead(0) === TOK_RBRACE) { this._match(TOK_RBRACE); break; } } return {type: "MultiSelectHash", children: pairs}; } }; function TreeInterpreter(runtime) { this.runtime = runtime; } TreeInterpreter.prototype = { search: function(node, value) { return this.visit(node, value); }, visit: function(node, value) { var matched, current, result, first, second, field, left, right, collected, i; switch (node.type) { case "Field": if (value === null ) { return null; } else if (isObject(value)) { field = value[node.name]; if (field === undefined) { return null; } else { return field; } } else { return null; } break; case "Subexpression": result = this.visit(node.children[0], value); for (i = 1; i < node.children.length; i++) { result = this.visit(node.children[1], result); if (result === null) { return null; } } return result; case "IndexExpression": left = this.visit(node.children[0], value); right = this.visit(node.children[1], left); return right; case "Index": if (!isArray(value)) { return null; } var index = node.value; if (index < 0) { index = value.length + index; } result = value[index]; if (result === undefined) { result = null; } return result; case "Slice": if (!isArray(value)) { return null; } var sliceParams = node.children.slice(0); var computed = this.computeSliceParams(value.length, sliceParams); var start = computed[0]; var stop = computed[1]; var step = computed[2]; result = []; if (step > 0) { for (i = start; i < stop; i += step) { result.push(value[i]); } } else { for (i = start; i > stop; i += step) { result.push(value[i]); } } return result; case "Projection": var base = this.visit(node.children[0], value); if (!isArray(base)) { return null; } collected = []; for (i = 0; i < base.length; i++) { current = this.visit(node.children[1], base[i]); if (current !== null) { collected.push(current); } } return collected; case "ValueProjection": base = this.visit(node.children[0], value); if (!isObject(base)) { return null; } collected = []; var values = objValues(base); for (i = 0; i < values.length; i++) { current = this.visit(node.children[1], values[i]); if (current !== null) { collected.push(current); } } return collected; case "FilterProjection": base = this.visit(node.children[0], value); if (!isArray(base)) { return null; } var filtered = []; var finalResults = []; for (i = 0; i < base.length; i++) { matched = this.visit(node.children[2], base[i]); if (!isFalse(matched)) { filtered.push(base[i]); } } for (var j = 0; j < filtered.length; j++) { current = this.visit(node.children[1], filtered[j]); if (current !== null) { finalResults.push(current); } } return finalResults; case "Comparator": first = this.visit(node.children[0], value); second = this.visit(node.children[1], value); switch(node.name) { case TOK_EQ: result = strictDeepEqual(first, second); break; case TOK_NE: result = !strictDeepEqual(first, second); break; case TOK_GT: result = first > second; break; case TOK_GTE: result = first >= second; break; case TOK_LT: result = first < second; break; case TOK_LTE: result = first <= second; break; default: throw new Error("Unknown comparator: " + node.name); } return result; case TOK_FLATTEN: var original = this.visit(node.children[0], value); if (!isArray(original)) { return null; } var merged = []; for (i = 0; i < original.length; i++) { current = original[i]; if (isArray(current)) { merged.push.apply(merged, current); } else { merged.push(current); } } return merged; case "Identity": return value; case "MultiSelectList": if (value === null) { return null; } collected = []; for (i = 0; i < node.children.length; i++) { collected.push(this.visit(node.children[i], value)); } return collected; case "MultiSelectHash": if (value === null) { return null; } collected = {}; var child; for (i = 0; i < node.children.length; i++) { child = node.children[i]; collected[child.name] = this.visit(child.value, value); } return collected; case "OrExpression": matched = this.visit(node.children[0], value); if (isFalse(matched)) { matched = this.visit(node.children[1], value); } return matched; case "AndExpression": first = this.visit(node.children[0], value); if (isFalse(first) === true) { return first; } return this.visit(node.children[1], value); case "NotExpression": first = this.visit(node.children[0], value); return isFalse(first); case "Literal": return node.value; case TOK_PIPE: left = this.visit(node.children[0], value); return this.visit(node.children[1], left); case TOK_CURRENT: return value; case "Function": var resolvedArgs = []; for (i = 0; i < node.children.length; i++) { resolvedArgs.push(this.visit(node.children[i], value)); } return this.runtime.callFunction(node.name, resolvedArgs); case "ExpressionReference": var refNode = node.children[0]; refNode.jmespathType = TOK_EXPREF; return refNode; default: throw new Error("Unknown node type: " + node.type); } }, computeSliceParams: function(arrayLength, sliceParams) { var start = sliceParams[0]; var stop = sliceParams[1]; var step = sliceParams[2]; var computed = [null, null, null]; if (step === null) { step = 1; } else if (step === 0) { var error = new Error("Invalid slice, step cannot be 0"); error.name = "RuntimeError"; throw error; } var stepValueNegative = step < 0 ? true : false; if (start === null) { start = stepValueNegative ? arrayLength - 1 : 0; } else { start = this.capSliceRange(arrayLength, start, step); } if (stop === null) { stop = stepValueNegative ? -1 : arrayLength; } else { stop = this.capSliceRange(arrayLength, stop, step); } computed[0] = start; computed[1] = stop; computed[2] = step; return computed; }, capSliceRange: function(arrayLength, actualValue, step) { if (actualValue < 0) { actualValue += arrayLength; if (actualValue < 0) { actualValue = step < 0 ? -1 : 0; } } else if (actualValue >= arrayLength) { actualValue = step < 0 ? arrayLength - 1 : arrayLength; } return actualValue; } }; function Runtime(interpreter) { this._interpreter = interpreter; this.functionTable = { abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]}, avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]}, contains: { _func: this._functionContains, _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}, {types: [TYPE_ANY]}]}, "ends_with": { _func: this._functionEndsWith, _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]}, length: { _func: this._functionLength, _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]}, map: { _func: this._functionMap, _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]}, max: { _func: this._functionMax, _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, "merge": { _func: this._functionMerge, _signature: [{types: [TYPE_OBJECT], variadic: true}] }, "max_by": { _func: this._functionMaxBy, _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] }, sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, "starts_with": { _func: this._functionStartsWith, _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, min: { _func: this._functionMin, _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, "min_by": { _func: this._functionMinBy, _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] }, type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]}, keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]}, values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]}, sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]}, "sort_by": { _func: this._functionSortBy, _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] }, join: { _func: this._functionJoin, _signature: [ {types: [TYPE_STRING]}, {types: [TYPE_ARRAY_STRING]} ] }, reverse: { _func: this._functionReverse, _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]}, "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]}, "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]}, "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]}, "not_null": { _func: this._functionNotNull, _signature: [{types: [TYPE_ANY], variadic: true}] } }; } Runtime.prototype = { callFunction: function(name, resolvedArgs) { var functionEntry = this.functionTable[name]; if (functionEntry === undefined) { throw new Error("Unknown function: " + name + "()"); } this._validateArgs(name, resolvedArgs, functionEntry._signature); return functionEntry._func.call(this, resolvedArgs); }, _validateArgs: function(name, args, signature) { var pluralized; if (signature[signature.length - 1].variadic) { if (args.length < signature.length) { pluralized = signature.length === 1 ? " argument" : " arguments"; throw new Error("ArgumentError: " + name + "() " + "takes at least" + signature.length + pluralized + " but received " + args.length); } } else if (args.length !== signature.length) { pluralized = signature.length === 1 ? " argument" : " arguments"; throw new Error("ArgumentError: " + name + "() " + "takes " + signature.length + pluralized + " but received " + args.length); } var currentSpec; var actualType; var typeMatched; for (var i = 0; i < signature.length; i++) { typeMatched = false; currentSpec = signature[i].types; actualType = this._getTypeName(args[i]); for (var j = 0; j < currentSpec.length; j++) { if (this._typeMatches(actualType, currentSpec[j], args[i])) { typeMatched = true; break; } } if (!typeMatched) { throw new Error("TypeError: " + name + "() " + "expected argument " + (i + 1) + " to be type " + currentSpec + " but received type " + actualType + " instead."); } } }, _typeMatches: function(actual, expected, argValue) { if (expected === TYPE_ANY) { return true; } if (expected === TYPE_ARRAY_STRING || expected === TYPE_ARRAY_NUMBER || expected === TYPE_ARRAY) { if (expected === TYPE_ARRAY) { return actual === TYPE_ARRAY; } else if (actual === TYPE_ARRAY) { var subtype; if (expected === TYPE_ARRAY_NUMBER) { subtype = TYPE_NUMBER; } else if (expected === TYPE_ARRAY_STRING) { subtype = TYPE_STRING; } for (var i = 0; i < argValue.length; i++) { if (!this._typeMatches( this._getTypeName(argValue[i]), subtype, argValue[i])) { return false; } } return true; } } else { return actual === expected; } }, _getTypeName: function(obj) { switch (Object.prototype.toString.call(obj)) { case "[object String]": return TYPE_STRING; case "[object Number]": return TYPE_NUMBER; case "[object Array]": return TYPE_ARRAY; case "[object Boolean]": return TYPE_BOOLEAN; case "[object Null]": return TYPE_NULL; case "[object Object]": if (obj.jmespathType === TOK_EXPREF) { return TYPE_EXPREF; } else { return TYPE_OBJECT; } } }, _functionStartsWith: function(resolvedArgs) { return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; }, _functionEndsWith: function(resolvedArgs) { var searchStr = resolvedArgs[0]; var suffix = resolvedArgs[1]; return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; }, _functionReverse: function(resolvedArgs) { var typeName = this._getTypeName(resolvedArgs[0]); if (typeName === TYPE_STRING) { var originalStr = resolvedArgs[0]; var reversedStr = ""; for (var i = originalStr.length - 1; i >= 0; i--) { reversedStr += originalStr[i]; } return reversedStr; } else { var reversedArray = resolvedArgs[0].slice(0); reversedArray.reverse(); return reversedArray; } }, _functionAbs: function(resolvedArgs) { return Math.abs(resolvedArgs[0]); }, _functionCeil: function(resolvedArgs) { return Math.ceil(resolvedArgs[0]); }, _functionAvg: function(resolvedArgs) { var sum = 0; var inputArray = resolvedArgs[0]; for (var i = 0; i < inputArray.length; i++) { sum += inputArray[i]; } return sum / inputArray.length; }, _functionContains: function(resolvedArgs) { return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; }, _functionFloor: function(resolvedArgs) { return Math.floor(resolvedArgs[0]); }, _functionLength: function(resolvedArgs) { if (!isObject(resolvedArgs[0])) { return resolvedArgs[0].length; } else { return Object.keys(resolvedArgs[0]).length; } }, _functionMap: function(resolvedArgs) { var mapped = []; var interpreter = this._interpreter; var exprefNode = resolvedArgs[0]; var elements = resolvedArgs[1]; for (var i = 0; i < elements.length; i++) { mapped.push(interpreter.visit(exprefNode, elements[i])); } return mapped; }, _functionMerge: function(resolvedArgs) { var merged = {}; for (var i = 0; i < resolvedArgs.length; i++) { var current = resolvedArgs[i]; for (var key in current) { merged[key] = current[key]; } } return merged; }, _functionMax: function(resolvedArgs) { if (resolvedArgs[0].length > 0) { var typeName = this._getTypeName(resolvedArgs[0][0]); if (typeName === TYPE_NUMBER) { return Math.max.apply(Math, resolvedArgs[0]); } else { var elements = resolvedArgs[0]; var maxElement = elements[0]; for (var i = 1; i < elements.length; i++) { if (maxElement.localeCompare(elements[i]) < 0) { maxElement = elements[i]; } } return maxElement; } } else { return null; } }, _functionMin: function(resolvedArgs) { if (resolvedArgs[0].length > 0) { var typeName = this._getTypeName(resolvedArgs[0][0]); if (typeName === TYPE_NUMBER) { return Math.min.apply(Math, resolvedArgs[0]); } else { var elements = resolvedArgs[0]; var minElement = elements[0]; for (var i = 1; i < elements.length; i++) { if (elements[i].localeCompare(minElement) < 0) { minElement = elements[i]; } } return minElement; } } else { return null; } }, _functionSum: function(resolvedArgs) { var sum = 0; var listToSum = resolvedArgs[0]; for (var i = 0; i < listToSum.length; i++) { sum += listToSum[i]; } return sum; }, _functionType: function(resolvedArgs) { switch (this._getTypeName(resolvedArgs[0])) { case TYPE_NUMBER: return "number"; case TYPE_STRING: return "string"; case TYPE_ARRAY: return "array"; case TYPE_OBJECT: return "object"; case TYPE_BOOLEAN: return "boolean"; case TYPE_EXPREF: return "expref"; case TYPE_NULL: return "null"; } }, _functionKeys: function(resolvedArgs) { return Object.keys(resolvedArgs[0]); }, _functionValues: function(resolvedArgs) { var obj = resolvedArgs[0]; var keys = Object.keys(obj); var values = []; for (var i = 0; i < keys.length; i++) { values.push(obj[keys[i]]); } return values; }, _functionJoin: function(resolvedArgs) { var joinChar = resolvedArgs[0]; var listJoin = resolvedArgs[1]; return listJoin.join(joinChar); }, _functionToArray: function(resolvedArgs) { if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { return resolvedArgs[0]; } else { return [resolvedArgs[0]]; } }, _functionToString: function(resolvedArgs) { if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { return resolvedArgs[0]; } else { return JSON.stringify(resolvedArgs[0]); } }, _functionToNumber: function(resolvedArgs) { var typeName = this._getTypeName(resolvedArgs[0]); var convertedValue; if (typeName === TYPE_NUMBER) { return resolvedArgs[0]; } else if (typeName === TYPE_STRING) { convertedValue = +resolvedArgs[0]; if (!isNaN(convertedValue)) { return convertedValue; } } return null; }, _functionNotNull: function(resolvedArgs) { for (var i = 0; i < resolvedArgs.length; i++) { if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { return resolvedArgs[i]; } } return null; }, _functionSort: function(resolvedArgs) { var sortedArray = resolvedArgs[0].slice(0); sortedArray.sort(); return sortedArray; }, _functionSortBy: function(resolvedArgs) { var sortedArray = resolvedArgs[0].slice(0); if (sortedArray.length === 0) { return sortedArray; } var interpreter = this._interpreter; var exprefNode = resolvedArgs[1]; var requiredType = this._getTypeName( interpreter.visit(exprefNode, sortedArray[0])); if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { throw new Error("TypeError"); } var that = this; var decorated = []; for (var i = 0; i < sortedArray.length; i++) { decorated.push([i, sortedArray[i]]); } decorated.sort(function(a, b) { var exprA = interpreter.visit(exprefNode, a[1]); var exprB = interpreter.visit(exprefNode, b[1]); if (that._getTypeName(exprA) !== requiredType) { throw new Error( "TypeError: expected " + requiredType + ", received " + that._getTypeName(exprA)); } else if (that._getTypeName(exprB) !== requiredType) { throw new Error( "TypeError: expected " + requiredType + ", received " + that._getTypeName(exprB)); } if (exprA > exprB) { return 1; } else if (exprA < exprB) { return -1; } else { return a[0] - b[0]; } }); for (var j = 0; j < decorated.length; j++) { sortedArray[j] = decorated[j][1]; } return sortedArray; }, _functionMaxBy: function(resolvedArgs) { var exprefNode = resolvedArgs[1]; var resolvedArray = resolvedArgs[0]; var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); var maxNumber = -Infinity; var maxRecord; var current; for (var i = 0; i < resolvedArray.length; i++) { current = keyFunction(resolvedArray[i]); if (current > maxNumber) { maxNumber = current; maxRecord = resolvedArray[i]; } } return maxRecord; }, _functionMinBy: function(resolvedArgs) { var exprefNode = resolvedArgs[1]; var resolvedArray = resolvedArgs[0]; var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); var minNumber = Infinity; var minRecord; var current; for (var i = 0; i < resolvedArray.length; i++) { current = keyFunction(resolvedArray[i]); if (current < minNumber) { minNumber = current; minRecord = resolvedArray[i]; } } return minRecord; }, createKeyFunction: function(exprefNode, allowedTypes) { var that = this; var interpreter = this._interpreter; var keyFunc = function(x) { var current = interpreter.visit(exprefNode, x); if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { var msg = "TypeError: expected one of " + allowedTypes + ", received " + that._getTypeName(current); throw new Error(msg); } return current; }; return keyFunc; } }; function compile(stream) { var parser = new Parser(); var ast = parser.parse(stream); return ast; } function tokenize(stream) { var lexer = new Lexer(); return lexer.tokenize(stream); } function search(data, expression) { var parser = new Parser(); var runtime = new Runtime(); var interpreter = new TreeInterpreter(runtime); runtime._interpreter = interpreter; var node = parser.parse(expression); return interpreter.search(node, data); } exports.tokenize = tokenize; exports.compile = compile; exports.search = search; exports.strictDeepEqual = strictDeepEqual; })(typeof exports === "undefined" ? this.jmespath = {} : exports); },{}],80:[function(require,module,exports){ 'use strict'; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (Array.isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; },{}],81:[function(require,module,exports){ 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return Object.keys(obj).map(function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (Array.isArray(obj[k])) { return obj[k].map(function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; },{}],82:[function(require,module,exports){ arguments[4][66][0].apply(exports,arguments) },{"./decode":80,"./encode":81}],83:[function(require,module,exports){ var punycode = require('punycode'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), autoEscape = ['\''].concat(unwise), nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, unsafeProtocol = { 'javascript': true, 'javascript:': true }, hostlessProtocol = { 'javascript': true, 'javascript:': true }, slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } var rest = url; rest = rest.trim(); var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } var auth, atSign; if (hostEnd === -1) { atSign = rest.lastIndexOf('@'); } else { atSign = rest.lastIndexOf('@', hostEnd); } if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); this.parseHost(); this.hostname = this.hostname || ''; var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { newpart += 'x'; } else { newpart += part[j]; } } if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { var domainArray = this.hostname.split('.'); var newOut = []; for (var i = 0; i < domainArray.length; ++i) { var s = domainArray[i]; newOut.push(s.match(/[^A-Za-z0-9_-]/) ? 'xn--' + punycode.encode(s) : s); } this.hostname = newOut.join('.'); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } if (!unsafeProtocol[lowerProto]) { for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } var hash = rest.indexOf('#'); if (hash !== -1) { this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } this.href = this.format(); return this; }; function urlFormat(obj) { if (isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); Object.keys(this).forEach(function(k) { result[k] = this[k]; }, this); result.hash = relative.hash; if (relative.href === '') { result.href = result.format(); return result; } if (relative.slashes && !relative.protocol) { Object.keys(relative).forEach(function(k) { if (k !== 'protocol') result[k] = relative[k]; }); if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { if (!slashedProtocol[relative.protocol]) { Object.keys(relative).forEach(function(k) { result[k] = relative[k]; }); result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; } else if (relPath.length) { if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!isNullOrUndefined(relative.search)) { if (psychotic) { result.hostname = result.host = srcPath.shift(); var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { result.pathname = null; if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host) && (last === '.' || last === '..') || last === ''); var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last == '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; function isString(arg) { return typeof arg === "string"; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isNull(arg) { return arg === null; } function isNullOrUndefined(arg) { return arg == null; } },{"punycode":63,"querystring":66}],84:[function(require,module,exports){ (function() { var XMLAttribute, create; create = require('lodash/object/create'); module.exports = XMLAttribute = (function() { function XMLAttribute(parent, name, value) { this.stringify = parent.stringify; if (name == null) { throw new Error("Missing attribute name of element " + parent.name); } if (value == null) { throw new Error("Missing attribute value for attribute " + name + " of element " + parent.name); } this.name = this.stringify.attName(name); this.value = this.stringify.attValue(value); } XMLAttribute.prototype.clone = function() { return create(XMLAttribute.prototype, this); }; XMLAttribute.prototype.toString = function(options, level) { return ' ' + this.name + '="' + this.value + '"'; }; return XMLAttribute; })(); }).call(this); },{"lodash/object/create":143}],85:[function(require,module,exports){ (function() { var XMLBuilder, XMLDeclaration, XMLDocType, XMLElement, XMLStringifier; XMLStringifier = require('./XMLStringifier'); XMLDeclaration = require('./XMLDeclaration'); XMLDocType = require('./XMLDocType'); XMLElement = require('./XMLElement'); module.exports = XMLBuilder = (function() { function XMLBuilder(name, options) { var root, temp; if (name == null) { throw new Error("Root element needs a name"); } if (options == null) { options = {}; } this.options = options; this.stringify = new XMLStringifier(options); temp = new XMLElement(this, 'doc'); root = temp.element(name); root.isRoot = true; root.documentObject = this; this.rootObject = root; if (!options.headless) { root.declaration(options); if ((options.pubID != null) || (options.sysID != null)) { root.doctype(options); } } } XMLBuilder.prototype.root = function() { return this.rootObject; }; XMLBuilder.prototype.end = function(options) { return this.toString(options); }; XMLBuilder.prototype.toString = function(options) { var indent, newline, offset, pretty, r, ref, ref1, ref2; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; r = ''; if (this.xmldec != null) { r += this.xmldec.toString(options); } if (this.doctype != null) { r += this.doctype.toString(options); } r += this.rootObject.toString(options); if (pretty && r.slice(-newline.length) === newline) { r = r.slice(0, -newline.length); } return r; }; return XMLBuilder; })(); }).call(this); },{"./XMLDeclaration":92,"./XMLDocType":93,"./XMLElement":94,"./XMLStringifier":98}],86:[function(require,module,exports){ (function() { var XMLCData, XMLNode, create, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; create = require('lodash/object/create'); XMLNode = require('./XMLNode'); module.exports = XMLCData = (function(superClass) { extend(XMLCData, superClass); function XMLCData(parent, text) { XMLCData.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing CDATA text"); } this.text = this.stringify.cdata(text); } XMLCData.prototype.clone = function() { return create(XMLCData.prototype, this); }; XMLCData.prototype.toString = function(options, level) { var indent, newline, offset, pretty, r, ref, ref1, ref2, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; if (pretty) { r += space; } r += ''; if (pretty) { r += newline; } return r; }; return XMLCData; })(XMLNode); }).call(this); },{"./XMLNode":95,"lodash/object/create":143}],87:[function(require,module,exports){ (function() { var XMLComment, XMLNode, create, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; create = require('lodash/object/create'); XMLNode = require('./XMLNode'); module.exports = XMLComment = (function(superClass) { extend(XMLComment, superClass); function XMLComment(parent, text) { XMLComment.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing comment text"); } this.text = this.stringify.comment(text); } XMLComment.prototype.clone = function() { return create(XMLComment.prototype, this); }; XMLComment.prototype.toString = function(options, level) { var indent, newline, offset, pretty, r, ref, ref1, ref2, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; if (pretty) { r += space; } r += ''; if (pretty) { r += newline; } return r; }; return XMLComment; })(XMLNode); }).call(this); },{"./XMLNode":95,"lodash/object/create":143}],88:[function(require,module,exports){ (function() { var XMLDTDAttList, create; create = require('lodash/object/create'); module.exports = XMLDTDAttList = (function() { function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) { this.stringify = parent.stringify; if (elementName == null) { throw new Error("Missing DTD element name"); } if (attributeName == null) { throw new Error("Missing DTD attribute name"); } if (!attributeType) { throw new Error("Missing DTD attribute type"); } if (!defaultValueType) { throw new Error("Missing DTD attribute default"); } if (defaultValueType.indexOf('#') !== 0) { defaultValueType = '#' + defaultValueType; } if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) { throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT"); } if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) { throw new Error("Default value only applies to #FIXED or #DEFAULT"); } this.elementName = this.stringify.eleName(elementName); this.attributeName = this.stringify.attName(attributeName); this.attributeType = this.stringify.dtdAttType(attributeType); this.defaultValue = this.stringify.dtdAttDefault(defaultValue); this.defaultValueType = defaultValueType; } XMLDTDAttList.prototype.clone = function() { return create(XMLDTDAttList.prototype, this); }; XMLDTDAttList.prototype.toString = function(options, level) { var indent, newline, offset, pretty, r, ref, ref1, ref2, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; if (pretty) { r += space; } r += ''; if (pretty) { r += newline; } return r; }; return XMLDTDAttList; })(); }).call(this); },{"lodash/object/create":143}],89:[function(require,module,exports){ (function() { var XMLDTDElement, create, isArray; create = require('lodash/object/create'); isArray = require('lodash/lang/isArray'); module.exports = XMLDTDElement = (function() { function XMLDTDElement(parent, name, value) { this.stringify = parent.stringify; if (name == null) { throw new Error("Missing DTD element name"); } if (!value) { value = '(#PCDATA)'; } if (isArray(value)) { value = '(' + value.join(',') + ')'; } this.name = this.stringify.eleName(name); this.value = this.stringify.dtdElementValue(value); } XMLDTDElement.prototype.clone = function() { return create(XMLDTDElement.prototype, this); }; XMLDTDElement.prototype.toString = function(options, level) { var indent, newline, offset, pretty, r, ref, ref1, ref2, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; if (pretty) { r += space; } r += ''; if (pretty) { r += newline; } return r; }; return XMLDTDElement; })(); }).call(this); },{"lodash/lang/isArray":135,"lodash/object/create":143}],90:[function(require,module,exports){ (function() { var XMLDTDEntity, create, isObject; create = require('lodash/object/create'); isObject = require('lodash/lang/isObject'); module.exports = XMLDTDEntity = (function() { function XMLDTDEntity(parent, pe, name, value) { this.stringify = parent.stringify; if (name == null) { throw new Error("Missing entity name"); } if (value == null) { throw new Error("Missing entity value"); } this.pe = !!pe; this.name = this.stringify.eleName(name); if (!isObject(value)) { this.value = this.stringify.dtdEntityValue(value); } else { if (!value.pubID && !value.sysID) { throw new Error("Public and/or system identifiers are required for an external entity"); } if (value.pubID && !value.sysID) { throw new Error("System identifier is required for a public external entity"); } if (value.pubID != null) { this.pubID = this.stringify.dtdPubID(value.pubID); } if (value.sysID != null) { this.sysID = this.stringify.dtdSysID(value.sysID); } if (value.nData != null) { this.nData = this.stringify.dtdNData(value.nData); } if (this.pe && this.nData) { throw new Error("Notation declaration is not allowed in a parameter entity"); } } } XMLDTDEntity.prototype.clone = function() { return create(XMLDTDEntity.prototype, this); }; XMLDTDEntity.prototype.toString = function(options, level) { var indent, newline, offset, pretty, r, ref, ref1, ref2, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; if (pretty) { r += space; } r += ''; if (pretty) { r += newline; } return r; }; return XMLDTDEntity; })(); }).call(this); },{"lodash/lang/isObject":139,"lodash/object/create":143}],91:[function(require,module,exports){ (function() { var XMLDTDNotation, create; create = require('lodash/object/create'); module.exports = XMLDTDNotation = (function() { function XMLDTDNotation(parent, name, value) { this.stringify = parent.stringify; if (name == null) { throw new Error("Missing notation name"); } if (!value.pubID && !value.sysID) { throw new Error("Public or system identifiers are required for an external entity"); } this.name = this.stringify.eleName(name); if (value.pubID != null) { this.pubID = this.stringify.dtdPubID(value.pubID); } if (value.sysID != null) { this.sysID = this.stringify.dtdSysID(value.sysID); } } XMLDTDNotation.prototype.clone = function() { return create(XMLDTDNotation.prototype, this); }; XMLDTDNotation.prototype.toString = function(options, level) { var indent, newline, offset, pretty, r, ref, ref1, ref2, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; if (pretty) { r += space; } r += ''; if (pretty) { r += newline; } return r; }; return XMLDTDNotation; })(); }).call(this); },{"lodash/object/create":143}],92:[function(require,module,exports){ (function() { var XMLDeclaration, XMLNode, create, isObject, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; create = require('lodash/object/create'); isObject = require('lodash/lang/isObject'); XMLNode = require('./XMLNode'); module.exports = XMLDeclaration = (function(superClass) { extend(XMLDeclaration, superClass); function XMLDeclaration(parent, version, encoding, standalone) { var ref; XMLDeclaration.__super__.constructor.call(this, parent); if (isObject(version)) { ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone; } if (!version) { version = '1.0'; } if (version != null) { this.version = this.stringify.xmlVersion(version); } if (encoding != null) { this.encoding = this.stringify.xmlEncoding(encoding); } if (standalone != null) { this.standalone = this.stringify.xmlStandalone(standalone); } } XMLDeclaration.prototype.clone = function() { return create(XMLDeclaration.prototype, this); }; XMLDeclaration.prototype.toString = function(options, level) { var indent, newline, offset, pretty, r, ref, ref1, ref2, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; if (pretty) { r += space; } r += ''; if (pretty) { r += newline; } return r; }; return XMLDeclaration; })(XMLNode); }).call(this); },{"./XMLNode":95,"lodash/lang/isObject":139,"lodash/object/create":143}],93:[function(require,module,exports){ (function() { var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLProcessingInstruction, create, isObject; create = require('lodash/object/create'); isObject = require('lodash/lang/isObject'); XMLCData = require('./XMLCData'); XMLComment = require('./XMLComment'); XMLDTDAttList = require('./XMLDTDAttList'); XMLDTDEntity = require('./XMLDTDEntity'); XMLDTDElement = require('./XMLDTDElement'); XMLDTDNotation = require('./XMLDTDNotation'); XMLProcessingInstruction = require('./XMLProcessingInstruction'); module.exports = XMLDocType = (function() { function XMLDocType(parent, pubID, sysID) { var ref, ref1; this.documentObject = parent; this.stringify = this.documentObject.stringify; this.children = []; if (isObject(pubID)) { ref = pubID, pubID = ref.pubID, sysID = ref.sysID; } if (sysID == null) { ref1 = [pubID, sysID], sysID = ref1[0], pubID = ref1[1]; } if (pubID != null) { this.pubID = this.stringify.dtdPubID(pubID); } if (sysID != null) { this.sysID = this.stringify.dtdSysID(sysID); } } XMLDocType.prototype.clone = function() { return create(XMLDocType.prototype, this); }; XMLDocType.prototype.element = function(name, value) { var child; child = new XMLDTDElement(this, name, value); this.children.push(child); return this; }; XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { var child; child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue); this.children.push(child); return this; }; XMLDocType.prototype.entity = function(name, value) { var child; child = new XMLDTDEntity(this, false, name, value); this.children.push(child); return this; }; XMLDocType.prototype.pEntity = function(name, value) { var child; child = new XMLDTDEntity(this, true, name, value); this.children.push(child); return this; }; XMLDocType.prototype.notation = function(name, value) { var child; child = new XMLDTDNotation(this, name, value); this.children.push(child); return this; }; XMLDocType.prototype.cdata = function(value) { var child; child = new XMLCData(this, value); this.children.push(child); return this; }; XMLDocType.prototype.comment = function(value) { var child; child = new XMLComment(this, value); this.children.push(child); return this; }; XMLDocType.prototype.instruction = function(target, value) { var child; child = new XMLProcessingInstruction(this, target, value); this.children.push(child); return this; }; XMLDocType.prototype.root = function() { return this.documentObject.root(); }; XMLDocType.prototype.document = function() { return this.documentObject; }; XMLDocType.prototype.toString = function(options, level) { var child, i, indent, len, newline, offset, pretty, r, ref, ref1, ref2, ref3, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; if (pretty) { r += space; } r += ' 0) { r += ' ['; if (pretty) { r += newline; } ref3 = this.children; for (i = 0, len = ref3.length; i < len; i++) { child = ref3[i]; r += child.toString(options, level + 1); } r += ']'; } r += '>'; if (pretty) { r += newline; } return r; }; XMLDocType.prototype.ele = function(name, value) { return this.element(name, value); }; XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) { return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue); }; XMLDocType.prototype.ent = function(name, value) { return this.entity(name, value); }; XMLDocType.prototype.pent = function(name, value) { return this.pEntity(name, value); }; XMLDocType.prototype.not = function(name, value) { return this.notation(name, value); }; XMLDocType.prototype.dat = function(value) { return this.cdata(value); }; XMLDocType.prototype.com = function(value) { return this.comment(value); }; XMLDocType.prototype.ins = function(target, value) { return this.instruction(target, value); }; XMLDocType.prototype.up = function() { return this.root(); }; XMLDocType.prototype.doc = function() { return this.document(); }; return XMLDocType; })(); }).call(this); },{"./XMLCData":86,"./XMLComment":87,"./XMLDTDAttList":88,"./XMLDTDElement":89,"./XMLDTDEntity":90,"./XMLDTDNotation":91,"./XMLProcessingInstruction":96,"lodash/lang/isObject":139,"lodash/object/create":143}],94:[function(require,module,exports){ (function() { var XMLAttribute, XMLElement, XMLNode, XMLProcessingInstruction, create, every, isArray, isFunction, isObject, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; create = require('lodash/object/create'); isObject = require('lodash/lang/isObject'); isArray = require('lodash/lang/isArray'); isFunction = require('lodash/lang/isFunction'); every = require('lodash/collection/every'); XMLNode = require('./XMLNode'); XMLAttribute = require('./XMLAttribute'); XMLProcessingInstruction = require('./XMLProcessingInstruction'); module.exports = XMLElement = (function(superClass) { extend(XMLElement, superClass); function XMLElement(parent, name, attributes) { XMLElement.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing element name"); } this.name = this.stringify.eleName(name); this.children = []; this.instructions = []; this.attributes = {}; if (attributes != null) { this.attribute(attributes); } } XMLElement.prototype.clone = function() { var att, attName, clonedSelf, i, len, pi, ref, ref1; clonedSelf = create(XMLElement.prototype, this); if (clonedSelf.isRoot) { clonedSelf.documentObject = null; } clonedSelf.attributes = {}; ref = this.attributes; for (attName in ref) { if (!hasProp.call(ref, attName)) continue; att = ref[attName]; clonedSelf.attributes[attName] = att.clone(); } clonedSelf.instructions = []; ref1 = this.instructions; for (i = 0, len = ref1.length; i < len; i++) { pi = ref1[i]; clonedSelf.instructions.push(pi.clone()); } clonedSelf.children = []; this.children.forEach(function(child) { var clonedChild; clonedChild = child.clone(); clonedChild.parent = clonedSelf; return clonedSelf.children.push(clonedChild); }); return clonedSelf; }; XMLElement.prototype.attribute = function(name, value) { var attName, attValue; if (name != null) { name = name.valueOf(); } if (isObject(name)) { for (attName in name) { if (!hasProp.call(name, attName)) continue; attValue = name[attName]; this.attribute(attName, attValue); } } else { if (isFunction(value)) { value = value.apply(); } if (!this.options.skipNullAttributes || (value != null)) { this.attributes[name] = new XMLAttribute(this, name, value); } } return this; }; XMLElement.prototype.removeAttribute = function(name) { var attName, i, len; if (name == null) { throw new Error("Missing attribute name"); } name = name.valueOf(); if (isArray(name)) { for (i = 0, len = name.length; i < len; i++) { attName = name[i]; delete this.attributes[attName]; } } else { delete this.attributes[name]; } return this; }; XMLElement.prototype.instruction = function(target, value) { var i, insTarget, insValue, instruction, len; if (target != null) { target = target.valueOf(); } if (value != null) { value = value.valueOf(); } if (isArray(target)) { for (i = 0, len = target.length; i < len; i++) { insTarget = target[i]; this.instruction(insTarget); } } else if (isObject(target)) { for (insTarget in target) { if (!hasProp.call(target, insTarget)) continue; insValue = target[insTarget]; this.instruction(insTarget, insValue); } } else { if (isFunction(value)) { value = value.apply(); } instruction = new XMLProcessingInstruction(this, target, value); this.instructions.push(instruction); } return this; }; XMLElement.prototype.toString = function(options, level) { var att, child, i, indent, instruction, j, len, len1, name, newline, offset, pretty, r, ref, ref1, ref2, ref3, ref4, ref5, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; ref3 = this.instructions; for (i = 0, len = ref3.length; i < len; i++) { instruction = ref3[i]; r += instruction.toString(options, level + 1); } if (pretty) { r += space; } r += '<' + this.name; ref4 = this.attributes; for (name in ref4) { if (!hasProp.call(ref4, name)) continue; att = ref4[name]; r += att.toString(options); } if (this.children.length === 0 || every(this.children, function(e) { return e.value === ''; })) { r += '/>'; if (pretty) { r += newline; } } else if (pretty && this.children.length === 1 && (this.children[0].value != null)) { r += '>'; r += this.children[0].value; r += ''; r += newline; } else { r += '>'; if (pretty) { r += newline; } ref5 = this.children; for (j = 0, len1 = ref5.length; j < len1; j++) { child = ref5[j]; r += child.toString(options, level + 1); } if (pretty) { r += space; } r += ''; if (pretty) { r += newline; } } return r; }; XMLElement.prototype.att = function(name, value) { return this.attribute(name, value); }; XMLElement.prototype.ins = function(target, value) { return this.instruction(target, value); }; XMLElement.prototype.a = function(name, value) { return this.attribute(name, value); }; XMLElement.prototype.i = function(target, value) { return this.instruction(target, value); }; return XMLElement; })(XMLNode); }).call(this); },{"./XMLAttribute":84,"./XMLNode":95,"./XMLProcessingInstruction":96,"lodash/collection/every":101,"lodash/lang/isArray":135,"lodash/lang/isFunction":137,"lodash/lang/isObject":139,"lodash/object/create":143}],95:[function(require,module,exports){ (function() { var XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLElement, XMLNode, XMLRaw, XMLText, isArray, isEmpty, isFunction, isObject, hasProp = {}.hasOwnProperty; isObject = require('lodash/lang/isObject'); isArray = require('lodash/lang/isArray'); isFunction = require('lodash/lang/isFunction'); isEmpty = require('lodash/lang/isEmpty'); XMLElement = null; XMLCData = null; XMLComment = null; XMLDeclaration = null; XMLDocType = null; XMLRaw = null; XMLText = null; module.exports = XMLNode = (function() { function XMLNode(parent) { this.parent = parent; this.options = this.parent.options; this.stringify = this.parent.stringify; if (XMLElement === null) { XMLElement = require('./XMLElement'); XMLCData = require('./XMLCData'); XMLComment = require('./XMLComment'); XMLDeclaration = require('./XMLDeclaration'); XMLDocType = require('./XMLDocType'); XMLRaw = require('./XMLRaw'); XMLText = require('./XMLText'); } } XMLNode.prototype.clone = function() { throw new Error("Cannot clone generic XMLNode"); }; XMLNode.prototype.element = function(name, attributes, text) { var item, j, key, lastChild, len, ref, val; lastChild = null; if (attributes == null) { attributes = {}; } attributes = attributes.valueOf(); if (!isObject(attributes)) { ref = [attributes, text], text = ref[0], attributes = ref[1]; } if (name != null) { name = name.valueOf(); } if (isArray(name)) { for (j = 0, len = name.length; j < len; j++) { item = name[j]; lastChild = this.element(item); } } else if (isFunction(name)) { lastChild = this.element(name.apply()); } else if (isObject(name)) { for (key in name) { if (!hasProp.call(name, key)) continue; val = name[key]; if (isFunction(val)) { val = val.apply(); } if ((isObject(val)) && (isEmpty(val))) { val = null; } if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) { lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val); } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && key.indexOf(this.stringify.convertPIKey) === 0) { lastChild = this.instruction(key.substr(this.stringify.convertPIKey.length), val); } else if (isObject(val)) { if (!this.options.ignoreDecorators && this.stringify.convertListKey && key.indexOf(this.stringify.convertListKey) === 0 && isArray(val)) { lastChild = this.element(val); } else { lastChild = this.element(key); lastChild.element(val); } } else { lastChild = this.element(key, val); } } } else { if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) { lastChild = this.text(text); } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) { lastChild = this.cdata(text); } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) { lastChild = this.comment(text); } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) { lastChild = this.raw(text); } else { lastChild = this.node(name, attributes, text); } } if (lastChild == null) { throw new Error("Could not create any elements with: " + name); } return lastChild; }; XMLNode.prototype.insertBefore = function(name, attributes, text) { var child, i, removed; if (this.isRoot) { throw new Error("Cannot insert elements at root level"); } i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i); child = this.parent.element(name, attributes, text); Array.prototype.push.apply(this.parent.children, removed); return child; }; XMLNode.prototype.insertAfter = function(name, attributes, text) { var child, i, removed; if (this.isRoot) { throw new Error("Cannot insert elements at root level"); } i = this.parent.children.indexOf(this); removed = this.parent.children.splice(i + 1); child = this.parent.element(name, attributes, text); Array.prototype.push.apply(this.parent.children, removed); return child; }; XMLNode.prototype.remove = function() { var i, ref; if (this.isRoot) { throw new Error("Cannot remove the root element"); } i = this.parent.children.indexOf(this); [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref = [])), ref; return this.parent; }; XMLNode.prototype.node = function(name, attributes, text) { var child, ref; if (name != null) { name = name.valueOf(); } if (attributes == null) { attributes = {}; } attributes = attributes.valueOf(); if (!isObject(attributes)) { ref = [attributes, text], text = ref[0], attributes = ref[1]; } child = new XMLElement(this, name, attributes); if (text != null) { child.text(text); } this.children.push(child); return child; }; XMLNode.prototype.text = function(value) { var child; child = new XMLText(this, value); this.children.push(child); return this; }; XMLNode.prototype.cdata = function(value) { var child; child = new XMLCData(this, value); this.children.push(child); return this; }; XMLNode.prototype.comment = function(value) { var child; child = new XMLComment(this, value); this.children.push(child); return this; }; XMLNode.prototype.raw = function(value) { var child; child = new XMLRaw(this, value); this.children.push(child); return this; }; XMLNode.prototype.declaration = function(version, encoding, standalone) { var doc, xmldec; doc = this.document(); xmldec = new XMLDeclaration(doc, version, encoding, standalone); doc.xmldec = xmldec; return doc.root(); }; XMLNode.prototype.doctype = function(pubID, sysID) { var doc, doctype; doc = this.document(); doctype = new XMLDocType(doc, pubID, sysID); doc.doctype = doctype; return doctype; }; XMLNode.prototype.up = function() { if (this.isRoot) { throw new Error("The root node has no parent. Use doc() if you need to get the document object."); } return this.parent; }; XMLNode.prototype.root = function() { var child; if (this.isRoot) { return this; } child = this.parent; while (!child.isRoot) { child = child.parent; } return child; }; XMLNode.prototype.document = function() { return this.root().documentObject; }; XMLNode.prototype.end = function(options) { return this.document().toString(options); }; XMLNode.prototype.prev = function() { var i; if (this.isRoot) { throw new Error("Root node has no siblings"); } i = this.parent.children.indexOf(this); if (i < 1) { throw new Error("Already at the first node"); } return this.parent.children[i - 1]; }; XMLNode.prototype.next = function() { var i; if (this.isRoot) { throw new Error("Root node has no siblings"); } i = this.parent.children.indexOf(this); if (i === -1 || i === this.parent.children.length - 1) { throw new Error("Already at the last node"); } return this.parent.children[i + 1]; }; XMLNode.prototype.importXMLBuilder = function(xmlbuilder) { var clonedRoot; clonedRoot = xmlbuilder.root().clone(); clonedRoot.parent = this; clonedRoot.isRoot = false; this.children.push(clonedRoot); return this; }; XMLNode.prototype.ele = function(name, attributes, text) { return this.element(name, attributes, text); }; XMLNode.prototype.nod = function(name, attributes, text) { return this.node(name, attributes, text); }; XMLNode.prototype.txt = function(value) { return this.text(value); }; XMLNode.prototype.dat = function(value) { return this.cdata(value); }; XMLNode.prototype.com = function(value) { return this.comment(value); }; XMLNode.prototype.doc = function() { return this.document(); }; XMLNode.prototype.dec = function(version, encoding, standalone) { return this.declaration(version, encoding, standalone); }; XMLNode.prototype.dtd = function(pubID, sysID) { return this.doctype(pubID, sysID); }; XMLNode.prototype.e = function(name, attributes, text) { return this.element(name, attributes, text); }; XMLNode.prototype.n = function(name, attributes, text) { return this.node(name, attributes, text); }; XMLNode.prototype.t = function(value) { return this.text(value); }; XMLNode.prototype.d = function(value) { return this.cdata(value); }; XMLNode.prototype.c = function(value) { return this.comment(value); }; XMLNode.prototype.r = function(value) { return this.raw(value); }; XMLNode.prototype.u = function() { return this.up(); }; return XMLNode; })(); }).call(this); },{"./XMLCData":86,"./XMLComment":87,"./XMLDeclaration":92,"./XMLDocType":93,"./XMLElement":94,"./XMLRaw":97,"./XMLText":99,"lodash/lang/isArray":135,"lodash/lang/isEmpty":136,"lodash/lang/isFunction":137,"lodash/lang/isObject":139}],96:[function(require,module,exports){ (function() { var XMLProcessingInstruction, create; create = require('lodash/object/create'); module.exports = XMLProcessingInstruction = (function() { function XMLProcessingInstruction(parent, target, value) { this.stringify = parent.stringify; if (target == null) { throw new Error("Missing instruction target"); } this.target = this.stringify.insTarget(target); if (value) { this.value = this.stringify.insValue(value); } } XMLProcessingInstruction.prototype.clone = function() { return create(XMLProcessingInstruction.prototype, this); }; XMLProcessingInstruction.prototype.toString = function(options, level) { var indent, newline, offset, pretty, r, ref, ref1, ref2, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; if (pretty) { r += space; } r += ''; if (pretty) { r += newline; } return r; }; return XMLProcessingInstruction; })(); }).call(this); },{"lodash/object/create":143}],97:[function(require,module,exports){ (function() { var XMLNode, XMLRaw, create, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; create = require('lodash/object/create'); XMLNode = require('./XMLNode'); module.exports = XMLRaw = (function(superClass) { extend(XMLRaw, superClass); function XMLRaw(parent, text) { XMLRaw.__super__.constructor.call(this, parent); if (text == null) { throw new Error("Missing raw text"); } this.value = this.stringify.raw(text); } XMLRaw.prototype.clone = function() { return create(XMLRaw.prototype, this); }; XMLRaw.prototype.toString = function(options, level) { var indent, newline, offset, pretty, r, ref, ref1, ref2, space; pretty = (options != null ? options.pretty : void 0) || false; indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' '; offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0; newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n'; level || (level = 0); space = new Array(level + offset + 1).join(indent); r = ''; if (pretty) { r += space; } r += this.value; if (pretty) { r += newline; } return r; }; return XMLRaw; })(XMLNode); }).call(this); },{"./XMLNode":95,"lodash/object/create":143}],98:[function(require,module,exports){ (function() { var XMLStringifier, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, hasProp = {}.hasOwnProperty; module.exports = XMLStringifier = (function() { function XMLStringifier(options) { this.assertLegalChar = bind(this.assertLegalChar, this); var key, ref, value; this.allowSurrogateChars = options != null ? options.allowSurrogateChars : void 0; ref = (options != null ? options.stringify : void 0) || {}; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this[key] = value; } } XMLStringifier.prototype.eleName = function(val) { val = '' + val || ''; return this.assertLegalChar(val); }; XMLStringifier.prototype.eleText = function(val) { val = '' + val || ''; return this.assertLegalChar(this.elEscape(val)); }; XMLStringifier.prototype.cdata = function(val) { val = '' + val || ''; if (val.match(/]]>/)) { throw new Error("Invalid CDATA text: " + val); } return this.assertLegalChar(val); }; XMLStringifier.prototype.comment = function(val) { val = '' + val || ''; if (val.match(/--/)) { throw new Error("Comment text cannot contain double-hypen: " + val); } return this.assertLegalChar(val); }; XMLStringifier.prototype.raw = function(val) { return '' + val || ''; }; XMLStringifier.prototype.attName = function(val) { return '' + val || ''; }; XMLStringifier.prototype.attValue = function(val) { val = '' + val || ''; return this.attEscape(val); }; XMLStringifier.prototype.insTarget = function(val) { return '' + val || ''; }; XMLStringifier.prototype.insValue = function(val) { val = '' + val || ''; if (val.match(/\?>/)) { throw new Error("Invalid processing instruction value: " + val); } return val; }; XMLStringifier.prototype.xmlVersion = function(val) { val = '' + val || ''; if (!val.match(/1\.[0-9]+/)) { throw new Error("Invalid version number: " + val); } return val; }; XMLStringifier.prototype.xmlEncoding = function(val) { val = '' + val || ''; if (!val.match(/[A-Za-z](?:[A-Za-z0-9._-]|-)*/)) { throw new Error("Invalid encoding: " + val); } return val; }; XMLStringifier.prototype.xmlStandalone = function(val) { if (val) { return "yes"; } else { return "no"; } }; XMLStringifier.prototype.dtdPubID = function(val) { return '' + val || ''; }; XMLStringifier.prototype.dtdSysID = function(val) { return '' + val || ''; }; XMLStringifier.prototype.dtdElementValue = function(val) { return '' + val || ''; }; XMLStringifier.prototype.dtdAttType = function(val) { return '' + val || ''; }; XMLStringifier.prototype.dtdAttDefault = function(val) { if (val != null) { return '' + val || ''; } else { return val; } }; XMLStringifier.prototype.dtdEntityValue = function(val) { return '' + val || ''; }; XMLStringifier.prototype.dtdNData = function(val) { return '' + val || ''; }; XMLStringifier.prototype.convertAttKey = '@'; XMLStringifier.prototype.convertPIKey = '?'; XMLStringifier.prototype.convertTextKey = '#text'; XMLStringifier.prototype.convertCDataKey = '#cdata'; XMLStringifier.prototype.convertCommentKey = '#comment'; XMLStringifier.prototype.convertRawKey = '#raw'; XMLStringifier.prototype.convertListKey = '#list'; XMLStringifier.prototype.assertLegalChar = function(str) { var chars, chr; if (this.allowSurrogateChars) { chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]/; } else { chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]/; } chr = str.match(chars); if (chr) { throw new Error("Invalid character (" + chr + ") in string: " + str + " at index " + chr.index); } return str; }; XMLStringifier.prototype.elEscape = function(str) { return str.replace(/&/g, '&').replace(//g, '>').replace(/\r/g, ' '); }; XMLStringifier.prototype.attEscape = function(str) { return str.replace(/&/g, '&').replace(/ 3 && typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = (length > 2 && typeof thisArg == 'function') ? thisArg : null; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(args[1], args[2], guard)) { customizer = length == 3 ? null : customizer; length = 2; } var index = 0; while (++index < length) { var source = args[index]; if (source) { assigner(object, source, customizer); } } return object; }; } module.exports = createAssigner; },{"./bindCallback":120,"./isIterateeCall":127}],122:[function(require,module,exports){ function equalArrays(array, other, equalFunc, customizer, isWhere, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length, result = true; if (arrLength != othLength && !(isWhere && othLength > arrLength)) { return false; } while (result && ++index < arrLength) { var arrValue = array[index], othValue = other[index]; result = undefined; if (customizer) { result = isWhere ? customizer(othValue, arrValue, index) : customizer(arrValue, othValue, index); } if (typeof result == 'undefined') { if (isWhere) { var othIndex = othLength; while (othIndex--) { othValue = other[othIndex]; result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isWhere, stackA, stackB); if (result) { break; } } } else { result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isWhere, stackA, stackB); } } } return !!result; } module.exports = equalArrays; },{}],123:[function(require,module,exports){ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', numberTag = '[object Number]', regexpTag = '[object RegExp]', stringTag = '[object String]'; function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: return +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: return (object != +object) ? other != +other : (object == 0 ? ((1 / object) == (1 / other)) : object == +other); case regexpTag: case stringTag: return object == (other + ''); } return false; } module.exports = equalByTag; },{}],124:[function(require,module,exports){ var keys = require('../object/keys'); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; function equalObjects(object, other, equalFunc, customizer, isWhere, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isWhere) { return false; } var hasCtor, index = -1; while (++index < objLength) { var key = objProps[index], result = hasOwnProperty.call(other, key); if (result) { var objValue = object[key], othValue = other[key]; result = undefined; if (customizer) { result = isWhere ? customizer(othValue, objValue, key) : customizer(objValue, othValue, key); } if (typeof result == 'undefined') { result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isWhere, stackA, stackB); } } if (!result) { return false; } hasCtor || (hasCtor = key == 'constructor'); } if (!hasCtor) { var objCtor = object.constructor, othCtor = other.constructor; if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { return false; } } return true; } module.exports = equalObjects; },{"../object/keys":144}],125:[function(require,module,exports){ var baseSetData = require('./baseSetData'), isNative = require('../lang/isNative'), support = require('../support'); var reFuncName = /^\s*function[ \n\r\t]+\w/; var reThis = /\bthis\b/; var fnToString = Function.prototype.toString; function isBindable(func) { var result = !(support.funcNames ? func.name : support.funcDecomp); if (!result) { var source = fnToString.call(func); if (!support.funcNames) { result = !reFuncName.test(source); } if (!result) { result = reThis.test(source) || isNative(func); baseSetData(func, result); } } return result; } module.exports = isBindable; },{"../lang/isNative":138,"../support":147,"./baseSetData":118}],126:[function(require,module,exports){ var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; function isIndex(value, length) { value = +value; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } module.exports = isIndex; },{}],127:[function(require,module,exports){ var isIndex = require('./isIndex'), isLength = require('./isLength'), isObject = require('../lang/isObject'); function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number') { var length = object.length, prereq = isLength(length) && isIndex(index, length); } else { prereq = type == 'string' && index in object; } if (prereq) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } module.exports = isIterateeCall; },{"../lang/isObject":139,"./isIndex":126,"./isLength":128}],128:[function(require,module,exports){ var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; },{}],129:[function(require,module,exports){ function isObjectLike(value) { return (value && typeof value == 'object') || false; } module.exports = isObjectLike; },{}],130:[function(require,module,exports){ var isObject = require('../lang/isObject'); function isStrictComparable(value) { return value === value && (value === 0 ? ((1 / value) > 0) : !isObject(value)); } module.exports = isStrictComparable; },{"../lang/isObject":139}],131:[function(require,module,exports){ (function (global){ var isNative = require('../lang/isNative'); var WeakMap = isNative(WeakMap = global.WeakMap) && WeakMap; var metaMap = WeakMap && new WeakMap; module.exports = metaMap; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../lang/isNative":138}],132:[function(require,module,exports){ var isArguments = require('../lang/isArguments'), isArray = require('../lang/isArray'), isIndex = require('./isIndex'), isLength = require('./isLength'), keysIn = require('../object/keysIn'), support = require('../support'); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = length && isLength(length) && (isArray(object) || (support.nonEnumArgs && isArguments(object))); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } module.exports = shimKeys; },{"../lang/isArguments":134,"../lang/isArray":135,"../object/keysIn":145,"../support":147,"./isIndex":126,"./isLength":128}],133:[function(require,module,exports){ var isObject = require('../lang/isObject'); function toObject(value) { return isObject(value) ? value : Object(value); } module.exports = toObject; },{"../lang/isObject":139}],134:[function(require,module,exports){ var isLength = require('../internal/isLength'), isObjectLike = require('../internal/isObjectLike'); var argsTag = '[object Arguments]'; var objectProto = Object.prototype; var objToString = objectProto.toString; function isArguments(value) { var length = isObjectLike(value) ? value.length : undefined; return (isLength(length) && objToString.call(value) == argsTag) || false; } module.exports = isArguments; },{"../internal/isLength":128,"../internal/isObjectLike":129}],135:[function(require,module,exports){ var isLength = require('../internal/isLength'), isNative = require('./isNative'), isObjectLike = require('../internal/isObjectLike'); var arrayTag = '[object Array]'; var objectProto = Object.prototype; var objToString = objectProto.toString; var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray; var isArray = nativeIsArray || function(value) { return (isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag) || false; }; module.exports = isArray; },{"../internal/isLength":128,"../internal/isObjectLike":129,"./isNative":138}],136:[function(require,module,exports){ var isArguments = require('./isArguments'), isArray = require('./isArray'), isFunction = require('./isFunction'), isLength = require('../internal/isLength'), isObjectLike = require('../internal/isObjectLike'), isString = require('./isString'), keys = require('../object/keys'); function isEmpty(value) { if (value == null) { return true; } var length = value.length; if (isLength(length) && (isArray(value) || isString(value) || isArguments(value) || (isObjectLike(value) && isFunction(value.splice)))) { return !length; } return !keys(value).length; } module.exports = isEmpty; },{"../internal/isLength":128,"../internal/isObjectLike":129,"../object/keys":144,"./isArguments":134,"./isArray":135,"./isFunction":137,"./isString":140}],137:[function(require,module,exports){ (function (global){ var baseIsFunction = require('../internal/baseIsFunction'), isNative = require('./isNative'); var funcTag = '[object Function]'; var objectProto = Object.prototype; var objToString = objectProto.toString; var Uint8Array = isNative(Uint8Array = global.Uint8Array) && Uint8Array; var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) { return objToString.call(value) == funcTag; }; module.exports = isFunction; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../internal/baseIsFunction":113,"./isNative":138}],138:[function(require,module,exports){ var escapeRegExp = require('../string/escapeRegExp'), isObjectLike = require('../internal/isObjectLike'); var funcTag = '[object Function]'; var reHostCtor = /^\[object .+?Constructor\]$/; var objectProto = Object.prototype; var fnToString = Function.prototype.toString; var objToString = objectProto.toString; var reNative = RegExp('^' + escapeRegExp(objToString) .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); function isNative(value) { if (value == null) { return false; } if (objToString.call(value) == funcTag) { return reNative.test(fnToString.call(value)); } return (isObjectLike(value) && reHostCtor.test(value)) || false; } module.exports = isNative; },{"../internal/isObjectLike":129,"../string/escapeRegExp":146}],139:[function(require,module,exports){ function isObject(value) { var type = typeof value; return type == 'function' || (value && type == 'object') || false; } module.exports = isObject; },{}],140:[function(require,module,exports){ var isObjectLike = require('../internal/isObjectLike'); var stringTag = '[object String]'; var objectProto = Object.prototype; var objToString = objectProto.toString; function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag) || false; } module.exports = isString; },{"../internal/isObjectLike":129}],141:[function(require,module,exports){ var isLength = require('../internal/isLength'), isObjectLike = require('../internal/isObjectLike'); var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; var objectProto = Object.prototype; var objToString = objectProto.toString; function isTypedArray(value) { return (isObjectLike(value) && isLength(value.length) && typedArrayTags[objToString.call(value)]) || false; } module.exports = isTypedArray; },{"../internal/isLength":128,"../internal/isObjectLike":129}],142:[function(require,module,exports){ var baseAssign = require('../internal/baseAssign'), createAssigner = require('../internal/createAssigner'); var assign = createAssigner(baseAssign); module.exports = assign; },{"../internal/baseAssign":103,"../internal/createAssigner":121}],143:[function(require,module,exports){ var baseCopy = require('../internal/baseCopy'), baseCreate = require('../internal/baseCreate'), isIterateeCall = require('../internal/isIterateeCall'), keys = require('./keys'); function create(prototype, properties, guard) { var result = baseCreate(prototype); if (guard && isIterateeCall(prototype, properties, guard)) { properties = null; } return properties ? baseCopy(properties, result, keys(properties)) : result; } module.exports = create; },{"../internal/baseCopy":105,"../internal/baseCreate":106,"../internal/isIterateeCall":127,"./keys":144}],144:[function(require,module,exports){ var isLength = require('../internal/isLength'), isNative = require('../lang/isNative'), isObject = require('../lang/isObject'), shimKeys = require('../internal/shimKeys'); var nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys; var keys = !nativeKeys ? shimKeys : function(object) { if (object) { var Ctor = object.constructor, length = object.length; } if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && (length && isLength(length)))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; module.exports = keys; },{"../internal/isLength":128,"../internal/shimKeys":132,"../lang/isNative":138,"../lang/isObject":139}],145:[function(require,module,exports){ var isArguments = require('../lang/isArguments'), isArray = require('../lang/isArray'), isIndex = require('../internal/isIndex'), isLength = require('../internal/isLength'), isObject = require('../lang/isObject'), support = require('../support'); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || (support.nonEnumArgs && isArguments(object))) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keysIn; },{"../internal/isIndex":126,"../internal/isLength":128,"../lang/isArguments":134,"../lang/isArray":135,"../lang/isObject":139,"../support":147}],146:[function(require,module,exports){ var baseToString = require('../internal/baseToString'); var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = escapeRegExp; },{"../internal/baseToString":119}],147:[function(require,module,exports){ (function (global){ var isNative = require('./lang/isNative'); var reThis = /\bthis\b/; var objectProto = Object.prototype; var document = (document = global.window) && document.document; var propertyIsEnumerable = objectProto.propertyIsEnumerable; var support = {}; (function(x) { support.funcDecomp = !isNative(global.WinRTError) && reThis.test(function() { return this; }); support.funcNames = typeof Function.name == 'string'; try { support.dom = document.createDocumentFragment().nodeType === 11; } catch(e) { support.dom = false; } try { support.nonEnumArgs = !propertyIsEnumerable.call(arguments, 1); } catch(e) { support.nonEnumArgs = true; } }(0, 0)); module.exports = support; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./lang/isNative":138}],148:[function(require,module,exports){ function identity(value) { return value; } module.exports = identity; },{}]},{},[8]) ================================================ FILE: enhance-rn.js ================================================ import AWS from 'aws-sdk/global'; import { NativeModules } from 'react-native'; import * as enhancements from './src'; import BigInteger from './src/BigInteger'; export * from './src'; const { RNAWSCognito } = NativeModules; Object.keys(enhancements).forEach(key => { AWS.CognitoIdentityServiceProvider[key] = enhancements[key]; }); BigInteger.prototype.modPow = function nativeModPow(e, m, callback) { RNAWSCognito.computeModPow({ target: this.toString(16), value: e.toString(16), modifier: m.toString(16), }, (err, result) => { if (err) { return callback(new Error(err), null); } const bigIntResult = new BigInteger(result, 16); return callback(null, bigIntResult); }); }; enhancements.AuthenticationHelper.prototype.calculateS = function nativeComputeS(xValue, serverBValue, callback) { RNAWSCognito.computeS({ g: this.g.toString(16), x: xValue.toString(16), k: this.k.toString(16), a: this.smallAValue.toString(16), b: serverBValue.toString(16), u: this.UValue.toString(16), }, (err, result) => { if (err) { return callback(new Error(err), null); } const bigIntResult = new BigInteger(result, 16); return callback(null, bigIntResult); }); return undefined; }; const libraryVersion = '1.0'; const libraryName = 'aws-amplify'; const originalUserAgent = AWS.util.userAgent; if (originalUserAgent) { AWS.util.userAgent = function newUserAgent() { return `${libraryName}/${libraryVersion} ${originalUserAgent()}`; }; } else { const previousUserAgent = AWS.config.customUserAgent || ''; AWS.config.update({ customUserAgent: `${libraryName}/${libraryVersion} ${previousUserAgent}` }); } ================================================ FILE: enhance.js ================================================ import CognitoIdentityServiceProvider from 'aws-sdk/clients/cognitoidentityserviceprovider'; import * as enhancements from './src'; export * from './src'; Object.keys(enhancements).forEach(key => { CognitoIdentityServiceProvider[key] = enhancements[key]; }); ================================================ FILE: examples/babel-webpack/.babelrc ================================================ { "presets": [ "es2015", "stage-0", "react" ] } ================================================ FILE: examples/babel-webpack/.editorconfig ================================================ root = true [*] trim_trailing_whitespace = true insert_final_newline = true charset = utf-8 indent_style = space indent_size = 2 ================================================ FILE: examples/babel-webpack/README.md ================================================ # Babel webpack example To run the example first setup your AWS configuration. ```js // src/config.js export default { region: '', IdentityPoolId: '', UserPoolId: '', ClientId: '', } ``` Now, you are ready to build this example. ``` npm install npm run build ``` Open browser to try this example. ``` open index.html ``` ================================================ FILE: examples/babel-webpack/index.html ================================================

Sign up

================================================ FILE: examples/babel-webpack/package.json ================================================ { "name": "babel-webpack", "version": "1.0.0", "description": "Babel webpack example ", "scripts": { "build": "webpack" }, "devDependencies": { "babel-core": "^6.17.0", "babel-loader": "^6.2.5", "babel-preset-es2015": "^6.16.0", "babel-preset-react": "^6.16.0", "babel-preset-stage-0": "^6.16.0", "babel-register": "^6.16.3", "json-loader": "^0.5.4", "webpack": "^1.13.2" }, "dependencies": { "amazon-cognito-identity-js": "^1.5.0", "react": "^15.3.2", "react-dom": "^15.3.2" } } ================================================ FILE: examples/babel-webpack/src/config.js ================================================ export default { region: '', IdentityPoolId: '', UserPoolId: '', ClientId: '', } ================================================ FILE: examples/babel-webpack/src/main.jsx ================================================ import {Config, CognitoIdentityCredentials} from "aws-sdk"; import { CognitoUserPool, CognitoUserAttribute } from "amazon-cognito-identity-js"; import React from "react"; import ReactDOM from "react-dom"; import appConfig from "./config"; Config.region = appConfig.region; Config.credentials = new CognitoIdentityCredentials({ IdentityPoolId: appConfig.IdentityPoolId }); const userPool = new CognitoUserPool({ UserPoolId: appConfig.UserPoolId, ClientId: appConfig.ClientId, }); class SignUpForm extends React.Component { constructor(props) { super(props); this.state = { email: '', password: '', }; } handleEmailChange(e) { this.setState({email: e.target.value}); } handlePasswordChange(e) { this.setState({password: e.target.value}); } handleSubmit(e) { e.preventDefault(); const email = this.state.email.trim(); const password = this.state.password.trim(); const attributeList = [ new CognitoUserAttribute({ Name: 'email', Value: email, }) ]; userPool.signUp(email, password, attributeList, null, (err, result) => { if (err) { console.log(err); return; } console.log('user name is ' + result.user.getUsername()); console.log('call result: ' + result); }); } render() { return (
); } } ReactDOM.render(, document.getElementById('app')); ================================================ FILE: examples/babel-webpack/webpack.config.babel.js ================================================ export default { resolve: { extensions: ['', '.js', 'jsx'], }, devtool: "cheap-eval-source-map", entry: ['./src/main.jsx'], output: { path: 'dist', filename: 'main.bundle.js' }, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel', exclude: /node_modules/, query: { cacheDirectory: true, } }, { test: /\.json$/, loader: 'json' } ] } }; ================================================ FILE: index.d.ts ================================================ declare module "amazon-cognito-identity-js" { import * as AWS from "aws-sdk"; export type NodeCallback = (err?: E, result?: T) => void; export interface IAuthenticationDetailsData { Username: string; Password: string; } export class AuthenticationDetails { constructor(data: IAuthenticationDetailsData); public getUsername(): string; public getPassword(): string; public getValidationData(): any[]; } export interface ICognitoStorage { setItem(key: string, value: string): void; getItem(key: string): string; removeItem(key: string): void; clear(): void; } export interface ICognitoUserData { Username: string; Pool: CognitoUserPool; Storage?: ICognitoStorage; } export class CognitoUser { constructor(data: ICognitoUserData); public setSignInUserSession(signInUserSession: CognitoUserSession): void; public getSignInUserSession(): CognitoUserSession | null; public getUsername(): string; public getAuthenticationFlowType(): string; public setAuthenticationFlowType(authenticationFlowType: string): string; public getSession(callback: Function): any; public refreshSession(refreshToken: CognitoRefreshToken, callback: NodeCallback): void; public authenticateUser(authenticationDetails: AuthenticationDetails, callbacks: { onSuccess: (session: CognitoUserSession, userConfirmationNecessary?: boolean) => void, onFailure: (err: any) => void, newPasswordRequired?: (userAttributes: any, requiredAttributes: any) => void, mfaRequired?: (challengeName: any, challengeParameters: any) => void, customChallenge?: (challengeParameters: any) => void }): void; public confirmRegistration(code: string, forceAliasCreation: boolean, callback: NodeCallback): void; public sendCustomChallengeAnswer(answerChallenge: any, callback:NodeCallback):void; public resendConfirmationCode(callback: NodeCallback): void; public changePassword(oldPassword: string, newPassword: string, callback: NodeCallback): void; public forgotPassword(callbacks: { onSuccess: (data: any) => void, onFailure: (err: Error) => void, inputVerificationCode?: (data: any) => void }): void; public confirmPassword(verificationCode: string, newPassword: string, callbacks: { onSuccess: () => void, onFailure: (err: Error) => void }): void; public setDeviceStatusRemembered(callbacks: { onSuccess: (success: string) => void, onFailure: (err: any) => void }): void; public setDeviceStatusNotRemembered(callbacks: { onSuccess: (success: string) => void, onFailure: (err: any) => void }): void; public getDevice(callbacks: {onSuccess: (success: string) => void, onFailure: (err: Error) => void}): any; public sendMFACode(confirmationCode: string, callbacks: { onSuccess: (session: CognitoUserSession) => void, onFailure: (err: any) => void }): void; public completeNewPasswordChallenge(newPassword: string, requiredAttributeData: any, callbacks: { onSuccess: (session: CognitoUserSession) => void, onFailure: (err: any) => void, mfaRequired?: (challengeName: any, challengeParameters: any) => void, customChallenge?: (challengeParameters: any) => void }): void; public signOut(): void; public globalSignOut(callbacks: { onSuccess: (msg: string) => void, onFailure: (err: Error) => void }): void; public verifyAttribute(attributeName: string, confirmationCode: string, callbacks: { onSuccess: (success: string) => void, onFailure: (err: Error) => void }): void; public getUserAttributes(callback: NodeCallback): void; public updateAttributes(attributes: ICognitoUserAttributeData[], callback: NodeCallback): void; public deleteAttributes(attributeList: string[], callback: NodeCallback): void; public getAttributeVerificationCode(name: string, callback: { onSuccess: () => void, onFailure: (err: Error) => void, inputVerificationCode: (data: string) => void | null }): void; public deleteUser(callback: NodeCallback): void; public enableMFA(callback: NodeCallback): void; public disableMFA(callback: NodeCallback): void; public getMFAOptions(callback: NodeCallback): void; } export interface MFAOption { DeliveryMedium: "SMS" |"EMAIL"; AttributeName: string; } export interface ICognitoUserAttributeData { Name: string; Value: string; } export class CognitoUserAttribute { constructor(data: ICognitoUserAttributeData); public getValue(): string; public setValue(value: string): CognitoUserAttribute; public getName(): string; public setName(name: string): CognitoUserAttribute; public toString(): string; public toJSON(): Object; } export interface ISignUpResult { user: CognitoUser; userConfirmed: boolean; userSub: string; } export interface ICognitoUserPoolData { UserPoolId: string; ClientId: string; endpoint?: string; Storage?: ICognitoStorage; } export class CognitoUserPool { constructor(data: ICognitoUserPoolData); public getUserPoolId(): string; public getClientId(): string; public signUp(username: string, password: string, userAttributes: CognitoUserAttribute[], validationData: CognitoUserAttribute[], callback: NodeCallback): void; public getCurrentUser(): CognitoUser | null; } export interface ICognitoUserSessionData { IdToken: CognitoIdToken; AccessToken: CognitoAccessToken; RefreshToken?: CognitoRefreshToken; } export class CognitoUserSession { constructor(data: ICognitoUserSessionData); public getIdToken(): CognitoIdToken; public getRefreshToken(): CognitoRefreshToken; public getAccessToken(): CognitoAccessToken; public isValid(): boolean; } export class CognitoIdentityServiceProvider { public config: AWS.CognitoIdentityServiceProvider.Types.ClientConfiguration; } export class CognitoAccessToken { constructor({ AccessToken }: { AccessToken: string }); public getJwtToken(): string; public getExpiration(): number; } export class CognitoIdToken { constructor({ IdToken }: { IdToken: string }); public getJwtToken(): string; public getExpiration(): number; } export class CognitoRefreshToken { constructor({ RefreshToken }: { RefreshToken: string }); public getToken(): string; } export interface ICookieStorageData { domain: string; path?: string; expires?: number; secure?: boolean; } export class CookieStorage implements ICognitoStorage { constructor(data: ICookieStorageData); setItem(key: string, value: string): void; getItem(key: string): string; removeItem(key: string): void; clear(): void; } } ================================================ FILE: ios/JKBigInteger/JKBigDecimal.h ================================================ // // JKBigDecimal.h // JKBigInteger // // Created by Midfar Sun on 5/4/15. // Copyright (c) 2015 Midfar Sun. All rights reserved. // // Licensed under the MIT License #import #import "JKBigInteger.h" @interface JKBigDecimal : NSObject @property(nonatomic, retain)JKBigInteger *bigInteger; @property(nonatomic, assign)NSUInteger figure;//小数位数 + (id)decimalWithString:(NSString *)string; - (id)initWithString:(NSString *)string; - (id)add:(JKBigDecimal *)bigDecimal; - (id)subtract:(JKBigDecimal *)bigDecimal; - (id)multiply:(JKBigDecimal *)bigDecimal; - (id)divide:(JKBigDecimal *)bigDecimal; - (id)remainder:(JKBigDecimal *)bigInteger; //- (NSArray *)divideAndRemainder:(JKBigDecimal *)bigInteger; - (NSComparisonResult) compare:(JKBigDecimal *)other; - (id)pow:(unsigned int)exponent; - (id)negate; - (id)abs; - (NSString *)stringValue; - (NSString *)description; @end ================================================ FILE: ios/JKBigInteger/JKBigDecimal.m ================================================ // // JKBigDecimal.m // JKBigInteger // // Created by Midfar Sun on 5/4/15. // Copyright (c) 2015 Midfar Sun. All rights reserved. // // Licensed under the MIT License #import "JKBigDecimal.h" @implementation JKBigDecimal @synthesize bigInteger, figure; - (id)init { return [self initWithString:@"0"]; } - (id)initWithString:(NSString *)string { self = [super init]; if (self) { figure = 0; if ([string containsString:@"."]) { NSRange range = [string rangeOfString:@"."]; figure = string.length-range.location-range.length; string = [string stringByReplacingCharactersInRange:range withString:@""]; } bigInteger = [[JKBigInteger alloc] initWithString:string]; } return self; } + (id)decimalWithString:(NSString *)string { return [[JKBigDecimal alloc] initWithString:string]; } -(id)initWithBigInteger:(JKBigInteger *)i figure:(NSInteger)f { self = [super init]; if (self) { bigInteger = i; figure = f; } return self; } - (instancetype)initWithCoder:(NSCoder *)decoder { self = [super init]; if (self) { bigInteger = [[JKBigInteger alloc] initWithCoder:decoder]; figure = [decoder decodeInt32ForKey:@"JKBigDecimalFigure"]; } return self; } -(void)encodeWithCoder:(NSCoder *)encoder { [bigInteger encodeWithCoder:encoder]; [encoder encodeInteger:figure forKey:@"JKBigDecimalFigure"]; } - (id)add:(JKBigDecimal *)bigDecimal { NSInteger maxFigure = 0; if (figure>=bigDecimal.figure) { maxFigure = figure; NSInteger exponent = maxFigure-bigDecimal.figure; JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; bigDecimal.bigInteger = [bigDecimal.bigInteger multiply:newInteger]; bigDecimal.figure = maxFigure; }else{ maxFigure = bigDecimal.figure; NSInteger exponent = maxFigure-figure; JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; bigInteger = [bigInteger multiply:newInteger]; figure = maxFigure; } JKBigInteger *newBigInteger = [bigInteger add:bigDecimal.bigInteger]; JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:maxFigure]; return newBigDecimal; } - (id)subtract:(JKBigDecimal *)bigDecimal { NSInteger maxFigure = 0; if (figure>=bigDecimal.figure) { maxFigure = figure; NSInteger exponent = maxFigure-bigDecimal.figure; JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; bigDecimal.bigInteger = [bigDecimal.bigInteger multiply:newInteger]; bigDecimal.figure = maxFigure; }else{ maxFigure = bigDecimal.figure; NSInteger exponent = maxFigure-figure; JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; bigInteger = [bigDecimal.bigInteger multiply:newInteger]; figure = maxFigure; } JKBigInteger *newBigInteger = [bigInteger subtract:bigDecimal.bigInteger]; JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:maxFigure]; return newBigDecimal; } - (id)multiply:(JKBigDecimal *)bigDecimal { NSInteger totalFigure = figure+bigDecimal.figure; JKBigInteger *newBigInteger = [bigInteger multiply:bigDecimal.bigInteger]; JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:totalFigure]; return newBigDecimal; } - (id)divide:(JKBigDecimal *)bigDecimal { NSInteger totalFigure = figure-bigDecimal.figure; if (totalFigure<0) { NSInteger exponent = -totalFigure; totalFigure=0; JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; bigInteger = [bigInteger multiply:newInteger]; } JKBigInteger *newBigInteger = [bigInteger divide:bigDecimal.bigInteger]; JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:totalFigure]; return newBigDecimal; } - (id)remainder:(JKBigDecimal *)bigDecimal { NSInteger totalFigure = figure-bigDecimal.figure; if (totalFigure<0) { NSInteger exponent = -totalFigure; totalFigure=0; JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; bigInteger = [bigInteger multiply:newInteger]; } JKBigInteger *newBigInteger = [bigInteger remainder:bigDecimal.bigInteger]; JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:bigDecimal.figure]; return newBigDecimal; } //- (NSArray *)divideAndRemainder:(JKBigDecimal *)bigInteger //{ // //} -(NSComparisonResult) compare:(JKBigDecimal *)other { JKBigDecimal *tens = [[JKBigDecimal alloc] initWithString:@"10"]; JKBigInteger *scaledNum; JKBigInteger *scaledCompareTo; if (figure > other.figure){ tens = [tens pow:(int)figure]; } else { tens = [tens pow:(int)other.figure]; } //scale my value to integer value scaledNum = [[JKBigInteger alloc] initWithString:[[self multiply:tens] stringValue]]; //scale other value to integer scaledCompareTo = [[JKBigInteger alloc] initWithString:[[other multiply:tens] stringValue]]; NSComparisonResult compareBigInteger = [scaledNum compare:scaledCompareTo]; return compareBigInteger; } - (id)pow:(unsigned int)exponent { NSInteger totalFigure = figure*exponent; JKBigInteger *newBigInteger = [bigInteger pow:exponent]; JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:totalFigure]; return newBigDecimal; } - (id)negate { JKBigInteger *newBigInteger = [bigInteger negate]; JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:figure]; return newBigDecimal; } - (id)abs { JKBigInteger *newBigInteger = [bigInteger abs]; JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:figure]; return newBigDecimal; } - (NSString *)stringValue { NSString *string = [bigInteger stringValue]; if (figure==0) { return string; } NSMutableString *mString = [NSMutableString stringWithString:string]; NSInteger newFigure = string.length-figure; while (newFigure<=0) { [mString insertString:@"0" atIndex:0]; newFigure++; } [mString insertString:@"." atIndex:newFigure]; return mString; } - (NSString *)description { return [self stringValue]; } @end ================================================ FILE: ios/JKBigInteger/JKBigInteger.h ================================================ // // JKBigInteger.h // JKBigInteger // // Created by Jānis Kiršteins on 5/21/13. // Copyright (c) 2013 Jānis Kiršteins. All rights reserved. // // Licensed under the MIT License #import #include "tommath.h" @interface JKBigInteger : NSObject - (id)initWithValue:(mp_int *)value; - (mp_int *)value; - (id)initWithUnsignedLong:(unsigned long)ul; - (id)initWithString:(NSString *)string; - (id)initWithString:(NSString *)string andRadix:(int)radix; - (id)initWithCString:(char *)cString; - (id)initWithCString:(char *)cString andRadix:(int)radix; - (id)add:(JKBigInteger *)bigInteger; - (id)subtract:(JKBigInteger *)bigInteger; - (id)multiply:(JKBigInteger *)bigInteger; - (id)divide:(JKBigInteger *)bigInteger; - (id)remainder:(JKBigInteger *)bigInteger; - (NSArray *)divideAndRemainder:(JKBigInteger *)bigInteger; - (id)pow:(unsigned int)exponent; - (id)pow:(JKBigInteger*)exponent andMod:(JKBigInteger*)modulus; - (id)negate; - (id)abs; - (id)bitwiseXor:(JKBigInteger *)bigInteger; - (id)bitwiseOr:(JKBigInteger *)bigInteger; - (id)bitwiseAnd:(JKBigInteger *)bigInteger; - (id)shiftLeft:(unsigned int)n; - (id)shiftRight:(unsigned int)n; - (id)gcd:(JKBigInteger *)bigInteger; - (NSComparisonResult) compare:(JKBigInteger *)bigInteger; - (unsigned long)unsignedIntValue; - (NSString *)stringValue; - (NSString *)stringValueWithRadix:(int)radix; - (NSString *)description; - (unsigned int)countBytes; - (void)toByteArraySigned: (unsigned char*) byteArray; - (void)toByteArrayUnsigned: (unsigned char*) byteArray; @end ================================================ FILE: ios/JKBigInteger/JKBigInteger.m ================================================ // // JKBigInteger.m // JKBigInteger // // Created by Jānis Kiršteins on 5/21/13. // Copyright (c) 2013 Jānis Kiršteins. All rights reserved. // // Licensed under the MIT License #import "JKBigInteger.h" @implementation JKBigInteger { @private mp_int m_value; } - (id)initWithValue:(mp_int *)value { self = [super init]; if (self) { mp_init_copy(&m_value, value); } return self; } - (mp_int *)value { return &m_value; } - (id)initWithUnsignedLong:(unsigned long)unsignedLong { self = [super init]; if (self) { mp_set_int(&m_value, unsignedLong); } return self; } - (id)init { return [self initWithUnsignedLong:0]; } - (id)initWithCString:(char *)cString andRadix:(int)radix { if (radix < 2 || radix > 64) { return nil; } self = [super init]; if (self) { mp_init(&m_value); int result; result = mp_read_radix(&m_value, cString, radix); if (result != MP_OKAY) { mp_clear(&m_value); return nil; } } return self; } - (id)initWithCString:(char *)cString { int radix = 10; return [self initWithCString:cString andRadix:radix]; } - (id)initWithString:(NSString *)string andRadix:(int)radix { return [self initWithCString:(char *)[string UTF8String] andRadix:radix]; } - (id)initWithString:(NSString *)string { int radix = 10; return [self initWithCString:(char *)[string UTF8String] andRadix:radix]; } - (id)initWithCoder:(NSCoder *)decoder { self = [super init]; if (self) { int sign = [decoder decodeInt32ForKey:@"JKBigIntegerSign"]; int alloc = [decoder decodeInt32ForKey:@"JKBigIntegerAlloc"]; mp_init_size(&m_value, alloc); NSData *data = (NSData *)[decoder decodeObjectForKey:@"JKBigIntegerDP"]; mp_digit *temp = (mp_digit *)[data bytes]; for (unsigned int i = 0; i < alloc; ++i) { m_value.dp[i] = temp[i]; } m_value.used = alloc; m_value.sign = sign; } return self; } - (void)encodeWithCoder:(NSCoder *)encoder { mp_clamp(&m_value); NSData *data = [NSData dataWithBytes:(const void *)m_value.dp length:m_value.alloc * sizeof(mp_digit)]; [encoder encodeObject:data forKey:@"JKBigIntegerDP"]; [encoder encodeInteger:m_value.alloc forKey:@"JKBigIntegerAlloc"]; [encoder encodeInteger:m_value.sign forKey:@"JKBigIntegerSign"]; } - (id)add:(JKBigInteger *)bigInteger { mp_int sum; mp_init(&sum); mp_add(&m_value, [bigInteger value], &sum); id newBigInteger = [[JKBigInteger alloc] initWithValue:&sum]; mp_clear(&sum); return newBigInteger; } - (id)subtract:(JKBigInteger *)bigInteger { mp_int difference; mp_init(&difference); mp_sub(&m_value, [bigInteger value], &difference); id newBigInteger = [[JKBigInteger alloc] initWithValue:&difference]; mp_clear(&difference); return newBigInteger; } - (id)multiply:(JKBigInteger *)bigInteger { mp_int product; mp_init(&product); mp_mul(&m_value, [bigInteger value], &product); JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&product]; mp_clear(&product); return newBigInteger; } - (id)divide:(JKBigInteger *)bigInteger { int result; mp_int quotient; mp_init("ient); result = mp_div(&m_value, [bigInteger value], "ient, NULL); if (result == MP_VAL) { mp_clear("ient); return nil; } JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:"ient]; mp_clear("ient); return newBigInteger; } - (id)remainder:(JKBigInteger *)bigInteger { int result; mp_int remainder; mp_init(&remainder); result = mp_div(&m_value, [bigInteger value], NULL, &remainder); if (result == MP_VAL) { mp_clear(&remainder); return nil; } JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&remainder]; mp_clear(&remainder); return newBigInteger; } - (NSArray *)divideAndRemainder:(JKBigInteger *)bigInteger { int result; mp_int quotient, remainder; mp_init_multi("ient, &remainder, NULL); result = mp_div(&m_value, [bigInteger value], "ient, &remainder); if (result == MP_VAL) { mp_clear_multi("ient, &remainder, NULL); return nil; } JKBigInteger *quotientBigInteger = [[JKBigInteger alloc] initWithValue:"ient]; JKBigInteger *remainderBigInteger = [[JKBigInteger alloc] initWithValue:&remainder]; mp_clear_multi("ient, &remainder, NULL); return @[quotientBigInteger, remainderBigInteger]; } - (id)pow:(unsigned int)exponent { int result; mp_int power; mp_init(&power); result = mp_expt_d(&m_value, (mp_digit)exponent, &power); if (result == MP_VAL) { mp_clear(&power); return nil; } JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&power]; mp_clear(&power); return newBigInteger; } - (id)pow:(JKBigInteger*)exponent andMod: (JKBigInteger*)modulus { int result; mp_int output; mp_init(&output); result = mp_exptmod(&m_value, &exponent->m_value, &modulus->m_value, &output); if (result == MP_VAL) { mp_clear(&output); return nil; } JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&output]; mp_clear(&output); return newBigInteger; } - (id)negate { mp_int negate; mp_init(&negate); mp_neg(&m_value, &negate); JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&negate]; mp_clear(&negate); return newBigInteger; } - (id)abs { mp_int absolute; mp_init(&absolute); mp_abs(&m_value, &absolute); JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&absolute]; mp_clear(&absolute); return newBigInteger; } - (id)bitwiseXor:(JKBigInteger *)bigInteger { mp_int xor; mp_init(&xor); mp_xor(&m_value, [bigInteger value], &xor); JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&xor]; mp_clear(&xor); return newBigInteger; } - (id)bitwiseOr:(JKBigInteger *)bigInteger { mp_int or; mp_init(&or); mp_or(&m_value, [bigInteger value], &or); JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&or]; mp_clear(&or); return newBigInteger; } - (id)bitwiseAnd:(JKBigInteger *)bigInteger { mp_int and; mp_init(&and); mp_and(&m_value, [bigInteger value], &and); JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&and]; mp_clear(&and); return newBigInteger; } - (id)shiftLeft:(unsigned int)n { mp_int lShift; mp_init(&lShift); mp_mul_2d(&m_value, n, &lShift); JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&lShift]; mp_clear(&lShift); return newBigInteger; } - (id)shiftRight:(unsigned int)n { mp_int rShift; mp_init(&rShift); mp_div_2d(&m_value, n, &rShift, NULL); JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&rShift]; mp_clear(&rShift); return newBigInteger; } - (id)gcd:(JKBigInteger *)bigInteger { int result; mp_int gcd; mp_init(&gcd); result = mp_gcd(&m_value, [bigInteger value], &gcd); if (result == MP_VAL) { mp_clear(&gcd); return nil; } JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&gcd]; mp_clear(&gcd); return newBigInteger; } - (NSComparisonResult) compare:(JKBigInteger *)bigInteger { NSComparisonResult comparisonResult; comparisonResult = mp_cmp([bigInteger value], &m_value); switch (comparisonResult) { case MP_GT: return NSOrderedAscending; case MP_EQ: return NSOrderedSame; case MP_LT: return NSOrderedDescending; default: return 0; } } - (unsigned long)unsignedIntValue { return mp_get_int(&m_value); } - (NSString *)stringValue { int radix = 10; return [self stringValueWithRadix:radix]; } - (NSString *)stringValueWithRadix:(int)radix { int stringSize; mp_radix_size(&m_value, radix, &stringSize); char cString[stringSize]; mp_toradix(&m_value, cString, radix); for (int i = 0; i < stringSize; ++i) { cString[i] = (char)tolower(cString[i]); } return [NSString stringWithUTF8String:cString]; } - (NSString *)description { return [self stringValue]; } - (void)dealloc { mp_clear(&m_value); } /* Returns the number of bytes required to store this JKBigInteger as binary */ - (unsigned int)countBytes { return (unsigned int) mp_unsigned_bin_size(&m_value); } /* Retrieves the signed [big endian] format of this JKBigInteger */ - (void)toByteArraySigned: (unsigned char*) byteArray { mp_to_signed_bin(&m_value, byteArray); } /* Retrieves the unsigned [big endian] format of this JKBigInteger */ - (void)toByteArrayUnsigned: (unsigned char*) byteArray { mp_to_unsigned_bin(&m_value, byteArray); } @end ================================================ FILE: ios/JKBigInteger/LibTomMath/tommath.c ================================================ #include "tommath.h" #ifdef BN_S_MP_MUL_DIGS_C /* LibTomMath, multiple-precision integer library -- Tom St Denis * * LibTomMath is a library that provides multiple-precision * integer arithmetic as well as number theoretic functionality. * * The library was designed directly after the MPI library by * Michael Fromberger but has been written from scratch with * additional optimizations in place. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, tomstdenis@gmail.com, http://libtom.org */ /* multiplies |a| * |b| and only computes upto digs digits of result * HAC pp. 595, Algorithm 14.12 Modified so you can control how * many digits of output are created. */ int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs) { mp_int t; int res, pa, pb, ix, iy; mp_digit u; mp_word r; mp_digit tmpx, *tmpt, *tmpy; /* can we use the fast multiplier? */ if (((digs) < MP_WARRAY) && MIN (a->used, b->used) < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) { return fast_s_mp_mul_digs (a, b, c, digs); } if ((res = mp_init_size (&t, digs)) != MP_OKAY) { return res; } t.used = digs; /* compute the digits of the product directly */ pa = a->used; for (ix = 0; ix < pa; ix++) { /* set the carry to zero */ u = 0; /* limit ourselves to making digs digits of output */ pb = MIN (b->used, digs - ix); /* setup some aliases */ /* copy of the digit from a used within the nested loop */ tmpx = a->dp[ix]; /* an alias for the destination shifted ix places */ tmpt = t.dp + ix; /* an alias for the digits of b */ tmpy = b->dp; /* compute the columns of the output and propagate the carry */ for (iy = 0; iy < pb; iy++) { /* compute the column as a mp_word */ r = ((mp_word)*tmpt) + ((mp_word)tmpx) * ((mp_word)*tmpy++) + ((mp_word) u); /* the new column is the lower part of the result */ *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); /* get the carry word from the result */ u = (mp_digit) (r >> ((mp_word) DIGIT_BIT)); } /* set carry if it is placed below digs */ if (ix + iy < digs) { *tmpt = u; } } mp_clamp (&t); mp_exch (&t, c); mp_clear (&t); return MP_OKAY; } #endif #ifdef BN_MP_TO_UNSIGNED_BIN_N_C /* store in unsigned [big endian] format */ int mp_to_unsigned_bin_n (mp_int * a, unsigned char *b, unsigned long *outlen) { if (*outlen < (unsigned long)mp_unsigned_bin_size(a)) { return MP_VAL; } *outlen = mp_unsigned_bin_size(a); return mp_to_unsigned_bin(a, b); } #endif #ifdef BN_MP_EXPT_D_C /* calculate c = a**b using a square-multiply algorithm */ int mp_expt_d (mp_int * a, mp_digit b, mp_int * c) { int res, x; mp_int g; if ((res = mp_init_copy (&g, a)) != MP_OKAY) { return res; } /* set initial result */ mp_set (c, 1); for (x = 0; x < (int) DIGIT_BIT; x++) { /* square */ if ((res = mp_sqr (c, c)) != MP_OKAY) { mp_clear (&g); return res; } /* if the bit is set multiply */ if ((b & (mp_digit) (((mp_digit)1) << (DIGIT_BIT - 1))) != 0) { if ((res = mp_mul (c, &g, c)) != MP_OKAY) { mp_clear (&g); return res; } } /* shift to next bit */ b <<= 1; } mp_clear (&g); return MP_OKAY; } #endif #ifdef BN_MP_SET_INT_C /* set a 32-bit const */ int mp_set_int (mp_int * a, unsigned long b) { int x, res; mp_zero (a); /* set four bits at a time */ for (x = 0; x < 8; x++) { /* shift the number up four bits */ if ((res = mp_mul_2d (a, 4, a)) != MP_OKAY) { return res; } /* OR in the top four bits of the source */ a->dp[0] |= (b >> 28) & 15; /* shift the source up to the next four bits */ b <<= 4; /* ensure that digits are not clamped off */ a->used += 1; } mp_clamp (a); return MP_OKAY; } #endif #ifdef BN_MP_ADD_C /* high level addition (handles signs) */ int mp_add (mp_int * a, mp_int * b, mp_int * c) { int sa, sb, res; /* get sign of both inputs */ sa = a->sign; sb = b->sign; /* handle two cases, not four */ if (sa == sb) { /* both positive or both negative */ /* add their magnitudes, copy the sign */ c->sign = sa; res = s_mp_add (a, b, c); } else { /* one positive, the other negative */ /* subtract the one with the greater magnitude from */ /* the one of the lesser magnitude. The result gets */ /* the sign of the one with the greater magnitude. */ if (mp_cmp_mag (a, b) == MP_LT) { c->sign = sb; res = s_mp_sub (b, a, c); } else { c->sign = sa; res = s_mp_sub (a, b, c); } } return res; } #endif #ifdef BN_MP_INIT_C /* init a new mp_int */ int mp_init (mp_int * a) { int i; /* allocate memory required and clear it */ a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * MP_PREC); if (a->dp == NULL) { return MP_MEM; } /* set the digits to zero */ for (i = 0; i < MP_PREC; i++) { a->dp[i] = 0; } /* set the used to zero, allocated digits to the default precision * and sign to positive */ a->used = 0; a->alloc = MP_PREC; a->sign = MP_ZPOS; return MP_OKAY; } #endif #ifdef BN_MP_CNT_LSB_C static const int lnz[16] = { 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0 }; /* Counts the number of lsbs which are zero before the first zero bit */ int mp_cnt_lsb(mp_int *a) { int x; mp_digit q, qq; /* easy out */ if (mp_iszero(a) == 1) { return 0; } /* scan lower digits until non-zero */ for (x = 0; x < a->used && a->dp[x] == 0; x++); q = a->dp[x]; x *= DIGIT_BIT; /* now scan this digit until a 1 is found */ if ((q & 1) == 0) { do { qq = q & 15; x += lnz[qq]; q >>= 4; } while (qq == 0); } return x; } #endif #ifdef BN_MP_TOOM_SQR_C /* squaring using Toom-Cook 3-way algorithm */ int mp_toom_sqr(mp_int *a, mp_int *b) { mp_int w0, w1, w2, w3, w4, tmp1, a0, a1, a2; int res, B; /* init temps */ if ((res = mp_init_multi(&w0, &w1, &w2, &w3, &w4, &a0, &a1, &a2, &tmp1, NULL)) != MP_OKAY) { return res; } /* B */ B = a->used / 3; /* a = a2 * B**2 + a1 * B + a0 */ if ((res = mp_mod_2d(a, DIGIT_BIT * B, &a0)) != MP_OKAY) { goto ERR; } if ((res = mp_copy(a, &a1)) != MP_OKAY) { goto ERR; } mp_rshd(&a1, B); mp_mod_2d(&a1, DIGIT_BIT * B, &a1); if ((res = mp_copy(a, &a2)) != MP_OKAY) { goto ERR; } mp_rshd(&a2, B*2); /* w0 = a0*a0 */ if ((res = mp_sqr(&a0, &w0)) != MP_OKAY) { goto ERR; } /* w4 = a2 * a2 */ if ((res = mp_sqr(&a2, &w4)) != MP_OKAY) { goto ERR; } /* w1 = (a2 + 2(a1 + 2a0))**2 */ if ((res = mp_mul_2(&a0, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, &a1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_mul_2(&tmp1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, &a2, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_sqr(&tmp1, &w1)) != MP_OKAY) { goto ERR; } /* w3 = (a0 + 2(a1 + 2a2))**2 */ if ((res = mp_mul_2(&a2, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, &a1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_mul_2(&tmp1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, &a0, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_sqr(&tmp1, &w3)) != MP_OKAY) { goto ERR; } /* w2 = (a2 + a1 + a0)**2 */ if ((res = mp_add(&a2, &a1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, &a0, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_sqr(&tmp1, &w2)) != MP_OKAY) { goto ERR; } /* now solve the matrix 0 0 0 0 1 1 2 4 8 16 1 1 1 1 1 16 8 4 2 1 1 0 0 0 0 using 12 subtractions, 4 shifts, 2 small divisions and 1 small multiplication. */ /* r1 - r4 */ if ((res = mp_sub(&w1, &w4, &w1)) != MP_OKAY) { goto ERR; } /* r3 - r0 */ if ((res = mp_sub(&w3, &w0, &w3)) != MP_OKAY) { goto ERR; } /* r1/2 */ if ((res = mp_div_2(&w1, &w1)) != MP_OKAY) { goto ERR; } /* r3/2 */ if ((res = mp_div_2(&w3, &w3)) != MP_OKAY) { goto ERR; } /* r2 - r0 - r4 */ if ((res = mp_sub(&w2, &w0, &w2)) != MP_OKAY) { goto ERR; } if ((res = mp_sub(&w2, &w4, &w2)) != MP_OKAY) { goto ERR; } /* r1 - r2 */ if ((res = mp_sub(&w1, &w2, &w1)) != MP_OKAY) { goto ERR; } /* r3 - r2 */ if ((res = mp_sub(&w3, &w2, &w3)) != MP_OKAY) { goto ERR; } /* r1 - 8r0 */ if ((res = mp_mul_2d(&w0, 3, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_sub(&w1, &tmp1, &w1)) != MP_OKAY) { goto ERR; } /* r3 - 8r4 */ if ((res = mp_mul_2d(&w4, 3, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_sub(&w3, &tmp1, &w3)) != MP_OKAY) { goto ERR; } /* 3r2 - r1 - r3 */ if ((res = mp_mul_d(&w2, 3, &w2)) != MP_OKAY) { goto ERR; } if ((res = mp_sub(&w2, &w1, &w2)) != MP_OKAY) { goto ERR; } if ((res = mp_sub(&w2, &w3, &w2)) != MP_OKAY) { goto ERR; } /* r1 - r2 */ if ((res = mp_sub(&w1, &w2, &w1)) != MP_OKAY) { goto ERR; } /* r3 - r2 */ if ((res = mp_sub(&w3, &w2, &w3)) != MP_OKAY) { goto ERR; } /* r1/3 */ if ((res = mp_div_3(&w1, &w1, NULL)) != MP_OKAY) { goto ERR; } /* r3/3 */ if ((res = mp_div_3(&w3, &w3, NULL)) != MP_OKAY) { goto ERR; } /* at this point shift W[n] by B*n */ if ((res = mp_lshd(&w1, 1*B)) != MP_OKAY) { goto ERR; } if ((res = mp_lshd(&w2, 2*B)) != MP_OKAY) { goto ERR; } if ((res = mp_lshd(&w3, 3*B)) != MP_OKAY) { goto ERR; } if ((res = mp_lshd(&w4, 4*B)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&w0, &w1, b)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&w2, &w3, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&w4, &tmp1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, b, b)) != MP_OKAY) { goto ERR; } ERR: mp_clear_multi(&w0, &w1, &w2, &w3, &w4, &a0, &a1, &a2, &tmp1, NULL); return res; } #endif #ifdef BN_MP_FREAD_C /* read a bigint from a file stream in ASCII */ int mp_fread(mp_int *a, int radix, FILE *stream) { int err, ch, neg, y; /* clear a */ mp_zero(a); /* if first digit is - then set negative */ ch = fgetc(stream); if (ch == '-') { neg = MP_NEG; ch = fgetc(stream); } else { neg = MP_ZPOS; } for (;;) { /* find y in the radix map */ for (y = 0; y < radix; y++) { if (mp_s_rmap[y] == ch) { break; } } if (y == radix) { break; } /* shift up and add */ if ((err = mp_mul_d(a, radix, a)) != MP_OKAY) { return err; } if ((err = mp_add_d(a, y, a)) != MP_OKAY) { return err; } ch = fgetc(stream); } if (mp_cmp_d(a, 0) != MP_EQ) { a->sign = neg; } return MP_OKAY; } #endif #ifdef BN_MP_DIV_3_C /* divide by three (based on routine from MPI and the GMP manual) */ int mp_div_3 (mp_int * a, mp_int *c, mp_digit * d) { mp_int q; mp_word w, t; mp_digit b; int res, ix; /* b = 2**DIGIT_BIT / 3 */ b = (((mp_word)1) << ((mp_word)DIGIT_BIT)) / ((mp_word)3); if ((res = mp_init_size(&q, a->used)) != MP_OKAY) { return res; } q.used = a->used; q.sign = a->sign; w = 0; for (ix = a->used - 1; ix >= 0; ix--) { w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]); if (w >= 3) { /* multiply w by [1/3] */ t = (w * ((mp_word)b)) >> ((mp_word)DIGIT_BIT); /* now subtract 3 * [w/3] from w, to get the remainder */ w -= t+t+t; /* fixup the remainder as required since * the optimization is not exact. */ while (w >= 3) { t += 1; w -= 3; } } else { t = 0; } q.dp[ix] = (mp_digit)t; } /* [optional] store the remainder */ if (d != NULL) { *d = (mp_digit)w; } /* [optional] store the quotient */ if (c != NULL) { mp_clamp(&q); mp_exch(&q, c); } mp_clear(&q); return res; } #endif #ifdef BN_MP_LCM_C /* computes least common multiple as |a*b|/(a, b) */ int mp_lcm (mp_int * a, mp_int * b, mp_int * c) { int res; mp_int t1, t2; if ((res = mp_init_multi (&t1, &t2, NULL)) != MP_OKAY) { return res; } /* t1 = get the GCD of the two inputs */ if ((res = mp_gcd (a, b, &t1)) != MP_OKAY) { goto LBL_T; } /* divide the smallest by the GCD */ if (mp_cmp_mag(a, b) == MP_LT) { /* store quotient in t2 such that t2 * b is the LCM */ if ((res = mp_div(a, &t1, &t2, NULL)) != MP_OKAY) { goto LBL_T; } res = mp_mul(b, &t2, c); } else { /* store quotient in t2 such that t2 * a is the LCM */ if ((res = mp_div(b, &t1, &t2, NULL)) != MP_OKAY) { goto LBL_T; } res = mp_mul(a, &t2, c); } /* fix the sign to positive */ c->sign = MP_ZPOS; LBL_T: mp_clear_multi (&t1, &t2, NULL); return res; } #endif #ifdef BN_MP_REDUCE_IS_2K_C /* determines if mp_reduce_2k can be used */ int mp_reduce_is_2k(mp_int *a) { int ix, iy, iw; mp_digit iz; if (a->used == 0) { return MP_NO; } else if (a->used == 1) { return MP_YES; } else if (a->used > 1) { iy = mp_count_bits(a); iz = 1; iw = 1; /* Test every bit from the second digit up, must be 1 */ for (ix = DIGIT_BIT; ix < iy; ix++) { if ((a->dp[iw] & iz) == 0) { return MP_NO; } iz <<= 1; if (iz > (mp_digit)MP_MASK) { ++iw; iz = 1; } } } return MP_YES; } #endif #ifdef BNCORE_C /* Known optimal configurations CPU /Compiler /MUL CUTOFF/SQR CUTOFF ------------------------------------------------------------- Intel P4 Northwood /GCC v3.4.1 / 88/ 128/LTM 0.32 ;-) AMD Athlon64 /GCC v3.4.4 / 80/ 120/LTM 0.35 */ int KARATSUBA_MUL_CUTOFF = 80, /* Min. number of digits before Karatsuba multiplication is used. */ KARATSUBA_SQR_CUTOFF = 120, /* Min. number of digits before Karatsuba squaring is used. */ TOOM_MUL_CUTOFF = 350, /* no optimal values of these are known yet so set em high */ TOOM_SQR_CUTOFF = 400; #endif #ifdef BN_MP_MOD_2D_C /* calc a value mod 2**b */ int mp_mod_2d (mp_int * a, int b, mp_int * c) { int x, res; /* if b is <= 0 then zero the int */ if (b <= 0) { mp_zero (c); return MP_OKAY; } /* if the modulus is larger than the value than return */ if (b >= (int) (a->used * DIGIT_BIT)) { res = mp_copy (a, c); return res; } /* copy */ if ((res = mp_copy (a, c)) != MP_OKAY) { return res; } /* zero digits above the last digit of the modulus */ for (x = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1); x < c->used; x++) { c->dp[x] = 0; } /* clear the digit that is not completely outside/inside the modulus */ c->dp[b / DIGIT_BIT] &= (mp_digit) ((((mp_digit) 1) << (((mp_digit) b) % DIGIT_BIT)) - ((mp_digit) 1)); mp_clamp (c); return MP_OKAY; } #endif #ifdef BN_MP_N_ROOT_C /* find the n'th root of an integer * * Result found such that (c)**b <= a and (c+1)**b > a * * This algorithm uses Newton's approximation * x[i+1] = x[i] - f(x[i])/f'(x[i]) * which will find the root in log(N) time where * each step involves a fair bit. This is not meant to * find huge roots [square and cube, etc]. */ int mp_n_root (mp_int * a, mp_digit b, mp_int * c) { mp_int t1, t2, t3; int res, neg; /* input must be positive if b is even */ if ((b & 1) == 0 && a->sign == MP_NEG) { return MP_VAL; } if ((res = mp_init (&t1)) != MP_OKAY) { return res; } if ((res = mp_init (&t2)) != MP_OKAY) { goto LBL_T1; } if ((res = mp_init (&t3)) != MP_OKAY) { goto LBL_T2; } /* if a is negative fudge the sign but keep track */ neg = a->sign; a->sign = MP_ZPOS; /* t2 = 2 */ mp_set (&t2, 2); do { /* t1 = t2 */ if ((res = mp_copy (&t2, &t1)) != MP_OKAY) { goto LBL_T3; } /* t2 = t1 - ((t1**b - a) / (b * t1**(b-1))) */ /* t3 = t1**(b-1) */ if ((res = mp_expt_d (&t1, b - 1, &t3)) != MP_OKAY) { goto LBL_T3; } /* numerator */ /* t2 = t1**b */ if ((res = mp_mul (&t3, &t1, &t2)) != MP_OKAY) { goto LBL_T3; } /* t2 = t1**b - a */ if ((res = mp_sub (&t2, a, &t2)) != MP_OKAY) { goto LBL_T3; } /* denominator */ /* t3 = t1**(b-1) * b */ if ((res = mp_mul_d (&t3, b, &t3)) != MP_OKAY) { goto LBL_T3; } /* t3 = (t1**b - a)/(b * t1**(b-1)) */ if ((res = mp_div (&t2, &t3, &t3, NULL)) != MP_OKAY) { goto LBL_T3; } if ((res = mp_sub (&t1, &t3, &t2)) != MP_OKAY) { goto LBL_T3; } } while (mp_cmp (&t1, &t2) != MP_EQ); /* result can be off by a few so check */ for (;;) { if ((res = mp_expt_d (&t1, b, &t2)) != MP_OKAY) { goto LBL_T3; } if (mp_cmp (&t2, a) == MP_GT) { if ((res = mp_sub_d (&t1, 1, &t1)) != MP_OKAY) { goto LBL_T3; } } else { break; } } /* reset the sign of a first */ a->sign = neg; /* set the result */ mp_exch (&t1, c); /* set the sign of the result */ c->sign = neg; res = MP_OKAY; LBL_T3:mp_clear (&t3); LBL_T2:mp_clear (&t2); LBL_T1:mp_clear (&t1); return res; } #endif #ifdef BN_MP_MULMOD_C /* d = a * b (mod c) */ int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d) { int res; mp_int t; if ((res = mp_init (&t)) != MP_OKAY) { return res; } if ((res = mp_mul (a, b, &t)) != MP_OKAY) { mp_clear (&t); return res; } res = mp_mod (&t, c, d); mp_clear (&t); return res; } #endif #ifdef BN_ERROR_C static const struct { int code; char *msg; } msgs[] = { { MP_OKAY, "Successful" }, { MP_MEM, "Out of heap" }, { MP_VAL, "Value out of range" } }; /* return a char * string for a given code */ char *mp_error_to_string(int code) { int x; /* scan the lookup table for the given message */ for (x = 0; x < (int)(sizeof(msgs) / sizeof(msgs[0])); x++) { if (msgs[x].code == code) { return msgs[x].msg; } } /* generic reply for invalid code */ return "Invalid error code"; } #endif #ifdef BN_MP_REDUCE_C /* reduces x mod m, assumes 0 < x < m**2, mu is * precomputed via mp_reduce_setup. * From HAC pp.604 Algorithm 14.42 */ int mp_reduce (mp_int * x, mp_int * m, mp_int * mu) { mp_int q; int res, um = m->used; /* q = x */ if ((res = mp_init_copy (&q, x)) != MP_OKAY) { return res; } /* q1 = x / b**(k-1) */ mp_rshd (&q, um - 1); /* according to HAC this optimization is ok */ if (((unsigned long) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) { if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) { goto CLEANUP; } } else { #ifdef BN_S_MP_MUL_HIGH_DIGS_C if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) { goto CLEANUP; } #elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C) if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) { goto CLEANUP; } #else { res = MP_VAL; goto CLEANUP; } #endif } /* q3 = q2 / b**(k+1) */ mp_rshd (&q, um + 1); /* x = x mod b**(k+1), quick (no division) */ if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) { goto CLEANUP; } /* q = q * m mod b**(k+1), quick (no division) */ if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) { goto CLEANUP; } /* x = x - q */ if ((res = mp_sub (x, &q, x)) != MP_OKAY) { goto CLEANUP; } /* If x < 0, add b**(k+1) to it */ if (mp_cmp_d (x, 0) == MP_LT) { mp_set (&q, 1); if ((res = mp_lshd (&q, um + 1)) != MP_OKAY) goto CLEANUP; if ((res = mp_add (x, &q, x)) != MP_OKAY) goto CLEANUP; } /* Back off if it's too big */ while (mp_cmp (x, m) != MP_LT) { if ((res = s_mp_sub (x, m, x)) != MP_OKAY) { goto CLEANUP; } } CLEANUP: mp_clear (&q); return res; } #endif #ifdef BN_MP_KARATSUBA_SQR_C /* Karatsuba squaring, computes b = a*a using three * half size squarings * * See comments of karatsuba_mul for details. It * is essentially the same algorithm but merely * tuned to perform recursive squarings. */ int mp_karatsuba_sqr (mp_int * a, mp_int * b) { mp_int x0, x1, t1, t2, x0x0, x1x1; int B, err; err = MP_MEM; /* min # of digits */ B = a->used; /* now divide in two */ B = B >> 1; /* init copy all the temps */ if (mp_init_size (&x0, B) != MP_OKAY) goto ERR; if (mp_init_size (&x1, a->used - B) != MP_OKAY) goto X0; /* init temps */ if (mp_init_size (&t1, a->used * 2) != MP_OKAY) goto X1; if (mp_init_size (&t2, a->used * 2) != MP_OKAY) goto T1; if (mp_init_size (&x0x0, B * 2) != MP_OKAY) goto T2; if (mp_init_size (&x1x1, (a->used - B) * 2) != MP_OKAY) goto X0X0; { register int x; register mp_digit *dst, *src; src = a->dp; /* now shift the digits */ dst = x0.dp; for (x = 0; x < B; x++) { *dst++ = *src++; } dst = x1.dp; for (x = B; x < a->used; x++) { *dst++ = *src++; } } x0.used = B; x1.used = a->used - B; mp_clamp (&x0); /* now calc the products x0*x0 and x1*x1 */ if (mp_sqr (&x0, &x0x0) != MP_OKAY) goto X1X1; /* x0x0 = x0*x0 */ if (mp_sqr (&x1, &x1x1) != MP_OKAY) goto X1X1; /* x1x1 = x1*x1 */ /* now calc (x1+x0)**2 */ if (s_mp_add (&x1, &x0, &t1) != MP_OKAY) goto X1X1; /* t1 = x1 - x0 */ if (mp_sqr (&t1, &t1) != MP_OKAY) goto X1X1; /* t1 = (x1 - x0) * (x1 - x0) */ /* add x0y0 */ if (s_mp_add (&x0x0, &x1x1, &t2) != MP_OKAY) goto X1X1; /* t2 = x0x0 + x1x1 */ if (s_mp_sub (&t1, &t2, &t1) != MP_OKAY) goto X1X1; /* t1 = (x1+x0)**2 - (x0x0 + x1x1) */ /* shift by B */ if (mp_lshd (&t1, B) != MP_OKAY) goto X1X1; /* t1 = (x0x0 + x1x1 - (x1-x0)*(x1-x0))<sign = MP_ZPOS; a->used = 0; tmp = a->dp; for (n = 0; n < a->alloc; n++) { *tmp++ = 0; } } #endif #ifdef BN_MP_TORADIX_C /* stores a bignum as a ASCII string in a given radix (2..64) */ int mp_toradix (mp_int * a, char *str, int radix) { int res, digs; mp_int t; mp_digit d; char *_s = str; /* check range of the radix */ if (radix < 2 || radix > 64) { return MP_VAL; } /* quick out if its zero */ if (mp_iszero(a) == 1) { *str++ = '0'; *str = '\0'; return MP_OKAY; } if ((res = mp_init_copy (&t, a)) != MP_OKAY) { return res; } /* if it is negative output a - */ if (t.sign == MP_NEG) { ++_s; *str++ = '-'; t.sign = MP_ZPOS; } digs = 0; while (mp_iszero (&t) == 0) { if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) { mp_clear (&t); return res; } *str++ = mp_s_rmap[d]; ++digs; } /* reverse the digits of the string. In this case _s points * to the first digit [exluding the sign] of the number] */ bn_reverse ((unsigned char *)_s, digs); /* append a NULL so the string is properly terminated */ *str = '\0'; mp_clear (&t); return MP_OKAY; } #endif #ifdef BN_MP_DIV_D_C static int s_is_power_of_two(mp_digit b, int *p) { int x; /* fast return if no power of two */ if ((b==0) || (b & (b-1))) { return 0; } for (x = 0; x < DIGIT_BIT; x++) { if (b == (((mp_digit)1)<dp[0] & ((((mp_digit)1)<used)) != MP_OKAY) { return res; } q.used = a->used; q.sign = a->sign; w = 0; for (ix = a->used - 1; ix >= 0; ix--) { w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]); if (w >= b) { t = (mp_digit)(w / b); w -= ((mp_word)t) * ((mp_word)b); } else { t = 0; } q.dp[ix] = (mp_digit)t; } if (d != NULL) { *d = (mp_digit)w; } if (c != NULL) { mp_clamp(&q); mp_exch(&q, c); } mp_clear(&q); return res; } #endif #ifdef BN_MP_SUB_C /* high level subtraction (handles signs) */ int mp_sub (mp_int * a, mp_int * b, mp_int * c) { int sa, sb, res; sa = a->sign; sb = b->sign; if (sa != sb) { /* subtract a negative from a positive, OR */ /* subtract a positive from a negative. */ /* In either case, ADD their magnitudes, */ /* and use the sign of the first number. */ c->sign = sa; res = s_mp_add (a, b, c); } else { /* subtract a positive from a positive, OR */ /* subtract a negative from a negative. */ /* First, take the difference between their */ /* magnitudes, then... */ if (mp_cmp_mag (a, b) != MP_LT) { /* Copy the sign from the first */ c->sign = sa; /* The first has a larger or equal magnitude */ res = s_mp_sub (a, b, c); } else { /* The result has the *opposite* sign from */ /* the first number. */ c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS; /* The second has a larger magnitude */ res = s_mp_sub (b, a, c); } } return res; } #endif #ifdef BN_MP_INIT_SIZE_C /* init an mp_init for a given size */ int mp_init_size (mp_int * a, int size) { int x; /* pad size so there are always extra digits */ size += (MP_PREC * 2) - (size % MP_PREC); /* alloc mem */ a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * size); if (a->dp == NULL) { return MP_MEM; } /* set the members */ a->used = 0; a->alloc = size; a->sign = MP_ZPOS; /* zero the digits */ for (x = 0; x < size; x++) { a->dp[x] = 0; } return MP_OKAY; } #endif #ifdef BN_MP_PRIME_NEXT_PRIME_C /* finds the next prime after the number "a" using "t" trials * of Miller-Rabin. * * bbs_style = 1 means the prime must be congruent to 3 mod 4 */ int mp_prime_next_prime(mp_int *a, int t, int bbs_style) { int err, res = 0, x, y; mp_digit res_tab[PRIME_SIZE], step, kstep; mp_int b; /* ensure t is valid */ if (t <= 0 || t > PRIME_SIZE) { return MP_VAL; } /* force positive */ a->sign = MP_ZPOS; /* simple algo if a is less than the largest prime in the table */ if (mp_cmp_d(a, ltm_prime_tab[PRIME_SIZE-1]) == MP_LT) { /* find which prime it is bigger than */ for (x = PRIME_SIZE - 2; x >= 0; x--) { if (mp_cmp_d(a, ltm_prime_tab[x]) != MP_LT) { if (bbs_style == 1) { /* ok we found a prime smaller or * equal [so the next is larger] * * however, the prime must be * congruent to 3 mod 4 */ if ((ltm_prime_tab[x + 1] & 3) != 3) { /* scan upwards for a prime congruent to 3 mod 4 */ for (y = x + 1; y < PRIME_SIZE; y++) { if ((ltm_prime_tab[y] & 3) == 3) { mp_set(a, ltm_prime_tab[y]); return MP_OKAY; } } } } else { mp_set(a, ltm_prime_tab[x + 1]); return MP_OKAY; } } } /* at this point a maybe 1 */ if (mp_cmp_d(a, 1) == MP_EQ) { mp_set(a, 2); return MP_OKAY; } /* fall through to the sieve */ } /* generate a prime congruent to 3 mod 4 or 1/3 mod 4? */ if (bbs_style == 1) { kstep = 4; } else { kstep = 2; } /* at this point we will use a combination of a sieve and Miller-Rabin */ if (bbs_style == 1) { /* if a mod 4 != 3 subtract the correct value to make it so */ if ((a->dp[0] & 3) != 3) { if ((err = mp_sub_d(a, (a->dp[0] & 3) + 1, a)) != MP_OKAY) { return err; }; } } else { if (mp_iseven(a) == 1) { /* force odd */ if ((err = mp_sub_d(a, 1, a)) != MP_OKAY) { return err; } } } /* generate the restable */ for (x = 1; x < PRIME_SIZE; x++) { if ((err = mp_mod_d(a, ltm_prime_tab[x], res_tab + x)) != MP_OKAY) { return err; } } /* init temp used for Miller-Rabin Testing */ if ((err = mp_init(&b)) != MP_OKAY) { return err; } for (;;) { /* skip to the next non-trivially divisible candidate */ step = 0; do { /* y == 1 if any residue was zero [e.g. cannot be prime] */ y = 0; /* increase step to next candidate */ step += kstep; /* compute the new residue without using division */ for (x = 1; x < PRIME_SIZE; x++) { /* add the step to each residue */ res_tab[x] += kstep; /* subtract the modulus [instead of using division] */ if (res_tab[x] >= ltm_prime_tab[x]) { res_tab[x] -= ltm_prime_tab[x]; } /* set flag if zero */ if (res_tab[x] == 0) { y = 1; } } } while (y == 1 && step < ((((mp_digit)1)<= ((((mp_digit)1)<sign == MP_NEG || mp_iszero(b) == 1) { return MP_VAL; } #ifdef BN_FAST_MP_INVMOD_C /* if the modulus is odd we can use a faster routine instead */ if (mp_isodd (b) == 1) { return fast_mp_invmod (a, b, c); } #endif #ifdef BN_MP_INVMOD_SLOW_C return mp_invmod_slow(a, b, c); #endif return MP_VAL; } #endif #ifdef BN_MP_DIV_2_C /* b = a/2 */ int mp_div_2(mp_int * a, mp_int * b) { int x, res, oldused; /* copy */ if (b->alloc < a->used) { if ((res = mp_grow (b, a->used)) != MP_OKAY) { return res; } } oldused = b->used; b->used = a->used; { register mp_digit r, rr, *tmpa, *tmpb; /* source alias */ tmpa = a->dp + b->used - 1; /* dest alias */ tmpb = b->dp + b->used - 1; /* carry */ r = 0; for (x = b->used - 1; x >= 0; x--) { /* get the carry for the next iteration */ rr = *tmpa & 1; /* shift the current digit, add in carry and store */ *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1)); /* forward carry to next iteration */ r = rr; } /* zero excess digits */ tmpb = b->dp + b->used; for (x = b->used; x < oldused; x++) { *tmpb++ = 0; } } b->sign = a->sign; mp_clamp (b); return MP_OKAY; } #endif #ifdef BN_MP_INIT_MULTI_C #include int mp_init_multi(mp_int *mp, ...) { mp_err res = MP_OKAY; /* Assume ok until proven otherwise */ int n = 0; /* Number of ok inits */ mp_int* cur_arg = mp; va_list args; va_start(args, mp); /* init args to next argument from caller */ while (cur_arg != NULL) { if (mp_init(cur_arg) != MP_OKAY) { /* Oops - error! Back-track and mp_clear what we already succeeded in init-ing, then return error. */ va_list clean_args; /* end the current list */ va_end(args); /* now start cleaning up */ cur_arg = mp; va_start(clean_args, mp); while (n--) { mp_clear(cur_arg); cur_arg = va_arg(clean_args, mp_int*); } va_end(clean_args); res = MP_MEM; break; } n++; cur_arg = va_arg(args, mp_int*); } va_end(args); return res; /* Assumed ok, if error flagged above. */ } #endif #ifdef BN_MP_READ_UNSIGNED_BIN_C /* reads a unsigned char array, assumes the msb is stored first [big endian] */ int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c) { int res; /* make sure there are at least two digits */ if (a->alloc < 2) { if ((res = mp_grow(a, 2)) != MP_OKAY) { return res; } } /* zero the int */ mp_zero (a); /* read the bytes in */ while (c-- > 0) { if ((res = mp_mul_2d (a, 8, a)) != MP_OKAY) { return res; } #ifndef MP_8BIT a->dp[0] |= *b++; a->used += 1; #else a->dp[0] = (*b & MP_MASK); a->dp[1] |= ((*b++ >> 7U) & 1); a->used += 2; #endif } mp_clamp (a); return MP_OKAY; } #endif #ifdef BN_MP_KARATSUBA_MUL_C /* c = |a| * |b| using Karatsuba Multiplication using * three half size multiplications * * Let B represent the radix [e.g. 2**DIGIT_BIT] and * let n represent half of the number of digits in * the min(a,b) * * a = a1 * B**n + a0 * b = b1 * B**n + b0 * * Then, a * b => a1b1 * B**2n + ((a1 + a0)(b1 + b0) - (a0b0 + a1b1)) * B + a0b0 * * Note that a1b1 and a0b0 are used twice and only need to be * computed once. So in total three half size (half # of * digit) multiplications are performed, a0b0, a1b1 and * (a1+b1)(a0+b0) * * Note that a multiplication of half the digits requires * 1/4th the number of single precision multiplications so in * total after one call 25% of the single precision multiplications * are saved. Note also that the call to mp_mul can end up back * in this function if the a0, a1, b0, or b1 are above the threshold. * This is known as divide-and-conquer and leads to the famous * O(N**lg(3)) or O(N**1.584) work which is asymptopically lower than * the standard O(N**2) that the baseline/comba methods use. * Generally though the overhead of this method doesn't pay off * until a certain size (N ~ 80) is reached. */ int mp_karatsuba_mul (mp_int * a, mp_int * b, mp_int * c) { mp_int x0, x1, y0, y1, t1, x0y0, x1y1; int B, err; /* default the return code to an error */ err = MP_MEM; /* min # of digits */ B = MIN (a->used, b->used); /* now divide in two */ B = B >> 1; /* init copy all the temps */ if (mp_init_size (&x0, B) != MP_OKAY) goto ERR; if (mp_init_size (&x1, a->used - B) != MP_OKAY) goto X0; if (mp_init_size (&y0, B) != MP_OKAY) goto X1; if (mp_init_size (&y1, b->used - B) != MP_OKAY) goto Y0; /* init temps */ if (mp_init_size (&t1, B * 2) != MP_OKAY) goto Y1; if (mp_init_size (&x0y0, B * 2) != MP_OKAY) goto T1; if (mp_init_size (&x1y1, B * 2) != MP_OKAY) goto X0Y0; /* now shift the digits */ x0.used = y0.used = B; x1.used = a->used - B; y1.used = b->used - B; { register int x; register mp_digit *tmpa, *tmpb, *tmpx, *tmpy; /* we copy the digits directly instead of using higher level functions * since we also need to shift the digits */ tmpa = a->dp; tmpb = b->dp; tmpx = x0.dp; tmpy = y0.dp; for (x = 0; x < B; x++) { *tmpx++ = *tmpa++; *tmpy++ = *tmpb++; } tmpx = x1.dp; for (x = B; x < a->used; x++) { *tmpx++ = *tmpa++; } tmpy = y1.dp; for (x = B; x < b->used; x++) { *tmpy++ = *tmpb++; } } /* only need to clamp the lower words since by definition the * upper words x1/y1 must have a known number of digits */ mp_clamp (&x0); mp_clamp (&y0); /* now calc the products x0y0 and x1y1 */ /* after this x0 is no longer required, free temp [x0==t2]! */ if (mp_mul (&x0, &y0, &x0y0) != MP_OKAY) goto X1Y1; /* x0y0 = x0*y0 */ if (mp_mul (&x1, &y1, &x1y1) != MP_OKAY) goto X1Y1; /* x1y1 = x1*y1 */ /* now calc x1+x0 and y1+y0 */ if (s_mp_add (&x1, &x0, &t1) != MP_OKAY) goto X1Y1; /* t1 = x1 - x0 */ if (s_mp_add (&y1, &y0, &x0) != MP_OKAY) goto X1Y1; /* t2 = y1 - y0 */ if (mp_mul (&t1, &x0, &t1) != MP_OKAY) goto X1Y1; /* t1 = (x1 + x0) * (y1 + y0) */ /* add x0y0 */ if (mp_add (&x0y0, &x1y1, &x0) != MP_OKAY) goto X1Y1; /* t2 = x0y0 + x1y1 */ if (s_mp_sub (&t1, &x0, &t1) != MP_OKAY) goto X1Y1; /* t1 = (x1+x0)*(y1+y0) - (x1y1 + x0y0) */ /* shift by B */ if (mp_lshd (&t1, B) != MP_OKAY) goto X1Y1; /* t1 = (x0y0 + x1y1 - (x1-x0)*(y1-y0))<alloc < a->used + 1) { if ((res = mp_grow (b, a->used + 1)) != MP_OKAY) { return res; } } oldused = b->used; b->used = a->used; { register mp_digit r, rr, *tmpa, *tmpb; /* alias for source */ tmpa = a->dp; /* alias for dest */ tmpb = b->dp; /* carry */ r = 0; for (x = 0; x < a->used; x++) { /* get what will be the *next* carry bit from the * MSB of the current digit */ rr = *tmpa >> ((mp_digit)(DIGIT_BIT - 1)); /* now shift up this digit, add in the carry [from the previous] */ *tmpb++ = ((*tmpa++ << ((mp_digit)1)) | r) & MP_MASK; /* copy the carry that would be from the source * digit into the next iteration */ r = rr; } /* new leading digit? */ if (r != 0) { /* add a MSB which is always 1 at this point */ *tmpb = 1; ++(b->used); } /* now zero any excess digits on the destination * that we didn't write to */ tmpb = b->dp + b->used; for (x = b->used; x < oldused; x++) { *tmpb++ = 0; } } b->sign = a->sign; return MP_OKAY; } #endif #ifdef BN_MP_AND_C /* AND two ints together */ int mp_and (mp_int * a, mp_int * b, mp_int * c) { int res, ix, px; mp_int t, *x; if (a->used > b->used) { if ((res = mp_init_copy (&t, a)) != MP_OKAY) { return res; } px = b->used; x = b; } else { if ((res = mp_init_copy (&t, b)) != MP_OKAY) { return res; } px = a->used; x = a; } for (ix = 0; ix < px; ix++) { t.dp[ix] &= x->dp[ix]; } /* zero digits above the last from the smallest mp_int */ for (; ix < t.used; ix++) { t.dp[ix] = 0; } mp_clamp (&t); mp_exch (c, &t); mp_clear (&t); return MP_OKAY; } #endif #ifdef BN_REVERSE_C /* reverse an array, used for radix code */ void bn_reverse (unsigned char *s, int len) { int ix, iy; unsigned char t; ix = 0; iy = len - 1; while (ix < iy) { t = s[ix]; s[ix] = s[iy]; s[iy] = t; ++ix; --iy; } } #endif #ifdef BN_MP_PRIME_RABIN_MILLER_TRIALS_C static const struct { int k, t; } sizes[] = { { 128, 28 }, { 256, 16 }, { 384, 10 }, { 512, 7 }, { 640, 6 }, { 768, 5 }, { 896, 4 }, { 1024, 4 } }; /* returns # of RM trials required for a given bit size */ int mp_prime_rabin_miller_trials(int size) { int x; for (x = 0; x < (int)(sizeof(sizes)/(sizeof(sizes[0]))); x++) { if (sizes[x].k == size) { return sizes[x].t; } else if (sizes[x].k > size) { return (x == 0) ? sizes[0].t : sizes[x - 1].t; } } return sizes[x-1].t + 1; } #endif #ifdef BN_MP_INIT_COPY_C /* creates "a" then copies b into it */ int mp_init_copy (mp_int * a, mp_int * b) { int res; if ((res = mp_init (a)) != MP_OKAY) { return res; } return mp_copy (b, a); } #endif #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C /* computes xR**-1 == x (mod N) via Montgomery Reduction * * This is an optimized implementation of montgomery_reduce * which uses the comba method to quickly calculate the columns of the * reduction. * * Based on Algorithm 14.32 on pp.601 of HAC. */ int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho) { int ix, res, olduse; mp_word W[MP_WARRAY] = {}; /* get old used count */ olduse = x->used; /* grow a as required */ if (x->alloc < n->used + 1) { if ((res = mp_grow (x, n->used + 1)) != MP_OKAY) { return res; } } /* first we have to get the digits of the input into * an array of double precision words W[...] */ { register mp_word *_W; register mp_digit *tmpx; /* alias for the W[] array */ _W = W; /* alias for the digits of x*/ tmpx = x->dp; /* copy the digits of a into W[0..a->used-1] */ for (ix = 0; ix < x->used; ix++) { *_W++ = *tmpx++; } /* zero the high words of W[a->used..m->used*2] */ for (; ix < n->used * 2 + 1; ix++) { *_W++ = 0; } } /* now we proceed to zero successive digits * from the least significant upwards */ for (ix = 0; ix < n->used; ix++) { /* mu = ai * m' mod b * * We avoid a double precision multiplication (which isn't required) * by casting the value down to a mp_digit. Note this requires * that W[ix-1] have the carry cleared (see after the inner loop) */ register mp_digit mu; mu = (mp_digit) (((W[ix] & MP_MASK) * rho) & MP_MASK); /* a = a + mu * m * b**i * * This is computed in place and on the fly. The multiplication * by b**i is handled by offseting which columns the results * are added to. * * Note the comba method normally doesn't handle carries in the * inner loop In this case we fix the carry from the previous * column since the Montgomery reduction requires digits of the * result (so far) [see above] to work. This is * handled by fixing up one carry after the inner loop. The * carry fixups are done in order so after these loops the * first m->used words of W[] have the carries fixed */ { register int iy; register mp_digit *tmpn; register mp_word *_W; /* alias for the digits of the modulus */ tmpn = n->dp; /* Alias for the columns set by an offset of ix */ _W = W + ix; /* inner loop */ for (iy = 0; iy < n->used; iy++) { *_W++ += ((mp_word)mu) * ((mp_word)*tmpn++); } } /* now fix carry for next digit, W[ix+1] */ W[ix + 1] += W[ix] >> ((mp_word) DIGIT_BIT); } /* now we have to propagate the carries and * shift the words downward [all those least * significant digits we zeroed]. */ { register mp_digit *tmpx; register mp_word *_W, *_W1; /* nox fix rest of carries */ /* alias for current word */ _W1 = W + ix; /* alias for next word, where the carry goes */ _W = W + ++ix; for (; ix <= n->used * 2 + 1; ix++) { *_W++ += *_W1++ >> ((mp_word) DIGIT_BIT); } /* copy out, A = A/b**n * * The result is A/b**n but instead of converting from an * array of mp_word to mp_digit than calling mp_rshd * we just copy them in the right order */ /* alias for destination word */ tmpx = x->dp; /* alias for shifted double precision result */ _W = W + n->used; for (ix = 0; ix < n->used + 1; ix++) { *tmpx++ = (mp_digit)(*_W++ & ((mp_word) MP_MASK)); } /* zero oldused digits, if the input a was larger than * m->used+1 we'll have to clear the digits */ for (; ix < olduse; ix++) { *tmpx++ = 0; } } /* set the max used and clamp */ x->used = n->used + 1; mp_clamp (x); /* if A >= m then A = A - m */ if (mp_cmp_mag (x, n) != MP_LT) { return s_mp_sub (x, n, x); } return MP_OKAY; } #endif #ifdef BN_MP_LSHD_C /* shift left a certain amount of digits */ int mp_lshd (mp_int * a, int b) { int x, res; /* if its less than zero return */ if (b <= 0) { return MP_OKAY; } /* grow to fit the new digits */ if (a->alloc < a->used + b) { if ((res = mp_grow (a, a->used + b)) != MP_OKAY) { return res; } } { register mp_digit *top, *bottom; /* increment the used by the shift amount then copy upwards */ a->used += b; /* top */ top = a->dp + a->used - 1; /* base */ bottom = a->dp + a->used - 1 - b; /* much like mp_rshd this is implemented using a sliding window * except the window goes the otherway around. Copying from * the bottom to the top. see bn_mp_rshd.c for more info. */ for (x = a->used - 1; x >= b; x--) { *top-- = *bottom--; } /* zero the lower digits */ top = a->dp; for (x = 0; x < b; x++) { *top++ = 0; } } return MP_OKAY; } #endif #ifdef BN_MP_CMP_C /* compare two ints (signed)*/ int mp_cmp (mp_int * a, mp_int * b) { /* compare based on sign */ if (a->sign != b->sign) { if (a->sign == MP_NEG) { return MP_LT; } else { return MP_GT; } } /* compare digits */ if (a->sign == MP_NEG) { /* if negative compare opposite direction */ return mp_cmp_mag(b, a); } else { return mp_cmp_mag(a, b); } } #endif #ifdef BN_MP_COUNT_BITS_C /* returns the number of bits in an int */ int mp_count_bits (mp_int * a) { int r; mp_digit q; /* shortcut */ if (a->used == 0) { return 0; } /* get number of digits and add that */ r = (a->used - 1) * DIGIT_BIT; /* take the last digit and count the bits in it */ q = a->dp[a->used - 1]; while (q > ((mp_digit) 0)) { ++r; q >>= ((mp_digit) 1); } return r; } #endif #ifdef BN_MP_OR_C /* OR two ints together */ int mp_or (mp_int * a, mp_int * b, mp_int * c) { int res, ix, px; mp_int t, *x; if (a->used > b->used) { if ((res = mp_init_copy (&t, a)) != MP_OKAY) { return res; } px = b->used; x = b; } else { if ((res = mp_init_copy (&t, b)) != MP_OKAY) { return res; } px = a->used; x = a; } for (ix = 0; ix < px; ix++) { t.dp[ix] |= x->dp[ix]; } mp_clamp (&t); mp_exch (c, &t); mp_clear (&t); return MP_OKAY; } #endif #ifdef BN_MP_EXTEUCLID_C /* Extended euclidean algorithm of (a, b) produces a*u1 + b*u2 = u3 */ int mp_exteuclid(mp_int *a, mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3) { mp_int u1,u2,u3,v1,v2,v3,t1,t2,t3,q,tmp; int err; if ((err = mp_init_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL)) != MP_OKAY) { return err; } /* initialize, (u1,u2,u3) = (1,0,a) */ mp_set(&u1, 1); if ((err = mp_copy(a, &u3)) != MP_OKAY) { goto _ERR; } /* initialize, (v1,v2,v3) = (0,1,b) */ mp_set(&v2, 1); if ((err = mp_copy(b, &v3)) != MP_OKAY) { goto _ERR; } /* loop while v3 != 0 */ while (mp_iszero(&v3) == MP_NO) { /* q = u3/v3 */ if ((err = mp_div(&u3, &v3, &q, NULL)) != MP_OKAY) { goto _ERR; } /* (t1,t2,t3) = (u1,u2,u3) - (v1,v2,v3)q */ if ((err = mp_mul(&v1, &q, &tmp)) != MP_OKAY) { goto _ERR; } if ((err = mp_sub(&u1, &tmp, &t1)) != MP_OKAY) { goto _ERR; } if ((err = mp_mul(&v2, &q, &tmp)) != MP_OKAY) { goto _ERR; } if ((err = mp_sub(&u2, &tmp, &t2)) != MP_OKAY) { goto _ERR; } if ((err = mp_mul(&v3, &q, &tmp)) != MP_OKAY) { goto _ERR; } if ((err = mp_sub(&u3, &tmp, &t3)) != MP_OKAY) { goto _ERR; } /* (u1,u2,u3) = (v1,v2,v3) */ if ((err = mp_copy(&v1, &u1)) != MP_OKAY) { goto _ERR; } if ((err = mp_copy(&v2, &u2)) != MP_OKAY) { goto _ERR; } if ((err = mp_copy(&v3, &u3)) != MP_OKAY) { goto _ERR; } /* (v1,v2,v3) = (t1,t2,t3) */ if ((err = mp_copy(&t1, &v1)) != MP_OKAY) { goto _ERR; } if ((err = mp_copy(&t2, &v2)) != MP_OKAY) { goto _ERR; } if ((err = mp_copy(&t3, &v3)) != MP_OKAY) { goto _ERR; } } /* make sure U3 >= 0 */ if (u3.sign == MP_NEG) { mp_neg(&u1, &u1); mp_neg(&u2, &u2); mp_neg(&u3, &u3); } /* copy result out */ if (U1 != NULL) { mp_exch(U1, &u1); } if (U2 != NULL) { mp_exch(U2, &u2); } if (U3 != NULL) { mp_exch(U3, &u3); } err = MP_OKAY; _ERR: mp_clear_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL); return err; } #endif #ifdef BN_MP_PRIME_RANDOM_EX_C /* makes a truly random prime of a given size (bits), * * Flags are as follows: * * LTM_PRIME_BBS - make prime congruent to 3 mod 4 * LTM_PRIME_SAFE - make sure (p-1)/2 is prime as well (implies LTM_PRIME_BBS) * LTM_PRIME_2MSB_OFF - make the 2nd highest bit zero * LTM_PRIME_2MSB_ON - make the 2nd highest bit one * * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself * so it can be NULL * */ /* This is possibly the mother of all prime generation functions, muahahahahaha! */ int mp_prime_random_ex(mp_int *a, int t, int size, int flags, ltm_prime_callback cb, void *dat) { unsigned char *tmp, maskAND, maskOR_msb, maskOR_lsb; int res, err, bsize, maskOR_msb_offset; /* sanity check the input */ if (size <= 1 || t <= 0) { return MP_VAL; } /* LTM_PRIME_SAFE implies LTM_PRIME_BBS */ if (flags & LTM_PRIME_SAFE) { flags |= LTM_PRIME_BBS; } /* calc the byte size */ bsize = (size>>3) + ((size&7)?1:0); /* we need a buffer of bsize bytes */ tmp = OPT_CAST(unsigned char) XMALLOC(bsize); if (tmp == NULL) { return MP_MEM; } /* calc the maskAND value for the MSbyte*/ maskAND = ((size&7) == 0) ? 0xFF : (0xFF >> (8 - (size & 7))); /* calc the maskOR_msb */ maskOR_msb = 0; maskOR_msb_offset = ((size & 7) == 1) ? 1 : 0; if (flags & LTM_PRIME_2MSB_ON) { maskOR_msb |= 0x80 >> ((9 - size) & 7); } /* get the maskOR_lsb */ maskOR_lsb = 1; if (flags & LTM_PRIME_BBS) { maskOR_lsb |= 3; } do { /* read the bytes */ if (cb(tmp, bsize, dat) != bsize) { err = MP_VAL; goto error; } /* work over the MSbyte */ tmp[0] &= maskAND; tmp[0] |= 1 << ((size - 1) & 7); /* mix in the maskORs */ tmp[maskOR_msb_offset] |= maskOR_msb; tmp[bsize-1] |= maskOR_lsb; /* read it in */ if ((err = mp_read_unsigned_bin(a, tmp, bsize)) != MP_OKAY) { goto error; } /* is it prime? */ if ((err = mp_prime_is_prime(a, t, &res)) != MP_OKAY) { goto error; } if (res == MP_NO) { continue; } if (flags & LTM_PRIME_SAFE) { /* see if (a-1)/2 is prime */ if ((err = mp_sub_d(a, 1, a)) != MP_OKAY) { goto error; } if ((err = mp_div_2(a, a)) != MP_OKAY) { goto error; } /* is it prime? */ if ((err = mp_prime_is_prime(a, t, &res)) != MP_OKAY) { goto error; } } } while (res == MP_NO); if (flags & LTM_PRIME_SAFE) { /* restore a to the original value */ if ((err = mp_mul_2(a, a)) != MP_OKAY) { goto error; } if ((err = mp_add_d(a, 1, a)) != MP_OKAY) { goto error; } } err = MP_OKAY; error: XFREE(tmp); return err; } #endif #ifdef BN_MP_JACOBI_C /* computes the jacobi c = (a | n) (or Legendre if n is prime) * HAC pp. 73 Algorithm 2.149 */ int mp_jacobi (mp_int * a, mp_int * p, int *c) { mp_int a1, p1; int k, s, r, res; mp_digit residue; /* if p <= 0 return MP_VAL */ if (mp_cmp_d(p, 0) != MP_GT) { return MP_VAL; } /* step 1. if a == 0, return 0 */ if (mp_iszero (a) == 1) { *c = 0; return MP_OKAY; } /* step 2. if a == 1, return 1 */ if (mp_cmp_d (a, 1) == MP_EQ) { *c = 1; return MP_OKAY; } /* default */ s = 0; /* step 3. write a = a1 * 2**k */ if ((res = mp_init_copy (&a1, a)) != MP_OKAY) { return res; } if ((res = mp_init (&p1)) != MP_OKAY) { goto LBL_A1; } /* divide out larger power of two */ k = mp_cnt_lsb(&a1); if ((res = mp_div_2d(&a1, k, &a1, NULL)) != MP_OKAY) { goto LBL_P1; } /* step 4. if e is even set s=1 */ if ((k & 1) == 0) { s = 1; } else { /* else set s=1 if p = 1/7 (mod 8) or s=-1 if p = 3/5 (mod 8) */ residue = p->dp[0] & 7; if (residue == 1 || residue == 7) { s = 1; } else if (residue == 3 || residue == 5) { s = -1; } } /* step 5. if p == 3 (mod 4) *and* a1 == 3 (mod 4) then s = -s */ if ( ((p->dp[0] & 3) == 3) && ((a1.dp[0] & 3) == 3)) { s = -s; } /* if a1 == 1 we're done */ if (mp_cmp_d (&a1, 1) == MP_EQ) { *c = s; } else { /* n1 = n mod a1 */ if ((res = mp_mod (p, &a1, &p1)) != MP_OKAY) { goto LBL_P1; } if ((res = mp_jacobi (&p1, &a1, &r)) != MP_OKAY) { goto LBL_P1; } *c = s * r; } /* done */ res = MP_OKAY; LBL_P1:mp_clear (&p1); LBL_A1:mp_clear (&a1); return res; } #endif #ifdef BN_MP_RADIX_SIZE_C /* returns size of ASCII reprensentation */ int mp_radix_size (mp_int * a, int radix, int *size) { int res, digs; mp_int t; mp_digit d; *size = 0; /* special case for binary */ if (radix == 2) { *size = mp_count_bits (a) + (a->sign == MP_NEG ? 1 : 0) + 1; return MP_OKAY; } /* make sure the radix is in range */ if (radix < 2 || radix > 64) { return MP_VAL; } if (mp_iszero(a) == MP_YES) { *size = 2; return MP_OKAY; } /* digs is the digit count */ digs = 0; /* if it's negative add one for the sign */ if (a->sign == MP_NEG) { ++digs; } /* init a copy of the input */ if ((res = mp_init_copy (&t, a)) != MP_OKAY) { return res; } /* force temp to positive */ t.sign = MP_ZPOS; /* fetch out all of the digits */ while (mp_iszero (&t) == MP_NO) { if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) { mp_clear (&t); return res; } ++digs; } mp_clear (&t); /* return digs + 1, the 1 is for the NULL byte that would be required. */ *size = digs + 1; return MP_OKAY; } #endif #ifdef BN_MP_RSHD_C /* shift right a certain amount of digits */ void mp_rshd (mp_int * a, int b) { int x; /* if b <= 0 then ignore it */ if (b <= 0) { return; } /* if b > used then simply zero it and return */ if (a->used <= b) { mp_zero (a); return; } { register mp_digit *bottom, *top; /* shift the digits down */ /* bottom */ bottom = a->dp; /* top [offset into digits] */ top = a->dp + b; /* this is implemented as a sliding window where * the window is b-digits long and digits from * the top of the window are copied to the bottom * * e.g. b-2 | b-1 | b0 | b1 | b2 | ... | bb | ----> /\ | ----> \-------------------/ ----> */ for (x = 0; x < (a->used - b); x++) { *bottom++ = *top++; } /* zero the top digits */ for (; x < a->used; x++) { *bottom++ = 0; } } /* remove excess digits */ a->used -= b; } #endif #ifdef BN_MP_MUL_D_C /* multiply by a digit */ int mp_mul_d (mp_int * a, mp_digit b, mp_int * c) { mp_digit u, *tmpa, *tmpc; mp_word r; int ix, res, olduse; /* make sure c is big enough to hold a*b */ if (c->alloc < a->used + 1) { if ((res = mp_grow (c, a->used + 1)) != MP_OKAY) { return res; } } /* get the original destinations used count */ olduse = c->used; /* set the sign */ c->sign = a->sign; /* alias for a->dp [source] */ tmpa = a->dp; /* alias for c->dp [dest] */ tmpc = c->dp; /* zero carry */ u = 0; /* compute columns */ for (ix = 0; ix < a->used; ix++) { /* compute product and carry sum for this term */ r = ((mp_word) u) + ((mp_word)*tmpa++) * ((mp_word)b); /* mask off higher bits to get a single digit */ *tmpc++ = (mp_digit) (r & ((mp_word) MP_MASK)); /* send carry into next iteration */ u = (mp_digit) (r >> ((mp_word) DIGIT_BIT)); } /* store final carry [if any] and increment ix offset */ *tmpc++ = u; ++ix; /* now zero digits above the top */ while (ix++ < olduse) { *tmpc++ = 0; } /* set used count */ c->used = a->used + 1; mp_clamp(c); return MP_OKAY; } #endif #ifdef BN_MP_MONTGOMERY_REDUCE_C /* computes xR**-1 == x (mod N) via Montgomery Reduction */ int mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho) { int ix, res, digs; mp_digit mu; /* can the fast reduction [comba] method be used? * * Note that unlike in mul you're safely allowed *less* * than the available columns [255 per default] since carries * are fixed up in the inner loop. */ digs = n->used * 2 + 1; if ((digs < MP_WARRAY) && n->used < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) { return fast_mp_montgomery_reduce (x, n, rho); } /* grow the input as required */ if (x->alloc < digs) { if ((res = mp_grow (x, digs)) != MP_OKAY) { return res; } } x->used = digs; for (ix = 0; ix < n->used; ix++) { /* mu = ai * rho mod b * * The value of rho must be precalculated via * montgomery_setup() such that * it equals -1/n0 mod b this allows the * following inner loop to reduce the * input one digit at a time */ mu = (mp_digit) (((mp_word)x->dp[ix]) * ((mp_word)rho) & MP_MASK); /* a = a + mu * m * b**i */ { register int iy; register mp_digit *tmpn, *tmpx, u; register mp_word r; /* alias for digits of the modulus */ tmpn = n->dp; /* alias for the digits of x [the input] */ tmpx = x->dp + ix; /* set the carry to zero */ u = 0; /* Multiply and add in place */ for (iy = 0; iy < n->used; iy++) { /* compute product and sum */ r = ((mp_word)mu) * ((mp_word)*tmpn++) + ((mp_word) u) + ((mp_word) * tmpx); /* get carry */ u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); /* fix digit */ *tmpx++ = (mp_digit)(r & ((mp_word) MP_MASK)); } /* At this point the ix'th digit of x should be zero */ /* propagate carries upwards as required*/ while (u) { *tmpx += u; u = *tmpx >> DIGIT_BIT; *tmpx++ &= MP_MASK; } } } /* at this point the n.used'th least * significant digits of x are all zero * which means we can shift x to the * right by n.used digits and the * residue is unchanged. */ /* x = x/b**n.used */ mp_clamp(x); mp_rshd (x, n->used); /* if x >= n then x = x - n */ if (mp_cmp_mag (x, n) != MP_LT) { return s_mp_sub (x, n, x); } return MP_OKAY; } #endif #ifdef BN_S_MP_EXPTMOD_C #ifdef MP_LOW_MEM #define TAB_SIZE 32 #else #define TAB_SIZE 256 #endif int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode) { mp_int M[TAB_SIZE], res, mu; mp_digit buf; int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize; int (*redux)(mp_int*,mp_int*,mp_int*); /* find window size */ x = mp_count_bits (X); if (x <= 7) { winsize = 2; } else if (x <= 36) { winsize = 3; } else if (x <= 140) { winsize = 4; } else if (x <= 450) { winsize = 5; } else if (x <= 1303) { winsize = 6; } else if (x <= 3529) { winsize = 7; } else { winsize = 8; } #ifdef MP_LOW_MEM if (winsize > 5) { winsize = 5; } #endif /* init M array */ /* init first cell */ if ((err = mp_init(&M[1])) != MP_OKAY) { return err; } /* now init the second half of the array */ for (x = 1<<(winsize-1); x < (1 << winsize); x++) { if ((err = mp_init(&M[x])) != MP_OKAY) { for (y = 1<<(winsize-1); y < x; y++) { mp_clear (&M[y]); } mp_clear(&M[1]); return err; } } /* create mu, used for Barrett reduction */ if ((err = mp_init (&mu)) != MP_OKAY) { goto LBL_M; } if (redmode == 0) { if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) { goto LBL_MU; } redux = mp_reduce; } else { if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) { goto LBL_MU; } redux = mp_reduce_2k_l; } /* create M table * * The M table contains powers of the base, * e.g. M[x] = G**x mod P * * The first half of the table is not * computed though accept for M[0] and M[1] */ if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) { goto LBL_MU; } /* compute the value at M[1<<(winsize-1)] by squaring * M[1] (winsize-1) times */ if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) { goto LBL_MU; } for (x = 0; x < (winsize - 1); x++) { /* square it */ if ((err = mp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)])) != MP_OKAY) { goto LBL_MU; } /* reduce modulo P */ if ((err = redux (&M[1 << (winsize - 1)], P, &mu)) != MP_OKAY) { goto LBL_MU; } } /* create upper table, that is M[x] = M[x-1] * M[1] (mod P) * for x = (2**(winsize - 1) + 1) to (2**winsize - 1) */ for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) { if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) { goto LBL_MU; } if ((err = redux (&M[x], P, &mu)) != MP_OKAY) { goto LBL_MU; } } /* setup result */ if ((err = mp_init (&res)) != MP_OKAY) { goto LBL_MU; } mp_set (&res, 1); /* set initial mode and bit cnt */ mode = 0; bitcnt = 1; buf = 0; digidx = X->used - 1; bitcpy = 0; bitbuf = 0; for (;;) { /* grab next digit as required */ if (--bitcnt == 0) { /* if digidx == -1 we are out of digits */ if (digidx == -1) { break; } /* read next digit and reset the bitcnt */ buf = X->dp[digidx--]; bitcnt = (int) DIGIT_BIT; } /* grab the next msb from the exponent */ y = (buf >> (mp_digit)(DIGIT_BIT - 1)) & 1; buf <<= (mp_digit)1; /* if the bit is zero and mode == 0 then we ignore it * These represent the leading zero bits before the first 1 bit * in the exponent. Technically this opt is not required but it * does lower the # of trivial squaring/reductions used */ if (mode == 0 && y == 0) { continue; } /* if the bit is zero and mode == 1 then we square */ if (mode == 1 && y == 0) { if ((err = mp_sqr (&res, &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, &mu)) != MP_OKAY) { goto LBL_RES; } continue; } /* else we add it to the window */ bitbuf |= (y << (winsize - ++bitcpy)); mode = 2; if (bitcpy == winsize) { /* ok window is filled so square as required and multiply */ /* square first */ for (x = 0; x < winsize; x++) { if ((err = mp_sqr (&res, &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, &mu)) != MP_OKAY) { goto LBL_RES; } } /* then multiply */ if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, &mu)) != MP_OKAY) { goto LBL_RES; } /* empty window and reset */ bitcpy = 0; bitbuf = 0; mode = 1; } } /* if bits remain then square/multiply */ if (mode == 2 && bitcpy > 0) { /* square then multiply if the bit is set */ for (x = 0; x < bitcpy; x++) { if ((err = mp_sqr (&res, &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, &mu)) != MP_OKAY) { goto LBL_RES; } bitbuf <<= 1; if ((bitbuf & (1 << winsize)) != 0) { /* then multiply */ if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, &mu)) != MP_OKAY) { goto LBL_RES; } } } } mp_exch (&res, Y); err = MP_OKAY; LBL_RES:mp_clear (&res); LBL_MU:mp_clear (&mu); LBL_M: mp_clear(&M[1]); for (x = 1<<(winsize-1); x < (1 << winsize); x++) { mp_clear (&M[x]); } return err; } #endif #ifdef BN_MP_SUB_D_C /* single digit subtraction */ int mp_sub_d (mp_int * a, mp_digit b, mp_int * c) { mp_digit *tmpa, *tmpc, mu; int res, ix, oldused; /* grow c as required */ if (c->alloc < a->used + 1) { if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) { return res; } } /* if a is negative just do an unsigned * addition [with fudged signs] */ if (a->sign == MP_NEG) { a->sign = MP_ZPOS; res = mp_add_d(a, b, c); a->sign = c->sign = MP_NEG; /* clamp */ mp_clamp(c); return res; } /* setup regs */ oldused = c->used; tmpa = a->dp; tmpc = c->dp; /* if a <= b simply fix the single digit */ if ((a->used == 1 && a->dp[0] <= b) || a->used == 0) { if (a->used == 1) { *tmpc++ = b - *tmpa; } else { *tmpc++ = b; } ix = 1; /* negative/1digit */ c->sign = MP_NEG; c->used = 1; } else { /* positive/size */ c->sign = MP_ZPOS; c->used = a->used; /* subtract first digit */ *tmpc = *tmpa++ - b; mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1); *tmpc++ &= MP_MASK; /* handle rest of the digits */ for (ix = 1; ix < a->used; ix++) { *tmpc = *tmpa++ - mu; mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1); *tmpc++ &= MP_MASK; } } /* zero excess digits */ while (ix++ < oldused) { *tmpc++ = 0; } mp_clamp(c); return MP_OKAY; } #endif #ifdef BN_MP_DIV_2D_C /* shift right by a certain bit count (store quotient in c, optional remainder in d) */ int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d) { mp_digit D, r, rr; int x, res; mp_int t; /* if the shift count is <= 0 then we do no work */ if (b <= 0) { res = mp_copy (a, c); if (d != NULL) { mp_zero (d); } return res; } if ((res = mp_init (&t)) != MP_OKAY) { return res; } /* get the remainder */ if (d != NULL) { if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) { mp_clear (&t); return res; } } /* copy */ if ((res = mp_copy (a, c)) != MP_OKAY) { mp_clear (&t); return res; } /* shift by as many digits in the bit count */ if (b >= (int)DIGIT_BIT) { mp_rshd (c, b / DIGIT_BIT); } /* shift any bit count < DIGIT_BIT */ D = (mp_digit) (b % DIGIT_BIT); if (D != 0) { register mp_digit *tmpc, mask, shift; /* mask */ mask = (((mp_digit)1) << D) - 1; /* shift for lsb */ shift = DIGIT_BIT - D; /* alias */ tmpc = c->dp + (c->used - 1); /* carry */ r = 0; for (x = c->used - 1; x >= 0; x--) { /* get the lower bits of this word in a temp */ rr = *tmpc & mask; /* shift the current word and mix in the carry bits from the previous word */ *tmpc = (*tmpc >> D) | (r << shift); --tmpc; /* set the carry to the carry bits of the current word found above */ r = rr; } } mp_clamp (c); if (d != NULL) { mp_exch (&t, d); } mp_clear (&t); return MP_OKAY; } #endif #ifdef BN_MP_ADD_D_C /* single digit addition */ int mp_add_d (mp_int * a, mp_digit b, mp_int * c) { int res, ix, oldused; mp_digit *tmpa, *tmpc, mu; /* grow c as required */ if (c->alloc < a->used + 1) { if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) { return res; } } /* if a is negative and |a| >= b, call c = |a| - b */ if (a->sign == MP_NEG && (a->used > 1 || a->dp[0] >= b)) { /* temporarily fix sign of a */ a->sign = MP_ZPOS; /* c = |a| - b */ res = mp_sub_d(a, b, c); /* fix sign */ a->sign = c->sign = MP_NEG; /* clamp */ mp_clamp(c); return res; } /* old number of used digits in c */ oldused = c->used; /* sign always positive */ c->sign = MP_ZPOS; /* source alias */ tmpa = a->dp; /* destination alias */ tmpc = c->dp; /* if a is positive */ if (a->sign == MP_ZPOS) { /* add digit, after this we're propagating * the carry. */ *tmpc = *tmpa++ + b; mu = *tmpc >> DIGIT_BIT; *tmpc++ &= MP_MASK; /* now handle rest of the digits */ for (ix = 1; ix < a->used; ix++) { *tmpc = *tmpa++ + mu; mu = *tmpc >> DIGIT_BIT; *tmpc++ &= MP_MASK; } /* set final carry */ ix++; *tmpc++ = mu; /* setup size */ c->used = a->used + 1; } else { /* a was negative and |a| < b */ c->used = 1; /* the result is a single digit */ if (a->used == 1) { *tmpc++ = b - a->dp[0]; } else { *tmpc++ = b; } /* setup count so the clearing of oldused * can fall through correctly */ ix = 1; } /* now zero to oldused */ while (ix++ < oldused) { *tmpc++ = 0; } mp_clamp(c); return MP_OKAY; } #endif #ifdef BN_MP_SQR_C /* computes b = a*a */ int mp_sqr (mp_int * a, mp_int * b) { int res; #ifdef BN_MP_TOOM_SQR_C /* use Toom-Cook? */ if (a->used >= TOOM_SQR_CUTOFF) { res = mp_toom_sqr(a, b); /* Karatsuba? */ } else #endif #ifdef BN_MP_KARATSUBA_SQR_C if (a->used >= KARATSUBA_SQR_CUTOFF) { res = mp_karatsuba_sqr (a, b); } else #endif { #ifdef BN_FAST_S_MP_SQR_C /* can we use the fast comba multiplier? */ if ((a->used * 2 + 1) < MP_WARRAY && a->used < (1 << (sizeof(mp_word) * CHAR_BIT - 2*DIGIT_BIT - 1))) { res = fast_s_mp_sqr (a, b); } else #endif #ifdef BN_S_MP_SQR_C res = s_mp_sqr (a, b); #else res = MP_VAL; #endif } b->sign = MP_ZPOS; return res; } #endif #ifdef BN_MP_GROW_C /* grow as required */ int mp_grow (mp_int * a, int size) { int i; mp_digit *tmp; /* if the alloc size is smaller alloc more ram */ if (a->alloc < size) { /* ensure there are always at least MP_PREC digits extra on top */ size += (MP_PREC * 2) - (size % MP_PREC); /* reallocate the array a->dp * * We store the return in a temporary variable * in case the operation failed we don't want * to overwrite the dp member of a. */ tmp = OPT_CAST(mp_digit) XREALLOC (a->dp, sizeof (mp_digit) * size); if (tmp == NULL) { /* reallocation failed but "a" is still valid [can be freed] */ return MP_MEM; } /* reallocation succeeded so set a->dp */ a->dp = tmp; /* zero excess digits */ i = a->alloc; a->alloc = size; for (; i < a->alloc; i++) { a->dp[i] = 0; } } return MP_OKAY; } #endif #ifdef BN_MP_MUL_2D_C /* shift left by a certain bit count */ int mp_mul_2d (mp_int * a, int b, mp_int * c) { mp_digit d; int res; /* copy */ if (a != c) { if ((res = mp_copy (a, c)) != MP_OKAY) { return res; } } if (c->alloc < (int)(c->used + b/DIGIT_BIT + 1)) { if ((res = mp_grow (c, c->used + b / DIGIT_BIT + 1)) != MP_OKAY) { return res; } } /* shift by as many digits in the bit count */ if (b >= (int)DIGIT_BIT) { if ((res = mp_lshd (c, b / DIGIT_BIT)) != MP_OKAY) { return res; } } /* shift any bit count < DIGIT_BIT */ d = (mp_digit) (b % DIGIT_BIT); if (d != 0) { register mp_digit *tmpc, shift, mask, r, rr; register int x; /* bitmask for carries */ mask = (((mp_digit)1) << d) - 1; /* shift for msbs */ shift = DIGIT_BIT - d; /* alias */ tmpc = c->dp; /* carry */ r = 0; for (x = 0; x < c->used; x++) { /* get the higher bits of the current word */ rr = (*tmpc >> shift) & mask; /* shift the current word and OR in the carry */ *tmpc = ((*tmpc << d) | r) & MP_MASK; ++tmpc; /* set the carry to the carry bits of the current word */ r = rr; } /* set final carry */ if (r != 0) { c->dp[(c->used)++] = r; } } mp_clamp (c); return MP_OKAY; } #endif #ifdef BN_MP_CMP_D_C /* compare a digit */ int mp_cmp_d(mp_int * a, mp_digit b) { /* compare based on sign */ if (a->sign == MP_NEG) { return MP_LT; } /* compare based on magnitude */ if (a->used > 1) { return MP_GT; } /* compare the only digit of a to b */ if (a->dp[0] > b) { return MP_GT; } else if (a->dp[0] < b) { return MP_LT; } else { return MP_EQ; } } #endif #ifdef BN_MP_CMP_MAG_C /* compare maginitude of two ints (unsigned) */ int mp_cmp_mag (mp_int * a, mp_int * b) { int n; mp_digit *tmpa, *tmpb; /* compare based on # of non-zero digits */ if (a->used > b->used) { return MP_GT; } if (a->used < b->used) { return MP_LT; } /* alias for a */ tmpa = a->dp + (a->used - 1); /* alias for b */ tmpb = b->dp + (a->used - 1); /* compare based on digits */ for (n = 0; n < a->used; ++n, --tmpa, --tmpb) { if (*tmpa > *tmpb) { return MP_GT; } if (*tmpa < *tmpb) { return MP_LT; } } return MP_EQ; } #endif #ifdef BN_MP_CLEAR_C /* clear one (frees) */ void mp_clear (mp_int * a) { int i; /* only do anything if a hasn't been freed previously */ if (a->dp != NULL) { /* first zero the digits */ for (i = 0; i < a->used; i++) { a->dp[i] = 0; } /* free ram */ XFREE(a->dp); /* reset members to make debugging easier */ a->dp = NULL; a->alloc = a->used = 0; a->sign = MP_ZPOS; } } #endif #ifdef BN_MP_INVMOD_SLOW_C /* hac 14.61, pp608 */ int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c) { mp_int x, y, u, v, A, B, C, D; int res; /* b cannot be negative */ if (b->sign == MP_NEG || mp_iszero(b) == 1) { return MP_VAL; } /* init temps */ if ((res = mp_init_multi(&x, &y, &u, &v, &A, &B, &C, &D, NULL)) != MP_OKAY) { return res; } /* x = a, y = b */ if ((res = mp_mod(a, b, &x)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_copy (b, &y)) != MP_OKAY) { goto LBL_ERR; } /* 2. [modified] if x,y are both even then return an error! */ if (mp_iseven (&x) == 1 && mp_iseven (&y) == 1) { res = MP_VAL; goto LBL_ERR; } /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */ if ((res = mp_copy (&x, &u)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_copy (&y, &v)) != MP_OKAY) { goto LBL_ERR; } mp_set (&A, 1); mp_set (&D, 1); top: /* 4. while u is even do */ while (mp_iseven (&u) == 1) { /* 4.1 u = u/2 */ if ((res = mp_div_2 (&u, &u)) != MP_OKAY) { goto LBL_ERR; } /* 4.2 if A or B is odd then */ if (mp_isodd (&A) == 1 || mp_isodd (&B) == 1) { /* A = (A+y)/2, B = (B-x)/2 */ if ((res = mp_add (&A, &y, &A)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) { goto LBL_ERR; } } /* A = A/2, B = B/2 */ if ((res = mp_div_2 (&A, &A)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_div_2 (&B, &B)) != MP_OKAY) { goto LBL_ERR; } } /* 5. while v is even do */ while (mp_iseven (&v) == 1) { /* 5.1 v = v/2 */ if ((res = mp_div_2 (&v, &v)) != MP_OKAY) { goto LBL_ERR; } /* 5.2 if C or D is odd then */ if (mp_isodd (&C) == 1 || mp_isodd (&D) == 1) { /* C = (C+y)/2, D = (D-x)/2 */ if ((res = mp_add (&C, &y, &C)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) { goto LBL_ERR; } } /* C = C/2, D = D/2 */ if ((res = mp_div_2 (&C, &C)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_div_2 (&D, &D)) != MP_OKAY) { goto LBL_ERR; } } /* 6. if u >= v then */ if (mp_cmp (&u, &v) != MP_LT) { /* u = u - v, A = A - C, B = B - D */ if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_sub (&A, &C, &A)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) { goto LBL_ERR; } } else { /* v - v - u, C = C - A, D = D - B */ if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_sub (&C, &A, &C)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) { goto LBL_ERR; } } /* if not zero goto step 4 */ if (mp_iszero (&u) == 0) goto top; /* now a = C, b = D, gcd == g*v */ /* if v != 1 then there is no inverse */ if (mp_cmp_d (&v, 1) != MP_EQ) { res = MP_VAL; goto LBL_ERR; } /* if its too low */ while (mp_cmp_d(&C, 0) == MP_LT) { if ((res = mp_add(&C, b, &C)) != MP_OKAY) { goto LBL_ERR; } } /* too big */ while (mp_cmp_mag(&C, b) != MP_LT) { if ((res = mp_sub(&C, b, &C)) != MP_OKAY) { goto LBL_ERR; } } /* C is now the inverse */ mp_exch (&C, c); res = MP_OKAY; LBL_ERR:mp_clear_multi (&x, &y, &u, &v, &A, &B, &C, &D, NULL); return res; } #endif #ifdef BN_MP_DIV_C #ifdef BN_MP_DIV_SMALL /* slower bit-bang division... also smaller */ int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d) { mp_int ta, tb, tq, q; int res, n, n2; /* is divisor zero ? */ if (mp_iszero (b) == 1) { return MP_VAL; } /* if a < b then q=0, r = a */ if (mp_cmp_mag (a, b) == MP_LT) { if (d != NULL) { res = mp_copy (a, d); } else { res = MP_OKAY; } if (c != NULL) { mp_zero (c); } return res; } /* init our temps */ if ((res = mp_init_multi(&ta, &tb, &tq, &q, NULL) != MP_OKAY)) { return res; } mp_set(&tq, 1); n = mp_count_bits(a) - mp_count_bits(b); if (((res = mp_abs(a, &ta)) != MP_OKAY) || ((res = mp_abs(b, &tb)) != MP_OKAY) || ((res = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) || ((res = mp_mul_2d(&tq, n, &tq)) != MP_OKAY)) { goto LBL_ERR; } while (n-- >= 0) { if (mp_cmp(&tb, &ta) != MP_GT) { if (((res = mp_sub(&ta, &tb, &ta)) != MP_OKAY) || ((res = mp_add(&q, &tq, &q)) != MP_OKAY)) { goto LBL_ERR; } } if (((res = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) || ((res = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY)) { goto LBL_ERR; } } /* now q == quotient and ta == remainder */ n = a->sign; n2 = (a->sign == b->sign ? MP_ZPOS : MP_NEG); if (c != NULL) { mp_exch(c, &q); c->sign = (mp_iszero(c) == MP_YES) ? MP_ZPOS : n2; } if (d != NULL) { mp_exch(d, &ta); d->sign = (mp_iszero(d) == MP_YES) ? MP_ZPOS : n; } LBL_ERR: mp_clear_multi(&ta, &tb, &tq, &q, NULL); return res; } #else /* integer signed division. * c*b + d == a [e.g. a/b, c=quotient, d=remainder] * HAC pp.598 Algorithm 14.20 * * Note that the description in HAC is horribly * incomplete. For example, it doesn't consider * the case where digits are removed from 'x' in * the inner loop. It also doesn't consider the * case that y has fewer than three digits, etc.. * * The overall algorithm is as described as * 14.20 from HAC but fixed to treat these cases. */ int mp_div (mp_int * a, mp_int * b, mp_int * c, mp_int * d) { mp_int q, x, y, t1, t2; int res, n, t, i, norm, neg; /* is divisor zero ? */ if (mp_iszero (b) == 1) { return MP_VAL; } /* if a < b then q=0, r = a */ if (mp_cmp_mag (a, b) == MP_LT) { if (d != NULL) { res = mp_copy (a, d); } else { res = MP_OKAY; } if (c != NULL) { mp_zero (c); } return res; } if ((res = mp_init_size (&q, a->used + 2)) != MP_OKAY) { return res; } q.used = a->used + 2; if ((res = mp_init (&t1)) != MP_OKAY) { goto LBL_Q; } if ((res = mp_init (&t2)) != MP_OKAY) { goto LBL_T1; } if ((res = mp_init_copy (&x, a)) != MP_OKAY) { goto LBL_T2; } if ((res = mp_init_copy (&y, b)) != MP_OKAY) { goto LBL_X; } /* fix the sign */ neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG; x.sign = y.sign = MP_ZPOS; /* normalize both x and y, ensure that y >= b/2, [b == 2**DIGIT_BIT] */ norm = mp_count_bits(&y) % DIGIT_BIT; if (norm < (int)(DIGIT_BIT-1)) { norm = (DIGIT_BIT-1) - norm; if ((res = mp_mul_2d (&x, norm, &x)) != MP_OKAY) { goto LBL_Y; } if ((res = mp_mul_2d (&y, norm, &y)) != MP_OKAY) { goto LBL_Y; } } else { norm = 0; } /* note hac does 0 based, so if used==5 then its 0,1,2,3,4, e.g. use 4 */ n = x.used - 1; t = y.used - 1; /* while (x >= y*b**n-t) do { q[n-t] += 1; x -= y*b**{n-t} } */ if ((res = mp_lshd (&y, n - t)) != MP_OKAY) { /* y = y*b**{n-t} */ goto LBL_Y; } while (mp_cmp (&x, &y) != MP_LT) { ++(q.dp[n - t]); if ((res = mp_sub (&x, &y, &x)) != MP_OKAY) { goto LBL_Y; } } /* reset y by shifting it back down */ mp_rshd (&y, n - t); /* step 3. for i from n down to (t + 1) */ for (i = n; i >= (t + 1); i--) { if (i > x.used) { continue; } /* step 3.1 if xi == yt then set q{i-t-1} to b-1, * otherwise set q{i-t-1} to (xi*b + x{i-1})/yt */ if (x.dp[i] == y.dp[t]) { q.dp[i - t - 1] = ((((mp_digit)1) << DIGIT_BIT) - 1); } else { mp_word tmp; tmp = ((mp_word) x.dp[i]) << ((mp_word) DIGIT_BIT); tmp |= ((mp_word) x.dp[i - 1]); tmp /= ((mp_word) y.dp[t]); if (tmp > (mp_word) MP_MASK) tmp = MP_MASK; q.dp[i - t - 1] = (mp_digit) (tmp & (mp_word) (MP_MASK)); } /* while (q{i-t-1} * (yt * b + y{t-1})) > xi * b**2 + xi-1 * b + xi-2 do q{i-t-1} -= 1; */ q.dp[i - t - 1] = (q.dp[i - t - 1] + 1) & MP_MASK; do { q.dp[i - t - 1] = (q.dp[i - t - 1] - 1) & MP_MASK; /* find left hand */ mp_zero (&t1); t1.dp[0] = (t - 1 < 0) ? 0 : y.dp[t - 1]; t1.dp[1] = y.dp[t]; t1.used = 2; if ((res = mp_mul_d (&t1, q.dp[i - t - 1], &t1)) != MP_OKAY) { goto LBL_Y; } /* find right hand */ t2.dp[0] = (i - 2 < 0) ? 0 : x.dp[i - 2]; t2.dp[1] = (i - 1 < 0) ? 0 : x.dp[i - 1]; t2.dp[2] = x.dp[i]; t2.used = 3; } while (mp_cmp_mag(&t1, &t2) == MP_GT); /* step 3.3 x = x - q{i-t-1} * y * b**{i-t-1} */ if ((res = mp_mul_d (&y, q.dp[i - t - 1], &t1)) != MP_OKAY) { goto LBL_Y; } if ((res = mp_lshd (&t1, i - t - 1)) != MP_OKAY) { goto LBL_Y; } if ((res = mp_sub (&x, &t1, &x)) != MP_OKAY) { goto LBL_Y; } /* if x < 0 then { x = x + y*b**{i-t-1}; q{i-t-1} -= 1; } */ if (x.sign == MP_NEG) { if ((res = mp_copy (&y, &t1)) != MP_OKAY) { goto LBL_Y; } if ((res = mp_lshd (&t1, i - t - 1)) != MP_OKAY) { goto LBL_Y; } if ((res = mp_add (&x, &t1, &x)) != MP_OKAY) { goto LBL_Y; } q.dp[i - t - 1] = (q.dp[i - t - 1] - 1UL) & MP_MASK; } } /* now q is the quotient and x is the remainder * [which we have to normalize] */ /* get sign before writing to c */ x.sign = x.used == 0 ? MP_ZPOS : a->sign; if (c != NULL) { mp_clamp (&q); mp_exch (&q, c); c->sign = neg; } if (d != NULL) { mp_div_2d (&x, norm, &x, NULL); mp_exch (&x, d); } res = MP_OKAY; LBL_Y:mp_clear (&y); LBL_X:mp_clear (&x); LBL_T2:mp_clear (&t2); LBL_T1:mp_clear (&t1); LBL_Q:mp_clear (&q); return res; } #endif #endif #ifdef BN_MP_REDUCE_2K_SETUP_L_C /* determines the setup value */ int mp_reduce_2k_setup_l(mp_int *a, mp_int *d) { int res; mp_int tmp; if ((res = mp_init(&tmp)) != MP_OKAY) { return res; } if ((res = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) { goto ERR; } if ((res = s_mp_sub(&tmp, a, d)) != MP_OKAY) { goto ERR; } ERR: mp_clear(&tmp); return res; } #endif #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C /* * shifts with subtractions when the result is greater than b. * * The method is slightly modified to shift B unconditionally upto just under * the leading bit of b. This saves alot of multiple precision shifting. */ int mp_montgomery_calc_normalization (mp_int * a, mp_int * b) { int x, bits, res; /* how many bits of last digit does b use */ bits = mp_count_bits (b) % DIGIT_BIT; if (b->used > 1) { if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1)) != MP_OKAY) { return res; } } else { mp_set(a, 1); bits = 1; } /* now compute C = A * B mod b */ for (x = bits - 1; x < (int)DIGIT_BIT; x++) { if ((res = mp_mul_2 (a, a)) != MP_OKAY) { return res; } if (mp_cmp_mag (a, b) != MP_LT) { if ((res = s_mp_sub (a, b, a)) != MP_OKAY) { return res; } } } return MP_OKAY; } #endif #ifdef BN_MP_READ_SIGNED_BIN_C /* read signed bin, big endian, first byte is 0==positive or 1==negative */ int mp_read_signed_bin (mp_int * a, const unsigned char *b, int c) { int res; /* read magnitude */ if ((res = mp_read_unsigned_bin (a, b + 1, c - 1)) != MP_OKAY) { return res; } /* first byte is 0 for positive, non-zero for negative */ if (b[0] == 0) { a->sign = MP_ZPOS; } else { a->sign = MP_NEG; } return MP_OKAY; } #endif #ifdef BN_MP_XOR_C /* XOR two ints together */ int mp_xor (mp_int * a, mp_int * b, mp_int * c) { int res, ix, px; mp_int t, *x; if (a->used > b->used) { if ((res = mp_init_copy (&t, a)) != MP_OKAY) { return res; } px = b->used; x = b; } else { if ((res = mp_init_copy (&t, b)) != MP_OKAY) { return res; } px = a->used; x = a; } for (ix = 0; ix < px; ix++) { t.dp[ix] ^= x->dp[ix]; } mp_clamp (&t); mp_exch (c, &t); mp_clear (&t); return MP_OKAY; } #endif #ifdef BN_MP_EXPTMOD_C /* this is a shell function that calls either the normal or Montgomery * exptmod functions. Originally the call to the montgomery code was * embedded in the normal function but that wasted alot of stack space * for nothing (since 99% of the time the Montgomery code would be called) */ int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y) { int dr; /* modulus P must be positive */ if (P->sign == MP_NEG) { return MP_VAL; } /* if exponent X is negative we have to recurse */ if (X->sign == MP_NEG) { #ifdef BN_MP_INVMOD_C mp_int tmpG, tmpX; int err; /* first compute 1/G mod P */ if ((err = mp_init(&tmpG)) != MP_OKAY) { return err; } if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) { mp_clear(&tmpG); return err; } /* now get |X| */ if ((err = mp_init(&tmpX)) != MP_OKAY) { mp_clear(&tmpG); return err; } if ((err = mp_abs(X, &tmpX)) != MP_OKAY) { mp_clear_multi(&tmpG, &tmpX, NULL); return err; } /* and now compute (1/G)**|X| instead of G**X [X < 0] */ err = mp_exptmod(&tmpG, &tmpX, P, Y); mp_clear_multi(&tmpG, &tmpX, NULL); return err; #else /* no invmod */ return MP_VAL; #endif } /* modified diminished radix reduction */ #if defined(BN_MP_REDUCE_IS_2K_L_C) && defined(BN_MP_REDUCE_2K_L_C) && defined(BN_S_MP_EXPTMOD_C) if (mp_reduce_is_2k_l(P) == MP_YES) { return s_mp_exptmod(G, X, P, Y, 1); } #endif #ifdef BN_MP_DR_IS_MODULUS_C /* is it a DR modulus? */ dr = mp_dr_is_modulus(P); #else /* default to no */ dr = 0; #endif #ifdef BN_MP_REDUCE_IS_2K_C /* if not, is it a unrestricted DR modulus? */ if (dr == 0) { dr = mp_reduce_is_2k(P) << 1; } #endif /* if the modulus is odd or dr != 0 use the montgomery method */ #ifdef BN_MP_EXPTMOD_FAST_C if (mp_isodd (P) == 1 || dr != 0) { return mp_exptmod_fast (G, X, P, Y, dr); } else { #endif #ifdef BN_S_MP_EXPTMOD_C /* otherwise use the generic Barrett reduction technique */ return s_mp_exptmod (G, X, P, Y, 0); #else /* no exptmod for evens */ return MP_VAL; #endif #ifdef BN_MP_EXPTMOD_FAST_C } #endif } #endif #ifdef BN_MP_PRIME_IS_PRIME_C /* performs a variable number of rounds of Miller-Rabin * * Probability of error after t rounds is no more than * * Sets result to 1 if probably prime, 0 otherwise */ int mp_prime_is_prime (mp_int * a, int t, int *result) { mp_int b; int ix, err, res; /* default to no */ *result = MP_NO; /* valid value of t? */ if (t <= 0 || t > PRIME_SIZE) { return MP_VAL; } /* is the input equal to one of the primes in the table? */ for (ix = 0; ix < PRIME_SIZE; ix++) { if (mp_cmp_d(a, ltm_prime_tab[ix]) == MP_EQ) { *result = 1; return MP_OKAY; } } /* first perform trial division */ if ((err = mp_prime_is_divisible (a, &res)) != MP_OKAY) { return err; } /* return if it was trivially divisible */ if (res == MP_YES) { return MP_OKAY; } /* now perform the miller-rabin rounds */ if ((err = mp_init (&b)) != MP_OKAY) { return err; } for (ix = 0; ix < t; ix++) { /* set the prime */ mp_set (&b, ltm_prime_tab[ix]); if ((err = mp_prime_miller_rabin (a, &b, &res)) != MP_OKAY) { goto LBL_B; } if (res == MP_NO) { goto LBL_B; } } /* passed the test */ *result = MP_YES; LBL_B:mp_clear (&b); return err; } #endif #ifdef BN_MP_REDUCE_2K_L_C /* reduces a modulo n where n is of the form 2**p - d This differs from reduce_2k since "d" can be larger than a single digit. */ int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d) { mp_int q; int p, res; if ((res = mp_init(&q)) != MP_OKAY) { return res; } p = mp_count_bits(n); top: /* q = a/2**p, a = a mod 2**p */ if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) { goto ERR; } /* q = q * d */ if ((res = mp_mul(&q, d, &q)) != MP_OKAY) { goto ERR; } /* a = a + q */ if ((res = s_mp_add(a, &q, a)) != MP_OKAY) { goto ERR; } if (mp_cmp_mag(a, n) != MP_LT) { s_mp_sub(a, n, a); goto top; } ERR: mp_clear(&q); return res; } #endif #ifdef BN_MP_EXPTMOD_FAST_C /* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85 * * Uses a left-to-right k-ary sliding window to compute the modular exponentiation. * The value of k changes based on the size of the exponent. * * Uses Montgomery or Diminished Radix reduction [whichever appropriate] */ #ifdef MP_LOW_MEM #define TAB_SIZE 32 #else #define TAB_SIZE 256 #endif int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode) { mp_int M[TAB_SIZE], res; mp_digit buf, mp; int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize; /* use a pointer to the reduction algorithm. This allows us to use * one of many reduction algorithms without modding the guts of * the code with if statements everywhere. */ int (*redux)(mp_int*,mp_int*,mp_digit); /* find window size */ x = mp_count_bits (X); if (x <= 7) { winsize = 2; } else if (x <= 36) { winsize = 3; } else if (x <= 140) { winsize = 4; } else if (x <= 450) { winsize = 5; } else if (x <= 1303) { winsize = 6; } else if (x <= 3529) { winsize = 7; } else { winsize = 8; } #ifdef MP_LOW_MEM if (winsize > 5) { winsize = 5; } #endif /* init M array */ /* init first cell */ if ((err = mp_init(&M[1])) != MP_OKAY) { return err; } /* now init the second half of the array */ for (x = 1<<(winsize-1); x < (1 << winsize); x++) { if ((err = mp_init(&M[x])) != MP_OKAY) { for (y = 1<<(winsize-1); y < x; y++) { mp_clear (&M[y]); } mp_clear(&M[1]); return err; } } /* determine and setup reduction code */ if (redmode == 0) { #ifdef BN_MP_MONTGOMERY_SETUP_C /* now setup montgomery */ if ((err = mp_montgomery_setup (P, &mp)) != MP_OKAY) { goto LBL_M; } #else err = MP_VAL; goto LBL_M; #endif /* automatically pick the comba one if available (saves quite a few calls/ifs) */ #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C if (((P->used * 2 + 1) < MP_WARRAY) && P->used < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) { redux = fast_mp_montgomery_reduce; } else #endif { #ifdef BN_MP_MONTGOMERY_REDUCE_C /* use slower baseline Montgomery method */ redux = mp_montgomery_reduce; #else err = MP_VAL; goto LBL_M; #endif } } else if (redmode == 1) { #if defined(BN_MP_DR_SETUP_C) && defined(BN_MP_DR_REDUCE_C) /* setup DR reduction for moduli of the form B**k - b */ mp_dr_setup(P, &mp); redux = mp_dr_reduce; #else err = MP_VAL; goto LBL_M; #endif } else { #if defined(BN_MP_REDUCE_2K_SETUP_C) && defined(BN_MP_REDUCE_2K_C) /* setup DR reduction for moduli of the form 2**k - b */ if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) { goto LBL_M; } redux = mp_reduce_2k; #else err = MP_VAL; goto LBL_M; #endif } /* setup result */ if ((err = mp_init (&res)) != MP_OKAY) { goto LBL_M; } /* create M table * * * The first half of the table is not computed though accept for M[0] and M[1] */ if (redmode == 0) { #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C /* now we need R mod m */ if ((err = mp_montgomery_calc_normalization (&res, P)) != MP_OKAY) { goto LBL_RES; } #else err = MP_VAL; goto LBL_RES; #endif /* now set M[1] to G * R mod m */ if ((err = mp_mulmod (G, &res, P, &M[1])) != MP_OKAY) { goto LBL_RES; } } else { mp_set(&res, 1); if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) { goto LBL_RES; } } /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times */ if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) { goto LBL_RES; } for (x = 0; x < (winsize - 1); x++) { if ((err = mp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)])) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&M[1 << (winsize - 1)], P, mp)) != MP_OKAY) { goto LBL_RES; } } /* create upper table */ for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) { if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&M[x], P, mp)) != MP_OKAY) { goto LBL_RES; } } /* set initial mode and bit cnt */ mode = 0; bitcnt = 1; buf = 0; digidx = X->used - 1; bitcpy = 0; bitbuf = 0; for (;;) { /* grab next digit as required */ if (--bitcnt == 0) { /* if digidx == -1 we are out of digits so break */ if (digidx == -1) { break; } /* read next digit and reset bitcnt */ buf = X->dp[digidx--]; bitcnt = (int)DIGIT_BIT; } /* grab the next msb from the exponent */ y = (mp_digit)(buf >> (DIGIT_BIT - 1)) & 1; buf <<= (mp_digit)1; /* if the bit is zero and mode == 0 then we ignore it * These represent the leading zero bits before the first 1 bit * in the exponent. Technically this opt is not required but it * does lower the # of trivial squaring/reductions used */ if (mode == 0 && y == 0) { continue; } /* if the bit is zero and mode == 1 then we square */ if (mode == 1 && y == 0) { if ((err = mp_sqr (&res, &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, mp)) != MP_OKAY) { goto LBL_RES; } continue; } /* else we add it to the window */ bitbuf |= (y << (winsize - ++bitcpy)); mode = 2; if (bitcpy == winsize) { /* ok window is filled so square as required and multiply */ /* square first */ for (x = 0; x < winsize; x++) { if ((err = mp_sqr (&res, &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, mp)) != MP_OKAY) { goto LBL_RES; } } /* then multiply */ if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, mp)) != MP_OKAY) { goto LBL_RES; } /* empty window and reset */ bitcpy = 0; bitbuf = 0; mode = 1; } } /* if bits remain then square/multiply */ if (mode == 2 && bitcpy > 0) { /* square then multiply if the bit is set */ for (x = 0; x < bitcpy; x++) { if ((err = mp_sqr (&res, &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, mp)) != MP_OKAY) { goto LBL_RES; } /* get next bit of the window */ bitbuf <<= 1; if ((bitbuf & (1 << winsize)) != 0) { /* then multiply */ if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) { goto LBL_RES; } if ((err = redux (&res, P, mp)) != MP_OKAY) { goto LBL_RES; } } } } if (redmode == 0) { /* fixup result if Montgomery reduction is used * recall that any value in a Montgomery system is * actually multiplied by R mod n. So we have * to reduce one more time to cancel out the factor * of R. */ if ((err = redux(&res, P, mp)) != MP_OKAY) { goto LBL_RES; } } /* swap res with Y */ mp_exch (&res, Y); err = MP_OKAY; LBL_RES:mp_clear (&res); LBL_M: mp_clear(&M[1]); for (x = 1<<(winsize-1); x < (1 << winsize); x++) { mp_clear (&M[x]); } return err; } #endif #ifdef BN_S_MP_ADD_C /* low level addition, based on HAC pp.594, Algorithm 14.7 */ int s_mp_add (mp_int * a, mp_int * b, mp_int * c) { mp_int *x; int olduse, res, min, max; /* find sizes, we let |a| <= |b| which means we have to sort * them. "x" will point to the input with the most digits */ if (a->used > b->used) { min = b->used; max = a->used; x = a; } else { min = a->used; max = b->used; x = b; } /* init result */ if (c->alloc < max + 1) { if ((res = mp_grow (c, max + 1)) != MP_OKAY) { return res; } } /* get old used digit count and set new one */ olduse = c->used; c->used = max + 1; { register mp_digit u, *tmpa, *tmpb, *tmpc; register int i; /* alias for digit pointers */ /* first input */ tmpa = a->dp; /* second input */ tmpb = b->dp; /* destination */ tmpc = c->dp; /* zero the carry */ u = 0; for (i = 0; i < min; i++) { /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */ *tmpc = *tmpa++ + *tmpb++ + u; /* U = carry bit of T[i] */ u = *tmpc >> ((mp_digit)DIGIT_BIT); /* take away carry bit from T[i] */ *tmpc++ &= MP_MASK; } /* now copy higher words if any, that is in A+B * if A or B has more digits add those in */ if (min != max) { for (; i < max; i++) { /* T[i] = X[i] + U */ *tmpc = x->dp[i] + u; /* U = carry bit of T[i] */ u = *tmpc >> ((mp_digit)DIGIT_BIT); /* take away carry bit from T[i] */ *tmpc++ &= MP_MASK; } } /* add carry */ *tmpc++ = u; /* clear digits above oldused */ for (i = c->used; i < olduse; i++) { *tmpc++ = 0; } } mp_clamp (c); return MP_OKAY; } #endif #ifdef BN_MP_PRIME_FERMAT_C /* performs one Fermat test. * * If "a" were prime then b**a == b (mod a) since the order of * the multiplicative sub-group would be phi(a) = a-1. That means * it would be the same as b**(a mod (a-1)) == b**1 == b (mod a). * * Sets result to 1 if the congruence holds, or zero otherwise. */ int mp_prime_fermat (mp_int * a, mp_int * b, int *result) { mp_int t; int err; /* default to composite */ *result = MP_NO; /* ensure b > 1 */ if (mp_cmp_d(b, 1) != MP_GT) { return MP_VAL; } /* init t */ if ((err = mp_init (&t)) != MP_OKAY) { return err; } /* compute t = b**a mod a */ if ((err = mp_exptmod (b, a, a, &t)) != MP_OKAY) { goto LBL_T; } /* is it equal to b? */ if (mp_cmp (&t, b) == MP_EQ) { *result = MP_YES; } err = MP_OKAY; LBL_T:mp_clear (&t); return err; } #endif #ifdef BN_MP_ABS_C /* b = |a| * * Simple function copies the input and fixes the sign to positive */ int mp_abs (mp_int * a, mp_int * b) { int res; /* copy a to b */ if (a != b) { if ((res = mp_copy (a, b)) != MP_OKAY) { return res; } } /* force the sign of b to positive */ b->sign = MP_ZPOS; return MP_OKAY; } #endif #ifdef BN_MP_CLAMP_C /* trim unused digits * * This is used to ensure that leading zero digits are * trimed and the leading "used" digit will be non-zero * Typically very fast. Also fixes the sign if there * are no more leading digits */ void mp_clamp (mp_int * a) { /* decrease used while the most significant digit is * zero. */ while (a->used > 0 && a->dp[a->used - 1] == 0) { --(a->used); } /* reset the sign flag if used == 0 */ if (a->used == 0) { a->sign = MP_ZPOS; } } #endif /* $Source$ */ /* $Revision: 0.41 $ */ /* $Date: 2007-04-18 09:58:18 +0000 $ */ #ifdef BN_MP_SIGNED_BIN_SIZE_C /* get the size for an signed equivalent */ int mp_signed_bin_size (mp_int * a) { return 1 + mp_unsigned_bin_size (a); } #endif #ifdef BN_MP_SQRT_C /* this function is less generic than mp_n_root, simpler and faster */ int mp_sqrt(mp_int *arg, mp_int *ret) { int res; mp_int t1,t2; /* must be positive */ if (arg->sign == MP_NEG) { return MP_VAL; } /* easy out */ if (mp_iszero(arg) == MP_YES) { mp_zero(ret); return MP_OKAY; } if ((res = mp_init_copy(&t1, arg)) != MP_OKAY) { return res; } if ((res = mp_init(&t2)) != MP_OKAY) { goto E2; } /* First approx. (not very bad for large arg) */ mp_rshd (&t1,t1.used/2); /* t1 > 0 */ if ((res = mp_div(arg,&t1,&t2,NULL)) != MP_OKAY) { goto E1; } if ((res = mp_add(&t1,&t2,&t1)) != MP_OKAY) { goto E1; } if ((res = mp_div_2(&t1,&t1)) != MP_OKAY) { goto E1; } /* And now t1 > sqrt(arg) */ do { if ((res = mp_div(arg,&t1,&t2,NULL)) != MP_OKAY) { goto E1; } if ((res = mp_add(&t1,&t2,&t1)) != MP_OKAY) { goto E1; } if ((res = mp_div_2(&t1,&t1)) != MP_OKAY) { goto E1; } /* t1 >= sqrt(arg) >= t2 at this point */ } while (mp_cmp_mag(&t1,&t2) == MP_GT); mp_exch(&t1,ret); E1: mp_clear(&t2); E2: mp_clear(&t1); return res; } #endif #ifdef BN_MP_MONTGOMERY_SETUP_C /* setups the montgomery reduction stuff */ int mp_montgomery_setup (mp_int * n, mp_digit * rho) { mp_digit x, b; /* fast inversion mod 2**k * * Based on the fact that * * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n) * => 2*X*A - X*X*A*A = 1 * => 2*(1) - (1) = 1 */ b = n->dp[0]; if ((b & 1) == 0) { return MP_VAL; } x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */ x *= 2 - b * x; /* here x*a==1 mod 2**8 */ #if !defined(MP_8BIT) x *= 2 - b * x; /* here x*a==1 mod 2**16 */ #endif #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT)) x *= 2 - b * x; /* here x*a==1 mod 2**32 */ #endif #ifdef MP_64BIT x *= 2 - b * x; /* here x*a==1 mod 2**64 */ #endif /* rho = -1/m mod b */ *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK; return MP_OKAY; } #endif #ifdef BN_MP_FWRITE_C int mp_fwrite(mp_int *a, int radix, FILE *stream) { char *buf = NULL; int err = 0, len = 0, x = 0; if ((err = mp_radix_size(a, radix, &len)) != MP_OKAY) { return err; } buf = OPT_CAST(char) XMALLOC (len); if (buf == NULL) { return MP_MEM; } if ((err = mp_toradix(a, buf, radix)) != MP_OKAY) { XFREE (buf); return err; } for (x = 0; x < len; x++) { if (fputc(buf[x], stream) == EOF) { XFREE (buf); return MP_VAL; } } XFREE (buf); return MP_OKAY; } #endif #ifdef BN_MP_EXCH_C /* swap the elements of two integers, for cases where you can't simply swap the * mp_int pointers around */ void mp_exch (mp_int * a, mp_int * b) { mp_int t; t = *a; *a = *b; *b = t; } #endif #ifdef BN_PRIME_TAB_C const mp_digit ltm_prime_tab[] = { 0x0002, 0x0003, 0x0005, 0x0007, 0x000B, 0x000D, 0x0011, 0x0013, 0x0017, 0x001D, 0x001F, 0x0025, 0x0029, 0x002B, 0x002F, 0x0035, 0x003B, 0x003D, 0x0043, 0x0047, 0x0049, 0x004F, 0x0053, 0x0059, 0x0061, 0x0065, 0x0067, 0x006B, 0x006D, 0x0071, 0x007F, #ifndef MP_8BIT 0x0083, 0x0089, 0x008B, 0x0095, 0x0097, 0x009D, 0x00A3, 0x00A7, 0x00AD, 0x00B3, 0x00B5, 0x00BF, 0x00C1, 0x00C5, 0x00C7, 0x00D3, 0x00DF, 0x00E3, 0x00E5, 0x00E9, 0x00EF, 0x00F1, 0x00FB, 0x0101, 0x0107, 0x010D, 0x010F, 0x0115, 0x0119, 0x011B, 0x0125, 0x0133, 0x0137, 0x0139, 0x013D, 0x014B, 0x0151, 0x015B, 0x015D, 0x0161, 0x0167, 0x016F, 0x0175, 0x017B, 0x017F, 0x0185, 0x018D, 0x0191, 0x0199, 0x01A3, 0x01A5, 0x01AF, 0x01B1, 0x01B7, 0x01BB, 0x01C1, 0x01C9, 0x01CD, 0x01CF, 0x01D3, 0x01DF, 0x01E7, 0x01EB, 0x01F3, 0x01F7, 0x01FD, 0x0209, 0x020B, 0x021D, 0x0223, 0x022D, 0x0233, 0x0239, 0x023B, 0x0241, 0x024B, 0x0251, 0x0257, 0x0259, 0x025F, 0x0265, 0x0269, 0x026B, 0x0277, 0x0281, 0x0283, 0x0287, 0x028D, 0x0293, 0x0295, 0x02A1, 0x02A5, 0x02AB, 0x02B3, 0x02BD, 0x02C5, 0x02CF, 0x02D7, 0x02DD, 0x02E3, 0x02E7, 0x02EF, 0x02F5, 0x02F9, 0x0301, 0x0305, 0x0313, 0x031D, 0x0329, 0x032B, 0x0335, 0x0337, 0x033B, 0x033D, 0x0347, 0x0355, 0x0359, 0x035B, 0x035F, 0x036D, 0x0371, 0x0373, 0x0377, 0x038B, 0x038F, 0x0397, 0x03A1, 0x03A9, 0x03AD, 0x03B3, 0x03B9, 0x03C7, 0x03CB, 0x03D1, 0x03D7, 0x03DF, 0x03E5, 0x03F1, 0x03F5, 0x03FB, 0x03FD, 0x0407, 0x0409, 0x040F, 0x0419, 0x041B, 0x0425, 0x0427, 0x042D, 0x043F, 0x0443, 0x0445, 0x0449, 0x044F, 0x0455, 0x045D, 0x0463, 0x0469, 0x047F, 0x0481, 0x048B, 0x0493, 0x049D, 0x04A3, 0x04A9, 0x04B1, 0x04BD, 0x04C1, 0x04C7, 0x04CD, 0x04CF, 0x04D5, 0x04E1, 0x04EB, 0x04FD, 0x04FF, 0x0503, 0x0509, 0x050B, 0x0511, 0x0515, 0x0517, 0x051B, 0x0527, 0x0529, 0x052F, 0x0551, 0x0557, 0x055D, 0x0565, 0x0577, 0x0581, 0x058F, 0x0593, 0x0595, 0x0599, 0x059F, 0x05A7, 0x05AB, 0x05AD, 0x05B3, 0x05BF, 0x05C9, 0x05CB, 0x05CF, 0x05D1, 0x05D5, 0x05DB, 0x05E7, 0x05F3, 0x05FB, 0x0607, 0x060D, 0x0611, 0x0617, 0x061F, 0x0623, 0x062B, 0x062F, 0x063D, 0x0641, 0x0647, 0x0649, 0x064D, 0x0653 #endif }; #endif #ifdef BN_MP_INIT_SET_C /* initialize and set a digit */ int mp_init_set (mp_int * a, mp_digit b) { int err; if ((err = mp_init(a)) != MP_OKAY) { return err; } mp_set(a, b); return err; } #endif #ifdef BN_MP_GET_INT_C /* get the lower 32-bits of an mp_int */ unsigned long mp_get_int(mp_int * a) { int i; unsigned long res; if (a->used == 0) { return 0; } /* get number of digits of the lsb we have to read */ i = MIN(a->used,(int)((sizeof(unsigned long)*CHAR_BIT+DIGIT_BIT-1)/DIGIT_BIT))-1; /* get most significant digit of result */ res = DIGIT(a,i); while (--i >= 0) { res = (res << DIGIT_BIT) | DIGIT(a,i); } /* force result to 32-bits always so it is consistent on non 32-bit platforms */ return res & 0xFFFFFFFFUL; } #endif #ifdef BN_MP_MUL_C /* high level multiplication (handles sign) */ int mp_mul (mp_int * a, mp_int * b, mp_int * c) { int res, neg; neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG; /* use Toom-Cook? */ #ifdef BN_MP_TOOM_MUL_C if (MIN (a->used, b->used) >= TOOM_MUL_CUTOFF) { res = mp_toom_mul(a, b, c); } else #endif #ifdef BN_MP_KARATSUBA_MUL_C /* use Karatsuba? */ if (MIN (a->used, b->used) >= KARATSUBA_MUL_CUTOFF) { res = mp_karatsuba_mul (a, b, c); } else #endif { /* can we use the fast multiplier? * * The fast multiplier can be used if the output will * have less than MP_WARRAY digits and the number of * digits won't affect carry propagation */ int digs = a->used + b->used + 1; #ifdef BN_FAST_S_MP_MUL_DIGS_C if ((digs < MP_WARRAY) && MIN(a->used, b->used) <= (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) { res = fast_s_mp_mul_digs (a, b, c, digs); } else #endif #ifdef BN_S_MP_MUL_DIGS_C res = s_mp_mul (a, b, c); /* uses s_mp_mul_digs */ #else res = MP_VAL; #endif } c->sign = (c->used > 0) ? neg : MP_ZPOS; return res; } #endif #ifdef BN_MP_SQRMOD_C /* c = a * a (mod b) */ int mp_sqrmod (mp_int * a, mp_int * b, mp_int * c) { int res; mp_int t; if ((res = mp_init (&t)) != MP_OKAY) { return res; } if ((res = mp_sqr (a, &t)) != MP_OKAY) { mp_clear (&t); return res; } res = mp_mod (&t, b, c); mp_clear (&t); return res; } #endif #ifdef BN_MP_TO_UNSIGNED_BIN_C /* store in unsigned [big endian] format */ int mp_to_unsigned_bin (mp_int * a, unsigned char *b) { int x, res; mp_int t; if ((res = mp_init_copy (&t, a)) != MP_OKAY) { return res; } x = 0; while (mp_iszero (&t) == 0) { #ifndef MP_8BIT b[x++] = (unsigned char) (t.dp[0] & 255); #else b[x++] = (unsigned char) (t.dp[0] | ((t.dp[1] & 0x01) << 7)); #endif if ((res = mp_div_2d (&t, 8, &t, NULL)) != MP_OKAY) { mp_clear (&t); return res; } } bn_reverse (b, x); mp_clear (&t); return MP_OKAY; } #endif #ifdef BN_S_MP_SQR_C /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */ int s_mp_sqr (mp_int * a, mp_int * b) { mp_int t; int res, ix, iy, pa; mp_word r; mp_digit u, tmpx, *tmpt; pa = a->used; if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) { return res; } /* default used is maximum possible size */ t.used = 2*pa + 1; for (ix = 0; ix < pa; ix++) { /* first calculate the digit at 2*ix */ /* calculate double precision result */ r = ((mp_word) t.dp[2*ix]) + ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]); /* store lower part in result */ t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK)); /* get the carry */ u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); /* left hand side of A[ix] * A[iy] */ tmpx = a->dp[ix]; /* alias for where to store the results */ tmpt = t.dp + (2*ix + 1); for (iy = ix + 1; iy < pa; iy++) { /* first calculate the product */ r = ((mp_word)tmpx) * ((mp_word)a->dp[iy]); /* now calculate the double precision result, note we use * addition instead of *2 since it's easier to optimize */ r = ((mp_word) *tmpt) + r + r + ((mp_word) u); /* store lower part */ *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); /* get carry */ u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); } /* propagate upwards */ while (u != ((mp_digit) 0)) { r = ((mp_word) *tmpt) + ((mp_word) u); *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); } } mp_clamp (&t); mp_exch (&t, b); mp_clear (&t); return MP_OKAY; } #endif #ifdef BN_MP_NEG_C /* b = -a */ int mp_neg (mp_int * a, mp_int * b) { int res; if (a != b) { if ((res = mp_copy (a, b)) != MP_OKAY) { return res; } } if (mp_iszero(b) != MP_YES) { b->sign = (a->sign == MP_ZPOS) ? MP_NEG : MP_ZPOS; } else { b->sign = MP_ZPOS; } return MP_OKAY; } #endif #ifdef BN_MP_RADIX_SMAP_C /* chars used in radix conversions */ const char *mp_s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"; #endif #ifdef BN_FAST_S_MP_MUL_DIGS_C /* Fast (comba) multiplier * * This is the fast column-array [comba] multiplier. It is * designed to compute the columns of the product first * then handle the carries afterwards. This has the effect * of making the nested loops that compute the columns very * simple and schedulable on super-scalar processors. * * This has been modified to produce a variable number of * digits of output so if say only a half-product is required * you don't have to compute the upper half (a feature * required for fast Barrett reduction). * * Based on Algorithm 14.12 on pp.595 of HAC. * */ int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs) { int olduse, res, pa, ix, iz; mp_digit W[MP_WARRAY] = {}; register mp_word _W; /* grow the destination as required */ if (c->alloc < digs) { if ((res = mp_grow (c, digs)) != MP_OKAY) { return res; } } /* number of output digits to produce */ pa = MIN(digs, a->used + b->used); /* clear the carry */ _W = 0; for (ix = 0; ix < pa; ix++) { int tx, ty; int iy; mp_digit *tmpx, *tmpy; /* get offsets into the two bignums */ ty = MIN(b->used-1, ix); tx = ix - ty; /* setup temp aliases */ tmpx = a->dp + tx; tmpy = b->dp + ty; /* this is the number of times the loop will iterrate, essentially while (tx++ < a->used && ty-- >= 0) { ... } */ iy = MIN(a->used-tx, ty+1); /* execute loop */ for (iz = 0; iz < iy; ++iz) { _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--); } /* store term */ W[ix] = ((mp_digit)_W) & MP_MASK; /* make next carry */ _W = _W >> ((mp_word)DIGIT_BIT); } /* setup dest */ olduse = c->used; c->used = pa; { register mp_digit *tmpc; tmpc = c->dp; for (ix = 0; ix < pa+1; ix++) { /* now extract the previous digit [below the carry] */ *tmpc++ = W[ix]; } /* clear unused digits [that existed in the old copy of c] */ for (; ix < olduse; ix++) { *tmpc++ = 0; } } mp_clamp (c); return MP_OKAY; } #endif #ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C /* this is a modified version of fast_s_mul_digs that only produces * output digits *above* digs. See the comments for fast_s_mul_digs * to see how it works. * * This is used in the Barrett reduction since for one of the multiplications * only the higher digits were needed. This essentially halves the work. * * Based on Algorithm 14.12 on pp.595 of HAC. */ int fast_s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs) { int olduse, res, pa, ix, iz; mp_digit W[MP_WARRAY]; mp_word _W; /* grow the destination as required */ pa = a->used + b->used; if (c->alloc < pa) { if ((res = mp_grow (c, pa)) != MP_OKAY) { return res; } } /* number of output digits to produce */ pa = a->used + b->used; _W = 0; for (ix = digs; ix < pa; ix++) { int tx, ty, iy; mp_digit *tmpx, *tmpy; /* get offsets into the two bignums */ ty = MIN(b->used-1, ix); tx = ix - ty; /* setup temp aliases */ tmpx = a->dp + tx; tmpy = b->dp + ty; /* this is the number of times the loop will iterrate, essentially its while (tx++ < a->used && ty-- >= 0) { ... } */ iy = MIN(a->used-tx, ty+1); /* execute loop */ for (iz = 0; iz < iy; iz++) { _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--); } /* store term */ W[ix] = ((mp_digit)_W) & MP_MASK; /* make next carry */ _W = _W >> ((mp_word)DIGIT_BIT); } /* setup dest */ olduse = c->used; c->used = pa; { register mp_digit *tmpc; tmpc = c->dp + digs; for (ix = digs; ix < pa; ix++) { /* now extract the previous digit [below the carry] */ *tmpc++ = W[ix]; } /* clear unused digits [that existed in the old copy of c] */ for (; ix < olduse; ix++) { *tmpc++ = 0; } } mp_clamp (c); return MP_OKAY; } #endif #ifdef BN_MP_REDUCE_2K_C /* reduces a modulo n where n is of the form 2**p - d */ int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d) { mp_int q; int p, res; if ((res = mp_init(&q)) != MP_OKAY) { return res; } p = mp_count_bits(n); top: /* q = a/2**p, a = a mod 2**p */ if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) { goto ERR; } if (d != 1) { /* q = q * d */ if ((res = mp_mul_d(&q, d, &q)) != MP_OKAY) { goto ERR; } } /* a = a + q */ if ((res = s_mp_add(a, &q, a)) != MP_OKAY) { goto ERR; } if (mp_cmp_mag(a, n) != MP_LT) { s_mp_sub(a, n, a); goto top; } ERR: mp_clear(&q); return res; } #endif #ifdef BN_MP_SET_C /* set to a digit */ void mp_set (mp_int * a, mp_digit b) { mp_zero (a); a->dp[0] = b & MP_MASK; a->used = (a->dp[0] != 0) ? 1 : 0; } #endif #ifdef BN_MP_MOD_D_C int mp_mod_d (mp_int * a, mp_digit b, mp_digit * c) { return mp_div_d(a, b, NULL, c); } #endif #ifdef BN_MP_COPY_C /* copy, b = a */ int mp_copy (mp_int * a, mp_int * b) { int res, n; /* if dst == src do nothing */ if (a == b) { return MP_OKAY; } /* grow dest */ if (b->alloc < a->used) { if ((res = mp_grow (b, a->used)) != MP_OKAY) { return res; } } /* zero b and copy the parameters over */ { register mp_digit *tmpa, *tmpb; /* pointer aliases */ /* source */ tmpa = a->dp; /* destination */ tmpb = b->dp; /* copy all the digits */ for (n = 0; n < a->used; n++) { *tmpb++ = *tmpa++; } /* clear high digits */ for (; n < b->used; n++) { *tmpb++ = 0; } } /* copy used count and sign */ b->used = a->used; b->sign = a->sign; return MP_OKAY; } #endif #ifdef BN_MP_TO_SIGNED_BIN_N_C /* store in signed [big endian] format */ int mp_to_signed_bin_n (mp_int * a, unsigned char *b, unsigned long *outlen) { if (*outlen < (unsigned long)mp_signed_bin_size(a)) { return MP_VAL; } *outlen = mp_signed_bin_size(a); return mp_to_signed_bin(a, b); } #endif #ifdef BN_FAST_S_MP_SQR_C /* the jist of squaring... * you do like mult except the offset of the tmpx [one that * starts closer to zero] can't equal the offset of tmpy. * So basically you set up iy like before then you min it with * (ty-tx) so that it never happens. You double all those * you add in the inner loop After that loop you do the squares and add them in. */ int fast_s_mp_sqr (mp_int * a, mp_int * b) { int olduse, res, pa, ix, iz; mp_digit W[MP_WARRAY], *tmpx; mp_word W1; /* grow the destination as required */ pa = a->used + a->used; if (b->alloc < pa) { if ((res = mp_grow (b, pa)) != MP_OKAY) { return res; } } /* number of output digits to produce */ W1 = 0; for (ix = 0; ix < pa; ix++) { int tx, ty, iy; mp_word _W; mp_digit *tmpy; /* clear counter */ _W = 0; /* get offsets into the two bignums */ ty = MIN(a->used-1, ix); tx = ix - ty; /* setup temp aliases */ tmpx = a->dp + tx; tmpy = a->dp + ty; /* this is the number of times the loop will iterrate, essentially while (tx++ < a->used && ty-- >= 0) { ... } */ iy = MIN(a->used-tx, ty+1); /* now for squaring tx can never equal ty * we halve the distance since they approach at a rate of 2x * and we have to round because odd cases need to be executed */ iy = MIN(iy, (ty-tx+1)>>1); /* execute loop */ for (iz = 0; iz < iy; iz++) { _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--); } /* double the inner product and add carry */ _W = _W + _W + W1; /* even columns have the square term in them */ if ((ix&1) == 0) { _W += ((mp_word)a->dp[ix>>1])*((mp_word)a->dp[ix>>1]); } /* store it */ W[ix] = (mp_digit)(_W & MP_MASK); /* make next carry */ W1 = _W >> ((mp_word)DIGIT_BIT); } /* setup dest */ olduse = b->used; b->used = a->used+a->used; { mp_digit *tmpb; tmpb = b->dp; for (ix = 0; ix < pa; ix++) { *tmpb++ = W[ix] & MP_MASK; } /* clear unused digits [that existed in the old copy of c] */ for (; ix < olduse; ix++) { *tmpb++ = 0; } } mp_clamp (b); return MP_OKAY; } #endif #ifdef BN_MP_SHRINK_C /* shrink a bignum */ int mp_shrink (mp_int * a) { mp_digit *tmp; int used = 1; if(a->used > 0) used = a->used; if (a->alloc != used) { if ((tmp = OPT_CAST(mp_digit) XREALLOC (a->dp, sizeof (mp_digit) * used)) == NULL) { return MP_MEM; } a->dp = tmp; a->alloc = used; } return MP_OKAY; } #endif #ifdef BN_MP_2EXPT_C /* computes a = 2**b * * Simple algorithm which zeroes the int, grows it then just sets one bit * as required. */ int mp_2expt (mp_int * a, int b) { int res; /* zero a as per default */ mp_zero (a); /* grow a to accomodate the single bit */ if ((res = mp_grow (a, b / DIGIT_BIT + 1)) != MP_OKAY) { return res; } /* set the used count of where the bit will go */ a->used = b / DIGIT_BIT + 1; /* put the single bit in its place */ a->dp[b / DIGIT_BIT] = ((mp_digit)1) << (b % DIGIT_BIT); return MP_OKAY; } #endif #ifdef BN_MP_DR_REDUCE_C /* reduce "x" in place modulo "n" using the Diminished Radix algorithm. * * Based on algorithm from the paper * * "Generating Efficient Primes for Discrete Log Cryptosystems" * Chae Hoon Lim, Pil Joong Lee, * POSTECH Information Research Laboratories * * The modulus must be of a special format [see manual] * * Has been modified to use algorithm 7.10 from the LTM book instead * * Input x must be in the range 0 <= x <= (n-1)**2 */ int mp_dr_reduce (mp_int * x, mp_int * n, mp_digit k) { int err, i, m; mp_word r; mp_digit mu, *tmpx1, *tmpx2; /* m = digits in modulus */ m = n->used; /* ensure that "x" has at least 2m digits */ if (x->alloc < m + m) { if ((err = mp_grow (x, m + m)) != MP_OKAY) { return err; } } /* top of loop, this is where the code resumes if * another reduction pass is required. */ top: /* aliases for digits */ /* alias for lower half of x */ tmpx1 = x->dp; /* alias for upper half of x, or x/B**m */ tmpx2 = x->dp + m; /* set carry to zero */ mu = 0; /* compute (x mod B**m) + k * [x/B**m] inline and inplace */ for (i = 0; i < m; i++) { r = ((mp_word)*tmpx2++) * ((mp_word)k) + *tmpx1 + mu; *tmpx1++ = (mp_digit)(r & MP_MASK); mu = (mp_digit)(r >> ((mp_word)DIGIT_BIT)); } /* set final carry */ *tmpx1++ = mu; /* zero words above m */ for (i = m + 1; i < x->used; i++) { *tmpx1++ = 0; } /* clamp, sub and return */ mp_clamp (x); /* if x >= n then subtract and reduce again * Each successive "recursion" makes the input smaller and smaller. */ if (mp_cmp_mag (x, n) != MP_LT) { s_mp_sub(x, n, x); goto top; } return MP_OKAY; } #endif #ifdef BN_MP_TORADIX_N_C /* stores a bignum as a ASCII string in a given radix (2..64) * * Stores upto maxlen-1 chars and always a NULL byte */ int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen) { int res, digs; mp_int t; mp_digit d; char *_s = str; /* check range of the maxlen, radix */ if (maxlen < 2 || radix < 2 || radix > 64) { return MP_VAL; } /* quick out if its zero */ if (mp_iszero(a) == MP_YES) { *str++ = '0'; *str = '\0'; return MP_OKAY; } if ((res = mp_init_copy (&t, a)) != MP_OKAY) { return res; } /* if it is negative output a - */ if (t.sign == MP_NEG) { /* we have to reverse our digits later... but not the - sign!! */ ++_s; /* store the flag and mark the number as positive */ *str++ = '-'; t.sign = MP_ZPOS; /* subtract a char */ --maxlen; } digs = 0; while (mp_iszero (&t) == 0) { if (--maxlen < 1) { /* no more room */ break; } if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) { mp_clear (&t); return res; } *str++ = mp_s_rmap[d]; ++digs; } /* reverse the digits of the string. In this case _s points * to the first digit [exluding the sign] of the number */ bn_reverse ((unsigned char *)_s, digs); /* append a NULL so the string is properly terminated */ *str = '\0'; mp_clear (&t); return MP_OKAY; } #endif #ifdef BN_MP_PRIME_MILLER_RABIN_C /* Miller-Rabin test of "a" to the base of "b" as described in * HAC pp. 139 Algorithm 4.24 * * Sets result to 0 if definitely composite or 1 if probably prime. * Randomly the chance of error is no more than 1/4 and often * very much lower. */ int mp_prime_miller_rabin (mp_int * a, mp_int * b, int *result) { mp_int n1, y, r; int s, j, err; /* default */ *result = MP_NO; /* ensure b > 1 */ if (mp_cmp_d(b, 1) != MP_GT) { return MP_VAL; } /* get n1 = a - 1 */ if ((err = mp_init_copy (&n1, a)) != MP_OKAY) { return err; } if ((err = mp_sub_d (&n1, 1, &n1)) != MP_OKAY) { goto LBL_N1; } /* set 2**s * r = n1 */ if ((err = mp_init_copy (&r, &n1)) != MP_OKAY) { goto LBL_N1; } /* count the number of least significant bits * which are zero */ s = mp_cnt_lsb(&r); /* now divide n - 1 by 2**s */ if ((err = mp_div_2d (&r, s, &r, NULL)) != MP_OKAY) { goto LBL_R; } /* compute y = b**r mod a */ if ((err = mp_init (&y)) != MP_OKAY) { goto LBL_R; } if ((err = mp_exptmod (b, &r, a, &y)) != MP_OKAY) { goto LBL_Y; } /* if y != 1 and y != n1 do */ if (mp_cmp_d (&y, 1) != MP_EQ && mp_cmp (&y, &n1) != MP_EQ) { j = 1; /* while j <= s-1 and y != n1 */ while ((j <= (s - 1)) && mp_cmp (&y, &n1) != MP_EQ) { if ((err = mp_sqrmod (&y, a, &y)) != MP_OKAY) { goto LBL_Y; } /* if y == 1 then composite */ if (mp_cmp_d (&y, 1) == MP_EQ) { goto LBL_Y; } ++j; } /* if y != n1 then composite */ if (mp_cmp (&y, &n1) != MP_EQ) { goto LBL_Y; } } /* probably prime now */ *result = MP_YES; LBL_Y:mp_clear (&y); LBL_R:mp_clear (&r); LBL_N1:mp_clear (&n1); return err; } #endif #ifdef BN_MP_REDUCE_IS_2K_L_C /* determines if reduce_2k_l can be used */ int mp_reduce_is_2k_l(mp_int *a) { int ix, iy; if (a->used == 0) { return MP_NO; } else if (a->used == 1) { return MP_YES; } else if (a->used > 1) { /* if more than half of the digits are -1 we're sold */ for (iy = ix = 0; ix < a->used; ix++) { if (a->dp[ix] == MP_MASK) { ++iy; } } return (iy >= (a->used/2)) ? MP_YES : MP_NO; } return MP_NO; } #endif #ifdef BN_MP_DR_SETUP_C /* determines the setup value */ void mp_dr_setup(mp_int *a, mp_digit *d) { /* the casts are required if DIGIT_BIT is one less than * the number of bits in a mp_digit [e.g. DIGIT_BIT==31] */ *d = (mp_digit)((((mp_word)1) << ((mp_word)DIGIT_BIT)) - ((mp_word)a->dp[0])); } #endif #ifdef BN_MP_REDUCE_2K_SETUP_C /* determines the setup value */ int mp_reduce_2k_setup(mp_int *a, mp_digit *d) { int res, p; mp_int tmp; if ((res = mp_init(&tmp)) != MP_OKAY) { return res; } p = mp_count_bits(a); if ((res = mp_2expt(&tmp, p)) != MP_OKAY) { mp_clear(&tmp); return res; } if ((res = s_mp_sub(&tmp, a, &tmp)) != MP_OKAY) { mp_clear(&tmp); return res; } *d = tmp.dp[0]; mp_clear(&tmp); return MP_OKAY; } #endif #ifdef BN_MP_REDUCE_SETUP_C /* pre-calculate the value required for Barrett reduction * For a given modulus "b" it calulates the value required in "a" */ int mp_reduce_setup (mp_int * a, mp_int * b) { int res; if ((res = mp_2expt (a, b->used * 2 * DIGIT_BIT)) != MP_OKAY) { return res; } return mp_div (a, b, a, NULL); } #endif #ifdef BN_MP_GCD_C /* Greatest Common Divisor using the binary method */ int mp_gcd (mp_int * a, mp_int * b, mp_int * c) { mp_int u, v; int k, u_lsb, v_lsb, res; /* either zero than gcd is the largest */ if (mp_iszero (a) == MP_YES) { return mp_abs (b, c); } if (mp_iszero (b) == MP_YES) { return mp_abs (a, c); } /* get copies of a and b we can modify */ if ((res = mp_init_copy (&u, a)) != MP_OKAY) { return res; } if ((res = mp_init_copy (&v, b)) != MP_OKAY) { goto LBL_U; } /* must be positive for the remainder of the algorithm */ u.sign = v.sign = MP_ZPOS; /* B1. Find the common power of two for u and v */ u_lsb = mp_cnt_lsb(&u); v_lsb = mp_cnt_lsb(&v); k = MIN(u_lsb, v_lsb); if (k > 0) { /* divide the power of two out */ if ((res = mp_div_2d(&u, k, &u, NULL)) != MP_OKAY) { goto LBL_V; } if ((res = mp_div_2d(&v, k, &v, NULL)) != MP_OKAY) { goto LBL_V; } } /* divide any remaining factors of two out */ if (u_lsb != k) { if ((res = mp_div_2d(&u, u_lsb - k, &u, NULL)) != MP_OKAY) { goto LBL_V; } } if (v_lsb != k) { if ((res = mp_div_2d(&v, v_lsb - k, &v, NULL)) != MP_OKAY) { goto LBL_V; } } while (mp_iszero(&v) == 0) { /* make sure v is the largest */ if (mp_cmp_mag(&u, &v) == MP_GT) { /* swap u and v to make sure v is >= u */ mp_exch(&u, &v); } /* subtract smallest from largest */ if ((res = s_mp_sub(&v, &u, &v)) != MP_OKAY) { goto LBL_V; } /* Divide out all factors of two */ if ((res = mp_div_2d(&v, mp_cnt_lsb(&v), &v, NULL)) != MP_OKAY) { goto LBL_V; } } /* multiply by 2**k which we divided out at the beginning */ if ((res = mp_mul_2d (&u, k, c)) != MP_OKAY) { goto LBL_V; } c->sign = MP_ZPOS; res = MP_OKAY; LBL_V:mp_clear (&u); LBL_U:mp_clear (&v); return res; } #endif #ifdef BN_S_MP_SUB_C /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */ int s_mp_sub (mp_int * a, mp_int * b, mp_int * c) { int olduse, res, min, max; /* find sizes */ min = b->used; max = a->used; /* init result */ if (c->alloc < max) { if ((res = mp_grow (c, max)) != MP_OKAY) { return res; } } olduse = c->used; c->used = max; { register mp_digit u, *tmpa, *tmpb, *tmpc; register int i; /* alias for digit pointers */ tmpa = a->dp; tmpb = b->dp; tmpc = c->dp; /* set carry to zero */ u = 0; for (i = 0; i < min; i++) { /* T[i] = A[i] - B[i] - U */ *tmpc = *tmpa++ - *tmpb++ - u; /* U = carry bit of T[i] * Note this saves performing an AND operation since * if a carry does occur it will propagate all the way to the * MSB. As a result a single shift is enough to get the carry */ u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1)); /* Clear carry from T[i] */ *tmpc++ &= MP_MASK; } /* now copy higher words if any, e.g. if A has more digits than B */ for (; i < max; i++) { /* T[i] = A[i] - U */ *tmpc = *tmpa++ - u; /* U = carry bit of T[i] */ u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1)); /* Clear carry from T[i] */ *tmpc++ &= MP_MASK; } /* clear digits above used (since we may not have grown result above) */ for (i = c->used; i < olduse; i++) { *tmpc++ = 0; } } mp_clamp (c); return MP_OKAY; } #endif #ifdef BN_MP_TOOM_MUL_C /* multiplication using the Toom-Cook 3-way algorithm * * Much more complicated than Karatsuba but has a lower * asymptotic running time of O(N**1.464). This algorithm is * only particularly useful on VERY large inputs * (we're talking 1000s of digits here...). */ int mp_toom_mul(mp_int *a, mp_int *b, mp_int *c) { mp_int w0, w1, w2, w3, w4, tmp1, tmp2, a0, a1, a2, b0, b1, b2; int res, B; /* init temps */ if ((res = mp_init_multi(&w0, &w1, &w2, &w3, &w4, &a0, &a1, &a2, &b0, &b1, &b2, &tmp1, &tmp2, NULL)) != MP_OKAY) { return res; } /* B */ B = MIN(a->used, b->used) / 3; /* a = a2 * B**2 + a1 * B + a0 */ if ((res = mp_mod_2d(a, DIGIT_BIT * B, &a0)) != MP_OKAY) { goto ERR; } if ((res = mp_copy(a, &a1)) != MP_OKAY) { goto ERR; } mp_rshd(&a1, B); mp_mod_2d(&a1, DIGIT_BIT * B, &a1); if ((res = mp_copy(a, &a2)) != MP_OKAY) { goto ERR; } mp_rshd(&a2, B*2); /* b = b2 * B**2 + b1 * B + b0 */ if ((res = mp_mod_2d(b, DIGIT_BIT * B, &b0)) != MP_OKAY) { goto ERR; } if ((res = mp_copy(b, &b1)) != MP_OKAY) { goto ERR; } mp_rshd(&b1, B); mp_mod_2d(&b1, DIGIT_BIT * B, &b1); if ((res = mp_copy(b, &b2)) != MP_OKAY) { goto ERR; } mp_rshd(&b2, B*2); /* w0 = a0*b0 */ if ((res = mp_mul(&a0, &b0, &w0)) != MP_OKAY) { goto ERR; } /* w4 = a2 * b2 */ if ((res = mp_mul(&a2, &b2, &w4)) != MP_OKAY) { goto ERR; } /* w1 = (a2 + 2(a1 + 2a0))(b2 + 2(b1 + 2b0)) */ if ((res = mp_mul_2(&a0, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, &a1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_mul_2(&tmp1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, &a2, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_mul_2(&b0, &tmp2)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp2, &b1, &tmp2)) != MP_OKAY) { goto ERR; } if ((res = mp_mul_2(&tmp2, &tmp2)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp2, &b2, &tmp2)) != MP_OKAY) { goto ERR; } if ((res = mp_mul(&tmp1, &tmp2, &w1)) != MP_OKAY) { goto ERR; } /* w3 = (a0 + 2(a1 + 2a2))(b0 + 2(b1 + 2b2)) */ if ((res = mp_mul_2(&a2, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, &a1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_mul_2(&tmp1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, &a0, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_mul_2(&b2, &tmp2)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp2, &b1, &tmp2)) != MP_OKAY) { goto ERR; } if ((res = mp_mul_2(&tmp2, &tmp2)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp2, &b0, &tmp2)) != MP_OKAY) { goto ERR; } if ((res = mp_mul(&tmp1, &tmp2, &w3)) != MP_OKAY) { goto ERR; } /* w2 = (a2 + a1 + a0)(b2 + b1 + b0) */ if ((res = mp_add(&a2, &a1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, &a0, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&b2, &b1, &tmp2)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp2, &b0, &tmp2)) != MP_OKAY) { goto ERR; } if ((res = mp_mul(&tmp1, &tmp2, &w2)) != MP_OKAY) { goto ERR; } /* now solve the matrix 0 0 0 0 1 1 2 4 8 16 1 1 1 1 1 16 8 4 2 1 1 0 0 0 0 using 12 subtractions, 4 shifts, 2 small divisions and 1 small multiplication */ /* r1 - r4 */ if ((res = mp_sub(&w1, &w4, &w1)) != MP_OKAY) { goto ERR; } /* r3 - r0 */ if ((res = mp_sub(&w3, &w0, &w3)) != MP_OKAY) { goto ERR; } /* r1/2 */ if ((res = mp_div_2(&w1, &w1)) != MP_OKAY) { goto ERR; } /* r3/2 */ if ((res = mp_div_2(&w3, &w3)) != MP_OKAY) { goto ERR; } /* r2 - r0 - r4 */ if ((res = mp_sub(&w2, &w0, &w2)) != MP_OKAY) { goto ERR; } if ((res = mp_sub(&w2, &w4, &w2)) != MP_OKAY) { goto ERR; } /* r1 - r2 */ if ((res = mp_sub(&w1, &w2, &w1)) != MP_OKAY) { goto ERR; } /* r3 - r2 */ if ((res = mp_sub(&w3, &w2, &w3)) != MP_OKAY) { goto ERR; } /* r1 - 8r0 */ if ((res = mp_mul_2d(&w0, 3, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_sub(&w1, &tmp1, &w1)) != MP_OKAY) { goto ERR; } /* r3 - 8r4 */ if ((res = mp_mul_2d(&w4, 3, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_sub(&w3, &tmp1, &w3)) != MP_OKAY) { goto ERR; } /* 3r2 - r1 - r3 */ if ((res = mp_mul_d(&w2, 3, &w2)) != MP_OKAY) { goto ERR; } if ((res = mp_sub(&w2, &w1, &w2)) != MP_OKAY) { goto ERR; } if ((res = mp_sub(&w2, &w3, &w2)) != MP_OKAY) { goto ERR; } /* r1 - r2 */ if ((res = mp_sub(&w1, &w2, &w1)) != MP_OKAY) { goto ERR; } /* r3 - r2 */ if ((res = mp_sub(&w3, &w2, &w3)) != MP_OKAY) { goto ERR; } /* r1/3 */ if ((res = mp_div_3(&w1, &w1, NULL)) != MP_OKAY) { goto ERR; } /* r3/3 */ if ((res = mp_div_3(&w3, &w3, NULL)) != MP_OKAY) { goto ERR; } /* at this point shift W[n] by B*n */ if ((res = mp_lshd(&w1, 1*B)) != MP_OKAY) { goto ERR; } if ((res = mp_lshd(&w2, 2*B)) != MP_OKAY) { goto ERR; } if ((res = mp_lshd(&w3, 3*B)) != MP_OKAY) { goto ERR; } if ((res = mp_lshd(&w4, 4*B)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&w0, &w1, c)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&w2, &w3, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&w4, &tmp1, &tmp1)) != MP_OKAY) { goto ERR; } if ((res = mp_add(&tmp1, c, c)) != MP_OKAY) { goto ERR; } ERR: mp_clear_multi(&w0, &w1, &w2, &w3, &w4, &a0, &a1, &a2, &b0, &b1, &b2, &tmp1, &tmp2, NULL); return res; } #endif #ifdef BN_MP_INIT_SET_INT_C /* initialize and set a digit */ int mp_init_set_int (mp_int * a, unsigned long b) { int err; if ((err = mp_init(a)) != MP_OKAY) { return err; } return mp_set_int(a, b); } #endif #ifdef BN_FAST_MP_INVMOD_C /* computes the modular inverse via binary extended euclidean algorithm, * that is c = 1/a mod b * * Based on slow invmod except this is optimized for the case where b is * odd as per HAC Note 14.64 on pp. 610 */ int fast_mp_invmod (mp_int * a, mp_int * b, mp_int * c) { mp_int x, y, u, v, B, D; int res, neg; /* 2. [modified] b must be odd */ if (mp_iseven (b) == 1) { return MP_VAL; } /* init all our temps */ if ((res = mp_init_multi(&x, &y, &u, &v, &B, &D, NULL)) != MP_OKAY) { return res; } /* x == modulus, y == value to invert */ if ((res = mp_copy (b, &x)) != MP_OKAY) { goto LBL_ERR; } /* we need y = |a| */ if ((res = mp_mod (a, b, &y)) != MP_OKAY) { goto LBL_ERR; } /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */ if ((res = mp_copy (&x, &u)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_copy (&y, &v)) != MP_OKAY) { goto LBL_ERR; } mp_set (&D, 1); top: /* 4. while u is even do */ while (mp_iseven (&u) == 1) { /* 4.1 u = u/2 */ if ((res = mp_div_2 (&u, &u)) != MP_OKAY) { goto LBL_ERR; } /* 4.2 if B is odd then */ if (mp_isodd (&B) == 1) { if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) { goto LBL_ERR; } } /* B = B/2 */ if ((res = mp_div_2 (&B, &B)) != MP_OKAY) { goto LBL_ERR; } } /* 5. while v is even do */ while (mp_iseven (&v) == 1) { /* 5.1 v = v/2 */ if ((res = mp_div_2 (&v, &v)) != MP_OKAY) { goto LBL_ERR; } /* 5.2 if D is odd then */ if (mp_isodd (&D) == 1) { /* D = (D-x)/2 */ if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) { goto LBL_ERR; } } /* D = D/2 */ if ((res = mp_div_2 (&D, &D)) != MP_OKAY) { goto LBL_ERR; } } /* 6. if u >= v then */ if (mp_cmp (&u, &v) != MP_LT) { /* u = u - v, B = B - D */ if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) { goto LBL_ERR; } } else { /* v - v - u, D = D - B */ if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) { goto LBL_ERR; } if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) { goto LBL_ERR; } } /* if not zero goto step 4 */ if (mp_iszero (&u) == 0) { goto top; } /* now a = C, b = D, gcd == g*v */ /* if v != 1 then there is no inverse */ if (mp_cmp_d (&v, 1) != MP_EQ) { res = MP_VAL; goto LBL_ERR; } /* b is now the inverse */ neg = a->sign; while (D.sign == MP_NEG) { if ((res = mp_add (&D, b, &D)) != MP_OKAY) { goto LBL_ERR; } } mp_exch (&D, c); c->sign = neg; res = MP_OKAY; LBL_ERR:mp_clear_multi (&x, &y, &u, &v, &B, &D, NULL); return res; } #endif #ifdef BN_MP_TO_SIGNED_BIN_C /* store in signed [big endian] format */ int mp_to_signed_bin (mp_int * a, unsigned char *b) { int res; if ((res = mp_to_unsigned_bin (a, b + 1)) != MP_OKAY) { return res; } b[0] = (unsigned char) ((a->sign == MP_ZPOS) ? 0 : 1); return MP_OKAY; } #endif #ifdef BN_MP_MOD_C /* c = a mod b, 0 <= c < b */ int mp_mod (mp_int * a, mp_int * b, mp_int * c) { mp_int t; int res; if ((res = mp_init (&t)) != MP_OKAY) { return res; } if ((res = mp_div (a, b, NULL, &t)) != MP_OKAY) { mp_clear (&t); return res; } if (t.sign != b->sign) { res = mp_add (b, &t, c); } else { res = MP_OKAY; mp_exch (&t, c); } mp_clear (&t); return res; } #endif #ifdef BN_MP_DR_IS_MODULUS_C /* determines if a number is a valid DR modulus */ int mp_dr_is_modulus(mp_int *a) { int ix; /* must be at least two digits */ if (a->used < 2) { return 0; } /* must be of the form b**k - a [a <= b] so all * but the first digit must be equal to -1 (mod b). */ for (ix = 1; ix < a->used; ix++) { if (a->dp[ix] != MP_MASK) { return 0; } } return 1; } #endif #ifdef BN_MP_IS_SQUARE_C /* Check if remainders are possible squares - fast exclude non-squares */ static const char rem_128[128] = { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }; static const char rem_105[105] = { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1 }; /* Store non-zero to ret if arg is square, and zero if not */ int mp_is_square(mp_int *arg,int *ret) { int res; mp_digit c; mp_int t; unsigned long r; /* Default to Non-square :) */ *ret = MP_NO; if (arg->sign == MP_NEG) { return MP_VAL; } /* digits used? (TSD) */ if (arg->used == 0) { return MP_OKAY; } /* First check mod 128 (suppose that DIGIT_BIT is at least 7) */ if (rem_128[127 & DIGIT(arg,0)] == 1) { return MP_OKAY; } /* Next check mod 105 (3*5*7) */ if ((res = mp_mod_d(arg,105,&c)) != MP_OKAY) { return res; } if (rem_105[c] == 1) { return MP_OKAY; } if ((res = mp_init_set_int(&t,11L*13L*17L*19L*23L*29L*31L)) != MP_OKAY) { return res; } if ((res = mp_mod(arg,&t,&t)) != MP_OKAY) { goto ERR; } r = mp_get_int(&t); /* Check for other prime modules, note it's not an ERROR but we must * free "t" so the easiest way is to goto ERR. We know that res * is already equal to MP_OKAY from the mp_mod call */ if ( (1L<<(r%11)) & 0x5C4L ) goto ERR; if ( (1L<<(r%13)) & 0x9E4L ) goto ERR; if ( (1L<<(r%17)) & 0x5CE8L ) goto ERR; if ( (1L<<(r%19)) & 0x4F50CL ) goto ERR; if ( (1L<<(r%23)) & 0x7ACCA0L ) goto ERR; if ( (1L<<(r%29)) & 0xC2EDD0CL ) goto ERR; if ( (1L<<(r%31)) & 0x6DE2B848L ) goto ERR; /* Final check - is sqr(sqrt(arg)) == arg ? */ if ((res = mp_sqrt(arg,&t)) != MP_OKAY) { goto ERR; } if ((res = mp_sqr(&t,&t)) != MP_OKAY) { goto ERR; } *ret = (mp_cmp_mag(&t,arg) == MP_EQ) ? MP_YES : MP_NO; ERR:mp_clear(&t); return res; } #endif #ifdef BN_MP_SUBMOD_C /* d = a - b (mod c) */ int mp_submod (mp_int * a, mp_int * b, mp_int * c, mp_int * d) { int res; mp_int t; if ((res = mp_init (&t)) != MP_OKAY) { return res; } if ((res = mp_sub (a, b, &t)) != MP_OKAY) { mp_clear (&t); return res; } res = mp_mod (&t, c, d); mp_clear (&t); return res; } #endif #ifdef BN_MP_RAND_C /* makes a pseudo-random int of a given size */ int mp_rand (mp_int * a, int digits) { int res; mp_digit d; mp_zero (a); if (digits <= 0) { return MP_OKAY; } /* first place a random non-zero digit */ do { d = ((mp_digit) abs (rand ())) & MP_MASK; } while (d == 0); if ((res = mp_add_d (a, d, a)) != MP_OKAY) { return res; } while (--digits > 0) { if ((res = mp_lshd (a, 1)) != MP_OKAY) { return res; } if ((res = mp_add_d (a, ((mp_digit) abs (rand ())), a)) != MP_OKAY) { return res; } } return MP_OKAY; } #endif #ifdef BN_MP_READ_RADIX_C /* read a string [ASCII] in a given radix */ int mp_read_radix (mp_int * a, const char *str, int radix) { int y, res, neg; char ch; /* zero the digit bignum */ mp_zero(a); /* make sure the radix is ok */ if (radix < 2 || radix > 64) { return MP_VAL; } /* if the leading digit is a * minus set the sign to negative. */ if (*str == '-') { ++str; neg = MP_NEG; } else { neg = MP_ZPOS; } /* set the integer to the default of zero */ mp_zero (a); /* process each digit of the string */ while (*str) { /* if the radix < 36 the conversion is case insensitive * this allows numbers like 1AB and 1ab to represent the same value * [e.g. in hex] */ ch = (char) ((radix < 36) ? toupper (*str) : *str); for (y = 0; y < 64; y++) { if (ch == mp_s_rmap[y]) { break; } } /* if the char was found in the map * and is less than the given radix add it * to the number, otherwise exit the loop. */ if (y < radix) { if ((res = mp_mul_d (a, (mp_digit) radix, a)) != MP_OKAY) { return res; } if ((res = mp_add_d (a, (mp_digit) y, a)) != MP_OKAY) { return res; } } else { break; } ++str; } /* set the sign only if a != 0 */ if (mp_iszero(a) != 1) { a->sign = neg; } return MP_OKAY; } #endif #ifdef BN_MP_CLEAR_MULTI_C #include void mp_clear_multi(mp_int *mp, ...) { mp_int* next_mp = mp; va_list args; va_start(args, mp); while (next_mp != NULL) { mp_clear(next_mp); next_mp = va_arg(args, mp_int*); } va_end(args); } #endif #ifdef BN_MP_ADDMOD_C /* d = a + b (mod c) */ int mp_addmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d) { int res; mp_int t; if ((res = mp_init (&t)) != MP_OKAY) { return res; } if ((res = mp_add (a, b, &t)) != MP_OKAY) { mp_clear (&t); return res; } res = mp_mod (&t, c, d); mp_clear (&t); return res; } #endif #ifdef BN_S_MP_MUL_HIGH_DIGS_C /* multiplies |a| * |b| and does not compute the lower digs digits * [meant to get the higher part of the product] */ int s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs) { mp_int t; int res, pa, pb, ix, iy; mp_digit u; mp_word r; mp_digit tmpx, *tmpt, *tmpy; /* can we use the fast multiplier? */ #ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C if (((a->used + b->used + 1) < MP_WARRAY) && MIN (a->used, b->used) < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) { return fast_s_mp_mul_high_digs (a, b, c, digs); } #endif if ((res = mp_init_size (&t, a->used + b->used + 1)) != MP_OKAY) { return res; } t.used = a->used + b->used + 1; pa = a->used; pb = b->used; for (ix = 0; ix < pa; ix++) { /* clear the carry */ u = 0; /* left hand side of A[ix] * B[iy] */ tmpx = a->dp[ix]; /* alias to the address of where the digits will be stored */ tmpt = &(t.dp[digs]); /* alias for where to read the right hand side from */ tmpy = b->dp + (digs - ix); for (iy = digs - ix; iy < pb; iy++) { /* calculate the double precision result */ r = ((mp_word)*tmpt) + ((mp_word)tmpx) * ((mp_word)*tmpy++) + ((mp_word) u); /* get the lower part */ *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); /* carry the carry */ u = (mp_digit) (r >> ((mp_word) DIGIT_BIT)); } *tmpt = u; } mp_clamp (&t); mp_exch (&t, c); mp_clear (&t); return MP_OKAY; } #endif #ifdef BN_MP_UNSIGNED_BIN_SIZE_C /* get the size for an unsigned equivalent */ int mp_unsigned_bin_size (mp_int * a) { int size = mp_count_bits (a); return (size / 8 + ((size & 7) != 0 ? 1 : 0)); } #endif ================================================ FILE: ios/JKBigInteger/LibTomMath/tommath.h ================================================ /* LibTomMath, multiple-precision integer library -- Tom St Denis * * LibTomMath is a library that provides multiple-precision * integer arithmetic as well as number theoretic functionality. * * The library was designed directly after the MPI library by * Michael Fromberger but has been written from scratch with * additional optimizations in place. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com */ #ifndef BN_H_ #define BN_H_ #include #include #include #include #include #include "tommath_class.h" #ifndef MIN #define MIN(x,y) ((x)<(y)?(x):(y)) #endif #ifndef MAX #define MAX(x,y) ((x)>(y)?(x):(y)) #endif #ifdef __cplusplus extern "C" { /* C++ compilers don't like assigning void * to mp_digit * */ #define OPT_CAST(x) (x *) #else /* C on the other hand doesn't care */ #define OPT_CAST(x) #endif /* detect 64-bit mode if possible */ #if defined(__x86_64__) #if !(defined(MP_64BIT) && defined(MP_16BIT) && defined(MP_8BIT)) #define MP_64BIT #endif #endif /* some default configurations. * * A "mp_digit" must be able to hold DIGIT_BIT + 1 bits * A "mp_word" must be able to hold 2*DIGIT_BIT + 1 bits * * At the very least a mp_digit must be able to hold 7 bits * [any size beyond that is ok provided it doesn't overflow the data type] */ #ifdef MP_8BIT typedef unsigned char mp_digit; typedef unsigned short mp_word; #elif defined(MP_16BIT) typedef unsigned short mp_digit; typedef unsigned long mp_word; #elif defined(MP_64BIT) /* for GCC only on supported platforms */ #ifndef CRYPT typedef unsigned long long ulong64; typedef signed long long long64; #endif typedef unsigned long mp_digit; typedef unsigned long mp_word __attribute__ ((mode(TI))); #define DIGIT_BIT 60 #else /* this is the default case, 28-bit digits */ /* this is to make porting into LibTomCrypt easier :-) */ #ifndef CRYPT #if defined(_MSC_VER) || defined(__BORLANDC__) typedef unsigned __int64 ulong64; typedef signed __int64 long64; #else typedef unsigned long long ulong64; typedef signed long long long64; #endif #endif typedef unsigned long mp_digit; typedef ulong64 mp_word; #ifdef MP_31BIT /* this is an extension that uses 31-bit digits */ #define DIGIT_BIT 31 #else /* default case is 28-bit digits, defines MP_28BIT as a handy macro to test */ #define DIGIT_BIT 28 #define MP_28BIT #endif #endif /* define heap macros */ #ifndef CRYPT /* default to libc stuff */ #ifndef XMALLOC #define XMALLOC malloc #define XFREE free #define XREALLOC realloc #define XCALLOC calloc #else /* prototypes for our heap functions */ extern void *XMALLOC(size_t n); extern void *XREALLOC(void *p, size_t n); extern void *XCALLOC(size_t n, size_t s); extern void XFREE(void *p); #endif #endif /* otherwise the bits per digit is calculated automatically from the size of a mp_digit */ #ifndef DIGIT_BIT #define DIGIT_BIT ((int)((CHAR_BIT * sizeof(mp_digit) - 1))) /* bits per digit */ #endif #define MP_DIGIT_BIT DIGIT_BIT #define MP_MASK ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1)) #define MP_DIGIT_MAX MP_MASK /* equalities */ #define MP_LT -1 /* less than */ #define MP_EQ 0 /* equal to */ #define MP_GT 1 /* greater than */ #define MP_ZPOS 0 /* positive integer */ #define MP_NEG 1 /* negative */ #define MP_OKAY 0 /* ok result */ #define MP_MEM -2 /* out of mem */ #define MP_VAL -3 /* invalid input */ #define MP_RANGE MP_VAL #define MP_YES 1 /* yes response */ #define MP_NO 0 /* no response */ /* Primality generation flags */ #define LTM_PRIME_BBS 0x0001 /* BBS style prime */ #define LTM_PRIME_SAFE 0x0002 /* Safe prime (p-1)/2 == prime */ #define LTM_PRIME_2MSB_ON 0x0008 /* force 2nd MSB to 1 */ typedef int mp_err; /* you'll have to tune these... */ extern int KARATSUBA_MUL_CUTOFF, KARATSUBA_SQR_CUTOFF, TOOM_MUL_CUTOFF, TOOM_SQR_CUTOFF; /* define this to use lower memory usage routines (exptmods mostly) */ /* #define MP_LOW_MEM */ /* default precision */ #ifndef MP_PREC #ifndef MP_LOW_MEM #define MP_PREC 32 /* default digits of precision */ #else #define MP_PREC 8 /* default digits of precision */ #endif #endif /* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */ #define MP_WARRAY (1 << (sizeof(mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1)) /* the infamous mp_int structure */ typedef struct { int used, alloc, sign; mp_digit *dp; } mp_int; /* callback for mp_prime_random, should fill dst with random bytes and return how many read [upto len] */ typedef int ltm_prime_callback(unsigned char *dst, int len, void *dat); #define USED(m) ((m)->used) #define DIGIT(m,k) ((m)->dp[(k)]) #define SIGN(m) ((m)->sign) /* error code to char* string */ char *mp_error_to_string(int code); /* ---> init and deinit bignum functions <--- */ /* init a bignum */ int mp_init(mp_int *a); /* free a bignum */ void mp_clear(mp_int *a); /* init a null terminated series of arguments */ int mp_init_multi(mp_int *mp, ...); /* clear a null terminated series of arguments */ void mp_clear_multi(mp_int *mp, ...); /* exchange two ints */ void mp_exch(mp_int *a, mp_int *b); /* shrink ram required for a bignum */ int mp_shrink(mp_int *a); /* grow an int to a given size */ int mp_grow(mp_int *a, int size); /* init to a given number of digits */ int mp_init_size(mp_int *a, int size); /* ---> Basic Manipulations <--- */ #define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO) #define mp_iseven(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 0)) ? MP_YES : MP_NO) #define mp_isodd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? MP_YES : MP_NO) /* set to zero */ void mp_zero(mp_int *a); /* set to a digit */ void mp_set(mp_int *a, mp_digit b); /* set a 32-bit const */ int mp_set_int(mp_int *a, unsigned long b); /* get a 32-bit value */ unsigned long mp_get_int(mp_int * a); /* initialize and set a digit */ int mp_init_set (mp_int * a, mp_digit b); /* initialize and set 32-bit value */ int mp_init_set_int (mp_int * a, unsigned long b); /* copy, b = a */ int mp_copy(mp_int *a, mp_int *b); /* inits and copies, a = b */ int mp_init_copy(mp_int *a, mp_int *b); /* trim unused digits */ void mp_clamp(mp_int *a); /* ---> digit manipulation <--- */ /* right shift by "b" digits */ void mp_rshd(mp_int *a, int b); /* left shift by "b" digits */ int mp_lshd(mp_int *a, int b); /* c = a / 2**b */ int mp_div_2d(mp_int *a, int b, mp_int *c, mp_int *d); /* b = a/2 */ int mp_div_2(mp_int *a, mp_int *b); /* c = a * 2**b */ int mp_mul_2d(mp_int *a, int b, mp_int *c); /* b = a*2 */ int mp_mul_2(mp_int *a, mp_int *b); /* c = a mod 2**d */ int mp_mod_2d(mp_int *a, int b, mp_int *c); /* computes a = 2**b */ int mp_2expt(mp_int *a, int b); /* Counts the number of lsbs which are zero before the first zero bit */ int mp_cnt_lsb(mp_int *a); /* I Love Earth! */ /* makes a pseudo-random int of a given size */ int mp_rand(mp_int *a, int digits); /* ---> binary operations <--- */ /* c = a XOR b */ int mp_xor(mp_int *a, mp_int *b, mp_int *c); /* c = a OR b */ int mp_or(mp_int *a, mp_int *b, mp_int *c); /* c = a AND b */ int mp_and(mp_int *a, mp_int *b, mp_int *c); /* ---> Basic arithmetic <--- */ /* b = -a */ int mp_neg(mp_int *a, mp_int *b); /* b = |a| */ int mp_abs(mp_int *a, mp_int *b); /* compare a to b */ int mp_cmp(mp_int *a, mp_int *b); /* compare |a| to |b| */ int mp_cmp_mag(mp_int *a, mp_int *b); /* c = a + b */ int mp_add(mp_int *a, mp_int *b, mp_int *c); /* c = a - b */ int mp_sub(mp_int *a, mp_int *b, mp_int *c); /* c = a * b */ int mp_mul(mp_int *a, mp_int *b, mp_int *c); /* b = a*a */ int mp_sqr(mp_int *a, mp_int *b); /* a/b => cb + d == a */ int mp_div(mp_int *a, mp_int *b, mp_int *c, mp_int *d); /* c = a mod b, 0 <= c < b */ int mp_mod(mp_int *a, mp_int *b, mp_int *c); /* ---> single digit functions <--- */ /* compare against a single digit */ int mp_cmp_d(mp_int *a, mp_digit b); /* c = a + b */ int mp_add_d(mp_int *a, mp_digit b, mp_int *c); /* c = a - b */ int mp_sub_d(mp_int *a, mp_digit b, mp_int *c); /* c = a * b */ int mp_mul_d(mp_int *a, mp_digit b, mp_int *c); /* a/b => cb + d == a */ int mp_div_d(mp_int *a, mp_digit b, mp_int *c, mp_digit *d); /* a/3 => 3c + d == a */ int mp_div_3(mp_int *a, mp_int *c, mp_digit *d); /* c = a**b */ int mp_expt_d(mp_int *a, mp_digit b, mp_int *c); /* c = a mod b, 0 <= c < b */ int mp_mod_d(mp_int *a, mp_digit b, mp_digit *c); /* ---> number theory <--- */ /* d = a + b (mod c) */ int mp_addmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d); /* d = a - b (mod c) */ int mp_submod(mp_int *a, mp_int *b, mp_int *c, mp_int *d); /* d = a * b (mod c) */ int mp_mulmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d); /* c = a * a (mod b) */ int mp_sqrmod(mp_int *a, mp_int *b, mp_int *c); /* c = 1/a (mod b) */ int mp_invmod(mp_int *a, mp_int *b, mp_int *c); /* c = (a, b) */ int mp_gcd(mp_int *a, mp_int *b, mp_int *c); /* produces value such that U1*a + U2*b = U3 */ int mp_exteuclid(mp_int *a, mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3); /* c = [a, b] or (a*b)/(a, b) */ int mp_lcm(mp_int *a, mp_int *b, mp_int *c); /* finds one of the b'th root of a, such that |c|**b <= |a| * * returns error if a < 0 and b is even */ int mp_n_root(mp_int *a, mp_digit b, mp_int *c); /* special sqrt algo */ int mp_sqrt(mp_int *arg, mp_int *ret); /* is number a square? */ int mp_is_square(mp_int *arg, int *ret); /* computes the jacobi c = (a | n) (or Legendre if b is prime) */ int mp_jacobi(mp_int *a, mp_int *n, int *c); /* used to setup the Barrett reduction for a given modulus b */ int mp_reduce_setup(mp_int *a, mp_int *b); /* Barrett Reduction, computes a (mod b) with a precomputed value c * * Assumes that 0 < a <= b*b, note if 0 > a > -(b*b) then you can merely * compute the reduction as -1 * mp_reduce(mp_abs(a)) [pseudo code]. */ int mp_reduce(mp_int *a, mp_int *b, mp_int *c); /* setups the montgomery reduction */ int mp_montgomery_setup(mp_int *a, mp_digit *mp); /* computes a = B**n mod b without division or multiplication useful for * normalizing numbers in a Montgomery system. */ int mp_montgomery_calc_normalization(mp_int *a, mp_int *b); /* computes x/R == x (mod N) via Montgomery Reduction */ int mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp); /* returns 1 if a is a valid DR modulus */ int mp_dr_is_modulus(mp_int *a); /* sets the value of "d" required for mp_dr_reduce */ void mp_dr_setup(mp_int *a, mp_digit *d); /* reduces a modulo b using the Diminished Radix method */ int mp_dr_reduce(mp_int *a, mp_int *b, mp_digit mp); /* returns true if a can be reduced with mp_reduce_2k */ int mp_reduce_is_2k(mp_int *a); /* determines k value for 2k reduction */ int mp_reduce_2k_setup(mp_int *a, mp_digit *d); /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */ int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d); /* returns true if a can be reduced with mp_reduce_2k_l */ int mp_reduce_is_2k_l(mp_int *a); /* determines k value for 2k reduction */ int mp_reduce_2k_setup_l(mp_int *a, mp_int *d); /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */ int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d); /* d = a**b (mod c) */ int mp_exptmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d); /* ---> Primes <--- */ /* number of primes */ #ifdef MP_8BIT #define PRIME_SIZE 31 #else #define PRIME_SIZE 256 #endif /* table of first PRIME_SIZE primes */ extern const mp_digit ltm_prime_tab[]; /* result=1 if a is divisible by one of the first PRIME_SIZE primes */ int mp_prime_is_divisible(mp_int *a, int *result); /* performs one Fermat test of "a" using base "b". * Sets result to 0 if composite or 1 if probable prime */ int mp_prime_fermat(mp_int *a, mp_int *b, int *result); /* performs one Miller-Rabin test of "a" using base "b". * Sets result to 0 if composite or 1 if probable prime */ int mp_prime_miller_rabin(mp_int *a, mp_int *b, int *result); /* This gives [for a given bit size] the number of trials required * such that Miller-Rabin gives a prob of failure lower than 2^-96 */ int mp_prime_rabin_miller_trials(int size); /* performs t rounds of Miller-Rabin on "a" using the first * t prime bases. Also performs an initial sieve of trial * division. Determines if "a" is prime with probability * of error no more than (1/4)**t. * * Sets result to 1 if probably prime, 0 otherwise */ int mp_prime_is_prime(mp_int *a, int t, int *result); /* finds the next prime after the number "a" using "t" trials * of Miller-Rabin. * * bbs_style = 1 means the prime must be congruent to 3 mod 4 */ int mp_prime_next_prime(mp_int *a, int t, int bbs_style); /* makes a truly random prime of a given size (bytes), * call with bbs = 1 if you want it to be congruent to 3 mod 4 * * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself * so it can be NULL * * The prime generated will be larger than 2^(8*size). */ #define mp_prime_random(a, t, size, bbs, cb, dat) mp_prime_random_ex(a, t, ((size) * 8) + 1, (bbs==1)?LTM_PRIME_BBS:0, cb, dat) /* makes a truly random prime of a given size (bits), * * Flags are as follows: * * LTM_PRIME_BBS - make prime congruent to 3 mod 4 * LTM_PRIME_SAFE - make sure (p-1)/2 is prime as well (implies LTM_PRIME_BBS) * LTM_PRIME_2MSB_OFF - make the 2nd highest bit zero * LTM_PRIME_2MSB_ON - make the 2nd highest bit one * * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself * so it can be NULL * */ int mp_prime_random_ex(mp_int *a, int t, int size, int flags, ltm_prime_callback cb, void *dat); /* ---> radix conversion <--- */ int mp_count_bits(mp_int *a); int mp_unsigned_bin_size(mp_int *a); int mp_read_unsigned_bin(mp_int *a, const unsigned char *b, int c); int mp_to_unsigned_bin(mp_int *a, unsigned char *b); int mp_to_unsigned_bin_n (mp_int * a, unsigned char *b, unsigned long *outlen); int mp_signed_bin_size(mp_int *a); int mp_read_signed_bin(mp_int *a, const unsigned char *b, int c); int mp_to_signed_bin(mp_int *a, unsigned char *b); int mp_to_signed_bin_n (mp_int * a, unsigned char *b, unsigned long *outlen); int mp_read_radix(mp_int *a, const char *str, int radix); int mp_toradix(mp_int *a, char *str, int radix); int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen); int mp_radix_size(mp_int *a, int radix, int *size); int mp_fread(mp_int *a, int radix, FILE *stream); int mp_fwrite(mp_int *a, int radix, FILE *stream); #define mp_read_raw(mp, str, len) mp_read_signed_bin((mp), (str), (len)) #define mp_raw_size(mp) mp_signed_bin_size(mp) #define mp_toraw(mp, str) mp_to_signed_bin((mp), (str)) #define mp_read_mag(mp, str, len) mp_read_unsigned_bin((mp), (str), (len)) #define mp_mag_size(mp) mp_unsigned_bin_size(mp) #define mp_tomag(mp, str) mp_to_unsigned_bin((mp), (str)) #define mp_tobinary(M, S) mp_toradix((M), (S), 2) #define mp_tooctal(M, S) mp_toradix((M), (S), 8) #define mp_todecimal(M, S) mp_toradix((M), (S), 10) #define mp_tohex(M, S) mp_toradix((M), (S), 16) /* lowlevel functions, do not call! */ int s_mp_add(mp_int *a, mp_int *b, mp_int *c); int s_mp_sub(mp_int *a, mp_int *b, mp_int *c); #define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1) int fast_s_mp_mul_digs(mp_int *a, mp_int *b, mp_int *c, int digs); int s_mp_mul_digs(mp_int *a, mp_int *b, mp_int *c, int digs); int fast_s_mp_mul_high_digs(mp_int *a, mp_int *b, mp_int *c, int digs); int s_mp_mul_high_digs(mp_int *a, mp_int *b, mp_int *c, int digs); int fast_s_mp_sqr(mp_int *a, mp_int *b); int s_mp_sqr(mp_int *a, mp_int *b); int mp_karatsuba_mul(mp_int *a, mp_int *b, mp_int *c); int mp_toom_mul(mp_int *a, mp_int *b, mp_int *c); int mp_karatsuba_sqr(mp_int *a, mp_int *b); int mp_toom_sqr(mp_int *a, mp_int *b); int fast_mp_invmod(mp_int *a, mp_int *b, mp_int *c); int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c); int fast_mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp); int mp_exptmod_fast(mp_int *G, mp_int *X, mp_int *P, mp_int *Y, int mode); int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int mode); void bn_reverse(unsigned char *s, int len); extern const char *mp_s_rmap; #ifdef __cplusplus } #endif #endif /* $Source$ */ /* $Revision: 0.39 $ */ /* $Date: 2006-04-06 19:49:59 +0000 $ */ ================================================ FILE: ios/JKBigInteger/LibTomMath/tommath_class.h ================================================ #if !(defined(LTM1) && defined(LTM2) && defined(LTM3)) #if defined(LTM2) #define LTM3 #endif #if defined(LTM1) #define LTM2 #endif #define LTM1 #if defined(LTM_ALL) #define BN_ERROR_C #define BN_FAST_MP_INVMOD_C #define BN_FAST_MP_MONTGOMERY_REDUCE_C #define BN_FAST_S_MP_MUL_DIGS_C #define BN_FAST_S_MP_MUL_HIGH_DIGS_C #define BN_FAST_S_MP_SQR_C #define BN_MP_2EXPT_C #define BN_MP_ABS_C #define BN_MP_ADD_C #define BN_MP_ADD_D_C #define BN_MP_ADDMOD_C #define BN_MP_AND_C #define BN_MP_CLAMP_C #define BN_MP_CLEAR_C #define BN_MP_CLEAR_MULTI_C #define BN_MP_CMP_C #define BN_MP_CMP_D_C #define BN_MP_CMP_MAG_C #define BN_MP_CNT_LSB_C #define BN_MP_COPY_C #define BN_MP_COUNT_BITS_C #define BN_MP_DIV_C #define BN_MP_DIV_2_C #define BN_MP_DIV_2D_C #define BN_MP_DIV_3_C #define BN_MP_DIV_D_C #define BN_MP_DR_IS_MODULUS_C #define BN_MP_DR_REDUCE_C #define BN_MP_DR_SETUP_C #define BN_MP_EXCH_C #define BN_MP_EXPT_D_C #define BN_MP_EXPTMOD_C #define BN_MP_EXPTMOD_FAST_C #define BN_MP_EXTEUCLID_C #define BN_MP_FREAD_C #define BN_MP_FWRITE_C #define BN_MP_GCD_C #define BN_MP_GET_INT_C #define BN_MP_GROW_C #define BN_MP_INIT_C #define BN_MP_INIT_COPY_C #define BN_MP_INIT_MULTI_C #define BN_MP_INIT_SET_C #define BN_MP_INIT_SET_INT_C #define BN_MP_INIT_SIZE_C #define BN_MP_INVMOD_C #define BN_MP_INVMOD_SLOW_C #define BN_MP_IS_SQUARE_C #define BN_MP_JACOBI_C #define BN_MP_KARATSUBA_MUL_C #define BN_MP_KARATSUBA_SQR_C #define BN_MP_LCM_C #define BN_MP_LSHD_C #define BN_MP_MOD_C #define BN_MP_MOD_2D_C #define BN_MP_MOD_D_C #define BN_MP_MONTGOMERY_CALC_NORMALIZATION_C #define BN_MP_MONTGOMERY_REDUCE_C #define BN_MP_MONTGOMERY_SETUP_C #define BN_MP_MUL_C #define BN_MP_MUL_2_C #define BN_MP_MUL_2D_C #define BN_MP_MUL_D_C #define BN_MP_MULMOD_C #define BN_MP_N_ROOT_C #define BN_MP_NEG_C #define BN_MP_OR_C #define BN_MP_PRIME_FERMAT_C #define BN_MP_PRIME_IS_DIVISIBLE_C #define BN_MP_PRIME_IS_PRIME_C #define BN_MP_PRIME_MILLER_RABIN_C #define BN_MP_PRIME_NEXT_PRIME_C #define BN_MP_PRIME_RABIN_MILLER_TRIALS_C #define BN_MP_PRIME_RANDOM_EX_C #define BN_MP_RADIX_SIZE_C #define BN_MP_RADIX_SMAP_C #define BN_MP_RAND_C #define BN_MP_READ_RADIX_C #define BN_MP_READ_SIGNED_BIN_C #define BN_MP_READ_UNSIGNED_BIN_C #define BN_MP_REDUCE_C #define BN_MP_REDUCE_2K_C #define BN_MP_REDUCE_2K_L_C #define BN_MP_REDUCE_2K_SETUP_C #define BN_MP_REDUCE_2K_SETUP_L_C #define BN_MP_REDUCE_IS_2K_C #define BN_MP_REDUCE_IS_2K_L_C #define BN_MP_REDUCE_SETUP_C #define BN_MP_RSHD_C #define BN_MP_SET_C #define BN_MP_SET_INT_C #define BN_MP_SHRINK_C #define BN_MP_SIGNED_BIN_SIZE_C #define BN_MP_SQR_C #define BN_MP_SQRMOD_C #define BN_MP_SQRT_C #define BN_MP_SUB_C #define BN_MP_SUB_D_C #define BN_MP_SUBMOD_C #define BN_MP_TO_SIGNED_BIN_C #define BN_MP_TO_SIGNED_BIN_N_C #define BN_MP_TO_UNSIGNED_BIN_C #define BN_MP_TO_UNSIGNED_BIN_N_C #define BN_MP_TOOM_MUL_C #define BN_MP_TOOM_SQR_C #define BN_MP_TORADIX_C #define BN_MP_TORADIX_N_C #define BN_MP_UNSIGNED_BIN_SIZE_C #define BN_MP_XOR_C #define BN_MP_ZERO_C #define BN_PRIME_TAB_C #define BN_REVERSE_C #define BN_S_MP_ADD_C #define BN_S_MP_EXPTMOD_C #define BN_S_MP_MUL_DIGS_C #define BN_S_MP_MUL_HIGH_DIGS_C #define BN_S_MP_SQR_C #define BN_S_MP_SUB_C #define BNCORE_C #endif #if defined(BN_ERROR_C) #define BN_MP_ERROR_TO_STRING_C #endif #if defined(BN_FAST_MP_INVMOD_C) #define BN_MP_ISEVEN_C #define BN_MP_INIT_MULTI_C #define BN_MP_COPY_C #define BN_MP_MOD_C #define BN_MP_SET_C #define BN_MP_DIV_2_C #define BN_MP_ISODD_C #define BN_MP_SUB_C #define BN_MP_CMP_C #define BN_MP_ISZERO_C #define BN_MP_CMP_D_C #define BN_MP_ADD_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_MULTI_C #endif #if defined(BN_FAST_MP_MONTGOMERY_REDUCE_C) #define BN_MP_GROW_C #define BN_MP_RSHD_C #define BN_MP_CLAMP_C #define BN_MP_CMP_MAG_C #define BN_S_MP_SUB_C #endif #if defined(BN_FAST_S_MP_MUL_DIGS_C) #define BN_MP_GROW_C #define BN_MP_CLAMP_C #endif #if defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C) #define BN_MP_GROW_C #define BN_MP_CLAMP_C #endif #if defined(BN_FAST_S_MP_SQR_C) #define BN_MP_GROW_C #define BN_MP_CLAMP_C #endif #if defined(BN_MP_2EXPT_C) #define BN_MP_ZERO_C #define BN_MP_GROW_C #endif #if defined(BN_MP_ABS_C) #define BN_MP_COPY_C #endif #if defined(BN_MP_ADD_C) #define BN_S_MP_ADD_C #define BN_MP_CMP_MAG_C #define BN_S_MP_SUB_C #endif #if defined(BN_MP_ADD_D_C) #define BN_MP_GROW_C #define BN_MP_SUB_D_C #define BN_MP_CLAMP_C #endif #if defined(BN_MP_ADDMOD_C) #define BN_MP_INIT_C #define BN_MP_ADD_C #define BN_MP_CLEAR_C #define BN_MP_MOD_C #endif #if defined(BN_MP_AND_C) #define BN_MP_INIT_COPY_C #define BN_MP_CLAMP_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_CLAMP_C) #endif #if defined(BN_MP_CLEAR_C) #endif #if defined(BN_MP_CLEAR_MULTI_C) #define BN_MP_CLEAR_C #endif #if defined(BN_MP_CMP_C) #define BN_MP_CMP_MAG_C #endif #if defined(BN_MP_CMP_D_C) #endif #if defined(BN_MP_CMP_MAG_C) #endif #if defined(BN_MP_CNT_LSB_C) #define BN_MP_ISZERO_C #endif #if defined(BN_MP_COPY_C) #define BN_MP_GROW_C #endif #if defined(BN_MP_COUNT_BITS_C) #endif #if defined(BN_MP_DIV_C) #define BN_MP_ISZERO_C #define BN_MP_CMP_MAG_C #define BN_MP_COPY_C #define BN_MP_ZERO_C #define BN_MP_INIT_MULTI_C #define BN_MP_SET_C #define BN_MP_COUNT_BITS_C #define BN_MP_ABS_C #define BN_MP_MUL_2D_C #define BN_MP_CMP_C #define BN_MP_SUB_C #define BN_MP_ADD_C #define BN_MP_DIV_2D_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_MULTI_C #define BN_MP_INIT_SIZE_C #define BN_MP_INIT_C #define BN_MP_INIT_COPY_C #define BN_MP_LSHD_C #define BN_MP_RSHD_C #define BN_MP_MUL_D_C #define BN_MP_CLAMP_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_DIV_2_C) #define BN_MP_GROW_C #define BN_MP_CLAMP_C #endif #if defined(BN_MP_DIV_2D_C) #define BN_MP_COPY_C #define BN_MP_ZERO_C #define BN_MP_INIT_C #define BN_MP_MOD_2D_C #define BN_MP_CLEAR_C #define BN_MP_RSHD_C #define BN_MP_CLAMP_C #define BN_MP_EXCH_C #endif #if defined(BN_MP_DIV_3_C) #define BN_MP_INIT_SIZE_C #define BN_MP_CLAMP_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_DIV_D_C) #define BN_MP_ISZERO_C #define BN_MP_COPY_C #define BN_MP_DIV_2D_C #define BN_MP_DIV_3_C #define BN_MP_INIT_SIZE_C #define BN_MP_CLAMP_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_DR_IS_MODULUS_C) #endif #if defined(BN_MP_DR_REDUCE_C) #define BN_MP_GROW_C #define BN_MP_CLAMP_C #define BN_MP_CMP_MAG_C #define BN_S_MP_SUB_C #endif #if defined(BN_MP_DR_SETUP_C) #endif #if defined(BN_MP_EXCH_C) #endif #if defined(BN_MP_EXPT_D_C) #define BN_MP_INIT_COPY_C #define BN_MP_SET_C #define BN_MP_SQR_C #define BN_MP_CLEAR_C #define BN_MP_MUL_C #endif #if defined(BN_MP_EXPTMOD_C) #define BN_MP_INIT_C #define BN_MP_INVMOD_C #define BN_MP_CLEAR_C #define BN_MP_ABS_C #define BN_MP_CLEAR_MULTI_C #define BN_MP_REDUCE_IS_2K_L_C #define BN_S_MP_EXPTMOD_C #define BN_MP_DR_IS_MODULUS_C #define BN_MP_REDUCE_IS_2K_C #define BN_MP_ISODD_C #define BN_MP_EXPTMOD_FAST_C #endif #if defined(BN_MP_EXPTMOD_FAST_C) #define BN_MP_COUNT_BITS_C #define BN_MP_INIT_C #define BN_MP_CLEAR_C #define BN_MP_MONTGOMERY_SETUP_C #define BN_FAST_MP_MONTGOMERY_REDUCE_C #define BN_MP_MONTGOMERY_REDUCE_C #define BN_MP_DR_SETUP_C #define BN_MP_DR_REDUCE_C #define BN_MP_REDUCE_2K_SETUP_C #define BN_MP_REDUCE_2K_C #define BN_MP_MONTGOMERY_CALC_NORMALIZATION_C #define BN_MP_MULMOD_C #define BN_MP_SET_C #define BN_MP_MOD_C #define BN_MP_COPY_C #define BN_MP_SQR_C #define BN_MP_MUL_C #define BN_MP_EXCH_C #endif #if defined(BN_MP_EXTEUCLID_C) #define BN_MP_INIT_MULTI_C #define BN_MP_SET_C #define BN_MP_COPY_C #define BN_MP_ISZERO_C #define BN_MP_DIV_C #define BN_MP_MUL_C #define BN_MP_SUB_C #define BN_MP_NEG_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_MULTI_C #endif #if defined(BN_MP_FREAD_C) #define BN_MP_ZERO_C #define BN_MP_S_RMAP_C #define BN_MP_MUL_D_C #define BN_MP_ADD_D_C #define BN_MP_CMP_D_C #endif #if defined(BN_MP_FWRITE_C) #define BN_MP_RADIX_SIZE_C #define BN_MP_TORADIX_C #endif #if defined(BN_MP_GCD_C) #define BN_MP_ISZERO_C #define BN_MP_ABS_C #define BN_MP_ZERO_C #define BN_MP_INIT_COPY_C #define BN_MP_CNT_LSB_C #define BN_MP_DIV_2D_C #define BN_MP_CMP_MAG_C #define BN_MP_EXCH_C #define BN_S_MP_SUB_C #define BN_MP_MUL_2D_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_GET_INT_C) #endif #if defined(BN_MP_GROW_C) #endif #if defined(BN_MP_INIT_C) #endif #if defined(BN_MP_INIT_COPY_C) #define BN_MP_COPY_C #endif #if defined(BN_MP_INIT_MULTI_C) #define BN_MP_ERR_C #define BN_MP_INIT_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_INIT_SET_C) #define BN_MP_INIT_C #define BN_MP_SET_C #endif #if defined(BN_MP_INIT_SET_INT_C) #define BN_MP_INIT_C #define BN_MP_SET_INT_C #endif #if defined(BN_MP_INIT_SIZE_C) #define BN_MP_INIT_C #endif #if defined(BN_MP_INVMOD_C) #define BN_MP_ISZERO_C #define BN_MP_ISODD_C #define BN_FAST_MP_INVMOD_C #define BN_MP_INVMOD_SLOW_C #endif #if defined(BN_MP_INVMOD_SLOW_C) #define BN_MP_ISZERO_C #define BN_MP_INIT_MULTI_C #define BN_MP_MOD_C #define BN_MP_COPY_C #define BN_MP_ISEVEN_C #define BN_MP_SET_C #define BN_MP_DIV_2_C #define BN_MP_ISODD_C #define BN_MP_ADD_C #define BN_MP_SUB_C #define BN_MP_CMP_C #define BN_MP_CMP_D_C #define BN_MP_CMP_MAG_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_MULTI_C #endif #if defined(BN_MP_IS_SQUARE_C) #define BN_MP_MOD_D_C #define BN_MP_INIT_SET_INT_C #define BN_MP_MOD_C #define BN_MP_GET_INT_C #define BN_MP_SQRT_C #define BN_MP_SQR_C #define BN_MP_CMP_MAG_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_JACOBI_C) #define BN_MP_CMP_D_C #define BN_MP_ISZERO_C #define BN_MP_INIT_COPY_C #define BN_MP_CNT_LSB_C #define BN_MP_DIV_2D_C #define BN_MP_MOD_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_KARATSUBA_MUL_C) #define BN_MP_MUL_C #define BN_MP_INIT_SIZE_C #define BN_MP_CLAMP_C #define BN_MP_SUB_C #define BN_MP_ADD_C #define BN_MP_LSHD_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_KARATSUBA_SQR_C) #define BN_MP_INIT_SIZE_C #define BN_MP_CLAMP_C #define BN_MP_SQR_C #define BN_MP_SUB_C #define BN_S_MP_ADD_C #define BN_MP_LSHD_C #define BN_MP_ADD_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_LCM_C) #define BN_MP_INIT_MULTI_C #define BN_MP_GCD_C #define BN_MP_CMP_MAG_C #define BN_MP_DIV_C #define BN_MP_MUL_C #define BN_MP_CLEAR_MULTI_C #endif #if defined(BN_MP_LSHD_C) #define BN_MP_GROW_C #define BN_MP_RSHD_C #endif #if defined(BN_MP_MOD_C) #define BN_MP_INIT_C #define BN_MP_DIV_C #define BN_MP_CLEAR_C #define BN_MP_ADD_C #define BN_MP_EXCH_C #endif #if defined(BN_MP_MOD_2D_C) #define BN_MP_ZERO_C #define BN_MP_COPY_C #define BN_MP_CLAMP_C #endif #if defined(BN_MP_MOD_D_C) #define BN_MP_DIV_D_C #endif #if defined(BN_MP_MONTGOMERY_CALC_NORMALIZATION_C) #define BN_MP_COUNT_BITS_C #define BN_MP_2EXPT_C #define BN_MP_SET_C #define BN_MP_MUL_2_C #define BN_MP_CMP_MAG_C #define BN_S_MP_SUB_C #endif #if defined(BN_MP_MONTGOMERY_REDUCE_C) #define BN_FAST_MP_MONTGOMERY_REDUCE_C #define BN_MP_GROW_C #define BN_MP_CLAMP_C #define BN_MP_RSHD_C #define BN_MP_CMP_MAG_C #define BN_S_MP_SUB_C #endif #if defined(BN_MP_MONTGOMERY_SETUP_C) #endif #if defined(BN_MP_MUL_C) #define BN_MP_TOOM_MUL_C #define BN_MP_KARATSUBA_MUL_C #define BN_FAST_S_MP_MUL_DIGS_C #define BN_S_MP_MUL_C #define BN_S_MP_MUL_DIGS_C #endif #if defined(BN_MP_MUL_2_C) #define BN_MP_GROW_C #endif #if defined(BN_MP_MUL_2D_C) #define BN_MP_COPY_C #define BN_MP_GROW_C #define BN_MP_LSHD_C #define BN_MP_CLAMP_C #endif #if defined(BN_MP_MUL_D_C) #define BN_MP_GROW_C #define BN_MP_CLAMP_C #endif #if defined(BN_MP_MULMOD_C) #define BN_MP_INIT_C #define BN_MP_MUL_C #define BN_MP_CLEAR_C #define BN_MP_MOD_C #endif #if defined(BN_MP_N_ROOT_C) #define BN_MP_INIT_C #define BN_MP_SET_C #define BN_MP_COPY_C #define BN_MP_EXPT_D_C #define BN_MP_MUL_C #define BN_MP_SUB_C #define BN_MP_MUL_D_C #define BN_MP_DIV_C #define BN_MP_CMP_C #define BN_MP_SUB_D_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_NEG_C) #define BN_MP_COPY_C #define BN_MP_ISZERO_C #endif #if defined(BN_MP_OR_C) #define BN_MP_INIT_COPY_C #define BN_MP_CLAMP_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_PRIME_FERMAT_C) #define BN_MP_CMP_D_C #define BN_MP_INIT_C #define BN_MP_EXPTMOD_C #define BN_MP_CMP_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_PRIME_IS_DIVISIBLE_C) #define BN_MP_MOD_D_C #endif #if defined(BN_MP_PRIME_IS_PRIME_C) #define BN_MP_CMP_D_C #define BN_MP_PRIME_IS_DIVISIBLE_C #define BN_MP_INIT_C #define BN_MP_SET_C #define BN_MP_PRIME_MILLER_RABIN_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_PRIME_MILLER_RABIN_C) #define BN_MP_CMP_D_C #define BN_MP_INIT_COPY_C #define BN_MP_SUB_D_C #define BN_MP_CNT_LSB_C #define BN_MP_DIV_2D_C #define BN_MP_EXPTMOD_C #define BN_MP_CMP_C #define BN_MP_SQRMOD_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_PRIME_NEXT_PRIME_C) #define BN_MP_CMP_D_C #define BN_MP_SET_C #define BN_MP_SUB_D_C #define BN_MP_ISEVEN_C #define BN_MP_MOD_D_C #define BN_MP_INIT_C #define BN_MP_ADD_D_C #define BN_MP_PRIME_MILLER_RABIN_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_PRIME_RABIN_MILLER_TRIALS_C) #endif #if defined(BN_MP_PRIME_RANDOM_EX_C) #define BN_MP_READ_UNSIGNED_BIN_C #define BN_MP_PRIME_IS_PRIME_C #define BN_MP_SUB_D_C #define BN_MP_DIV_2_C #define BN_MP_MUL_2_C #define BN_MP_ADD_D_C #endif #if defined(BN_MP_RADIX_SIZE_C) #define BN_MP_COUNT_BITS_C #define BN_MP_INIT_COPY_C #define BN_MP_ISZERO_C #define BN_MP_DIV_D_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_RADIX_SMAP_C) #define BN_MP_S_RMAP_C #endif #if defined(BN_MP_RAND_C) #define BN_MP_ZERO_C #define BN_MP_ADD_D_C #define BN_MP_LSHD_C #endif #if defined(BN_MP_READ_RADIX_C) #define BN_MP_ZERO_C #define BN_MP_S_RMAP_C #define BN_MP_RADIX_SMAP_C #define BN_MP_MUL_D_C #define BN_MP_ADD_D_C #define BN_MP_ISZERO_C #endif #if defined(BN_MP_READ_SIGNED_BIN_C) #define BN_MP_READ_UNSIGNED_BIN_C #endif #if defined(BN_MP_READ_UNSIGNED_BIN_C) #define BN_MP_GROW_C #define BN_MP_ZERO_C #define BN_MP_MUL_2D_C #define BN_MP_CLAMP_C #endif #if defined(BN_MP_REDUCE_C) #define BN_MP_REDUCE_SETUP_C #define BN_MP_INIT_COPY_C #define BN_MP_RSHD_C #define BN_MP_MUL_C #define BN_S_MP_MUL_HIGH_DIGS_C #define BN_FAST_S_MP_MUL_HIGH_DIGS_C #define BN_MP_MOD_2D_C #define BN_S_MP_MUL_DIGS_C #define BN_MP_SUB_C #define BN_MP_CMP_D_C #define BN_MP_SET_C #define BN_MP_LSHD_C #define BN_MP_ADD_C #define BN_MP_CMP_C #define BN_S_MP_SUB_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_REDUCE_2K_C) #define BN_MP_INIT_C #define BN_MP_COUNT_BITS_C #define BN_MP_DIV_2D_C #define BN_MP_MUL_D_C #define BN_S_MP_ADD_C #define BN_MP_CMP_MAG_C #define BN_S_MP_SUB_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_REDUCE_2K_L_C) #define BN_MP_INIT_C #define BN_MP_COUNT_BITS_C #define BN_MP_DIV_2D_C #define BN_MP_MUL_C #define BN_S_MP_ADD_C #define BN_MP_CMP_MAG_C #define BN_S_MP_SUB_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_REDUCE_2K_SETUP_C) #define BN_MP_INIT_C #define BN_MP_COUNT_BITS_C #define BN_MP_2EXPT_C #define BN_MP_CLEAR_C #define BN_S_MP_SUB_C #endif #if defined(BN_MP_REDUCE_2K_SETUP_L_C) #define BN_MP_INIT_C #define BN_MP_2EXPT_C #define BN_MP_COUNT_BITS_C #define BN_S_MP_SUB_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_REDUCE_IS_2K_C) #define BN_MP_REDUCE_2K_C #define BN_MP_COUNT_BITS_C #endif #if defined(BN_MP_REDUCE_IS_2K_L_C) #endif #if defined(BN_MP_REDUCE_SETUP_C) #define BN_MP_2EXPT_C #define BN_MP_DIV_C #endif #if defined(BN_MP_RSHD_C) #define BN_MP_ZERO_C #endif #if defined(BN_MP_SET_C) #define BN_MP_ZERO_C #endif #if defined(BN_MP_SET_INT_C) #define BN_MP_ZERO_C #define BN_MP_MUL_2D_C #define BN_MP_CLAMP_C #endif #if defined(BN_MP_SHRINK_C) #endif #if defined(BN_MP_SIGNED_BIN_SIZE_C) #define BN_MP_UNSIGNED_BIN_SIZE_C #endif #if defined(BN_MP_SQR_C) #define BN_MP_TOOM_SQR_C #define BN_MP_KARATSUBA_SQR_C #define BN_FAST_S_MP_SQR_C #define BN_S_MP_SQR_C #endif #if defined(BN_MP_SQRMOD_C) #define BN_MP_INIT_C #define BN_MP_SQR_C #define BN_MP_CLEAR_C #define BN_MP_MOD_C #endif #if defined(BN_MP_SQRT_C) #define BN_MP_N_ROOT_C #define BN_MP_ISZERO_C #define BN_MP_ZERO_C #define BN_MP_INIT_COPY_C #define BN_MP_RSHD_C #define BN_MP_DIV_C #define BN_MP_ADD_C #define BN_MP_DIV_2_C #define BN_MP_CMP_MAG_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_SUB_C) #define BN_S_MP_ADD_C #define BN_MP_CMP_MAG_C #define BN_S_MP_SUB_C #endif #if defined(BN_MP_SUB_D_C) #define BN_MP_GROW_C #define BN_MP_ADD_D_C #define BN_MP_CLAMP_C #endif #if defined(BN_MP_SUBMOD_C) #define BN_MP_INIT_C #define BN_MP_SUB_C #define BN_MP_CLEAR_C #define BN_MP_MOD_C #endif #if defined(BN_MP_TO_SIGNED_BIN_C) #define BN_MP_TO_UNSIGNED_BIN_C #endif #if defined(BN_MP_TO_SIGNED_BIN_N_C) #define BN_MP_SIGNED_BIN_SIZE_C #define BN_MP_TO_SIGNED_BIN_C #endif #if defined(BN_MP_TO_UNSIGNED_BIN_C) #define BN_MP_INIT_COPY_C #define BN_MP_ISZERO_C #define BN_MP_DIV_2D_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_TO_UNSIGNED_BIN_N_C) #define BN_MP_UNSIGNED_BIN_SIZE_C #define BN_MP_TO_UNSIGNED_BIN_C #endif #if defined(BN_MP_TOOM_MUL_C) #define BN_MP_INIT_MULTI_C #define BN_MP_MOD_2D_C #define BN_MP_COPY_C #define BN_MP_RSHD_C #define BN_MP_MUL_C #define BN_MP_MUL_2_C #define BN_MP_ADD_C #define BN_MP_SUB_C #define BN_MP_DIV_2_C #define BN_MP_MUL_2D_C #define BN_MP_MUL_D_C #define BN_MP_DIV_3_C #define BN_MP_LSHD_C #define BN_MP_CLEAR_MULTI_C #endif #if defined(BN_MP_TOOM_SQR_C) #define BN_MP_INIT_MULTI_C #define BN_MP_MOD_2D_C #define BN_MP_COPY_C #define BN_MP_RSHD_C #define BN_MP_SQR_C #define BN_MP_MUL_2_C #define BN_MP_ADD_C #define BN_MP_SUB_C #define BN_MP_DIV_2_C #define BN_MP_MUL_2D_C #define BN_MP_MUL_D_C #define BN_MP_DIV_3_C #define BN_MP_LSHD_C #define BN_MP_CLEAR_MULTI_C #endif #if defined(BN_MP_TORADIX_C) #define BN_MP_ISZERO_C #define BN_MP_INIT_COPY_C #define BN_MP_DIV_D_C #define BN_MP_CLEAR_C #define BN_MP_S_RMAP_C #endif #if defined(BN_MP_TORADIX_N_C) #define BN_MP_ISZERO_C #define BN_MP_INIT_COPY_C #define BN_MP_DIV_D_C #define BN_MP_CLEAR_C #define BN_MP_S_RMAP_C #endif #if defined(BN_MP_UNSIGNED_BIN_SIZE_C) #define BN_MP_COUNT_BITS_C #endif #if defined(BN_MP_XOR_C) #define BN_MP_INIT_COPY_C #define BN_MP_CLAMP_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_C #endif #if defined(BN_MP_ZERO_C) #endif #if defined(BN_PRIME_TAB_C) #endif #if defined(BN_REVERSE_C) #endif #if defined(BN_S_MP_ADD_C) #define BN_MP_GROW_C #define BN_MP_CLAMP_C #endif #if defined(BN_S_MP_EXPTMOD_C) #define BN_MP_COUNT_BITS_C #define BN_MP_INIT_C #define BN_MP_CLEAR_C #define BN_MP_REDUCE_SETUP_C #define BN_MP_REDUCE_C #define BN_MP_REDUCE_2K_SETUP_L_C #define BN_MP_REDUCE_2K_L_C #define BN_MP_MOD_C #define BN_MP_COPY_C #define BN_MP_SQR_C #define BN_MP_MUL_C #define BN_MP_SET_C #define BN_MP_EXCH_C #endif #if defined(BN_S_MP_MUL_DIGS_C) #define BN_FAST_S_MP_MUL_DIGS_C #define BN_MP_INIT_SIZE_C #define BN_MP_CLAMP_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_C #endif #if defined(BN_S_MP_MUL_HIGH_DIGS_C) #define BN_FAST_S_MP_MUL_HIGH_DIGS_C #define BN_MP_INIT_SIZE_C #define BN_MP_CLAMP_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_C #endif #if defined(BN_S_MP_SQR_C) #define BN_MP_INIT_SIZE_C #define BN_MP_CLAMP_C #define BN_MP_EXCH_C #define BN_MP_CLEAR_C #endif #if defined(BN_S_MP_SUB_C) #define BN_MP_GROW_C #define BN_MP_CLAMP_C #endif #if defined(BNCORE_C) #endif #ifdef LTM3 #define LTM_LAST #endif #include "tommath_superclass.h" #include "tommath_class.h" #else #define LTM_LAST #endif /* $Source$ */ /* $Revision: 0.36 $ */ /* $Date: 2005-08-01 16:37:28 +0000 $ */ ================================================ FILE: ios/JKBigInteger/LibTomMath/tommath_superclass.h ================================================ /* super class file for PK algos */ /* default ... include all MPI */ #define LTM_ALL /* RSA only (does not support DH/DSA/ECC) */ /* #define SC_RSA_1 */ /* For reference.... On an Athlon64 optimizing for speed... LTM's mpi.o with all functions [striped] is 142KiB in size. */ /* Works for RSA only, mpi.o is 68KiB */ #ifdef SC_RSA_1 #define BN_MP_SHRINK_C #define BN_MP_LCM_C #define BN_MP_PRIME_RANDOM_EX_C #define BN_MP_INVMOD_C #define BN_MP_GCD_C #define BN_MP_MOD_C #define BN_MP_MULMOD_C #define BN_MP_ADDMOD_C #define BN_MP_EXPTMOD_C #define BN_MP_SET_INT_C #define BN_MP_INIT_MULTI_C #define BN_MP_CLEAR_MULTI_C #define BN_MP_UNSIGNED_BIN_SIZE_C #define BN_MP_TO_UNSIGNED_BIN_C #define BN_MP_MOD_D_C #define BN_MP_PRIME_RABIN_MILLER_TRIALS_C #define BN_REVERSE_C #define BN_PRIME_TAB_C /* other modifiers */ #define BN_MP_DIV_SMALL /* Slower division, not critical */ /* here we are on the last pass so we turn things off. The functions classes are still there * but we remove them specifically from the build. This also invokes tweaks in functions * like removing support for even moduli, etc... */ #ifdef LTM_LAST #undef BN_MP_TOOM_MUL_C #undef BN_MP_TOOM_SQR_C #undef BN_MP_KARATSUBA_MUL_C #undef BN_MP_KARATSUBA_SQR_C #undef BN_MP_REDUCE_C #undef BN_MP_REDUCE_SETUP_C #undef BN_MP_DR_IS_MODULUS_C #undef BN_MP_DR_SETUP_C #undef BN_MP_DR_REDUCE_C #undef BN_MP_REDUCE_IS_2K_C #undef BN_MP_REDUCE_2K_SETUP_C #undef BN_MP_REDUCE_2K_C #undef BN_S_MP_EXPTMOD_C #undef BN_MP_DIV_3_C #undef BN_S_MP_MUL_HIGH_DIGS_C #undef BN_FAST_S_MP_MUL_HIGH_DIGS_C #undef BN_FAST_MP_INVMOD_C /* To safely undefine these you have to make sure your RSA key won't exceed the Comba threshold * which is roughly 255 digits [7140 bits for 32-bit machines, 15300 bits for 64-bit machines] * which means roughly speaking you can handle upto 2536-bit RSA keys with these defined without * trouble. */ #undef BN_S_MP_MUL_DIGS_C #undef BN_S_MP_SQR_C #undef BN_MP_MONTGOMERY_REDUCE_C #endif #endif /* $Source$ */ /* $Revision: 0.36 $ */ /* $Date: 2005-08-01 16:37:28 +0000 $ */ ================================================ FILE: ios/RNAWSCognito.h ================================================ #if __has_include("RCTBridgeModule.h") #import "RCTBridgeModule.h" #else #import #endif #if __has_include("RCTLog.h") #import "RCTLog.h" #else #import #endif #if __has_include("RCTUtils.h") #import "RCTUtils.h" #else #import #endif #import "JKBigInteger.h" @interface RNAWSCognito : NSObject @end ================================================ FILE: ios/RNAWSCognito.m ================================================ #import "RNAWSCognito.h" static NSString* N_IN_HEX = @"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; @implementation RNAWSCognito - (dispatch_queue_t)methodQueue { return dispatch_get_main_queue(); } RCT_EXPORT_MODULE() RCT_EXPORT_METHOD(computeModPow:(NSDictionary *)values callback:(RCTResponseSenderBlock)callback) { JKBigInteger *target = [[JKBigInteger alloc] initWithString:values[@"target"] andRadix:16]; JKBigInteger *value = [[JKBigInteger alloc] initWithString:values[@"value"] andRadix:16]; JKBigInteger *modifier = [[JKBigInteger alloc] initWithString:values[@"modifier"] andRadix:16]; JKBigInteger *result = [target pow:value andMod:modifier]; if (result) { callback(@[[NSNull null], [result stringValueWithRadix:16]]); } else { callback(@[@[RCTMakeError(@"computeModPow error", nil, nil)], [NSNull null]]); } } RCT_EXPORT_METHOD(computeS:(NSDictionary *)values callback:(RCTResponseSenderBlock)callback) { JKBigInteger *N = [[JKBigInteger alloc] initWithString:N_IN_HEX andRadix:16]; JKBigInteger *g = [[JKBigInteger alloc] initWithString:values[@"g"] andRadix:16]; JKBigInteger *x = [[JKBigInteger alloc] initWithString:values[@"x"] andRadix:16]; JKBigInteger *k = [[JKBigInteger alloc] initWithString:values[@"k"] andRadix:16]; JKBigInteger *a = [[JKBigInteger alloc] initWithString:values[@"a"] andRadix:16]; JKBigInteger *b = [[JKBigInteger alloc] initWithString:values[@"b"] andRadix:16]; JKBigInteger *u = [[JKBigInteger alloc] initWithString:values[@"u"] andRadix:16]; JKBigInteger *exp = [a add:[u multiply:x]]; JKBigInteger *base = [b subtract:[k multiply:[g pow:x andMod:N]]]; base = [self mod:base divisor:N]; JKBigInteger *result = [base pow:exp andMod:N]; result = [self mod:result divisor:N]; if (result) { callback(@[[NSNull null], [result stringValueWithRadix:16]]); } else { callback(@[@[RCTMakeError(@"computeS error", nil, nil)], [NSNull null]]); } } - (JKBigInteger*) mod:(JKBigInteger*)dividend divisor:(JKBigInteger*) divisor { return [[divisor add:[dividend remainder:divisor]] remainder:divisor]; } @end ================================================ FILE: ios/RNAWSCognito.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ B3E7B58A1CC2AC0600A0062D /* RNAWSCognito.m in Sources */ = {isa = PBXBuildFile; fileRef = B3E7B5891CC2AC0600A0062D /* RNAWSCognito.m */; }; E2C4A2A31EAEEA5500F05BD3 /* JKBigDecimal.m in Sources */ = {isa = PBXBuildFile; fileRef = E2C4A29B1EAEEA5500F05BD3 /* JKBigDecimal.m */; }; E2C4A2A41EAEEA5500F05BD3 /* JKBigInteger.m in Sources */ = {isa = PBXBuildFile; fileRef = E2C4A29D1EAEEA5500F05BD3 /* JKBigInteger.m */; }; E2C4A2A51EAEEA5500F05BD3 /* tommath.c in Sources */ = {isa = PBXBuildFile; fileRef = E2C4A29F1EAEEA5500F05BD3 /* tommath.c */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ 58B511D91A9E6C8500147676 /* CopyFiles */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = "include/$(PRODUCT_NAME)"; dstSubfolderSpec = 16; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 134814201AA4EA6300B7C361 /* libRNAWSCognito.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRNAWSCognito.a; sourceTree = BUILT_PRODUCTS_DIR; }; B3E7B5881CC2AC0600A0062D /* RNAWSCognito.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNAWSCognito.h; sourceTree = ""; }; B3E7B5891CC2AC0600A0062D /* RNAWSCognito.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNAWSCognito.m; sourceTree = ""; }; E2C4A29A1EAEEA5500F05BD3 /* JKBigDecimal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JKBigDecimal.h; sourceTree = ""; }; E2C4A29B1EAEEA5500F05BD3 /* JKBigDecimal.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JKBigDecimal.m; sourceTree = ""; }; E2C4A29C1EAEEA5500F05BD3 /* JKBigInteger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JKBigInteger.h; sourceTree = ""; }; E2C4A29D1EAEEA5500F05BD3 /* JKBigInteger.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JKBigInteger.m; sourceTree = ""; }; E2C4A29F1EAEEA5500F05BD3 /* tommath.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tommath.c; sourceTree = ""; }; E2C4A2A01EAEEA5500F05BD3 /* tommath.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tommath.h; sourceTree = ""; }; E2C4A2A11EAEEA5500F05BD3 /* tommath_class.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tommath_class.h; sourceTree = ""; }; E2C4A2A21EAEEA5500F05BD3 /* tommath_superclass.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tommath_superclass.h; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 58B511D81A9E6C8500147676 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 134814211AA4EA7D00B7C361 /* Products */ = { isa = PBXGroup; children = ( 134814201AA4EA6300B7C361 /* libRNAWSCognito.a */, ); name = Products; sourceTree = ""; }; 58B511D21A9E6C8500147676 = { isa = PBXGroup; children = ( E2C4A2991EAEEA5500F05BD3 /* JKBigInteger */, B3E7B5881CC2AC0600A0062D /* RNAWSCognito.h */, B3E7B5891CC2AC0600A0062D /* RNAWSCognito.m */, 134814211AA4EA7D00B7C361 /* Products */, ); sourceTree = ""; }; E2C4A2991EAEEA5500F05BD3 /* JKBigInteger */ = { isa = PBXGroup; children = ( E2C4A29A1EAEEA5500F05BD3 /* JKBigDecimal.h */, E2C4A29B1EAEEA5500F05BD3 /* JKBigDecimal.m */, E2C4A29C1EAEEA5500F05BD3 /* JKBigInteger.h */, E2C4A29D1EAEEA5500F05BD3 /* JKBigInteger.m */, E2C4A29E1EAEEA5500F05BD3 /* LibTomMath */, ); path = JKBigInteger; sourceTree = ""; }; E2C4A29E1EAEEA5500F05BD3 /* LibTomMath */ = { isa = PBXGroup; children = ( E2C4A29F1EAEEA5500F05BD3 /* tommath.c */, E2C4A2A01EAEEA5500F05BD3 /* tommath.h */, E2C4A2A11EAEEA5500F05BD3 /* tommath_class.h */, E2C4A2A21EAEEA5500F05BD3 /* tommath_superclass.h */, ); path = LibTomMath; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 58B511DA1A9E6C8500147676 /* RNAWSCognito */ = { isa = PBXNativeTarget; buildConfigurationList = 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "RNAWSCognito" */; buildPhases = ( 58B511D71A9E6C8500147676 /* Sources */, 58B511D81A9E6C8500147676 /* Frameworks */, 58B511D91A9E6C8500147676 /* CopyFiles */, ); buildRules = ( ); dependencies = ( ); name = RNAWSCognito; productName = RCTDataManager; productReference = 134814201AA4EA6300B7C361 /* libRNAWSCognito.a */; productType = "com.apple.product-type.library.static"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 58B511D31A9E6C8500147676 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 0830; ORGANIZATIONNAME = Facebook; TargetAttributes = { 58B511DA1A9E6C8500147676 = { CreatedOnToolsVersion = 6.1.1; }; }; }; buildConfigurationList = 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "RNAWSCognito" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, ); mainGroup = 58B511D21A9E6C8500147676; productRefGroup = 58B511D21A9E6C8500147676; projectDirPath = ""; projectRoot = ""; targets = ( 58B511DA1A9E6C8500147676 /* RNAWSCognito */, ); }; /* End PBXProject section */ /* Begin PBXSourcesBuildPhase section */ 58B511D71A9E6C8500147676 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( E2C4A2A51EAEEA5500F05BD3 /* tommath.c in Sources */, B3E7B58A1CC2AC0600A0062D /* RNAWSCognito.m in Sources */, E2C4A2A41EAEEA5500F05BD3 /* JKBigInteger.m in Sources */, E2C4A2A31EAEEA5500F05BD3 /* JKBigDecimal.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 58B511ED1A9E6C8500147676 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; }; name = Debug; }; 58B511EE1A9E6C8500147676 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; }; name = Release; }; 58B511F01A9E6C8500147676 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { HEADER_SEARCH_PATHS = ( "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", ); LIBRARY_SEARCH_PATHS = "$(inherited)"; OTHER_LDFLAGS = "-ObjC"; PRODUCT_NAME = RNAWSCognito; SKIP_INSTALL = YES; }; name = Debug; }; 58B511F11A9E6C8500147676 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { HEADER_SEARCH_PATHS = ( "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", ); LIBRARY_SEARCH_PATHS = "$(inherited)"; OTHER_LDFLAGS = "-ObjC"; PRODUCT_NAME = RNAWSCognito; SKIP_INSTALL = YES; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "RNAWSCognito" */ = { isa = XCConfigurationList; buildConfigurations = ( 58B511ED1A9E6C8500147676 /* Debug */, 58B511EE1A9E6C8500147676 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "RNAWSCognito" */ = { isa = XCConfigurationList; buildConfigurations = ( 58B511F01A9E6C8500147676 /* Debug */, 58B511F11A9E6C8500147676 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 58B511D31A9E6C8500147676 /* Project object */; } ================================================ FILE: ios/RNAWSCognito.xcodeproj/project.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: lib/AuthenticationDetails.js ================================================ "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var AuthenticationDetails = function () { /** * Constructs a new AuthenticationDetails object * @param {object=} data Creation options. * @param {string} data.Username User being authenticated. * @param {string} data.Password Plain-text password to authenticate with. * @param {(AttributeArg[])?} data.ValidationData Application extra metadata. * @param {(AttributeArg[])?} data.AuthParamaters Authentication paramaters for custom auth. */ function AuthenticationDetails(data) { _classCallCheck(this, AuthenticationDetails); var _ref = data || {}, ValidationData = _ref.ValidationData, Username = _ref.Username, Password = _ref.Password, AuthParameters = _ref.AuthParameters; this.validationData = ValidationData || []; this.authParameters = AuthParameters || []; this.username = Username; this.password = Password; } /** * @returns {string} the record's username */ AuthenticationDetails.prototype.getUsername = function getUsername() { return this.username; }; /** * @returns {string} the record's password */ AuthenticationDetails.prototype.getPassword = function getPassword() { return this.password; }; /** * @returns {Array} the record's validationData */ AuthenticationDetails.prototype.getValidationData = function getValidationData() { return this.validationData; }; /** * @returns {Array} the record's authParameters */ AuthenticationDetails.prototype.getAuthParameters = function getAuthParameters() { return this.authParameters; }; return AuthenticationDetails; }(); exports.default = AuthenticationDetails; ================================================ FILE: lib/AuthenticationHelper.js ================================================ 'use strict'; exports.__esModule = true; var _global = require('aws-sdk/global'); var _BigInteger = require('./BigInteger'); var _BigInteger2 = _interopRequireDefault(_BigInteger); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ var initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF'; var newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.'; /** @class */ var AuthenticationHelper = function () { /** * Constructs a new AuthenticationHelper object * @param {string} PoolName Cognito user pool name. */ function AuthenticationHelper(PoolName) { _classCallCheck(this, AuthenticationHelper); this.N = new _BigInteger2.default(initN, 16); this.g = new _BigInteger2.default('2', 16); this.k = new _BigInteger2.default(this.hexHash('00' + this.N.toString(16) + '0' + this.g.toString(16)), 16); this.smallAValue = this.generateRandomSmallA(); this.getLargeAValue(function () {}); this.infoBits = new _global.util.Buffer('Caldera Derived Key', 'utf8'); this.poolName = PoolName; } /** * @returns {BigInteger} small A, a random number */ AuthenticationHelper.prototype.getSmallAValue = function getSmallAValue() { return this.smallAValue; }; /** * @param {nodeCallback} callback Called with (err, largeAValue) * @returns {void} */ AuthenticationHelper.prototype.getLargeAValue = function getLargeAValue(callback) { var _this = this; if (this.largeAValue) { callback(null, this.largeAValue); } else { this.calculateA(this.smallAValue, function (err, largeAValue) { if (err) { callback(err, null); } _this.largeAValue = largeAValue; callback(null, _this.largeAValue); }); } }; /** * helper function to generate a random big integer * @returns {BigInteger} a random value. * @private */ AuthenticationHelper.prototype.generateRandomSmallA = function generateRandomSmallA() { var hexRandom = _global.util.crypto.lib.randomBytes(128).toString('hex'); var randomBigInt = new _BigInteger2.default(hexRandom, 16); var smallABigInt = randomBigInt.mod(this.N); return smallABigInt; }; /** * helper function to generate a random string * @returns {string} a random value. * @private */ AuthenticationHelper.prototype.generateRandomString = function generateRandomString() { return _global.util.crypto.lib.randomBytes(40).toString('base64'); }; /** * @returns {string} Generated random value included in password hash. */ AuthenticationHelper.prototype.getRandomPassword = function getRandomPassword() { return this.randomPassword; }; /** * @returns {string} Generated random value included in devices hash. */ AuthenticationHelper.prototype.getSaltDevices = function getSaltDevices() { return this.SaltToHashDevices; }; /** * @returns {string} Value used to verify devices. */ AuthenticationHelper.prototype.getVerifierDevices = function getVerifierDevices() { return this.verifierDevices; }; /** * Generate salts and compute verifier. * @param {string} deviceGroupKey Devices to generate verifier for. * @param {string} username User to generate verifier for. * @param {nodeCallback} callback Called with (err, null) * @returns {void} */ AuthenticationHelper.prototype.generateHashDevice = function generateHashDevice(deviceGroupKey, username, callback) { var _this2 = this; this.randomPassword = this.generateRandomString(); var combinedString = '' + deviceGroupKey + username + ':' + this.randomPassword; var hashedString = this.hash(combinedString); var hexRandom = _global.util.crypto.lib.randomBytes(16).toString('hex'); this.SaltToHashDevices = this.padHex(new _BigInteger2.default(hexRandom, 16)); this.g.modPow(new _BigInteger2.default(this.hexHash(this.SaltToHashDevices + hashedString), 16), this.N, function (err, verifierDevicesNotPadded) { if (err) { callback(err, null); } _this2.verifierDevices = _this2.padHex(verifierDevicesNotPadded); callback(null, null); }); }; /** * Calculate the client's public value A = g^a%N * with the generated random number a * @param {BigInteger} a Randomly generated small A. * @param {nodeCallback} callback Called with (err, largeAValue) * @returns {void} * @private */ AuthenticationHelper.prototype.calculateA = function calculateA(a, callback) { var _this3 = this; this.g.modPow(a, this.N, function (err, A) { if (err) { callback(err, null); } if (A.mod(_this3.N).equals(_BigInteger2.default.ZERO)) { callback(new Error('Illegal paramater. A mod N cannot be 0.'), null); } callback(null, A); }); }; /** * Calculate the client's value U which is the hash of A and B * @param {BigInteger} A Large A value. * @param {BigInteger} B Server B value. * @returns {BigInteger} Computed U value. * @private */ AuthenticationHelper.prototype.calculateU = function calculateU(A, B) { this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B)); var finalU = new _BigInteger2.default(this.UHexHash, 16); return finalU; }; /** * Calculate a hash from a bitArray * @param {Buffer} buf Value to hash. * @returns {String} Hex-encoded hash. * @private */ AuthenticationHelper.prototype.hash = function hash(buf) { var hashHex = _global.util.crypto.sha256(buf, 'hex'); return new Array(64 - hashHex.length).join('0') + hashHex; }; /** * Calculate a hash from a hex string * @param {String} hexStr Value to hash. * @returns {String} Hex-encoded hash. * @private */ AuthenticationHelper.prototype.hexHash = function hexHash(hexStr) { return this.hash(new _global.util.Buffer(hexStr, 'hex')); }; /** * Standard hkdf algorithm * @param {Buffer} ikm Input key material. * @param {Buffer} salt Salt value. * @returns {Buffer} Strong key material. * @private */ AuthenticationHelper.prototype.computehkdf = function computehkdf(ikm, salt) { var prk = _global.util.crypto.hmac(salt, ikm, 'buffer', 'sha256'); var infoBitsUpdate = _global.util.buffer.concat([this.infoBits, new _global.util.Buffer(String.fromCharCode(1), 'utf8')]); var hmac = _global.util.crypto.hmac(prk, infoBitsUpdate, 'buffer', 'sha256'); return hmac.slice(0, 16); }; /** * Calculates the final hkdf based on computed S value, and computed U value and the key * @param {String} username Username. * @param {String} password Password. * @param {BigInteger} serverBValue Server B value. * @param {BigInteger} salt Generated salt. * @param {nodeCallback} callback Called with (err, hkdfValue) * @returns {void} */ AuthenticationHelper.prototype.getPasswordAuthenticationKey = function getPasswordAuthenticationKey(username, password, serverBValue, salt, callback) { var _this4 = this; if (serverBValue.mod(this.N).equals(_BigInteger2.default.ZERO)) { throw new Error('B cannot be zero.'); } this.UValue = this.calculateU(this.largeAValue, serverBValue); if (this.UValue.equals(_BigInteger2.default.ZERO)) { throw new Error('U cannot be zero.'); } var usernamePassword = '' + this.poolName + username + ':' + password; var usernamePasswordHash = this.hash(usernamePassword); var xValue = new _BigInteger2.default(this.hexHash(this.padHex(salt) + usernamePasswordHash), 16); this.calculateS(xValue, serverBValue, function (err, sValue) { if (err) { callback(err, null); } var hkdf = _this4.computehkdf(new _global.util.Buffer(_this4.padHex(sValue), 'hex'), new _global.util.Buffer(_this4.padHex(_this4.UValue.toString(16)), 'hex')); callback(null, hkdf); }); }; /** * Calculates the S value used in getPasswordAuthenticationKey * @param {BigInteger} xValue Salted password hash value. * @param {BigInteger} serverBValue Server B value. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ AuthenticationHelper.prototype.calculateS = function calculateS(xValue, serverBValue, callback) { var _this5 = this; this.g.modPow(xValue, this.N, function (err, gModPowXN) { if (err) { callback(err, null); } var intValue2 = serverBValue.subtract(_this5.k.multiply(gModPowXN)); intValue2.modPow(_this5.smallAValue.add(_this5.UValue.multiply(xValue)), _this5.N, function (err2, result) { if (err2) { callback(err2, null); } callback(null, result.mod(_this5.N)); }); }); }; /** * Return constant newPasswordRequiredChallengeUserAttributePrefix * @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value */ AuthenticationHelper.prototype.getNewPasswordRequiredChallengeUserAttributePrefix = function getNewPasswordRequiredChallengeUserAttributePrefix() { return newPasswordRequiredChallengeUserAttributePrefix; }; /** * Converts a BigInteger (or hex string) to hex format padded with zeroes for hashing * @param {BigInteger|String} bigInt Number or string to pad. * @returns {String} Padded hex string. */ AuthenticationHelper.prototype.padHex = function padHex(bigInt) { var hashStr = bigInt.toString(16); if (hashStr.length % 2 === 1) { hashStr = '0' + hashStr; } else if ('89ABCDEFabcdef'.indexOf(hashStr[0]) !== -1) { hashStr = '00' + hashStr; } return hashStr; }; return AuthenticationHelper; }(); exports.default = AuthenticationHelper; ================================================ FILE: lib/BigInteger.js ================================================ "use strict"; exports.__esModule = true; // A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/ // // All public methods have been removed except the following: // new BigInteger(a, b) (only radix 2, 4, 8, 16 and 32 supported) // toString (only radix 2, 4, 8, 16 and 32 supported) // negate // abs // compareTo // bitLength // mod // equals // add // subtract // multiply // divide // modPow exports.default = BigInteger; /* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ // (public) Constructor function BigInteger(a, b) { if (a != null) this.fromString(a, b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = (canary & 0xffffff) == 0xefcafe; // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i, x, w, j, c, n) { while (--n >= 0) { var v = x * this[i++] + w[j] + c; c = Math.floor(v / 0x4000000); w[j++] = v & 0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i, x, w, j, c, n) { var xl = x & 0x7fff, xh = x >> 15; while (--n >= 0) { var l = this[i] & 0x7fff; var h = this[i++] >> 15; var m = xh * l + h * xl; l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); w[j++] = l & 0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i, x, w, j, c, n) { var xl = x & 0x3fff, xh = x >> 14; while (--n >= 0) { var l = this[i] & 0x3fff; var h = this[i++] >> 14; var m = xh * l + h * xl; l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; c = (l >> 28) + (m >> 14) + xh * h; w[j++] = l & 0xfffffff; } return c; } var inBrowser = typeof navigator !== "undefined"; if (inBrowser && j_lm && navigator.appName == "Microsoft Internet Explorer") { BigInteger.prototype.am = am2; dbits = 30; } else if (inBrowser && j_lm && navigator.appName != "Netscape") { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = (1 << dbits) - 1; BigInteger.prototype.DV = 1 << dbits; var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2, BI_FP); BigInteger.prototype.F1 = BI_FP - dbits; BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = new Array(); var rr, vv; rr = "0".charCodeAt(0); for (vv = 0; vv <= 9; ++vv) { BI_RC[rr++] = vv; }rr = "a".charCodeAt(0); for (vv = 10; vv < 36; ++vv) { BI_RC[rr++] = vv; }rr = "A".charCodeAt(0); for (vv = 10; vv < 36; ++vv) { BI_RC[rr++] = vv; }function int2char(n) { return BI_RM.charAt(n); } function intAt(s, i) { var c = BI_RC[s.charCodeAt(i)]; return c == null ? -1 : c; } // (protected) copy this to r function bnpCopyTo(r) { for (var i = this.t - 1; i >= 0; --i) { r[i] = this[i]; }r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = x < 0 ? -1 : 0; if (x > 0) this[0] = x;else if (x < -1) this[0] = x + this.DV;else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s, b) { var k; if (b == 16) k = 4;else if (b == 8) k = 3;else if (b == 2) k = 1;else if (b == 32) k = 5;else if (b == 4) k = 2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported"); this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while (--i >= 0) { var x = intAt(s, i); if (x < 0) { if (s.charAt(i) == "-") mi = true; continue; } mi = false; if (sh == 0) this[this.t++] = x;else if (sh + k > this.DB) { this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; this[this.t++] = x >> this.DB - sh; } else this[this.t - 1] |= x << sh; sh += k; if (sh >= this.DB) sh -= this.DB; } this.clamp(); if (mi) BigInteger.ZERO.subTo(this, this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s & this.DM; while (this.t > 0 && this[this.t - 1] == c) { --this.t; } } // (public) return string representation in given radix function bnToString(b) { if (this.s < 0) return "-" + this.negate().toString(); var k; if (b == 16) k = 4;else if (b == 8) k = 3;else if (b == 2) k = 1;else if (b == 32) k = 5;else if (b == 4) k = 2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported"); var km = (1 << k) - 1, d, m = false, r = "", i = this.t; var p = this.DB - i * this.DB % k; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) > 0) { m = true; r = int2char(d); } while (i >= 0) { if (p < k) { d = (this[i] & (1 << p) - 1) << k - p; d |= this[--i] >> (p += this.DB - k); } else { d = this[i] >> (p -= k) & km; if (p <= 0) { p += this.DB; --i; } } if (d > 0) m = true; if (m) r += int2char(d); } } return m ? r : "0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; } // (public) |this| function bnAbs() { return this.s < 0 ? this.negate() : this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s - a.s; if (r != 0) return r; var i = this.t; r = i - a.t; if (r != 0) return this.s < 0 ? -r : r; while (--i >= 0) { if ((r = this[i] - a[i]) != 0) return r; }return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if ((t = x >>> 16) != 0) { x = t; r += 16; } if ((t = x >> 8) != 0) { x = t; r += 8; } if ((t = x >> 4) != 0) { x = t; r += 4; } if ((t = x >> 2) != 0) { x = t; r += 2; } if ((t = x >> 1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if (this.t <= 0) return 0; return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM); } // (protected) r = this << n*DB function bnpDLShiftTo(n, r) { var i; for (i = this.t - 1; i >= 0; --i) { r[i + n] = this[i]; }for (i = n - 1; i >= 0; --i) { r[i] = 0; }r.t = this.t + n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n, r) { for (var i = n; i < this.t; ++i) { r[i - n] = this[i]; }r.t = Math.max(this.t - n, 0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n, r) { var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << cbs) - 1; var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; for (i = this.t - 1; i >= 0; --i) { r[i + ds + 1] = this[i] >> cbs | c; c = (this[i] & bm) << bs; } for (i = ds - 1; i >= 0; --i) { r[i] = 0; }r[ds] = c; r.t = this.t + ds + 1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n, r) { r.s = this.s; var ds = Math.floor(n / this.DB); if (ds >= this.t) { r.t = 0; return; } var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << bs) - 1; r[0] = this[ds] >> bs; for (var i = ds + 1; i < this.t; ++i) { r[i - ds - 1] |= (this[i] & bm) << cbs; r[i - ds] = this[i] >> bs; } if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; r.t = this.t - ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { c += this[i] - a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c -= a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c -= a[i]; r[i++] = c & this.DM; c >>= this.DB; } c -= a.s; } r.s = c < 0 ? -1 : 0; if (c < -1) r[i++] = this.DV + c;else if (c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a, r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i + y.t; while (--i >= 0) { r[i] = 0; }for (i = 0; i < y.t; ++i) { r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); }r.s = 0; r.clamp(); if (this.s != a.s) BigInteger.ZERO.subTo(r, r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2 * x.t; while (--i >= 0) { r[i] = 0; }for (i = 0; i < x.t - 1; ++i) { var c = x.am(i, x[i], r, 2 * i, 0, 1); if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { r[i + x.t] -= x.DV; r[i + x.t + 1] = 1; } } if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m, q, r) { var pm = m.abs(); if (pm.t <= 0) return; var pt = this.abs(); if (pt.t < pm.t) { if (q != null) q.fromInt(0); if (r != null) this.copyTo(r); return; } if (r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys - 1]; if (y0 == 0) return; var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; var i = r.t, j = i - ys, t = q == null ? nbi() : q; y.dlShiftTo(j, t); if (r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t, r); } BigInteger.ONE.dlShiftTo(ys, t); t.subTo(y, y); // "negative" y so we can replace sub with am later while (y.t < ys) { y[y.t++] = 0; }while (--j >= 0) { // Estimate quotient digit var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out y.dlShiftTo(j, t); r.subTo(t, r); while (r[i] < --qd) { r.subTo(t, r); } } } if (q != null) { r.drShiftTo(ys, q); if (ts != ms) BigInteger.ZERO.subTo(q, q); } r.t = ys; r.clamp(); if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder if (ts < 0) BigInteger.ZERO.subTo(r, r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); return r; } // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if (this.t < 1) return 0; var x = this[0]; if ((x & 1) == 0) return 0; var y = x & 3; // y == 1/x mod 2^2 y = y * (2 - (x & 0xf) * y) & 0xf; // y == 1/x mod 2^4 y = y * (2 - (x & 0xff) * y) & 0xff; // y == 1/x mod 2^8 y = y * (2 - ((x & 0xffff) * y & 0xffff)) & 0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = y * (2 - x * y % this.DV) % this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return y > 0 ? this.DV - y : -y; } function bnEquals(a) { return this.compareTo(a) == 0; } // (protected) r = this + a function bnpAddTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { c += this[i] + a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c += a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c += a[i]; r[i++] = c & this.DM; c >>= this.DB; } c += a.s; } r.s = c < 0 ? -1 : 0; if (c > 0) r[i++] = c;else if (c < -1) r[i++] = this.DV + c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a, r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a, r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a, r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a, r, null); return r; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp & 0x7fff; this.mph = this.mp >> 15; this.um = (1 << m.DB - 15) - 1; this.mt2 = 2 * m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t, r); r.divRemTo(this.m, null, r); if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while (x.t <= this.mt2) { // pad x so am has enough room later x[x.t++] = 0; }for (var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i] & 0x7fff; var u0 = j * this.mpl + ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & x.DM; // use am to combine the multiply-shift-add into one call j = i + this.m.t; x[j] += this.m.am(0, u0, x, i, 0, this.m.t); // propagate carry while (x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t, x); if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); } // r = "x^2/R mod m"; x != r function montSqrTo(x, r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e, m, callback) { var i = e.bitLength(), k, r = nbv(1), z = new Montgomery(m); if (i <= 0) return r;else if (i < 18) k = 1;else if (i < 48) k = 3;else if (i < 144) k = 4;else if (i < 768) k = 5;else k = 6; // precomputation var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { var g2 = nbi(); z.sqrTo(g[1], g2); while (n <= km) { g[n] = nbi(); z.mulTo(g2, g[n - 2], g[n]); n += 2; } } var j = e.t - 1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j]) - 1; while (j >= 0) { if (i >= k1) w = e[j] >> i - k1 & km;else { w = (e[j] & (1 << i + 1) - 1) << k1 - i; if (j > 0) w |= e[j - 1] >> this.DB + i - k1; } n = k; while ((w & 1) == 0) { w >>= 1; --n; } if ((i -= n) < 0) { i += this.DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n > 1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n > 0) z.sqrTo(r, r2);else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j >= 0 && (e[j] & 1 << i) == 0) { z.sqrTo(r, r2); t = r; r = r2; r2 = t; if (--i < 0) { i = this.DB - 1; --j; } } } var result = z.revert(r); callback(null, result); return result; } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.addTo = bnpAddTo; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.modPow = bnModPow; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); ================================================ FILE: lib/CognitoAccessToken.js ================================================ 'use strict'; exports.__esModule = true; var _CognitoJwtToken2 = require('./CognitoJwtToken'); var _CognitoJwtToken3 = _interopRequireDefault(_CognitoJwtToken2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoAccessToken = function (_CognitoJwtToken) { _inherits(CognitoAccessToken, _CognitoJwtToken); /** * Constructs a new CognitoAccessToken object * @param {string=} AccessToken The JWT access token. */ function CognitoAccessToken() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, AccessToken = _ref.AccessToken; _classCallCheck(this, CognitoAccessToken); return _possibleConstructorReturn(this, _CognitoJwtToken.call(this, AccessToken || '')); } return CognitoAccessToken; }(_CognitoJwtToken3.default); exports.default = CognitoAccessToken; ================================================ FILE: lib/CognitoIdToken.js ================================================ 'use strict'; exports.__esModule = true; var _CognitoJwtToken2 = require('./CognitoJwtToken'); var _CognitoJwtToken3 = _interopRequireDefault(_CognitoJwtToken2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoIdToken = function (_CognitoJwtToken) { _inherits(CognitoIdToken, _CognitoJwtToken); /** * Constructs a new CognitoIdToken object * @param {string=} IdToken The JWT Id token */ function CognitoIdToken() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, IdToken = _ref.IdToken; _classCallCheck(this, CognitoIdToken); return _possibleConstructorReturn(this, _CognitoJwtToken.call(this, IdToken || '')); } return CognitoIdToken; }(_CognitoJwtToken3.default); exports.default = CognitoIdToken; ================================================ FILE: lib/CognitoJwtToken.js ================================================ 'use strict'; exports.__esModule = true; var _global = require('aws-sdk/global'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoJwtToken = function () { /** * Constructs a new CognitoJwtToken object * @param {string=} token The JWT token. */ function CognitoJwtToken(token) { _classCallCheck(this, CognitoJwtToken); // Assign object this.jwtToken = token || ''; this.payload = this.decodePayload(); } /** * @returns {string} the record's token. */ CognitoJwtToken.prototype.getJwtToken = function getJwtToken() { return this.jwtToken; }; /** * @returns {int} the token's expiration (exp member). */ CognitoJwtToken.prototype.getExpiration = function getExpiration() { return this.payload.exp; }; /** * @returns {int} the token's "issued at" (iat member). */ CognitoJwtToken.prototype.getIssuedAt = function getIssuedAt() { return this.payload.iat; }; /** * @returns {object} the token's payload. */ CognitoJwtToken.prototype.decodePayload = function decodePayload() { var payload = this.jwtToken.split('.')[1]; try { return JSON.parse(_global.util.base64.decode(payload).toString('utf8')); } catch (err) { return {}; } }; return CognitoJwtToken; }(); exports.default = CognitoJwtToken; ================================================ FILE: lib/CognitoRefreshToken.js ================================================ 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoRefreshToken = function () { /** * Constructs a new CognitoRefreshToken object * @param {string=} RefreshToken The JWT refresh token. */ function CognitoRefreshToken() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, RefreshToken = _ref.RefreshToken; _classCallCheck(this, CognitoRefreshToken); // Assign object this.token = RefreshToken || ''; } /** * @returns {string} the record's token. */ CognitoRefreshToken.prototype.getToken = function getToken() { return this.token; }; return CognitoRefreshToken; }(); exports.default = CognitoRefreshToken; ================================================ FILE: lib/CognitoUser.js ================================================ 'use strict'; exports.__esModule = true; var _global = require('aws-sdk/global'); var _BigInteger = require('./BigInteger'); var _BigInteger2 = _interopRequireDefault(_BigInteger); var _AuthenticationHelper = require('./AuthenticationHelper'); var _AuthenticationHelper2 = _interopRequireDefault(_AuthenticationHelper); var _CognitoAccessToken = require('./CognitoAccessToken'); var _CognitoAccessToken2 = _interopRequireDefault(_CognitoAccessToken); var _CognitoIdToken = require('./CognitoIdToken'); var _CognitoIdToken2 = _interopRequireDefault(_CognitoIdToken); var _CognitoRefreshToken = require('./CognitoRefreshToken'); var _CognitoRefreshToken2 = _interopRequireDefault(_CognitoRefreshToken); var _CognitoUserSession = require('./CognitoUserSession'); var _CognitoUserSession2 = _interopRequireDefault(_CognitoUserSession); var _DateHelper = require('./DateHelper'); var _DateHelper2 = _interopRequireDefault(_DateHelper); var _CognitoUserAttribute = require('./CognitoUserAttribute'); var _CognitoUserAttribute2 = _interopRequireDefault(_CognitoUserAttribute); var _StorageHelper = require('./StorageHelper'); var _StorageHelper2 = _interopRequireDefault(_StorageHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** * @callback nodeCallback * @template T result * @param {*} err The operation failure reason, or null. * @param {T} result The operation result. */ /** * @callback onFailure * @param {*} err Failure reason. */ /** * @callback onSuccess * @template T result * @param {T} result The operation result. */ /** * @callback mfaRequired * @param {*} details MFA challenge details. */ /** * @callback customChallenge * @param {*} details Custom challenge details. */ /** * @callback inputVerificationCode * @param {*} data Server response. */ /** * @callback authSuccess * @param {CognitoUserSession} session The new session. * @param {bool=} userConfirmationNecessary User must be confirmed. */ /** @class */ var CognitoUser = function () { /** * Constructs a new CognitoUser object * @param {object} data Creation options * @param {string} data.Username The user's username. * @param {CognitoUserPool} data.Pool Pool containing the user. * @param {object} data.Storage Optional storage object. */ function CognitoUser(data) { _classCallCheck(this, CognitoUser); if (data == null || data.Username == null || data.Pool == null) { throw new Error('Username and pool information are required.'); } this.username = data.Username || ''; this.pool = data.Pool; this.Session = null; this.client = data.Pool.client; this.signInUserSession = null; this.authenticationFlowType = 'USER_SRP_AUTH'; this.storage = data.Storage || new _StorageHelper2.default().getStorage(); } /** * Sets the session for this user * @param {CognitoUserSession} signInUserSession the session * @returns {void} */ CognitoUser.prototype.setSignInUserSession = function setSignInUserSession(signInUserSession) { this.clearCachedTokens(); this.signInUserSession = signInUserSession; this.cacheTokens(); }; /** * @returns {CognitoUserSession} the current session for this user */ CognitoUser.prototype.getSignInUserSession = function getSignInUserSession() { return this.signInUserSession; }; /** * @returns {string} the user's username */ CognitoUser.prototype.getUsername = function getUsername() { return this.username; }; /** * @returns {String} the authentication flow type */ CognitoUser.prototype.getAuthenticationFlowType = function getAuthenticationFlowType() { return this.authenticationFlowType; }; /** * sets authentication flow type * @param {string} authenticationFlowType New value. * @returns {void} */ CognitoUser.prototype.setAuthenticationFlowType = function setAuthenticationFlowType(authenticationFlowType) { this.authenticationFlowType = authenticationFlowType; }; /** * This is used for authenticating the user through the custom authentication flow. * @param {AuthenticationDetails} authDetails Contains the authentication data * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.initiateAuth = function initiateAuth(authDetails, callback) { var _this = this; var authParameters = authDetails.getAuthParameters(); authParameters.USERNAME = this.username; var jsonReq = { AuthFlow: 'CUSTOM_AUTH', ClientId: this.pool.getClientId(), AuthParameters: authParameters, ClientMetadata: authDetails.getValidationData() }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('initiateAuth', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } var challengeName = data.ChallengeName; var challengeParameters = data.ChallengeParameters; if (challengeName === 'CUSTOM_CHALLENGE') { _this.Session = data.Session; return callback.customChallenge(challengeParameters); } _this.signInUserSession = _this.getCognitoUserSession(data.AuthenticationResult); _this.cacheTokens(); return callback.onSuccess(_this.signInUserSession); }); }; /** * This is used for authenticating the user. it calls the AuthenticationHelper for SRP related * stuff * @param {AuthenticationDetails} authDetails Contains the authentication data * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {newPasswordRequired} callback.newPasswordRequired new * password and any required attributes are required to continue * @param {mfaRequired} callback.mfaRequired MFA code * required to continue. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.authenticateUser = function authenticateUser(authDetails, callback) { var _this2 = this; var authenticationHelper = new _AuthenticationHelper2.default(this.pool.getUserPoolId().split('_')[1]); var dateHelper = new _DateHelper2.default(); var serverBValue = void 0; var salt = void 0; var authParameters = {}; if (this.deviceKey != null) { authParameters.DEVICE_KEY = this.deviceKey; } authParameters.USERNAME = this.username; authenticationHelper.getLargeAValue(function (errOnAValue, aValue) { // getLargeAValue callback start if (errOnAValue) { callback.onFailure(errOnAValue); } authParameters.SRP_A = aValue.toString(16); if (_this2.authenticationFlowType === 'CUSTOM_AUTH') { authParameters.CHALLENGE_NAME = 'SRP_A'; } var jsonReq = { AuthFlow: _this2.authenticationFlowType, ClientId: _this2.pool.getClientId(), AuthParameters: authParameters, ClientMetadata: authDetails.getValidationData() }; if (_this2.getUserContextData(_this2.username)) { jsonReq.UserContextData = _this2.getUserContextData(_this2.username); } _this2.client.makeUnauthenticatedRequest('initiateAuth', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } var challengeParameters = data.ChallengeParameters; _this2.username = challengeParameters.USER_ID_FOR_SRP; serverBValue = new _BigInteger2.default(challengeParameters.SRP_B, 16); salt = new _BigInteger2.default(challengeParameters.SALT, 16); _this2.getCachedDeviceKeyAndPassword(); authenticationHelper.getPasswordAuthenticationKey(_this2.username, authDetails.getPassword(), serverBValue, salt, function (errOnHkdf, hkdf) { // getPasswordAuthenticationKey callback start if (errOnHkdf) { callback.onFailure(errOnHkdf); } var dateNow = dateHelper.getNowString(); var signatureString = _global.util.crypto.hmac(hkdf, _global.util.buffer.concat([new _global.util.Buffer(_this2.pool.getUserPoolId().split('_')[1], 'utf8'), new _global.util.Buffer(_this2.username, 'utf8'), new _global.util.Buffer(challengeParameters.SECRET_BLOCK, 'base64'), new _global.util.Buffer(dateNow, 'utf8')]), 'base64', 'sha256'); var challengeResponses = {}; challengeResponses.USERNAME = _this2.username; challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK; challengeResponses.TIMESTAMP = dateNow; challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString; if (_this2.deviceKey != null) { challengeResponses.DEVICE_KEY = _this2.deviceKey; } var respondToAuthChallenge = function respondToAuthChallenge(challenge, challengeCallback) { return _this2.client.makeUnauthenticatedRequest('respondToAuthChallenge', challenge, function (errChallenge, dataChallenge) { if (errChallenge && errChallenge.code === 'ResourceNotFoundException' && errChallenge.message.toLowerCase().indexOf('device') !== -1) { challengeResponses.DEVICE_KEY = null; _this2.deviceKey = null; _this2.randomPassword = null; _this2.deviceGroupKey = null; _this2.clearCachedDeviceKeyAndPassword(); return respondToAuthChallenge(challenge, challengeCallback); } return challengeCallback(errChallenge, dataChallenge); }); }; var jsonReqResp = { ChallengeName: 'PASSWORD_VERIFIER', ClientId: _this2.pool.getClientId(), ChallengeResponses: challengeResponses, Session: data.Session }; if (_this2.getUserContextData()) { jsonReqResp.UserContextData = _this2.getUserContextData(); } respondToAuthChallenge(jsonReqResp, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } var challengeName = dataAuthenticate.ChallengeName; if (challengeName === 'NEW_PASSWORD_REQUIRED') { _this2.Session = dataAuthenticate.Session; var userAttributes = null; var rawRequiredAttributes = null; var requiredAttributes = []; var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix(); if (dataAuthenticate.ChallengeParameters) { userAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.userAttributes); rawRequiredAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.requiredAttributes); } if (rawRequiredAttributes) { for (var i = 0; i < rawRequiredAttributes.length; i++) { requiredAttributes[i] = rawRequiredAttributes[i].substr(userAttributesPrefix.length); } } return callback.newPasswordRequired(userAttributes, requiredAttributes); } return _this2.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback); }); return undefined; // getPasswordAuthenticationKey callback end }); return undefined; }); // getLargeAValue callback end }); }; /** * PRIVATE ONLY: This is an internal only method and should not * be directly called by the consumers. * @param {object} dataAuthenticate authentication data * @param {object} authenticationHelper helper created * @param {callback} callback passed on from caller * @returns {void} */ CognitoUser.prototype.authenticateUserInternal = function authenticateUserInternal(dataAuthenticate, authenticationHelper, callback) { var _this3 = this; var challengeName = dataAuthenticate.ChallengeName; var challengeParameters = dataAuthenticate.ChallengeParameters; if (challengeName === 'SMS_MFA') { this.Session = dataAuthenticate.Session; return callback.mfaRequired(challengeName, challengeParameters); } if (challengeName === 'SELECT_MFA_TYPE') { this.Session = dataAuthenticate.Session; return callback.selectMFAType(challengeName, challengeParameters); } if (challengeName === 'MFA_SETUP') { this.Session = dataAuthenticate.Session; return callback.mfaSetup(challengeName, challengeParameters); } if (challengeName === 'SOFTWARE_TOKEN_MFA') { this.Session = dataAuthenticate.Session; return callback.totpRequired(challengeName, challengeParameters); } if (challengeName === 'CUSTOM_CHALLENGE') { this.Session = dataAuthenticate.Session; return callback.customChallenge(challengeParameters); } if (challengeName === 'DEVICE_SRP_AUTH') { this.getDeviceResponse(callback); return undefined; } this.signInUserSession = this.getCognitoUserSession(dataAuthenticate.AuthenticationResult); this.cacheTokens(); var newDeviceMetadata = dataAuthenticate.AuthenticationResult.NewDeviceMetadata; if (newDeviceMetadata == null) { return callback.onSuccess(this.signInUserSession); } authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) { if (errGenHash) { return callback.onFailure(errGenHash); } var deviceSecretVerifierConfig = { Salt: new _global.util.Buffer(authenticationHelper.getSaltDevices(), 'hex').toString('base64'), PasswordVerifier: new _global.util.Buffer(authenticationHelper.getVerifierDevices(), 'hex').toString('base64') }; _this3.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier; _this3.deviceGroupKey = newDeviceMetadata.DeviceGroupKey; _this3.randomPassword = authenticationHelper.getRandomPassword(); _this3.client.makeUnauthenticatedRequest('confirmDevice', { DeviceKey: newDeviceMetadata.DeviceKey, AccessToken: _this3.signInUserSession.getAccessToken().getJwtToken(), DeviceSecretVerifierConfig: deviceSecretVerifierConfig, DeviceName: navigator.userAgent }, function (errConfirm, dataConfirm) { if (errConfirm) { return callback.onFailure(errConfirm); } _this3.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey; _this3.cacheDeviceKeyAndPassword(); if (dataConfirm.UserConfirmationNecessary === true) { return callback.onSuccess(_this3.signInUserSession, dataConfirm.UserConfirmationNecessary); } return callback.onSuccess(_this3.signInUserSession); }); return undefined; }); return undefined; }; /** * This method is user to complete the NEW_PASSWORD_REQUIRED challenge. * Pass the new password with any new user attributes to be updated. * User attribute keys must be of format userAttributes.. * @param {string} newPassword new password for this user * @param {object} requiredAttributeData map with values for all required attributes * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {mfaRequired} callback.mfaRequired MFA code required to continue. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.completeNewPasswordChallenge = function completeNewPasswordChallenge(newPassword, requiredAttributeData, callback) { var _this4 = this; if (!newPassword) { return callback.onFailure(new Error('New password is required.')); } var authenticationHelper = new _AuthenticationHelper2.default(this.pool.getUserPoolId().split('_')[1]); var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix(); var finalUserAttributes = {}; if (requiredAttributeData) { Object.keys(requiredAttributeData).forEach(function (key) { finalUserAttributes[userAttributesPrefix + key] = requiredAttributeData[key]; }); } finalUserAttributes.NEW_PASSWORD = newPassword; finalUserAttributes.USERNAME = this.username; var jsonReq = { ChallengeName: 'NEW_PASSWORD_REQUIRED', ClientId: this.pool.getClientId(), ChallengeResponses: finalUserAttributes, Session: this.Session }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } return _this4.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback); }); return undefined; }; /** * This is used to get a session using device authentication. It is called at the end of user * authentication * * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} * @private */ CognitoUser.prototype.getDeviceResponse = function getDeviceResponse(callback) { var _this5 = this; var authenticationHelper = new _AuthenticationHelper2.default(this.deviceGroupKey); var dateHelper = new _DateHelper2.default(); var authParameters = {}; authParameters.USERNAME = this.username; authParameters.DEVICE_KEY = this.deviceKey; authenticationHelper.getLargeAValue(function (errAValue, aValue) { // getLargeAValue callback start if (errAValue) { callback.onFailure(errAValue); } authParameters.SRP_A = aValue.toString(16); var jsonReq = { ChallengeName: 'DEVICE_SRP_AUTH', ClientId: _this5.pool.getClientId(), ChallengeResponses: authParameters }; if (_this5.getUserContextData()) { jsonReq.UserContextData = _this5.getUserContextData(); } _this5.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } var challengeParameters = data.ChallengeParameters; var serverBValue = new _BigInteger2.default(challengeParameters.SRP_B, 16); var salt = new _BigInteger2.default(challengeParameters.SALT, 16); authenticationHelper.getPasswordAuthenticationKey(_this5.deviceKey, _this5.randomPassword, serverBValue, salt, function (errHkdf, hkdf) { // getPasswordAuthenticationKey callback start if (errHkdf) { return callback.onFailure(errHkdf); } var dateNow = dateHelper.getNowString(); var signatureString = _global.util.crypto.hmac(hkdf, _global.util.buffer.concat([new _global.util.Buffer(_this5.deviceGroupKey, 'utf8'), new _global.util.Buffer(_this5.deviceKey, 'utf8'), new _global.util.Buffer(challengeParameters.SECRET_BLOCK, 'base64'), new _global.util.Buffer(dateNow, 'utf8')]), 'base64', 'sha256'); var challengeResponses = {}; challengeResponses.USERNAME = _this5.username; challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK; challengeResponses.TIMESTAMP = dateNow; challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString; challengeResponses.DEVICE_KEY = _this5.deviceKey; var jsonReqResp = { ChallengeName: 'DEVICE_PASSWORD_VERIFIER', ClientId: _this5.pool.getClientId(), ChallengeResponses: challengeResponses, Session: data.Session }; if (_this5.getUserContextData()) { jsonReqResp.UserContextData = _this5.getUserContextData(); } _this5.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReqResp, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } _this5.signInUserSession = _this5.getCognitoUserSession(dataAuthenticate.AuthenticationResult); _this5.cacheTokens(); return callback.onSuccess(_this5.signInUserSession); }); return undefined; // getPasswordAuthenticationKey callback end }); return undefined; }); // getLargeAValue callback end }); }; /** * This is used for a certain user to confirm the registration by using a confirmation code * @param {string} confirmationCode Code entered by user. * @param {bool} forceAliasCreation Allow migrating from an existing email / phone number. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.confirmRegistration = function confirmRegistration(confirmationCode, forceAliasCreation, callback) { var jsonReq = { ClientId: this.pool.getClientId(), ConfirmationCode: confirmationCode, Username: this.username, ForceAliasCreation: forceAliasCreation }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('confirmSignUp', jsonReq, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); }; /** * This is used by the user once he has the responses to a custom challenge * @param {string} answerChallenge The custom challange answer. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {customChallenge} callback.customChallenge * Custom challenge response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.sendCustomChallengeAnswer = function sendCustomChallengeAnswer(answerChallenge, callback) { var _this6 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.ANSWER = answerChallenge; var authenticationHelper = new _AuthenticationHelper2.default(this.pool.getUserPoolId().split('_')[1]); this.getCachedDeviceKeyAndPassword(); if (this.deviceKey != null) { challengeResponses.DEVICE_KEY = this.deviceKey; } var jsonReq = { ChallengeName: 'CUSTOM_CHALLENGE', ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } return _this6.authenticateUserInternal(data, authenticationHelper, callback); }); }; /** * This is used by the user once he has an MFA code * @param {string} confirmationCode The MFA code entered by the user. * @param {object} callback Result callback map. * @param {string} mfaType The mfa we are replying to. * @param {onFailure} callback.onFailure Called on any error. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.sendMFACode = function sendMFACode(confirmationCode, callback, mfaType) { var _this7 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.SMS_MFA_CODE = confirmationCode; var mfaTypeSelection = mfaType || 'SMS_MFA'; if (mfaTypeSelection === 'SOFTWARE_TOKEN_MFA') { challengeResponses.SOFTWARE_TOKEN_MFA_CODE = confirmationCode; } if (this.deviceKey != null) { challengeResponses.DEVICE_KEY = this.deviceKey; } var jsonReq = { ChallengeName: mfaTypeSelection, ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (err, dataAuthenticate) { if (err) { return callback.onFailure(err); } var challengeName = dataAuthenticate.ChallengeName; if (challengeName === 'DEVICE_SRP_AUTH') { _this7.getDeviceResponse(callback); return undefined; } _this7.signInUserSession = _this7.getCognitoUserSession(dataAuthenticate.AuthenticationResult); _this7.cacheTokens(); if (dataAuthenticate.AuthenticationResult.NewDeviceMetadata == null) { return callback.onSuccess(_this7.signInUserSession); } var authenticationHelper = new _AuthenticationHelper2.default(_this7.pool.getUserPoolId().split('_')[1]); authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) { if (errGenHash) { return callback.onFailure(errGenHash); } var deviceSecretVerifierConfig = { Salt: new _global.util.Buffer(authenticationHelper.getSaltDevices(), 'hex').toString('base64'), PasswordVerifier: new _global.util.Buffer(authenticationHelper.getVerifierDevices(), 'hex').toString('base64') }; _this7.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier; _this7.deviceGroupKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey; _this7.randomPassword = authenticationHelper.getRandomPassword(); _this7.client.makeUnauthenticatedRequest('confirmDevice', { DeviceKey: dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, AccessToken: _this7.signInUserSession.getAccessToken().getJwtToken(), DeviceSecretVerifierConfig: deviceSecretVerifierConfig, DeviceName: navigator.userAgent }, function (errConfirm, dataConfirm) { if (errConfirm) { return callback.onFailure(errConfirm); } _this7.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey; _this7.cacheDeviceKeyAndPassword(); if (dataConfirm.UserConfirmationNecessary === true) { return callback.onSuccess(_this7.signInUserSession, dataConfirm.UserConfirmationNecessary); } return callback.onSuccess(_this7.signInUserSession); }); return undefined; }); return undefined; }); }; /** * This is used by an authenticated user to change the current password * @param {string} oldUserPassword The current password. * @param {string} newUserPassword The requested new password. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.changePassword = function changePassword(oldUserPassword, newUserPassword, callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('changePassword', { PreviousPassword: oldUserPassword, ProposedPassword: newUserPassword, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to enable MFA for himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.enableMFA = function enableMFA(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } var mfaOptions = []; var mfaEnabled = { DeliveryMedium: 'SMS', AttributeName: 'phone_number' }; mfaOptions.push(mfaEnabled); this.client.makeUnauthenticatedRequest('setUserSettings', { MFAOptions: mfaOptions, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to enable MFA for himself * @param {string[]} smsMfaSettings the sms mfa settings * @param {string[]} softwareTokenMfaSettings the software token mfa settings * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.setUserMfaPreference = function setUserMfaPreference(smsMfaSettings, softwareTokenMfaSettings, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('setUserMFAPreference', { SMSMfaSettings: smsMfaSettings, SoftwareTokenMfaSettings: softwareTokenMfaSettings, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to disable MFA for himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.disableMFA = function disableMFA(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } var mfaOptions = []; this.client.makeUnauthenticatedRequest('setUserSettings', { MFAOptions: mfaOptions, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to delete himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.deleteUser = function deleteUser(callback) { var _this8 = this; if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('deleteUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } _this8.clearCachedTokens(); return callback(null, 'SUCCESS'); }); return undefined; }; /** * @typedef {CognitoUserAttribute | { Name:string, Value:string }} AttributeArg */ /** * This is used by an authenticated user to change a list of attributes * @param {AttributeArg[]} attributes A list of the new user attributes. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.updateAttributes = function updateAttributes(attributes, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('updateUserAttributes', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), UserAttributes: attributes }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to get a list of attributes * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.getUserAttributes = function getUserAttributes(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('getUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, userData) { if (err) { return callback(err, null); } var attributeList = []; for (var i = 0; i < userData.UserAttributes.length; i++) { var attribute = { Name: userData.UserAttributes[i].Name, Value: userData.UserAttributes[i].Value }; var userAttribute = new _CognitoUserAttribute2.default(attribute); attributeList.push(userAttribute); } return callback(null, attributeList); }); return undefined; }; /** * This is used by an authenticated user to get the MFAOptions * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.getMFAOptions = function getMFAOptions(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('getUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, userData) { if (err) { return callback(err, null); } return callback(null, userData.MFAOptions); }); return undefined; }; /** * This is used by an authenticated user to delete a list of attributes * @param {string[]} attributeList Names of the attributes to delete. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.deleteAttributes = function deleteAttributes(attributeList, callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('deleteUserAttributes', { UserAttributeNames: attributeList, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by a user to resend a confirmation code * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.resendConfirmationCode = function resendConfirmationCode(callback) { var jsonReq = { ClientId: this.pool.getClientId(), Username: this.username }; this.client.makeUnauthenticatedRequest('resendConfirmationCode', jsonReq, function (err, result) { if (err) { return callback(err, null); } return callback(null, result); }); }; /** * This is used to get a session, either from the session object * or from the local storage, or by using a refresh token * * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.getSession = function getSession(callback) { if (this.username == null) { return callback(new Error('Username is null. Cannot retrieve a new session'), null); } if (this.signInUserSession != null && this.signInUserSession.isValid()) { return callback(null, this.signInUserSession); } var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var idTokenKey = keyPrefix + '.idToken'; var accessTokenKey = keyPrefix + '.accessToken'; var refreshTokenKey = keyPrefix + '.refreshToken'; var clockDriftKey = keyPrefix + '.clockDrift'; if (this.storage.getItem(idTokenKey)) { var idToken = new _CognitoIdToken2.default({ IdToken: this.storage.getItem(idTokenKey) }); var accessToken = new _CognitoAccessToken2.default({ AccessToken: this.storage.getItem(accessTokenKey) }); var refreshToken = new _CognitoRefreshToken2.default({ RefreshToken: this.storage.getItem(refreshTokenKey) }); var clockDrift = parseInt(this.storage.getItem(clockDriftKey), 0) || 0; var sessionData = { IdToken: idToken, AccessToken: accessToken, RefreshToken: refreshToken, ClockDrift: clockDrift }; var cachedSession = new _CognitoUserSession2.default(sessionData); if (cachedSession.isValid()) { this.signInUserSession = cachedSession; return callback(null, this.signInUserSession); } if (refreshToken.getToken() == null) { return callback(new Error('Cannot retrieve a new session. Please authenticate.'), null); } this.refreshSession(refreshToken, callback); } else { callback(new Error('Local storage is missing an ID Token, Please authenticate'), null); } return undefined; }; /** * This uses the refreshToken to retrieve a new session * @param {CognitoRefreshToken} refreshToken A previous session's refresh token. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.refreshSession = function refreshSession(refreshToken, callback) { var _this9 = this; var authParameters = {}; authParameters.REFRESH_TOKEN = refreshToken.getToken(); var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId(); var lastUserKey = keyPrefix + '.LastAuthUser'; if (this.storage.getItem(lastUserKey)) { this.username = this.storage.getItem(lastUserKey); var deviceKeyKey = keyPrefix + '.' + this.username + '.deviceKey'; this.deviceKey = this.storage.getItem(deviceKeyKey); authParameters.DEVICE_KEY = this.deviceKey; } var jsonReq = { ClientId: this.pool.getClientId(), AuthFlow: 'REFRESH_TOKEN_AUTH', AuthParameters: authParameters }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('initiateAuth', jsonReq, function (err, authResult) { if (err) { if (err.code === 'NotAuthorizedException') { _this9.clearCachedTokens(); } return callback(err, null); } if (authResult) { var authenticationResult = authResult.AuthenticationResult; if (!Object.prototype.hasOwnProperty.call(authenticationResult, 'RefreshToken')) { authenticationResult.RefreshToken = refreshToken.getToken(); } _this9.signInUserSession = _this9.getCognitoUserSession(authenticationResult); _this9.cacheTokens(); return callback(null, _this9.signInUserSession); } return undefined; }); }; /** * This is used to save the session tokens to local storage * @returns {void} */ CognitoUser.prototype.cacheTokens = function cacheTokens() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId(); var idTokenKey = keyPrefix + '.' + this.username + '.idToken'; var accessTokenKey = keyPrefix + '.' + this.username + '.accessToken'; var refreshTokenKey = keyPrefix + '.' + this.username + '.refreshToken'; var clockDriftKey = keyPrefix + '.' + this.username + '.clockDrift'; var lastUserKey = keyPrefix + '.LastAuthUser'; this.storage.setItem(idTokenKey, this.signInUserSession.getIdToken().getJwtToken()); this.storage.setItem(accessTokenKey, this.signInUserSession.getAccessToken().getJwtToken()); this.storage.setItem(refreshTokenKey, this.signInUserSession.getRefreshToken().getToken()); this.storage.setItem(clockDriftKey, '' + this.signInUserSession.getClockDrift()); this.storage.setItem(lastUserKey, this.username); }; /** * This is used to cache the device key and device group and device password * @returns {void} */ CognitoUser.prototype.cacheDeviceKeyAndPassword = function cacheDeviceKeyAndPassword() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var deviceKeyKey = keyPrefix + '.deviceKey'; var randomPasswordKey = keyPrefix + '.randomPasswordKey'; var deviceGroupKeyKey = keyPrefix + '.deviceGroupKey'; this.storage.setItem(deviceKeyKey, this.deviceKey); this.storage.setItem(randomPasswordKey, this.randomPassword); this.storage.setItem(deviceGroupKeyKey, this.deviceGroupKey); }; /** * This is used to get current device key and device group and device password * @returns {void} */ CognitoUser.prototype.getCachedDeviceKeyAndPassword = function getCachedDeviceKeyAndPassword() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var deviceKeyKey = keyPrefix + '.deviceKey'; var randomPasswordKey = keyPrefix + '.randomPasswordKey'; var deviceGroupKeyKey = keyPrefix + '.deviceGroupKey'; if (this.storage.getItem(deviceKeyKey)) { this.deviceKey = this.storage.getItem(deviceKeyKey); this.randomPassword = this.storage.getItem(randomPasswordKey); this.deviceGroupKey = this.storage.getItem(deviceGroupKeyKey); } }; /** * This is used to clear the device key info from local storage * @returns {void} */ CognitoUser.prototype.clearCachedDeviceKeyAndPassword = function clearCachedDeviceKeyAndPassword() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var deviceKeyKey = keyPrefix + '.deviceKey'; var randomPasswordKey = keyPrefix + '.randomPasswordKey'; var deviceGroupKeyKey = keyPrefix + '.deviceGroupKey'; this.storage.removeItem(deviceKeyKey); this.storage.removeItem(randomPasswordKey); this.storage.removeItem(deviceGroupKeyKey); }; /** * This is used to clear the session tokens from local storage * @returns {void} */ CognitoUser.prototype.clearCachedTokens = function clearCachedTokens() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId(); var idTokenKey = keyPrefix + '.' + this.username + '.idToken'; var accessTokenKey = keyPrefix + '.' + this.username + '.accessToken'; var refreshTokenKey = keyPrefix + '.' + this.username + '.refreshToken'; var lastUserKey = keyPrefix + '.LastAuthUser'; this.storage.removeItem(idTokenKey); this.storage.removeItem(accessTokenKey); this.storage.removeItem(refreshTokenKey); this.storage.removeItem(lastUserKey); }; /** * This is used to build a user session from tokens retrieved in the authentication result * @param {object} authResult Successful auth response from server. * @returns {CognitoUserSession} The new user session. * @private */ CognitoUser.prototype.getCognitoUserSession = function getCognitoUserSession(authResult) { var idToken = new _CognitoIdToken2.default(authResult); var accessToken = new _CognitoAccessToken2.default(authResult); var refreshToken = new _CognitoRefreshToken2.default(authResult); var sessionData = { IdToken: idToken, AccessToken: accessToken, RefreshToken: refreshToken }; return new _CognitoUserSession2.default(sessionData); }; /** * This is used to initiate a forgot password request * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {inputVerificationCode?} callback.inputVerificationCode * Optional callback raised instead of onSuccess with response data. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.forgotPassword = function forgotPassword(callback) { var jsonReq = { ClientId: this.pool.getClientId(), Username: this.username }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('forgotPassword', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } if (typeof callback.inputVerificationCode === 'function') { return callback.inputVerificationCode(data); } return callback.onSuccess(data); }); }; /** * This is used to confirm a new password using a confirmationCode * @param {string} confirmationCode Code entered by user. * @param {string} newPassword Confirm new password. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.confirmPassword = function confirmPassword(confirmationCode, newPassword, callback) { var jsonReq = { ClientId: this.pool.getClientId(), Username: this.username, ConfirmationCode: confirmationCode, Password: newPassword }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('confirmForgotPassword', jsonReq, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess(); }); }; /** * This is used to initiate an attribute confirmation request * @param {string} attributeName User attribute that needs confirmation. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {inputVerificationCode} callback.inputVerificationCode Called on success. * @returns {void} */ CognitoUser.prototype.getAttributeVerificationCode = function getAttributeVerificationCode(attributeName, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('getUserAttributeVerificationCode', { AttributeName: attributeName, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, data) { if (err) { return callback.onFailure(err); } if (typeof callback.inputVerificationCode === 'function') { return callback.inputVerificationCode(data); } return callback.onSuccess(); }); return undefined; }; /** * This is used to confirm an attribute using a confirmation code * @param {string} attributeName Attribute being confirmed. * @param {string} confirmationCode Code entered by user. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.verifyAttribute = function verifyAttribute(attributeName, confirmationCode, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('verifyUserAttribute', { AttributeName: attributeName, Code: confirmationCode, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to get the device information using the current device key * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess<*>} callback.onSuccess Called on success with device data. * @returns {void} */ CognitoUser.prototype.getDevice = function getDevice(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('getDevice', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey }, function (err, data) { if (err) { return callback.onFailure(err); } return callback.onSuccess(data); }); return undefined; }; /** * This is used to forget a specific device * @param {string} deviceKey Device key. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.forgetSpecificDevice = function forgetSpecificDevice(deviceKey, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('forgetDevice', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: deviceKey }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to forget the current device * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.forgetDevice = function forgetDevice(callback) { var _this10 = this; this.forgetSpecificDevice(this.deviceKey, { onFailure: callback.onFailure, onSuccess: function onSuccess(result) { _this10.deviceKey = null; _this10.deviceGroupKey = null; _this10.randomPassword = null; _this10.clearCachedDeviceKeyAndPassword(); return callback.onSuccess(result); } }); }; /** * This is used to set the device status as remembered * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.setDeviceStatusRemembered = function setDeviceStatusRemembered(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('updateDeviceStatus', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey, DeviceRememberedStatus: 'remembered' }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to set the device status as not remembered * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.setDeviceStatusNotRemembered = function setDeviceStatusNotRemembered(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('updateDeviceStatus', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey, DeviceRememberedStatus: 'not_remembered' }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to list all devices for a user * * @param {int} limit the number of devices returned in a call * @param {string} paginationToken the pagination token in case any was returned before * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess<*>} callback.onSuccess Called on success with device list. * @returns {void} */ CognitoUser.prototype.listDevices = function listDevices(limit, paginationToken, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('listDevices', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), Limit: limit, PaginationToken: paginationToken }, function (err, data) { if (err) { return callback.onFailure(err); } return callback.onSuccess(data); }); return undefined; }; /** * This is used to globally revoke all tokens issued to a user * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.globalSignOut = function globalSignOut(callback) { var _this11 = this; if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('globalSignOut', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback.onFailure(err); } _this11.clearCachedTokens(); return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used for the user to signOut of the application and clear the cached tokens. * @returns {void} */ CognitoUser.prototype.signOut = function signOut() { this.signInUserSession = null; this.clearCachedTokens(); }; /** * This is used by a user trying to select a given MFA * @param {string} answerChallenge the mfa the user wants * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.sendMFASelectionAnswer = function sendMFASelectionAnswer(answerChallenge, callback) { var _this12 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.ANSWER = answerChallenge; var jsonReq = { ChallengeName: 'SELECT_MFA_TYPE', ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } _this12.Session = data.Session; if (answerChallenge === 'SMS_MFA') { return callback.mfaRequired(data.challengeName, data.challengeParameters); } if (answerChallenge === 'SOFTWARE_TOKEN_MFA') { return callback.totpRequired(data.challengeName, data.challengeParameters); } return undefined; }); }; /** * This returns the user context data for advanced security feature. * @returns {void} */ CognitoUser.prototype.getUserContextData = function getUserContextData() { var pool = this.pool; return pool.getUserContextData(this.username); }; /** * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.associateSoftwareToken = function associateSoftwareToken(callback) { var _this13 = this; if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { this.client.makeUnauthenticatedRequest('associateSoftwareToken', { Session: this.Session }, function (err, data) { if (err) { return callback.onFailure(err); } _this13.Session = data.Session; return callback.associateSecretCode(data.SecretCode); }); } else { this.client.makeUnauthenticatedRequest('associateSoftwareToken', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, data) { if (err) { return callback.onFailure(err); } return callback.associateSecretCode(data.SecretCode); }); } }; /** * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA * @param {string} totpCode The MFA code entered by the user. * @param {string} friendlyDeviceName The device name we are assigning to the device. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.verifySoftwareToken = function verifySoftwareToken(totpCode, friendlyDeviceName, callback) { var _this14 = this; if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { this.client.makeUnauthenticatedRequest('verifySoftwareToken', { Session: this.Session, UserCode: totpCode, FriendlyDeviceName: friendlyDeviceName }, function (err, data) { if (err) { return callback.onFailure(err); } _this14.Session = data.Session; var challengeResponses = {}; challengeResponses.USERNAME = _this14.username; var jsonReq = { ChallengeName: 'MFA_SETUP', ClientId: _this14.pool.getClientId(), ChallengeResponses: challengeResponses, Session: _this14.Session }; if (_this14.getUserContextData()) { jsonReq.UserContextData = _this14.getUserContextData(); } _this14.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, function (errRespond, dataRespond) { if (errRespond) { return callback.onFailure(errRespond); } _this14.signInUserSession = _this14.getCognitoUserSession(dataRespond.AuthenticationResult); _this14.cacheTokens(); return callback.onSuccess(_this14.signInUserSession); }); return undefined; }); } else { this.client.makeUnauthenticatedRequest('verifySoftwareToken', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), UserCode: totpCode, FriendlyDeviceName: friendlyDeviceName }, function (err, data) { if (err) { return callback.onFailure(err); } return callback(null, data); }); } }; return CognitoUser; }(); exports.default = CognitoUser; ================================================ FILE: lib/CognitoUserAttribute.js ================================================ 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoUserAttribute = function () { /** * Constructs a new CognitoUserAttribute object * @param {string=} Name The record's name * @param {string=} Value The record's value */ function CognitoUserAttribute() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, Name = _ref.Name, Value = _ref.Value; _classCallCheck(this, CognitoUserAttribute); this.Name = Name || ''; this.Value = Value || ''; } /** * @returns {string} the record's value. */ CognitoUserAttribute.prototype.getValue = function getValue() { return this.Value; }; /** * Sets the record's value. * @param {string} value The new value. * @returns {CognitoUserAttribute} The record for method chaining. */ CognitoUserAttribute.prototype.setValue = function setValue(value) { this.Value = value; return this; }; /** * @returns {string} the record's name. */ CognitoUserAttribute.prototype.getName = function getName() { return this.Name; }; /** * Sets the record's name * @param {string} name The new name. * @returns {CognitoUserAttribute} The record for method chaining. */ CognitoUserAttribute.prototype.setName = function setName(name) { this.Name = name; return this; }; /** * @returns {string} a string representation of the record. */ CognitoUserAttribute.prototype.toString = function toString() { return JSON.stringify(this); }; /** * @returns {object} a flat object representing the record. */ CognitoUserAttribute.prototype.toJSON = function toJSON() { return { Name: this.Name, Value: this.Value }; }; return CognitoUserAttribute; }(); exports.default = CognitoUserAttribute; ================================================ FILE: lib/CognitoUserPool.js ================================================ 'use strict'; exports.__esModule = true; var _cognitoidentityserviceprovider = require('aws-sdk/clients/cognitoidentityserviceprovider'); var _cognitoidentityserviceprovider2 = _interopRequireDefault(_cognitoidentityserviceprovider); var _CognitoUser = require('./CognitoUser'); var _CognitoUser2 = _interopRequireDefault(_CognitoUser); var _StorageHelper = require('./StorageHelper'); var _StorageHelper2 = _interopRequireDefault(_StorageHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoUserPool = function () { /** * Constructs a new CognitoUserPool object * @param {object} data Creation options. * @param {string} data.UserPoolId Cognito user pool id. * @param {string} data.ClientId User pool application client id. * @param {object} data.Storage Optional storage object. * @param {boolean} data.AdvancedSecurityDataCollectionFlag Optional: * boolean flag indicating if the data collection is enabled * to support cognito advanced security features. By default, this * flag is set to true. */ function CognitoUserPool(data) { _classCallCheck(this, CognitoUserPool); var _ref = data || {}, UserPoolId = _ref.UserPoolId, ClientId = _ref.ClientId, endpoint = _ref.endpoint, AdvancedSecurityDataCollectionFlag = _ref.AdvancedSecurityDataCollectionFlag; if (!UserPoolId || !ClientId) { throw new Error('Both UserPoolId and ClientId are required.'); } if (!/^[\w-]+_.+$/.test(UserPoolId)) { throw new Error('Invalid UserPoolId format.'); } var region = UserPoolId.split('_')[0]; this.userPoolId = UserPoolId; this.clientId = ClientId; this.client = new _cognitoidentityserviceprovider2.default({ apiVersion: '2016-04-19', region: region, endpoint: endpoint }); /** * By default, AdvancedSecurityDataCollectionFlag is set to true, * if no input value is provided. */ this.advancedSecurityDataCollectionFlag = AdvancedSecurityDataCollectionFlag !== false; this.storage = data.Storage || new _StorageHelper2.default().getStorage(); } /** * @returns {string} the user pool id */ CognitoUserPool.prototype.getUserPoolId = function getUserPoolId() { return this.userPoolId; }; /** * @returns {string} the client id */ CognitoUserPool.prototype.getClientId = function getClientId() { return this.clientId; }; /** * @typedef {object} SignUpResult * @property {CognitoUser} user New user. * @property {bool} userConfirmed If the user is already confirmed. */ /** * method for signing up a user * @param {string} username User's username. * @param {string} password Plain-text initial password entered by user. * @param {(AttributeArg[])=} userAttributes New user attributes. * @param {(AttributeArg[])=} validationData Application metadata. * @param {nodeCallback} callback Called on error or with the new user. * @returns {void} */ CognitoUserPool.prototype.signUp = function signUp(username, password, userAttributes, validationData, callback) { var _this = this; var jsonReq = { ClientId: this.clientId, Username: username, Password: password, UserAttributes: userAttributes, ValidationData: validationData }; if (this.getUserContextData(username)) { jsonReq.UserContextData = this.getUserContextData(username); } this.client.makeUnauthenticatedRequest('signUp', jsonReq, function (err, data) { if (err) { return callback(err, null); } var cognitoUser = { Username: username, Pool: _this, Storage: _this.storage }; var returnData = { user: new _CognitoUser2.default(cognitoUser), userConfirmed: data.UserConfirmed, userSub: data.UserSub }; return callback(null, returnData); }); }; /** * method for getting the current user of the application from the local storage * * @returns {CognitoUser} the user retrieved from storage */ CognitoUserPool.prototype.getCurrentUser = function getCurrentUser() { var lastUserKey = 'CognitoIdentityServiceProvider.' + this.clientId + '.LastAuthUser'; var lastAuthUser = this.storage.getItem(lastUserKey); if (lastAuthUser) { var cognitoUser = { Username: lastAuthUser, Pool: this, Storage: this.storage }; return new _CognitoUser2.default(cognitoUser); } return null; }; /** * This method returns the encoded data string used for cognito advanced security feature. * This would be generated only when developer has included the JS used for collecting the * data on their client. Please refer to documentation to know more about using AdvancedSecurity * features * @param {string} username the username for the context data * @returns {string} the user context data **/ CognitoUserPool.prototype.getUserContextData = function getUserContextData(username) { if (typeof AmazonCognitoAdvancedSecurityData === 'undefined') { return undefined; } /* eslint-disable */ var amazonCognitoAdvancedSecurityDataConst = AmazonCognitoAdvancedSecurityData; /* eslint-enable */ if (this.advancedSecurityDataCollectionFlag) { var advancedSecurityData = amazonCognitoAdvancedSecurityDataConst.getData(username, this.userPoolId, this.clientId); if (advancedSecurityData) { var userContextData = { EncodedData: advancedSecurityData }; return userContextData; } } return {}; }; return CognitoUserPool; }(); exports.default = CognitoUserPool; ================================================ FILE: lib/CognitoUserSession.js ================================================ 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoUserSession = function () { /** * Constructs a new CognitoUserSession object * @param {CognitoIdToken} IdToken The session's Id token. * @param {CognitoRefreshToken=} RefreshToken The session's refresh token. * @param {CognitoAccessToken} AccessToken The session's access token. * @param {int} ClockDrift The saved computer's clock drift or undefined to force calculation. */ function CognitoUserSession() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, IdToken = _ref.IdToken, RefreshToken = _ref.RefreshToken, AccessToken = _ref.AccessToken, ClockDrift = _ref.ClockDrift; _classCallCheck(this, CognitoUserSession); if (AccessToken == null || IdToken == null) { throw new Error('Id token and Access Token must be present.'); } this.idToken = IdToken; this.refreshToken = RefreshToken; this.accessToken = AccessToken; this.clockDrift = ClockDrift === undefined ? this.calculateClockDrift() : ClockDrift; } /** * @returns {CognitoIdToken} the session's Id token */ CognitoUserSession.prototype.getIdToken = function getIdToken() { return this.idToken; }; /** * @returns {CognitoRefreshToken} the session's refresh token */ CognitoUserSession.prototype.getRefreshToken = function getRefreshToken() { return this.refreshToken; }; /** * @returns {CognitoAccessToken} the session's access token */ CognitoUserSession.prototype.getAccessToken = function getAccessToken() { return this.accessToken; }; /** * @returns {int} the session's clock drift */ CognitoUserSession.prototype.getClockDrift = function getClockDrift() { return this.clockDrift; }; /** * @returns {int} the computer's clock drift */ CognitoUserSession.prototype.calculateClockDrift = function calculateClockDrift() { var now = Math.floor(new Date() / 1000); var iat = Math.min(this.accessToken.getIssuedAt(), this.idToken.getIssuedAt()); return now - iat; }; /** * Checks to see if the session is still valid based on session expiry information found * in tokens and the current time (adjusted with clock drift) * @returns {boolean} if the session is still valid */ CognitoUserSession.prototype.isValid = function isValid() { var now = Math.floor(new Date() / 1000); var adjusted = now - this.clockDrift; return adjusted < this.accessToken.getExpiration() && adjusted < this.idToken.getExpiration(); }; return CognitoUserSession; }(); exports.default = CognitoUserSession; ================================================ FILE: lib/CookieStorage.js ================================================ 'use strict'; exports.__esModule = true; var _jsCookie = require('js-cookie'); var Cookies = _interopRequireWildcard(_jsCookie); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** @class */ var CookieStorage = function () { /** * Constructs a new CookieStorage object * @param {object} data Creation options. * @param {string} data.domain Cookies domain (mandatory). * @param {string} data.path Cookies path (default: '/') * @param {integer} data.expires Cookie expiration (in days, default: 365) * @param {boolean} data.secure Cookie secure flag (default: true) */ function CookieStorage(data) { _classCallCheck(this, CookieStorage); this.domain = data.domain; if (data.path) { this.path = data.path; } else { this.path = '/'; } if (Object.prototype.hasOwnProperty.call(data, 'expires')) { this.expires = data.expires; } else { this.expires = 365; } if (Object.prototype.hasOwnProperty.call(data, 'secure')) { this.secure = data.secure; } else { this.secure = true; } } /** * This is used to set a specific item in storage * @param {string} key - the key for the item * @param {object} value - the value * @returns {string} value that was set */ CookieStorage.prototype.setItem = function setItem(key, value) { Cookies.set(key, value, { path: this.path, expires: this.expires, domain: this.domain, secure: this.secure }); return Cookies.get(key); }; /** * This is used to get a specific key from storage * @param {string} key - the key for the item * This is used to clear the storage * @returns {string} the data item */ CookieStorage.prototype.getItem = function getItem(key) { return Cookies.get(key); }; /** * This is used to remove an item from storage * @param {string} key - the key being set * @returns {string} value - value that was deleted */ CookieStorage.prototype.removeItem = function removeItem(key) { return Cookies.remove(key, { path: this.path, domain: this.domain, secure: this.secure }); }; /** * This is used to clear the storage * @returns {string} nothing */ CookieStorage.prototype.clear = function clear() { var cookies = Cookies.get(); var index = void 0; for (index = 0; index < cookies.length; ++index) { Cookies.remove(cookies[index]); } return {}; }; return CookieStorage; }(); exports.default = CookieStorage; ================================================ FILE: lib/DateHelper.js ================================================ 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var weekNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; /** @class */ var DateHelper = function () { function DateHelper() { _classCallCheck(this, DateHelper); } /** * @returns {string} The current time in "ddd MMM D HH:mm:ss UTC YYYY" format. */ DateHelper.prototype.getNowString = function getNowString() { var now = new Date(); var weekDay = weekNames[now.getUTCDay()]; var month = monthNames[now.getUTCMonth()]; var day = now.getUTCDate(); var hours = now.getUTCHours(); if (hours < 10) { hours = '0' + hours; } var minutes = now.getUTCMinutes(); if (minutes < 10) { minutes = '0' + minutes; } var seconds = now.getUTCSeconds(); if (seconds < 10) { seconds = '0' + seconds; } var year = now.getUTCFullYear(); // ddd MMM D HH:mm:ss UTC YYYY var dateNow = weekDay + ' ' + month + ' ' + day + ' ' + hours + ':' + minutes + ':' + seconds + ' UTC ' + year; return dateNow; }; return DateHelper; }(); exports.default = DateHelper; ================================================ FILE: lib/StorageHelper-rn.js ================================================ 'use strict'; exports.__esModule = true; var _reactNative = require('react-native'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ var MEMORY_KEY_PREFIX = '@MemoryStorage:'; var dataMemory = {}; /** @class */ var MemoryStorage = function () { function MemoryStorage() { _classCallCheck(this, MemoryStorage); } /** * This is used to set a specific item in storage * @param {string} key - the key for the item * @param {object} value - the value * @returns {string} value that was set */ MemoryStorage.setItem = function setItem(key, value) { _reactNative.AsyncStorage.setItem(MEMORY_KEY_PREFIX + key, value); dataMemory[key] = value; return dataMemory[key]; }; /** * This is used to get a specific key from storage * @param {string} key - the key for the item * This is used to clear the storage * @returns {string} the data item */ MemoryStorage.getItem = function getItem(key) { return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined; }; /** * This is used to remove an item from storage * @param {string} key - the key being set * @returns {string} value - value that was deleted */ MemoryStorage.removeItem = function removeItem(key) { _reactNative.AsyncStorage.removeItem(MEMORY_KEY_PREFIX + key); return delete dataMemory[key]; }; /** * This is used to clear the storage * @returns {string} nothing */ MemoryStorage.clear = function clear() { dataMemory = {}; return dataMemory; }; /** * Will sync the MemoryStorage data from AsyncStorage to storageWindow MemoryStorage * @param {nodeCallback} callback callback with (err, 'SUCCESS') * @returns {void} */ MemoryStorage.sync = function sync(callback) { _reactNative.AsyncStorage.getAllKeys(function (errKeys, keys) { if (errKeys) return callback(errKeys, null); var memoryKeys = keys.filter(function (key) { return key.startsWith(MEMORY_KEY_PREFIX); }); _reactNative.AsyncStorage.multiGet(memoryKeys, function (err, stores) { if (err) return callback(err, null); stores.map(function (result, index, store) { var key = store[index][0]; var value = store[index][1]; var memoryKey = key.replace(MEMORY_KEY_PREFIX, ''); dataMemory[memoryKey] = value; return undefined; }); callback(null, 'SUCCESS'); return undefined; }); return undefined; }); }; return MemoryStorage; }(); /** @class */ var StorageHelper = function () { /** * This is used to get a storage object * @returns {object} the storage */ function StorageHelper() { _classCallCheck(this, StorageHelper); this.storageWindow = MemoryStorage; } /** * This is used to return the storage * @returns {object} the storage */ StorageHelper.prototype.getStorage = function getStorage() { return this.storageWindow; }; return StorageHelper; }(); exports.default = StorageHelper; ================================================ FILE: lib/StorageHelper.js ================================================ 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ var dataMemory = {}; /** @class */ var MemoryStorage = function () { function MemoryStorage() { _classCallCheck(this, MemoryStorage); } /** * This is used to set a specific item in storage * @param {string} key - the key for the item * @param {object} value - the value * @returns {string} value that was set */ MemoryStorage.setItem = function setItem(key, value) { dataMemory[key] = value; return dataMemory[key]; }; /** * This is used to get a specific key from storage * @param {string} key - the key for the item * This is used to clear the storage * @returns {string} the data item */ MemoryStorage.getItem = function getItem(key) { return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined; }; /** * This is used to remove an item from storage * @param {string} key - the key being set * @returns {string} value - value that was deleted */ MemoryStorage.removeItem = function removeItem(key) { return delete dataMemory[key]; }; /** * This is used to clear the storage * @returns {string} nothing */ MemoryStorage.clear = function clear() { dataMemory = {}; return dataMemory; }; return MemoryStorage; }(); /** @class */ var StorageHelper = function () { /** * This is used to get a storage object * @returns {object} the storage */ function StorageHelper() { _classCallCheck(this, StorageHelper); try { this.storageWindow = window.localStorage; this.storageWindow.setItem('aws.cognito.test-ls', 1); this.storageWindow.removeItem('aws.cognito.test-ls'); } catch (exception) { this.storageWindow = MemoryStorage; } } /** * This is used to return the storage * @returns {object} the storage */ StorageHelper.prototype.getStorage = function getStorage() { return this.storageWindow; }; return StorageHelper; }(); exports.default = StorageHelper; ================================================ FILE: lib/index.js ================================================ 'use strict'; exports.__esModule = true; var _AuthenticationDetails = require('./AuthenticationDetails'); Object.defineProperty(exports, 'AuthenticationDetails', { enumerable: true, get: function get() { return _interopRequireDefault(_AuthenticationDetails).default; } }); var _AuthenticationHelper = require('./AuthenticationHelper'); Object.defineProperty(exports, 'AuthenticationHelper', { enumerable: true, get: function get() { return _interopRequireDefault(_AuthenticationHelper).default; } }); var _CognitoAccessToken = require('./CognitoAccessToken'); Object.defineProperty(exports, 'CognitoAccessToken', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoAccessToken).default; } }); var _CognitoIdToken = require('./CognitoIdToken'); Object.defineProperty(exports, 'CognitoIdToken', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoIdToken).default; } }); var _CognitoRefreshToken = require('./CognitoRefreshToken'); Object.defineProperty(exports, 'CognitoRefreshToken', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoRefreshToken).default; } }); var _CognitoUser = require('./CognitoUser'); Object.defineProperty(exports, 'CognitoUser', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoUser).default; } }); var _CognitoUserAttribute = require('./CognitoUserAttribute'); Object.defineProperty(exports, 'CognitoUserAttribute', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoUserAttribute).default; } }); var _CognitoUserPool = require('./CognitoUserPool'); Object.defineProperty(exports, 'CognitoUserPool', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoUserPool).default; } }); var _CognitoUserSession = require('./CognitoUserSession'); Object.defineProperty(exports, 'CognitoUserSession', { enumerable: true, get: function get() { return _interopRequireDefault(_CognitoUserSession).default; } }); var _CookieStorage = require('./CookieStorage'); Object.defineProperty(exports, 'CookieStorage', { enumerable: true, get: function get() { return _interopRequireDefault(_CookieStorage).default; } }); var _DateHelper = require('./DateHelper'); Object.defineProperty(exports, 'DateHelper', { enumerable: true, get: function get() { return _interopRequireDefault(_DateHelper).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // The version of crypto-browserify included by aws-sdk only // checks for window.crypto, not window.msCrypto as used by // IE 11 – so we set it explicitly here if (typeof window !== 'undefined' && !window.crypto && window.msCrypto) { window.crypto = window.msCrypto; } ================================================ FILE: package.json ================================================ { "name": "amazon-cognito-identity-js", "description": "Amazon Cognito Identity Provider JavaScript SDK", "version": "1.31.0", "author": { "name": "Amazon Web Services", "email": "aws@amazon.com", "url": "http://aws.amazon.com" }, "homepage": "http://aws.amazon.com/cognito", "contributors": [ "Simon Buchan with Skilitics", "Jonathan Goldwasser", "Matt Durant", "John Ferlito", "Michael Hart", "Tylor Steinberger", "Paul Watts", "Gleb Promokhov", "Min Bi", "Chetan Mehta ", "Ionut Trestian " ], "repository": { "type": "git", "url": "https://github.com/aws/amazon-cognito-identity-js.git" }, "license": "SEE LICENSE IN LICENSE.txt", "licenses": [ { "type": "Amazon Software License", "url": "http://aws.amazon.com/asl" } ], "keywords": [ "amazon", "aws", "cognito", "identity", "react-native", "reactnative" ], "scripts": { "clean": "rimraf lib es", "build:commonjs": "cross-env BABEL_ENV=commonjs babel src --out-dir lib", "build:es": "cross-env BABEL_ENV=es babel src --out-dir es", "build:umd": "cross-env BABEL_ENV=commonjs NODE_ENV=development webpack dist/amazon-cognito-identity.js", "build:umd:min": "cross-env BABEL_ENV=commonjs NODE_ENV=production webpack dist/amazon-cognito-identity.min.js", "build": "npm run clean && npm run build:commonjs && npm run build:es && npm run build:umd && npm run build:umd:min", "doc": "jsdoc src -d docs", "lint": "eslint src", "lint2": "eslint enhance-rn.js" }, "main": "lib/index.js", "react-native": { "lib/index.js": "./enhance-rn.js", "./src/StorageHelper": "./src/StorageHelper-rn.js" }, "module": "es/index.js", "jsnext:main": "es/index.js", "types": "./index.d.ts", "dependencies": { "aws-sdk": "2.177.0", "js-cookie": "^2.1.4" }, "devDependencies": { "babel-cli": "^6.23.0", "babel-core": "^6.13.2", "babel-loader": "^6.2.4", "babel-plugin-transform-es2015-modules-commonjs": "^6.23.0", "babel-preset-es2015": "^6.22.0", "cross-env": "^3.1.4", "eslint": "^3.19.0", "eslint-config-airbnb-base": "^5.0.2", "eslint-import-resolver-webpack": "^0.5.1", "eslint-plugin-import": "^2.7.0", "eslint-plugin-node": "^5.2.0", "eslint-plugin-promise": "^3.6.0", "eslint-plugin-standard": "^3.0.1", "jsdoc": "^3.4.0", "react": "^16.0.0-alpha.6", "react-native": "^0.44.0", "rimraf": "^2.5.4", "webpack": "^1.13.1" } } ================================================ FILE: src/AuthenticationDetails.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ export default class AuthenticationDetails { /** * Constructs a new AuthenticationDetails object * @param {object=} data Creation options. * @param {string} data.Username User being authenticated. * @param {string} data.Password Plain-text password to authenticate with. * @param {(AttributeArg[])?} data.ValidationData Application extra metadata. * @param {(AttributeArg[])?} data.AuthParamaters Authentication paramaters for custom auth. */ constructor(data) { const { ValidationData, Username, Password, AuthParameters } = data || {}; this.validationData = ValidationData || []; this.authParameters = AuthParameters || []; this.username = Username; this.password = Password; } /** * @returns {string} the record's username */ getUsername() { return this.username; } /** * @returns {string} the record's password */ getPassword() { return this.password; } /** * @returns {Array} the record's validationData */ getValidationData() { return this.validationData; } /** * @returns {Array} the record's authParameters */ getAuthParameters() { return this.authParameters; } } ================================================ FILE: src/AuthenticationHelper.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ import { util } from 'aws-sdk/global'; import BigInteger from './BigInteger'; const initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF'; const newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.'; /** @class */ export default class AuthenticationHelper { /** * Constructs a new AuthenticationHelper object * @param {string} PoolName Cognito user pool name. */ constructor(PoolName) { this.N = new BigInteger(initN, 16); this.g = new BigInteger('2', 16); this.k = new BigInteger(this.hexHash(`00${this.N.toString(16)}0${this.g.toString(16)}`), 16); this.smallAValue = this.generateRandomSmallA(); this.getLargeAValue(() => {}); this.infoBits = new util.Buffer('Caldera Derived Key', 'utf8'); this.poolName = PoolName; } /** * @returns {BigInteger} small A, a random number */ getSmallAValue() { return this.smallAValue; } /** * @param {nodeCallback} callback Called with (err, largeAValue) * @returns {void} */ getLargeAValue(callback) { if (this.largeAValue) { callback(null, this.largeAValue); } else { this.calculateA(this.smallAValue, (err, largeAValue) => { if (err) { callback(err, null); } this.largeAValue = largeAValue; callback(null, this.largeAValue); }); } } /** * helper function to generate a random big integer * @returns {BigInteger} a random value. * @private */ generateRandomSmallA() { const hexRandom = util.crypto.lib.randomBytes(128).toString('hex'); const randomBigInt = new BigInteger(hexRandom, 16); const smallABigInt = randomBigInt.mod(this.N); return smallABigInt; } /** * helper function to generate a random string * @returns {string} a random value. * @private */ generateRandomString() { return util.crypto.lib.randomBytes(40).toString('base64'); } /** * @returns {string} Generated random value included in password hash. */ getRandomPassword() { return this.randomPassword; } /** * @returns {string} Generated random value included in devices hash. */ getSaltDevices() { return this.SaltToHashDevices; } /** * @returns {string} Value used to verify devices. */ getVerifierDevices() { return this.verifierDevices; } /** * Generate salts and compute verifier. * @param {string} deviceGroupKey Devices to generate verifier for. * @param {string} username User to generate verifier for. * @param {nodeCallback} callback Called with (err, null) * @returns {void} */ generateHashDevice(deviceGroupKey, username, callback) { this.randomPassword = this.generateRandomString(); const combinedString = `${deviceGroupKey}${username}:${this.randomPassword}`; const hashedString = this.hash(combinedString); const hexRandom = util.crypto.lib.randomBytes(16).toString('hex'); this.SaltToHashDevices = this.padHex(new BigInteger(hexRandom, 16)); this.g.modPow( new BigInteger(this.hexHash(this.SaltToHashDevices + hashedString), 16), this.N, (err, verifierDevicesNotPadded) => { if (err) { callback(err, null); } this.verifierDevices = this.padHex(verifierDevicesNotPadded); callback(null, null); }); } /** * Calculate the client's public value A = g^a%N * with the generated random number a * @param {BigInteger} a Randomly generated small A. * @param {nodeCallback} callback Called with (err, largeAValue) * @returns {void} * @private */ calculateA(a, callback) { this.g.modPow(a, this.N, (err, A) => { if (err) { callback(err, null); } if (A.mod(this.N).equals(BigInteger.ZERO)) { callback(new Error('Illegal paramater. A mod N cannot be 0.'), null); } callback(null, A); }); } /** * Calculate the client's value U which is the hash of A and B * @param {BigInteger} A Large A value. * @param {BigInteger} B Server B value. * @returns {BigInteger} Computed U value. * @private */ calculateU(A, B) { this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B)); const finalU = new BigInteger(this.UHexHash, 16); return finalU; } /** * Calculate a hash from a bitArray * @param {Buffer} buf Value to hash. * @returns {String} Hex-encoded hash. * @private */ hash(buf) { const hashHex = util.crypto.sha256(buf, 'hex'); return (new Array(64 - hashHex.length).join('0')) + hashHex; } /** * Calculate a hash from a hex string * @param {String} hexStr Value to hash. * @returns {String} Hex-encoded hash. * @private */ hexHash(hexStr) { return this.hash(new util.Buffer(hexStr, 'hex')); } /** * Standard hkdf algorithm * @param {Buffer} ikm Input key material. * @param {Buffer} salt Salt value. * @returns {Buffer} Strong key material. * @private */ computehkdf(ikm, salt) { const prk = util.crypto.hmac(salt, ikm, 'buffer', 'sha256'); const infoBitsUpdate = util.buffer.concat([ this.infoBits, new util.Buffer(String.fromCharCode(1), 'utf8'), ]); const hmac = util.crypto.hmac(prk, infoBitsUpdate, 'buffer', 'sha256'); return hmac.slice(0, 16); } /** * Calculates the final hkdf based on computed S value, and computed U value and the key * @param {String} username Username. * @param {String} password Password. * @param {BigInteger} serverBValue Server B value. * @param {BigInteger} salt Generated salt. * @param {nodeCallback} callback Called with (err, hkdfValue) * @returns {void} */ getPasswordAuthenticationKey(username, password, serverBValue, salt, callback) { if (serverBValue.mod(this.N).equals(BigInteger.ZERO)) { throw new Error('B cannot be zero.'); } this.UValue = this.calculateU(this.largeAValue, serverBValue); if (this.UValue.equals(BigInteger.ZERO)) { throw new Error('U cannot be zero.'); } const usernamePassword = `${this.poolName}${username}:${password}`; const usernamePasswordHash = this.hash(usernamePassword); const xValue = new BigInteger(this.hexHash(this.padHex(salt) + usernamePasswordHash), 16); this.calculateS(xValue, serverBValue, (err, sValue) => { if (err) { callback(err, null); } const hkdf = this.computehkdf( new util.Buffer(this.padHex(sValue), 'hex'), new util.Buffer(this.padHex(this.UValue.toString(16)), 'hex')); callback(null, hkdf); }); } /** * Calculates the S value used in getPasswordAuthenticationKey * @param {BigInteger} xValue Salted password hash value. * @param {BigInteger} serverBValue Server B value. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ calculateS(xValue, serverBValue, callback) { this.g.modPow(xValue, this.N, (err, gModPowXN) => { if (err) { callback(err, null); } const intValue2 = serverBValue.subtract(this.k.multiply(gModPowXN)); intValue2.modPow( this.smallAValue.add(this.UValue.multiply(xValue)), this.N, (err2, result) => { if (err2) { callback(err2, null); } callback(null, result.mod(this.N)); } ); }); } /** * Return constant newPasswordRequiredChallengeUserAttributePrefix * @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value */ getNewPasswordRequiredChallengeUserAttributePrefix() { return newPasswordRequiredChallengeUserAttributePrefix; } /** * Converts a BigInteger (or hex string) to hex format padded with zeroes for hashing * @param {BigInteger|String} bigInt Number or string to pad. * @returns {String} Padded hex string. */ padHex(bigInt) { let hashStr = bigInt.toString(16); if (hashStr.length % 2 === 1) { hashStr = `0${hashStr}`; } else if ('89ABCDEFabcdef'.indexOf(hashStr[0]) !== -1) { hashStr = `00${hashStr}`; } return hashStr; } } ================================================ FILE: src/BigInteger.js ================================================ // A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/ // // All public methods have been removed except the following: // new BigInteger(a, b) (only radix 2, 4, 8, 16 and 32 supported) // toString (only radix 2, 4, 8, 16 and 32 supported) // negate // abs // compareTo // bitLength // mod // equals // add // subtract // multiply // divide // modPow export default BigInteger; /* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ // (public) Constructor function BigInteger(a, b) { if (a != null) this.fromString(a, b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } var inBrowser = typeof navigator !== "undefined"; if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = (1 << dbits) - 1; BigInteger.prototype.DV = 1 << dbits; var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2, BI_FP); BigInteger.prototype.F1 = BI_FP - dbits; BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = new Array(); var rr, vv; rr = "0".charCodeAt(0); for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s, i) { var c = BI_RC[s.charCodeAt(i)]; return c == null ? -1 : c; } // (protected) copy this to r function bnpCopyTo(r) { for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = x < 0 ? -1 : 0; if (x > 0) this[0] = x; else if (x < -1) this[0] = x + this.DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s, b) { var k; if (b == 16) k = 4; else if (b == 8) k = 3; else if (b == 2) k = 1; else if (b == 32) k = 5; else if (b == 4) k = 2; else throw new Error("Only radix 2, 4, 8, 16, 32 are supported"); this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while (--i >= 0) { var x = intAt(s, i); if (x < 0) { if (s.charAt(i) == "-") mi = true; continue; } mi = false; if (sh == 0) this[this.t++] = x; else if (sh + k > this.DB) { this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; this[this.t++] = x >> this.DB - sh; } else this[this.t - 1] |= x << sh; sh += k; if (sh >= this.DB) sh -= this.DB; } this.clamp(); if (mi) BigInteger.ZERO.subTo(this, this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s & this.DM; while (this.t > 0 && this[this.t - 1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if (this.s < 0) return "-" + this.negate().toString(); var k; if (b == 16) k = 4; else if (b == 8) k = 3; else if (b == 2) k = 1; else if (b == 32) k = 5; else if (b == 4) k = 2; else throw new Error("Only radix 2, 4, 8, 16, 32 are supported"); var km = (1 << k) - 1, d, m = false, r = "", i = this.t; var p = this.DB - i * this.DB % k; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) > 0) { m = true; r = int2char(d); } while (i >= 0) { if (p < k) { d = (this[i] & (1 << p) - 1) << k - p; d |= this[--i] >> (p += this.DB - k); } else { d = this[i] >> (p -= k) & km; if (p <= 0) { p += this.DB; --i; } } if (d > 0) m = true; if (m) r += int2char(d); } } return m ? r : "0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; } // (public) |this| function bnAbs() { return this.s < 0 ? this.negate() : this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s - a.s; if (r != 0) return r; var i = this.t; r = i - a.t; if (r != 0) return this.s < 0 ? -r : r; while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if ((t = x >>> 16) != 0) { x = t; r += 16; } if ((t = x >> 8) != 0) { x = t; r += 8; } if ((t = x >> 4) != 0) { x = t; r += 4; } if ((t = x >> 2) != 0) { x = t; r += 2; } if ((t = x >> 1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if (this.t <= 0) return 0; return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM); } // (protected) r = this << n*DB function bnpDLShiftTo(n, r) { var i; for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; for (i = n - 1; i >= 0; --i) r[i] = 0; r.t = this.t + n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n, r) { for (var i = n; i < this.t; ++i) r[i - n] = this[i]; r.t = Math.max(this.t - n, 0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n, r) { var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << cbs) - 1; var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; for (i = this.t - 1; i >= 0; --i) { r[i + ds + 1] = this[i] >> cbs | c; c = (this[i] & bm) << bs; } for (i = ds - 1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t + ds + 1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n, r) { r.s = this.s; var ds = Math.floor(n / this.DB); if (ds >= this.t) { r.t = 0; return; } var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << bs) - 1; r[0] = this[ds] >> bs; for (var i = ds + 1; i < this.t; ++i) { r[i - ds - 1] |= (this[i] & bm) << cbs; r[i - ds] = this[i] >> bs; } if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; r.t = this.t - ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { c += this[i] - a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c -= a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c -= a[i]; r[i++] = c & this.DM; c >>= this.DB; } c -= a.s; } r.s = c < 0 ? -1 : 0; if (c < -1) r[i++] = this.DV + c; else if (c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a, r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i + y.t; while (--i >= 0) r[i] = 0; for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); r.s = 0; r.clamp(); if (this.s != a.s) BigInteger.ZERO.subTo(r, r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2 * x.t; while (--i >= 0) r[i] = 0; for (i = 0; i < x.t - 1; ++i) { var c = x.am(i, x[i], r, 2 * i, 0, 1); if ( (r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV ) { r[i + x.t] -= x.DV; r[i + x.t + 1] = 1; } } if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m, q, r) { var pm = m.abs(); if (pm.t <= 0) return; var pt = this.abs(); if (pt.t < pm.t) { if (q != null) q.fromInt(0); if (r != null) this.copyTo(r); return; } if (r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys - 1]; if (y0 == 0) return; var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; var i = r.t, j = i - ys, t = q == null ? nbi() : q; y.dlShiftTo(j, t); if (r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t, r); } BigInteger.ONE.dlShiftTo(ys, t); t.subTo(y, y); // "negative" y so we can replace sub with am later while (y.t < ys) y[y.t++] = 0; while (--j >= 0) { // Estimate quotient digit var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out y.dlShiftTo(j, t); r.subTo(t, r); while (r[i] < --qd) r.subTo(t, r); } } if (q != null) { r.drShiftTo(ys, q); if (ts != ms) BigInteger.ZERO.subTo(q, q); } r.t = ys; r.clamp(); if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder if (ts < 0) BigInteger.ZERO.subTo(r, r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); return r; } // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if (this.t < 1) return 0; var x = this[0]; if ((x & 1) == 0) return 0; var y = x & 3; // y == 1/x mod 2^2 y = y * (2 - (x & 0xf) * y) & 0xf; // y == 1/x mod 2^4 y = y * (2 - (x & 0xff) * y) & 0xff; // y == 1/x mod 2^8 y = y * (2 - ((x & 0xffff) * y & 0xffff)) & 0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = y * (2 - x * y % this.DV) % this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return y > 0 ? this.DV - y : -y; } function bnEquals(a) { return this.compareTo(a) == 0; } // (protected) r = this + a function bnpAddTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { c += this[i] + a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c += a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c += a[i]; r[i++] = c & this.DM; c >>= this.DB; } c += a.s; } r.s = c < 0 ? -1 : 0; if (c > 0) r[i++] = c; else if (c < -1) r[i++] = this.DV + c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a, r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a, r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a, r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a, r, null); return r; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp & 0x7fff; this.mph = this.mp >> 15; this.um = (1 << m.DB - 15) - 1; this.mt2 = 2 * m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t, r); r.divRemTo(this.m, null, r); if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while (x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for (var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i] & 0x7fff; var u0 = j * this.mpl + ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & x.DM; // use am to combine the multiply-shift-add into one call j = i + this.m.t; x[j] += this.m.am(0, u0, x, i, 0, this.m.t); // propagate carry while (x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t, x); if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); } // r = "x^2/R mod m"; x != r function montSqrTo(x, r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e, m, callback) { var i = e.bitLength(), k, r = nbv(1), z = new Montgomery(m); if (i <= 0) return r; else if (i < 18) k = 1; else if (i < 48) k = 3; else if (i < 144) k = 4; else if (i < 768) k = 5; else k = 6; // precomputation var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { var g2 = nbi(); z.sqrTo(g[1], g2); while (n <= km) { g[n] = nbi(); z.mulTo(g2, g[n - 2], g[n]); n += 2; } } var j = e.t - 1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j]) - 1; while (j >= 0) { if (i >= k1) w = e[j] >> i - k1 & km; else { w = (e[j] & (1 << i + 1) - 1) << k1 - i; if (j > 0) w |= e[j - 1] >> this.DB + i - k1; } n = k; while ((w & 1) == 0) { w >>= 1; --n; } if ((i -= n) < 0) { i += this.DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n > 1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n > 0) z.sqrTo(r, r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j >= 0 && (e[j] & 1 << i) == 0) { z.sqrTo(r, r2); t = r; r = r2; r2 = t; if (--i < 0) { i = this.DB - 1; --j; } } } var result = z.revert(r); callback(null, result); return result; } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.addTo = bnpAddTo; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.modPow = bnModPow; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); ================================================ FILE: src/CognitoAccessToken.js ================================================ /* * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ import CognitoJwtToken from './CognitoJwtToken'; /** @class */ export default class CognitoAccessToken extends CognitoJwtToken { /** * Constructs a new CognitoAccessToken object * @param {string=} AccessToken The JWT access token. */ constructor({ AccessToken } = {}) { super(AccessToken || ''); } } ================================================ FILE: src/CognitoIdToken.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ import CognitoJwtToken from './CognitoJwtToken'; /** @class */ export default class CognitoIdToken extends CognitoJwtToken { /** * Constructs a new CognitoIdToken object * @param {string=} IdToken The JWT Id token */ constructor({ IdToken } = {}) { super(IdToken || ''); } } ================================================ FILE: src/CognitoJwtToken.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ import { util } from 'aws-sdk/global'; /** @class */ export default class CognitoJwtToken { /** * Constructs a new CognitoJwtToken object * @param {string=} token The JWT token. */ constructor(token) { // Assign object this.jwtToken = token || ''; this.payload = this.decodePayload(); } /** * @returns {string} the record's token. */ getJwtToken() { return this.jwtToken; } /** * @returns {int} the token's expiration (exp member). */ getExpiration() { return this.payload.exp; } /** * @returns {int} the token's "issued at" (iat member). */ getIssuedAt() { return this.payload.iat; } /** * @returns {object} the token's payload. */ decodePayload() { const payload = this.jwtToken.split('.')[1]; try { return JSON.parse(util.base64.decode(payload).toString('utf8')); } catch (err) { return {}; } } } ================================================ FILE: src/CognitoRefreshToken.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ export default class CognitoRefreshToken { /** * Constructs a new CognitoRefreshToken object * @param {string=} RefreshToken The JWT refresh token. */ constructor({ RefreshToken } = {}) { // Assign object this.token = RefreshToken || ''; } /** * @returns {string} the record's token. */ getToken() { return this.token; } } ================================================ FILE: src/CognitoUser.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ import { util } from 'aws-sdk/global'; import BigInteger from './BigInteger'; import AuthenticationHelper from './AuthenticationHelper'; import CognitoAccessToken from './CognitoAccessToken'; import CognitoIdToken from './CognitoIdToken'; import CognitoRefreshToken from './CognitoRefreshToken'; import CognitoUserSession from './CognitoUserSession'; import DateHelper from './DateHelper'; import CognitoUserAttribute from './CognitoUserAttribute'; import StorageHelper from './StorageHelper'; /** * @callback nodeCallback * @template T result * @param {*} err The operation failure reason, or null. * @param {T} result The operation result. */ /** * @callback onFailure * @param {*} err Failure reason. */ /** * @callback onSuccess * @template T result * @param {T} result The operation result. */ /** * @callback mfaRequired * @param {*} details MFA challenge details. */ /** * @callback customChallenge * @param {*} details Custom challenge details. */ /** * @callback inputVerificationCode * @param {*} data Server response. */ /** * @callback authSuccess * @param {CognitoUserSession} session The new session. * @param {bool=} userConfirmationNecessary User must be confirmed. */ /** @class */ export default class CognitoUser { /** * Constructs a new CognitoUser object * @param {object} data Creation options * @param {string} data.Username The user's username. * @param {CognitoUserPool} data.Pool Pool containing the user. * @param {object} data.Storage Optional storage object. */ constructor(data) { if (data == null || data.Username == null || data.Pool == null) { throw new Error('Username and pool information are required.'); } this.username = data.Username || ''; this.pool = data.Pool; this.Session = null; this.client = data.Pool.client; this.signInUserSession = null; this.authenticationFlowType = 'USER_SRP_AUTH'; this.storage = data.Storage || new StorageHelper().getStorage(); } /** * Sets the session for this user * @param {CognitoUserSession} signInUserSession the session * @returns {void} */ setSignInUserSession(signInUserSession) { this.clearCachedTokens(); this.signInUserSession = signInUserSession; this.cacheTokens(); } /** * @returns {CognitoUserSession} the current session for this user */ getSignInUserSession() { return this.signInUserSession; } /** * @returns {string} the user's username */ getUsername() { return this.username; } /** * @returns {String} the authentication flow type */ getAuthenticationFlowType() { return this.authenticationFlowType; } /** * sets authentication flow type * @param {string} authenticationFlowType New value. * @returns {void} */ setAuthenticationFlowType(authenticationFlowType) { this.authenticationFlowType = authenticationFlowType; } /** * This is used for authenticating the user through the custom authentication flow. * @param {AuthenticationDetails} authDetails Contains the authentication data * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ initiateAuth(authDetails, callback) { const authParameters = authDetails.getAuthParameters(); authParameters.USERNAME = this.username; const jsonReq = { AuthFlow: 'CUSTOM_AUTH', ClientId: this.pool.getClientId(), AuthParameters: authParameters, ClientMetadata: authDetails.getValidationData(), }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('initiateAuth', jsonReq, (err, data) => { if (err) { return callback.onFailure(err); } const challengeName = data.ChallengeName; const challengeParameters = data.ChallengeParameters; if (challengeName === 'CUSTOM_CHALLENGE') { this.Session = data.Session; return callback.customChallenge(challengeParameters); } this.signInUserSession = this.getCognitoUserSession(data.AuthenticationResult); this.cacheTokens(); return callback.onSuccess(this.signInUserSession); }); } /** * This is used for authenticating the user. it calls the AuthenticationHelper for SRP related * stuff * @param {AuthenticationDetails} authDetails Contains the authentication data * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {newPasswordRequired} callback.newPasswordRequired new * password and any required attributes are required to continue * @param {mfaRequired} callback.mfaRequired MFA code * required to continue. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ authenticateUser(authDetails, callback) { const authenticationHelper = new AuthenticationHelper( this.pool.getUserPoolId().split('_')[1]); const dateHelper = new DateHelper(); let serverBValue; let salt; const authParameters = {}; if (this.deviceKey != null) { authParameters.DEVICE_KEY = this.deviceKey; } authParameters.USERNAME = this.username; authenticationHelper.getLargeAValue((errOnAValue, aValue) => { // getLargeAValue callback start if (errOnAValue) { callback.onFailure(errOnAValue); } authParameters.SRP_A = aValue.toString(16); if (this.authenticationFlowType === 'CUSTOM_AUTH') { authParameters.CHALLENGE_NAME = 'SRP_A'; } const jsonReq = { AuthFlow: this.authenticationFlowType, ClientId: this.pool.getClientId(), AuthParameters: authParameters, ClientMetadata: authDetails.getValidationData(), }; if (this.getUserContextData(this.username)) { jsonReq.UserContextData = this.getUserContextData(this.username); } this.client.makeUnauthenticatedRequest('initiateAuth', jsonReq, (err, data) => { if (err) { return callback.onFailure(err); } const challengeParameters = data.ChallengeParameters; this.username = challengeParameters.USER_ID_FOR_SRP; serverBValue = new BigInteger(challengeParameters.SRP_B, 16); salt = new BigInteger(challengeParameters.SALT, 16); this.getCachedDeviceKeyAndPassword(); authenticationHelper.getPasswordAuthenticationKey( this.username, authDetails.getPassword(), serverBValue, salt, (errOnHkdf, hkdf) => { // getPasswordAuthenticationKey callback start if (errOnHkdf) { callback.onFailure(errOnHkdf); } const dateNow = dateHelper.getNowString(); const signatureString = util.crypto.hmac(hkdf, util.buffer.concat([ new util.Buffer(this.pool.getUserPoolId().split('_')[1], 'utf8'), new util.Buffer(this.username, 'utf8'), new util.Buffer(challengeParameters.SECRET_BLOCK, 'base64'), new util.Buffer(dateNow, 'utf8'), ]), 'base64', 'sha256'); const challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK; challengeResponses.TIMESTAMP = dateNow; challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString; if (this.deviceKey != null) { challengeResponses.DEVICE_KEY = this.deviceKey; } const respondToAuthChallenge = (challenge, challengeCallback) => this.client.makeUnauthenticatedRequest('respondToAuthChallenge', challenge, (errChallenge, dataChallenge) => { if (errChallenge && errChallenge.code === 'ResourceNotFoundException' && errChallenge.message.toLowerCase().indexOf('device') !== -1) { challengeResponses.DEVICE_KEY = null; this.deviceKey = null; this.randomPassword = null; this.deviceGroupKey = null; this.clearCachedDeviceKeyAndPassword(); return respondToAuthChallenge(challenge, challengeCallback); } return challengeCallback(errChallenge, dataChallenge); }); const jsonReqResp = { ChallengeName: 'PASSWORD_VERIFIER', ClientId: this.pool.getClientId(), ChallengeResponses: challengeResponses, Session: data.Session, }; if (this.getUserContextData()) { jsonReqResp.UserContextData = this.getUserContextData(); } respondToAuthChallenge(jsonReqResp, (errAuthenticate, dataAuthenticate) => { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } const challengeName = dataAuthenticate.ChallengeName; if (challengeName === 'NEW_PASSWORD_REQUIRED') { this.Session = dataAuthenticate.Session; let userAttributes = null; let rawRequiredAttributes = null; const requiredAttributes = []; const userAttributesPrefix = authenticationHelper .getNewPasswordRequiredChallengeUserAttributePrefix(); if (dataAuthenticate.ChallengeParameters) { userAttributes = JSON.parse( dataAuthenticate.ChallengeParameters.userAttributes); rawRequiredAttributes = JSON.parse( dataAuthenticate.ChallengeParameters.requiredAttributes); } if (rawRequiredAttributes) { for (let i = 0; i < rawRequiredAttributes.length; i++) { requiredAttributes[i] = rawRequiredAttributes[i].substr( userAttributesPrefix.length ); } } return callback.newPasswordRequired(userAttributes, requiredAttributes); } return this.authenticateUserInternal( dataAuthenticate, authenticationHelper, callback ); }); return undefined; // getPasswordAuthenticationKey callback end }); return undefined; }); // getLargeAValue callback end }); } /** * PRIVATE ONLY: This is an internal only method and should not * be directly called by the consumers. * @param {object} dataAuthenticate authentication data * @param {object} authenticationHelper helper created * @param {callback} callback passed on from caller * @returns {void} */ authenticateUserInternal(dataAuthenticate, authenticationHelper, callback) { const challengeName = dataAuthenticate.ChallengeName; const challengeParameters = dataAuthenticate.ChallengeParameters; if (challengeName === 'SMS_MFA') { this.Session = dataAuthenticate.Session; return callback.mfaRequired(challengeName, challengeParameters); } if (challengeName === 'SELECT_MFA_TYPE') { this.Session = dataAuthenticate.Session; return callback.selectMFAType(challengeName, challengeParameters); } if (challengeName === 'MFA_SETUP') { this.Session = dataAuthenticate.Session; return callback.mfaSetup(challengeName, challengeParameters); } if (challengeName === 'SOFTWARE_TOKEN_MFA') { this.Session = dataAuthenticate.Session; return callback.totpRequired(challengeName, challengeParameters); } if (challengeName === 'CUSTOM_CHALLENGE') { this.Session = dataAuthenticate.Session; return callback.customChallenge(challengeParameters); } if (challengeName === 'DEVICE_SRP_AUTH') { this.getDeviceResponse(callback); return undefined; } this.signInUserSession = this.getCognitoUserSession(dataAuthenticate.AuthenticationResult); this.cacheTokens(); const newDeviceMetadata = dataAuthenticate.AuthenticationResult.NewDeviceMetadata; if (newDeviceMetadata == null) { return callback.onSuccess(this.signInUserSession); } authenticationHelper.generateHashDevice( dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, (errGenHash) => { if (errGenHash) { return callback.onFailure(errGenHash); } const deviceSecretVerifierConfig = { Salt: new util.Buffer( authenticationHelper.getSaltDevices(), 'hex' ).toString('base64'), PasswordVerifier: new util.Buffer( authenticationHelper.getVerifierDevices(), 'hex' ).toString('base64'), }; this.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier; this.deviceGroupKey = newDeviceMetadata.DeviceGroupKey; this.randomPassword = authenticationHelper.getRandomPassword(); this.client.makeUnauthenticatedRequest('confirmDevice', { DeviceKey: newDeviceMetadata.DeviceKey, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceSecretVerifierConfig: deviceSecretVerifierConfig, DeviceName: navigator.userAgent, }, (errConfirm, dataConfirm) => { if (errConfirm) { return callback.onFailure(errConfirm); } this.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey; this.cacheDeviceKeyAndPassword(); if (dataConfirm.UserConfirmationNecessary === true) { return callback.onSuccess( this.signInUserSession, dataConfirm.UserConfirmationNecessary); } return callback.onSuccess(this.signInUserSession); }); return undefined; }); return undefined; } /** * This method is user to complete the NEW_PASSWORD_REQUIRED challenge. * Pass the new password with any new user attributes to be updated. * User attribute keys must be of format userAttributes.. * @param {string} newPassword new password for this user * @param {object} requiredAttributeData map with values for all required attributes * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {mfaRequired} callback.mfaRequired MFA code required to continue. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ completeNewPasswordChallenge(newPassword, requiredAttributeData, callback) { if (!newPassword) { return callback.onFailure(new Error('New password is required.')); } const authenticationHelper = new AuthenticationHelper( this.pool.getUserPoolId().split('_')[1]); const userAttributesPrefix = authenticationHelper .getNewPasswordRequiredChallengeUserAttributePrefix(); const finalUserAttributes = {}; if (requiredAttributeData) { Object.keys(requiredAttributeData).forEach((key) => { finalUserAttributes[userAttributesPrefix + key] = requiredAttributeData[key]; }); } finalUserAttributes.NEW_PASSWORD = newPassword; finalUserAttributes.USERNAME = this.username; const jsonReq = { ChallengeName: 'NEW_PASSWORD_REQUIRED', ClientId: this.pool.getClientId(), ChallengeResponses: finalUserAttributes, Session: this.Session, }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, (errAuthenticate, dataAuthenticate) => { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } return this.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback); }); return undefined; } /** * This is used to get a session using device authentication. It is called at the end of user * authentication * * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} * @private */ getDeviceResponse(callback) { const authenticationHelper = new AuthenticationHelper( this.deviceGroupKey); const dateHelper = new DateHelper(); const authParameters = {}; authParameters.USERNAME = this.username; authParameters.DEVICE_KEY = this.deviceKey; authenticationHelper.getLargeAValue((errAValue, aValue) => { // getLargeAValue callback start if (errAValue) { callback.onFailure(errAValue); } authParameters.SRP_A = aValue.toString(16); const jsonReq = { ChallengeName: 'DEVICE_SRP_AUTH', ClientId: this.pool.getClientId(), ChallengeResponses: authParameters, }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, (err, data) => { if (err) { return callback.onFailure(err); } const challengeParameters = data.ChallengeParameters; const serverBValue = new BigInteger(challengeParameters.SRP_B, 16); const salt = new BigInteger(challengeParameters.SALT, 16); authenticationHelper.getPasswordAuthenticationKey( this.deviceKey, this.randomPassword, serverBValue, salt, (errHkdf, hkdf) => { // getPasswordAuthenticationKey callback start if (errHkdf) { return callback.onFailure(errHkdf); } const dateNow = dateHelper.getNowString(); const signatureString = util.crypto.hmac(hkdf, util.buffer.concat([ new util.Buffer(this.deviceGroupKey, 'utf8'), new util.Buffer(this.deviceKey, 'utf8'), new util.Buffer(challengeParameters.SECRET_BLOCK, 'base64'), new util.Buffer(dateNow, 'utf8'), ]), 'base64', 'sha256'); const challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK; challengeResponses.TIMESTAMP = dateNow; challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString; challengeResponses.DEVICE_KEY = this.deviceKey; const jsonReqResp = { ChallengeName: 'DEVICE_PASSWORD_VERIFIER', ClientId: this.pool.getClientId(), ChallengeResponses: challengeResponses, Session: data.Session, }; if (this.getUserContextData()) { jsonReqResp.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReqResp, (errAuthenticate, dataAuthenticate) => { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } this.signInUserSession = this.getCognitoUserSession( dataAuthenticate.AuthenticationResult ); this.cacheTokens(); return callback.onSuccess(this.signInUserSession); }); return undefined; // getPasswordAuthenticationKey callback end }); return undefined; }); // getLargeAValue callback end }); } /** * This is used for a certain user to confirm the registration by using a confirmation code * @param {string} confirmationCode Code entered by user. * @param {bool} forceAliasCreation Allow migrating from an existing email / phone number. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ confirmRegistration(confirmationCode, forceAliasCreation, callback) { const jsonReq = { ClientId: this.pool.getClientId(), ConfirmationCode: confirmationCode, Username: this.username, ForceAliasCreation: forceAliasCreation, }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('confirmSignUp', jsonReq, err => { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); } /** * This is used by the user once he has the responses to a custom challenge * @param {string} answerChallenge The custom challange answer. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {customChallenge} callback.customChallenge * Custom challenge response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ sendCustomChallengeAnswer(answerChallenge, callback) { const challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.ANSWER = answerChallenge; const authenticationHelper = new AuthenticationHelper( this.pool.getUserPoolId().split('_')[1]); this.getCachedDeviceKeyAndPassword(); if (this.deviceKey != null) { challengeResponses.DEVICE_KEY = this.deviceKey; } const jsonReq = { ChallengeName: 'CUSTOM_CHALLENGE', ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session, }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, (err, data) => { if (err) { return callback.onFailure(err); } return this.authenticateUserInternal(data, authenticationHelper, callback); }); } /** * This is used by the user once he has an MFA code * @param {string} confirmationCode The MFA code entered by the user. * @param {object} callback Result callback map. * @param {string} mfaType The mfa we are replying to. * @param {onFailure} callback.onFailure Called on any error. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ sendMFACode(confirmationCode, callback, mfaType) { const challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.SMS_MFA_CODE = confirmationCode; const mfaTypeSelection = mfaType || 'SMS_MFA'; if (mfaTypeSelection === 'SOFTWARE_TOKEN_MFA') { challengeResponses.SOFTWARE_TOKEN_MFA_CODE = confirmationCode; } if (this.deviceKey != null) { challengeResponses.DEVICE_KEY = this.deviceKey; } const jsonReq = { ChallengeName: mfaTypeSelection, ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session, }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, (err, dataAuthenticate) => { if (err) { return callback.onFailure(err); } const challengeName = dataAuthenticate.ChallengeName; if (challengeName === 'DEVICE_SRP_AUTH') { this.getDeviceResponse(callback); return undefined; } this.signInUserSession = this.getCognitoUserSession(dataAuthenticate.AuthenticationResult); this.cacheTokens(); if (dataAuthenticate.AuthenticationResult.NewDeviceMetadata == null) { return callback.onSuccess(this.signInUserSession); } const authenticationHelper = new AuthenticationHelper( this.pool.getUserPoolId().split('_')[1]); authenticationHelper.generateHashDevice( dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, (errGenHash) => { if (errGenHash) { return callback.onFailure(errGenHash); } const deviceSecretVerifierConfig = { Salt: new util.Buffer( authenticationHelper.getSaltDevices(), 'hex' ).toString('base64'), PasswordVerifier: new util.Buffer( authenticationHelper.getVerifierDevices(), 'hex' ).toString('base64'), }; this.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier; this.deviceGroupKey = dataAuthenticate.AuthenticationResult .NewDeviceMetadata.DeviceGroupKey; this.randomPassword = authenticationHelper.getRandomPassword(); this.client.makeUnauthenticatedRequest('confirmDevice', { DeviceKey: dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceSecretVerifierConfig: deviceSecretVerifierConfig, DeviceName: navigator.userAgent, }, (errConfirm, dataConfirm) => { if (errConfirm) { return callback.onFailure(errConfirm); } this.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey; this.cacheDeviceKeyAndPassword(); if (dataConfirm.UserConfirmationNecessary === true) { return callback.onSuccess( this.signInUserSession, dataConfirm.UserConfirmationNecessary); } return callback.onSuccess(this.signInUserSession); }); return undefined; }); return undefined; }); } /** * This is used by an authenticated user to change the current password * @param {string} oldUserPassword The current password. * @param {string} newUserPassword The requested new password. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ changePassword(oldUserPassword, newUserPassword, callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('changePassword', { PreviousPassword: oldUserPassword, ProposedPassword: newUserPassword, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, err => { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; } /** * This is used by an authenticated user to enable MFA for himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ enableMFA(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } const mfaOptions = []; const mfaEnabled = { DeliveryMedium: 'SMS', AttributeName: 'phone_number', }; mfaOptions.push(mfaEnabled); this.client.makeUnauthenticatedRequest('setUserSettings', { MFAOptions: mfaOptions, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, err => { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; } /** * This is used by an authenticated user to enable MFA for himself * @param {string[]} smsMfaSettings the sms mfa settings * @param {string[]} softwareTokenMfaSettings the software token mfa settings * @param {nodeCallback} callback Called on success or error. * @returns {void} */ setUserMfaPreference(smsMfaSettings, softwareTokenMfaSettings, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('setUserMFAPreference', { SMSMfaSettings: smsMfaSettings, SoftwareTokenMfaSettings: softwareTokenMfaSettings, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, err => { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; } /** * This is used by an authenticated user to disable MFA for himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ disableMFA(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } const mfaOptions = []; this.client.makeUnauthenticatedRequest('setUserSettings', { MFAOptions: mfaOptions, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, err => { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; } /** * This is used by an authenticated user to delete himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ deleteUser(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('deleteUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, err => { if (err) { return callback(err, null); } this.clearCachedTokens(); return callback(null, 'SUCCESS'); }); return undefined; } /** * @typedef {CognitoUserAttribute | { Name:string, Value:string }} AttributeArg */ /** * This is used by an authenticated user to change a list of attributes * @param {AttributeArg[]} attributes A list of the new user attributes. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ updateAttributes(attributes, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('updateUserAttributes', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), UserAttributes: attributes, }, err => { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; } /** * This is used by an authenticated user to get a list of attributes * @param {nodeCallback} callback Called on success or error. * @returns {void} */ getUserAttributes(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('getUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, (err, userData) => { if (err) { return callback(err, null); } const attributeList = []; for (let i = 0; i < userData.UserAttributes.length; i++) { const attribute = { Name: userData.UserAttributes[i].Name, Value: userData.UserAttributes[i].Value, }; const userAttribute = new CognitoUserAttribute(attribute); attributeList.push(userAttribute); } return callback(null, attributeList); }); return undefined; } /** * This is used by an authenticated user to get the MFAOptions * @param {nodeCallback} callback Called on success or error. * @returns {void} */ getMFAOptions(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('getUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, (err, userData) => { if (err) { return callback(err, null); } return callback(null, userData.MFAOptions); }); return undefined; } /** * This is used by an authenticated user to delete a list of attributes * @param {string[]} attributeList Names of the attributes to delete. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ deleteAttributes(attributeList, callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('deleteUserAttributes', { UserAttributeNames: attributeList, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, err => { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; } /** * This is used by a user to resend a confirmation code * @param {nodeCallback} callback Called on success or error. * @returns {void} */ resendConfirmationCode(callback) { const jsonReq = { ClientId: this.pool.getClientId(), Username: this.username, }; this.client.makeUnauthenticatedRequest('resendConfirmationCode', jsonReq, (err, result) => { if (err) { return callback(err, null); } return callback(null, result); }); } /** * This is used to get a session, either from the session object * or from the local storage, or by using a refresh token * * @param {nodeCallback} callback Called on success or error. * @returns {void} */ getSession(callback) { if (this.username == null) { return callback(new Error('Username is null. Cannot retrieve a new session'), null); } if (this.signInUserSession != null && this.signInUserSession.isValid()) { return callback(null, this.signInUserSession); } const keyPrefix = `CognitoIdentityServiceProvider.${this.pool.getClientId()}.${this.username}`; const idTokenKey = `${keyPrefix}.idToken`; const accessTokenKey = `${keyPrefix}.accessToken`; const refreshTokenKey = `${keyPrefix}.refreshToken`; const clockDriftKey = `${keyPrefix}.clockDrift`; if (this.storage.getItem(idTokenKey)) { const idToken = new CognitoIdToken({ IdToken: this.storage.getItem(idTokenKey), }); const accessToken = new CognitoAccessToken({ AccessToken: this.storage.getItem(accessTokenKey), }); const refreshToken = new CognitoRefreshToken({ RefreshToken: this.storage.getItem(refreshTokenKey), }); const clockDrift = parseInt(this.storage.getItem(clockDriftKey), 0) || 0; const sessionData = { IdToken: idToken, AccessToken: accessToken, RefreshToken: refreshToken, ClockDrift: clockDrift, }; const cachedSession = new CognitoUserSession(sessionData); if (cachedSession.isValid()) { this.signInUserSession = cachedSession; return callback(null, this.signInUserSession); } if (refreshToken.getToken() == null) { return callback(new Error('Cannot retrieve a new session. Please authenticate.'), null); } this.refreshSession(refreshToken, callback); } else { callback(new Error('Local storage is missing an ID Token, Please authenticate'), null); } return undefined; } /** * This uses the refreshToken to retrieve a new session * @param {CognitoRefreshToken} refreshToken A previous session's refresh token. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ refreshSession(refreshToken, callback) { const authParameters = {}; authParameters.REFRESH_TOKEN = refreshToken.getToken(); const keyPrefix = `CognitoIdentityServiceProvider.${this.pool.getClientId()}`; const lastUserKey = `${keyPrefix}.LastAuthUser`; if (this.storage.getItem(lastUserKey)) { this.username = this.storage.getItem(lastUserKey); const deviceKeyKey = `${keyPrefix}.${this.username}.deviceKey`; this.deviceKey = this.storage.getItem(deviceKeyKey); authParameters.DEVICE_KEY = this.deviceKey; } const jsonReq = { ClientId: this.pool.getClientId(), AuthFlow: 'REFRESH_TOKEN_AUTH', AuthParameters: authParameters, }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('initiateAuth', jsonReq, (err, authResult) => { if (err) { if (err.code === 'NotAuthorizedException') { this.clearCachedTokens(); } return callback(err, null); } if (authResult) { const authenticationResult = authResult.AuthenticationResult; if (!Object.prototype.hasOwnProperty.call(authenticationResult, 'RefreshToken')) { authenticationResult.RefreshToken = refreshToken.getToken(); } this.signInUserSession = this.getCognitoUserSession(authenticationResult); this.cacheTokens(); return callback(null, this.signInUserSession); } return undefined; }); } /** * This is used to save the session tokens to local storage * @returns {void} */ cacheTokens() { const keyPrefix = `CognitoIdentityServiceProvider.${this.pool.getClientId()}`; const idTokenKey = `${keyPrefix}.${this.username}.idToken`; const accessTokenKey = `${keyPrefix}.${this.username}.accessToken`; const refreshTokenKey = `${keyPrefix}.${this.username}.refreshToken`; const clockDriftKey = `${keyPrefix}.${this.username}.clockDrift`; const lastUserKey = `${keyPrefix}.LastAuthUser`; this.storage.setItem(idTokenKey, this.signInUserSession.getIdToken().getJwtToken()); this.storage.setItem(accessTokenKey, this.signInUserSession.getAccessToken().getJwtToken()); this.storage.setItem(refreshTokenKey, this.signInUserSession.getRefreshToken().getToken()); this.storage.setItem(clockDriftKey, `${this.signInUserSession.getClockDrift()}`); this.storage.setItem(lastUserKey, this.username); } /** * This is used to cache the device key and device group and device password * @returns {void} */ cacheDeviceKeyAndPassword() { const keyPrefix = `CognitoIdentityServiceProvider.${this.pool.getClientId()}.${this.username}`; const deviceKeyKey = `${keyPrefix}.deviceKey`; const randomPasswordKey = `${keyPrefix}.randomPasswordKey`; const deviceGroupKeyKey = `${keyPrefix}.deviceGroupKey`; this.storage.setItem(deviceKeyKey, this.deviceKey); this.storage.setItem(randomPasswordKey, this.randomPassword); this.storage.setItem(deviceGroupKeyKey, this.deviceGroupKey); } /** * This is used to get current device key and device group and device password * @returns {void} */ getCachedDeviceKeyAndPassword() { const keyPrefix = `CognitoIdentityServiceProvider.${this.pool.getClientId()}.${this.username}`; const deviceKeyKey = `${keyPrefix}.deviceKey`; const randomPasswordKey = `${keyPrefix}.randomPasswordKey`; const deviceGroupKeyKey = `${keyPrefix}.deviceGroupKey`; if (this.storage.getItem(deviceKeyKey)) { this.deviceKey = this.storage.getItem(deviceKeyKey); this.randomPassword = this.storage.getItem(randomPasswordKey); this.deviceGroupKey = this.storage.getItem(deviceGroupKeyKey); } } /** * This is used to clear the device key info from local storage * @returns {void} */ clearCachedDeviceKeyAndPassword() { const keyPrefix = `CognitoIdentityServiceProvider.${this.pool.getClientId()}.${this.username}`; const deviceKeyKey = `${keyPrefix}.deviceKey`; const randomPasswordKey = `${keyPrefix}.randomPasswordKey`; const deviceGroupKeyKey = `${keyPrefix}.deviceGroupKey`; this.storage.removeItem(deviceKeyKey); this.storage.removeItem(randomPasswordKey); this.storage.removeItem(deviceGroupKeyKey); } /** * This is used to clear the session tokens from local storage * @returns {void} */ clearCachedTokens() { const keyPrefix = `CognitoIdentityServiceProvider.${this.pool.getClientId()}`; const idTokenKey = `${keyPrefix}.${this.username}.idToken`; const accessTokenKey = `${keyPrefix}.${this.username}.accessToken`; const refreshTokenKey = `${keyPrefix}.${this.username}.refreshToken`; const lastUserKey = `${keyPrefix}.LastAuthUser`; this.storage.removeItem(idTokenKey); this.storage.removeItem(accessTokenKey); this.storage.removeItem(refreshTokenKey); this.storage.removeItem(lastUserKey); } /** * This is used to build a user session from tokens retrieved in the authentication result * @param {object} authResult Successful auth response from server. * @returns {CognitoUserSession} The new user session. * @private */ getCognitoUserSession(authResult) { const idToken = new CognitoIdToken(authResult); const accessToken = new CognitoAccessToken(authResult); const refreshToken = new CognitoRefreshToken(authResult); const sessionData = { IdToken: idToken, AccessToken: accessToken, RefreshToken: refreshToken, }; return new CognitoUserSession(sessionData); } /** * This is used to initiate a forgot password request * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {inputVerificationCode?} callback.inputVerificationCode * Optional callback raised instead of onSuccess with response data. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ forgotPassword(callback) { const jsonReq = { ClientId: this.pool.getClientId(), Username: this.username, }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('forgotPassword', jsonReq, (err, data) => { if (err) { return callback.onFailure(err); } if (typeof callback.inputVerificationCode === 'function') { return callback.inputVerificationCode(data); } return callback.onSuccess(data); }); } /** * This is used to confirm a new password using a confirmationCode * @param {string} confirmationCode Code entered by user. * @param {string} newPassword Confirm new password. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ confirmPassword(confirmationCode, newPassword, callback) { const jsonReq = { ClientId: this.pool.getClientId(), Username: this.username, ConfirmationCode: confirmationCode, Password: newPassword, }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('confirmForgotPassword', jsonReq, err => { if (err) { return callback.onFailure(err); } return callback.onSuccess(); }); } /** * This is used to initiate an attribute confirmation request * @param {string} attributeName User attribute that needs confirmation. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {inputVerificationCode} callback.inputVerificationCode Called on success. * @returns {void} */ getAttributeVerificationCode(attributeName, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('getUserAttributeVerificationCode', { AttributeName: attributeName, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, (err, data) => { if (err) { return callback.onFailure(err); } if (typeof callback.inputVerificationCode === 'function') { return callback.inputVerificationCode(data); } return callback.onSuccess(); }); return undefined; } /** * This is used to confirm an attribute using a confirmation code * @param {string} attributeName Attribute being confirmed. * @param {string} confirmationCode Code entered by user. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ verifyAttribute(attributeName, confirmationCode, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('verifyUserAttribute', { AttributeName: attributeName, Code: confirmationCode, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, err => { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; } /** * This is used to get the device information using the current device key * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess<*>} callback.onSuccess Called on success with device data. * @returns {void} */ getDevice(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('getDevice', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey, }, (err, data) => { if (err) { return callback.onFailure(err); } return callback.onSuccess(data); }); return undefined; } /** * This is used to forget a specific device * @param {string} deviceKey Device key. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ forgetSpecificDevice(deviceKey, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('forgetDevice', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: deviceKey, }, err => { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; } /** * This is used to forget the current device * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ forgetDevice(callback) { this.forgetSpecificDevice(this.deviceKey, { onFailure: callback.onFailure, onSuccess: result => { this.deviceKey = null; this.deviceGroupKey = null; this.randomPassword = null; this.clearCachedDeviceKeyAndPassword(); return callback.onSuccess(result); }, }); } /** * This is used to set the device status as remembered * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ setDeviceStatusRemembered(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('updateDeviceStatus', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey, DeviceRememberedStatus: 'remembered', }, err => { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; } /** * This is used to set the device status as not remembered * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ setDeviceStatusNotRemembered(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('updateDeviceStatus', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey, DeviceRememberedStatus: 'not_remembered', }, err => { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; } /** * This is used to list all devices for a user * * @param {int} limit the number of devices returned in a call * @param {string} paginationToken the pagination token in case any was returned before * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess<*>} callback.onSuccess Called on success with device list. * @returns {void} */ listDevices(limit, paginationToken, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('listDevices', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), Limit: limit, PaginationToken: paginationToken, }, (err, data) => { if (err) { return callback.onFailure(err); } return callback.onSuccess(data); }); return undefined; } /** * This is used to globally revoke all tokens issued to a user * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ globalSignOut(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('globalSignOut', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, err => { if (err) { return callback.onFailure(err); } this.clearCachedTokens(); return callback.onSuccess('SUCCESS'); }); return undefined; } /** * This is used for the user to signOut of the application and clear the cached tokens. * @returns {void} */ signOut() { this.signInUserSession = null; this.clearCachedTokens(); } /** * This is used by a user trying to select a given MFA * @param {string} answerChallenge the mfa the user wants * @param {nodeCallback} callback Called on success or error. * @returns {void} */ sendMFASelectionAnswer(answerChallenge, callback) { const challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.ANSWER = answerChallenge; const jsonReq = { ChallengeName: 'SELECT_MFA_TYPE', ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session, }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, (err, data) => { if (err) { return callback.onFailure(err); } this.Session = data.Session; if (answerChallenge === 'SMS_MFA') { return callback.mfaRequired(data.challengeName, data.challengeParameters); } if (answerChallenge === 'SOFTWARE_TOKEN_MFA') { return callback.totpRequired(data.challengeName, data.challengeParameters); } return undefined; }); } /** * This returns the user context data for advanced security feature. * @returns {void} */ getUserContextData() { const pool = this.pool; return pool.getUserContextData(this.username); } /** * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA * @param {nodeCallback} callback Called on success or error. * @returns {void} */ associateSoftwareToken(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { this.client.makeUnauthenticatedRequest('associateSoftwareToken', { Session: this.Session, }, (err, data) => { if (err) { return callback.onFailure(err); } this.Session = data.Session; return callback.associateSecretCode(data.SecretCode); }); } else { this.client.makeUnauthenticatedRequest('associateSoftwareToken', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), }, (err, data) => { if (err) { return callback.onFailure(err); } return callback.associateSecretCode(data.SecretCode); }); } } /** * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA * @param {string} totpCode The MFA code entered by the user. * @param {string} friendlyDeviceName The device name we are assigning to the device. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ verifySoftwareToken(totpCode, friendlyDeviceName, callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { this.client.makeUnauthenticatedRequest('verifySoftwareToken', { Session: this.Session, UserCode: totpCode, FriendlyDeviceName: friendlyDeviceName, }, (err, data) => { if (err) { return callback.onFailure(err); } this.Session = data.Session; const challengeResponses = {}; challengeResponses.USERNAME = this.username; const jsonReq = { ChallengeName: 'MFA_SETUP', ClientId: this.pool.getClientId(), ChallengeResponses: challengeResponses, Session: this.Session, }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', jsonReq, (errRespond, dataRespond) => { if (errRespond) { return callback.onFailure(errRespond); } this.signInUserSession = this.getCognitoUserSession(dataRespond.AuthenticationResult); this.cacheTokens(); return callback.onSuccess(this.signInUserSession); }); return undefined; }); } else { this.client.makeUnauthenticatedRequest('verifySoftwareToken', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), UserCode: totpCode, FriendlyDeviceName: friendlyDeviceName, }, (err, data) => { if (err) { return callback.onFailure(err); } return callback.onSuccess(data); }); } } } ================================================ FILE: src/CognitoUserAttribute.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ export default class CognitoUserAttribute { /** * Constructs a new CognitoUserAttribute object * @param {string=} Name The record's name * @param {string=} Value The record's value */ constructor({ Name, Value } = {}) { this.Name = Name || ''; this.Value = Value || ''; } /** * @returns {string} the record's value. */ getValue() { return this.Value; } /** * Sets the record's value. * @param {string} value The new value. * @returns {CognitoUserAttribute} The record for method chaining. */ setValue(value) { this.Value = value; return this; } /** * @returns {string} the record's name. */ getName() { return this.Name; } /** * Sets the record's name * @param {string} name The new name. * @returns {CognitoUserAttribute} The record for method chaining. */ setName(name) { this.Name = name; return this; } /** * @returns {string} a string representation of the record. */ toString() { return JSON.stringify(this); } /** * @returns {object} a flat object representing the record. */ toJSON() { return { Name: this.Name, Value: this.Value, }; } } ================================================ FILE: src/CognitoUserPool.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ import CognitoIdentityServiceProvider from 'aws-sdk/clients/cognitoidentityserviceprovider'; import CognitoUser from './CognitoUser'; import StorageHelper from './StorageHelper'; /** @class */ export default class CognitoUserPool { /** * Constructs a new CognitoUserPool object * @param {object} data Creation options. * @param {string} data.UserPoolId Cognito user pool id. * @param {string} data.ClientId User pool application client id. * @param {object} data.Storage Optional storage object. * @param {boolean} data.AdvancedSecurityDataCollectionFlag Optional: * boolean flag indicating if the data collection is enabled * to support cognito advanced security features. By default, this * flag is set to true. */ constructor(data) { const { UserPoolId, ClientId, endpoint, AdvancedSecurityDataCollectionFlag } = data || {}; if (!UserPoolId || !ClientId) { throw new Error('Both UserPoolId and ClientId are required.'); } if (!/^[\w-]+_.+$/.test(UserPoolId)) { throw new Error('Invalid UserPoolId format.'); } const region = UserPoolId.split('_')[0]; this.userPoolId = UserPoolId; this.clientId = ClientId; this.client = new CognitoIdentityServiceProvider({ apiVersion: '2016-04-19', region, endpoint, }); /** * By default, AdvancedSecurityDataCollectionFlag is set to true, * if no input value is provided. */ this.advancedSecurityDataCollectionFlag = AdvancedSecurityDataCollectionFlag !== false; this.storage = data.Storage || new StorageHelper().getStorage(); } /** * @returns {string} the user pool id */ getUserPoolId() { return this.userPoolId; } /** * @returns {string} the client id */ getClientId() { return this.clientId; } /** * @typedef {object} SignUpResult * @property {CognitoUser} user New user. * @property {bool} userConfirmed If the user is already confirmed. */ /** * method for signing up a user * @param {string} username User's username. * @param {string} password Plain-text initial password entered by user. * @param {(AttributeArg[])=} userAttributes New user attributes. * @param {(AttributeArg[])=} validationData Application metadata. * @param {nodeCallback} callback Called on error or with the new user. * @returns {void} */ signUp(username, password, userAttributes, validationData, callback) { const jsonReq = { ClientId: this.clientId, Username: username, Password: password, UserAttributes: userAttributes, ValidationData: validationData, }; if (this.getUserContextData(username)) { jsonReq.UserContextData = this.getUserContextData(username); } this.client.makeUnauthenticatedRequest('signUp', jsonReq, (err, data) => { if (err) { return callback(err, null); } const cognitoUser = { Username: username, Pool: this, Storage: this.storage, }; const returnData = { user: new CognitoUser(cognitoUser), userConfirmed: data.UserConfirmed, userSub: data.UserSub, }; return callback(null, returnData); }); } /** * method for getting the current user of the application from the local storage * * @returns {CognitoUser} the user retrieved from storage */ getCurrentUser() { const lastUserKey = `CognitoIdentityServiceProvider.${this.clientId}.LastAuthUser`; const lastAuthUser = this.storage.getItem(lastUserKey); if (lastAuthUser) { const cognitoUser = { Username: lastAuthUser, Pool: this, Storage: this.storage, }; return new CognitoUser(cognitoUser); } return null; } /** * This method returns the encoded data string used for cognito advanced security feature. * This would be generated only when developer has included the JS used for collecting the * data on their client. Please refer to documentation to know more about using AdvancedSecurity * features * @param {string} username the username for the context data * @returns {string} the user context data **/ getUserContextData(username) { if (typeof AmazonCognitoAdvancedSecurityData === 'undefined') { return undefined; } /* eslint-disable */ const amazonCognitoAdvancedSecurityDataConst = AmazonCognitoAdvancedSecurityData; /* eslint-enable */ if (this.advancedSecurityDataCollectionFlag) { const advancedSecurityData = amazonCognitoAdvancedSecurityDataConst.getData(username, this.userPoolId, this.clientId); if (advancedSecurityData) { const userContextData = { EncodedData: advancedSecurityData, }; return userContextData; } } return {}; } } ================================================ FILE: src/CognitoUserSession.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ export default class CognitoUserSession { /** * Constructs a new CognitoUserSession object * @param {CognitoIdToken} IdToken The session's Id token. * @param {CognitoRefreshToken=} RefreshToken The session's refresh token. * @param {CognitoAccessToken} AccessToken The session's access token. * @param {int} ClockDrift The saved computer's clock drift or undefined to force calculation. */ constructor({ IdToken, RefreshToken, AccessToken, ClockDrift } = {}) { if (AccessToken == null || IdToken == null) { throw new Error('Id token and Access Token must be present.'); } this.idToken = IdToken; this.refreshToken = RefreshToken; this.accessToken = AccessToken; this.clockDrift = ClockDrift === undefined ? this.calculateClockDrift() : ClockDrift; } /** * @returns {CognitoIdToken} the session's Id token */ getIdToken() { return this.idToken; } /** * @returns {CognitoRefreshToken} the session's refresh token */ getRefreshToken() { return this.refreshToken; } /** * @returns {CognitoAccessToken} the session's access token */ getAccessToken() { return this.accessToken; } /** * @returns {int} the session's clock drift */ getClockDrift() { return this.clockDrift; } /** * @returns {int} the computer's clock drift */ calculateClockDrift() { const now = Math.floor(new Date() / 1000); const iat = Math.min(this.accessToken.getIssuedAt(), this.idToken.getIssuedAt()); return now - iat; } /** * Checks to see if the session is still valid based on session expiry information found * in tokens and the current time (adjusted with clock drift) * @returns {boolean} if the session is still valid */ isValid() { const now = Math.floor(new Date() / 1000); const adjusted = now - this.clockDrift; return adjusted < this.accessToken.getExpiration() && adjusted < this.idToken.getExpiration(); } } ================================================ FILE: src/CookieStorage.js ================================================ import * as Cookies from 'js-cookie'; /** @class */ export default class CookieStorage { /** * Constructs a new CookieStorage object * @param {object} data Creation options. * @param {string} data.domain Cookies domain (mandatory). * @param {string} data.path Cookies path (default: '/') * @param {integer} data.expires Cookie expiration (in days, default: 365) * @param {boolean} data.secure Cookie secure flag (default: true) */ constructor(data) { this.domain = data.domain; if (data.path) { this.path = data.path; } else { this.path = '/'; } if (Object.prototype.hasOwnProperty.call(data, 'expires')) { this.expires = data.expires; } else { this.expires = 365; } if (Object.prototype.hasOwnProperty.call(data, 'secure')) { this.secure = data.secure; } else { this.secure = true; } } /** * This is used to set a specific item in storage * @param {string} key - the key for the item * @param {object} value - the value * @returns {string} value that was set */ setItem(key, value) { Cookies.set(key, value, { path: this.path, expires: this.expires, domain: this.domain, secure: this.secure, } ); return Cookies.get(key); } /** * This is used to get a specific key from storage * @param {string} key - the key for the item * This is used to clear the storage * @returns {string} the data item */ getItem(key) { return Cookies.get(key); } /** * This is used to remove an item from storage * @param {string} key - the key being set * @returns {string} value - value that was deleted */ removeItem(key) { return Cookies.remove(key, { path: this.path, domain: this.domain, secure: this.secure, } ); } /** * This is used to clear the storage * @returns {string} nothing */ clear() { const cookies = Cookies.get(); let index; for (index = 0; index < cookies.length; ++index) { Cookies.remove(cookies[index]); } return {}; } } ================================================ FILE: src/DateHelper.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const weekNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; /** @class */ export default class DateHelper { /** * @returns {string} The current time in "ddd MMM D HH:mm:ss UTC YYYY" format. */ getNowString() { const now = new Date(); const weekDay = weekNames[now.getUTCDay()]; const month = monthNames[now.getUTCMonth()]; const day = now.getUTCDate(); let hours = now.getUTCHours(); if (hours < 10) { hours = `0${hours}`; } let minutes = now.getUTCMinutes(); if (minutes < 10) { minutes = `0${minutes}`; } let seconds = now.getUTCSeconds(); if (seconds < 10) { seconds = `0${seconds}`; } const year = now.getUTCFullYear(); // ddd MMM D HH:mm:ss UTC YYYY const dateNow = `${weekDay} ${month} ${day} ${hours}:${minutes}:${seconds} UTC ${year}`; return dateNow; } } ================================================ FILE: src/StorageHelper-rn.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ import { AsyncStorage } from 'react-native'; const MEMORY_KEY_PREFIX = '@MemoryStorage:'; let dataMemory = {}; /** @class */ class MemoryStorage { /** * This is used to set a specific item in storage * @param {string} key - the key for the item * @param {object} value - the value * @returns {string} value that was set */ static setItem(key, value) { AsyncStorage.setItem(MEMORY_KEY_PREFIX + key, value); dataMemory[key] = value; return dataMemory[key]; } /** * This is used to get a specific key from storage * @param {string} key - the key for the item * This is used to clear the storage * @returns {string} the data item */ static getItem(key) { return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined; } /** * This is used to remove an item from storage * @param {string} key - the key being set * @returns {string} value - value that was deleted */ static removeItem(key) { AsyncStorage.removeItem(MEMORY_KEY_PREFIX + key); return delete dataMemory[key]; } /** * This is used to clear the storage * @returns {string} nothing */ static clear() { dataMemory = {}; return dataMemory; } /** * Will sync the MemoryStorage data from AsyncStorage to storageWindow MemoryStorage * @param {nodeCallback} callback callback with (err, 'SUCCESS') * @returns {void} */ static sync(callback) { AsyncStorage.getAllKeys((errKeys, keys) => { if (errKeys) return callback(errKeys, null); const memoryKeys = keys.filter((key) => key.startsWith(MEMORY_KEY_PREFIX)); AsyncStorage.multiGet(memoryKeys, (err, stores) => { if (err) return callback(err, null); stores.map((result, index, store) => { const key = store[index][0]; const value = store[index][1]; const memoryKey = key.replace(MEMORY_KEY_PREFIX, ''); dataMemory[memoryKey] = value; return undefined; }); callback(null, 'SUCCESS'); return undefined; }); return undefined; }); } } /** @class */ export default class StorageHelper { /** * This is used to get a storage object * @returns {object} the storage */ constructor() { this.storageWindow = MemoryStorage; } /** * This is used to return the storage * @returns {object} the storage */ getStorage() { return this.storageWindow; } } ================================================ FILE: src/StorageHelper.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ let dataMemory = {}; /** @class */ class MemoryStorage { /** * This is used to set a specific item in storage * @param {string} key - the key for the item * @param {object} value - the value * @returns {string} value that was set */ static setItem(key, value) { dataMemory[key] = value; return dataMemory[key]; } /** * This is used to get a specific key from storage * @param {string} key - the key for the item * This is used to clear the storage * @returns {string} the data item */ static getItem(key) { return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined; } /** * This is used to remove an item from storage * @param {string} key - the key being set * @returns {string} value - value that was deleted */ static removeItem(key) { return delete dataMemory[key]; } /** * This is used to clear the storage * @returns {string} nothing */ static clear() { dataMemory = {}; return dataMemory; } } /** @class */ export default class StorageHelper { /** * This is used to get a storage object * @returns {object} the storage */ constructor() { try { this.storageWindow = window.localStorage; this.storageWindow.setItem('aws.cognito.test-ls', 1); this.storageWindow.removeItem('aws.cognito.test-ls'); } catch (exception) { this.storageWindow = MemoryStorage; } } /** * This is used to return the storage * @returns {object} the storage */ getStorage() { return this.storageWindow; } } ================================================ FILE: src/index.js ================================================ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ export { default as AuthenticationDetails } from './AuthenticationDetails'; export { default as AuthenticationHelper } from './AuthenticationHelper'; export { default as CognitoAccessToken } from './CognitoAccessToken'; export { default as CognitoIdToken } from './CognitoIdToken'; export { default as CognitoRefreshToken } from './CognitoRefreshToken'; export { default as CognitoUser } from './CognitoUser'; export { default as CognitoUserAttribute } from './CognitoUserAttribute'; export { default as CognitoUserPool } from './CognitoUserPool'; export { default as CognitoUserSession } from './CognitoUserSession'; export { default as CookieStorage } from './CookieStorage'; export { default as DateHelper } from './DateHelper'; // The version of crypto-browserify included by aws-sdk only // checks for window.crypto, not window.msCrypto as used by // IE 11 – so we set it explicitly here if (typeof window !== 'undefined' && !window.crypto && window.msCrypto) { window.crypto = window.msCrypto; } ================================================ FILE: webpack.config.js ================================================ /* eslint-disable */ var webpack = require('webpack'); var banner = '/*!\n' + ' * Copyright 2016 Amazon.com,\n' + ' * Inc. or its affiliates. All Rights Reserved.\n' + ' * \n' + ' * Licensed under the Amazon Software License (the "License").\n' + ' * You may not use this file except in compliance with the\n' + ' * License. A copy of the License is located at\n' + ' * \n' + ' * http://aws.amazon.com/asl/\n' + ' * \n' + ' * or in the "license" file accompanying this file. This file is\n' + ' * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR\n' + ' * CONDITIONS OF ANY KIND, express or implied. See the License\n' + ' * for the specific language governing permissions and\n' + ' * limitations under the License. \n' + ' */\n\n'; var config = { entry: './enhance', output: { libraryTarget: 'umd', library: 'AmazonCognitoIdentity' }, externals: { // This umd context config isn't in configuration documentation, but see example: // https://github.com/webpack/webpack/tree/master/examples/externals 'aws-sdk/global': { root: ['AWSCognito'], commonjs2: 'aws-sdk/global', commonjs: 'aws-sdk/global', amd: 'aws-sdk/global' }, 'aws-sdk/clients/cognitoidentityserviceprovider': { root: ['AWSCognito', 'CognitoIdentityServiceProvider'], commonjs2: 'aws-sdk/clients/cognitoidentityserviceprovider', commonjs: 'aws-sdk/clients/cognitoidentityserviceprovider', amd: 'aws-sdk/clients/cognitoidentityserviceprovider' }, }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.BannerPlugin(banner, { raw: true }) ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { cacheDirectory: './node_modules/.cache/babel' } } ] } }; if (process.env.NODE_ENV === 'production') { config.devtool = 'source-map'; config.plugins.push( new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ); } module.exports = config;